recovered from aaronjaworski710
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
"""Pytest root for tests/ tree.
|
||||
|
||||
Legacy root-level test_*.py remain discoverable via pyproject testpaths.
|
||||
Prefer adding new unit tests under tests/unit/.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
@@ -0,0 +1,139 @@
|
||||
"""Control-plane to pipeline reachability for Outlook (Task #206).
|
||||
|
||||
Pins the full in-process chain WITHOUT touching the network or a real
|
||||
browser/mailbox:
|
||||
|
||||
get_provider("outlook") → real OutlookProvider
|
||||
→ Pipeline.run(count=N, fail_fast=...) (proxy preflight mocked)
|
||||
→ OutlookProvider.register_one() short-circuits at the live gate
|
||||
→ RegisterResult(ok=False, error_kind="provider")
|
||||
→ pipeline classifies as terminal provider, stats.fail++,
|
||||
and (under fail_fast=True) stops after the first attempt.
|
||||
|
||||
This closes the gap left by ``test_outlook_pipeline_gated`` (Task 11), which
|
||||
fakes the provider entirely with ``FakeOutlookProvider``: it never reaches
|
||||
the REAL registry-resolved OutlookProvider nor the REAL live gate, so a
|
||||
regression that breaks the gate short-circuit (e.g. moving network work above
|
||||
the gate) would slip past it. Here the provider is real; only the shared
|
||||
node/egress proxy preflight is mocked — it would otherwise hit the network
|
||||
per dead node (~12s libcurl timeouts), which is environment-dependent and
|
||||
not part of the reachability contract.
|
||||
|
||||
Live-browser behaviour is NOT exercised; this is mock-environment only and is
|
||||
explicitly skipped when ``GROK_REGISTER_OUTLOOK_LIVE=1``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from register_core.pipeline import Pipeline
|
||||
from register_core.providers.outlook_adapter import OutlookProvider
|
||||
from register_core.providers.registry import get_provider
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
os.environ.get("GROK_REGISTER_OUTLOOK_LIVE") == "1",
|
||||
reason="acceptance test is mock-only; live browser tests are separately gated",
|
||||
)
|
||||
|
||||
|
||||
def _mock_proxy_prefs(monkeypatch):
|
||||
"""Mock the shared node/egress probe so the test never touches the network."""
|
||||
monkeypatch.setattr(
|
||||
"register_core.util.proxy.preflight_nodes_for_register",
|
||||
lambda extra=None, *, log_fn=None: dict(extra or {}),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"register_core.util.proxy.inject_attempt_proxy",
|
||||
lambda extra=None, *, log_fn=None: {**(extra or {}), "proxy": None},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"register_core.util.proxy.report_attempt_proxy_result",
|
||||
lambda *a, **k: None,
|
||||
)
|
||||
|
||||
|
||||
def test_registry_returns_real_outlook_provider(monkeypatch):
|
||||
"""The control-plane argv `--provider outlook` resolves, through the same
|
||||
registry the CLI / Pipeline.from_job uses, to a real OutlookProvider (not a
|
||||
fake, not None). This is the first hop of reachability."""
|
||||
monkeypatch.delenv("GROK_REGISTER_OUTLOOK_LIVE", raising=False)
|
||||
provider = get_provider("outlook")
|
||||
assert isinstance(provider, OutlookProvider)
|
||||
assert provider.name == "outlook"
|
||||
|
||||
|
||||
def test_outlook_gate_off_pipeline_classifies_provider_and_stops_fast(
|
||||
monkeypatch, tmp_path
|
||||
):
|
||||
"""Gate OFF + fail_fast=True → the pipeline does exactly ONE attempt, the
|
||||
real OutlookProvider short-circuits at the gate (no browser/mailbox), and
|
||||
the result is classified as a terminal ``provider`` failure (not mail_miss,
|
||||
not fatal). This is the safe control-flow reachability contract: a non-live
|
||||
harness never opens a browser/mailbox/proxy and surfaces a provider-kind
|
||||
failure to the control plane."""
|
||||
monkeypatch.delenv("GROK_REGISTER_OUTLOOK_LIVE", raising=False)
|
||||
monkeypatch.setenv("OUTLOOK_AUTHS_DIR", str(tmp_path / "outlook_auths"))
|
||||
_mock_proxy_prefs(monkeypatch)
|
||||
|
||||
provider = get_provider("outlook")
|
||||
emitted: list = []
|
||||
stats = Pipeline(
|
||||
provider,
|
||||
fail_fast=True,
|
||||
on_result=emitted.append,
|
||||
).run(count=3, extra={})
|
||||
|
||||
# Exactly one attempt before fail-fast stop (gate is terminal provider, not
|
||||
# a soft mail_miss retry).
|
||||
assert len(stats.results) == 1, stats.results
|
||||
result = stats.results[0]
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "provider"
|
||||
assert result.provider == "outlook"
|
||||
assert result.error is not None
|
||||
assert "live gate" in result.error.lower() or "GROK_REGISTER_OUTLOOK_LIVE" in result.error, (
|
||||
result.error
|
||||
)
|
||||
assert stats.fail == 1
|
||||
assert stats.ok == 0
|
||||
assert stats.stopped_reason, "fail_fast=True must record why it stopped"
|
||||
# No artifact written (gate is OFF).
|
||||
auths = tmp_path / "outlook_auths"
|
||||
assert not auths.exists() or not list(auths.glob("outlook-*.json"))
|
||||
# Public view carries no real credential even on a gated failure: the
|
||||
# password/secret fields are present (key names are public schema, not
|
||||
# secrets) but MUST be empty for a gate-off short-circuit — no account
|
||||
# was created, so there is no value to leak.
|
||||
public = result.to_public_dict()
|
||||
assert public.get("password") in (None, "")
|
||||
assert public.get("secret") in (None, "")
|
||||
assert public.get("secret_kind") in (None, "none")
|
||||
|
||||
|
||||
def test_outlook_gate_off_is_deterministic_across_attempts(monkeypatch, tmp_path):
|
||||
"""Gate OFF + fail_fast=False → every attempt across count=3 short-circuits
|
||||
identically and deterministically (stateless gate). Proves the live gate is
|
||||
not stateful and does not degrade into a network call on repeat attempts."""
|
||||
monkeypatch.delenv("GROK_REGISTER_OUTLOOK_LIVE", raising=False)
|
||||
monkeypatch.setenv("OUTLOOK_AUTHS_DIR", str(tmp_path / "outlook_auths"))
|
||||
_mock_proxy_prefs(monkeypatch)
|
||||
|
||||
provider = get_provider("outlook")
|
||||
stats = Pipeline(provider, fail_fast=False).run(count=3, extra={})
|
||||
|
||||
assert len(stats.results) == 3, stats.results
|
||||
assert stats.fail == 3
|
||||
assert stats.ok == 0
|
||||
assert all(r.ok is False for r in stats.results)
|
||||
assert all(r.error_kind == "provider" for r in stats.results)
|
||||
assert all(
|
||||
r.error is not None
|
||||
and ("live gate" in r.error.lower() or "GROK_REGISTER_OUTLOOK_LIVE" in r.error)
|
||||
for r in stats.results
|
||||
)
|
||||
# Gate OFF across all three attempts → never opens a browser, never writes.
|
||||
auths = tmp_path / "outlook_auths"
|
||||
assert not auths.exists() or not list(auths.glob("outlook-*.json"))
|
||||
@@ -0,0 +1,103 @@
|
||||
"""End-to-end mocked acceptance for the Outlook pipeline (Task 11).
|
||||
|
||||
Live-browser behaviour is NOT exercised here — this test is mock-only and is
|
||||
explicitly skipped when ``GROK_REGISTER_OUTLOOK_LIVE=1`` (the live browser
|
||||
tests live in their own separately-gated module). The contract pinned here:
|
||||
|
||||
1. The pipeline's ``inject_attempt_proxy`` shallow-copies ``extra`` and sets
|
||||
``extra["proxy"]``; the value reaches the provider's ``register_one``.
|
||||
2. A provider that writes a 0600 Outlook auth artifact and returns a
|
||||
``RegisterResult`` with ``secret_kind="refresh_token"`` is carried
|
||||
through unchanged.
|
||||
3. The public result view (``to_public_dict``) redacts the password, the
|
||||
refresh-token secret, and the proxy value — none leak into public dicts,
|
||||
even though the on-disk private artifact retains the secret.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
|
||||
import pytest
|
||||
|
||||
from register_core.contracts import RegisterResult
|
||||
from register_core.pipeline import Pipeline
|
||||
|
||||
pytestmark = pytest.mark.skipif(
|
||||
os.environ.get("GROK_REGISTER_OUTLOOK_LIVE") == "1",
|
||||
reason="this acceptance test is mock-only; live browser tests are separately gated",
|
||||
)
|
||||
|
||||
|
||||
def test_mock_outlook_pipeline_carries_proxy_and_redacts_public_result(
|
||||
monkeypatch, tmp_path
|
||||
):
|
||||
seen: dict[str, object] = {}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"register_core.util.proxy.preflight_nodes_for_register",
|
||||
lambda extra=None, *, log_fn=None: dict(extra or {}),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"register_core.util.proxy.inject_attempt_proxy",
|
||||
lambda extra=None, *, log_fn=None: {**(extra or {}), "proxy": "synthetic-proxy"},
|
||||
)
|
||||
|
||||
class FakeOutlookProvider:
|
||||
name = "outlook"
|
||||
|
||||
def register_one(self, *, email_source, extra):
|
||||
seen["proxy"] = extra["proxy"]
|
||||
path = tmp_path / "outlook_auths" / "outlook-user.json"
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"email": "user@outlook.com",
|
||||
"password": "synthetic-password",
|
||||
"client_id": "synthetic-client-id",
|
||||
"refresh_token": "synthetic-refresh-token",
|
||||
"bound": True,
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
path.chmod(stat.S_IRUSR | stat.S_IWUSR)
|
||||
return RegisterResult(
|
||||
ok=True,
|
||||
provider=self.name,
|
||||
email="user@outlook.com",
|
||||
password="synthetic-password",
|
||||
secret="synthetic-refresh-token",
|
||||
secret_kind="refresh_token",
|
||||
artifacts={
|
||||
"outlook_auth_path": str(path),
|
||||
"bound": True,
|
||||
"recovery_email": "r@invalid",
|
||||
},
|
||||
)
|
||||
|
||||
emitted: list[RegisterResult] = []
|
||||
stats = Pipeline(
|
||||
FakeOutlookProvider(),
|
||||
fail_fast=False,
|
||||
on_result=emitted.append,
|
||||
).run(count=1, extra={})
|
||||
|
||||
assert stats.results and stats.results[0].ok is True
|
||||
assert seen == {"proxy": "synthetic-proxy"}
|
||||
path = tmp_path / "outlook_auths" / "outlook-user.json"
|
||||
assert stat.S_IMODE(path.stat().st_mode) == 0o600
|
||||
private = json.loads(path.read_text(encoding="utf-8"))
|
||||
assert private["refresh_token"] == "synthetic-refresh-token"
|
||||
|
||||
public = emitted[0].to_public_dict()
|
||||
public_json = json.dumps(public)
|
||||
assert public["artifacts"]["outlook_auth_path"] == str(path)
|
||||
assert public["artifacts"]["bound"] is True
|
||||
assert public["artifacts"]["recovery_email"] == "r@invalid"
|
||||
assert "synthetic-password" not in public_json
|
||||
assert "synthetic-refresh-token" not in public_json
|
||||
assert "synthetic-proxy" not in public_json
|
||||
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Static + filesystem checks for project-local account backup."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shutil
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def test_module_api() -> None:
|
||||
import account_backup as ab
|
||||
|
||||
assert hasattr(ab, "snapshot_registered_accounts")
|
||||
assert hasattr(ab, "backup_after_success")
|
||||
print("PASS module api")
|
||||
|
||||
|
||||
def test_snapshot_roundtrip() -> None:
|
||||
import account_backup as ab
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
root = Path(td)
|
||||
(root / "cpa_auths").mkdir()
|
||||
(root / "accounts_cli.txt").write_text(
|
||||
"a@x.com----pw----" + ("s" * 40) + "\n"
|
||||
"b@x.com----pw2----" + ("t" * 40) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
(root / "emails_used.txt").write_text("a@x.com\nb@x.com\n", encoding="utf-8")
|
||||
(root / "cpa_auths" / "xai-a@x.com.json").write_text('{"email":"a@x.com"}\n', encoding="utf-8")
|
||||
(root / "cpa_auths" / "xai-b@x.com.json").write_text('{"email":"b@x.com"}\n', encoding="utf-8")
|
||||
|
||||
res = ab.snapshot_registered_accounts(
|
||||
root,
|
||||
reason="test",
|
||||
email="a@x.com",
|
||||
make_timestamped=True,
|
||||
log_callback=lambda m: None,
|
||||
)
|
||||
assert res["ok"] is True
|
||||
assert res["account_count"] == 2
|
||||
assert res["cpa_count"] == 2
|
||||
latest = Path(res["latest"])
|
||||
assert (latest / "accounts_cli.txt").is_file()
|
||||
assert (latest / "cpa_auths" / "xai-a@x.com.json").is_file()
|
||||
man = json.loads((latest / "manifest.json").read_text(encoding="utf-8"))
|
||||
assert man["account_count"] == 2
|
||||
assert man["trigger_email"] == "a@x.com"
|
||||
assert man["accounts"][0]["has_sso"] is True
|
||||
stamped = Path(res["stamped"])
|
||||
assert stamped.is_dir()
|
||||
assert (stamped / "manifest.json").is_file()
|
||||
|
||||
# incremental success path refreshes latest only
|
||||
res2 = ab.backup_after_success(
|
||||
"b@x.com",
|
||||
root=root,
|
||||
cpa_path=root / "cpa_auths" / "xai-b@x.com.json",
|
||||
log_callback=lambda m: None,
|
||||
)
|
||||
assert res2["ok"] is True
|
||||
assert res2["stamped"] == ""
|
||||
print("PASS snapshot roundtrip")
|
||||
|
||||
|
||||
def test_cli_wires_backup() -> None:
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
assert "account_backup" in src
|
||||
assert "backup_after_success" in src
|
||||
assert "snapshot_registered_accounts" in src
|
||||
exp = (ROOT / "cpa_export.py").read_text(encoding="utf-8")
|
||||
assert "account_backup" in exp
|
||||
assert "local_backup" in exp
|
||||
print("PASS cli/export wire backup")
|
||||
|
||||
|
||||
def test_gitignore_covers_backups() -> None:
|
||||
gi = (ROOT / ".gitignore").read_text(encoding="utf-8")
|
||||
assert "backups/" in gi
|
||||
assert "accounts_cli.txt" in gi
|
||||
assert "cpa_auths" in gi
|
||||
print("PASS gitignore covers backups")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
test_module_api()
|
||||
test_snapshot_roundtrip()
|
||||
test_cli_wires_backup()
|
||||
test_gitignore_covers_backups()
|
||||
print("\nALL PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Static contracts for disk-first batch CPA import milestones."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SUP = ROOT / "scripts" / "launch_batch_supervisor.sh"
|
||||
|
||||
|
||||
def test_supervisor_forces_per_account_inject_off():
|
||||
src = SUP.read_text(encoding="utf-8")
|
||||
assert "export CPA_REMOTE_INJECT=false" in src
|
||||
# Intent may be true, but mint path freezes inject off.
|
||||
assert "per_account_inject=false" in src or "per_account_inject=false" in src.replace(" ", "")
|
||||
|
||||
|
||||
def test_supervisor_milestone_import_defaults_100():
|
||||
src = SUP.read_text(encoding="utf-8")
|
||||
assert "CPA_BATCH_IMPORT_EVERY:-100" in src or 'CPA_BATCH_IMPORT_EVERY:-100' in src
|
||||
assert "CPA_BATCH_IMPORT_SIZE:-100" in src
|
||||
assert "maybe_milestone_cpa_import" in src
|
||||
assert "LAST_IMPORT_COMPLETE" in src
|
||||
|
||||
|
||||
def test_supervisor_import_only_on_gained_and_remainder():
|
||||
src = SUP.read_text(encoding="utf-8")
|
||||
# Mid-loop: only after gained > 0, not every sub.
|
||||
assert "if (( gained > 0 )); then" in src
|
||||
assert 'maybe_milestone_cpa_import "$AFTER_COMPLETE"' in src
|
||||
# Final remainder path exists; no unconditional import every account.
|
||||
assert "target_reached_remainder" in src or "remainder" in src
|
||||
# Must not call import inside the register_cli command block.
|
||||
mint_block = src.split("python -u register_cli.py", 1)[1].split("code=$?", 1)[0]
|
||||
assert "run_batch_end_cpa_import" not in mint_block
|
||||
assert "import_cpa_auth_dir.py" not in mint_block
|
||||
|
||||
|
||||
def test_supervisor_watermark_soft_fail_advances():
|
||||
"""Import soft-failure must still advance LAST_IMPORT_COMPLETE (no spin)."""
|
||||
src = SUP.read_text(encoding="utf-8")
|
||||
assert "Advance watermark even on soft failure" in src
|
||||
assert "LAST_IMPORT_COMPLETE=$cur_complete" in src
|
||||
# Milestone path returns 0 after soft import (never stalls mint loop).
|
||||
assert "(soft)" in src
|
||||
# Probe always hard-false on mint path.
|
||||
assert "export CPA_PROBE_CHAT=false" in src
|
||||
|
||||
|
||||
def test_supervisor_residential_proxy_rotate_off():
|
||||
"""Residential must not hardcode --proxy-rotate clash (CLI overrides env)."""
|
||||
src = SUP.read_text(encoding="utf-8")
|
||||
# Shared launch uses mode variable, not a literal clash flag.
|
||||
assert '--proxy-rotate "$PROXY_ROTATE_CLI"' in src
|
||||
assert "PROXY_ROTATE_CLI=off" in src
|
||||
# Must not hardcode clash on the register_cli line (the residential bug).
|
||||
mint_block = src.split("python -u register_cli.py", 1)[1].split("code=$?", 1)[0]
|
||||
assert "--proxy-rotate clash" not in mint_block
|
||||
assert '--proxy-rotate "$PROXY_ROTATE_CLI"' in mint_block
|
||||
# Residential branch sets rotate off + 1024 PROXY.
|
||||
assert "mode=residential" in src
|
||||
assert "PROXY_ROTATE_MODE=off" in src
|
||||
@@ -0,0 +1,402 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unit checks for light browser fingerprint mode (tier A, A/B arm).
|
||||
|
||||
No live Chromium — option factory + resolver + CLI surface only.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
import types
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
|
||||
def _stub_heavy_deps() -> None:
|
||||
"""Allow importing grok_register_ttk without tkinter/DrissionPage in bare CI."""
|
||||
if "tkinter" not in sys.modules:
|
||||
tk = types.ModuleType("tkinter")
|
||||
tk.StringVar = object
|
||||
tk.BooleanVar = object
|
||||
tk.END = "end"
|
||||
for attr in ("W", "E", "N", "S", "EW", "BOTH", "X", "Y", "LEFT"):
|
||||
setattr(tk, attr, attr.lower())
|
||||
tk.Tk = type("Tk", (), {})
|
||||
sys.modules["tkinter"] = tk
|
||||
for sub in ("ttk", "messagebox", "scrolledtext"):
|
||||
sys.modules[f"tkinter.{sub}"] = types.ModuleType(f"tkinter.{sub}")
|
||||
if "DrissionPage" not in sys.modules:
|
||||
dp = types.ModuleType("DrissionPage")
|
||||
dp.Chromium = object
|
||||
dp.ChromiumOptions = object
|
||||
sys.modules["DrissionPage"] = dp
|
||||
err = types.ModuleType("DrissionPage.errors")
|
||||
err.PageDisconnectedError = type("PageDisconnectedError", (Exception,), {})
|
||||
sys.modules["DrissionPage.errors"] = err
|
||||
if "curl_cffi" not in sys.modules:
|
||||
cc = types.ModuleType("curl_cffi")
|
||||
req = types.ModuleType("curl_cffi.requests")
|
||||
cc.requests = req
|
||||
sys.modules["curl_cffi"] = cc
|
||||
sys.modules["curl_cffi.requests"] = req
|
||||
|
||||
|
||||
def _load():
|
||||
_stub_heavy_deps()
|
||||
import grok_register_ttk as m
|
||||
|
||||
return m
|
||||
|
||||
|
||||
def test_resolve_mode_defaults_off() -> None:
|
||||
ttk = _load()
|
||||
old_env = os.environ.pop("BROWSER_FINGERPRINT_MODE", None)
|
||||
old_cfg = ttk.config.get("browser_fingerprint_mode")
|
||||
old_perf = ttk.PERF_FLAGS.get("browser_fingerprint_mode")
|
||||
try:
|
||||
ttk.config["browser_fingerprint_mode"] = "off"
|
||||
ttk.PERF_FLAGS["browser_fingerprint_mode"] = "off"
|
||||
assert ttk.resolve_browser_fingerprint_mode() == "off"
|
||||
assert ttk.resolve_browser_fingerprint_mode("light") == "light"
|
||||
assert ttk.resolve_browser_fingerprint_mode("OFF") == "off"
|
||||
assert ttk.resolve_browser_fingerprint_mode("random") == "light"
|
||||
assert ttk.resolve_browser_fingerprint_mode("anon") == "anon"
|
||||
assert ttk.resolve_browser_fingerprint_mode("anonymous") == "anon"
|
||||
assert ttk.resolve_browser_fingerprint_mode("incognito") == "anon"
|
||||
os.environ["BROWSER_FINGERPRINT_MODE"] = "light"
|
||||
ttk.config["browser_fingerprint_mode"] = "off"
|
||||
ttk.PERF_FLAGS["browser_fingerprint_mode"] = "off"
|
||||
# explicit still wins
|
||||
assert ttk.resolve_browser_fingerprint_mode("off") == "off"
|
||||
# PERF/config empty → env light
|
||||
ttk.PERF_FLAGS["browser_fingerprint_mode"] = ""
|
||||
ttk.config["browser_fingerprint_mode"] = ""
|
||||
assert ttk.resolve_browser_fingerprint_mode() == "light"
|
||||
finally:
|
||||
if old_env is None:
|
||||
os.environ.pop("BROWSER_FINGERPRINT_MODE", None)
|
||||
else:
|
||||
os.environ["BROWSER_FINGERPRINT_MODE"] = old_env
|
||||
if old_cfg is not None:
|
||||
ttk.config["browser_fingerprint_mode"] = old_cfg
|
||||
if old_perf is not None:
|
||||
ttk.PERF_FLAGS["browser_fingerprint_mode"] = old_perf
|
||||
print("PASS resolve_browser_fingerprint_mode")
|
||||
|
||||
|
||||
def test_pick_light_fingerprint_deterministic() -> None:
|
||||
ttk = _load()
|
||||
a = ttk.pick_light_fingerprint(rng=random.Random(42))
|
||||
b = ttk.pick_light_fingerprint(rng=random.Random(42))
|
||||
assert a == b
|
||||
assert a["mode"] == "light"
|
||||
assert a["user_agent"] in ttk._LIGHT_UA_POOL
|
||||
assert (a["width"], a["height"]) in ttk._LIGHT_VIEWPORTS
|
||||
assert a["lang"]
|
||||
assert a["accept_lang"]
|
||||
c = ttk.pick_light_fingerprint(rng=random.Random(7))
|
||||
d = ttk.pick_light_fingerprint(rng=random.Random(99))
|
||||
assert c["user_agent"] and d["user_agent"]
|
||||
print("PASS pick_light_fingerprint deterministic")
|
||||
|
||||
|
||||
def test_apply_light_fingerprint_sets_options() -> None:
|
||||
ttk = _load()
|
||||
opts = MagicMock()
|
||||
fp = {
|
||||
"user_agent": (
|
||||
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36"
|
||||
),
|
||||
"width": 1440,
|
||||
"height": 900,
|
||||
"lang": "en-GB",
|
||||
"accept_lang": "en-GB,en;q=0.9",
|
||||
}
|
||||
out = ttk.apply_light_fingerprint(opts, fp)
|
||||
opts.set_user_agent.assert_called_with(fp["user_agent"])
|
||||
args = [c.args[0] for c in opts.set_argument.call_args_list]
|
||||
assert "--window-size=1440,900" in args
|
||||
assert "--lang=en-GB" in args
|
||||
assert "--accept-lang=en-GB,en;q=0.9" in args
|
||||
assert out["mode"] == "light"
|
||||
assert ttk._LAST_BROWSER_FINGERPRINT == out
|
||||
print("PASS apply_light_fingerprint sets options")
|
||||
|
||||
|
||||
def test_create_browser_options_light_applies_pool() -> None:
|
||||
ttk = _load()
|
||||
|
||||
class FakeOpts:
|
||||
def __init__(self):
|
||||
self.arguments = []
|
||||
self.ua = None
|
||||
|
||||
def auto_port(self):
|
||||
return None
|
||||
|
||||
def set_timeouts(self, **kw):
|
||||
return None
|
||||
|
||||
def set_argument(self, flag):
|
||||
self.arguments.append(flag)
|
||||
|
||||
def set_user_agent(self, ua):
|
||||
self.ua = ua
|
||||
|
||||
def headless(self, v):
|
||||
return None
|
||||
|
||||
def add_extension(self, path):
|
||||
return None
|
||||
|
||||
old_co = ttk.ChromiumOptions
|
||||
old_env = os.environ.pop("BROWSER_FINGERPRINT_MODE", None)
|
||||
old_seed = os.environ.pop("BROWSER_FINGERPRINT_SEED", None)
|
||||
old_mode_cfg = ttk.config.get("browser_fingerprint_mode")
|
||||
old_mode_perf = ttk.PERF_FLAGS.get("browser_fingerprint_mode")
|
||||
old_headless = ttk.config.get("browser_headless")
|
||||
try:
|
||||
ttk.ChromiumOptions = FakeOpts # type: ignore
|
||||
ttk.config["browser_headless"] = True # skip DISPLAY check
|
||||
ttk.config["browser_fingerprint_mode"] = "light"
|
||||
ttk.PERF_FLAGS["browser_fingerprint_mode"] = "light"
|
||||
os.environ["BROWSER_FINGERPRINT_SEED"] = "12345"
|
||||
opts = ttk.create_browser_options(browser_proxy="", apply_config_proxy=False)
|
||||
assert isinstance(opts, FakeOpts)
|
||||
assert opts.ua # light set UA even in headless
|
||||
assert any(str(a).startswith("--window-size=") for a in opts.arguments)
|
||||
assert any(str(a).startswith("--lang=") for a in opts.arguments)
|
||||
assert ttk._LAST_BROWSER_FINGERPRINT and ttk._LAST_BROWSER_FINGERPRINT.get("mode") == "light"
|
||||
# off mode
|
||||
ttk.config["browser_fingerprint_mode"] = "off"
|
||||
ttk.PERF_FLAGS["browser_fingerprint_mode"] = "off"
|
||||
os.environ.pop("BROWSER_FINGERPRINT_MODE", None)
|
||||
opts2 = ttk.create_browser_options(browser_proxy="", apply_config_proxy=False)
|
||||
assert ttk._LAST_BROWSER_FINGERPRINT == {"mode": "off"}
|
||||
assert any(str(a) == "--window-size=1280,900" for a in opts2.arguments)
|
||||
finally:
|
||||
ttk.ChromiumOptions = old_co
|
||||
if old_env is None:
|
||||
os.environ.pop("BROWSER_FINGERPRINT_MODE", None)
|
||||
else:
|
||||
os.environ["BROWSER_FINGERPRINT_MODE"] = old_env
|
||||
if old_seed is None:
|
||||
os.environ.pop("BROWSER_FINGERPRINT_SEED", None)
|
||||
else:
|
||||
os.environ["BROWSER_FINGERPRINT_SEED"] = old_seed
|
||||
if old_mode_cfg is not None:
|
||||
ttk.config["browser_fingerprint_mode"] = old_mode_cfg
|
||||
if old_mode_perf is not None:
|
||||
ttk.PERF_FLAGS["browser_fingerprint_mode"] = old_mode_perf
|
||||
if old_headless is not None:
|
||||
ttk.config["browser_headless"] = old_headless
|
||||
print("PASS create_browser_options light vs off")
|
||||
|
||||
|
||||
def test_register_cli_surface() -> None:
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
assert "--browser-fingerprint-mode" in src
|
||||
assert "browser_fingerprint_mode" in src
|
||||
assert 'choices=("off", "light", "anon")' in src or "choices=('off', 'light', 'anon')" in src
|
||||
ttk_src = (ROOT / "grok_register_ttk.py").read_text(encoding="utf-8")
|
||||
assert "def resolve_browser_fingerprint_mode" in ttk_src
|
||||
assert "def pick_light_fingerprint" in ttk_src
|
||||
assert "def apply_light_fingerprint" in ttk_src
|
||||
assert "def fingerprint_forces_hard_recycle" in ttk_src
|
||||
assert '"browser_fingerprint_mode"' in ttk_src
|
||||
cfg = (ROOT / "config.example.json").read_text(encoding="utf-8")
|
||||
assert "browser_fingerprint_mode" in cfg
|
||||
assert "anon" in cfg
|
||||
print("PASS register_cli + ttk + config.example surface")
|
||||
|
||||
|
||||
def test_anon_forces_hard_recycle_no_incognito() -> None:
|
||||
"""anon = light + hard recycle; --incognito is intentionally NOT set.
|
||||
|
||||
2026-07-25: anon+Chrome/138 spoof + --incognito → Turnstile token_len=0 on
|
||||
CFT 149. Isolation comes from hard recycle + auto_port, not private mode.
|
||||
"""
|
||||
ttk = _load()
|
||||
|
||||
class FakeOpts:
|
||||
def __init__(self):
|
||||
self.arguments = []
|
||||
self.ua = None
|
||||
|
||||
def auto_port(self):
|
||||
return None
|
||||
|
||||
def set_timeouts(self, **kw):
|
||||
return None
|
||||
|
||||
def set_argument(self, flag):
|
||||
self.arguments.append(flag)
|
||||
|
||||
def set_user_agent(self, ua):
|
||||
self.ua = ua
|
||||
|
||||
def headless(self, v):
|
||||
return None
|
||||
|
||||
def add_extension(self, path):
|
||||
return None
|
||||
|
||||
old_co = ttk.ChromiumOptions
|
||||
old_env = os.environ.pop("BROWSER_FINGERPRINT_MODE", None)
|
||||
old_seed = os.environ.pop("BROWSER_FINGERPRINT_SEED", None)
|
||||
old_mode_cfg = ttk.config.get("browser_fingerprint_mode")
|
||||
old_mode_perf = ttk.PERF_FLAGS.get("browser_fingerprint_mode")
|
||||
old_recycle_cfg = ttk.config.get("browser_recycle_mode")
|
||||
old_recycle_perf = ttk.PERF_FLAGS.get("browser_recycle_mode")
|
||||
old_headless = ttk.config.get("browser_headless")
|
||||
try:
|
||||
ttk.ChromiumOptions = FakeOpts # type: ignore
|
||||
ttk.config["browser_headless"] = True
|
||||
ttk.config["browser_fingerprint_mode"] = "anon"
|
||||
ttk.PERF_FLAGS["browser_fingerprint_mode"] = "anon"
|
||||
ttk.config["browser_recycle_mode"] = "hybrid"
|
||||
ttk.PERF_FLAGS["browser_recycle_mode"] = "hybrid"
|
||||
assert ttk.fingerprint_forces_hard_recycle() is True
|
||||
assert ttk._resolved_recycle_mode() == "hard"
|
||||
os.environ["BROWSER_FINGERPRINT_SEED"] = "99"
|
||||
opts = ttk.create_browser_options(browser_proxy="", apply_config_proxy=False)
|
||||
assert isinstance(opts, FakeOpts)
|
||||
assert opts.ua
|
||||
assert "Chrome/149" in opts.ua # must match CFT major
|
||||
assert "--incognito" not in opts.arguments
|
||||
assert ttk._LAST_BROWSER_FINGERPRINT.get("mode") == "anon"
|
||||
assert ttk._LAST_BROWSER_FINGERPRINT.get("incognito") is False
|
||||
# light does not force hard or incognito
|
||||
ttk.config["browser_fingerprint_mode"] = "light"
|
||||
ttk.PERF_FLAGS["browser_fingerprint_mode"] = "light"
|
||||
assert ttk.fingerprint_forces_hard_recycle() is False
|
||||
assert ttk._resolved_recycle_mode() == "hybrid"
|
||||
opts_light = ttk.create_browser_options(browser_proxy="", apply_config_proxy=False)
|
||||
assert "--incognito" not in opts_light.arguments
|
||||
assert ttk._LAST_BROWSER_FINGERPRINT.get("mode") == "light"
|
||||
assert "Chrome/149" in (opts_light.ua or "")
|
||||
finally:
|
||||
ttk.ChromiumOptions = old_co
|
||||
if old_env is None:
|
||||
os.environ.pop("BROWSER_FINGERPRINT_MODE", None)
|
||||
else:
|
||||
os.environ["BROWSER_FINGERPRINT_MODE"] = old_env
|
||||
if old_seed is None:
|
||||
os.environ.pop("BROWSER_FINGERPRINT_SEED", None)
|
||||
else:
|
||||
os.environ["BROWSER_FINGERPRINT_SEED"] = old_seed
|
||||
if old_mode_cfg is not None:
|
||||
ttk.config["browser_fingerprint_mode"] = old_mode_cfg
|
||||
if old_mode_perf is not None:
|
||||
ttk.PERF_FLAGS["browser_fingerprint_mode"] = old_mode_perf
|
||||
if old_recycle_cfg is not None:
|
||||
ttk.config["browser_recycle_mode"] = old_recycle_cfg
|
||||
if old_recycle_perf is not None:
|
||||
ttk.PERF_FLAGS["browser_recycle_mode"] = old_recycle_perf
|
||||
if old_headless is not None:
|
||||
ttk.config["browser_headless"] = old_headless
|
||||
print("PASS anon forces hard recycle, no --incognito, UA major 149")
|
||||
|
||||
|
||||
def test_light_ua_pool_matches_cft_major() -> None:
|
||||
"""Every pool UA must carry Chrome/149 — binary is CFT 149 on pxed."""
|
||||
ttk = _load()
|
||||
for ua in ttk._LIGHT_UA_POOL:
|
||||
assert "Chrome/149" in ua, f"stale major in pool: {ua}"
|
||||
assert "Chrome/138" not in ua
|
||||
assert "Chrome/137" not in ua
|
||||
assert "Chrome/136" not in ua
|
||||
# default config UA too
|
||||
default_ua = str(ttk.DEFAULT_CONFIG.get("user_agent") or "")
|
||||
assert "Chrome/149" in default_ua, default_ua
|
||||
print("PASS light UA pool major matches CFT 149")
|
||||
|
||||
|
||||
def test_email_fill_shares_ready_selectors() -> None:
|
||||
"""AB_N=10 light: ready saw the input, fill used a narrower CSS list → 20s timeout.
|
||||
|
||||
Ready + fill + submit must all inject the same _EMAIL_INPUT_CSS constant.
|
||||
"""
|
||||
ttk = _load()
|
||||
src = (ROOT / "grok_register_ttk.py").read_text(encoding="utf-8")
|
||||
assert "_EMAIL_INPUT_CSS" in src
|
||||
assert "input[autocomplete=\"username\"]" in ttk._EMAIL_INPUT_CSS
|
||||
assert "placeholder*=" in ttk._EMAIL_INPUT_CSS
|
||||
# ready + both fill_email run_js sites must reference the shared constant
|
||||
ready_idx = src.find("def _email_input_ready")
|
||||
fill_idx = src.find("def fill_email_and_submit")
|
||||
assert ready_idx >= 0 and fill_idx > ready_idx
|
||||
ready_chunk = src[ready_idx:fill_idx]
|
||||
fill_chunk = src[fill_idx : fill_idx + 9000]
|
||||
assert "_EMAIL_INPUT_CSS" in ready_chunk
|
||||
assert fill_chunk.count("_EMAIL_INPUT_CSS") >= 2
|
||||
# Old narrow hard-coded list must not remain in fill path
|
||||
assert (
|
||||
"input[data-testid=\"email\"], input[name=\"email\"], input[type=\"email\"], "
|
||||
"input[autocomplete=\"email\"]"
|
||||
) not in fill_chunk
|
||||
print("PASS email fill shares ready selectors")
|
||||
|
||||
|
||||
def test_submit_button_matches_en_sign_up_after_space_strip() -> None:
|
||||
"""EN 'Sign up' became 'signup' after whitespace strip; old matcher looked for 'sign up'."""
|
||||
src = (ROOT / "grok_register_ttk.py").read_text(encoding="utf-8")
|
||||
fill_idx = src.find("def fill_email_and_submit")
|
||||
fill_chunk = src[fill_idx : fill_idx + 9000]
|
||||
assert "compact.includes('signup')" in fill_chunk
|
||||
# Regression: must NOT require spaced phrase after stripping spaces
|
||||
assert "lower.includes('sign up')" not in fill_chunk
|
||||
# checkValidity gate removed (custom validators false-negative on EN form)
|
||||
assert "input.checkValidity()" not in fill_chunk
|
||||
print("PASS EN Sign up submit matcher + no checkValidity gate")
|
||||
|
||||
|
||||
def test_signing_into_not_login_progress() -> None:
|
||||
"""Provider chooser header 'You are signing into …' must not trip login-progress."""
|
||||
src = (ROOT / "grok_register_ttk.py").read_text(encoding="utf-8")
|
||||
fn = src.find("def _signup_login_in_progress")
|
||||
assert fn >= 0
|
||||
chunk = src[fn : fn + 2500]
|
||||
assert "signingInto" in chunk or "signing\\\\s*into" in chunk or "signing\\s*into" in chunk
|
||||
assert "signing into" in chunk.lower() or "signingInto" in chunk
|
||||
print("PASS signing-into excluded from login-progress")
|
||||
|
||||
|
||||
def test_light_lang_pool_includes_zh_cn() -> None:
|
||||
ttk = _load()
|
||||
joined = " | ".join(ttk._LIGHT_LANGS)
|
||||
assert "zh-CN" in joined
|
||||
# at least one primary zh-CN entry (not only secondary q=0.8)
|
||||
primaries = [
|
||||
(lang.split(",", 1)[0] or "").split(";", 1)[0].strip()
|
||||
for lang in ttk._LIGHT_LANGS
|
||||
]
|
||||
assert "zh-CN" in primaries
|
||||
print("PASS light lang pool includes zh-CN primary")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
test_resolve_mode_defaults_off()
|
||||
test_pick_light_fingerprint_deterministic()
|
||||
test_apply_light_fingerprint_sets_options()
|
||||
test_create_browser_options_light_applies_pool()
|
||||
test_register_cli_surface()
|
||||
test_anon_forces_hard_recycle_no_incognito()
|
||||
test_light_ua_pool_matches_cft_major()
|
||||
test_email_fill_shares_ready_selectors()
|
||||
test_submit_button_matches_en_sign_up_after_space_strip()
|
||||
test_signing_into_not_login_progress()
|
||||
test_light_lang_pool_includes_zh_cn()
|
||||
print("ALL PASS test_browser_fingerprint_light")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,202 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Static + unit checks for recycle modes, slot retry, and mint proxy wiring."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def test_account_retry_exception_exists() -> None:
|
||||
src = (ROOT / "grok_register_ttk.py").read_text(encoding="utf-8")
|
||||
assert "class AccountRetryNeeded" in src
|
||||
assert "raise AccountRetryNeeded" in src
|
||||
assert "except AccountRetryNeeded" in src
|
||||
assert "final_page_no_submit" in src
|
||||
# no silent bridge downgrade
|
||||
assert "refuse direct" in src or "proxy bridge failed" in src
|
||||
assert "apply_config_proxy" in src
|
||||
print("PASS AccountRetryNeeded + proxy API in ttk")
|
||||
|
||||
|
||||
def test_recycle_mode_in_perf_and_prepare() -> None:
|
||||
src = (ROOT / "grok_register_ttk.py").read_text(encoding="utf-8")
|
||||
assert '"browser_recycle_mode"' in src or "'browser_recycle_mode'" in src
|
||||
assert "def _resolved_recycle_mode" in src
|
||||
assert "def prepare_browser_for_next_account" in src
|
||||
assert 'mode != "hard"' in src or "mode != 'hard'" in src or 'mode == "hard"' in src
|
||||
assert "hybrid" in src
|
||||
assert "stop_browser_proxy_bridge" in src
|
||||
assert "stop_all_browser_proxy_bridges" in src
|
||||
# dead helper must stay gone
|
||||
assert "def _thread_proxy_bridge" not in src
|
||||
print("PASS recycle mode wiring in ttk")
|
||||
|
||||
|
||||
def test_register_cli_slot_retry() -> None:
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
assert "account_slot_retry" in src
|
||||
assert "_account_slot_retry_limit" in src
|
||||
assert "slot 重试" in src or "slot重试" in src
|
||||
assert "browser_recycle_mode" in src
|
||||
assert "--browser-recycle-mode" in src
|
||||
assert "--browser-fingerprint-mode" in src
|
||||
assert "browser_fingerprint_mode" in src
|
||||
assert "--account-slot-retry" in src
|
||||
assert "FatalRegisterError" in src
|
||||
assert "AccountRetryNeeded" in src
|
||||
assert "_resolved_recycle_mode" in src
|
||||
# no local AccountRetryNeeded fallback class
|
||||
assert "class AccountRetryNeeded" not in src
|
||||
# no worker×slot multiplicative outer re-run loop
|
||||
assert "while retry < 2" not in src
|
||||
assert "slot_exhausted" in src
|
||||
assert "skip-outer-retry" in src
|
||||
# patch must forward apply_config_proxy
|
||||
assert "apply_config_proxy" in src
|
||||
# mail-stage ARN must not escape register_one: shared try wraps mail+profile
|
||||
assert "Mail + profile share one try" in src
|
||||
# mail try re-raises ARN into shared handler (not swallowed)
|
||||
assert "except AccountRetryNeeded" in src
|
||||
print("PASS register_cli slot retry + recycle CLI")
|
||||
|
||||
|
||||
def test_mint_proxy_once() -> None:
|
||||
src = (ROOT / "cpa_xai" / "browser_confirm.py").read_text(encoding="utf-8")
|
||||
assert "apply_config_proxy=False" in src
|
||||
assert 'browser_proxy=""' in src or "browser_proxy=''" in src
|
||||
assert "resolve_browser_proxy" in src
|
||||
assert "_auth_proxy_bridge" in src
|
||||
print("PASS mint path proxy set once")
|
||||
|
||||
|
||||
def test_config_example_keys() -> None:
|
||||
raw = (ROOT / "config.example.json").read_text(encoding="utf-8")
|
||||
for key in (
|
||||
"browser_recycle_mode",
|
||||
"browser_recycle_every",
|
||||
"browser_fingerprint_mode",
|
||||
"account_slot_retry",
|
||||
"final_page_no_submit_timeout",
|
||||
"LocalAuthProxyBridge",
|
||||
"soft 忽略",
|
||||
):
|
||||
assert key in raw, f"missing in config.example.json: {key}"
|
||||
print("PASS config.example keys")
|
||||
|
||||
|
||||
def test_resolved_recycle_mode_unit() -> None:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
tree = ast.parse((ROOT / "register_cli.py").read_text(encoding="utf-8"))
|
||||
names = {
|
||||
n.name
|
||||
for n in tree.body
|
||||
if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef))
|
||||
}
|
||||
assert "_resolved_recycle_mode" in names
|
||||
assert "_account_slot_retry_limit" in names
|
||||
assert "register_one" in names
|
||||
print("PASS register_cli helper defs present")
|
||||
|
||||
|
||||
def test_account_slot_retry_limit_values() -> None:
|
||||
"""0 must stay 0; missing/None/empty → 3; clamp to [0,10]."""
|
||||
sys.path.insert(0, str(ROOT))
|
||||
# Import only the pure helper without side-effectful register_cli import.
|
||||
# Execute the function body from source via a minimal namespace.
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
# Locate function AST and compile just that function + deps
|
||||
tree = ast.parse(src)
|
||||
fn_node = None
|
||||
for n in tree.body:
|
||||
if isinstance(n, ast.FunctionDef) and n.name == "_account_slot_retry_limit":
|
||||
fn_node = n
|
||||
break
|
||||
assert fn_node is not None
|
||||
mod = ast.Module(body=[fn_node], type_ignores=[])
|
||||
ast.fix_missing_locations(mod)
|
||||
ns: dict = {}
|
||||
exec(compile(mod, "<slot_limit>", "exec"), ns)
|
||||
limit = ns["_account_slot_retry_limit"]
|
||||
|
||||
assert limit({"account_slot_retry": 0}) == 0
|
||||
assert limit({"account_slot_retry": "0"}) == 0
|
||||
assert limit({"account_slot_retry": 3}) == 3
|
||||
assert limit({"account_slot_retry": 11}) == 10
|
||||
assert limit({"account_slot_retry": -1}) == 0
|
||||
assert limit({}) == 3
|
||||
assert limit({"account_slot_retry": None}) == 3
|
||||
assert limit({"account_slot_retry": ""}) == 3
|
||||
assert limit({"account_slot_retry": "nope"}) == 3
|
||||
print("PASS account_slot_retry_limit 0/3/11/missing")
|
||||
|
||||
|
||||
def test_proxy_bridge_module() -> None:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from proxy_bridge import proxy_has_auth, resolve_browser_proxy, strip_proxy_auth
|
||||
|
||||
assert proxy_has_auth("http://a:b@h:1")
|
||||
assert strip_proxy_auth("http://a:b@h:1") == "http://h:1"
|
||||
u, b = resolve_browser_proxy("http://127.0.0.1:9")
|
||||
assert b is None and "127.0.0.1" in u
|
||||
print("PASS proxy_bridge import smoke")
|
||||
|
||||
|
||||
def test_list_rotate_hard_recycles_browser() -> None:
|
||||
"""list-mode proxy rotate must stop_browser so --proxy-server rebinds."""
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
assert "def _ensure_browser" in src
|
||||
assert 'rotate_result.get("rotated")' in src or "rotate_result.get('rotated')" in src
|
||||
assert '== "list"' in src or "== 'list'" in src
|
||||
assert "list 代理已轮换" in src
|
||||
assert "reg.stop_browser()" in src
|
||||
# must sit inside _ensure_browser path (not only elsewhere)
|
||||
idx = src.find("def _ensure_browser")
|
||||
assert idx >= 0
|
||||
chunk = src[idx : idx + 2500]
|
||||
assert "list 代理已轮换" in chunk
|
||||
assert "stop_browser" in chunk
|
||||
print("PASS list rotate hard-recycles browser in _ensure_browser")
|
||||
|
||||
|
||||
def test_final_page_cf_fail_fast_markers() -> None:
|
||||
"""final-page Turnstile must fail-fast via AccountRetryNeeded + log throttle."""
|
||||
src = (ROOT / "grok_register_ttk.py").read_text(encoding="utf-8")
|
||||
assert "final_cf_wait_since" in src
|
||||
assert "last_final_cf_token_len" in src
|
||||
assert "final_cf_retried" in src
|
||||
assert "final_cf_stuck_timeout" in src
|
||||
assert "final_cf_retry_limit" in src
|
||||
assert "最终页 Turnstile 卡住 fail-fast" in src
|
||||
assert "最终页 Turnstile retries exhausted" in src
|
||||
assert "raise AccountRetryNeeded" in src
|
||||
# fill_email must re-raise AccountRetryNeeded (SPA-stuck / browser_boot)
|
||||
assert "except AccountRetryNeeded" in src
|
||||
fill_idx = src.find("def fill_email_and_submit")
|
||||
assert fill_idx >= 0
|
||||
fill_chunk = src[fill_idx : fill_idx + 3500]
|
||||
assert "except AccountRetryNeeded" in fill_chunk
|
||||
assert "raise" in fill_chunk[fill_chunk.find("except AccountRetryNeeded") :]
|
||||
print("PASS final-page CF fail-fast + fill_email re-raise AccountRetryNeeded")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
test_account_retry_exception_exists()
|
||||
test_recycle_mode_in_perf_and_prepare()
|
||||
test_register_cli_slot_retry()
|
||||
test_mint_proxy_once()
|
||||
test_config_example_keys()
|
||||
test_resolved_recycle_mode_unit()
|
||||
test_account_slot_retry_limit_values()
|
||||
test_proxy_bridge_module()
|
||||
test_list_rotate_hard_recycles_browser()
|
||||
test_final_page_cf_fail_fast_markers()
|
||||
print("\nALL PASS (recycle/slot)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,507 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline tests for browser reliability: start lock, mint retries, chrome-error page."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import os
|
||||
import sys
|
||||
import types
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def test_tab_pool_chromium_start_lock_source() -> None:
|
||||
src = (ROOT / "tab_pool.py").read_text(encoding="utf-8")
|
||||
assert "_chromium_start_lock" in src
|
||||
assert "def chromium_start_lock" in src
|
||||
assert "with _chromium_start_lock:" in src
|
||||
assert "browser = Chromium(options)" in src
|
||||
assert "def display_available" in src
|
||||
# CFT149 + turnstilePatch: only service_worker in /json → need page target.
|
||||
assert "def patch_drission_test_connect" in src
|
||||
assert "def ensure_cdp_page_target" in src
|
||||
assert "patch_drission_test_connect()" in src
|
||||
print("PASS tab_pool chromium start lock + display_available + cdp page patch")
|
||||
|
||||
|
||||
def test_remote_allow_origins_in_slim_flags() -> None:
|
||||
"""Chrome 149 CDP rejects WS without --remote-allow-origins (HTTP /json still works)."""
|
||||
ttk = (ROOT / "grok_register_ttk.py").read_text(encoding="utf-8")
|
||||
assert '"--remote-allow-origins=*"' in ttk or "'--remote-allow-origins=*'" in ttk
|
||||
assert "CHROMIUM_SLIM_FLAGS" in ttk
|
||||
cli = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
assert "--remote-allow-origins=*" in cli
|
||||
mint = (ROOT / "cpa_xai" / "browser_confirm.py").read_text(encoding="utf-8")
|
||||
assert "--remote-allow-origins=*" in mint
|
||||
print("PASS remote-allow-origins in slim flags + register_cli + mint fallback")
|
||||
|
||||
|
||||
def test_display_available_unit() -> None:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
import importlib
|
||||
|
||||
import tab_pool as tp
|
||||
|
||||
importlib.reload(tp)
|
||||
# Platform-specific: darwin always True regardless of DISPLAY
|
||||
if sys.platform == "darwin" or sys.platform.startswith("win"):
|
||||
with mock.patch.dict(os.environ, {"DISPLAY": ""}, clear=False):
|
||||
assert tp.display_available() is True
|
||||
print("PASS display_available always True on macOS/Windows")
|
||||
else:
|
||||
with mock.patch.dict(os.environ, {"DISPLAY": ""}, clear=False):
|
||||
os.environ.pop("DISPLAY", None)
|
||||
assert tp.display_available() is False
|
||||
with mock.patch.dict(os.environ, {"DISPLAY": ":99"}, clear=False):
|
||||
assert tp.display_available() is True
|
||||
with mock.patch.dict(os.environ, {"DISPLAY": " "}, clear=False):
|
||||
assert tp.display_available() is False
|
||||
print("PASS display_available Linux DISPLAY gate")
|
||||
|
||||
|
||||
def test_create_standalone_retries_and_lock() -> None:
|
||||
src = (ROOT / "cpa_xai" / "browser_confirm.py").read_text(encoding="utf-8")
|
||||
assert "chromium_start_lock" in src
|
||||
assert "max_attempts" in src
|
||||
# Default max_attempts must match start_browser (4) — first-start flake recovery.
|
||||
assert "max_attempts: int = 4" in src
|
||||
assert "max_attempts or 4" in src or "int(max_attempts or 4)" in src
|
||||
assert "cleanup_orphan_drission_chromes" in src
|
||||
assert "SIGKILL" in src or "signal.SIGKILL" in src
|
||||
assert "standalone chromium start failed" in src
|
||||
assert "with chromium_start_lock()" in src
|
||||
# no bare single Chromium(opts) without lock in create path — lock wraps Chromium
|
||||
assert "browser = Chromium(opts)" in src
|
||||
assert "headed mint 需要 DISPLAY" in src
|
||||
assert "no DISPLAY/xvfb" in src
|
||||
print("PASS create_standalone retry+lock+orphan+DISPLAY source")
|
||||
|
||||
|
||||
def test_hard_recycle_cleans_orphans() -> None:
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
assert "def _hard_recycle_browser" in src
|
||||
# mid-run orphan cleanup
|
||||
assert "cleanup_orphans" in src
|
||||
assert "hard recycle orphan cleanup" in src
|
||||
assert "browser_boot" in src
|
||||
assert "def headed_display_ready" in src
|
||||
assert "Turnstile headless 失败且无可用 DISPLAY" in src
|
||||
assert "headed_display_ready()" in src
|
||||
print("PASS hard recycle orphan cleanup + DISPLAY upgrade gate source")
|
||||
|
||||
|
||||
def test_launch_supervisor_wires_fingerprint_default_off() -> None:
|
||||
"""Default off (known-good Turnstile). anon still available via env override."""
|
||||
src = (ROOT / "scripts" / "launch_batch_supervisor.sh").read_text(encoding="utf-8")
|
||||
assert "BROWSER_FINGERPRINT_MODE" in src
|
||||
assert "--browser-fingerprint-mode" in src
|
||||
assert (
|
||||
'FP_MODE=${BROWSER_FINGERPRINT_MODE:-off}' in src
|
||||
or 'FP_MODE="${BROWSER_FINGERPRINT_MODE:-off}"' in src
|
||||
)
|
||||
# anon still forces hard recycle when selected
|
||||
assert 'RECYCLE_MODE=hard' in src
|
||||
assert 'FP_MODE" == "anon"' in src or "FP_MODE == \"anon\"" in src or 'FP_MODE" == "anon"' in src or '[[ "$FP_MODE" == "anon" ]]' in src
|
||||
print("PASS launch_batch_supervisor fingerprint default=off")
|
||||
|
||||
|
||||
def test_start_browser_cleans_orphans_on_fail() -> None:
|
||||
src = (ROOT / "grok_register_ttk.py").read_text(encoding="utf-8")
|
||||
assert "def start_browser" in src
|
||||
assert "TabPool.cleanup_orphans" in src
|
||||
assert "def is_chrome_error_page" in src
|
||||
assert "def chrome_error_summary" in src
|
||||
assert "browser_boot: chrome error page" in src
|
||||
assert "raise AccountRetryNeeded" in src
|
||||
assert "headed 需要 DISPLAY/xvfb-run" in src
|
||||
print("PASS start_browser orphan + chrome error page + DISPLAY source")
|
||||
|
||||
|
||||
def test_signup_spa_stuck_raises_account_retry() -> None:
|
||||
"""Pre-email「您正在登录」stickiness must AccountRetryNeeded, not plain Exception."""
|
||||
src = (ROOT / "grok_register_ttk.py").read_text(encoding="utf-8")
|
||||
assert "def click_email_signup_button" in src
|
||||
assert "signup_spa_stuck" in src
|
||||
assert "browser_boot: signup_spa_stuck" in src
|
||||
# Both raise sites must use AccountRetryNeeded with stable prefix.
|
||||
assert src.count("browser_boot: signup_spa_stuck") >= 2
|
||||
bad_plain = (
|
||||
'raise Exception(\n "邮箱注册按钮点击后停留在「您正在登录」'
|
||||
)
|
||||
bad_plain2 = (
|
||||
'raise Exception(\n "未找到邮箱表单:页面停在「您正在登录」'
|
||||
)
|
||||
assert bad_plain not in src, "SPA stuck mid-wait still raises plain Exception"
|
||||
assert bad_plain2 not in src, "SPA stuck final still raises plain Exception"
|
||||
print("PASS signup_spa_stuck raises AccountRetryNeeded")
|
||||
|
||||
|
||||
def test_classify_email_stage_browser_boot() -> None:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
# Load classify without importing full register_cli side effects.
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(src)
|
||||
needed = []
|
||||
for n in tree.body:
|
||||
if isinstance(n, ast.FunctionDef) and n.name in (
|
||||
"classify_email_stage_failure",
|
||||
"is_fatal_register_error",
|
||||
"is_turnstile_headless_upgradeable",
|
||||
"headed_display_ready",
|
||||
):
|
||||
needed.append(n)
|
||||
if isinstance(n, ast.ImportFrom) and n.module and "fail_policy" in (n.module or ""):
|
||||
needed.insert(0, n)
|
||||
# Prefer importing is_fatal from module if present as local def; else stub.
|
||||
names = {n.name for n in needed if isinstance(n, ast.FunctionDef)}
|
||||
if "is_fatal_register_error" not in names:
|
||||
# inject stub then classify only
|
||||
ns: dict = {
|
||||
"is_fatal_register_error": lambda _m: False,
|
||||
}
|
||||
fn = next(
|
||||
n
|
||||
for n in tree.body
|
||||
if isinstance(n, ast.FunctionDef) and n.name == "classify_email_stage_failure"
|
||||
)
|
||||
mod = ast.Module(body=[fn], type_ignores=[])
|
||||
ast.fix_missing_locations(mod)
|
||||
exec(compile(mod, "<classify>", "exec"), ns)
|
||||
classify = ns["classify_email_stage_failure"]
|
||||
is_fatal = ns["is_fatal_register_error"]
|
||||
else:
|
||||
ns = {"os": os, "sys": sys}
|
||||
mod = ast.Module(body=needed, type_ignores=[])
|
||||
ast.fix_missing_locations(mod)
|
||||
exec(compile(mod, "<classify2>", "exec"), ns)
|
||||
classify = ns["classify_email_stage_failure"]
|
||||
is_fatal = ns["is_fatal_register_error"]
|
||||
|
||||
assert classify("browser_boot: chrome error page url=...") == "browser_boot"
|
||||
assert classify("The browser connection fails") == "browser_boot"
|
||||
assert classify("standalone chromium start failed after 3 attempts: x") == "browser_boot"
|
||||
assert classify("浏览器启动失败,已重试4次: x") == "browser_boot"
|
||||
# Dead Clash / proxy path (batch50 ordinary stall on accounts.x.ai)
|
||||
assert classify("net::ERR_CONNECTION_CLOSED") == "browser_boot"
|
||||
assert classify("ERR_CONNECTION_RESET at accounts.x.ai") == "browser_boot"
|
||||
assert classify("ERR_PROXY_CONNECTION_FAILED") == "browser_boot"
|
||||
assert classify("ERR_TUNNEL_CONNECTION_FAILED") == "browser_boot"
|
||||
assert classify("chrome-error://chromewebdata/") == "browser_boot"
|
||||
# Pre-email SPA stuck on「您正在登录」must recycle as browser_boot (slot retry).
|
||||
assert (
|
||||
classify(
|
||||
"browser_boot: signup_spa_stuck 邮箱注册按钮点击后停留在「您正在登录」"
|
||||
"中间态,邮箱表单未挂载"
|
||||
)
|
||||
== "browser_boot"
|
||||
)
|
||||
assert (
|
||||
classify(
|
||||
"browser_boot: signup_spa_stuck 未找到邮箱表单:页面停在「您正在登录」"
|
||||
"中间态(点击邮箱注册后未挂载输入框)"
|
||||
)
|
||||
== "browser_boot"
|
||||
)
|
||||
# Legacy plain-Exception wording (pre-fix) still classifies for safety.
|
||||
assert (
|
||||
classify("邮箱注册按钮点击后停留在「您正在登录」中间态,邮箱表单未挂载")
|
||||
== "browser_boot"
|
||||
)
|
||||
assert (
|
||||
classify(
|
||||
"未找到邮箱表单:页面停在「您正在登录」中间态(点击邮箱注册后未挂载输入框)"
|
||||
)
|
||||
== "browser_boot"
|
||||
)
|
||||
# Post-profile SSO mid-state wording must NOT be browser_boot (different path).
|
||||
assert (
|
||||
classify("final-page-no-submit:您正在登录 您正在登录 | 返回 返回")
|
||||
!= "browser_boot"
|
||||
)
|
||||
assert classify("未收到验证码") == "mail_miss"
|
||||
assert classify("未进入资料页") == "progress_fail"
|
||||
assert classify("未找到「使用邮箱注册」按钮或邮箱表单未出现") == "other"
|
||||
# DISPLAY-related messages must be fatal (not browser_boot retry spin)
|
||||
assert is_fatal("Turnstile headless 失败且无可用 DISPLAY/xvfb-run") is True
|
||||
assert is_fatal("headed 需要 DISPLAY/xvfb-run(当前 Linux DISPLAY 为空)") is True
|
||||
assert classify("Turnstile headless 失败且无可用 DISPLAY/xvfb-run") == "fatal"
|
||||
print("PASS classify browser_boot + signup_spa_stuck + DISPLAY fatal")
|
||||
|
||||
|
||||
def test_is_chrome_error_page_unit() -> None:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
# Import helpers by executing only the pure functions from ttk would pull heavy deps.
|
||||
# Instead, re-implement the url/title quick path tests via a minimal fake page
|
||||
# after importing from a stripped exec of the two functions.
|
||||
src = (ROOT / "grok_register_ttk.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(src)
|
||||
fns = []
|
||||
for n in tree.body:
|
||||
if isinstance(n, ast.FunctionDef) and n.name in (
|
||||
"is_chrome_error_page",
|
||||
"chrome_error_summary",
|
||||
):
|
||||
fns.append(n)
|
||||
assert len(fns) == 2
|
||||
mod = ast.Module(body=fns, type_ignores=[])
|
||||
ast.fix_missing_locations(mod)
|
||||
ns: dict = {}
|
||||
exec(compile(mod, "<chrome_err>", "exec"), ns)
|
||||
is_err = ns["is_chrome_error_page"]
|
||||
summary = ns["chrome_error_summary"]
|
||||
|
||||
class FakePage:
|
||||
def __init__(self, url="", title="", js_ret="ok", body=""):
|
||||
self.url = url
|
||||
self.title = title
|
||||
self._js = js_ret
|
||||
self._body = body
|
||||
|
||||
def run_js(self, _code):
|
||||
# summary path requests body slice; error probe returns _js
|
||||
if "innerText" in _code and "needles" not in _code and "main-frame-error" not in _code:
|
||||
return self._body
|
||||
return self._js
|
||||
|
||||
assert is_err(None) is False
|
||||
assert is_err(FakePage(url="https://accounts.x.ai/sign-up")) is False
|
||||
assert is_err(FakePage(url="chrome-error://chromewebdata/")) is True
|
||||
assert is_err(FakePage(url="https://x.com", title="This site can’t be reached")) is True
|
||||
assert is_err(FakePage(url="https://x.com", js_ret="error")) is True
|
||||
assert is_err(FakePage(url="https://x.com", js_ret="ok")) is False
|
||||
s = summary(FakePage(url="chrome-error://x", title="err", body="ERR_PROXY"))
|
||||
assert "chrome-error" in s
|
||||
print("PASS is_chrome_error_page unit")
|
||||
|
||||
|
||||
def test_create_standalone_retries_mocked() -> None:
|
||||
"""3 connection fails → BrowserConfirmError; orphan cleanup called."""
|
||||
sys.path.insert(0, str(ROOT))
|
||||
# Stub DrissionPage before import path uses it
|
||||
fake_dp = types.ModuleType("DrissionPage")
|
||||
|
||||
class BoomChromium:
|
||||
def __init__(self, _opts):
|
||||
raise RuntimeError("The browser connection fails")
|
||||
|
||||
class OkOpts:
|
||||
def set_argument(self, *_a, **_k):
|
||||
return None
|
||||
|
||||
def headless(self, *_a, **_k):
|
||||
return None
|
||||
|
||||
def auto_port(self):
|
||||
return None
|
||||
|
||||
def set_timeouts(self, **_k):
|
||||
return None
|
||||
|
||||
def set_browser_path(self, *_a):
|
||||
return None
|
||||
|
||||
def add_extension(self, *_a):
|
||||
return None
|
||||
|
||||
fake_dp.Chromium = BoomChromium
|
||||
fake_dp.ChromiumOptions = lambda: OkOpts()
|
||||
sys.modules["DrissionPage"] = fake_dp
|
||||
|
||||
# stub tab_pool cleanup + lock
|
||||
import tab_pool as tp
|
||||
|
||||
clean_calls: list[int] = []
|
||||
|
||||
def fake_clean(**_kwargs):
|
||||
clean_calls.append(1)
|
||||
return {"killed": 0, "matched": 0, "pids": [], "scanned": 0}
|
||||
|
||||
with mock.patch.object(tp, "cleanup_orphan_drission_chromes", side_effect=fake_clean):
|
||||
# force reimport of browser_confirm helpers
|
||||
if "cpa_xai.browser_confirm" in sys.modules:
|
||||
del sys.modules["cpa_xai.browser_confirm"]
|
||||
from cpa_xai.browser_confirm import BrowserConfirmError, create_standalone_page
|
||||
|
||||
logs: list[str] = []
|
||||
with mock.patch("cpa_xai.browser_confirm._sleep", return_value=None):
|
||||
try:
|
||||
create_standalone_page(
|
||||
proxy=None,
|
||||
headless=True,
|
||||
log=logs.append,
|
||||
max_attempts=3,
|
||||
)
|
||||
raise AssertionError("expected BrowserConfirmError")
|
||||
except BrowserConfirmError as e:
|
||||
assert "after 3 attempts" in str(e)
|
||||
assert "browser connection fails" in str(e).lower()
|
||||
# Pre-clean before first attempt + cleanup after each failed boot.
|
||||
assert len(clean_calls) >= 3
|
||||
assert any("start failed" in m for m in logs)
|
||||
print("PASS create_standalone mocked 3-retry + orphan")
|
||||
|
||||
|
||||
def test_create_standalone_succeeds_second_attempt() -> None:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
fake_dp = types.ModuleType("DrissionPage")
|
||||
state = {"n": 0}
|
||||
|
||||
class FlipChromium:
|
||||
def __init__(self, _opts):
|
||||
state["n"] += 1
|
||||
if state["n"] < 2:
|
||||
raise RuntimeError("The browser connection fails")
|
||||
self.process_id = 4242
|
||||
self.latest_tab = object()
|
||||
|
||||
def quit(self):
|
||||
return None
|
||||
|
||||
class OkOpts:
|
||||
def set_argument(self, *_a, **_k):
|
||||
return None
|
||||
|
||||
def headless(self, *_a, **_k):
|
||||
return None
|
||||
|
||||
def auto_port(self):
|
||||
return None
|
||||
|
||||
def set_timeouts(self, **_k):
|
||||
return None
|
||||
|
||||
def set_browser_path(self, *_a):
|
||||
return None
|
||||
|
||||
def add_extension(self, *_a):
|
||||
return None
|
||||
|
||||
fake_dp.Chromium = FlipChromium
|
||||
fake_dp.ChromiumOptions = lambda: OkOpts()
|
||||
sys.modules["DrissionPage"] = fake_dp
|
||||
|
||||
if "cpa_xai.browser_confirm" in sys.modules:
|
||||
del sys.modules["cpa_xai.browser_confirm"]
|
||||
from cpa_xai import browser_confirm as bc
|
||||
|
||||
with mock.patch.object(bc, "_cleanup_orphans_best_effort"):
|
||||
with mock.patch.object(bc, "_sleep", return_value=None):
|
||||
# Avoid register options import complexity: force fallback options
|
||||
with mock.patch.object(bc, "_build_standalone_options", return_value=OkOpts()):
|
||||
with mock.patch.object(
|
||||
bc, "_resolve_standalone_chrome_proxy", return_value=("", None)
|
||||
):
|
||||
browser, page = bc.create_standalone_page(
|
||||
proxy=None, headless=True, log=lambda _m: None, max_attempts=3
|
||||
)
|
||||
assert state["n"] == 2
|
||||
assert browser is not None and page is not None
|
||||
print("PASS create_standalone succeeds on 2nd attempt")
|
||||
|
||||
|
||||
def test_create_standalone_headed_no_display_fail_fast() -> None:
|
||||
"""Headed mint with empty DISPLAY must raise immediately (no 3× spin)."""
|
||||
if sys.platform == "darwin" or sys.platform.startswith("win"):
|
||||
# macOS always has display_available=True — skip behavior test, check source only
|
||||
src = (ROOT / "cpa_xai" / "browser_confirm.py").read_text(encoding="utf-8")
|
||||
assert "headed mint 需要 DISPLAY" in src
|
||||
print("PASS create_standalone headed DISPLAY fail-fast (source-only on macOS)")
|
||||
return
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
fake_dp = types.ModuleType("DrissionPage")
|
||||
|
||||
class NeverChromium:
|
||||
def __init__(self, _opts):
|
||||
raise AssertionError("Chromium must not start without DISPLAY")
|
||||
|
||||
class OkOpts:
|
||||
def set_argument(self, *_a, **_k):
|
||||
return None
|
||||
|
||||
def headless(self, *_a, **_k):
|
||||
return None
|
||||
|
||||
def auto_port(self):
|
||||
return None
|
||||
|
||||
def set_timeouts(self, **_k):
|
||||
return None
|
||||
|
||||
def set_browser_path(self, *_a):
|
||||
return None
|
||||
|
||||
def add_extension(self, *_a):
|
||||
return None
|
||||
|
||||
fake_dp.Chromium = NeverChromium
|
||||
fake_dp.ChromiumOptions = lambda: OkOpts()
|
||||
sys.modules["DrissionPage"] = fake_dp
|
||||
|
||||
if "cpa_xai.browser_confirm" in sys.modules:
|
||||
del sys.modules["cpa_xai.browser_confirm"]
|
||||
from cpa_xai.browser_confirm import BrowserConfirmError, create_standalone_page
|
||||
|
||||
logs: list[str] = []
|
||||
with mock.patch.dict(os.environ, {"DISPLAY": ""}, clear=False):
|
||||
os.environ.pop("DISPLAY", None)
|
||||
with mock.patch("cpa_xai.browser_confirm._sleep", return_value=None) as sleep_m:
|
||||
try:
|
||||
create_standalone_page(
|
||||
proxy=None,
|
||||
headless=False,
|
||||
log=logs.append,
|
||||
max_attempts=3,
|
||||
)
|
||||
raise AssertionError("expected BrowserConfirmError for empty DISPLAY")
|
||||
except BrowserConfirmError as e:
|
||||
assert "DISPLAY" in str(e) or "xvfb" in str(e).lower()
|
||||
assert sleep_m.call_count == 0
|
||||
print("PASS create_standalone headed no-DISPLAY fail-fast")
|
||||
|
||||
|
||||
def test_headed_display_ready_unit() -> None:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(src)
|
||||
fn = next(
|
||||
n
|
||||
for n in tree.body
|
||||
if isinstance(n, ast.FunctionDef) and n.name == "headed_display_ready"
|
||||
)
|
||||
ns: dict = {"os": os, "sys": sys}
|
||||
mod = ast.Module(body=[fn], type_ignores=[])
|
||||
ast.fix_missing_locations(mod)
|
||||
exec(compile(mod, "<hdr>", "exec"), ns)
|
||||
ready = ns["headed_display_ready"]
|
||||
with mock.patch("tab_pool.display_available", return_value=False):
|
||||
assert ready() is False
|
||||
with mock.patch("tab_pool.display_available", return_value=True):
|
||||
assert ready() is True
|
||||
print("PASS headed_display_ready unit")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
test_tab_pool_chromium_start_lock_source()
|
||||
test_remote_allow_origins_in_slim_flags()
|
||||
test_display_available_unit()
|
||||
test_create_standalone_retries_and_lock()
|
||||
test_hard_recycle_cleans_orphans()
|
||||
test_launch_supervisor_wires_fingerprint_default_off()
|
||||
test_start_browser_cleans_orphans_on_fail()
|
||||
test_signup_spa_stuck_raises_account_retry()
|
||||
test_classify_email_stage_browser_boot()
|
||||
test_is_chrome_error_page_unit()
|
||||
test_create_standalone_retries_mocked()
|
||||
test_create_standalone_succeeds_second_attempt()
|
||||
test_create_standalone_headed_no_display_fail_fast()
|
||||
test_headed_display_ready_unit()
|
||||
print("\nALL PASS (browser reliability)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Static gate: Grok bulk supervisor is intentional disk-first authority.
|
||||
|
||||
Bulk path = scripts/launch_batch_supervisor.sh → register_cli (concurrent chunk).
|
||||
Must NOT route through register_core serial shell-out; must freeze:
|
||||
CPA_EXPORT_ENABLED=true / CPA_PROBE_CHAT=false / CPA_REMOTE_INJECT=false
|
||||
during mint. Optional batch-end inject is a *post-target* unified import only.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SUP = ROOT / "scripts" / "launch_batch_supervisor.sh"
|
||||
IMPORT = ROOT / "scripts" / "import_cpa_auth_dir.py"
|
||||
|
||||
|
||||
class TestBulkSupervisorDiskFirst(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.assertTrue(SUP.is_file(), f"missing {SUP}")
|
||||
self.src = SUP.read_text(encoding="utf-8")
|
||||
|
||||
def test_disk_first_env_frozen(self) -> None:
|
||||
# Force product boundary: mint write only, no chat probe, no inject.
|
||||
self.assertIn("CPA_EXPORT_ENABLED=true", self.src)
|
||||
self.assertIn("CPA_PROBE_CHAT=false", self.src)
|
||||
self.assertIn("CPA_REMOTE_INJECT=false", self.src)
|
||||
# Criterion documented in script header/log
|
||||
self.assertIn("complete", self.src.lower())
|
||||
self.assertIn("refresh", self.src.lower())
|
||||
|
||||
def test_ordinary_node_score_env_default_on(self) -> None:
|
||||
# Dynamic weight is env-gated; ordinary bulk defaults NODE_SCORE=1.
|
||||
self.assertIn("NODE_SCORE=${NODE_SCORE:-1}", self.src)
|
||||
self.assertIn("node_score", self.src)
|
||||
# Off must remain possible without code change.
|
||||
self.assertIn("NODE_SCORE=0", self.src)
|
||||
|
||||
def test_calls_register_cli_not_register_core(self) -> None:
|
||||
# Concurrent bulk authority: direct register_cli with --extra chunk.
|
||||
self.assertIn("register_cli.py", self.src)
|
||||
self.assertIn("--extra", self.src)
|
||||
# Must not silently migrate bulk onto serial register_core.
|
||||
self.assertNotIn("register_core run", self.src)
|
||||
self.assertNotIn("run-register-core.sh", self.src)
|
||||
|
||||
def test_success_criterion_is_disk_not_chat(self) -> None:
|
||||
# Log line / comment must state disk success, not chat_ok product.
|
||||
self.assertRegex(
|
||||
self.src,
|
||||
r"success criterion:.*complete xai-.*refresh",
|
||||
)
|
||||
self.assertIn("not chat_ok", self.src)
|
||||
|
||||
def test_batch_end_import_only_after_target(self) -> None:
|
||||
"""Inject intent ≠ per-account inject; only post-target unified import."""
|
||||
self.assertIn("BATCH_CPA_INJECT_INTENT", self.src)
|
||||
self.assertIn("run_batch_end_cpa_import", self.src)
|
||||
self.assertIn("import_cpa_auth_dir.py", self.src)
|
||||
self.assertIn("HIT_TARGET", self.src)
|
||||
# Mint loop must keep forcing inject false (not honor config mid-batch).
|
||||
self.assertIn("export CPA_REMOTE_INJECT=false", self.src)
|
||||
# Import gated on target reached + intent.
|
||||
self.assertIn("target_reached", self.src)
|
||||
self.assertIn('HIT_TARGET == 1', self.src)
|
||||
# Soft: import fail must not kill disk product.
|
||||
self.assertIn("soft", self.src.lower())
|
||||
# Batch-of-5 default for Clash-friendly import.
|
||||
self.assertIn("CPA_BATCH_IMPORT_SIZE", self.src)
|
||||
self.assertIn("--batch-size", self.src)
|
||||
|
||||
def test_import_script_has_force_remote_flag(self) -> None:
|
||||
self.assertTrue(IMPORT.is_file(), f"missing {IMPORT}")
|
||||
src = IMPORT.read_text(encoding="utf-8")
|
||||
self.assertIn('--remote', src)
|
||||
self.assertIn("args.remote", src)
|
||||
# --remote must force inject even when config is false.
|
||||
self.assertIn("elif args.remote:", src)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,178 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unit tests: CFT149 + turnstilePatch leaves only service_worker → create page.
|
||||
|
||||
DrissionPage 4.1.x test_connect requires type in {page, webview}. With
|
||||
--load-extension=turnstilePatch, Chrome for Testing 149 often exposes only a
|
||||
chrome-extension service_worker in /json, so Chromium() times out even though
|
||||
DevTools is healthy. ensure_cdp_page_target + patch_drission_test_connect fix it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import types
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
import tab_pool as tp # noqa: E402
|
||||
|
||||
|
||||
def test_cdp_target_has_page() -> None:
|
||||
assert tp.cdp_target_has_page(None) is False
|
||||
assert tp.cdp_target_has_page([]) is False
|
||||
assert tp.cdp_target_has_page([{"type": "service_worker"}]) is False
|
||||
assert tp.cdp_target_has_page([{"type": "page", "url": "about:blank"}]) is True
|
||||
assert tp.cdp_target_has_page(
|
||||
[
|
||||
{"type": "service_worker", "url": "chrome-extension://x/sw.js"},
|
||||
{"type": "webview", "url": "about:blank"},
|
||||
]
|
||||
) is True
|
||||
print("PASS cdp_target_has_page")
|
||||
|
||||
|
||||
class _FakeResp:
|
||||
def __init__(self, body: bytes):
|
||||
self._body = body
|
||||
|
||||
def read(self) -> bytes:
|
||||
return self._body
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *args):
|
||||
return False
|
||||
|
||||
|
||||
def test_ensure_cdp_page_target_creates_when_only_sw() -> None:
|
||||
"""/json only service_worker → PUT /json/new → page appears."""
|
||||
state = {"n": 0}
|
||||
|
||||
def fake_urlopen(req, timeout=2): # noqa: ARG001
|
||||
url = getattr(req, "full_url", None) or getattr(req, "get_full_url", lambda: "")()
|
||||
method = getattr(req, "get_method", lambda: "GET")()
|
||||
state["n"] += 1
|
||||
if url.endswith("/json") and method == "GET":
|
||||
# first list: SW only; after PUT: page present
|
||||
if state.get("created"):
|
||||
body = json.dumps(
|
||||
[
|
||||
{"type": "page", "url": "about:blank"},
|
||||
{"type": "service_worker", "url": "chrome-extension://x/sw.js"},
|
||||
]
|
||||
).encode()
|
||||
else:
|
||||
body = json.dumps(
|
||||
[{"type": "service_worker", "url": "chrome-extension://x/sw.js"}]
|
||||
).encode()
|
||||
return _FakeResp(body)
|
||||
if "/json/new" in url:
|
||||
state["created"] = True
|
||||
body = json.dumps(
|
||||
{"type": "page", "url": "about:blank", "id": "ABC"}
|
||||
).encode()
|
||||
return _FakeResp(body)
|
||||
raise AssertionError(f"unexpected urlopen {method} {url}")
|
||||
|
||||
with mock.patch("urllib.request.urlopen", side_effect=fake_urlopen):
|
||||
ok = tp.ensure_cdp_page_target("127.0.0.1", 12345, timeout=1.0)
|
||||
assert ok is True
|
||||
assert state.get("created") is True
|
||||
print("PASS ensure_cdp_page_target creates page from SW-only")
|
||||
|
||||
|
||||
def test_ensure_cdp_page_target_noop_when_page_exists() -> None:
|
||||
calls: list[str] = []
|
||||
|
||||
def fake_urlopen(req, timeout=2): # noqa: ARG001
|
||||
url = getattr(req, "full_url", None) or getattr(req, "get_full_url", lambda: "")()
|
||||
calls.append(url)
|
||||
body = json.dumps([{"type": "page", "url": "chrome://newtab/"}]).encode()
|
||||
return _FakeResp(body)
|
||||
|
||||
with mock.patch("urllib.request.urlopen", side_effect=fake_urlopen):
|
||||
ok = tp.ensure_cdp_page_target("127.0.0.1", 9999, timeout=1.0)
|
||||
assert ok is True
|
||||
assert all("/json/new" not in u for u in calls)
|
||||
print("PASS ensure_cdp_page_target noop when page exists")
|
||||
|
||||
|
||||
def test_patch_drission_test_connect_wraps_once() -> None:
|
||||
# Build a fake DrissionPage._functions.browser module
|
||||
fake_mod = types.ModuleType("DrissionPage._functions.browser")
|
||||
|
||||
def original_test_connect(ip, port): # noqa: ARG001
|
||||
raise AssertionError("original test_connect must not be used after patch")
|
||||
|
||||
fake_mod.test_connect = original_test_connect # type: ignore[attr-defined]
|
||||
|
||||
# Reset module-level patch flag so this test can re-apply.
|
||||
tp._test_connect_patched = False
|
||||
|
||||
ensure_calls = {"n": 0}
|
||||
|
||||
def fake_ensure(ip, port, timeout=1.0): # noqa: ARG001
|
||||
ensure_calls["n"] += 1
|
||||
# Fail once (chrome not ready), then succeed (page created).
|
||||
return ensure_calls["n"] >= 2
|
||||
|
||||
settings_mod = types.ModuleType("DrissionPage._functions.settings")
|
||||
|
||||
class _S:
|
||||
browser_connect_timeout = 5
|
||||
|
||||
settings_mod.Settings = _S # type: ignore[attr-defined]
|
||||
|
||||
with mock.patch.dict(
|
||||
sys.modules,
|
||||
{
|
||||
"DrissionPage": types.ModuleType("DrissionPage"),
|
||||
"DrissionPage._functions": types.ModuleType("DrissionPage._functions"),
|
||||
"DrissionPage._functions.browser": fake_mod,
|
||||
"DrissionPage._functions.settings": settings_mod,
|
||||
},
|
||||
):
|
||||
sys.modules["DrissionPage"]._functions = sys.modules["DrissionPage._functions"] # type: ignore
|
||||
sys.modules["DrissionPage._functions"].browser = fake_mod # type: ignore
|
||||
sys.modules["DrissionPage._functions"].settings = settings_mod # type: ignore
|
||||
with mock.patch.object(tp, "ensure_cdp_page_target", side_effect=fake_ensure):
|
||||
with mock.patch.object(tp.time, "sleep", return_value=None):
|
||||
assert tp.patch_drission_test_connect() is True
|
||||
# second call idempotent
|
||||
assert tp.patch_drission_test_connect() is True
|
||||
wrapped = fake_mod.test_connect
|
||||
assert getattr(wrapped, "_grok_page_target_patch", False) is True
|
||||
assert getattr(wrapped, "_grok_page_target_original", None) is original_test_connect
|
||||
assert wrapped("127.0.0.1", 1) is True
|
||||
assert ensure_calls["n"] >= 2
|
||||
print("PASS patch_drission_test_connect replaces once")
|
||||
|
||||
|
||||
def test_create_browser_wires_patch() -> None:
|
||||
src = (ROOT / "tab_pool.py").read_text(encoding="utf-8")
|
||||
assert "patch_drission_test_connect()" in src
|
||||
assert "def ensure_cdp_page_target" in src
|
||||
assert "json/new" in src
|
||||
mint = (ROOT / "cpa_xai" / "browser_confirm.py").read_text(encoding="utf-8")
|
||||
assert "patch_drission_test_connect" in mint
|
||||
print("PASS create_browser / mint wire patch")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
test_cdp_target_has_page()
|
||||
test_ensure_cdp_page_target_creates_when_only_sw()
|
||||
test_ensure_cdp_page_target_noop_when_page_exists()
|
||||
test_patch_drission_test_connect_wraps_once()
|
||||
test_create_browser_wires_patch()
|
||||
print("ALL PASS test_cdp_page_target_patch")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env python3
|
||||
"""error_kind taxonomy constants + normalize (offline)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
|
||||
from register_core.contracts import ALLOWED_ERROR_KINDS, normalize_error_kind
|
||||
|
||||
|
||||
class TestErrorKinds(unittest.TestCase):
|
||||
def test_allowed_contains_public_taxonomy(self) -> None:
|
||||
for k in (
|
||||
"mail_miss",
|
||||
"registration_disallowed",
|
||||
"unsupported_email",
|
||||
"already_registered",
|
||||
"captcha",
|
||||
"session",
|
||||
"otp_invalid",
|
||||
"oauth_callback",
|
||||
"token",
|
||||
"proxy",
|
||||
"network",
|
||||
"provider",
|
||||
"verify",
|
||||
"fatal",
|
||||
"other",
|
||||
):
|
||||
self.assertIn(k, ALLOWED_ERROR_KINDS)
|
||||
|
||||
def test_normalize_keeps_known(self) -> None:
|
||||
self.assertEqual(normalize_error_kind("registration_disallowed"), "registration_disallowed")
|
||||
self.assertEqual(normalize_error_kind("mail_miss"), "mail_miss")
|
||||
self.assertEqual(normalize_error_kind("unsupported_email"), "unsupported_email")
|
||||
self.assertEqual(normalize_error_kind("already_registered"), "already_registered")
|
||||
self.assertEqual(normalize_error_kind("captcha"), "captcha")
|
||||
self.assertEqual(normalize_error_kind("session"), "session")
|
||||
self.assertEqual(normalize_error_kind("otp_invalid"), "otp_invalid")
|
||||
self.assertEqual(normalize_error_kind("oauth_callback"), "oauth_callback")
|
||||
self.assertEqual(normalize_error_kind("token"), "token")
|
||||
self.assertEqual(normalize_error_kind("proxy"), "proxy")
|
||||
self.assertEqual(normalize_error_kind("network"), "network")
|
||||
self.assertEqual(normalize_error_kind("fatal"), "fatal")
|
||||
|
||||
def test_normalize_unknown_to_provider(self) -> None:
|
||||
self.assertEqual(normalize_error_kind("weird_thing"), "provider")
|
||||
self.assertEqual(normalize_error_kind(""), "provider")
|
||||
self.assertEqual(normalize_error_kind(None), "provider") # type: ignore[arg-type]
|
||||
|
||||
def test_normalize_aliases(self) -> None:
|
||||
self.assertEqual(normalize_error_kind("disallowed"), "registration_disallowed")
|
||||
self.assertEqual(normalize_error_kind("Disallowed"), "registration_disallowed")
|
||||
self.assertEqual(normalize_error_kind("registration-disallowed"), "registration_disallowed")
|
||||
self.assertEqual(normalize_error_kind("sentinel"), "captcha")
|
||||
self.assertEqual(normalize_error_kind("sentinel_fail"), "captcha")
|
||||
self.assertEqual(normalize_error_kind("pow"), "captcha")
|
||||
self.assertEqual(normalize_error_kind("otp_bad"), "otp_invalid")
|
||||
self.assertEqual(normalize_error_kind("bad_otp"), "otp_invalid")
|
||||
self.assertEqual(normalize_error_kind("invalid_otp"), "otp_invalid")
|
||||
self.assertEqual(normalize_error_kind("oauth"), "oauth_callback")
|
||||
self.assertEqual(normalize_error_kind("callback"), "oauth_callback")
|
||||
self.assertEqual(normalize_error_kind("missing_oauth_callback"), "oauth_callback")
|
||||
self.assertEqual(normalize_error_kind("refresh"), "token")
|
||||
self.assertEqual(normalize_error_kind("missing_refresh"), "token")
|
||||
self.assertEqual(normalize_error_kind("missing_tokens"), "token")
|
||||
self.assertEqual(normalize_error_kind("oauth_token"), "token")
|
||||
|
||||
def test_normalize_prefix_compounds(self) -> None:
|
||||
self.assertEqual(normalize_error_kind("oauth_token_http_400"), "token")
|
||||
self.assertEqual(normalize_error_kind("missing_token_refresh"), "token")
|
||||
self.assertEqual(normalize_error_kind("sentinel_challenge_fail"), "captcha")
|
||||
self.assertEqual(normalize_error_kind("captcha:solve_timeout"), "captcha")
|
||||
self.assertEqual(normalize_error_kind("session_cookie_missing"), "session")
|
||||
self.assertEqual(normalize_error_kind("session_missing_cookie"), "session")
|
||||
self.assertEqual(normalize_error_kind("session_establish_failed"), "session")
|
||||
self.assertEqual(normalize_error_kind("session:cookie"), "session")
|
||||
self.assertEqual(normalize_error_kind("otp_invalid_http_400"), "otp_invalid")
|
||||
self.assertEqual(normalize_error_kind("registration_disallowed_http_400"), "registration_disallowed")
|
||||
self.assertEqual(normalize_error_kind("already_registered_409"), "already_registered")
|
||||
self.assertEqual(normalize_error_kind("unsupported_email_domain"), "unsupported_email")
|
||||
self.assertEqual(normalize_error_kind("oauth_callback_missing"), "oauth_callback")
|
||||
self.assertEqual(normalize_error_kind("mail_miss:timeout"), "mail_miss")
|
||||
|
||||
def test_normalize_network_beats_session_prefix(self) -> None:
|
||||
"""session_* must not swallow transport compounds into kind=session."""
|
||||
self.assertEqual(normalize_error_kind("session_timeout_network"), "network")
|
||||
self.assertEqual(normalize_error_kind("session_proxy_error"), "proxy")
|
||||
self.assertEqual(normalize_error_kind("session_connection_reset"), "network")
|
||||
# Bare session still product kind
|
||||
self.assertEqual(normalize_error_kind("session"), "session")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(unittest.main())
|
||||
@@ -0,0 +1,640 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline protocol step mapping + hard gates (no live OpenAI)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from providers.chatgpt.protocol.flow import (
|
||||
ChatGPTRegisterError,
|
||||
PlatformRegistrar,
|
||||
RegistrationResult,
|
||||
_is_transport_exception,
|
||||
_sentinel_soft_enabled,
|
||||
register_one,
|
||||
)
|
||||
|
||||
|
||||
class _Resp:
|
||||
def __init__(self, status: int, body: dict[str, Any] | None = None, headers: dict | None = None):
|
||||
self.status_code = status
|
||||
self._body = body or {}
|
||||
self.headers = headers or {}
|
||||
self.text = str(body or "")
|
||||
self.url = "https://auth.openai.com/test"
|
||||
|
||||
def json(self):
|
||||
return self._body
|
||||
|
||||
|
||||
class TestSentinelSoftFlag(unittest.TestCase):
|
||||
def test_default_hard(self) -> None:
|
||||
with patch.dict("os.environ", {"CHATGPT_SENTINEL_SOFT": "0"}, clear=False):
|
||||
self.assertFalse(_sentinel_soft_enabled())
|
||||
with patch.dict("os.environ", {}, clear=False):
|
||||
# Unset → hard
|
||||
import os
|
||||
|
||||
os.environ.pop("CHATGPT_SENTINEL_SOFT", None)
|
||||
self.assertFalse(_sentinel_soft_enabled())
|
||||
|
||||
def test_soft_opt_in(self) -> None:
|
||||
with patch.dict("os.environ", {"CHATGPT_SENTINEL_SOFT": "1"}, clear=False):
|
||||
self.assertTrue(_sentinel_soft_enabled())
|
||||
with patch.dict("os.environ", {"CHATGPT_SENTINEL_SOFT": "soft"}, clear=False):
|
||||
self.assertTrue(_sentinel_soft_enabled())
|
||||
|
||||
|
||||
class TestSessionHardGate(unittest.TestCase):
|
||||
def test_missing_session_cookie_raises_session_kind(self) -> None:
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev-test"
|
||||
reg.state = "st"
|
||||
reg.last_authorize = {"final_url": "https://auth.openai.com/u/signup"}
|
||||
|
||||
with (
|
||||
patch.object(reg, "_ensure_sentinel", return_value="tok"),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.request_with_retry",
|
||||
return_value=(_Resp(200, {}), None),
|
||||
),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.cookie_get",
|
||||
return_value="",
|
||||
),
|
||||
):
|
||||
with self.assertRaises(ChatGPTRegisterError) as cm:
|
||||
reg.establish_session()
|
||||
self.assertEqual(cm.exception.kind, "session")
|
||||
self.assertEqual(cm.exception.step, "session")
|
||||
|
||||
def test_session_all_transport_fail_is_network(self) -> None:
|
||||
"""All candidate GETs return None → network, not product session."""
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev-test"
|
||||
reg.state = "st"
|
||||
reg.last_authorize = {"final_url": "https://auth.openai.com/u/signup"}
|
||||
|
||||
with (
|
||||
patch.object(reg, "_ensure_sentinel", return_value="tok"),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.request_with_retry",
|
||||
return_value=(None, "connection reset"),
|
||||
),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.cookie_get",
|
||||
return_value="",
|
||||
),
|
||||
):
|
||||
with self.assertRaises(ChatGPTRegisterError) as cm:
|
||||
reg.establish_session()
|
||||
self.assertEqual(cm.exception.kind, "network")
|
||||
self.assertEqual(cm.exception.step, "session")
|
||||
self.assertIn("transport", str(cm.exception))
|
||||
|
||||
def test_sentinel_hard_fail_on_accounts_headers(self) -> None:
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev-test"
|
||||
with (
|
||||
patch.dict("os.environ", {"CHATGPT_SENTINEL_SOFT": "0"}, clear=False),
|
||||
patch.object(
|
||||
reg,
|
||||
"_ensure_sentinel",
|
||||
side_effect=RuntimeError("pow_failed"),
|
||||
),
|
||||
):
|
||||
with self.assertRaises(ChatGPTRegisterError) as cm:
|
||||
reg._accounts_headers("https://auth.openai.com/x", "authorize_continue")
|
||||
self.assertEqual(cm.exception.kind, "captcha")
|
||||
self.assertIn("sentinel", cm.exception.step)
|
||||
|
||||
def test_is_transport_exception_classifies_network(self) -> None:
|
||||
"""Transport/proxy/timeout must not be mis-tagged as captcha."""
|
||||
self.assertTrue(_is_transport_exception(TimeoutError("timed out")))
|
||||
self.assertTrue(_is_transport_exception(OSError("connection reset")))
|
||||
self.assertTrue(_is_transport_exception(ConnectionError("proxy refused")))
|
||||
self.assertTrue(_is_transport_exception(RuntimeError("HTTPSConnectionPool timed out")))
|
||||
self.assertTrue(_is_transport_exception(RuntimeError("ProxyError: 407")))
|
||||
# genuine PoW/captcha failures stay non-transport
|
||||
self.assertFalse(_is_transport_exception(RuntimeError("pow_failed")))
|
||||
self.assertFalse(_is_transport_exception(RuntimeError("sentinel challenge")))
|
||||
self.assertFalse(_is_transport_exception(ValueError("bad token")))
|
||||
|
||||
def test_sentinel_transport_fail_is_network_not_captcha(self) -> None:
|
||||
"""Proxy/timeout on sentinel must hard-fail as network, not captcha."""
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev-test"
|
||||
with (
|
||||
patch.dict("os.environ", {"CHATGPT_SENTINEL_SOFT": "0"}, clear=False),
|
||||
patch.object(
|
||||
reg,
|
||||
"_ensure_sentinel",
|
||||
side_effect=TimeoutError("proxy timed out"),
|
||||
),
|
||||
):
|
||||
with self.assertRaises(ChatGPTRegisterError) as cm:
|
||||
reg._accounts_headers("https://auth.openai.com/x", "authorize_continue")
|
||||
self.assertEqual(cm.exception.kind, "network")
|
||||
self.assertIn("sentinel_transport", str(cm.exception))
|
||||
|
||||
def test_sentinel_soft_continues(self) -> None:
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev-test"
|
||||
with (
|
||||
patch.dict("os.environ", {"CHATGPT_SENTINEL_SOFT": "1"}, clear=False),
|
||||
patch.object(
|
||||
reg,
|
||||
"_ensure_sentinel",
|
||||
side_effect=RuntimeError("pow_failed"),
|
||||
),
|
||||
):
|
||||
headers = reg._accounts_headers(
|
||||
"https://auth.openai.com/x", "authorize_continue"
|
||||
)
|
||||
self.assertIn("x-openai-sentinel-error", headers)
|
||||
self.assertNotIn("openai-sentinel-token", headers)
|
||||
|
||||
|
||||
class TestStepKinds(unittest.TestCase):
|
||||
def test_register_user_409_is_already_registered(self) -> None:
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev"
|
||||
with (
|
||||
patch.object(reg, "_accounts_headers", return_value={}),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.request_with_retry",
|
||||
return_value=(_Resp(409, {"error": "already exists"}), None),
|
||||
),
|
||||
):
|
||||
with self.assertRaises(ChatGPTRegisterError) as cm:
|
||||
reg.register_user("a@b.com", "Pw1!abcdef")
|
||||
self.assertEqual(cm.exception.kind, "already_registered")
|
||||
self.assertEqual(cm.exception.step, "register_user")
|
||||
|
||||
def test_register_user_bare_exists_not_already_registered(self) -> None:
|
||||
"""Loose 'exists'/'already' alone must not classify as identity collision."""
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev"
|
||||
with (
|
||||
patch.object(reg, "_accounts_headers", return_value={}),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.request_with_retry",
|
||||
return_value=(_Resp(400, {"error": "rate limit exists upstream"}), None),
|
||||
),
|
||||
):
|
||||
with self.assertRaises(ChatGPTRegisterError) as cm:
|
||||
reg.register_user("a@b.com", "Pw1!abcdef")
|
||||
self.assertEqual(cm.exception.kind, "provider")
|
||||
self.assertNotEqual(cm.exception.kind, "already_registered")
|
||||
|
||||
def test_register_user_transport_none_is_network(self) -> None:
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev"
|
||||
with (
|
||||
patch.object(reg, "_accounts_headers", return_value={}),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.request_with_retry",
|
||||
return_value=(None, "connection reset"),
|
||||
),
|
||||
):
|
||||
with self.assertRaises(ChatGPTRegisterError) as cm:
|
||||
reg.register_user("a@b.com", "Pw1!abcdef")
|
||||
self.assertEqual(cm.exception.kind, "network")
|
||||
self.assertEqual(cm.exception.step, "register_user")
|
||||
|
||||
def test_validate_otp_bad_is_otp_invalid(self) -> None:
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev"
|
||||
with (
|
||||
patch.object(reg, "_accounts_headers", return_value={}),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.request_with_retry",
|
||||
return_value=(_Resp(400, {"error": "invalid code"}), None),
|
||||
),
|
||||
):
|
||||
with self.assertRaises(ChatGPTRegisterError) as cm:
|
||||
reg.validate_otp("000000")
|
||||
self.assertEqual(cm.exception.kind, "otp_invalid")
|
||||
self.assertEqual(cm.exception.step, "validate_otp")
|
||||
|
||||
def test_validate_otp_captcha_body_is_captcha(self) -> None:
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev"
|
||||
with (
|
||||
patch.object(reg, "_accounts_headers", return_value={}),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.request_with_retry",
|
||||
return_value=(
|
||||
_Resp(403, {"error": {"code": "captcha_required", "message": "solve captcha"}}),
|
||||
None,
|
||||
),
|
||||
),
|
||||
):
|
||||
with self.assertRaises(ChatGPTRegisterError) as cm:
|
||||
reg.validate_otp("123456")
|
||||
self.assertEqual(cm.exception.kind, "captcha")
|
||||
self.assertEqual(cm.exception.step, "validate_otp")
|
||||
|
||||
def test_validate_otp_rate_limit_is_provider(self) -> None:
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev"
|
||||
with (
|
||||
patch.object(reg, "_accounts_headers", return_value={}),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.request_with_retry",
|
||||
return_value=(
|
||||
_Resp(429, {"error": {"message": "rate limit exceeded"}}),
|
||||
None,
|
||||
),
|
||||
),
|
||||
):
|
||||
with self.assertRaises(ChatGPTRegisterError) as cm:
|
||||
reg.validate_otp("123456")
|
||||
self.assertEqual(cm.exception.kind, "provider")
|
||||
self.assertEqual(cm.exception.step, "validate_otp")
|
||||
|
||||
def test_validate_otp_transport_is_network(self) -> None:
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev"
|
||||
with (
|
||||
patch.object(reg, "_accounts_headers", return_value={}),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.request_with_retry",
|
||||
return_value=(None, "proxy timeout"),
|
||||
),
|
||||
):
|
||||
with self.assertRaises(ChatGPTRegisterError) as cm:
|
||||
reg.validate_otp("123456")
|
||||
self.assertEqual(cm.exception.kind, "network")
|
||||
self.assertEqual(cm.exception.step, "validate_otp")
|
||||
|
||||
def test_validate_otp_5xx_is_network(self) -> None:
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev"
|
||||
with (
|
||||
patch.object(reg, "_accounts_headers", return_value={}),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.request_with_retry",
|
||||
return_value=(_Resp(502, {"error": "bad gateway"}), None),
|
||||
),
|
||||
):
|
||||
with self.assertRaises(ChatGPTRegisterError) as cm:
|
||||
reg.validate_otp("123456")
|
||||
self.assertEqual(cm.exception.kind, "network")
|
||||
|
||||
def test_authorize_transport_is_network(self) -> None:
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev"
|
||||
with patch(
|
||||
"providers.chatgpt.protocol.flow.request_with_retry",
|
||||
return_value=(None, "connect timeout"),
|
||||
):
|
||||
with self.assertRaises(ChatGPTRegisterError) as cm:
|
||||
reg.start_authorize("a@b.com")
|
||||
self.assertEqual(cm.exception.kind, "network")
|
||||
self.assertEqual(cm.exception.step, "authorize")
|
||||
|
||||
def test_authorize_http_4xx_is_provider(self) -> None:
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev"
|
||||
with patch(
|
||||
"providers.chatgpt.protocol.flow.request_with_retry",
|
||||
return_value=(_Resp(403, {"error": "forbidden"}), None),
|
||||
):
|
||||
with self.assertRaises(ChatGPTRegisterError) as cm:
|
||||
reg.start_authorize("a@b.com")
|
||||
self.assertEqual(cm.exception.kind, "provider")
|
||||
self.assertEqual(cm.exception.step, "authorize")
|
||||
|
||||
def test_authorize_http_5xx_is_network(self) -> None:
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev"
|
||||
with patch(
|
||||
"providers.chatgpt.protocol.flow.request_with_retry",
|
||||
return_value=(_Resp(502, {"error": "bad gateway"}), None),
|
||||
):
|
||||
with self.assertRaises(ChatGPTRegisterError) as cm:
|
||||
reg.start_authorize("a@b.com")
|
||||
self.assertEqual(cm.exception.kind, "network")
|
||||
self.assertEqual(cm.exception.step, "authorize")
|
||||
|
||||
def test_send_otp_transport_is_network(self) -> None:
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev"
|
||||
with patch(
|
||||
"providers.chatgpt.protocol.flow.request_with_retry",
|
||||
return_value=(None, "empty response"),
|
||||
):
|
||||
with self.assertRaises(ChatGPTRegisterError) as cm:
|
||||
reg.send_otp()
|
||||
self.assertEqual(cm.exception.kind, "network")
|
||||
self.assertEqual(cm.exception.step, "send_otp")
|
||||
|
||||
def test_create_account_transport_is_network(self) -> None:
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev"
|
||||
seq = [
|
||||
(_Resp(200, {}), None), # about-you GET
|
||||
(None, "connection refused"), # create_account POST
|
||||
]
|
||||
|
||||
def _req(*_a, **_k):
|
||||
return seq.pop(0)
|
||||
|
||||
with (
|
||||
patch.object(reg, "_accounts_headers", return_value={}),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.request_with_retry",
|
||||
side_effect=_req,
|
||||
),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.response_json",
|
||||
side_effect=lambda r: getattr(r, "_body", {}) if r is not None else {},
|
||||
),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow._human_pause",
|
||||
return_value=0.0,
|
||||
),
|
||||
patch.dict("os.environ", {"CHATGPT_HUMAN_PACE": "0"}, clear=False),
|
||||
):
|
||||
with self.assertRaises(ChatGPTRegisterError) as cm:
|
||||
reg.create_account("Test User", "1990-01-01")
|
||||
self.assertEqual(cm.exception.kind, "network")
|
||||
self.assertEqual(cm.exception.step, "create_account")
|
||||
|
||||
def test_create_account_disallowed(self) -> None:
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev"
|
||||
# First call = GET about-you (200); second = POST create_account (400).
|
||||
seq = [
|
||||
(_Resp(200, {}), None),
|
||||
(_Resp(400, {"error": {"code": "registration_disallowed"}}), None),
|
||||
]
|
||||
|
||||
def _req(*_a, **_k):
|
||||
return seq.pop(0)
|
||||
|
||||
with (
|
||||
patch.object(reg, "_accounts_headers", return_value={}),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.request_with_retry",
|
||||
side_effect=_req,
|
||||
),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.response_json",
|
||||
side_effect=lambda r: getattr(r, "_body", {}) if r is not None else {},
|
||||
),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow._human_pause",
|
||||
return_value=0.0,
|
||||
),
|
||||
patch.dict("os.environ", {"CHATGPT_HUMAN_PACE": "0"}, clear=False),
|
||||
):
|
||||
with self.assertRaises(ChatGPTRegisterError) as cm:
|
||||
reg.create_account("Test User", "1990-01-01")
|
||||
self.assertEqual(cm.exception.kind, "registration_disallowed")
|
||||
self.assertEqual(cm.exception.step, "create_account")
|
||||
|
||||
def test_exchange_tokens_missing_callback(self) -> None:
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev"
|
||||
reg.code_verifier = "v" * 43
|
||||
with patch.object(reg, "_follow_consent_for_code", return_value=None):
|
||||
result = reg.exchange_tokens("")
|
||||
self.assertFalse(result.ok)
|
||||
self.assertEqual(result.error_kind, "oauth_callback")
|
||||
self.assertEqual(result.fail_step, "oauth_callback")
|
||||
self.assertIn("oauth_callback", result.steps)
|
||||
|
||||
def test_exchange_tokens_consent_transport_is_network(self) -> None:
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev"
|
||||
reg.code_verifier = "v" * 43
|
||||
with patch.object(
|
||||
reg,
|
||||
"_follow_consent_for_code",
|
||||
side_effect=ChatGPTRegisterError(
|
||||
"consent_transport:connection reset",
|
||||
kind="network",
|
||||
step="oauth_callback",
|
||||
),
|
||||
):
|
||||
result = reg.exchange_tokens(
|
||||
"https://auth.openai.com/api/accounts/consent?continue=x"
|
||||
)
|
||||
self.assertFalse(result.ok)
|
||||
self.assertEqual(result.error_kind, "network")
|
||||
self.assertEqual(result.fail_step, "oauth_callback")
|
||||
self.assertIn("oauth_callback", result.steps)
|
||||
|
||||
def test_follow_consent_first_get_none_is_network(self) -> None:
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev"
|
||||
with patch(
|
||||
"providers.chatgpt.protocol.flow.request_with_retry",
|
||||
return_value=(None, "proxy timeout"),
|
||||
):
|
||||
with self.assertRaises(ChatGPTRegisterError) as cm:
|
||||
reg._follow_consent_for_code(
|
||||
"https://auth.openai.com/api/accounts/consent?continue=x"
|
||||
)
|
||||
self.assertEqual(cm.exception.kind, "network")
|
||||
self.assertEqual(cm.exception.step, "oauth_callback")
|
||||
|
||||
def test_exchange_tokens_http_error_is_token(self) -> None:
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev"
|
||||
reg.code_verifier = "v" * 43
|
||||
fake_session = MagicMock()
|
||||
with (
|
||||
patch.object(
|
||||
reg, "_follow_consent_for_code", return_value={"code": "abc"}
|
||||
),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.create_session",
|
||||
return_value=fake_session,
|
||||
),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.request_with_retry",
|
||||
return_value=(_Resp(400, {"error": "bad"}), None),
|
||||
),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.response_json",
|
||||
return_value={"error": "bad"},
|
||||
),
|
||||
):
|
||||
result = reg.exchange_tokens("https://platform.openai.com/auth/callback?code=x")
|
||||
self.assertFalse(result.ok)
|
||||
self.assertEqual(result.error_kind, "token")
|
||||
self.assertEqual(result.fail_step, "token")
|
||||
self.assertIn("token", result.steps)
|
||||
self.assertIn("oauth_callback", result.steps)
|
||||
|
||||
def test_exchange_tokens_transport_none_is_network(self) -> None:
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev"
|
||||
reg.code_verifier = "v" * 43
|
||||
fake_session = MagicMock()
|
||||
with (
|
||||
patch.object(
|
||||
reg, "_follow_consent_for_code", return_value={"code": "abc"}
|
||||
),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.create_session",
|
||||
return_value=fake_session,
|
||||
),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.request_with_retry",
|
||||
return_value=(None, "connection aborted"),
|
||||
),
|
||||
):
|
||||
result = reg.exchange_tokens(
|
||||
"https://platform.openai.com/auth/callback?code=x"
|
||||
)
|
||||
self.assertFalse(result.ok)
|
||||
self.assertEqual(result.error_kind, "network")
|
||||
self.assertEqual(result.fail_step, "token")
|
||||
|
||||
def test_exchange_tokens_5xx_is_network(self) -> None:
|
||||
reg = PlatformRegistrar(proxy="", log=lambda _m: None)
|
||||
reg.device_id = "dev"
|
||||
reg.code_verifier = "v" * 43
|
||||
fake_session = MagicMock()
|
||||
with (
|
||||
patch.object(
|
||||
reg, "_follow_consent_for_code", return_value={"code": "abc"}
|
||||
),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.create_session",
|
||||
return_value=fake_session,
|
||||
),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.request_with_retry",
|
||||
return_value=(_Resp(503, {"error": "unavailable"}), None),
|
||||
),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.response_json",
|
||||
return_value={"error": "unavailable"},
|
||||
),
|
||||
):
|
||||
result = reg.exchange_tokens(
|
||||
"https://platform.openai.com/auth/callback?code=x"
|
||||
)
|
||||
self.assertFalse(result.ok)
|
||||
self.assertEqual(result.error_kind, "network")
|
||||
|
||||
|
||||
class TestRegisterOnePartialSteps(unittest.TestCase):
|
||||
def test_mail_miss_attaches_partial_steps(self) -> None:
|
||||
"""otp miss after successful early steps carries ledger on exception."""
|
||||
|
||||
class _FakeReg:
|
||||
device_id = "dev"
|
||||
|
||||
def __init__(self, *a, **k):
|
||||
pass
|
||||
|
||||
def start_authorize(self, email):
|
||||
return {"status": 200, "final_url": "https://auth.openai.com/u/signup"}
|
||||
|
||||
def establish_session(self):
|
||||
return {"ok": True}
|
||||
|
||||
def register_user(self, email, password):
|
||||
return {"status": 200}
|
||||
|
||||
def send_otp(self):
|
||||
return {"status": 200}
|
||||
|
||||
def close(self):
|
||||
return None
|
||||
|
||||
with (
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.PlatformRegistrar",
|
||||
_FakeReg,
|
||||
),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow._human_pause",
|
||||
return_value=0.0,
|
||||
),
|
||||
patch.dict("os.environ", {"CHATGPT_HUMAN_PACE": "0"}, clear=False),
|
||||
):
|
||||
def otp_provider():
|
||||
raise TimeoutError("no mail")
|
||||
|
||||
with self.assertRaises(ChatGPTRegisterError) as cm:
|
||||
register_one(
|
||||
email="a@b.com",
|
||||
password="Pw1!abcdef12",
|
||||
proxy="",
|
||||
otp_provider=otp_provider,
|
||||
log=lambda _m: None,
|
||||
)
|
||||
self.assertEqual(cm.exception.kind, "mail_miss")
|
||||
self.assertEqual(cm.exception.step, "otp_wait")
|
||||
self.assertIn("authorize", cm.exception.steps)
|
||||
self.assertIn("send_otp", cm.exception.steps)
|
||||
|
||||
def test_session_fail_short_circuits(self) -> None:
|
||||
class _FakeReg:
|
||||
device_id = "dev"
|
||||
|
||||
def __init__(self, *a, **k):
|
||||
pass
|
||||
|
||||
def start_authorize(self, email):
|
||||
return {"status": 200, "final_url": "https://auth.openai.com/u/signup"}
|
||||
|
||||
def establish_session(self):
|
||||
raise ChatGPTRegisterError(
|
||||
"session_cookie_missing", kind="session", step="session"
|
||||
)
|
||||
|
||||
def close(self):
|
||||
return None
|
||||
|
||||
with (
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.PlatformRegistrar",
|
||||
_FakeReg,
|
||||
),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow._human_pause",
|
||||
return_value=0.0,
|
||||
),
|
||||
patch.dict("os.environ", {"CHATGPT_HUMAN_PACE": "0"}, clear=False),
|
||||
):
|
||||
with self.assertRaises(ChatGPTRegisterError) as cm:
|
||||
register_one(
|
||||
email="a@b.com",
|
||||
password="Pw1!abcdef12",
|
||||
proxy="",
|
||||
otp_provider=lambda: "123456",
|
||||
log=lambda _m: None,
|
||||
)
|
||||
self.assertEqual(cm.exception.kind, "session")
|
||||
self.assertEqual(cm.exception.step, "session")
|
||||
self.assertIn("authorize", cm.exception.steps)
|
||||
self.assertNotIn("register_user", cm.exception.steps)
|
||||
|
||||
|
||||
class TestRegistrationResultPublic(unittest.TestCase):
|
||||
def test_public_includes_fail_step(self) -> None:
|
||||
r = RegistrationResult(
|
||||
ok=False,
|
||||
error="missing_oauth_callback",
|
||||
error_kind="oauth_callback",
|
||||
fail_step="oauth_callback",
|
||||
steps={"oauth_callback": {"ok": False}},
|
||||
)
|
||||
pub = r.to_public_dict()
|
||||
self.assertEqual(pub["fail_step"], "oauth_callback")
|
||||
self.assertEqual(pub["error_kind"], "oauth_callback")
|
||||
self.assertIn("oauth_callback", pub["step_keys"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(unittest.main())
|
||||
@@ -0,0 +1,439 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline unit tests for ChatGPT provider (no live OpenAI register)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from unittest.mock import patch
|
||||
|
||||
from register_core.contracts import Mailbox, OtpCode, RegisterResult
|
||||
from register_core.errors import FailFastError, MailMissError
|
||||
from register_core.pipeline import Pipeline
|
||||
from register_core.providers.chatgpt_adapter import ChatGPTProvider
|
||||
from register_core.providers.registry import get_provider, list_providers
|
||||
from register_core.verify.chatgpt_token import ChatGPTTokenVerifier
|
||||
from register_core.verify.noop import NoopVerifier
|
||||
from register_core.verify.registry import get_verifier
|
||||
|
||||
|
||||
class FakeEmail:
|
||||
name = "fake"
|
||||
|
||||
def __init__(self, *, fail_otp: bool = False) -> None:
|
||||
self.fail_otp = fail_otp
|
||||
self.released: list[tuple[str, bool]] = []
|
||||
self.poll_kwargs: list[dict[str, Any]] = []
|
||||
self._codes = ["111111", "222222", "333333"]
|
||||
self._i = 0
|
||||
|
||||
def allocate(self) -> Mailbox:
|
||||
return Mailbox(
|
||||
address="newuser@example.com",
|
||||
token="t",
|
||||
provider=self.name,
|
||||
meta={"local": "newuser", "domain": "example.com"},
|
||||
)
|
||||
|
||||
def poll_otp(self, mailbox: Mailbox, **kwargs: Any) -> OtpCode:
|
||||
self.poll_kwargs.append(dict(kwargs))
|
||||
if self.fail_otp:
|
||||
raise MailMissError("otp timeout test")
|
||||
code = self._codes[min(self._i, len(self._codes) - 1)]
|
||||
self._i += 1
|
||||
return OtpCode(code=code, source=self.name)
|
||||
|
||||
def release(self, mailbox: Mailbox, *, success: bool) -> None:
|
||||
self.released.append((mailbox.address, success))
|
||||
|
||||
|
||||
class TestChatGPTRegistry(unittest.TestCase):
|
||||
def test_registered_and_aliases(self):
|
||||
self.assertIn("chatgpt", list_providers())
|
||||
p = get_provider("openai")
|
||||
self.assertEqual(p.name, "chatgpt")
|
||||
v = get_verifier("chatgpt")
|
||||
self.assertEqual(v.name, "chatgpt_token")
|
||||
|
||||
|
||||
class TestChatGPTVerifier(unittest.TestCase):
|
||||
def test_shape_gate(self):
|
||||
v = ChatGPTTokenVerifier(live=False)
|
||||
bad = v.verify(RegisterResult(ok=True, provider="chatgpt", secret="short"))
|
||||
self.assertFalse(bad.ok)
|
||||
good = v.verify(
|
||||
RegisterResult(
|
||||
ok=True,
|
||||
provider="chatgpt",
|
||||
secret="rt_" + "x" * 40,
|
||||
secret_kind="refresh_token",
|
||||
)
|
||||
)
|
||||
self.assertTrue(good.ok)
|
||||
# Live OpenAI opaque refresh: rt.1.<payload> (two dots, short first segment)
|
||||
modern_rt = v.verify(
|
||||
RegisterResult(
|
||||
ok=True,
|
||||
provider="chatgpt",
|
||||
secret="rt.1." + ("A" * 160),
|
||||
secret_kind="refresh_token",
|
||||
)
|
||||
)
|
||||
self.assertTrue(modern_rt.ok, modern_rt.detail)
|
||||
# Still reject clearly broken JWT-shaped secrets (not rt.*)
|
||||
malformed_jwt = v.verify(
|
||||
RegisterResult(
|
||||
ok=True,
|
||||
provider="chatgpt",
|
||||
secret="ab.cd." + ("e" * 40),
|
||||
secret_kind="access_token",
|
||||
)
|
||||
)
|
||||
self.assertFalse(malformed_jwt.ok)
|
||||
wrong_kind = v.verify(
|
||||
RegisterResult(
|
||||
ok=True,
|
||||
provider="chatgpt",
|
||||
secret="rt_" + "y" * 40,
|
||||
secret_kind="api_key",
|
||||
)
|
||||
)
|
||||
self.assertFalse(wrong_kind.ok)
|
||||
|
||||
|
||||
class TestChatGPTProtocolHelpers(unittest.TestCase):
|
||||
def test_pkce_and_sentinel_pow_offline(self):
|
||||
from providers.chatgpt.protocol.flow import _generate_pkce
|
||||
from providers.chatgpt.protocol.sentinel import SentinelTokenGenerator
|
||||
|
||||
verifier, challenge = _generate_pkce()
|
||||
self.assertGreater(len(verifier), 20)
|
||||
self.assertGreater(len(challenge), 20)
|
||||
self.assertNotEqual(verifier, challenge)
|
||||
|
||||
gen = SentinelTokenGenerator("device-test")
|
||||
req = gen.generate_requirements_token()
|
||||
self.assertTrue(req.startswith("gAAAAAC"))
|
||||
# difficulty "f" is easy — should solve quickly
|
||||
tok = gen.generate_token("seed", "f")
|
||||
self.assertTrue(tok.startswith("gAAAAAB"))
|
||||
|
||||
def test_registration_result_public_redacts(self):
|
||||
from providers.chatgpt.protocol.flow import RegistrationResult
|
||||
|
||||
r = RegistrationResult(
|
||||
ok=True,
|
||||
email="e@x.com",
|
||||
password="SuperSecretPass1!",
|
||||
access_token="sk-access-abcdefghijklmnopqrstuvwxyz",
|
||||
refresh_token="rt-refresh-abcdefghijklmnopqrstuvwxyz",
|
||||
id_token="id.token.value.here",
|
||||
)
|
||||
pub = r.to_public_dict()
|
||||
blob = json.dumps(pub)
|
||||
self.assertNotIn("SuperSecretPass1!", blob)
|
||||
self.assertNotIn("sk-access-abcdefghijklmnopqrstuvwxyz", blob)
|
||||
self.assertNotIn("rt-refresh-abcdefghijklmnopqrstuvwxyz", blob)
|
||||
|
||||
def test_human_pause_off_is_noop(self):
|
||||
from providers.chatgpt.protocol.flow import _human_pause
|
||||
|
||||
logs: list[str] = []
|
||||
with patch.dict(
|
||||
"os.environ",
|
||||
{"CHATGPT_HUMAN_PACE": "0"},
|
||||
clear=False,
|
||||
), patch("providers.chatgpt.protocol.flow.time.sleep") as sleep:
|
||||
waited = _human_pause(logs.append, label="unit")
|
||||
self.assertEqual(waited, 0.0)
|
||||
sleep.assert_not_called()
|
||||
self.assertEqual(logs, [])
|
||||
|
||||
def test_human_pause_default_jitter_range(self):
|
||||
from providers.chatgpt.protocol.flow import _human_pause
|
||||
|
||||
logs: list[str] = []
|
||||
with patch.dict(
|
||||
"os.environ",
|
||||
{
|
||||
"CHATGPT_HUMAN_PACE": "1",
|
||||
"CHATGPT_STEP_DELAY_S": "10",
|
||||
"CHATGPT_STEP_JITTER_S": "1",
|
||||
},
|
||||
clear=False,
|
||||
), patch(
|
||||
"providers.chatgpt.protocol.flow.random.uniform", return_value=10.4
|
||||
) as uniform, patch(
|
||||
"providers.chatgpt.protocol.flow.time.sleep"
|
||||
) as sleep:
|
||||
waited = _human_pause(logs.append, label="after_authorize")
|
||||
self.assertEqual(waited, 10.4)
|
||||
uniform.assert_called_once_with(9.0, 11.0)
|
||||
sleep.assert_called_once_with(10.4)
|
||||
self.assertTrue(any("human_pace" in x and "after_authorize" in x for x in logs))
|
||||
|
||||
|
||||
class TestChatGPTAdapterUsedCodes(unittest.TestCase):
|
||||
def test_otp_provider_accumulates_used_codes_across_polls(self):
|
||||
"""Resend path must pass previously returned codes as used_codes."""
|
||||
email = FakeEmail()
|
||||
provider = ChatGPTProvider(proxy="")
|
||||
captured: list[Any] = []
|
||||
|
||||
def fake_register_one(**kwargs: Any):
|
||||
otp_fn = kwargs.get("otp_provider")
|
||||
assert callable(otp_fn)
|
||||
c1 = otp_fn()
|
||||
c2 = otp_fn()
|
||||
captured.extend([c1, c2])
|
||||
from providers.chatgpt.protocol.flow import RegistrationResult
|
||||
|
||||
return RegistrationResult(
|
||||
ok=True,
|
||||
email="newuser@example.com",
|
||||
password="Pw1!abcdef",
|
||||
access_token="a" * 48,
|
||||
refresh_token="r" * 48,
|
||||
id_token="h.p.s",
|
||||
device_id="dev",
|
||||
)
|
||||
|
||||
with patch(
|
||||
"providers.chatgpt.protocol.flow.register_one",
|
||||
side_effect=fake_register_one,
|
||||
):
|
||||
result = provider.register_one(email_source=email)
|
||||
self.assertTrue(result.ok)
|
||||
self.assertEqual(captured, ["111111", "222222"])
|
||||
self.assertEqual(len(email.poll_kwargs), 2)
|
||||
# first poll: empty used set → None or empty
|
||||
first_used = email.poll_kwargs[0].get("used_codes")
|
||||
self.assertTrue(first_used is None or first_used == set())
|
||||
# second poll must exclude first code
|
||||
second_used = email.poll_kwargs[1].get("used_codes")
|
||||
self.assertIsNotNone(second_used)
|
||||
self.assertIn("111111", second_used)
|
||||
|
||||
|
||||
class TestChatGPTAdapterAttribution(unittest.TestCase):
|
||||
def test_success_from_this_run_only(self):
|
||||
"""Historical accounts.jsonl must not make ok=True without protocol result."""
|
||||
email = FakeEmail()
|
||||
provider = ChatGPTProvider(proxy="")
|
||||
|
||||
from providers.chatgpt.protocol.flow import RegistrationResult
|
||||
|
||||
fake_ok = RegistrationResult(
|
||||
ok=True,
|
||||
email="newuser@example.com",
|
||||
password="Pw1!abcdef",
|
||||
access_token="a" * 48,
|
||||
refresh_token="r" * 48,
|
||||
id_token="h.p.s",
|
||||
device_id="dev",
|
||||
steps={"authorize": {}, "register_user": {}},
|
||||
)
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
out = Path(td)
|
||||
with patch(
|
||||
"register_core.providers.chatgpt_adapter.OUTPUT_DIR", out
|
||||
), patch(
|
||||
"providers.chatgpt.protocol.flow.register_one",
|
||||
return_value=fake_ok,
|
||||
):
|
||||
# Pre-seed historical ledger
|
||||
(out / "accounts.jsonl").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"ok": True,
|
||||
"email": "old@example.com",
|
||||
"refresh_token": "old-refresh-token-should-not-win",
|
||||
}
|
||||
)
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
result = provider.register_one(email_source=email)
|
||||
|
||||
self.assertTrue(result.ok)
|
||||
self.assertEqual(result.email, "newuser@example.com")
|
||||
self.assertEqual(result.secret, "r" * 48)
|
||||
self.assertEqual(result.secret_kind, "refresh_token")
|
||||
self.assertNotEqual(result.secret, "old-refresh-token-should-not-win")
|
||||
pub = result.to_public_dict()
|
||||
self.assertNotIn("r" * 48, json.dumps(pub))
|
||||
self.assertEqual(email.released, [("newuser@example.com", True)])
|
||||
|
||||
def test_missing_refresh_is_failure(self):
|
||||
email = FakeEmail()
|
||||
provider = ChatGPTProvider(proxy="")
|
||||
from providers.chatgpt.protocol.flow import RegistrationResult
|
||||
|
||||
fake = RegistrationResult(
|
||||
ok=True,
|
||||
email="newuser@example.com",
|
||||
access_token="a" * 48,
|
||||
refresh_token="",
|
||||
)
|
||||
with patch(
|
||||
"providers.chatgpt.protocol.flow.register_one", return_value=fake
|
||||
):
|
||||
result = provider.register_one(email_source=email)
|
||||
self.assertFalse(result.ok)
|
||||
self.assertEqual(result.error_kind, "token")
|
||||
self.assertEqual(result.artifacts.get("fail_step"), "token")
|
||||
self.assertEqual(email.released[-1][1], False)
|
||||
|
||||
def test_error_path_surfaces_steps_and_fail_step(self):
|
||||
email = FakeEmail()
|
||||
provider = ChatGPTProvider(proxy="")
|
||||
from providers.chatgpt.protocol.flow import ChatGPTRegisterError
|
||||
|
||||
with patch(
|
||||
"providers.chatgpt.protocol.flow.register_one",
|
||||
side_effect=ChatGPTRegisterError(
|
||||
"create_account_http_400:registration_disallowed",
|
||||
kind="registration_disallowed",
|
||||
step="create_account",
|
||||
steps={
|
||||
"authorize": {"status": 200},
|
||||
"session": {"ok": True},
|
||||
"register_user": {"status": 200},
|
||||
"send_otp": {"status": 200},
|
||||
"validate_otp": {"status": 200},
|
||||
},
|
||||
),
|
||||
):
|
||||
result = provider.register_one(email_source=email)
|
||||
self.assertFalse(result.ok)
|
||||
self.assertEqual(result.error_kind, "registration_disallowed")
|
||||
self.assertEqual(result.artifacts.get("fail_step"), "create_account")
|
||||
self.assertIsInstance(result.artifacts.get("steps"), dict)
|
||||
self.assertIn("validate_otp", result.artifacts["steps"])
|
||||
self.assertEqual(result.artifacts.get("protocol"), "openai_platform_oauth")
|
||||
# fail_step is create_account even when partial ledger stops before recording it
|
||||
self.assertEqual(result.artifacts.get("fail_step"), "create_account")
|
||||
self.assertIn("validate_otp", result.artifacts.get("step_keys", []))
|
||||
|
||||
def test_otp_invalid_kind_passthrough(self):
|
||||
email = FakeEmail()
|
||||
provider = ChatGPTProvider(proxy="")
|
||||
from providers.chatgpt.protocol.flow import ChatGPTRegisterError
|
||||
|
||||
with patch(
|
||||
"providers.chatgpt.protocol.flow.register_one",
|
||||
side_effect=ChatGPTRegisterError(
|
||||
"validate_otp_http_400:bad",
|
||||
kind="otp_invalid",
|
||||
step="validate_otp",
|
||||
steps={"send_otp": {"status": 200}},
|
||||
),
|
||||
):
|
||||
result = provider.register_one(email_source=email)
|
||||
self.assertFalse(result.ok)
|
||||
self.assertEqual(result.error_kind, "otp_invalid")
|
||||
self.assertEqual(result.artifacts.get("fail_step"), "validate_otp")
|
||||
|
||||
def test_mail_miss_returns_result_with_email(self):
|
||||
email = FakeEmail(fail_otp=True)
|
||||
provider = ChatGPTProvider(proxy="")
|
||||
from providers.chatgpt.protocol.flow import ChatGPTRegisterError
|
||||
|
||||
with patch(
|
||||
"providers.chatgpt.protocol.flow.register_one",
|
||||
side_effect=ChatGPTRegisterError("otp_wait:x", kind="mail_miss"),
|
||||
):
|
||||
result = provider.register_one(email_source=email)
|
||||
self.assertFalse(result.ok)
|
||||
self.assertEqual(result.error_kind, "mail_miss")
|
||||
self.assertEqual(result.email, "newuser@example.com")
|
||||
self.assertEqual(email.released[-1][1], False)
|
||||
|
||||
def test_pipeline_in_process_accepts_email_source(self):
|
||||
"""chatgpt is not black-box — Pipeline.from_job allows tinyhost."""
|
||||
from register_core.contracts import RegisterJob
|
||||
|
||||
# should not raise ValueError (unlike mimo)
|
||||
job = RegisterJob(provider="chatgpt", email_source="tinyhost", verify=False)
|
||||
# from_job will try to construct real tinyhost source — ok
|
||||
pipe = Pipeline.from_job(job)
|
||||
self.assertEqual(pipe.provider.name, "chatgpt")
|
||||
self.assertIsNotNone(pipe.email_source)
|
||||
|
||||
def test_fail_fast_empty_allocate(self):
|
||||
class EmptyMail:
|
||||
name = "empty"
|
||||
|
||||
def allocate(self) -> Mailbox:
|
||||
return Mailbox(address="", provider=self.name)
|
||||
|
||||
def poll_otp(self, mailbox, **kwargs):
|
||||
raise AssertionError("no")
|
||||
|
||||
def release(self, mailbox, *, success):
|
||||
return None
|
||||
|
||||
with self.assertRaises(FailFastError):
|
||||
ChatGPTProvider(proxy="").register_one(email_source=EmptyMail())
|
||||
|
||||
def test_pipeline_uses_this_run_result(self):
|
||||
email = FakeEmail()
|
||||
provider = ChatGPTProvider(proxy="")
|
||||
from providers.chatgpt.protocol.flow import RegistrationResult
|
||||
|
||||
fake_ok = RegistrationResult(
|
||||
ok=True,
|
||||
email="newuser@example.com",
|
||||
password="Pw1!abcdef",
|
||||
access_token="a" * 48,
|
||||
refresh_token="r" * 48,
|
||||
)
|
||||
|
||||
def _noop_preflight(extra, **_kw):
|
||||
base = dict(extra or {})
|
||||
base["_nodes_preflight_done"] = True
|
||||
base["_nodes_preflight"] = {"skipped": True, "reason": "test"}
|
||||
return base
|
||||
|
||||
def _noop_inject(extra, **_kw):
|
||||
return dict(extra or {})
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
with (
|
||||
patch(
|
||||
"register_core.providers.chatgpt_adapter.OUTPUT_DIR", Path(td)
|
||||
),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.register_one",
|
||||
return_value=fake_ok,
|
||||
),
|
||||
patch(
|
||||
"register_core.util.proxy.preflight_nodes_for_register",
|
||||
side_effect=_noop_preflight,
|
||||
),
|
||||
patch(
|
||||
"register_core.util.proxy.inject_attempt_proxy",
|
||||
side_effect=_noop_inject,
|
||||
),
|
||||
):
|
||||
pipe = Pipeline(
|
||||
provider,
|
||||
email_source=email,
|
||||
verifier=ChatGPTTokenVerifier(),
|
||||
fail_fast=True,
|
||||
)
|
||||
# direct + no preflight: offline unit must never probe nodes.json
|
||||
stats = pipe.run(
|
||||
1, extra={"egress": "direct", "nodes_preflight": False}
|
||||
)
|
||||
self.assertEqual(stats.ok, 1)
|
||||
self.assertEqual(stats.fail, 0)
|
||||
self.assertTrue(stats.results[0].ok)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,218 @@
|
||||
"""Accounts pool + ops selfcheck/cleanup for control plane."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
from apps.control_api.accounts_ops import delete_account, list_accounts
|
||||
from apps.control_api.system_ops import cleanup_orphans, selfcheck
|
||||
|
||||
|
||||
def _write_auth(d: Path, email: str, *, access: bool = True, refresh: bool = True) -> Path:
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
path = d / f"xai-{email}.json"
|
||||
data = {
|
||||
"email": email,
|
||||
"access_token": "at-xxx" if access else "",
|
||||
"refresh_token": "rt-yyy" if refresh else "",
|
||||
"priority": 1000,
|
||||
"auth_kind": "sso",
|
||||
}
|
||||
path.write_text(json.dumps(data), encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def _client(tmp_path, monkeypatch, **env):
|
||||
monkeypatch.setenv("REGISTER_PROJECT_ROOT", str(tmp_path))
|
||||
monkeypatch.setenv("CONTROL_API_SESSION_SECRET", "test-session-secret-32bytes-min!!")
|
||||
monkeypatch.setenv("CONTROL_API_PASSWORD_LOGIN", "1")
|
||||
monkeypatch.setenv("CONTROL_API_TOKEN", "secret-token")
|
||||
for k, v in env.items():
|
||||
if v is None:
|
||||
monkeypatch.delenv(k, raising=False)
|
||||
else:
|
||||
monkeypatch.setenv(k, v)
|
||||
from apps.control_api.settings import clear_settings_cache
|
||||
from apps.control_api.app import create_app
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
clear_settings_cache()
|
||||
return TestClient(create_app())
|
||||
|
||||
|
||||
def test_list_accounts_filter_and_paginate(tmp_path: Path):
|
||||
auths = tmp_path / "cpa_auths"
|
||||
_write_auth(auths, "a@ex.com", access=True, refresh=True)
|
||||
_write_auth(auths, "b@ex.com", access=True, refresh=False)
|
||||
_write_auth(auths, "c@other.com", access=True, refresh=True)
|
||||
|
||||
all_items = list_accounts(tmp_path, page_size=0)
|
||||
assert all_items["total"] == 3
|
||||
assert all_items["disk_complete"] == 2
|
||||
assert all_items["complete"] == 2
|
||||
|
||||
only_ok = list_accounts(tmp_path, complete="1", page_size=50)
|
||||
assert only_ok["total"] == 2
|
||||
assert all(it["complete"] for it in only_ok["items"])
|
||||
|
||||
only_bad = list_accounts(tmp_path, complete="0", page_size=50)
|
||||
assert only_bad["total"] == 1
|
||||
assert only_bad["items"][0]["email"] == "b@ex.com"
|
||||
|
||||
q = list_accounts(tmp_path, q="other", page_size=50)
|
||||
assert q["total"] == 1
|
||||
assert q["items"][0]["email"] == "c@other.com"
|
||||
|
||||
page1 = list_accounts(tmp_path, page=1, page_size=2)
|
||||
assert page1["page"] == 1
|
||||
assert page1["page_size"] == 2
|
||||
assert page1["pages"] == 2
|
||||
assert len(page1["items"]) == 2
|
||||
|
||||
|
||||
def test_delete_account_safe_name(tmp_path: Path):
|
||||
auths = tmp_path / "cpa_auths"
|
||||
path = _write_auth(auths, "del@ex.com")
|
||||
assert path.is_file()
|
||||
out = delete_account(tmp_path, "xai-del@ex.com.json")
|
||||
assert out["ok"] is True
|
||||
assert not path.exists()
|
||||
# Soft-delete: archived under cpa_auths/.trash/
|
||||
assert out.get("archived")
|
||||
archived = Path(out["archived_path"])
|
||||
assert archived.is_file()
|
||||
assert archived.parent.name == ".trash"
|
||||
assert archived.parent.parent == auths
|
||||
|
||||
with pytest.raises(FileNotFoundError):
|
||||
delete_account(tmp_path, "xai-missing@ex.com.json")
|
||||
|
||||
with pytest.raises(ValueError, match="invalid|must be"):
|
||||
delete_account(tmp_path, "../evil.json")
|
||||
|
||||
with pytest.raises(ValueError, match="must be"):
|
||||
delete_account(tmp_path, "not-xai.json")
|
||||
|
||||
|
||||
def test_list_accounts_summary_cache_skips_reread(tmp_path: Path, monkeypatch):
|
||||
auths = tmp_path / "cpa_auths"
|
||||
path = _write_auth(auths, "cache@ex.com")
|
||||
reads = {"n": 0}
|
||||
real_read = Path.read_text
|
||||
|
||||
def counting_read(self, *a, **k):
|
||||
if self == path:
|
||||
reads["n"] += 1
|
||||
return real_read(self, *a, **k)
|
||||
|
||||
monkeypatch.setattr(Path, "read_text", counting_read)
|
||||
list_accounts(tmp_path, page_size=50)
|
||||
list_accounts(tmp_path, page_size=50)
|
||||
# Second list should hit mtime cache, not re-read file body.
|
||||
assert reads["n"] == 1
|
||||
|
||||
|
||||
def test_selfcheck_missing_and_present(tmp_path: Path):
|
||||
out = selfcheck(tmp_path)
|
||||
assert "checks" in out
|
||||
assert "ok" in out
|
||||
names = {c["name"] for c in out["checks"]}
|
||||
assert "config.json" in names
|
||||
assert "cpa_auths" in names
|
||||
assert "register_cli.py" in names
|
||||
|
||||
(tmp_path / "config.json").write_text(
|
||||
json.dumps({"email_provider": "cloudflare", "defaultDomains": "a.com"}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
(tmp_path / "register_cli.py").write_text("# stub\n", encoding="utf-8")
|
||||
(tmp_path / "scripts").mkdir()
|
||||
(tmp_path / "scripts" / "launch_batch_supervisor.sh").write_text("#!/bin/bash\n", encoding="utf-8")
|
||||
(tmp_path / ".venv" / "bin").mkdir(parents=True)
|
||||
(tmp_path / ".venv" / "bin" / "python").write_text("#!/bin/sh\n", encoding="utf-8")
|
||||
_write_auth(tmp_path / "cpa_auths", "ok@ex.com")
|
||||
|
||||
out2 = selfcheck(tmp_path)
|
||||
by = {c["name"]: c for c in out2["checks"]}
|
||||
assert by["config.json"]["ok"] is True
|
||||
assert by["cpa_auths"]["ok"] is True
|
||||
assert by["register_cli.py"]["ok"] is True
|
||||
assert by["email_config"]["ok"] is True
|
||||
assert by["venv_python"]["ok"] is True
|
||||
|
||||
|
||||
def test_cleanup_orphans_success_path():
|
||||
chrome = {"killed": 2, "matched": 2}
|
||||
xvfb = {"killed": 1, "matched": 1}
|
||||
fake = SimpleNamespace(
|
||||
cleanup_orphan_drission_chromes=lambda **_k: chrome,
|
||||
cleanup_orphan_xvfb=lambda **_k: xvfb,
|
||||
)
|
||||
with mock.patch.dict(sys.modules, {"tab_pool": fake}):
|
||||
out = cleanup_orphans(dry_run=False)
|
||||
assert out["ok"] is True
|
||||
assert out["chrome"]["killed"] == 2
|
||||
assert out["xvfb"]["killed"] == 1
|
||||
assert "chrome_killed=2" in out["detail"]
|
||||
|
||||
|
||||
def test_cleanup_orphans_dry_run():
|
||||
chrome = {"would_kill": 3, "matched": 3}
|
||||
xvfb = {"would_kill": 1, "matched": 1}
|
||||
fake = SimpleNamespace(
|
||||
cleanup_orphan_drission_chromes=lambda **_k: chrome,
|
||||
cleanup_orphan_xvfb=lambda **_k: xvfb,
|
||||
)
|
||||
with mock.patch.dict(sys.modules, {"tab_pool": fake}):
|
||||
out = cleanup_orphans(dry_run=True)
|
||||
assert out["ok"] is True
|
||||
assert out["dry_run"] is True
|
||||
assert "chrome_would=3" in out["detail"]
|
||||
|
||||
|
||||
def test_routes_accounts_and_ops(tmp_path: Path, monkeypatch):
|
||||
(tmp_path / "config.json").write_text("{}", encoding="utf-8")
|
||||
_write_auth(tmp_path / "cpa_auths", "route@ex.com")
|
||||
(tmp_path / "register_cli.py").write_text("#\n", encoding="utf-8")
|
||||
(tmp_path / "scripts").mkdir()
|
||||
(tmp_path / "scripts" / "launch_batch_supervisor.sh").write_text("#!/bin/bash\n", encoding="utf-8")
|
||||
|
||||
client = _client(tmp_path, monkeypatch)
|
||||
headers = {"Authorization": "Bearer secret-token"}
|
||||
|
||||
r = client.get("/api/accounts", headers=headers)
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["total"] >= 1
|
||||
assert any(it["email"] == "route@ex.com" for it in body["items"])
|
||||
|
||||
sc = client.get("/api/ops/selfcheck", headers=headers)
|
||||
assert sc.status_code == 200
|
||||
assert "checks" in sc.json()
|
||||
|
||||
name = "xai-route@ex.com.json"
|
||||
d = client.delete(f"/api/accounts/{name}", headers=headers)
|
||||
assert d.status_code == 200
|
||||
assert d.json()["ok"] is True
|
||||
|
||||
d2 = client.delete(f"/api/accounts/{name}", headers=headers)
|
||||
assert d2.status_code == 404
|
||||
|
||||
# invalid account name rejected by API
|
||||
bad = client.delete("/api/accounts/not-xai.json", headers=headers)
|
||||
assert bad.status_code == 400
|
||||
|
||||
fake = SimpleNamespace(
|
||||
cleanup_orphan_drission_chromes=lambda **_k: {"killed": 0, "matched": 0},
|
||||
cleanup_orphan_xvfb=lambda **_k: {"killed": 0, "matched": 0},
|
||||
)
|
||||
with mock.patch.dict(sys.modules, {"tab_pool": fake}):
|
||||
cl = client.post("/api/ops/cleanup-orphans?dry_run=true", headers=headers)
|
||||
assert cl.status_code == 200
|
||||
assert cl.json()["ok"] is True
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Auth and settings tests for control API."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def test_settings_reads_env(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("REGISTER_PROJECT_ROOT", str(tmp_path))
|
||||
monkeypatch.setenv("CONTROL_API_TOKEN", "secret-token")
|
||||
monkeypatch.setenv("CONTROL_API_HOST", "127.0.0.1")
|
||||
monkeypatch.setenv("CONTROL_API_PORT", "8787")
|
||||
from apps.control_api.settings import clear_settings_cache, get_settings
|
||||
|
||||
clear_settings_cache()
|
||||
s = get_settings()
|
||||
assert s.project_root == tmp_path.resolve()
|
||||
assert s.token == "secret-token"
|
||||
assert s.port == 8787
|
||||
|
||||
|
||||
def test_health_ok_without_token_when_unset(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("REGISTER_PROJECT_ROOT", str(tmp_path))
|
||||
monkeypatch.delenv("CONTROL_API_TOKEN", raising=False)
|
||||
monkeypatch.setenv("CONTROL_API_PASSWORD_LOGIN", "0")
|
||||
from apps.control_api.settings import clear_settings_cache
|
||||
from apps.control_api.app import create_app
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
clear_settings_cache()
|
||||
client = TestClient(create_app())
|
||||
r = client.get("/api/health")
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["ok"] is True
|
||||
assert body["auth_required"] is False
|
||||
|
||||
|
||||
def test_protected_route_401_without_bearer(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("REGISTER_PROJECT_ROOT", str(tmp_path))
|
||||
monkeypatch.setenv("CONTROL_API_TOKEN", "secret-token")
|
||||
from apps.control_api.settings import clear_settings_cache
|
||||
from apps.control_api.app import create_app
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
clear_settings_cache()
|
||||
client = TestClient(create_app())
|
||||
r = client.get("/api/overview")
|
||||
assert r.status_code == 401
|
||||
|
||||
|
||||
def test_protected_route_ok_with_bearer(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("REGISTER_PROJECT_ROOT", str(tmp_path))
|
||||
monkeypatch.setenv("CONTROL_API_TOKEN", "secret-token")
|
||||
(tmp_path / "cpa_auths").mkdir()
|
||||
from apps.control_api.settings import clear_settings_cache
|
||||
from apps.control_api.app import create_app
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
clear_settings_cache()
|
||||
client = TestClient(create_app())
|
||||
r = client.get("/api/overview", headers={"Authorization": "Bearer secret-token"})
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["product_ok"] == 0
|
||||
assert "project_root" in body
|
||||
@@ -0,0 +1,402 @@
|
||||
"""Config IO and overview count tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from apps.control_api.config_io import (
|
||||
config_to_env_map,
|
||||
enrich_config_from_env,
|
||||
load_config,
|
||||
redact_config,
|
||||
save_config,
|
||||
sync_config_to_env,
|
||||
update_env_file,
|
||||
)
|
||||
from apps.control_api.overview import count_product_ok
|
||||
|
||||
|
||||
def test_load_strips_comment_keys(tmp_path: Path):
|
||||
(tmp_path / "config.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"// note": "x",
|
||||
"email_provider": "cloudflare",
|
||||
"cloudflare_api_key": "abc12345",
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
data = load_config(tmp_path)
|
||||
assert "// note" not in data
|
||||
assert data["email_provider"] == "cloudflare"
|
||||
|
||||
|
||||
def test_redact_masks_secrets():
|
||||
out = redact_config(
|
||||
{
|
||||
"email_provider": "cloudflare",
|
||||
"cloudflare_api_key": "abc12345",
|
||||
"proxy": "http://x",
|
||||
}
|
||||
)
|
||||
assert out["email_provider"] == "cloudflare"
|
||||
assert out["cloudflare_api_key"].startswith("***")
|
||||
assert "2345" in out["cloudflare_api_key"]
|
||||
assert out["proxy"] == "http://x"
|
||||
|
||||
|
||||
def test_save_backup_and_preserve_secret_on_empty(tmp_path: Path):
|
||||
(tmp_path / "config.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"email_provider": "cloudflare",
|
||||
"cloudflare_api_key": "keepme-secret",
|
||||
"defaultDomains": "a.com",
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
# Pre-seed .env with unrelated operational key that must survive a partial save.
|
||||
(tmp_path / ".env").write_text("PROXY=http://127.0.0.1:7897\n", encoding="utf-8")
|
||||
result = save_config(
|
||||
tmp_path,
|
||||
{
|
||||
"email_provider": "cloudflare",
|
||||
"cloudflare_api_key": "",
|
||||
"defaultDomains": "b.com",
|
||||
},
|
||||
)
|
||||
assert result["backup"]
|
||||
assert Path(result["backup"]).is_file()
|
||||
data = json.loads((tmp_path / "config.json").read_text(encoding="utf-8"))
|
||||
assert data["cloudflare_api_key"] == "keepme-secret"
|
||||
assert data["defaultDomains"] == "b.com"
|
||||
# only payload operational keys mirrored; PROXY untouched
|
||||
env_text = (tmp_path / ".env").read_text(encoding="utf-8")
|
||||
assert "EMAIL_PROVIDER=cloudflare" in env_text
|
||||
assert "DEFAULT_DOMAINS=b.com" in env_text
|
||||
assert "PROXY=http://127.0.0.1:7897" in env_text
|
||||
# secrets must never land in .env via console sync
|
||||
assert "keepme-secret" not in env_text
|
||||
assert "cloudflare_api_key" not in env_text.lower()
|
||||
|
||||
|
||||
def test_save_preserves_masked_secret(tmp_path: Path):
|
||||
(tmp_path / "config.json").write_text(
|
||||
json.dumps({"cloudflare_api_key": "real-secret-value"}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
save_config(tmp_path, {"cloudflare_api_key": "***alue", "email_provider": "gmail"})
|
||||
data = json.loads((tmp_path / "config.json").read_text(encoding="utf-8"))
|
||||
assert data["cloudflare_api_key"] == "real-secret-value"
|
||||
assert data["email_provider"] == "gmail"
|
||||
|
||||
|
||||
def test_config_to_env_map_formats_lists_and_bools():
|
||||
m = config_to_env_map(
|
||||
{
|
||||
"email_provider": "hotmail",
|
||||
"email_providers": ["duckmail", "gmail"],
|
||||
"cpa_probe_chat": False,
|
||||
"mail_timeout": 20,
|
||||
"defaultDomains": "a.com,b.com",
|
||||
"cloudflare_api_key": "secret-should-skip", # secret key substr
|
||||
}
|
||||
)
|
||||
assert m["EMAIL_PROVIDER"] == "hotmail"
|
||||
assert m["EMAIL_PROVIDERS"] == "duckmail,gmail"
|
||||
assert m["CPA_PROBE_CHAT"] == "false"
|
||||
assert m["MAIL_TIMEOUT"] == "20"
|
||||
assert m["DEFAULT_DOMAINS"] == "a.com,b.com"
|
||||
assert "CLOUDFLARE_API_KEY" not in m
|
||||
|
||||
|
||||
def test_update_env_file_preserves_comments_and_unknown(tmp_path: Path):
|
||||
env = tmp_path / ".env"
|
||||
env.write_text(
|
||||
"# keep me\n"
|
||||
"EMAIL_PROVIDER=cloudflare\n"
|
||||
"CUSTOM_UNKNOWN=stay\n"
|
||||
"MAIL_TIMEOUT=10\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
out = update_env_file(
|
||||
env,
|
||||
{
|
||||
"EMAIL_PROVIDER": "hotmail",
|
||||
"EMAIL_PROVIDERS": "",
|
||||
"EVIL_NOT_ALLOWED": "nope",
|
||||
},
|
||||
)
|
||||
assert "EMAIL_PROVIDER" in out["changed_env_keys"]
|
||||
text = env.read_text(encoding="utf-8")
|
||||
assert "# keep me" in text
|
||||
assert "EMAIL_PROVIDER=hotmail" in text
|
||||
assert "CUSTOM_UNKNOWN=stay" in text
|
||||
assert "EVIL_NOT_ALLOWED" not in text
|
||||
assert "EMAIL_PROVIDERS=" in text
|
||||
assert out["backup"]
|
||||
assert Path(out["backup"]).is_file()
|
||||
|
||||
|
||||
def test_sync_config_to_env_from_disk(tmp_path: Path):
|
||||
(tmp_path / "config.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"email_provider": "hotmail",
|
||||
"email_provider_strategy": "failover",
|
||||
"cloudflare_api_base": "https://temp-mail.example",
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
(tmp_path / ".env").write_text("EMAIL_PROVIDER=cloudflare\n", encoding="utf-8")
|
||||
out = sync_config_to_env(tmp_path)
|
||||
assert "EMAIL_PROVIDER" in out["changed_env_keys"]
|
||||
text = (tmp_path / ".env").read_text(encoding="utf-8")
|
||||
assert "EMAIL_PROVIDER=hotmail" in text
|
||||
assert "EMAIL_PROVIDER_STRATEGY=failover" in text
|
||||
assert "CLOUDFLARE_API_BASE=https://temp-mail.example" in text
|
||||
|
||||
|
||||
def test_count_product_ok(tmp_path: Path):
|
||||
d = tmp_path / "cpa_auths"
|
||||
d.mkdir()
|
||||
(d / "xai-a.json").write_text(
|
||||
json.dumps({"access_token": "a", "refresh_token": "r"}), encoding="utf-8"
|
||||
)
|
||||
(d / "xai-b.json").write_text(json.dumps({"access_token": "a"}), encoding="utf-8")
|
||||
(d / "other.json").write_text(
|
||||
json.dumps({"access_token": "a", "refresh_token": "r"}), encoding="utf-8"
|
||||
)
|
||||
assert count_product_ok(tmp_path) == 1
|
||||
|
||||
|
||||
def test_save_sticky_empty_proxy_does_not_wipe_env(tmp_path: Path):
|
||||
"""Register page used to POST proxy=\"\" and blank host PROXY.
|
||||
|
||||
defaultDomains is intentionally clearable (Resources may empty the pool);
|
||||
blank-only whitespace still clears after strip via _is_blank / clearable path.
|
||||
This test keeps domains out of the wipe-check: only proxy stays sticky.
|
||||
"""
|
||||
(tmp_path / "config.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"email_provider": "cloudflare",
|
||||
"proxy": "http://127.0.0.1:7897",
|
||||
"defaultDomains": "a.com,b.com",
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
(tmp_path / ".env").write_text(
|
||||
"EMAIL_PROVIDER=cloudflare\n"
|
||||
"PROXY=http://127.0.0.1:7897\n"
|
||||
"DEFAULT_DOMAINS=a.com,b.com\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
result = save_config(
|
||||
tmp_path,
|
||||
{
|
||||
"email_provider": "hotmail",
|
||||
"proxy": "",
|
||||
"proxy_list": "", # clearable
|
||||
# omit defaultDomains → sticky keep (Register never posts it)
|
||||
},
|
||||
)
|
||||
data = json.loads((tmp_path / "config.json").read_text(encoding="utf-8"))
|
||||
assert data["email_provider"] == "hotmail"
|
||||
assert data["proxy"] == "http://127.0.0.1:7897"
|
||||
assert data["defaultDomains"] == "a.com,b.com"
|
||||
assert data.get("proxy_list") == ""
|
||||
env_text = (tmp_path / ".env").read_text(encoding="utf-8")
|
||||
assert "EMAIL_PROVIDER=hotmail" in env_text
|
||||
assert "PROXY=http://127.0.0.1:7897" in env_text
|
||||
assert "DEFAULT_DOMAINS=a.com,b.com" in env_text
|
||||
assert "PROXY_LIST=" in env_text
|
||||
assert "EMAIL_PROVIDER" in result["changed_env_keys"]
|
||||
assert "PROXY" not in result["changed_env_keys"]
|
||||
assert "DEFAULT_DOMAINS" not in result["changed_env_keys"]
|
||||
|
||||
|
||||
def test_save_clearable_default_domains(tmp_path: Path):
|
||||
"""Resources may intentionally clear defaultDomains (and DEFAULT_DOMAINS=)."""
|
||||
(tmp_path / "config.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"email_provider": "cloudflare",
|
||||
"defaultDomains": "a.com,b.com",
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
(tmp_path / ".env").write_text(
|
||||
"EMAIL_PROVIDER=cloudflare\nDEFAULT_DOMAINS=a.com,b.com\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
result = save_config(tmp_path, {"defaultDomains": ""})
|
||||
data = json.loads((tmp_path / "config.json").read_text(encoding="utf-8"))
|
||||
assert data["defaultDomains"] == ""
|
||||
env_text = (tmp_path / ".env").read_text(encoding="utf-8")
|
||||
assert "DEFAULT_DOMAINS=" in env_text
|
||||
# cleared value should not retain old domains
|
||||
assert "DEFAULT_DOMAINS=a.com,b.com" not in env_text
|
||||
assert "DEFAULT_DOMAINS" in result["changed_env_keys"]
|
||||
|
||||
|
||||
def test_config_to_env_map_sticky_empty_skips_proxy():
|
||||
m = config_to_env_map(
|
||||
{
|
||||
"email_provider": "hotmail",
|
||||
"proxy": "",
|
||||
"defaultDomains": "",
|
||||
"email_providers": [],
|
||||
}
|
||||
)
|
||||
assert m["EMAIL_PROVIDER"] == "hotmail"
|
||||
assert "PROXY" not in m
|
||||
# defaultDomains is clearable → empty emits DEFAULT_DOMAINS=
|
||||
assert m.get("DEFAULT_DOMAINS") == ""
|
||||
# multi-select may clear
|
||||
assert m.get("EMAIL_PROVIDERS") == ""
|
||||
|
||||
|
||||
def test_enrich_config_from_env_fills_blank_ops(tmp_path: Path):
|
||||
(tmp_path / "config.json").write_text(
|
||||
json.dumps({"email_provider": "hotmail", "proxy": "", "defaultDomains": ""}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
(tmp_path / ".env").write_text(
|
||||
"PROXY=http://127.0.0.1:7897\n"
|
||||
"DEFAULT_DOMAINS=mangoqwq.com,a.cd\n"
|
||||
"EMAIL_PROVIDER=cloudflare\n", # config non-blank wins
|
||||
encoding="utf-8",
|
||||
)
|
||||
out = enrich_config_from_env(tmp_path)
|
||||
assert out["email_provider"] == "hotmail"
|
||||
assert out["proxy"] == "http://127.0.0.1:7897"
|
||||
assert out["defaultDomains"] == "mangoqwq.com,a.cd"
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_config_api_roundtrip(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.setenv("REGISTER_PROJECT_ROOT", str(tmp_path))
|
||||
monkeypatch.setenv("CONTROL_API_TOKEN", "t")
|
||||
(tmp_path / "config.json").write_text(
|
||||
json.dumps({"email_provider": "cloudflare", "defaultDomains": "a.com"}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
from apps.control_api.app import create_app
|
||||
from apps.control_api.settings import clear_settings_cache
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
clear_settings_cache()
|
||||
client = TestClient(create_app())
|
||||
headers = {"Authorization": "Bearer t"}
|
||||
r = client.get("/api/config", headers=headers)
|
||||
assert r.status_code == 200
|
||||
assert r.json()["config"]["email_provider"] == "cloudflare"
|
||||
r2 = client.put(
|
||||
"/api/config",
|
||||
headers=headers,
|
||||
json={"config": {"email_provider": "gmail", "defaultDomains": "b.com"}},
|
||||
)
|
||||
assert r2.status_code == 200
|
||||
assert r2.json()["ok"] is True
|
||||
assert "defaultDomains" in r2.json()["changed_keys"]
|
||||
body = r2.json()
|
||||
assert "EMAIL_PROVIDER" in body.get("changed_env_keys", [])
|
||||
env_text = (tmp_path / ".env").read_text(encoding="utf-8")
|
||||
assert "EMAIL_PROVIDER=gmail" in env_text
|
||||
assert "DEFAULT_DOMAINS=b.com" in env_text
|
||||
|
||||
|
||||
def test_config_api_get_enriches_from_env(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.setenv("REGISTER_PROJECT_ROOT", str(tmp_path))
|
||||
monkeypatch.setenv("CONTROL_API_TOKEN", "t")
|
||||
(tmp_path / "config.json").write_text(
|
||||
json.dumps({"email_provider": "hotmail", "proxy": "", "defaultDomains": ""}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
(tmp_path / ".env").write_text(
|
||||
"PROXY=http://127.0.0.1:7897\nDEFAULT_DOMAINS=keep.me\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
from apps.control_api.app import create_app
|
||||
from apps.control_api.settings import clear_settings_cache
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
clear_settings_cache()
|
||||
client = TestClient(create_app())
|
||||
headers = {"Authorization": "Bearer t"}
|
||||
r = client.get("/api/config", headers=headers)
|
||||
assert r.status_code == 200
|
||||
cfg = r.json()["config"]
|
||||
assert cfg["email_provider"] == "hotmail"
|
||||
assert cfg["proxy"] == "http://127.0.0.1:7897"
|
||||
assert cfg["defaultDomains"] == "keep.me"
|
||||
# disk unchanged
|
||||
disk = json.loads((tmp_path / "config.json").read_text(encoding="utf-8"))
|
||||
assert disk["proxy"] == ""
|
||||
assert disk["defaultDomains"] == ""
|
||||
|
||||
|
||||
def test_config_api_put_sticky_empty_and_enrich(tmp_path: Path, monkeypatch):
|
||||
"""proxy stays sticky; defaultDomains empty is intentional clear."""
|
||||
monkeypatch.setenv("REGISTER_PROJECT_ROOT", str(tmp_path))
|
||||
monkeypatch.setenv("CONTROL_API_TOKEN", "t")
|
||||
(tmp_path / "config.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"email_provider": "cloudflare",
|
||||
"proxy": "http://old:1",
|
||||
"defaultDomains": "old.com",
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
(tmp_path / ".env").write_text(
|
||||
"PROXY=http://old:1\nDEFAULT_DOMAINS=old.com\nEMAIL_PROVIDER=cloudflare\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
from apps.control_api.app import create_app
|
||||
from apps.control_api.settings import clear_settings_cache
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
clear_settings_cache()
|
||||
client = TestClient(create_app())
|
||||
headers = {"Authorization": "Bearer t"}
|
||||
r = client.put(
|
||||
"/api/config",
|
||||
headers=headers,
|
||||
json={
|
||||
"config": {
|
||||
"email_provider": "hotmail",
|
||||
"proxy": "",
|
||||
"defaultDomains": "",
|
||||
}
|
||||
},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["config"]["email_provider"] == "hotmail"
|
||||
assert body["config"]["proxy"] == "http://old:1"
|
||||
assert body["config"]["defaultDomains"] == ""
|
||||
assert "PROXY" not in body.get("changed_env_keys", [])
|
||||
assert "DEFAULT_DOMAINS" in body.get("changed_env_keys", [])
|
||||
env_text = (tmp_path / ".env").read_text(encoding="utf-8")
|
||||
assert "PROXY=http://old:1" in env_text
|
||||
assert "DEFAULT_DOMAINS=" in env_text
|
||||
assert "DEFAULT_DOMAINS=old.com" not in env_text
|
||||
assert "EMAIL_PROVIDER=hotmail" in env_text
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
"""Import ops tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
from apps.control_api.imports_ops import (
|
||||
ensure_under,
|
||||
import_mail,
|
||||
import_nodes,
|
||||
import_pack,
|
||||
safe_extract_zip,
|
||||
save_upload,
|
||||
)
|
||||
|
||||
|
||||
def test_path_traversal_rejected(tmp_path: Path):
|
||||
with pytest.raises(ValueError, match="escapes"):
|
||||
ensure_under(tmp_path, tmp_path / ".." / "etc" / "passwd")
|
||||
|
||||
|
||||
def test_save_upload_size_cap(tmp_path: Path):
|
||||
with pytest.raises(ValueError, match="max_upload"):
|
||||
save_upload(tmp_path, "big.bin", b"x" * 100, max_bytes=10)
|
||||
|
||||
|
||||
def test_mail_append_backup(tmp_path: Path):
|
||||
target = tmp_path / "mail_credentials.txt"
|
||||
target.write_text("old@x.com----a----b----c\n", encoding="utf-8")
|
||||
result = import_mail(tmp_path, "new@x.com----a----b----c\n", mode="append")
|
||||
assert result["ok"] is True
|
||||
assert result["backup"]
|
||||
assert result["status"] == "success"
|
||||
assert result["new"] == 1
|
||||
assert result["duplicate"] == 0
|
||||
assert "导入成功" in result["summary"]
|
||||
assert "new@x.com" in result["summary"]
|
||||
text = target.read_text(encoding="utf-8")
|
||||
assert "old@x.com" in text
|
||||
assert "new@x.com" in text
|
||||
|
||||
|
||||
def test_mail_replace(tmp_path: Path):
|
||||
target = tmp_path / "mail_credentials.txt"
|
||||
target.write_text("keep@x.com----a----b----c\n", encoding="utf-8")
|
||||
result = import_mail(tmp_path, "new@x.com----p----c----r\n", mode="replace")
|
||||
assert result["ok"] is True
|
||||
assert result["lines_written"] == 1
|
||||
assert target.read_text(encoding="utf-8") == "new@x.com----p----c----r\n"
|
||||
|
||||
|
||||
def test_mail_replace_all_invalid_refused(tmp_path: Path):
|
||||
"""replace with 0 valid credentials must not truncate the pool."""
|
||||
target = tmp_path / "mail_credentials.txt"
|
||||
target.write_text("keep@x.com----a----b----c\n", encoding="utf-8")
|
||||
with pytest.raises(ValueError, match="将清空邮箱池"):
|
||||
import_mail(tmp_path, "only-new\n", mode="replace")
|
||||
# pool untouched, and no stray backup written
|
||||
assert target.read_text(encoding="utf-8") == "keep@x.com----a----b----c\n"
|
||||
assert not list(tmp_path.glob("mail_credentials.txt.bak-web-*"))
|
||||
|
||||
|
||||
def test_mail_replace_empty_pool_allowed(tmp_path: Path):
|
||||
"""No existing pool → replace with invalid input is a harmless no-op, not an error."""
|
||||
result = import_mail(tmp_path, "only-new\n", mode="replace")
|
||||
assert result["ok"] is True
|
||||
assert result["lines_written"] == 0
|
||||
assert result["status"] == "empty"
|
||||
assert "未导入" in result["summary"]
|
||||
|
||||
|
||||
def test_mail_import_json_object_normalized(tmp_path: Path):
|
||||
target = tmp_path / "mail_credentials.txt"
|
||||
target.write_text("keep@x.com----a----b----c\n", encoding="utf-8")
|
||||
payload = (
|
||||
'{"email":"Kanode@outlook.com","password":"p1",'
|
||||
'"clientId":"cid-1","refreshToken":"rt-1"}'
|
||||
)
|
||||
result = import_mail(tmp_path, payload, mode="append")
|
||||
assert result["ok"] is True
|
||||
assert result["lines_written"] == 1
|
||||
assert result["new"] == 1
|
||||
assert result["status"] == "success"
|
||||
assert result["normalized"]["json_objects"] == 1
|
||||
assert result["formats"]["json_objects"] == 1
|
||||
assert "JSON 1" in result["summary"]
|
||||
text = target.read_text(encoding="utf-8")
|
||||
assert "keep@x.com----a----b----c" in text
|
||||
assert "Kanode@outlook.com----p1----cid-1----rt-1" in text
|
||||
assert '{"email"' not in text
|
||||
|
||||
|
||||
def test_mail_import_json_array(tmp_path: Path):
|
||||
target = tmp_path / "mail_credentials.txt"
|
||||
payload = (
|
||||
'[{"email":"a@outlook.com","password":"pa","clientId":"c1","refreshToken":"r1"},'
|
||||
'{"email":"bad","password":"x","clientId":"c","refreshToken":"r"},'
|
||||
'{"email":"b@hotmail.com","password":"pb","clientId":"c2","refreshToken":"r2"}]'
|
||||
)
|
||||
result = import_mail(tmp_path, payload, mode="replace")
|
||||
assert result["lines_written"] == 2
|
||||
assert result["skipped"] == 1
|
||||
assert result["status"] == "partial"
|
||||
assert "部分成功" in result["summary"]
|
||||
assert result["normalized"]["skipped"] == 1
|
||||
lines = [ln for ln in target.read_text(encoding="utf-8").splitlines() if ln.strip()]
|
||||
assert lines == [
|
||||
"a@outlook.com----pa----c1----r1",
|
||||
"b@hotmail.com----pb----c2----r2",
|
||||
]
|
||||
|
||||
|
||||
def test_mail_import_pipe_and_csv(tmp_path: Path):
|
||||
target = tmp_path / "mail_credentials.txt"
|
||||
result = import_mail(tmp_path, "p@outlook.com|pw|cid-pipe1|rt-pipe001\n", mode="replace")
|
||||
assert result["lines_written"] == 1
|
||||
assert "p@outlook.com----pw----cid-pipe1----rt-pipe001" in target.read_text(encoding="utf-8")
|
||||
|
||||
csv_only = (
|
||||
"email,password,client_id,refresh_token\n"
|
||||
"r@live.com,pr,cid-csv2,rt-csv002\n"
|
||||
)
|
||||
result2 = import_mail(tmp_path, csv_only, mode="replace")
|
||||
assert result2["lines_written"] == 1
|
||||
assert result2["normalized"].get("csv_rows") == 1
|
||||
assert "r@live.com----pr----cid-csv2----rt-csv002" in target.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_mail_import_append_dedupe_feedback(tmp_path: Path):
|
||||
"""Append skips emails already in pool and reports duplicate honestly."""
|
||||
target = tmp_path / "mail_credentials.txt"
|
||||
target.write_text(
|
||||
"exist@outlook.com----pw----cid-exist----rt-exist\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
payload = (
|
||||
"exist@outlook.com----pw2----cid2----rt2\n"
|
||||
"fresh@outlook.com----pw3----cid3----rt3\n"
|
||||
"EXIST@outlook.com----pw4----cid4----rt4\n" # case-insensitive dup
|
||||
"fresh@outlook.com----pw5----cid5----rt5\n" # batch-internal dup
|
||||
)
|
||||
result = import_mail(tmp_path, payload, mode="append")
|
||||
assert result["ok"] is True
|
||||
assert result["new"] == 1
|
||||
assert result["lines_written"] == 1
|
||||
assert result["duplicate"] == 3
|
||||
assert result["status"] == "partial"
|
||||
assert result["pool_before"] == 1
|
||||
assert result["pool_after"] == 2
|
||||
assert "部分成功" in result["summary"]
|
||||
assert "新增 1" in result["summary"]
|
||||
assert "重复跳过 3" in result["summary"]
|
||||
assert "fresh@outlook.com" in result["new_emails"]
|
||||
assert "exist@outlook.com" in [e.lower() for e in result["duplicate_emails"]]
|
||||
text = target.read_text(encoding="utf-8")
|
||||
assert text.count("fresh@outlook.com") == 1
|
||||
assert text.count("exist@outlook.com") == 1
|
||||
# only original exist line + one new
|
||||
lines = [ln for ln in text.splitlines() if ln.strip()]
|
||||
assert len(lines) == 2
|
||||
|
||||
|
||||
def test_mail_import_all_duplicate_feedback(tmp_path: Path):
|
||||
target = tmp_path / "mail_credentials.txt"
|
||||
target.write_text("a@outlook.com----p----c----r\n", encoding="utf-8")
|
||||
result = import_mail(
|
||||
tmp_path,
|
||||
"a@outlook.com----p2----c2----r2\n",
|
||||
mode="append",
|
||||
)
|
||||
assert result["new"] == 0
|
||||
assert result["duplicate"] == 1
|
||||
assert result["status"] == "empty"
|
||||
assert result["backup"] is None # nothing written → no bak
|
||||
assert "未新增" in result["summary"]
|
||||
assert "全部已在池中" in result["summary"]
|
||||
assert target.read_text(encoding="utf-8") == "a@outlook.com----p----c----r\n"
|
||||
|
||||
|
||||
def test_nodes_dry_run_invokes_script(tmp_path: Path):
|
||||
script = tmp_path / "scripts" / "import_nodes.py"
|
||||
script.parent.mkdir(parents=True)
|
||||
script.write_text("print('ok')\n", encoding="utf-8")
|
||||
f = tmp_path / "output" / "web_uploads" / "n.yaml"
|
||||
f.parent.mkdir(parents=True)
|
||||
f.write_text("proxies: []\n", encoding="utf-8")
|
||||
|
||||
class R:
|
||||
returncode = 0
|
||||
stdout = "imported 0"
|
||||
stderr = ""
|
||||
|
||||
with mock.patch("apps.control_api.imports_ops.subprocess.run", return_value=R()) as run:
|
||||
result = import_nodes(tmp_path, f, dry_run=True)
|
||||
assert result["ok"] is True
|
||||
assert result["dry_run"] is True
|
||||
argv = run.call_args[0][0]
|
||||
assert "--dry-run" in argv
|
||||
|
||||
|
||||
def test_import_pack_plan_and_apply(tmp_path: Path):
|
||||
zpath = tmp_path / "pack.zip"
|
||||
with zipfile.ZipFile(zpath, "w") as zf:
|
||||
zf.writestr("config.json", '{"email_provider":"cloudflare"}')
|
||||
zf.writestr("nodes.json", "[]")
|
||||
# move zip under staging-friendly path
|
||||
staging = tmp_path / "output" / "web_uploads"
|
||||
staging.mkdir(parents=True)
|
||||
z2 = staging / "pack.zip"
|
||||
z2.write_bytes(zpath.read_bytes())
|
||||
plan = import_pack(tmp_path, z2, apply=False)
|
||||
assert plan["plan"]["config"]
|
||||
assert plan["applied"] == {}
|
||||
applied = import_pack(tmp_path, z2, apply=True)
|
||||
assert (tmp_path / "config.json").is_file()
|
||||
assert "config" in applied["applied"]
|
||||
|
||||
|
||||
# ── zip extraction hardening (symlink skip + bomb + traversal) ────────────────
|
||||
|
||||
|
||||
def _make_symlink_zip(path: Path, linkname: str, target: str) -> None:
|
||||
"""Build a zip whose member is a Unix symlink (S_IFLNK in external_attr)."""
|
||||
with zipfile.ZipFile(path, "w") as zf:
|
||||
zi = zipfile.ZipInfo(linkname)
|
||||
# high 16 bits = unix st_mode; 0o120000 = S_IFLNK
|
||||
zi.external_attr = (0o120000 << 16) | 0o777
|
||||
zf.writestr(zi, target)
|
||||
|
||||
|
||||
def test_safe_extract_skips_symlink_entry(tmp_path: Path):
|
||||
"""A symlink entry in an upload zip must not be materialized at all.
|
||||
|
||||
The link could point anywhere on disk; a later import walking the tree
|
||||
would follow it out of the staging dir. safe_extract_zip drops it.
|
||||
"""
|
||||
z = tmp_path / "links.zip"
|
||||
_make_symlink_zip(z, "escape.txt", "/etc/passwd")
|
||||
out = tmp_path / "out"
|
||||
with zipfile.ZipFile(z, "r") as zf:
|
||||
written = safe_extract_zip(zf, out)
|
||||
assert written == 0
|
||||
assert not (out / "escape.txt").exists()
|
||||
assert not list(out.rglob("*")) or all(p.is_dir() for p in out.rglob("*"))
|
||||
|
||||
|
||||
def test_safe_extract_rejects_zip_slip(tmp_path: Path):
|
||||
"""A ``..`` traversal entry must raise before anything is written."""
|
||||
z = tmp_path / "slip.zip"
|
||||
with zipfile.ZipFile(z, "w") as zf:
|
||||
zf.writestr("../outside.txt", "pwn")
|
||||
out = tmp_path / "out"
|
||||
with pytest.raises(ValueError, match="unsafe zip entry"), zipfile.ZipFile(z, "r") as zf:
|
||||
safe_extract_zip(zf, out)
|
||||
# nothing landed outside the dest
|
||||
assert not (tmp_path / "outside.txt").exists()
|
||||
|
||||
|
||||
def test_safe_extract_rejects_absolute_entry(tmp_path: Path):
|
||||
z = tmp_path / "abs.zip"
|
||||
with zipfile.ZipFile(z, "w") as zf:
|
||||
zf.writestr("/abs.txt", "pwn")
|
||||
out = tmp_path / "out"
|
||||
with pytest.raises(ValueError, match="unsafe zip entry"), zipfile.ZipFile(z, "r") as zf:
|
||||
safe_extract_zip(zf, out)
|
||||
|
||||
|
||||
def test_safe_extract_rejects_decompression_bomb(tmp_path: Path):
|
||||
"""A stream that exceeds max_bytes (real decompressed bytes) is refused mid-read.
|
||||
|
||||
The cap counts bytes actually read from the stream, so a header that lies
|
||||
about its size cannot slip an oversized payload through.
|
||||
"""
|
||||
z = tmp_path / "bomb.zip"
|
||||
big = b"A" * (1024 * 100) # 100 KiB body
|
||||
with zipfile.ZipFile(z, "w", compression=zipfile.ZIP_DEFLATED) as zf:
|
||||
zf.writestr("bin", big)
|
||||
out = tmp_path / "out"
|
||||
with pytest.raises(ValueError, match="max uncompressed bytes"), zipfile.ZipFile(z, "r") as zf:
|
||||
safe_extract_zip(zf, out, max_bytes=4096)
|
||||
# partial file must be gone — we unlink on overflow
|
||||
assert not (out / "bin").exists()
|
||||
|
||||
|
||||
def test_safe_extract_normal_archive_unaffected(tmp_path: Path):
|
||||
"""A benign zip with nested dirs extracts fully under dest."""
|
||||
z = tmp_path / "ok.zip"
|
||||
with zipfile.ZipFile(z, "w") as zf:
|
||||
zf.writestr("a/b/c.txt", "hello")
|
||||
zf.writestr("d.txt", "world")
|
||||
out = tmp_path / "out"
|
||||
with zipfile.ZipFile(z, "r") as zf:
|
||||
written = safe_extract_zip(zf, out)
|
||||
# two file entries; intermediate dirs (a/, a/b/) created via mkdir, not counted
|
||||
assert written == 2
|
||||
assert (out / "a" / "b" / "c.txt").read_text() == "hello"
|
||||
assert (out / "d.txt").read_text() == "world"
|
||||
|
||||
|
||||
def test_import_pack_skips_symlink_entry(tmp_path: Path):
|
||||
"""import_pack routes through safe_extract_zip, so a symlinked member is
|
||||
dropped — no config.json is found and no link is materialized on disk."""
|
||||
staging = tmp_path / "output" / "web_uploads"
|
||||
staging.mkdir(parents=True)
|
||||
z = staging / "pack.zip"
|
||||
_make_symlink_zip(z, "config.json", "/etc/passwd")
|
||||
out = import_pack(tmp_path, z)
|
||||
assert out["ok"] is True
|
||||
# nothing usable in the plan — the symlink was skipped, not followed
|
||||
assert out["plan"]["config"] is None
|
||||
# and no symlink / file named config.json exists in the extraction dir
|
||||
extract_root = Path(out["extract_to"])
|
||||
assert not (extract_root / "config.json").is_symlink()
|
||||
assert not any(p.name == "config.json" for p in extract_root.rglob("*") if p.is_symlink())
|
||||
@@ -0,0 +1,235 @@
|
||||
"""Password login + session cookie tests for control API."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def _client(tmp_path, monkeypatch, **env):
|
||||
monkeypatch.setenv("REGISTER_PROJECT_ROOT", str(tmp_path))
|
||||
monkeypatch.setenv("CONTROL_API_SESSION_SECRET", "test-session-secret-32bytes-min!!")
|
||||
monkeypatch.setenv("CONTROL_API_PASSWORD_LOGIN", "1")
|
||||
for k, v in env.items():
|
||||
if v is None:
|
||||
monkeypatch.delenv(k, raising=False)
|
||||
else:
|
||||
monkeypatch.setenv(k, v)
|
||||
from apps.control_api.settings import clear_settings_cache
|
||||
from apps.control_api.app import create_app
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
clear_settings_cache()
|
||||
return TestClient(create_app())
|
||||
|
||||
|
||||
def test_password_hash_roundtrip():
|
||||
from apps.control_api.passwords import hash_password, verify_password
|
||||
|
||||
h = hash_password("correct horse battery")
|
||||
assert h.startswith("scrypt$")
|
||||
assert verify_password("correct horse battery", h)
|
||||
assert not verify_password("wrong", h)
|
||||
|
||||
|
||||
def test_login_sets_cookie_and_opens_overview(tmp_path, monkeypatch):
|
||||
from apps.control_api.users import upsert_user
|
||||
|
||||
monkeypatch.setenv("REGISTER_PROJECT_ROOT", str(tmp_path))
|
||||
monkeypatch.delenv("CONTROL_API_TOKEN", raising=False)
|
||||
upsert_user(tmp_path, "admin", "password123")
|
||||
client = _client(tmp_path, monkeypatch, CONTROL_API_TOKEN=None)
|
||||
|
||||
r = client.get("/api/overview")
|
||||
assert r.status_code == 401
|
||||
|
||||
r = client.post("/api/auth/login", json={"username": "admin", "password": "wrong-password"})
|
||||
assert r.status_code == 401
|
||||
|
||||
r = client.post("/api/auth/login", json={"username": "admin", "password": "password123"})
|
||||
assert r.status_code == 200
|
||||
assert r.json()["ok"] is True
|
||||
assert "control_session" in r.cookies
|
||||
|
||||
r = client.get("/api/overview")
|
||||
assert r.status_code == 200
|
||||
assert "product_ok" in r.json()
|
||||
|
||||
r = client.get("/api/auth/me")
|
||||
assert r.status_code == 200
|
||||
assert r.json()["authenticated"] is True
|
||||
assert r.json()["username"] == "admin"
|
||||
|
||||
r = client.post("/api/auth/logout")
|
||||
assert r.status_code == 200
|
||||
r = client.get("/api/overview")
|
||||
assert r.status_code == 401
|
||||
|
||||
|
||||
def test_bearer_still_works_with_password_users(tmp_path, monkeypatch):
|
||||
from apps.control_api.users import upsert_user
|
||||
|
||||
(tmp_path / "cpa_auths").mkdir()
|
||||
upsert_user(tmp_path, "admin", "password123")
|
||||
client = _client(tmp_path, monkeypatch, CONTROL_API_TOKEN="secret-token")
|
||||
|
||||
r = client.get("/api/overview")
|
||||
assert r.status_code == 401
|
||||
r = client.get("/api/overview", headers={"Authorization": "Bearer secret-token"})
|
||||
assert r.status_code == 200
|
||||
|
||||
|
||||
def test_bootstrap_creates_first_user(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("REGISTER_PROJECT_ROOT", str(tmp_path))
|
||||
monkeypatch.setenv("CONTROL_API_SESSION_SECRET", "test-session-secret-32bytes-min!!")
|
||||
monkeypatch.setenv("CONTROL_API_BOOTSTRAP_USER", "ops")
|
||||
monkeypatch.setenv("CONTROL_API_BOOTSTRAP_PASSWORD", "bootstrap-pass-9")
|
||||
monkeypatch.delenv("CONTROL_API_TOKEN", raising=False)
|
||||
from apps.control_api.settings import clear_settings_cache
|
||||
from apps.control_api.app import create_app
|
||||
from apps.control_api.users import has_any_user
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
clear_settings_cache()
|
||||
with TestClient(create_app()) as client:
|
||||
assert has_any_user(tmp_path)
|
||||
r = client.post(
|
||||
"/api/auth/login",
|
||||
json={"username": "ops", "password": "bootstrap-pass-9"},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
r = client.get("/api/overview")
|
||||
assert r.status_code == 200
|
||||
|
||||
|
||||
def test_default_bootstrap_admin_admin123(tmp_path, monkeypatch):
|
||||
"""Empty store + no bootstrap env → admin / admin123 (project default)."""
|
||||
monkeypatch.setenv("REGISTER_PROJECT_ROOT", str(tmp_path))
|
||||
monkeypatch.setenv("CONTROL_API_SESSION_SECRET", "test-session-secret-32bytes-min!!")
|
||||
monkeypatch.delenv("CONTROL_API_BOOTSTRAP_USER", raising=False)
|
||||
monkeypatch.delenv("CONTROL_API_BOOTSTRAP_PASSWORD", raising=False)
|
||||
monkeypatch.delenv("CONTROL_API_TOKEN", raising=False)
|
||||
from apps.control_api.settings import clear_settings_cache, get_settings
|
||||
from apps.control_api.app import create_app
|
||||
from apps.control_api.users import has_any_user
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
clear_settings_cache()
|
||||
s = get_settings()
|
||||
assert s.bootstrap_user == "admin"
|
||||
assert s.bootstrap_password == "admin123"
|
||||
with TestClient(create_app()) as client:
|
||||
assert has_any_user(tmp_path)
|
||||
r = client.post(
|
||||
"/api/auth/login",
|
||||
json={"username": "admin", "password": "admin123"},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
|
||||
|
||||
def test_session_secret_loads_from_file_when_env_missing(tmp_path, monkeypatch):
|
||||
"""Bare start without CONTROL_API_SESSION_SECRET still works via durable file."""
|
||||
from apps.control_api.users import upsert_user
|
||||
from apps.control_api.settings import clear_settings_cache, get_settings
|
||||
from apps.control_api.app import create_app
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
secret = "file-session-secret-for-unit-test-only!!"
|
||||
(tmp_path / ".control_api_session_secret").write_text(secret + "\n", encoding="utf-8")
|
||||
upsert_user(tmp_path, "mango", "pw-file-secret-9")
|
||||
|
||||
monkeypatch.setenv("REGISTER_PROJECT_ROOT", str(tmp_path))
|
||||
monkeypatch.delenv("CONTROL_API_SESSION_SECRET", raising=False)
|
||||
monkeypatch.delenv("CONTROL_API_TOKEN", raising=False)
|
||||
monkeypatch.delenv("CONTROL_API_DEV_SESSION_SECRET", raising=False)
|
||||
monkeypatch.delenv("CONTROL_API_ALLOW_EPHEMERAL_SESSION", raising=False)
|
||||
monkeypatch.setenv("CONTROL_API_PASSWORD_LOGIN", "1")
|
||||
clear_settings_cache()
|
||||
s = get_settings()
|
||||
assert s.session_secret == secret
|
||||
assert s.session_secret_source.startswith("file:")
|
||||
|
||||
with TestClient(create_app()) as client:
|
||||
r = client.post(
|
||||
"/api/auth/login",
|
||||
json={"username": "mango", "password": "pw-file-secret-9"},
|
||||
)
|
||||
assert r.status_code == 200, r.text
|
||||
assert r.json()["ok"] is True
|
||||
|
||||
|
||||
def test_token_file_fallback_and_source(tmp_path, monkeypatch):
|
||||
from apps.control_api.settings import clear_settings_cache, get_settings
|
||||
|
||||
(tmp_path / ".control_api_token").write_text("bearer-from-file-token-xyz\n", encoding="utf-8")
|
||||
monkeypatch.setenv("REGISTER_PROJECT_ROOT", str(tmp_path))
|
||||
monkeypatch.delenv("CONTROL_API_TOKEN", raising=False)
|
||||
monkeypatch.delenv("CONTROL_API_SESSION_SECRET", raising=False)
|
||||
monkeypatch.delenv("CONTROL_API_ALLOW_EPHEMERAL_SESSION", raising=False)
|
||||
clear_settings_cache()
|
||||
s = get_settings()
|
||||
assert s.token == "bearer-from-file-token-xyz"
|
||||
assert s.token_source.startswith("file:")
|
||||
# session secret falls back to token when no dedicated secret
|
||||
assert s.session_secret == "bearer-from-file-token-xyz"
|
||||
assert s.session_secret_source == "token"
|
||||
|
||||
|
||||
def test_session_secret_loads_from_file_when_env_missing(tmp_path, monkeypatch):
|
||||
"""Bare start without CONTROL_API_SESSION_SECRET still works via durable file."""
|
||||
from apps.control_api.users import upsert_user
|
||||
from apps.control_api.settings import clear_settings_cache, get_settings
|
||||
from apps.control_api.app import create_app
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
secret = "file-session-secret-for-unit-test-only!!"
|
||||
(tmp_path / ".control_api_session_secret").write_text(secret + "\n", encoding="utf-8")
|
||||
upsert_user(tmp_path, "mango", "pw-file-secret-9")
|
||||
|
||||
monkeypatch.setenv("REGISTER_PROJECT_ROOT", str(tmp_path))
|
||||
monkeypatch.delenv("CONTROL_API_SESSION_SECRET", raising=False)
|
||||
monkeypatch.delenv("CONTROL_API_TOKEN", raising=False)
|
||||
monkeypatch.delenv("CONTROL_API_DEV_SESSION_SECRET", raising=False)
|
||||
monkeypatch.delenv("CONTROL_API_ALLOW_EPHEMERAL_SESSION", raising=False)
|
||||
monkeypatch.setenv("CONTROL_API_PASSWORD_LOGIN", "1")
|
||||
clear_settings_cache()
|
||||
s = get_settings()
|
||||
assert s.session_secret == secret
|
||||
assert s.session_secret_source.startswith("file:")
|
||||
|
||||
with TestClient(create_app()) as client:
|
||||
r = client.post(
|
||||
"/api/auth/login",
|
||||
json={"username": "mango", "password": "pw-file-secret-9"},
|
||||
)
|
||||
assert r.status_code == 200, r.text
|
||||
assert r.json()["ok"] is True
|
||||
|
||||
|
||||
def test_token_file_fallback_and_source(tmp_path, monkeypatch):
|
||||
from apps.control_api.settings import clear_settings_cache, get_settings
|
||||
|
||||
(tmp_path / ".control_api_token").write_text("bearer-from-file-token-xyz\n", encoding="utf-8")
|
||||
monkeypatch.setenv("REGISTER_PROJECT_ROOT", str(tmp_path))
|
||||
monkeypatch.delenv("CONTROL_API_TOKEN", raising=False)
|
||||
monkeypatch.delenv("CONTROL_API_SESSION_SECRET", raising=False)
|
||||
monkeypatch.delenv("CONTROL_API_ALLOW_EPHEMERAL_SESSION", raising=False)
|
||||
clear_settings_cache()
|
||||
s = get_settings()
|
||||
assert s.token == "bearer-from-file-token-xyz"
|
||||
assert s.token_source.startswith("file:")
|
||||
# session secret falls back to token when no dedicated secret
|
||||
assert s.session_secret == "bearer-from-file-token-xyz"
|
||||
assert s.session_secret_source == "token"
|
||||
|
||||
|
||||
def test_login_rate_limit(tmp_path, monkeypatch):
|
||||
from apps.control_api.users import upsert_user
|
||||
from apps.control_api.rate_limit import login_limiter
|
||||
|
||||
upsert_user(tmp_path, "admin", "password123")
|
||||
# reset limiter state between tests
|
||||
login_limiter._failures.clear()
|
||||
client = _client(tmp_path, monkeypatch, CONTROL_API_TOKEN=None)
|
||||
for _ in range(8):
|
||||
r = client.post("/api/auth/login", json={"username": "admin", "password": "nope"})
|
||||
assert r.status_code == 401
|
||||
r = client.post("/api/auth/login", json={"username": "admin", "password": "nope"})
|
||||
assert r.status_code == 429
|
||||
@@ -0,0 +1,419 @@
|
||||
"""control_api mail pool routes/ops (mocked refresh, no network)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from apps.control_api import mail_ops
|
||||
|
||||
|
||||
def _write_pool(path: Path, n: int = 5, domain: str = "hotmail.com") -> None:
|
||||
lines = [f"u{i}@{domain}----pw{i}----cid{i}----rt{i}\n" for i in range(n)]
|
||||
path.write_text("".join(lines), encoding="utf-8")
|
||||
|
||||
|
||||
def test_get_pool_stats(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.delenv("HOTMAIL_ACCOUNTS_FILE", raising=False)
|
||||
(tmp_path / "config.json").write_text("{}", encoding="utf-8")
|
||||
pool = tmp_path / "mail_credentials.txt"
|
||||
_write_pool(pool, 3)
|
||||
with pool.open("a", encoding="utf-8") as f:
|
||||
f.write("z@outlook.com----p----c----r\n")
|
||||
|
||||
st = mail_ops.get_pool_stats(tmp_path)
|
||||
assert st["total"] == 4
|
||||
assert st["by_domain"]["hotmail.com"] == 3
|
||||
assert st["by_domain"]["outlook.com"] == 1
|
||||
assert "known_domains" in st
|
||||
assert "quarantinable_statuses" in st
|
||||
blob = str(st)
|
||||
assert "pw0" not in blob
|
||||
assert "rt0" not in blob
|
||||
|
||||
|
||||
def test_live_path_rejects_escape(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.delenv("HOTMAIL_ACCOUNTS_FILE", raising=False)
|
||||
# relative escape via config
|
||||
(tmp_path / "config.json").write_text(
|
||||
'{"hotmail_accounts_file": "../../../etc/passwd"}',
|
||||
encoding="utf-8",
|
||||
)
|
||||
path = mail_ops._live_path(tmp_path)
|
||||
assert path == (tmp_path.resolve() / "mail_credentials.txt")
|
||||
|
||||
|
||||
def test_probe_mail_uses_injectable_via_core(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.delenv("HOTMAIL_ACCOUNTS_FILE", raising=False)
|
||||
(tmp_path / "config.json").write_text("{}", encoding="utf-8")
|
||||
pool = tmp_path / "mail_credentials.txt"
|
||||
_write_pool(pool, 6)
|
||||
|
||||
def fake_refresh(acc):
|
||||
if acc.email.startswith("u0") or acc.email.startswith("u2"):
|
||||
return True, "", None
|
||||
if acc.email.startswith("u1"):
|
||||
return False, "Connection timed out", None
|
||||
return False, "AADSTS700082: grant is expired", None
|
||||
|
||||
import mail_pool_probe as core
|
||||
|
||||
monkeypatch.setattr(core, "_default_refresh", fake_refresh)
|
||||
|
||||
out = mail_ops.probe_mail(
|
||||
tmp_path,
|
||||
domains=["hotmail.com"],
|
||||
limit=4,
|
||||
seed=1,
|
||||
concurrency=2,
|
||||
)
|
||||
assert out["probed"] == 4
|
||||
assert out["ok"] + out["dead"] == 4
|
||||
assert "quarantinable" in out
|
||||
assert out.get("mode") == "sample"
|
||||
assert out.get("offset") is None
|
||||
for row in out["results"]:
|
||||
assert set(row.keys()) == {
|
||||
"email",
|
||||
"domain",
|
||||
"status",
|
||||
"reason",
|
||||
"ms_error",
|
||||
"quarantinable",
|
||||
}
|
||||
assert "pw" not in row["email"]
|
||||
if row["status"] == "network_error":
|
||||
assert row["quarantinable"] is False
|
||||
if row["status"] == "grant_expired":
|
||||
assert row["quarantinable"] is True
|
||||
|
||||
|
||||
def test_probe_mail_sequential_offset(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.delenv("HOTMAIL_ACCOUNTS_FILE", raising=False)
|
||||
(tmp_path / "config.json").write_text("{}", encoding="utf-8")
|
||||
pool = tmp_path / "mail_credentials.txt"
|
||||
_write_pool(pool, 5)
|
||||
|
||||
import mail_pool_probe as core
|
||||
|
||||
monkeypatch.setattr(core, "_default_refresh", lambda acc: (True, "", None))
|
||||
|
||||
w0 = mail_ops.probe_mail(
|
||||
tmp_path,
|
||||
domains=["hotmail.com"],
|
||||
limit=2,
|
||||
offset=0,
|
||||
concurrency=2,
|
||||
)
|
||||
assert w0["mode"] == "sequential"
|
||||
assert w0["offset"] == 0
|
||||
assert w0["next_offset"] == 2
|
||||
assert w0["done"] is False
|
||||
assert w0["pool_filtered_total"] == 5
|
||||
assert [r["email"] for r in w0["results"]] == [
|
||||
"u0@hotmail.com",
|
||||
"u1@hotmail.com",
|
||||
]
|
||||
|
||||
w1 = mail_ops.probe_mail(
|
||||
tmp_path,
|
||||
domains=["hotmail.com"],
|
||||
limit=2,
|
||||
offset=w0["next_offset"],
|
||||
concurrency=2,
|
||||
)
|
||||
assert w1["offset"] == 2
|
||||
assert w1["next_offset"] == 4
|
||||
assert w1["done"] is False
|
||||
|
||||
w2 = mail_ops.probe_mail(
|
||||
tmp_path,
|
||||
domains=["hotmail.com"],
|
||||
limit=2,
|
||||
offset=w1["next_offset"],
|
||||
concurrency=2,
|
||||
)
|
||||
assert w2["offset"] == 4
|
||||
assert w2["next_offset"] == 5
|
||||
assert w2["done"] is True
|
||||
assert w2["probed"] == 1
|
||||
|
||||
|
||||
def test_quarantine_mail(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.delenv("HOTMAIL_ACCOUNTS_FILE", raising=False)
|
||||
(tmp_path / "config.json").write_text("{}", encoding="utf-8")
|
||||
pool = tmp_path / "mail_credentials.txt"
|
||||
_write_pool(pool, 4)
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
mail_ops.quarantine_mail(tmp_path, [])
|
||||
|
||||
out = mail_ops.quarantine_mail(
|
||||
tmp_path,
|
||||
["u1@hotmail.com", "u3@hotmail.com"],
|
||||
reason="probe:test",
|
||||
)
|
||||
assert out["removed"] == 2
|
||||
assert out["live_total_after"] == 2
|
||||
assert Path(out["backup_path"]).is_file()
|
||||
remaining = pool.read_text(encoding="utf-8")
|
||||
assert "u1@hotmail.com" not in remaining
|
||||
assert "u0@hotmail.com" in remaining
|
||||
dead = Path(out["dead_path"]).read_text(encoding="utf-8")
|
||||
assert "u1@hotmail.com----pw1----cid1----rt1----probe:test----" in dead
|
||||
|
||||
|
||||
def test_compact_mail(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.delenv("HOTMAIL_ACCOUNTS_FILE", raising=False)
|
||||
(tmp_path / "config.json").write_text("{}", encoding="utf-8")
|
||||
pool = tmp_path / "mail_credentials.txt"
|
||||
pool.write_text(
|
||||
"u0@hotmail.com----pw0----cid0----rt0\n"
|
||||
"U0@hotmail.com----pwX----cidX----rtX\n"
|
||||
"u1@hotmail.com----pw1----cid1----rt1\n"
|
||||
"junk-line\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
st = mail_ops.get_pool_stats(tmp_path)
|
||||
assert st["total"] == 2
|
||||
assert st["duplicate_extra"] == 1
|
||||
assert st["invalid_lines"] == 1
|
||||
assert st["needs_compact"] is True
|
||||
|
||||
preview = mail_ops.compact_mail(tmp_path, dry_run=True)
|
||||
assert preview["dry_run"] is True
|
||||
assert preview["duplicate_extra"] == 1
|
||||
assert "junk-line" in pool.read_text(encoding="utf-8")
|
||||
|
||||
out = mail_ops.compact_mail(tmp_path, dry_run=False)
|
||||
assert out["changed"] is True
|
||||
assert out["unique"] == 2
|
||||
assert out["invalid_dropped"] == 1
|
||||
text = pool.read_text(encoding="utf-8")
|
||||
assert "u0@hotmail.com----pw0----cid0----rt0" in text
|
||||
assert "u1@hotmail.com----pw1----cid1----rt1" in text
|
||||
assert "pwX" not in text
|
||||
assert "junk-line" not in text
|
||||
# public result: emails ok, secrets must not appear
|
||||
blob = str(out)
|
||||
assert "pw0" not in blob
|
||||
assert "cid0" not in blob
|
||||
assert "rt0" not in blob
|
||||
|
||||
|
||||
def test_routes_http_errors(tmp_path: Path, monkeypatch):
|
||||
"""Route layer maps missing pool → 404, empty emails → 400."""
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from apps.control_api.auth import require_auth
|
||||
from apps.control_api import routes_mail
|
||||
from apps.control_api import settings as settings_mod
|
||||
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.delenv("HOTMAIL_ACCOUNTS_FILE", raising=False)
|
||||
monkeypatch.delenv("REGISTER_PROJECT_ROOT", raising=False)
|
||||
(tmp_path / "config.json").write_text("{}", encoding="utf-8")
|
||||
|
||||
class _S:
|
||||
project_root = tmp_path
|
||||
|
||||
# routes_mail does `from ...settings import get_settings` — must patch the
|
||||
# bound name on the routes module, not only settings.get_settings.
|
||||
# Also clear lru_cache so a prior config TestClient cannot pin another root.
|
||||
settings_mod.clear_settings_cache()
|
||||
monkeypatch.setattr(settings_mod, "get_settings", lambda: _S())
|
||||
monkeypatch.setattr(routes_mail, "get_settings", lambda: _S())
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
async def _ok():
|
||||
return True
|
||||
|
||||
app.dependency_overrides[require_auth] = _ok
|
||||
app.include_router(routes_mail.router, dependencies=[])
|
||||
client = TestClient(app)
|
||||
|
||||
r = client.get("/api/mail/pool")
|
||||
# empty/missing pool still returns stats with total=0
|
||||
assert r.status_code == 200
|
||||
assert r.json()["total"] == 0
|
||||
|
||||
r = client.post("/api/mail/probe", json={"limit": 5, "domains": ["hotmail.com"]})
|
||||
assert r.status_code == 404
|
||||
|
||||
r = client.post("/api/mail/quarantine", json={"emails": []})
|
||||
assert r.status_code == 422 # pydantic min_length
|
||||
|
||||
_write_pool(tmp_path / "mail_credentials.txt", 2)
|
||||
r = client.post(
|
||||
"/api/mail/quarantine",
|
||||
json={"emails": [" "], "reason": "x"},
|
||||
)
|
||||
# stripped empty → 400 from handler
|
||||
assert r.status_code == 400
|
||||
|
||||
# compact endpoint
|
||||
with (tmp_path / "mail_credentials.txt").open("a", encoding="utf-8") as f:
|
||||
f.write("u0@hotmail.com----dup----dup----dup\n")
|
||||
r = client.post("/api/mail/compact", json={"dry_run": True})
|
||||
assert r.status_code == 200
|
||||
body = r.json()
|
||||
assert body["dry_run"] is True
|
||||
assert body["duplicate_extra"] >= 1
|
||||
assert "summary" in body
|
||||
r = client.post("/api/mail/compact", json={"dry_run": False})
|
||||
assert r.status_code == 200
|
||||
assert r.json()["unique"] == 2
|
||||
|
||||
# sequential offset probe (injectable refresh, no network)
|
||||
import mail_pool_probe as core
|
||||
|
||||
monkeypatch.setattr(core, "_default_refresh", lambda acc: (True, "", None))
|
||||
r = client.post(
|
||||
"/api/mail/probe",
|
||||
json={
|
||||
"domains": ["hotmail.com"],
|
||||
"limit": 1,
|
||||
"offset": 0,
|
||||
"concurrency": 1,
|
||||
"wall_seconds": 30,
|
||||
},
|
||||
)
|
||||
assert r.status_code == 200, r.text
|
||||
body = r.json()
|
||||
assert body["mode"] == "sequential"
|
||||
assert body["offset"] == 0
|
||||
assert body["next_offset"] == 1
|
||||
assert body["done"] is False
|
||||
assert body["pool_filtered_total"] == 2
|
||||
assert body["probed"] == 1
|
||||
# validation: limit > 500 / negative offset rejected by pydantic
|
||||
r = client.post("/api/mail/probe", json={"limit": 501, "offset": 0})
|
||||
assert r.status_code == 422
|
||||
r = client.post("/api/mail/probe", json={"limit": 1, "offset": -1})
|
||||
assert r.status_code == 422
|
||||
|
||||
|
||||
def test_list_cloudflare_domains_requires_base(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.chdir(tmp_path)
|
||||
(tmp_path / "config.json").write_text("{}", encoding="utf-8")
|
||||
monkeypatch.delenv("CLOUDFLARE_API_BASE", raising=False)
|
||||
monkeypatch.delenv("CLOUDFLARE_API_KEY", raising=False)
|
||||
try:
|
||||
mail_ops.list_cloudflare_domains(tmp_path)
|
||||
assert False, "expected ValueError"
|
||||
except ValueError as exc:
|
||||
assert "cloudflare_api_base" in str(exc)
|
||||
|
||||
|
||||
def test_list_cloudflare_domains_parses_and_redacts(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.chdir(tmp_path)
|
||||
(tmp_path / "config.json").write_text(
|
||||
'{"cloudflare_api_base":"https://mail.example","cloudflare_api_key":"sekret1234","defaultDomains":"a.com"}',
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
class _Resp:
|
||||
status = 200
|
||||
|
||||
def read(self):
|
||||
return b'{"results":[{"domain":"a.com"},"b.com",{"name":"c.com"}]}'
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
return False
|
||||
|
||||
def _fake_urlopen(req, timeout=15):
|
||||
assert str(req.full_url).startswith("https://mail.example/domains")
|
||||
# Browser UA required to avoid CF Error 1010
|
||||
ua = req.headers.get("User-agent") or req.headers.get("User-Agent") or ""
|
||||
if not ua and hasattr(req, "get_header"):
|
||||
ua = req.get_header("User-agent") or req.get_header("User-Agent") or ""
|
||||
assert "Mozilla" in str(ua)
|
||||
return _Resp()
|
||||
|
||||
monkeypatch.setattr(mail_ops, "urlopen", _fake_urlopen)
|
||||
out = mail_ops.list_cloudflare_domains(tmp_path)
|
||||
assert out["domains"] == ["a.com", "b.com", "c.com"]
|
||||
assert out["selected"] == ["a.com"]
|
||||
assert out["has_api_key"] is True
|
||||
assert out["path"] == "/domains"
|
||||
blob = str(out)
|
||||
assert "sekret1234" not in blob
|
||||
|
||||
|
||||
def test_list_cloudflare_domains_falls_back_open_settings(tmp_path: Path, monkeypatch):
|
||||
"""cloudflare_temp_email: /api/domains needs address JWT → 401; open_api/settings is public."""
|
||||
from urllib.error import HTTPError
|
||||
from io import BytesIO
|
||||
|
||||
monkeypatch.chdir(tmp_path)
|
||||
(tmp_path / "config.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"cloudflare_api_base": "https://temp-mail.example",
|
||||
"cloudflare_path_domains": "/api/domains",
|
||||
"cloudflare_auth_mode": "none",
|
||||
"defaultDomains": "keep.me",
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
class _Ok:
|
||||
status = 200
|
||||
|
||||
def read(self):
|
||||
return (
|
||||
b'{"title":"CF","domains":["mangoqwq.com","mangoq.ccwu.cc"],'
|
||||
b'"defaultDomains":["mangoqwq.com"]}'
|
||||
)
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
return False
|
||||
|
||||
calls: list[str] = []
|
||||
|
||||
def _fake_urlopen(req, timeout=15):
|
||||
url = str(req.full_url)
|
||||
calls.append(url)
|
||||
ua = req.headers.get("User-agent") or req.headers.get("User-Agent") or ""
|
||||
assert "Mozilla" in str(ua)
|
||||
if url.endswith("/api/domains"):
|
||||
raise HTTPError(
|
||||
url,
|
||||
401,
|
||||
"Unauthorized",
|
||||
hdrs=None, # type: ignore[arg-type]
|
||||
fp=BytesIO(b"Invalid address credential"),
|
||||
)
|
||||
if url.endswith("/open_api/settings"):
|
||||
# Public path: no Authorization
|
||||
auth = req.headers.get("Authorization") or req.headers.get("authorization")
|
||||
assert not auth
|
||||
return _Ok()
|
||||
raise AssertionError(f"unexpected url {url}")
|
||||
|
||||
monkeypatch.setattr(mail_ops, "urlopen", _fake_urlopen)
|
||||
out = mail_ops.list_cloudflare_domains(tmp_path)
|
||||
assert out["domains"] == ["mangoqwq.com", "mangoq.ccwu.cc"]
|
||||
assert out["path"] == "/open_api/settings"
|
||||
assert out["selected"] == ["keep.me"]
|
||||
assert out["count"] == 2
|
||||
assert any(u.endswith("/api/domains") for u in calls)
|
||||
assert any(u.endswith("/open_api/settings") for u in calls)
|
||||
@@ -0,0 +1,508 @@
|
||||
"""Catalog + Clash node ops for control plane."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
from apps.control_api import nodes_ops
|
||||
|
||||
|
||||
def test_catalog_add_list_delete(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.delenv("REGISTER_NODES_FILE", raising=False)
|
||||
monkeypatch.delenv("NODES_FILE", raising=False)
|
||||
|
||||
added = nodes_ops.add_catalog_node(
|
||||
tmp_path,
|
||||
url="http://user:pass@10.0.0.1:8080",
|
||||
label="lab1",
|
||||
tags=["dc"],
|
||||
tier=0,
|
||||
)
|
||||
assert added["ok"] is True
|
||||
nid = added["node"]["id"]
|
||||
|
||||
listing = nodes_ops.list_catalog(tmp_path, page_size=0)
|
||||
assert listing["total"] == 1
|
||||
assert listing["enabled"] == 1
|
||||
assert listing["nodes"][0]["label"] == "lab1"
|
||||
assert listing["nodes"][0]["tier"] == 0
|
||||
|
||||
# duplicate rejected
|
||||
dup = nodes_ops.add_catalog_node(tmp_path, url="http://user:pass@10.0.0.1:8080")
|
||||
assert dup["ok"] is False
|
||||
assert dup["error"] == "duplicate"
|
||||
|
||||
toggled = nodes_ops.set_catalog_enabled(tmp_path, nid, False)
|
||||
assert toggled["ok"] is True
|
||||
assert toggled["node"]["enabled"] is False
|
||||
|
||||
deleted = nodes_ops.delete_catalog_node(tmp_path, nid)
|
||||
assert deleted["ok"] is True
|
||||
assert deleted["total"] == 0
|
||||
|
||||
|
||||
def test_catalog_filter_and_paginate(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.delenv("REGISTER_NODES_FILE", raising=False)
|
||||
monkeypatch.delenv("NODES_FILE", raising=False)
|
||||
for i in range(5):
|
||||
nodes_ops.add_catalog_node(
|
||||
tmp_path,
|
||||
url=f"http://10.0.0.{i}:8080",
|
||||
label=f"node-{i}",
|
||||
tags=["dc"] if i % 2 == 0 else ["res"],
|
||||
tier=0 if i % 2 == 0 else 1,
|
||||
)
|
||||
page1 = nodes_ops.list_catalog(tmp_path, page=1, page_size=2, sort="label")
|
||||
assert page1["total"] == 5
|
||||
assert page1["filtered"] == 5
|
||||
assert page1["page"] == 1
|
||||
assert page1["page_size"] == 2
|
||||
assert page1["pages"] == 3
|
||||
assert len(page1["nodes"]) == 2
|
||||
assert page1["nodes"][0]["label"] == "node-0"
|
||||
|
||||
q = nodes_ops.list_catalog(tmp_path, q="node-3", page_size=50)
|
||||
assert q["filtered"] == 1
|
||||
assert q["nodes"][0]["label"] == "node-3"
|
||||
|
||||
tier1 = nodes_ops.list_catalog(tmp_path, tier=1, page_size=50)
|
||||
assert tier1["filtered"] == 2
|
||||
assert all(n["tier"] == 1 for n in tier1["nodes"])
|
||||
|
||||
|
||||
def test_test_catalog_nodes_persists_probe(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.chdir(tmp_path)
|
||||
nodes_ops.add_catalog_node(tmp_path, url="socks5://1.2.3.4:1080", label="p1")
|
||||
|
||||
def fake_probe(n, timeout=12.0):
|
||||
n.last_ok = True
|
||||
n.last_ms = 42
|
||||
n.last_ip = "9.9.9.9"
|
||||
n.last_error = ""
|
||||
return {"ok": True, "id": n.id, "ms": 42, "ip": "9.9.9.9"}
|
||||
|
||||
monkeypatch.setattr(nodes_ops, "probe_node", fake_probe)
|
||||
out = nodes_ops.test_catalog_nodes(tmp_path, limit=10)
|
||||
assert out["tested"] == 1
|
||||
assert out["healthy"] == 1
|
||||
listing = nodes_ops.list_catalog(tmp_path)
|
||||
assert listing["healthy"] == 1
|
||||
assert listing["nodes"][0]["health"] == "ok"
|
||||
assert listing["nodes"][0]["last_ms"] == 42
|
||||
|
||||
|
||||
def test_list_clash_nodes_parses_groups_and_scores(tmp_path: Path, monkeypatch):
|
||||
scores = {
|
||||
"nodes": {
|
||||
"HK-01": {"score": 1.25, "cool_until": None, "success": 3, "fail": 0},
|
||||
}
|
||||
}
|
||||
(tmp_path / "output").mkdir()
|
||||
score_path = tmp_path / "output" / "node_scores.json"
|
||||
score_path.write_text(json.dumps(scores), encoding="utf-8")
|
||||
# Hermetic: suite may leave NODE_SCORE_PATH pointing elsewhere.
|
||||
monkeypatch.setenv("NODE_SCORE_PATH", str(score_path))
|
||||
|
||||
def fake_req(path, *, secret, method="GET", body=None, timeout=8.0):
|
||||
assert path == "/proxies"
|
||||
return {
|
||||
"proxies": {
|
||||
"🎯Grok注册": {
|
||||
"type": "Selector",
|
||||
"now": "HK-01",
|
||||
"all": ["HK-01", "US-02"],
|
||||
},
|
||||
"HK-01": {
|
||||
"type": "ss",
|
||||
"udp": True,
|
||||
"history": [{"delay": 88}],
|
||||
},
|
||||
"US-02": {
|
||||
"type": "vmess",
|
||||
"history": [{"delay": 0}],
|
||||
},
|
||||
"DIRECT": {"type": "Direct"},
|
||||
}
|
||||
}
|
||||
|
||||
monkeypatch.setattr(nodes_ops, "_clash_request", fake_req)
|
||||
monkeypatch.setattr(nodes_ops, "_clash_secret", lambda root: "sec")
|
||||
out = nodes_ops.list_clash_nodes(tmp_path)
|
||||
assert out["ok"] is True
|
||||
assert out["leaf_count"] == 2
|
||||
leaves = {x["name"]: x for x in out["leaves"]}
|
||||
assert leaves["HK-01"]["health"] == "ok"
|
||||
assert leaves["HK-01"]["priority_score"] == 1.25
|
||||
assert leaves["HK-01"]["in_register_pool"] is True
|
||||
assert leaves["US-02"]["health"] == "fail"
|
||||
assert any(g["name"] == "🎯Grok注册" and g["register_relevant"] for g in out["groups"])
|
||||
|
||||
|
||||
def test_test_clash_nodes_delay(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
nodes_ops,
|
||||
"list_clash_nodes",
|
||||
lambda root: {
|
||||
"ok": True,
|
||||
"leaves": [
|
||||
{"name": "A", "in_register_pool": True},
|
||||
{"name": "B", "in_register_pool": False},
|
||||
],
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(nodes_ops, "_clash_secret", lambda root: "s")
|
||||
|
||||
def fake_req(path, *, secret, method="GET", body=None, timeout=8.0):
|
||||
if path.startswith("/proxies/A/delay"):
|
||||
return {"delay": 120}
|
||||
if path.startswith("/proxies/B/delay"):
|
||||
return {"delay": 0}
|
||||
return {}
|
||||
|
||||
monkeypatch.setattr(nodes_ops, "_clash_request", fake_req)
|
||||
out = nodes_ops.test_clash_nodes(tmp_path, names=["A", "B"])
|
||||
assert out["tested"] == 2
|
||||
assert out["healthy"] == 1
|
||||
by = {r["name"]: r for r in out["results"]}
|
||||
assert by["A"]["ok"] is True
|
||||
assert by["A"]["delay_ms"] == 120
|
||||
assert by["B"]["ok"] is False
|
||||
|
||||
|
||||
def test_parse_subscription_base64_uri_and_meta_filter():
|
||||
import base64
|
||||
|
||||
lines = "\n".join(
|
||||
[
|
||||
"ss://YWVzLTI1Ni1nY206cGFzcw@1.2.3.4:8388#HK-01",
|
||||
"vless://11111111-1111-1111-1111-111111111111@5.6.7.8:443?type=ws&security=tls&sni=a.com#US-02",
|
||||
"hysteria2://secret@9.9.9.9:443?sni=hy.example&insecure=1#HY-03",
|
||||
"ss://YWVzLTI1Ni1nY206cGFzcw@1.2.3.4:8389#剩余流量:99GB",
|
||||
"ss://YWVzLTI1Ni1nY206cGFzcw@1.2.3.4:8390#套餐到期:2099",
|
||||
]
|
||||
)
|
||||
body = base64.b64encode(lines.encode("utf-8")).decode("ascii")
|
||||
proxies, info = nodes_ops.parse_subscription_proxies(body, source="test", prefix="SUB")
|
||||
assert info["base64"] is True
|
||||
assert info["format"] == "uri_list"
|
||||
assert info["skipped_meta"] >= 2
|
||||
assert info["imported"] == 3
|
||||
names = [p["name"] for p in proxies]
|
||||
assert all(n.startswith("SUB-") for n in names)
|
||||
types = {p["type"] for p in proxies}
|
||||
assert "ss" in types
|
||||
assert "vless" in types
|
||||
assert "hysteria2" in types
|
||||
|
||||
|
||||
def test_merge_proxies_replace_prefix(tmp_path: Path, monkeypatch):
|
||||
yaml = nodes_ops._require_yaml()
|
||||
cfg = tmp_path / "config.yaml"
|
||||
data = {
|
||||
"proxies": [
|
||||
{"name": "KEEP-1", "type": "ss", "server": "1.1.1.1", "port": 1, "cipher": "aes-256-gcm", "password": "x"},
|
||||
{"name": "SUB-old", "type": "ss", "server": "2.2.2.2", "port": 2, "cipher": "aes-256-gcm", "password": "x"},
|
||||
],
|
||||
"proxy-groups": [
|
||||
{"name": "🎯Grok注册", "type": "select", "proxies": ["KEEP-1", "SUB-old", "DIRECT"]},
|
||||
],
|
||||
}
|
||||
cfg.write_text(yaml.dump(data, allow_unicode=True, sort_keys=False), encoding="utf-8")
|
||||
new_proxies = [
|
||||
{"name": "SUB-new", "type": "ss", "server": "3.3.3.3", "port": 3, "cipher": "aes-256-gcm", "password": "y"},
|
||||
]
|
||||
out = nodes_ops.merge_proxies_into_clash_config(
|
||||
cfg,
|
||||
new_proxies,
|
||||
groups=["🎯Grok注册"],
|
||||
mode="replace_prefix",
|
||||
prefix="SUB",
|
||||
)
|
||||
assert out["ok"] is True
|
||||
assert out["removed_prefix"] == 1
|
||||
assert out["added"] == 1
|
||||
loaded = yaml.safe_load(cfg.read_text(encoding="utf-8"))
|
||||
names = [p["name"] for p in loaded["proxies"]]
|
||||
assert "KEEP-1" in names
|
||||
assert "SUB-new" in names
|
||||
assert "SUB-old" not in names
|
||||
group = next(g for g in loaded["proxy-groups"] if g["name"] == "🎯Grok注册")
|
||||
assert "SUB-new" in group["proxies"]
|
||||
assert "SUB-old" not in group["proxies"]
|
||||
assert "KEEP-1" in group["proxies"]
|
||||
|
||||
|
||||
def test_import_clash_subscription_dry_run(tmp_path: Path, monkeypatch):
|
||||
import base64
|
||||
|
||||
body = base64.b64encode(
|
||||
b"ss://YWVzLTI1Ni1nY206cGFzcw@1.2.3.4:8388#HK-dry\n"
|
||||
).decode("ascii")
|
||||
monkeypatch.setattr(
|
||||
nodes_ops,
|
||||
"fetch_subscription_body",
|
||||
lambda url, timeout=25.0: (body, {"http_status": 200, "bytes": len(body)}),
|
||||
)
|
||||
monkeypatch.setattr(nodes_ops, "clash_config_paths", lambda: [])
|
||||
out = nodes_ops.import_clash_subscription(
|
||||
tmp_path,
|
||||
url="https://example.com/sub/abc",
|
||||
group="🎯Grok注册",
|
||||
prefix="SUB",
|
||||
mode="merge",
|
||||
dry_run=True,
|
||||
reload=False,
|
||||
)
|
||||
assert out["ok"] is True
|
||||
assert out["dry_run"] is True
|
||||
assert out["parse"]["imported"] == 1
|
||||
assert "预检成功" in out["message"]
|
||||
|
||||
|
||||
def test_import_clash_subscription_fetch_error(tmp_path: Path, monkeypatch):
|
||||
def boom(url, timeout=25.0):
|
||||
raise RuntimeError("fetch failed: timeout")
|
||||
|
||||
monkeypatch.setattr(nodes_ops, "fetch_subscription_body", boom)
|
||||
out = nodes_ops.import_clash_subscription(
|
||||
tmp_path,
|
||||
url="https://example.com/sub/bad",
|
||||
dry_run=True,
|
||||
)
|
||||
assert out["ok"] is False
|
||||
assert out["stage"] == "fetch"
|
||||
assert out["error"] == "fetch_failed"
|
||||
|
||||
|
||||
def test_parse_subscription_filters_placeholder_banner_nodes():
|
||||
"""Airport "device-over-quota" banner nodes must never enter the pool.
|
||||
|
||||
When a token is invalid or the plan is over the device cap, some airports
|
||||
return a Clash YAML whose only ``proxies`` are fake SS rows pointing at
|
||||
127.0.0.1:65535. parse must drop them and raise SubscriptionFilterError
|
||||
with a stable machine code so the UI toast can branch.
|
||||
|
||||
Two flavors are tested together: a banner row whose NAME carries a meta
|
||||
marker (设备数量…, counted as meta), and a plain loopback-dummy row with a
|
||||
clean name (counted as placeholder). Both are dropped; the placeholder one
|
||||
lands in ``skipped_placeholder`` and the union raises the stable code.
|
||||
"""
|
||||
import base64
|
||||
|
||||
yaml = nodes_ops._require_yaml()
|
||||
banner_cfg = {
|
||||
"proxies": [
|
||||
# meta-marker banner name — caught by _is_meta_proxy_name
|
||||
{
|
||||
"name": "设备数量超过套餐允许值!",
|
||||
"type": "ss",
|
||||
"server": "127.0.0.1",
|
||||
"port": 65535,
|
||||
"cipher": "aes-256-gcm",
|
||||
"password": "x",
|
||||
},
|
||||
# clean name but loopback+dummy port — caught by loopback_dummy
|
||||
{
|
||||
"name": "node-x",
|
||||
"type": "ss",
|
||||
"server": "127.0.0.1",
|
||||
"port": 65535,
|
||||
"cipher": "aes-256-gcm",
|
||||
"password": "x",
|
||||
},
|
||||
]
|
||||
}
|
||||
body = base64.b64encode(
|
||||
yaml.dump(banner_cfg, allow_unicode=True).encode("utf-8")
|
||||
).decode("ascii")
|
||||
with pytest.raises(nodes_ops.SubscriptionFilterError) as ei:
|
||||
nodes_ops.parse_subscription_proxies(body, source="banner", prefix="X")
|
||||
err = ei.value
|
||||
assert err.code == "subscription_placeholder_only"
|
||||
assert err.info["skipped_placeholder"] >= 1 # the loopback dummy
|
||||
assert err.info["skipped_meta"] >= 1 # the meta-marker banner
|
||||
assert err.info["imported"] == 0
|
||||
|
||||
|
||||
def test_parse_subscription_mixed_real_and_placeholder_keeps_real():
|
||||
"""A loopback placeholder port-65535 row is dropped; a real node survives."""
|
||||
import base64
|
||||
|
||||
yaml = nodes_ops._require_yaml()
|
||||
mixed = {
|
||||
"proxies": [
|
||||
{"name": "real-HK-1", "type": "ss", "server": "1.2.3.4", "port": 8388,
|
||||
"cipher": "aes-256-gcm", "password": "x"},
|
||||
# clean name → placeholder path via loopback_dummy
|
||||
{"name": "ph-1", "type": "ss", "server": "127.0.0.1", "port": 65535,
|
||||
"cipher": "aes-256-gcm", "password": "x"},
|
||||
]
|
||||
}
|
||||
body = base64.b64encode(yaml.dump(mixed, allow_unicode=True).encode("utf-8")).decode("ascii")
|
||||
proxies, info = nodes_ops.parse_subscription_proxies(body, source="mixed", prefix="MIX")
|
||||
assert info["imported"] == 1
|
||||
assert info["skipped_placeholder"] >= 1
|
||||
assert proxies[0]["server"] == "1.2.3.4"
|
||||
|
||||
|
||||
def test_import_clash_subscription_surfaces_subscription_filter_code(tmp_path, monkeypatch):
|
||||
"""import_clash_subscription must forward the SubscriptionFilterError code
|
||||
(not collapse it to parse_failed) so the UI can branch on it."""
|
||||
import base64
|
||||
|
||||
yaml = nodes_ops._require_yaml()
|
||||
banner = {
|
||||
"proxies": [
|
||||
{"name": "ph-node", "type": "ss", "server": "127.0.0.1", "port": 65535,
|
||||
"cipher": "aes-256-gcm", "password": "x"},
|
||||
]
|
||||
}
|
||||
body = base64.b64encode(yaml.dump(banner, allow_unicode=True).encode("utf-8")).decode("ascii")
|
||||
monkeypatch.setattr(
|
||||
nodes_ops,
|
||||
"fetch_subscription_body",
|
||||
lambda url, timeout=25.0: (body, {"http_status": 200, "bytes": len(body)}),
|
||||
)
|
||||
out = nodes_ops.import_clash_subscription(
|
||||
tmp_path,
|
||||
url="https://example.com/sub/over",
|
||||
dry_run=True,
|
||||
)
|
||||
assert out["ok"] is False
|
||||
assert out["stage"] == "parse"
|
||||
assert out["error"] == "subscription_placeholder_only", out
|
||||
assert out["error"] != "parse_failed"
|
||||
|
||||
|
||||
def test_remove_proxies_by_prefix_from_config(tmp_path: Path):
|
||||
yaml = nodes_ops._require_yaml()
|
||||
cfg = tmp_path / "config.yaml"
|
||||
data = {
|
||||
"proxies": [
|
||||
{"name": "KEEP-1", "type": "ss", "server": "1.1.1.1", "port": 1, "cipher": "aes-256-gcm", "password": "x"},
|
||||
{"name": "YF-dead", "type": "ss", "server": "2.2.2.2", "port": 2, "cipher": "aes-256-gcm", "password": "x"},
|
||||
{"name": "YF", "type": "ss", "server": "3.3.3.3", "port": 3, "cipher": "aes-256-gcm", "password": "x"},
|
||||
{"name": "YFAKE-1", "type": "ss", "server": "4.4.4.4", "port": 4, "cipher": "aes-256-gcm", "password": "x"},
|
||||
],
|
||||
"proxy-groups": [
|
||||
{
|
||||
"name": "🎯Grok注册",
|
||||
"type": "select",
|
||||
"proxies": ["KEEP-1", "YF-dead", "YF", "YFAKE-1", "DIRECT"],
|
||||
},
|
||||
],
|
||||
}
|
||||
cfg.write_text(yaml.dump(data, allow_unicode=True, sort_keys=False), encoding="utf-8")
|
||||
out = nodes_ops.remove_proxies_by_prefix_from_config(cfg, prefix="YF")
|
||||
assert out["ok"] is True
|
||||
assert out["removed"] == 2
|
||||
loaded = yaml.safe_load(cfg.read_text(encoding="utf-8"))
|
||||
names = [p["name"] for p in loaded["proxies"]]
|
||||
assert "KEEP-1" in names
|
||||
assert "YFAKE-1" in names
|
||||
assert "YF-dead" not in names
|
||||
assert "YF" not in names
|
||||
group = next(g for g in loaded["proxy-groups"] if g["name"] == "🎯Grok注册")
|
||||
assert "YF-dead" not in group["proxies"]
|
||||
assert "KEEP-1" in group["proxies"]
|
||||
assert "YFAKE-1" in group["proxies"]
|
||||
|
||||
|
||||
def test_delete_clash_prefix_dry_run_and_write(tmp_path: Path, monkeypatch):
|
||||
yaml = nodes_ops._require_yaml()
|
||||
cfg = tmp_path / "config.yaml"
|
||||
data = {
|
||||
"proxies": [
|
||||
{"name": "KEEP-1", "type": "ss", "server": "1.1.1.1", "port": 1, "cipher": "aes-256-gcm", "password": "x"},
|
||||
{"name": "BP-1", "type": "ss", "server": "2.2.2.2", "port": 2, "cipher": "aes-256-gcm", "password": "x"},
|
||||
],
|
||||
"proxy-groups": [
|
||||
{"name": "🎯Grok注册", "type": "select", "proxies": ["KEEP-1", "BP-1"]},
|
||||
],
|
||||
}
|
||||
cfg.write_text(yaml.dump(data, allow_unicode=True, sort_keys=False), encoding="utf-8")
|
||||
monkeypatch.setattr(nodes_ops, "clash_config_paths", lambda: [cfg])
|
||||
|
||||
dry = nodes_ops.delete_clash_prefix(tmp_path, prefix="BP", dry_run=True, reload=False)
|
||||
assert dry["ok"] is True
|
||||
assert dry["dry_run"] is True
|
||||
assert dry["would_remove"] == 1
|
||||
# file untouched
|
||||
assert "BP-1" in [p["name"] for p in yaml.safe_load(cfg.read_text())["proxies"]]
|
||||
|
||||
real = nodes_ops.delete_clash_prefix(tmp_path, prefix="BP", dry_run=False, reload=False)
|
||||
assert real["ok"] is True
|
||||
assert real["removed"] == 1
|
||||
loaded = yaml.safe_load(cfg.read_text(encoding="utf-8"))
|
||||
names = [p["name"] for p in loaded["proxies"]]
|
||||
assert "BP-1" not in names
|
||||
assert "KEEP-1" in names
|
||||
|
||||
|
||||
def test_delete_clash_prefix_protected_without_force(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.setattr(nodes_ops, "clash_config_paths", lambda: [tmp_path / "config.yaml"])
|
||||
out = nodes_ops.delete_clash_prefix(tmp_path, prefix="GVPS", dry_run=False, force=False)
|
||||
assert out["ok"] is False
|
||||
assert out["error"] == "protected_prefix"
|
||||
|
||||
|
||||
def test_prune_clash_unhealthy_dry_run(tmp_path: Path, monkeypatch):
|
||||
yaml = nodes_ops._require_yaml()
|
||||
cfg = tmp_path / "config.yaml"
|
||||
data = {
|
||||
"proxies": [
|
||||
{"name": "A-1", "type": "ss", "server": "1.1.1.1", "port": 1, "cipher": "aes-256-gcm", "password": "x"},
|
||||
{"name": "A-2", "type": "ss", "server": "2.2.2.2", "port": 2, "cipher": "aes-256-gcm", "password": "x"},
|
||||
],
|
||||
"proxy-groups": [
|
||||
{"name": "🎯Grok注册", "type": "select", "proxies": ["A-1", "A-2", "DIRECT"]},
|
||||
],
|
||||
}
|
||||
cfg.write_text(yaml.dump(data, allow_unicode=True, sort_keys=False), encoding="utf-8")
|
||||
monkeypatch.setattr(nodes_ops, "clash_config_paths", lambda: [cfg])
|
||||
|
||||
def fake_test(root, *, names=None, timeout_ms=5000, limit=40, url=None):
|
||||
return {
|
||||
"ok": True,
|
||||
"tested": 2,
|
||||
"healthy": 1,
|
||||
"results": [
|
||||
{"name": "A-1", "ok": True, "delay_ms": 100},
|
||||
{"name": "A-2", "ok": False, "delay_ms": None, "error": "timeout"},
|
||||
],
|
||||
}
|
||||
|
||||
monkeypatch.setattr(nodes_ops, "test_clash_nodes", fake_test)
|
||||
out = nodes_ops.prune_clash_unhealthy(
|
||||
tmp_path,
|
||||
prefix="A",
|
||||
dry_run=True,
|
||||
reload=False,
|
||||
delete_defs=True,
|
||||
)
|
||||
assert out["ok"] is True
|
||||
assert out["dry_run"] is True
|
||||
assert out["unhealthy"] == 1
|
||||
assert out["would_remove"] == 1
|
||||
# still present
|
||||
names = [p["name"] for p in yaml.safe_load(cfg.read_text())["proxies"]]
|
||||
assert "A-2" in names
|
||||
|
||||
real = nodes_ops.prune_clash_unhealthy(
|
||||
tmp_path,
|
||||
prefix="A",
|
||||
dry_run=False,
|
||||
reload=False,
|
||||
delete_defs=True,
|
||||
)
|
||||
assert real["ok"] is True
|
||||
assert real["removed"] == 1
|
||||
names2 = [p["name"] for p in yaml.safe_load(cfg.read_text())["proxies"]]
|
||||
assert "A-1" in names2
|
||||
assert "A-2" not in names2
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Control API schema tests for Outlook product acceptance (Task 10)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from apps.control_api.schemas import StartRunRequest
|
||||
|
||||
|
||||
def test_start_run_accepts_outlook():
|
||||
request = StartRunRequest(
|
||||
product="outlook",
|
||||
target=1,
|
||||
extra_env={"GROK_REGISTER_OUTLOOK_LIVE": "0"},
|
||||
)
|
||||
assert request.product == "outlook"
|
||||
|
||||
|
||||
def test_start_run_accepts_typesafe():
|
||||
request = StartRunRequest(product="typesafe", target=1, kind="register_sh")
|
||||
assert request.product == "typesafe"
|
||||
|
||||
|
||||
def test_start_run_rejects_unknown_product():
|
||||
with pytest.raises(ValidationError):
|
||||
StartRunRequest(product="xai")
|
||||
|
||||
|
||||
def test_start_run_default_product_is_grok():
|
||||
assert StartRunRequest().product == "grok"
|
||||
|
||||
|
||||
def test_start_run_extra_env_carry_names_not_values_required():
|
||||
# extra_env is a str->str map for env NAMES/flags; this test only asserts
|
||||
# the type accepts the Outlook live-gate flag name without constraints.
|
||||
request = StartRunRequest(product="outlook", extra_env={"GROK_REGISTER_OUTLOOK_LIVE": "1"})
|
||||
assert request.extra_env == {"GROK_REGISTER_OUTLOOK_LIVE": "1"}
|
||||
|
||||
|
||||
def test_outlook_live_gate_env_name_passes_filter_extra_env():
|
||||
"""The live-gate env NAME must survive the control-plane allowlist filter
|
||||
so operators can turn the gate on via start_run extra_env. Only the NAME
|
||||
is exercised — never a secret value (the gate is a '1'/'0' flag)."""
|
||||
from apps.control_api.config_io import ENV_ALLOWLIST
|
||||
from apps.control_api.runs import filter_extra_env
|
||||
|
||||
assert "GROK_REGISTER_OUTLOOK_LIVE" in ENV_ALLOWLIST
|
||||
# The gate flag value is a tiny on/off string; the filter must accept it.
|
||||
assert filter_extra_env({"GROK_REGISTER_OUTLOOK_LIVE": "1"}) == {
|
||||
"GROK_REGISTER_OUTLOOK_LIVE": "1"
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
"""Progress / phase detection for control plane Runs UI."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from apps.control_api.progress import (
|
||||
build_progress,
|
||||
detect_phase,
|
||||
_parse_counters,
|
||||
build_batch_failures,
|
||||
)
|
||||
|
||||
|
||||
def _summary(**kw) -> str:
|
||||
import json
|
||||
|
||||
obj = {"event": "register_cli_summary"}
|
||||
obj.update(kw)
|
||||
return "SUMMARY_JSON " + json.dumps(obj, ensure_ascii=False, separators=(",", ":"))
|
||||
|
||||
|
||||
def test_build_batch_failures_none_when_empty():
|
||||
assert build_batch_failures("", "") is None
|
||||
assert build_batch_failures("[supervisor] boot\nnothing here", "") is None
|
||||
|
||||
|
||||
def test_build_batch_failures_aggregates_multiple_subs():
|
||||
sup = "\n".join(
|
||||
[
|
||||
"[supervisor] sub=1 start",
|
||||
_summary(reg_success=3, reg_fail=1, mint_fail=1,
|
||||
mint_fail_reason="invalid_grant", chat_fail=0),
|
||||
"[supervisor] sub=2 start",
|
||||
_summary(reg_success=2, reg_fail=2, mint_fail=1,
|
||||
mint_fail_reason="invalid_grant", fatal=True,
|
||||
fatal_reason="Turnstile 卡住"),
|
||||
"[supervisor] sub=3 start",
|
||||
_summary(reg_success=4, reg_fail=0, remote_live_fail=1),
|
||||
]
|
||||
)
|
||||
bf = build_batch_failures(sup, "")
|
||||
assert bf is not None
|
||||
assert bf["subs"] == 3
|
||||
assert bf["reg_success"] == 9
|
||||
assert bf["reg_fail"] == 3
|
||||
assert bf["mint_fail"] == 2
|
||||
assert bf["remote_live_fail"] == 1
|
||||
assert bf["fatal_subs"] == 1
|
||||
assert bf["attempts"] == 12 # 9 + 3
|
||||
# total_fail = reg_fail + mint_fail + chat_fail + inject_fail + live_fail
|
||||
assert bf["total_fail"] == 3 + 2 + 0 + 0 + 1
|
||||
assert bf["fail_rate"] == round(3 / 12, 4)
|
||||
# taxonomy breakdowns
|
||||
assert bf["mint_fail_reasons"][0] == ["invalid_grant", 2]
|
||||
assert bf["fatal_reasons"][0] == ["Turnstile 卡住", 1]
|
||||
# trend series
|
||||
assert bf["reg_fail_series"] == [1, 2, 0]
|
||||
assert bf["reg_success_series"] == [3, 2, 4]
|
||||
|
||||
|
||||
def test_build_batch_failures_includes_live_worker_summary():
|
||||
sup = _summary(reg_success=2, reg_fail=1)
|
||||
# Worker tail holds the freshest sub whose summary is not yet in supervisor.
|
||||
sub = _summary(reg_success=1, reg_fail=3)
|
||||
bf = build_batch_failures(sup, sub)
|
||||
assert bf["subs"] == 2
|
||||
assert bf["reg_fail"] == 4
|
||||
|
||||
|
||||
def test_build_progress_surfaces_batch_failures(tmp_path: Path):
|
||||
sup = tmp_path / "logs" / "run.supervisor.log"
|
||||
sup.parent.mkdir(parents=True, exist_ok=True)
|
||||
sup.write_text(
|
||||
"\n".join(
|
||||
[
|
||||
"[supervisor] sub=1 start",
|
||||
_summary(reg_success=1, reg_fail=2, mint_fail=1,
|
||||
mint_fail_reason="Access denied"),
|
||||
]
|
||||
)
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
prog = build_progress(tmp_path, sup_log=sup)
|
||||
bf = prog.get("batch_failures")
|
||||
assert bf is not None
|
||||
assert bf["reg_fail"] == 2
|
||||
assert bf["mint_fail_reasons"][0] == ["Access denied", 1]
|
||||
|
||||
|
||||
def test_detect_phase_otp_over_older_browser():
|
||||
text = "\n".join(
|
||||
[
|
||||
"browser_boot Chromium started",
|
||||
"填写注册表单 create_account",
|
||||
"waiting OTP mail_code extract_otp",
|
||||
]
|
||||
)
|
||||
p = detect_phase(text)
|
||||
assert p["phase"] == "otp"
|
||||
assert "OTP" in p["title"]
|
||||
|
||||
|
||||
def test_detect_phase_turnstile():
|
||||
p = detect_phase("Turnstile token_len=0 卡住 fail-fast")
|
||||
assert p["phase"] == "turnstile"
|
||||
|
||||
|
||||
def test_detect_phase_idle_empty():
|
||||
p = detect_phase("")
|
||||
assert p["phase"] == "idle"
|
||||
|
||||
|
||||
def test_parse_counters_supervisor_line():
|
||||
text = (
|
||||
"[supervisor] complete=575 consecutive_zero=0 sub=42 chunk=3 "
|
||||
"mode=ordinary accounts=120 + 84/615 gained_complete=2\n"
|
||||
)
|
||||
c = _parse_counters(text)
|
||||
assert c["complete"] == 575
|
||||
assert c["consecutive_zero"] == 0
|
||||
assert c["sub"] == 42
|
||||
assert c["chunk"] == 3
|
||||
assert c["mode"] == "ordinary"
|
||||
assert c["gained_last_sub"] == 2
|
||||
assert c["batch_gained"] == 84
|
||||
assert c["target"] == 615
|
||||
|
||||
|
||||
def test_parse_counters_goal_and_baseline():
|
||||
text = "\n".join(
|
||||
[
|
||||
"pid=1 mode=ordinary target_new=684 threads=1",
|
||||
"baseline total=506 complete=506 accounts=628 goal_complete=1190",
|
||||
"[supervisor] 02:16:51Z complete=591 (+85/684) accounts=755 attempt=63",
|
||||
"[supervisor] sub=63 gained_complete=2 consecutive_zero=0",
|
||||
]
|
||||
)
|
||||
c = _parse_counters(text)
|
||||
assert c["complete"] == 591
|
||||
assert c["goal_complete"] == 1190
|
||||
assert c["baseline_complete"] == 506
|
||||
assert c["target"] == 684
|
||||
assert c["target_new"] == 684
|
||||
assert c["batch_gained"] == 85
|
||||
assert c["remain"] == 1190 - 591
|
||||
assert c["batch_remain"] == 684 - 85
|
||||
|
||||
|
||||
def test_build_progress_steps_active_mint(tmp_path: Path):
|
||||
logs = tmp_path / "logs"
|
||||
logs.mkdir()
|
||||
sup = logs / "batch_dc1k_ns.supervisor.log"
|
||||
sup.write_text(
|
||||
"\n".join(
|
||||
[
|
||||
"[supervisor] baseline complete=10 goal_complete=1190 mode=ordinary",
|
||||
"[supervisor] sub=1 chunk=3 log=logs/batch.sub1_abc.log",
|
||||
"[supervisor] complete=12 consecutive_zero=0 sub=1",
|
||||
]
|
||||
)
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
worker = logs / "batch.sub1_abc.log"
|
||||
worker.write_text(
|
||||
"browser_boot ok\nregister form create_account\nmint token_ok wrote cpa_auths/xai-demo.json\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
prog = build_progress(tmp_path, sup_log=sup)
|
||||
assert prog["phase"] == "mint"
|
||||
assert prog["complete"] == 12
|
||||
assert prog["goal_complete"] == 1190
|
||||
assert prog["baseline_complete"] == 10
|
||||
assert prog["remain"] == 1190 - 12
|
||||
assert any(s["id"] == "mint" and s["state"] == "active" for s in prog["steps"])
|
||||
assert any(s["id"] == "browser_boot" and s["state"] == "done" for s in prog["steps"])
|
||||
assert prog["worker_log"] and "batch.sub1_abc.log" in prog["worker_log"]
|
||||
assert prog["timeline"]
|
||||
|
||||
|
||||
def test_build_progress_stuck_on_zero(tmp_path: Path):
|
||||
logs = tmp_path / "logs"
|
||||
logs.mkdir()
|
||||
sup = logs / "x.supervisor.log"
|
||||
sup.write_text(
|
||||
"[supervisor] complete=100 consecutive_zero=5 sub=9 chunk=3 mode=ordinary\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
prog = build_progress(tmp_path, sup_log=sup)
|
||||
assert prog["stuck"] is True
|
||||
assert "连续" in prog["stuck_reason"]
|
||||
|
||||
|
||||
def test_detect_phase_turnstile_from_summary_fatal():
|
||||
line = (
|
||||
'SUMMARY_JSON {"event":"register_cli_summary","exit":2,"reg_success":0,'
|
||||
'"remote_inject_ok":0,"fatal":true,"fatal_reason":"Turnstile 卡住 fail-fast: '
|
||||
'pre-submit wait 31s token_len=0"}'
|
||||
)
|
||||
p = detect_phase(line + "\n")
|
||||
assert p["phase"] == "turnstile"
|
||||
# must NOT classify as batch_end_inject due to remote_inject_ok key
|
||||
assert p["phase"] != "batch_end_inject"
|
||||
|
||||
|
||||
def test_build_progress_prefers_active_sub_over_finished_summary(tmp_path: Path, monkeypatch):
|
||||
"""Regression: mid-sub must not stick on previous SUMMARY_JSON / 子批汇总.
|
||||
|
||||
Supervisor only writes `log=` after a sub exits. During the next sub the
|
||||
newest mtime worker log is the authority — not the stale log= path.
|
||||
"""
|
||||
import time
|
||||
|
||||
logs = tmp_path / "logs"
|
||||
logs.mkdir()
|
||||
tag = "batch_dc1k_ns_ordinary_562_20260721_123509"
|
||||
sup = logs / f"{tag}.supervisor.log"
|
||||
finished = logs / f"{tag}.sub226_20260722_053405.log"
|
||||
active = logs / f"{tag}.sub227_20260722_054209.log"
|
||||
|
||||
finished.write_text(
|
||||
"\n".join(
|
||||
[
|
||||
"[05:40:01] [WM1] [cpa] wrote cpa_auths/xai-old@example.com.json mint_method=browser",
|
||||
"=== 完成: 注册成功 2, 注册失败 1 ===",
|
||||
'SUMMARY_JSON {"event":"register_cli_summary","exit":0,"reg_success":2,'
|
||||
'"fatal":false,"fatal_reason":"","product_ok":true}',
|
||||
]
|
||||
)
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
# Ensure finished is older than active.
|
||||
older = time.time() - 120
|
||||
import os
|
||||
|
||||
os.utime(finished, (older, older))
|
||||
|
||||
active.write_text(
|
||||
"\n".join(
|
||||
[
|
||||
"[*] lock acquired",
|
||||
"[05:47:50] browser_boot Chromium started",
|
||||
"[05:48:07] [WM1] [cpa] cookie inject count=39",
|
||||
"[05:48:22] [WM1] [cpa] oauth poll: authorization_pending",
|
||||
"mint token_ok wrote cpa_auths/xai-live@example.com.json",
|
||||
]
|
||||
)
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
os.utime(active, None)
|
||||
|
||||
sup.write_text(
|
||||
"\n".join(
|
||||
[
|
||||
f"[supervisor] sub=226 exit=0 log=logs/{finished.name}",
|
||||
"=== 完成: 注册成功 2, 注册失败 1 ===",
|
||||
'SUMMARY_JSON {"event":"register_cli_summary","exit":0,"reg_success":2,'
|
||||
'"fatal":false,"fatal_reason":"","product_ok":true}',
|
||||
"[supervisor] sub=226 gained_complete=2 consecutive_zero=0",
|
||||
"[supervisor] 21:42:09Z complete=800 (+172/562) accounts=1090 attempt=226",
|
||||
# Next sub started — no exit / log= yet (live production pattern).
|
||||
"[supervisor] sub=227 chunk=3 mode=ordinary clash_rotate zero=0",
|
||||
]
|
||||
)
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
prog = build_progress(tmp_path, sup_log=sup)
|
||||
assert prog["worker_log"] and active.name in prog["worker_log"], prog.get("worker_log")
|
||||
assert prog["phase"] != "sub_summary", prog
|
||||
assert prog["phase"] == "mint", prog
|
||||
assert any(s["id"] == "mint" and s["state"] == "active" for s in prog["steps"])
|
||||
assert any(s["id"] == "sub_summary" and s["state"] == "pending" for s in prog["steps"])
|
||||
|
||||
|
||||
def test_build_progress_prefers_active_sub_over_finished_summary(tmp_path: Path, monkeypatch):
|
||||
"""Regression: mid-sub must not stick on previous SUMMARY_JSON / 子批汇总.
|
||||
|
||||
Supervisor only writes `log=` after a sub exits. During the next sub the
|
||||
newest mtime worker log is the authority — not the stale log= path.
|
||||
"""
|
||||
import time
|
||||
|
||||
logs = tmp_path / "logs"
|
||||
logs.mkdir()
|
||||
tag = "batch_dc1k_ns_ordinary_562_20260721_123509"
|
||||
sup = logs / f"{tag}.supervisor.log"
|
||||
finished = logs / f"{tag}.sub226_20260722_053405.log"
|
||||
active = logs / f"{tag}.sub227_20260722_054209.log"
|
||||
|
||||
finished.write_text(
|
||||
"\n".join(
|
||||
[
|
||||
"[05:40:01] [WM1] [cpa] wrote cpa_auths/xai-old@example.com.json mint_method=browser",
|
||||
"=== 完成: 注册成功 2, 注册失败 1 ===",
|
||||
'SUMMARY_JSON {"event":"register_cli_summary","exit":0,"reg_success":2,'
|
||||
'"fatal":false,"fatal_reason":"","product_ok":true}',
|
||||
]
|
||||
)
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
# Ensure finished is older than active.
|
||||
older = time.time() - 120
|
||||
import os
|
||||
|
||||
os.utime(finished, (older, older))
|
||||
|
||||
active.write_text(
|
||||
"\n".join(
|
||||
[
|
||||
"[*] lock acquired",
|
||||
"[05:47:50] browser_boot Chromium started",
|
||||
"[05:48:07] [WM1] [cpa] cookie inject count=39",
|
||||
"[05:48:22] [WM1] [cpa] oauth poll: authorization_pending",
|
||||
"mint token_ok wrote cpa_auths/xai-live@example.com.json",
|
||||
]
|
||||
)
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
os.utime(active, None)
|
||||
|
||||
sup.write_text(
|
||||
"\n".join(
|
||||
[
|
||||
f"[supervisor] sub=226 exit=0 log=logs/{finished.name}",
|
||||
"=== 完成: 注册成功 2, 注册失败 1 ===",
|
||||
'SUMMARY_JSON {"event":"register_cli_summary","exit":0,"reg_success":2,'
|
||||
'"fatal":false,"fatal_reason":"","product_ok":true}',
|
||||
"[supervisor] sub=226 gained_complete=2 consecutive_zero=0",
|
||||
"[supervisor] 21:42:09Z complete=800 (+172/562) accounts=1090 attempt=226",
|
||||
# Next sub started — no exit / log= yet (live production pattern).
|
||||
"[supervisor] sub=227 chunk=3 mode=ordinary clash_rotate zero=0",
|
||||
]
|
||||
)
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
prog = build_progress(tmp_path, sup_log=sup)
|
||||
assert prog["worker_log"] and active.name in prog["worker_log"], prog.get("worker_log")
|
||||
assert prog["phase"] != "sub_summary", prog
|
||||
assert prog["phase"] == "mint", prog
|
||||
assert any(s["id"] == "mint" and s["state"] == "active" for s in prog["steps"])
|
||||
assert any(s["id"] == "sub_summary" and s["state"] == "pending" for s in prog["steps"])
|
||||
@@ -0,0 +1,707 @@
|
||||
"""Runs / process registry tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from apps.control_api.process_registry import ProcessRegistry, stop_pid
|
||||
from apps.control_api.runs import filter_extra_env, run_status, start_run, stop_run
|
||||
from apps.control_api.schemas import StartRunRequest
|
||||
|
||||
|
||||
def test_extra_env_reject_unknown():
|
||||
with pytest.raises(ValueError, match="not allowed"):
|
||||
filter_extra_env({"EVIL": "1"})
|
||||
|
||||
|
||||
def test_extra_env_allowlist():
|
||||
assert filter_extra_env({"SKIP_CLASH_PREFLIGHT": "1"}) == {"SKIP_CLASH_PREFLIGHT": "1"}
|
||||
assert filter_extra_env(
|
||||
{
|
||||
"CPA_BATCH_END_INJECT": "true",
|
||||
"CPA_BATCH_IMPORT_EVERY": "100",
|
||||
"CPA_BATCH_IMPORT_SIZE": "100",
|
||||
"CPA_BATCH_IMPORT_PAUSE": "3",
|
||||
}
|
||||
) == {
|
||||
"CPA_BATCH_END_INJECT": "true",
|
||||
"CPA_BATCH_IMPORT_EVERY": "100",
|
||||
"CPA_BATCH_IMPORT_SIZE": "100",
|
||||
"CPA_BATCH_IMPORT_PAUSE": "3",
|
||||
}
|
||||
|
||||
|
||||
def test_extra_env_rejects_lf_injection():
|
||||
"""A value containing a newline could inject a following line when the env
|
||||
is re-serialized (.env / shell sourcing / log lines). Refuse NUL/CR/LF
|
||||
(and vertical-tab/form-feed/DEL) outright — the actual line terminator
|
||||
family."""
|
||||
with pytest.raises(ValueError, match="control char"):
|
||||
filter_extra_env({"EMAIL_PROVIDER": "cloudflare\nEVIL=1"})
|
||||
with pytest.raises(ValueError, match="control char"):
|
||||
filter_extra_env({"EMAIL_PROVIDER": "a\rb"})
|
||||
with pytest.raises(ValueError, match="control char"):
|
||||
filter_extra_env({"EMAIL_PROVIDER": "a\x00b"})
|
||||
# tab and space are NOT line terminators and must survive (common in values)
|
||||
assert filter_extra_env({"CPA_BATCH_IMPORT_SIZE": "100\t200"})[
|
||||
"CPA_BATCH_IMPORT_SIZE"
|
||||
] == "100\t200"
|
||||
|
||||
|
||||
def test_extra_env_rejects_overlong_value():
|
||||
"""Cap value length so a multi-KB value cannot bloat env/logs indefinitely."""
|
||||
from apps.control_api.runs import EXTRA_ENV_VALUE_MAX_LEN
|
||||
|
||||
ok = "x" * EXTRA_ENV_VALUE_MAX_LEN
|
||||
assert filter_extra_env({"CPA_BATCH_IMPORT_SIZE": ok})["CPA_BATCH_IMPORT_SIZE"] == ok
|
||||
with pytest.raises(ValueError, match="too long"):
|
||||
filter_extra_env({"CPA_BATCH_IMPORT_SIZE": "x" * (EXTRA_ENV_VALUE_MAX_LEN + 1)})
|
||||
|
||||
|
||||
def test_start_409_when_registry_active(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.chdir(tmp_path)
|
||||
(tmp_path / "scripts").mkdir()
|
||||
(tmp_path / "scripts" / "launch_batch_supervisor.sh").write_text("#!/bin/bash\n", encoding="utf-8")
|
||||
(tmp_path / "logs").mkdir()
|
||||
reg = ProcessRegistry(tmp_path)
|
||||
reg.register("abc", os.getpid(), "grok_supervisor", {})
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
start_run(
|
||||
tmp_path,
|
||||
StartRunRequest(kind="grok_supervisor", target=10, tag="t"),
|
||||
)
|
||||
assert ei.value.status_code == 409
|
||||
|
||||
|
||||
def test_start_409_when_lock_pid_alive(tmp_path: Path, monkeypatch):
|
||||
monkeypatch.chdir(tmp_path)
|
||||
(tmp_path / "scripts").mkdir()
|
||||
(tmp_path / "scripts" / "launch_batch_supervisor.sh").write_text("#!/bin/bash\n", encoding="utf-8")
|
||||
lock = Path("/tmp/grok_batch_supervisor.lock.pid")
|
||||
# Only mock supervisor_lock_held path via monkeypatch of helper
|
||||
monkeypatch.setattr(
|
||||
"apps.control_api.runs.supervisor_lock_held",
|
||||
lambda: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"apps.control_api.runs.supervisor_lock_pid",
|
||||
lambda: 999999,
|
||||
)
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
start_run(tmp_path, StartRunRequest(kind="grok_supervisor", target=10))
|
||||
assert ei.value.status_code == 409
|
||||
del lock # silence unused
|
||||
|
||||
|
||||
def test_stop_only_recorded_pid(tmp_path: Path, monkeypatch):
|
||||
reg = ProcessRegistry(tmp_path)
|
||||
reg.register("r1", 424242, "register_sh", {"process_group": True})
|
||||
seen: dict = {}
|
||||
|
||||
def fake_stop(pid, grace_sec=10.0, *, process_group=True):
|
||||
seen["pid"] = pid
|
||||
seen["grace_sec"] = grace_sec
|
||||
seen["process_group"] = process_group
|
||||
return {"ok": True, "detail": "terminated", "pid": pid, "mode": "pg"}
|
||||
|
||||
# Keep fake registry pid "alive" so clear_if_dead does not drop it.
|
||||
monkeypatch.setattr(
|
||||
"apps.control_api.process_registry.ProcessRegistry.pid_alive",
|
||||
staticmethod(lambda pid: pid == 424242),
|
||||
)
|
||||
monkeypatch.setattr("apps.control_api.runs.stop_pid", fake_stop)
|
||||
out = stop_run(tmp_path)
|
||||
assert out["ok"] is True
|
||||
assert out["pid"] == 424242
|
||||
assert out["source"] == "registry"
|
||||
assert out["mode"] == "pg"
|
||||
assert seen["process_group"] is True
|
||||
# After stop, registry cleared; current() may still see nothing.
|
||||
monkeypatch.setattr(
|
||||
"apps.control_api.process_registry.ProcessRegistry.pid_alive",
|
||||
staticmethod(lambda pid: False),
|
||||
)
|
||||
assert ProcessRegistry(tmp_path).current() is None
|
||||
|
||||
|
||||
def test_stop_lock_fallback(tmp_path: Path, monkeypatch):
|
||||
# No registry current → use lock pid
|
||||
seen: dict = {}
|
||||
|
||||
def fake_stop(pid, grace_sec=10.0, *, process_group=True):
|
||||
seen["pid"] = pid
|
||||
seen["process_group"] = process_group
|
||||
return {"ok": True, "detail": "terminated", "pid": pid, "mode": "pid"}
|
||||
|
||||
monkeypatch.setattr("apps.control_api.runs.stop_pid", fake_stop)
|
||||
monkeypatch.setattr("apps.control_api.runs.supervisor_lock_pid", lambda: 777001)
|
||||
out = stop_run(tmp_path)
|
||||
assert out["ok"] is True
|
||||
assert out["pid"] == 777001
|
||||
assert out["source"] == "lock"
|
||||
assert seen["process_group"] is True
|
||||
|
||||
|
||||
def test_stop_pid_prefers_killpg(monkeypatch):
|
||||
calls: list[tuple[str, int, int]] = []
|
||||
|
||||
def fake_killpg(pgid, sig):
|
||||
calls.append(("pg", pgid, sig))
|
||||
|
||||
def fake_kill(pid, sig):
|
||||
calls.append(("pid", pid, sig))
|
||||
raise AssertionError("single-pid kill should not run when killpg works")
|
||||
|
||||
# alive before signal, dead after killpg
|
||||
states = iter([True, False])
|
||||
monkeypatch.setattr("apps.control_api.process_registry.os.killpg", fake_killpg)
|
||||
monkeypatch.setattr("apps.control_api.process_registry.os.kill", fake_kill)
|
||||
monkeypatch.setattr(
|
||||
"apps.control_api.process_registry.ProcessRegistry.pid_alive",
|
||||
staticmethod(lambda pid: next(states, False)),
|
||||
)
|
||||
out = stop_pid(4242, grace_sec=0.01, process_group=True)
|
||||
assert out["ok"] is True
|
||||
assert out["mode"] == "pg"
|
||||
assert out["detail"] == "terminated"
|
||||
assert calls and calls[0][0] == "pg"
|
||||
assert calls[0][1] == 4242
|
||||
|
||||
|
||||
def test_stop_pid_falls_back_to_single_pid(monkeypatch):
|
||||
calls: list[tuple[str, int]] = []
|
||||
|
||||
def fake_killpg(pgid, sig):
|
||||
calls.append(("pg", pgid))
|
||||
raise PermissionError("not leader")
|
||||
|
||||
def fake_kill(pid, sig):
|
||||
calls.append(("pid", pid))
|
||||
|
||||
states = iter([True, False])
|
||||
monkeypatch.setattr("apps.control_api.process_registry.os.killpg", fake_killpg)
|
||||
monkeypatch.setattr("apps.control_api.process_registry.os.kill", fake_kill)
|
||||
monkeypatch.setattr(
|
||||
"apps.control_api.process_registry.ProcessRegistry.pid_alive",
|
||||
staticmethod(lambda pid: next(states, False)),
|
||||
)
|
||||
out = stop_pid(9001, grace_sec=0.01, process_group=True)
|
||||
assert out["ok"] is True
|
||||
assert out["mode"] == "pid"
|
||||
assert ("pg", 9001) in calls
|
||||
assert ("pid", 9001) in calls
|
||||
|
||||
|
||||
def test_stop_pid_killpg_esrch_falls_back_when_pid_alive(monkeypatch):
|
||||
"""External flock supervisor is often not the group leader.
|
||||
|
||||
On Linux, killpg(non-leader-pid) raises ProcessLookupError (ESRCH) even when
|
||||
that pid is still alive. Treating ESRCH as "already dead" makes the UI report
|
||||
stop success while batch_dc1k_ns keeps running.
|
||||
"""
|
||||
calls: list[tuple[str, int, int]] = []
|
||||
|
||||
def fake_killpg(pgid, sig):
|
||||
calls.append(("pg", pgid, sig))
|
||||
raise ProcessLookupError(3, "No such process")
|
||||
|
||||
def fake_kill(pid, sig):
|
||||
calls.append(("pid", pid, sig))
|
||||
|
||||
# Stay alive until single-pid SIGTERM lands, then die.
|
||||
alive = {"v": True}
|
||||
|
||||
def fake_alive(pid):
|
||||
return alive["v"]
|
||||
|
||||
def kill_and_die(pid, sig):
|
||||
calls.append(("pid", pid, sig))
|
||||
alive["v"] = False
|
||||
|
||||
monkeypatch.setattr("apps.control_api.process_registry.os.killpg", fake_killpg)
|
||||
monkeypatch.setattr("apps.control_api.process_registry.os.kill", kill_and_die)
|
||||
monkeypatch.setattr(
|
||||
"apps.control_api.process_registry.ProcessRegistry.pid_alive",
|
||||
staticmethod(fake_alive),
|
||||
)
|
||||
out = stop_pid(1554550, grace_sec=0.05, process_group=True)
|
||||
assert out["ok"] is True
|
||||
assert out["detail"] == "terminated"
|
||||
assert out["mode"] == "pid"
|
||||
assert out["detail"] != "already dead"
|
||||
assert any(c[0] == "pg" for c in calls)
|
||||
assert any(c[0] == "pid" and c[1] == 1554550 for c in calls)
|
||||
|
||||
|
||||
def test_stop_pid_uses_real_pgid_for_external_tree(monkeypatch):
|
||||
"""Prefer os.getpgid(pid) so killpg hits the real group of a non-leader supervisor."""
|
||||
calls: list[tuple[str, int, int]] = []
|
||||
|
||||
def fake_getpgid(pid):
|
||||
assert pid == 1554550
|
||||
return 1554494
|
||||
|
||||
def fake_killpg(pgid, sig):
|
||||
calls.append(("pg", pgid, sig))
|
||||
|
||||
def fake_kill(pid, sig):
|
||||
calls.append(("pid", pid, sig))
|
||||
raise AssertionError("single-pid kill should not run when real pgid killpg works")
|
||||
|
||||
states = iter([True, False])
|
||||
monkeypatch.setattr("apps.control_api.process_registry.os.getpgid", fake_getpgid)
|
||||
monkeypatch.setattr("apps.control_api.process_registry.os.killpg", fake_killpg)
|
||||
monkeypatch.setattr("apps.control_api.process_registry.os.kill", fake_kill)
|
||||
monkeypatch.setattr(
|
||||
"apps.control_api.process_registry.ProcessRegistry.pid_alive",
|
||||
staticmethod(lambda pid: next(states, False)),
|
||||
)
|
||||
out = stop_pid(1554550, grace_sec=0.01, process_group=True)
|
||||
assert out["ok"] is True
|
||||
assert out["mode"] == "pg"
|
||||
assert calls[0] == ("pg", 1554494, signal.SIGTERM)
|
||||
|
||||
|
||||
def test_stop_pid_killpg_esrch_falls_back_when_pid_alive(monkeypatch):
|
||||
"""External flock supervisor is often not the group leader.
|
||||
|
||||
On Linux, killpg(non-leader-pid) raises ProcessLookupError (ESRCH) even when
|
||||
that pid is still alive. Treating ESRCH as "already dead" makes the UI report
|
||||
stop success while batch_dc1k_ns keeps running.
|
||||
"""
|
||||
calls: list[tuple[str, int, int]] = []
|
||||
|
||||
def fake_killpg(pgid, sig):
|
||||
calls.append(("pg", pgid, sig))
|
||||
raise ProcessLookupError(3, "No such process")
|
||||
|
||||
def fake_kill(pid, sig):
|
||||
calls.append(("pid", pid, sig))
|
||||
|
||||
# Stay alive until single-pid SIGTERM lands, then die.
|
||||
alive = {"v": True}
|
||||
|
||||
def fake_alive(pid):
|
||||
return alive["v"]
|
||||
|
||||
def kill_and_die(pid, sig):
|
||||
calls.append(("pid", pid, sig))
|
||||
alive["v"] = False
|
||||
|
||||
monkeypatch.setattr("apps.control_api.process_registry.os.killpg", fake_killpg)
|
||||
monkeypatch.setattr("apps.control_api.process_registry.os.kill", kill_and_die)
|
||||
monkeypatch.setattr(
|
||||
"apps.control_api.process_registry.ProcessRegistry.pid_alive",
|
||||
staticmethod(fake_alive),
|
||||
)
|
||||
out = stop_pid(1554550, grace_sec=0.05, process_group=True)
|
||||
assert out["ok"] is True
|
||||
assert out["detail"] == "terminated"
|
||||
assert out["mode"] == "pid"
|
||||
assert out["detail"] != "already dead"
|
||||
assert any(c[0] == "pg" for c in calls)
|
||||
assert any(c[0] == "pid" and c[1] == 1554550 for c in calls)
|
||||
|
||||
|
||||
def test_stop_pid_uses_real_pgid_for_external_tree(monkeypatch):
|
||||
"""Prefer os.getpgid(pid) so killpg hits the real group of a non-leader supervisor."""
|
||||
calls: list[tuple[str, int, int]] = []
|
||||
|
||||
def fake_getpgid(pid):
|
||||
assert pid == 1554550
|
||||
return 1554494
|
||||
|
||||
def fake_killpg(pgid, sig):
|
||||
calls.append(("pg", pgid, sig))
|
||||
|
||||
def fake_kill(pid, sig):
|
||||
calls.append(("pid", pid, sig))
|
||||
raise AssertionError("single-pid kill should not run when real pgid killpg works")
|
||||
|
||||
states = iter([True, False])
|
||||
monkeypatch.setattr("apps.control_api.process_registry.os.getpgid", fake_getpgid)
|
||||
monkeypatch.setattr("apps.control_api.process_registry.os.killpg", fake_killpg)
|
||||
monkeypatch.setattr("apps.control_api.process_registry.os.kill", fake_kill)
|
||||
monkeypatch.setattr(
|
||||
"apps.control_api.process_registry.ProcessRegistry.pid_alive",
|
||||
staticmethod(lambda pid: next(states, False)),
|
||||
)
|
||||
out = stop_pid(1554550, grace_sec=0.01, process_group=True)
|
||||
assert out["ok"] is True
|
||||
assert out["mode"] == "pg"
|
||||
assert calls[0] == ("pg", 1554494, signal.SIGTERM)
|
||||
|
||||
|
||||
def test_start_popen_argv(tmp_path: Path, monkeypatch):
|
||||
(tmp_path / "scripts").mkdir()
|
||||
script = tmp_path / "scripts" / "launch_batch_supervisor.sh"
|
||||
script.write_text("#!/bin/bash\n", encoding="utf-8")
|
||||
(tmp_path / "logs").mkdir()
|
||||
|
||||
class FakeProc:
|
||||
pid = 555
|
||||
|
||||
def poll(self):
|
||||
return None # still running through fail-fast window
|
||||
|
||||
def wait(self, timeout=None):
|
||||
return 0
|
||||
|
||||
captured = {}
|
||||
closed = {"n": 0}
|
||||
|
||||
class FakeFile:
|
||||
def close(self):
|
||||
closed["n"] += 1
|
||||
|
||||
def fake_open(*_a, **_k):
|
||||
return FakeFile()
|
||||
|
||||
def fake_popen(argv, **kwargs):
|
||||
captured["argv"] = argv
|
||||
captured["kwargs"] = kwargs
|
||||
return FakeProc()
|
||||
|
||||
monkeypatch.setattr("apps.control_api.runs.subprocess.Popen", fake_popen)
|
||||
monkeypatch.setattr("apps.control_api.runs.supervisor_lock_held", lambda: False)
|
||||
monkeypatch.setattr("apps.control_api.runs.time.sleep", lambda _s: None)
|
||||
monkeypatch.setattr("builtins.open", fake_open)
|
||||
# Fake child pid must look alive for registry.current() after register.
|
||||
monkeypatch.setattr(
|
||||
"apps.control_api.process_registry.ProcessRegistry.pid_alive",
|
||||
staticmethod(lambda pid: pid == 555),
|
||||
)
|
||||
# Stale process env must lose to config.json (console source of truth).
|
||||
monkeypatch.setenv("EMAIL_PROVIDER", "cloudflare")
|
||||
(tmp_path / "config.json").write_text(
|
||||
json.dumps({"email_provider": "hotmail", "email_provider_strategy": "round_robin"}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
result = start_run(
|
||||
tmp_path,
|
||||
StartRunRequest(
|
||||
kind="grok_supervisor",
|
||||
mode="ordinary",
|
||||
target=50,
|
||||
threads=1,
|
||||
tag="batch_web",
|
||||
extra_env={"NODE_SCORE": "1"},
|
||||
),
|
||||
)
|
||||
assert result["ok"] is True
|
||||
assert captured["argv"][0] == "bash"
|
||||
assert captured["argv"][2] == "ordinary"
|
||||
assert captured["argv"][3] == "50"
|
||||
assert captured["argv"][4] == "1"
|
||||
assert captured["argv"][5] == "batch_web"
|
||||
assert captured["kwargs"].get("start_new_session") is True
|
||||
child_env = captured["kwargs"].get("env") or {}
|
||||
assert child_env.get("EMAIL_PROVIDER") == "hotmail"
|
||||
assert child_env.get("EMAIL_PROVIDER_STRATEGY") == "round_robin"
|
||||
assert child_env.get("NODE_SCORE") == "1"
|
||||
# Parent log handle closed after successful Popen (child keeps its dup).
|
||||
assert closed["n"] == 1
|
||||
meta = result["run"]["meta"]
|
||||
assert meta.get("process_group") is True
|
||||
assert meta.get("pgid") == 555
|
||||
|
||||
|
||||
def test_start_register_sh_outlook_argv(tmp_path: Path, monkeypatch):
|
||||
"""kind=register_sh + product=outlook reaches register.sh as argv
|
||||
[bash, register.sh, outlook, target, threads] — the control-plane hop
|
||||
that lets an Outlook run launch. The live gate (GROK_REGISTER_OUTLOOK_LIVE)
|
||||
remains an operator env, NOT set here; the provider short-circuits to
|
||||
error_kind="provider", which is the safe non-live reachability contract."""
|
||||
# register.sh must exist for start_run's register_sh-branch file check.
|
||||
(tmp_path / "register.sh").write_text("#!/bin/bash\n", encoding="utf-8")
|
||||
(tmp_path / "logs").mkdir()
|
||||
|
||||
class FakeProc:
|
||||
pid = 556
|
||||
|
||||
def poll(self):
|
||||
return None
|
||||
|
||||
def wait(self, timeout=None):
|
||||
return 0
|
||||
|
||||
captured: dict = {}
|
||||
|
||||
class FakeFile:
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
def fake_popen(argv, **kwargs):
|
||||
captured["argv"] = argv
|
||||
return FakeProc()
|
||||
|
||||
monkeypatch.setattr("apps.control_api.runs.subprocess.Popen", fake_popen)
|
||||
monkeypatch.setattr("apps.control_api.runs.supervisor_lock_held", lambda: False)
|
||||
monkeypatch.setattr("apps.control_api.runs.time.sleep", lambda _s: None)
|
||||
monkeypatch.setattr("builtins.open", lambda *_a, **_k: FakeFile())
|
||||
monkeypatch.setattr(
|
||||
"apps.control_api.process_registry.ProcessRegistry.pid_alive",
|
||||
staticmethod(lambda pid: pid == 556),
|
||||
)
|
||||
result = start_run(
|
||||
tmp_path,
|
||||
StartRunRequest(
|
||||
kind="register_sh",
|
||||
product="outlook",
|
||||
mode="residential",
|
||||
target=3,
|
||||
threads=2,
|
||||
tag="batch_web",
|
||||
extra_env={},
|
||||
),
|
||||
)
|
||||
assert result["ok"] is True
|
||||
argv = captured["argv"]
|
||||
assert argv[0] == "bash"
|
||||
assert Path(argv[1]).name == "register.sh"
|
||||
assert argv[2] == "outlook"
|
||||
assert argv[3] == "3"
|
||||
assert argv[4] == "2" # threads is forwarded; register.sh forwards it to --threads
|
||||
assert result["run"]["meta"]["product"] == "outlook"
|
||||
|
||||
|
||||
def test_register_sh_outlook_branch_maps_to_register_core_run(tmp_path, monkeypatch):
|
||||
"""register.sh's `outlook` branch execs `python -m register_core run --provider
|
||||
outlook -n COUNT --threads N`, which resolves the provider via the registry and
|
||||
calls ``OutlookProvider.register_one``. We pin the safe non-live contract at
|
||||
the provider layer directly (in-process, no subprocess, no network):
|
||||
|
||||
- live gate OFF (``GROK_REGISTER_OUTLOOK_LIVE`` unset) → the provider
|
||||
short-circuits to ``error_kind="provider"`` with the gate phrase BEFORE
|
||||
any browser/mailbox/network is touched, in ~0s, and writes no artifact.
|
||||
|
||||
This is the control-flow reachability contract for a non-live harness: the
|
||||
argv wiring from register.sh is already pinned by
|
||||
``test_start_register_sh_outlook_argv`` above; here we pin that the provider
|
||||
the registry hands back honors the gate. Spawning the full ``register_core
|
||||
run`` subprocess is avoided because the pipeline runs the shared node/egress
|
||||
probe (network, ~12s libcurl timeouts per dead node) before reaching the
|
||||
per-account gate — that probe is environment-dependent and not part of this
|
||||
contract."""
|
||||
# Live gate OFF (default). No proxy, no browser, no mailbox is ever opened.
|
||||
monkeypatch.delenv("GROK_REGISTER_OUTLOOK_LIVE", raising=False)
|
||||
# Isolate the outlook_auths dir so a gate-on bug can't write into the repo.
|
||||
monkeypatch.setenv("OUTLOOK_AUTHS_DIR", str(tmp_path / "outlook_auths"))
|
||||
|
||||
import time
|
||||
|
||||
from register_core.providers.registry import get_provider
|
||||
|
||||
provider = get_provider("outlook")
|
||||
t0 = time.monotonic()
|
||||
result = provider.register_one()
|
||||
elapsed = time.monotonic() - t0
|
||||
|
||||
# The provider gated off without a LIVE flag → a provider-kind failure.
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "provider"
|
||||
# No browser/mailbox round-trip should occur on a gated-off short-circuit —
|
||||
# this guards against a future change that moves network work above the gate.
|
||||
assert elapsed < 5.0, f"gated short-circuit took {elapsed:.3f}s (network?)"
|
||||
assert result.error is not None
|
||||
assert "live gate" in result.error.lower() or "GROK_REGISTER_OUTLOOK_LIVE" in result.error, (
|
||||
result.error
|
||||
)
|
||||
# No outlook auth artifact should have been written (gate is OFF).
|
||||
auths_dir = tmp_path / "outlook_auths"
|
||||
assert not auths_dir.exists() or not list(auths_dir.glob("outlook-*.json")), (
|
||||
"gate OFF must not write an artifact"
|
||||
)
|
||||
|
||||
|
||||
def test_start_run_extra_env_overrides_config(tmp_path: Path, monkeypatch):
|
||||
"""Request extra_env wins over config.json for one-shot experiments."""
|
||||
(tmp_path / "scripts").mkdir()
|
||||
(tmp_path / "scripts" / "launch_batch_supervisor.sh").write_text(
|
||||
"#!/bin/bash\n", encoding="utf-8"
|
||||
)
|
||||
(tmp_path / "logs").mkdir()
|
||||
(tmp_path / "config.json").write_text(
|
||||
json.dumps({"email_provider": "hotmail"}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
class FakeProc:
|
||||
pid = 556
|
||||
|
||||
def poll(self):
|
||||
return None
|
||||
|
||||
captured: dict = {}
|
||||
|
||||
class FakeFile:
|
||||
def close(self):
|
||||
pass
|
||||
|
||||
def fake_popen(argv, **kwargs):
|
||||
captured["env"] = kwargs.get("env") or {}
|
||||
return FakeProc()
|
||||
|
||||
monkeypatch.setattr("apps.control_api.runs.subprocess.Popen", fake_popen)
|
||||
monkeypatch.setattr("apps.control_api.runs.supervisor_lock_held", lambda: False)
|
||||
monkeypatch.setattr("apps.control_api.runs.time.sleep", lambda _s: None)
|
||||
monkeypatch.setattr("builtins.open", lambda *_a, **_k: FakeFile())
|
||||
monkeypatch.setattr(
|
||||
"apps.control_api.process_registry.ProcessRegistry.pid_alive",
|
||||
staticmethod(lambda pid: pid == 556),
|
||||
)
|
||||
start_run(
|
||||
tmp_path,
|
||||
StartRunRequest(
|
||||
kind="grok_supervisor",
|
||||
target=10,
|
||||
tag="t",
|
||||
extra_env={"EMAIL_PROVIDER": "cloudflare"},
|
||||
),
|
||||
)
|
||||
assert captured["env"].get("EMAIL_PROVIDER") == "cloudflare"
|
||||
|
||||
|
||||
def test_run_status_flattens_recent_writes(tmp_path: Path):
|
||||
"""`run_status` should surface `recent_writes` at the top level for UI."""
|
||||
(tmp_path / "logs").mkdir()
|
||||
# No lock, no registry, no supervisor log ⇒ None is acceptable
|
||||
st = run_status(tmp_path)
|
||||
if st is None:
|
||||
return
|
||||
assert "recent_writes" in st
|
||||
assert isinstance(st["recent_writes"], list)
|
||||
|
||||
|
||||
def test_run_status_recent_writes_from_progress(tmp_path: Path, monkeypatch):
|
||||
"""When progress supplies recent_writes list, it is flattened to top-level."""
|
||||
(tmp_path / "logs").mkdir()
|
||||
sample = ["cpa_auths/xai-abc.json", "cpa_auths/xai-def.json"]
|
||||
|
||||
def fake_progress(root, sup_log=None):
|
||||
return {
|
||||
"complete": 42,
|
||||
"recent_writes": list(sample),
|
||||
"last_lines": ["hello"],
|
||||
"steps": [],
|
||||
"timeline": [],
|
||||
}
|
||||
|
||||
monkeypatch.setattr("apps.control_api.runs.build_progress", fake_progress)
|
||||
# Force a "log" source (no registry / no lock) via minimal shim.
|
||||
monkeypatch.setattr("apps.control_api.runs.supervisor_lock_pid", lambda: None)
|
||||
st = run_status(tmp_path)
|
||||
assert st is not None, "expected log-source run when progress reports complete"
|
||||
assert st.get("recent_writes") == sample
|
||||
|
||||
|
||||
def test_pid_alive_treats_zombie_as_dead(tmp_path: Path, monkeypatch):
|
||||
"""Zombie bash (kill 0 OK, /proc state Z) must not keep registry ALIVE."""
|
||||
reg = ProcessRegistry(tmp_path)
|
||||
reg.register("z1", 424242, "grok_supervisor", {})
|
||||
|
||||
monkeypatch.setattr(
|
||||
"apps.control_api.process_registry.ProcessRegistry._reap_children",
|
||||
staticmethod(lambda: None),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"apps.control_api.process_registry.os.kill",
|
||||
lambda pid, sig: None if pid == 424242 else (_ for _ in ()).throw(ProcessLookupError()),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
"apps.control_api.process_registry.ProcessRegistry._pid_is_zombie",
|
||||
staticmethod(lambda pid: pid == 424242),
|
||||
)
|
||||
assert ProcessRegistry.pid_alive(424242) is False
|
||||
assert ProcessRegistry(tmp_path).current() is None
|
||||
|
||||
|
||||
def test_supervisor_flock_busy_true_when_held(tmp_path: Path, monkeypatch):
|
||||
from apps.control_api.process_registry import supervisor_flock_busy, supervisor_lock_held
|
||||
|
||||
monkeypatch.setattr(
|
||||
"apps.control_api.process_registry.supervisor_lock_pid",
|
||||
lambda: None,
|
||||
)
|
||||
# Simulate BlockingIOError on flock NB acquire.
|
||||
import fcntl as _fcntl
|
||||
|
||||
real_flock = _fcntl.flock
|
||||
|
||||
def fake_flock(fd, op):
|
||||
if op == (_fcntl.LOCK_EX | _fcntl.LOCK_NB):
|
||||
raise BlockingIOError()
|
||||
return real_flock(fd, op)
|
||||
|
||||
monkeypatch.setattr("apps.control_api.process_registry.fcntl.flock", fake_flock)
|
||||
assert supervisor_flock_busy() is True
|
||||
assert supervisor_lock_held() is True
|
||||
|
||||
|
||||
def test_start_clears_registry_when_child_exits_immediately(tmp_path: Path, monkeypatch):
|
||||
(tmp_path / "scripts").mkdir()
|
||||
(tmp_path / "scripts" / "launch_batch_supervisor.sh").write_text(
|
||||
"#!/bin/bash\n", encoding="utf-8"
|
||||
)
|
||||
(tmp_path / "logs").mkdir()
|
||||
|
||||
class DeadProc:
|
||||
pid = 666
|
||||
|
||||
def poll(self):
|
||||
return 1
|
||||
|
||||
def wait(self, timeout=None):
|
||||
return 1
|
||||
|
||||
# Pre-seed the log path pattern: start_run creates control_api_<id>.log.
|
||||
# After Popen we inject failure text via a side-channel: wrap only the
|
||||
# log open used by start_run (apps.control_api.runs open call uses open()).
|
||||
real_open = open
|
||||
|
||||
class LogFile:
|
||||
def __init__(self, path: Path):
|
||||
self.path = path
|
||||
self._f = real_open(path, "a", encoding="utf-8")
|
||||
self.path.write_text(
|
||||
"another supervisor holds /tmp/grok_batch_supervisor.lock; exit\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
def close(self):
|
||||
self._f.close()
|
||||
|
||||
def write(self, data):
|
||||
return self._f.write(data)
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *a):
|
||||
self.close()
|
||||
|
||||
def fake_open(path, *a, **k):
|
||||
p = Path(path)
|
||||
if p.name.startswith("control_api_") and p.suffix == ".log":
|
||||
p.parent.mkdir(parents=True, exist_ok=True)
|
||||
return LogFile(p)
|
||||
return real_open(path, *a, **k)
|
||||
|
||||
monkeypatch.setattr("apps.control_api.runs.subprocess.Popen", lambda *a, **k: DeadProc())
|
||||
monkeypatch.setattr("apps.control_api.runs.supervisor_lock_held", lambda: False)
|
||||
monkeypatch.setattr("apps.control_api.runs.time.sleep", lambda _s: None)
|
||||
monkeypatch.setattr("builtins.open", fake_open)
|
||||
|
||||
with pytest.raises(HTTPException) as ei:
|
||||
start_run(tmp_path, StartRunRequest(kind="grok_supervisor", target=10, tag="t"))
|
||||
assert ei.value.status_code == 500
|
||||
assert "exited immediately" in str(ei.value.detail)
|
||||
assert "another supervisor holds" in str(ei.value.detail)
|
||||
assert ProcessRegistry(tmp_path).current() is None
|
||||
@@ -0,0 +1,101 @@
|
||||
"""§#163 — session ttl hard cap: lifetime can only shrink, never grow.
|
||||
|
||||
The operator-tunable CONTROL_API_SESSION_TTL is clamped in get_settings to
|
||||
[MIN, MAX]. mint_session_token AND read_session_token both bound the baked-in
|
||||
ttl payload field to MAX_SESSION_TTL_SECONDS, so:
|
||||
|
||||
- a runaway TTL env cannot mint an effectively-immortal cookie, and
|
||||
- a token minted by an older build that did NOT clamp the ttl (and so carries
|
||||
a ttl past MAX) is refused at read time even while still within max_age.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from apps.control_api.sessions import (
|
||||
mint_session_token,
|
||||
read_session_token,
|
||||
session_cookie_kwargs,
|
||||
)
|
||||
from apps.control_api.settings import (
|
||||
MAX_SESSION_TTL_SECONDS,
|
||||
MIN_SESSION_TTL_SECONDS,
|
||||
)
|
||||
|
||||
|
||||
SECRET = "test-session-secret-for-ttl-cap!!"
|
||||
|
||||
|
||||
def test_settings_clamps_ttl_into_band(monkeypatch):
|
||||
"""A TTL env above the cap is clamped down; below the floor is clamped up."""
|
||||
from apps.control_api.settings import clear_settings_cache, get_settings
|
||||
|
||||
monkeypatch.setenv("CONTROL_API_SESSION_TTL", str(MAX_SESSION_TTL_SECONDS * 10))
|
||||
clear_settings_cache()
|
||||
s = get_settings()
|
||||
assert s.session_ttl_seconds == MAX_SESSION_TTL_SECONDS
|
||||
|
||||
monkeypatch.setenv("CONTROL_API_SESSION_TTL", "60") # below floor
|
||||
clear_settings_cache()
|
||||
s = get_settings()
|
||||
assert s.session_ttl_seconds == MIN_SESSION_TTL_SECONDS
|
||||
|
||||
|
||||
def test_cookie_max_age_capped_at_constant():
|
||||
"""session_cookie_kwargs never returns a max_age above the hard ceiling."""
|
||||
kw = session_cookie_kwargs(secure=False, max_age=MAX_SESSION_TTL_SECONDS * 5)
|
||||
assert kw["max_age"] == MAX_SESSION_TTL_SECONDS
|
||||
# a normal value passes through
|
||||
assert session_cookie_kwargs(secure=True, max_age=3600)["max_age"] == 3600
|
||||
|
||||
|
||||
def test_mint_clamps_payload_ttl():
|
||||
"""mint_session_token never bakes a ttl past the cap into the signed token."""
|
||||
token = mint_session_token(
|
||||
secret=SECRET, username="ops", ttl_seconds=MAX_SESSION_TTL_SECONDS * 10
|
||||
)
|
||||
payload = read_session_token(token, secret=SECRET, max_age=MAX_SESSION_TTL_SECONDS * 10)
|
||||
assert payload is not None
|
||||
assert payload["ttl"] == MAX_SESSION_TTL_SECONDS
|
||||
|
||||
|
||||
def test_read_rejects_token_whose_baked_ttl_exceeds_cap():
|
||||
"""A token crafted with ttl past MAX_SESSION_TTL_SECONDS is refused on read.
|
||||
|
||||
Simulates an older build that minted without the clamp: we forge a payload
|
||||
carrying an oversized ttl through mint (bypassed by writing the payload
|
||||
directly) and confirm read_session_token rejects it via the max_ttl guard,
|
||||
independent of max_age being generous.
|
||||
"""
|
||||
import time
|
||||
|
||||
from apps.control_api.sessions import _serializer
|
||||
|
||||
over_ttl = MAX_SESSION_TTL_SECONDS + 3600
|
||||
tampered = _serializer(SECRET).dumps(
|
||||
{"u": "ops", "iat": int(time.time()), "ttl": over_ttl}
|
||||
)
|
||||
# max_age is generous (well over the token's actual age) — refusal must come
|
||||
# from the baked ttl exceeding the ceiling, not from expiry.
|
||||
assert read_session_token(tampered, secret=SECRET, max_age=over_ttl * 2) is None
|
||||
|
||||
|
||||
def test_read_accepts_normal_ttl():
|
||||
token = mint_session_token(secret=SECRET, username="ops", ttl_seconds=3600)
|
||||
payload = read_session_token(token, secret=SECRET, max_age=3600)
|
||||
assert payload is not None
|
||||
assert payload["u"] == "ops"
|
||||
assert payload["ttl"] == 3600
|
||||
|
||||
|
||||
def test_negative_ttl_treated_as_invalid():
|
||||
"""A signed token with a nonsensical ttl (<0) is rejected, not normalized."""
|
||||
import time
|
||||
|
||||
from apps.control_api.sessions import _serializer
|
||||
|
||||
token = _serializer(SECRET).dumps(
|
||||
{"u": "ops", "iat": int(time.time()), "ttl": -5}
|
||||
)
|
||||
assert read_session_token(token, secret=SECRET, max_age=3600) is None
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,250 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unit/static checks for one-click CPA chain: priority + multi remote dirs."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def _load(name: str, path: Path):
|
||||
spec = importlib.util.spec_from_file_location(name, path)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
assert spec and spec.loader
|
||||
sys.modules[name] = mod
|
||||
spec.loader.exec_module(mod)
|
||||
return mod
|
||||
|
||||
|
||||
def test_schema_priority_default() -> None:
|
||||
schema = _load("cpa_xai.schema", ROOT / "cpa_xai" / "schema.py")
|
||||
# fake JWT-like fields not required when expired provided
|
||||
payload = schema.build_cpa_xai_auth(
|
||||
email="a@b.com",
|
||||
access_token="x.y.z",
|
||||
refresh_token="r",
|
||||
expired="2026-01-01T00:00:00Z",
|
||||
expires_in=3600,
|
||||
sub="sub1",
|
||||
)
|
||||
assert payload.get("priority") == 1000
|
||||
payload2 = schema.build_cpa_xai_auth(
|
||||
email="a@b.com",
|
||||
access_token="x.y.z",
|
||||
refresh_token="r",
|
||||
expired="2026-01-01T00:00:00Z",
|
||||
expires_in=3600,
|
||||
sub="sub1",
|
||||
priority=50,
|
||||
)
|
||||
assert payload2.get("priority") == 50
|
||||
print("PASS schema priority")
|
||||
|
||||
|
||||
def test_resolve_remote_auth_dirs() -> None:
|
||||
exp = _load("cpa_export", ROOT / "cpa_export.py")
|
||||
# explicit list
|
||||
assert exp.resolve_remote_auth_dirs(
|
||||
{"cpa_remote_auth_dirs": ["/a", "/b", "/a"]}
|
||||
) == ["/a", "/b"]
|
||||
# comma string
|
||||
assert exp.resolve_remote_auth_dirs(
|
||||
{"cpa_remote_auth_dirs": "/live,/inv"}
|
||||
) == ["/live", "/inv"]
|
||||
# legacy single only when inject off
|
||||
assert exp.resolve_remote_auth_dirs(
|
||||
{"cpa_remote_auth_dir": "/only"}
|
||||
) == ["/only"]
|
||||
# inject on + no multi dirs → live+inventory (ignore legacy inventory-only)
|
||||
assert exp.resolve_remote_auth_dirs(
|
||||
{"cpa_remote_inject": True, "cpa_remote_auth_dir": "/personal/cpa/auths"}
|
||||
) == ["/root/.cli-proxy-api", "/personal/cpa/auths"]
|
||||
assert exp.resolve_remote_auth_dirs(
|
||||
{"cpa_remote_inject": True}
|
||||
) == ["/root/.cli-proxy-api", "/personal/cpa/auths"]
|
||||
# custom live dir in defaults
|
||||
assert exp.resolve_remote_auth_dirs(
|
||||
{"cpa_remote_inject": True, "cpa_remote_live_dir": "/custom/live"}
|
||||
) == ["/custom/live", "/personal/cpa/auths"]
|
||||
# inject off + no dirs → empty
|
||||
assert exp.resolve_remote_auth_dirs({}) == []
|
||||
print("PASS resolve_remote_auth_dirs")
|
||||
|
||||
|
||||
def test_ensure_auth_file_priority() -> None:
|
||||
exp = _load("cpa_export", ROOT / "cpa_export.py")
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
p = Path(td) / "xai-t@e.com.json"
|
||||
p.write_text(json.dumps({"type": "xai", "email": "t@e.com"}) + "\n", encoding="utf-8")
|
||||
got = exp.ensure_auth_file_priority(p, priority=42)
|
||||
assert got == 42
|
||||
data = json.loads(p.read_text(encoding="utf-8"))
|
||||
assert data["priority"] == 42
|
||||
# idempotent
|
||||
got2 = exp.ensure_auth_file_priority(p, priority=42)
|
||||
assert got2 == 42
|
||||
print("PASS ensure_auth_file_priority")
|
||||
|
||||
|
||||
def test_mint_accepts_priority_kw() -> None:
|
||||
src = (ROOT / "cpa_xai" / "mint.py").read_text(encoding="utf-8")
|
||||
assert "priority: int = 1000" in src
|
||||
assert "priority=pri" in src
|
||||
print("PASS mint priority kw")
|
||||
|
||||
|
||||
def test_export_wires_multi_and_priority() -> None:
|
||||
src = (ROOT / "cpa_export.py").read_text(encoding="utf-8")
|
||||
assert "resolve_remote_auth_dirs" in src
|
||||
assert "ensure_auth_file_priority" in src
|
||||
assert "apply_multi_remote_inject" in src
|
||||
assert "remote_injects" in src
|
||||
assert "priority=auth_priority" in src
|
||||
assert "cpa_auth_priority" in src
|
||||
assert "cpa_remote_live_required" in src
|
||||
print("PASS export multi+priority wiring")
|
||||
|
||||
|
||||
def test_config_example_one_click_keys() -> None:
|
||||
raw = (ROOT / "config.example.json").read_text(encoding="utf-8")
|
||||
for key in (
|
||||
"cpa_auth_priority",
|
||||
"cpa_remote_auth_dirs",
|
||||
"/root/.cli-proxy-api",
|
||||
"cpa_remote_inject",
|
||||
):
|
||||
assert key in raw, f"missing {key}"
|
||||
print("PASS config.example one-click keys")
|
||||
|
||||
|
||||
def test_remint_script_present() -> None:
|
||||
p = ROOT / "scripts" / "remint_expired_and_sync_authdir.py"
|
||||
assert p.is_file()
|
||||
src = p.read_text(encoding="utf-8")
|
||||
assert "export_cpa_xai_for_account" in src
|
||||
assert "cpa_remote_auth_dirs" in src
|
||||
assert "Does NOT start new registration" in src
|
||||
print("PASS remint script present")
|
||||
|
||||
|
||||
def test_cli_multi_inject_stats() -> None:
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
assert "remote_injects" in src
|
||||
assert "tebi inject x" in src or "tebi inject ok x" in src
|
||||
assert "remote_live_ok" in src
|
||||
print("PASS cli multi inject stats")
|
||||
|
||||
|
||||
def test_live_gate_inventory_only_fails() -> None:
|
||||
"""live fail + inventory ok must hard-fail export (one-click product gate).
|
||||
|
||||
Fixture must be chat_ok so we exercise multi-dir inject, not chat_not_ok skip.
|
||||
"""
|
||||
exp = _load("cpa_export_live_gate", ROOT / "cpa_export.py")
|
||||
calls: list[str] = []
|
||||
|
||||
def fake_inject(path, config=None, log_callback=None):
|
||||
rdir = str((config or {}).get("cpa_remote_auth_dir") or "")
|
||||
calls.append(rdir)
|
||||
if rdir.rstrip("/") == "/root/.cli-proxy-api":
|
||||
return {"ok": False, "error": "ssh fail live"}
|
||||
return {"ok": True, "remote_path": f"{rdir}/xai-t.json"}
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
auth = Path(td) / "xai-t@e.com.json"
|
||||
auth.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "xai",
|
||||
"email": "t@e.com",
|
||||
"priority": 1000,
|
||||
"chat_ok": True,
|
||||
"usable": True,
|
||||
"import_gate": "chat_ok",
|
||||
}
|
||||
)
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
result = {
|
||||
"ok": True,
|
||||
"path": str(auth),
|
||||
"email": "t@e.com",
|
||||
"chat_ok": True,
|
||||
"usable": True,
|
||||
"import_gate": "chat_ok",
|
||||
}
|
||||
cfg = {
|
||||
"cpa_remote_inject": True,
|
||||
"cpa_remote_auth_dirs": "/root/.cli-proxy-api,/personal/cpa/auths",
|
||||
"cpa_remote_live_required": True,
|
||||
"cpa_remote_inject_required": False,
|
||||
}
|
||||
out = exp.apply_multi_remote_inject(result, cfg, inject_fn=fake_inject)
|
||||
assert out["ok"] is False
|
||||
assert out.get("remote_live_ok") is False
|
||||
assert out.get("remote_inventory_ok") is True
|
||||
assert "live inject failed" in (out.get("remote_inject_error") or "")
|
||||
assert "/root/.cli-proxy-api" in calls
|
||||
assert "/personal/cpa/auths" in calls
|
||||
print("PASS live gate inventory-only fails")
|
||||
|
||||
|
||||
def test_live_gate_live_ok_keeps_success() -> None:
|
||||
exp = _load("cpa_export_live_gate_ok", ROOT / "cpa_export.py")
|
||||
|
||||
def fake_inject(path, config=None, log_callback=None):
|
||||
rdir = str((config or {}).get("cpa_remote_auth_dir") or "")
|
||||
return {"ok": True, "remote_path": f"{rdir}/xai-t.json"}
|
||||
|
||||
result = {
|
||||
"ok": True,
|
||||
"path": "/tmp/xai-t.json",
|
||||
"email": "t@e.com",
|
||||
"chat_ok": True,
|
||||
"usable": True,
|
||||
"import_gate": "chat_ok",
|
||||
}
|
||||
cfg = {
|
||||
"cpa_remote_inject": True,
|
||||
"cpa_remote_auth_dirs": "/root/.cli-proxy-api,/personal/cpa/auths",
|
||||
"cpa_remote_live_required": True,
|
||||
}
|
||||
out = exp.apply_multi_remote_inject(result, cfg, inject_fn=fake_inject)
|
||||
assert out["ok"] is True
|
||||
assert out.get("remote_live_ok") is True
|
||||
assert out.get("remote_inventory_ok") is True
|
||||
assert str(out.get("remote_path") or "").startswith("/root/.cli-proxy-api/")
|
||||
print("PASS live gate live ok")
|
||||
|
||||
|
||||
def test_config_example_live_keys() -> None:
|
||||
raw = (ROOT / "config.example.json").read_text(encoding="utf-8")
|
||||
for key in ("cpa_remote_live_dir", "cpa_remote_live_required"):
|
||||
assert key in raw, f"missing {key}"
|
||||
print("PASS config.example live keys")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
test_schema_priority_default()
|
||||
test_resolve_remote_auth_dirs()
|
||||
test_ensure_auth_file_priority()
|
||||
test_mint_accepts_priority_kw()
|
||||
test_export_wires_multi_and_priority()
|
||||
test_config_example_one_click_keys()
|
||||
test_config_example_live_keys()
|
||||
test_remint_script_present()
|
||||
test_cli_multi_inject_stats()
|
||||
test_live_gate_inventory_only_fails()
|
||||
test_live_gate_live_ok_keeps_success()
|
||||
print("\nALL PASS (cpa one-click)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,346 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline checks for the PKCE authorization-code mint path.
|
||||
|
||||
Covers the pure helper functions (no network, no curl_cffi, no real SSO):
|
||||
- grpcweb varint/string/frame encode→decode roundtrip
|
||||
- PKCE code_verifier / code_challenge S256 shape
|
||||
- authorization URL params (response_type=code, S256, cli-proxy-api referrer)
|
||||
- submitOAuth2Consent action_id extraction from a next.js HTML page
|
||||
- _code_from_url state mismatch failure + success
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import base64
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def _load(name: str, path: Path):
|
||||
spec = importlib.util.spec_from_file_location(name, path)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
assert spec and spec.loader
|
||||
if "cpa_xai" not in sys.modules:
|
||||
pkg = type(sys)("cpa_xai")
|
||||
pkg.__path__ = [str(ROOT / "cpa_xai")] # type: ignore[attr-defined]
|
||||
sys.modules["cpa_xai"] = pkg
|
||||
sys.modules[name] = mod
|
||||
spec.loader.exec_module(mod)
|
||||
return mod
|
||||
|
||||
|
||||
def _b64url(raw: bytes) -> str:
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def test_grpcweb_roundtrip() -> None:
|
||||
gw = _load("cpa_xai.grpcweb", ROOT / "cpa_xai" / "grpcweb.py")
|
||||
|
||||
# single string field, field number 1
|
||||
msg = gw.encode_string(1, "https://accounts.x.ai/set-cookie?token=abc")
|
||||
frame = gw.frame_request(msg)
|
||||
parsed = gw.parse_response(frame)
|
||||
assert parsed.get("grpc_status") in (None, 0), parsed
|
||||
msgs = parsed["messages"]
|
||||
assert msgs, "no messages decoded"
|
||||
# messages is list[list[dict]]; first sub-message's first field is the string
|
||||
first_msg = msgs[0]
|
||||
str_fields = [f for f in first_msg if f.get("type") == "string"]
|
||||
assert str_fields, first_msg
|
||||
text = str_fields[0].get("value")
|
||||
assert text and "set-cookie" in text, text
|
||||
print("PASS grpcweb_roundtrip")
|
||||
|
||||
|
||||
def test_pkce_code_challenge_shape() -> None:
|
||||
pkce = _load("cpa_xai.pkce_mint", ROOT / "cpa_xai" / "pkce_mint.py")
|
||||
|
||||
verifier = pkce._code_verifier()
|
||||
challenge = pkce._code_challenge(verifier)
|
||||
|
||||
# verifier: 48 bytes -> 64 base64url chars, no padding
|
||||
assert len(verifier) == 64, len(verifier)
|
||||
assert "=" not in verifier
|
||||
# challenge == S256(verifier), b64url no padding
|
||||
expected = _b64url(hashlib.sha256(verifier.encode("ascii")).digest())
|
||||
assert challenge == expected, (challenge, expected)
|
||||
assert "=" not in challenge
|
||||
# different verifiers yield different challenges
|
||||
other = pkce._code_challenge(pkce._code_verifier())
|
||||
assert other != challenge
|
||||
print("PASS pkce_code_challenge_shape")
|
||||
|
||||
|
||||
def test_authorization_url_params() -> None:
|
||||
pkce = _load("cpa_xai.pkce_mint", ROOT / "cpa_xai" / "pkce_mint.py")
|
||||
|
||||
url = pkce._build_authorization_url(
|
||||
client_id="CLIENT-X",
|
||||
redirect_uri="http://127.0.0.1:56121/callback",
|
||||
state="ST",
|
||||
nonce="NN",
|
||||
code_challenge="CH",
|
||||
scope="openid offline_access",
|
||||
)
|
||||
assert url.startswith("https://auth.x.ai/oauth2/authorize?"), url
|
||||
qs = parse_qs(urlparse(url).query)
|
||||
assert qs["response_type"] == ["code"]
|
||||
assert qs["client_id"] == ["CLIENT-X"]
|
||||
assert qs["code_challenge_method"] == ["S256"]
|
||||
assert qs["code_challenge"] == ["CH"]
|
||||
assert qs["state"] == ["ST"]
|
||||
assert qs["nonce"] == ["NN"]
|
||||
assert qs["redirect_uri"] == ["http://127.0.0.1:56121/callback"]
|
||||
assert qs["scope"] == ["openid offline_access"]
|
||||
assert qs["referrer"] == ["cli-proxy-api"]
|
||||
print("PASS authorization_url_params")
|
||||
|
||||
|
||||
def test_submit_consent_action_id_extraction() -> None:
|
||||
pkce = _load("cpa_xai.pkce_mint", ROOT / "cpa_xai" / "pkce_mint.py")
|
||||
assert hasattr(pkce, "_extract_action_id_from_html"), (
|
||||
"_extract_action_id_from_html must be a first-class helper "
|
||||
"(inline-only extraction silently falls back to stale hardcoded action → live 404)"
|
||||
)
|
||||
extract = pkce._extract_action_id_from_html
|
||||
|
||||
# 1. explicit submitOAuth2Consent action wins (even when other actions present)
|
||||
html_named = (
|
||||
'<script>createServerReference)("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",'
|
||||
' "otherAction");'
|
||||
'createServerReference)("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",'
|
||||
' "submitOAuth2Consent");</script>'
|
||||
)
|
||||
assert extract(html_named) == "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
|
||||
|
||||
# 2. name before id (alternate bundle order)
|
||||
html_name_first = (
|
||||
'submitOAuth2Consent",{id:"cccccccccccccccccccccccccccccccccccccccccc"}'
|
||||
'createServerReference)("dddddddddddddddddddddddddddddddddddddddddd"'
|
||||
)
|
||||
# prefer explicit next-action / action id near submitOAuth2Consent
|
||||
aid2 = extract(html_name_first)
|
||||
assert aid2 in {
|
||||
"cccccccccccccccccccccccccccccccccccccccccc",
|
||||
"dddddddddddddddddddddddddddddddddddddddddd",
|
||||
}, aid2
|
||||
|
||||
# 3. empty / SPA shell HTML → None (must NOT silently return stale hardcoded id)
|
||||
assert extract("") is None
|
||||
assert extract("<html><body>loading</body></html>") is None
|
||||
assert extract(None) is None # type: ignore[arg-type]
|
||||
|
||||
# 4. single anonymous createServerReference → that id (last-resort page scrape)
|
||||
html_one = 'createServerReference)("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee", void 0)'
|
||||
assert extract(html_one) == "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
|
||||
|
||||
# 5. flight / quoted next-action style
|
||||
html_flight = (
|
||||
r'{"id":"ffffffffffffffffffffffffffffffffffffffffff",'
|
||||
r'"bound":null},"submitOAuth2Consent"'
|
||||
)
|
||||
assert extract(html_flight) == "ffffffffffffffffffffffffffffffffffffffffff"
|
||||
|
||||
# 6. fast-path constant = current known-good id (x.ai rotated it on
|
||||
# 2026-08-16 and moved the reference into a JS chunk). Extraction +
|
||||
# bundle-scan recover FUTURE rotations without this value changing.
|
||||
assert (
|
||||
pkce.SUBMIT_OAUTH2_CONSENT_ACTION
|
||||
== "40b2dd48cd9fcc160a2c686b89f9f3468af49c36ca"
|
||||
), "consent action id rotated by x.ai; refresh via bundle-scan evidence"
|
||||
print("PASS submit_consent_action_id_extraction")
|
||||
|
||||
|
||||
def test_bundle_scan_extracts_consent_server_ref() -> None:
|
||||
"""Consent-page JS chunks: the submitOAuth2Consent server reference (named in
|
||||
the createServerReference call's last arg) is selected; other page actions
|
||||
(e.g. getSession) are excluded even when they look structurally similar."""
|
||||
pkce = _load("cpa_xai.pkce_mint", ROOT / "cpa_xai" / "pkce_mint.py")
|
||||
extract = pkce._extract_consent_action_id_from_bundles
|
||||
NEW_ID = "40b2dd48cd9fcc160a2c686b89f9f3468af49c36ca"
|
||||
SESSION_ID = "0056df73d790f7426a8b29cf35e20cebc56e4c0fad"
|
||||
|
||||
consent_chunk = (
|
||||
'let n=(0,a.createServerReference)("%s",'
|
||||
'a.callServer,void 0,a.findSourceMapURL,"submitOAuth2Consent")' % NEW_ID
|
||||
)
|
||||
session_chunk = (
|
||||
'let n=(0,r.createServerReference)("%s",'
|
||||
'r.callServer,void 0,r.findSourceMapURL,"getSession")' % SESSION_ID
|
||||
)
|
||||
|
||||
class FakeResp:
|
||||
def __init__(self, text: str) -> None:
|
||||
self.text = text
|
||||
|
||||
class FakeSession:
|
||||
def __init__(self, chunk_map: dict) -> None:
|
||||
self.chunks = chunk_map
|
||||
|
||||
def get(self, url, **kw): # type: ignore[no-untyped-def]
|
||||
return FakeResp(self.chunks.get(url, ""))
|
||||
|
||||
def _session(*names: str):
|
||||
return FakeSession(
|
||||
{
|
||||
"https://accounts.x.ai/_next/static/chunks/consent.js": consent_chunk,
|
||||
"https://accounts.x.ai/_next/static/chunks/session.js": session_chunk,
|
||||
}
|
||||
)
|
||||
|
||||
# consent (single-arg) wins over getSession (multi-arg) regardless of order
|
||||
page_both = (
|
||||
'<script src="/_next/static/chunks/session.js"></script>'
|
||||
'<script src="/_next/static/chunks/consent.js"></script>'
|
||||
)
|
||||
assert extract(_session(), page_both) == NEW_ID
|
||||
|
||||
# only getSession present -> None (multi-arg form excluded)
|
||||
page_session_only = '<script src="/_next/static/chunks/session.js"></script>'
|
||||
assert extract(_session(), page_session_only) is None
|
||||
|
||||
# no script srcs / empty page / no session -> None
|
||||
assert extract(_session(), "<html>no scripts</html>") is None
|
||||
assert extract(_session(), "") is None
|
||||
assert extract(None, page_both) is None
|
||||
print("PASS bundle_scan_extracts_single_arg_server_ref")
|
||||
|
||||
|
||||
def test_submit_consent_recovers_via_bundle_scan() -> None:
|
||||
"""404 on stale hardcoded id -> bundle-scan finds the CSR single-arg id and
|
||||
completes the consent POST, returning the authorization code."""
|
||||
pkce = _load("cpa_xai.pkce_mint", ROOT / "cpa_xai" / "pkce_mint.py")
|
||||
STALE = "4005315a1d7e426de592990bb54bb37471f39dd6d2"
|
||||
NEW = "40b2dd48cd9fcc160a2c686b89f9f3468af49c36ca"
|
||||
CODE = "AUTHORIZATION_CODE_123"
|
||||
|
||||
page_html = (
|
||||
'<html><head></head><body>'
|
||||
'<form action="https://auth.x.ai/oauth2/authorize" method="POST">'
|
||||
'<input type="hidden" name="principal_type" value="User"/>'
|
||||
"</form>"
|
||||
'<script src="/_next/static/chunks/consent.js"></script>'
|
||||
"</body></html>"
|
||||
)
|
||||
consent_chunk = (
|
||||
'let n=(0,a.createServerReference)("%s",'
|
||||
'a.callServer,void 0,a.findSourceMapURL,"submitOAuth2Consent")' % NEW
|
||||
)
|
||||
calls = []
|
||||
|
||||
class FakeResp:
|
||||
def __init__(self, status: int, text: str) -> None:
|
||||
self.status_code = status
|
||||
self.text = text
|
||||
self.headers = {}
|
||||
|
||||
class FakeSession:
|
||||
def get(self, url, **kw): # type: ignore[no-untyped-def]
|
||||
calls.append(("GET", url))
|
||||
if "_next/static/chunks" in url:
|
||||
return FakeResp(200, consent_chunk)
|
||||
return FakeResp(200, page_html) # consent page re-fetch
|
||||
|
||||
def post(self, url, **kw): # type: ignore[no-untyped-def]
|
||||
aid = (kw.get("headers") or {}).get("next-action")
|
||||
calls.append(("POST", aid))
|
||||
if aid == STALE:
|
||||
return FakeResp(404, "Server action not found.")
|
||||
if aid == NEW:
|
||||
return FakeResp(
|
||||
200,
|
||||
'0:{"a":"$@1"}\n1:{"success":true,"action":"allow",'
|
||||
'"code":"%s"}' % CODE,
|
||||
)
|
||||
return FakeResp(404, "Server action not found.")
|
||||
|
||||
saved = pkce.SUBMIT_OAUTH2_CONSENT_ACTION
|
||||
pkce.SUBMIT_OAUTH2_CONSENT_ACTION = STALE # simulate a future rotation
|
||||
try:
|
||||
code = pkce._submit_consent(
|
||||
FakeSession(),
|
||||
page_url="https://accounts.x.ai/oauth2/consent?response_type=code&client_id=X",
|
||||
page_html=page_html,
|
||||
client_id="CLIENT-X",
|
||||
redirect_uri="http://127.0.0.1:56121/callback",
|
||||
scope="openid profile email",
|
||||
state="STATE-1",
|
||||
code_challenge="CHALLENGE",
|
||||
nonce="NONCE-1",
|
||||
)
|
||||
finally:
|
||||
pkce.SUBMIT_OAUTH2_CONSENT_ACTION = saved
|
||||
|
||||
assert code == CODE, code
|
||||
post_ids = [aid for kind, aid in calls if kind == "POST"]
|
||||
assert post_ids, calls
|
||||
assert post_ids[0] == STALE, post_ids # first attempt uses the stale constant
|
||||
assert NEW in post_ids, post_ids # bundle-scan recovery tried the new id
|
||||
print("PASS submit_consent_recovers_via_bundle_scan")
|
||||
|
||||
|
||||
def test_code_from_url_state_mismatch_and_success() -> None:
|
||||
pkce = _load("cpa_xai.pkce_mint", ROOT / "cpa_xai" / "pkce_mint.py")
|
||||
|
||||
# success
|
||||
code = pkce._code_from_url(
|
||||
"http://127.0.0.1:56121/callback?code=AC-123&state=ST", "ST"
|
||||
)
|
||||
assert code == "AC-123", code
|
||||
|
||||
# state mismatch -> PKCEMintError
|
||||
raised = False
|
||||
try:
|
||||
pkce._code_from_url(
|
||||
"http://127.0.0.1:56121/callback?code=AC-123&state=OTHER", "ST"
|
||||
)
|
||||
except pkce.PKCEMintError as e:
|
||||
raised = "state mismatch" in str(e).lower()
|
||||
assert e.code == "state_mismatch"
|
||||
assert e.retryable is True
|
||||
assert raised, "state mismatch should raise PKCEMintError"
|
||||
|
||||
# missing code -> PKCEMintError
|
||||
raised = False
|
||||
try:
|
||||
pkce._code_from_url("http://127.0.0.1:56121/callback?state=ST", "ST")
|
||||
except pkce.PKCEMintError as e:
|
||||
raised = "missing code" in str(e).lower()
|
||||
assert e.code == "missing_code"
|
||||
assert e.retryable is True
|
||||
assert raised, "missing code should raise PKCEMintError"
|
||||
print("PASS code_from_url_state_mismatch_and_success")
|
||||
|
||||
|
||||
def test_pkce_mint_error_structured_fields() -> None:
|
||||
pkce = _load("cpa_xai.pkce_mint", ROOT / "cpa_xai" / "pkce_mint.py")
|
||||
e = pkce.PKCEMintError(
|
||||
"consent HTML missing submitOAuth2Consent action id",
|
||||
code="consent_action_missing",
|
||||
retryable=False,
|
||||
)
|
||||
assert e.code == "consent_action_missing"
|
||||
assert e.retryable is False
|
||||
assert "consent" in str(e).lower()
|
||||
# defaults
|
||||
e2 = pkce.PKCEMintError("generic")
|
||||
assert e2.code == "pkce_error"
|
||||
assert e2.retryable is True
|
||||
print("PASS pkce_mint_error_structured_fields")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_grpcweb_roundtrip()
|
||||
test_pkce_code_challenge_shape()
|
||||
test_authorization_url_params()
|
||||
test_submit_consent_action_id_extraction()
|
||||
test_bundle_scan_extracts_consent_server_ref()
|
||||
test_submit_consent_recovers_via_bundle_scan()
|
||||
test_code_from_url_state_mismatch_and_success()
|
||||
test_pkce_mint_error_structured_fields()
|
||||
print("\nALL PKCE UNIT TESTS PASSED")
|
||||
@@ -0,0 +1,344 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unit checks: OAuth refresh rotation must persist; import is access-first."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import importlib.util
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def _load(name: str, path: Path):
|
||||
spec = importlib.util.spec_from_file_location(name, path)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
assert spec and spec.loader
|
||||
sys.modules[name] = mod
|
||||
if "cpa_xai" not in sys.modules:
|
||||
pkg = type(sys)("cpa_xai")
|
||||
pkg.__path__ = [str(ROOT / "cpa_xai")] # type: ignore[attr-defined]
|
||||
sys.modules["cpa_xai"] = pkg
|
||||
spec.loader.exec_module(mod)
|
||||
return mod
|
||||
|
||||
|
||||
def _jwt(exp: int, *, sub: str = "sub-1", iat: int | None = None) -> str:
|
||||
payload = base64.urlsafe_b64encode(
|
||||
json.dumps(
|
||||
{
|
||||
"exp": exp,
|
||||
"iat": iat if iat is not None else exp - 21600,
|
||||
"sub": sub,
|
||||
}
|
||||
).encode()
|
||||
).decode().rstrip("=")
|
||||
return f"aaa.{payload}.bbb"
|
||||
|
||||
|
||||
def test_refresh_auth_file_persists_rotated_refresh() -> None:
|
||||
refresh = _load("cpa_xai.refresh", ROOT / "cpa_xai" / "refresh.py")
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
p = Path(td) / "xai-a@b.com.json"
|
||||
p.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "xai",
|
||||
"email": "a@b.com",
|
||||
"refresh_token": "old-refresh",
|
||||
"access_token": "old-access",
|
||||
"token_endpoint": "https://auth.x.ai/oauth2/token",
|
||||
"base_url": "https://cli-chat-proxy.grok.com/v1",
|
||||
}
|
||||
)
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
fake_access = _jwt(2_000_000_000)
|
||||
|
||||
def fake_refresh_xai_tokens(**kwargs): # noqa: ANN003
|
||||
assert kwargs["refresh_token"] == "old-refresh"
|
||||
return {
|
||||
"ok": True,
|
||||
"status": 200,
|
||||
"access_token": fake_access,
|
||||
"refresh_token": "new-refresh-rotated",
|
||||
"refresh_rotated": True,
|
||||
"id_token": "",
|
||||
"expires_in": 21600,
|
||||
"token_type": "Bearer",
|
||||
}
|
||||
|
||||
with patch.object(refresh, "refresh_xai_tokens", side_effect=fake_refresh_xai_tokens):
|
||||
out = refresh.refresh_auth_file(p, persist=True)
|
||||
assert out["ok"] is True, out
|
||||
assert out["persisted"] is True
|
||||
assert out["refresh_rotated"] is True
|
||||
data = json.loads(p.read_text(encoding="utf-8"))
|
||||
assert data["refresh_token"] == "new-refresh-rotated"
|
||||
assert data["access_token"] == fake_access
|
||||
assert data.get("expired")
|
||||
# pre-rotate snapshot + rotation ledger
|
||||
snap_dir = p.parent / ".rt_prerotate"
|
||||
assert snap_dir.is_dir()
|
||||
assert list(snap_dir.glob("*.json"))
|
||||
ledger = p.parent / "rt_rotation.jsonl"
|
||||
assert ledger.is_file()
|
||||
line = ledger.read_text(encoding="utf-8").strip().splitlines()[-1]
|
||||
rec = json.loads(line)
|
||||
assert rec["old_rt"] == "old-refresh"
|
||||
assert rec["new_rt"] == "new-refresh-rotated"
|
||||
print("PASS refresh_auth_file persists rotated refresh + ledger")
|
||||
|
||||
|
||||
def test_refresh_auth_file_fail_closed_on_persist_verify() -> None:
|
||||
refresh = _load("cpa_xai.refresh", ROOT / "cpa_xai" / "refresh.py")
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
p = Path(td) / "xai-b@c.com.json"
|
||||
p.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "xai",
|
||||
"email": "b@c.com",
|
||||
"refresh_token": "rt-old",
|
||||
"access_token": "at-old",
|
||||
"token_endpoint": "https://auth.x.ai/oauth2/token",
|
||||
"base_url": "https://cli-chat-proxy.grok.com/v1",
|
||||
}
|
||||
)
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
fake_access = _jwt(2_000_000_000)
|
||||
|
||||
def fake_refresh_xai_tokens(**kwargs): # noqa: ANN003
|
||||
return {
|
||||
"ok": True,
|
||||
"status": 200,
|
||||
"access_token": fake_access,
|
||||
"refresh_token": "rt-new",
|
||||
"refresh_rotated": True,
|
||||
"id_token": "",
|
||||
"expires_in": 21600,
|
||||
"token_type": "Bearer",
|
||||
}
|
||||
|
||||
def broken_patch(path, updates): # noqa: ANN001
|
||||
# Write wrong RT to simulate silent corruption / race.
|
||||
body = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
body.update(updates or {})
|
||||
body["refresh_token"] = "CORRUPTED"
|
||||
Path(path).write_text(json.dumps(body) + "\n", encoding="utf-8")
|
||||
return body
|
||||
|
||||
def broken_write(auth_dir, payload, filename=None): # noqa: ANN001
|
||||
dest = Path(auth_dir) / (filename or "xai-x.json")
|
||||
payload = dict(payload)
|
||||
payload["refresh_token"] = "CORRUPTED"
|
||||
dest.write_text(json.dumps(payload) + "\n", encoding="utf-8")
|
||||
return dest
|
||||
|
||||
with (
|
||||
patch.object(refresh, "refresh_xai_tokens", side_effect=fake_refresh_xai_tokens),
|
||||
patch.object(refresh, "patch_cpa_xai_auth", side_effect=broken_patch),
|
||||
patch.object(refresh, "write_cpa_xai_auth", side_effect=broken_write),
|
||||
):
|
||||
out = refresh.refresh_auth_file(p, persist=True)
|
||||
assert out["ok"] is False, out
|
||||
assert out.get("error_code") in {
|
||||
"rt_persist_verify_failed",
|
||||
"rt_persist_failed",
|
||||
}
|
||||
assert out.get("fatal_rt_loss_risk") is True
|
||||
print("PASS refresh_auth_file fail-closed on persist verify")
|
||||
|
||||
|
||||
def test_refresh_persist_false_force_saves_rotated_rt() -> None:
|
||||
"""persist=False + rotate must not silently discard new RT."""
|
||||
refresh = _load("cpa_xai.refresh", ROOT / "cpa_xai" / "refresh.py")
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
p = Path(td) / "xai-c@d.com.json"
|
||||
p.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "xai",
|
||||
"email": "c@d.com",
|
||||
"refresh_token": "rt-old2",
|
||||
"access_token": "at-old2",
|
||||
"token_endpoint": "https://auth.x.ai/oauth2/token",
|
||||
"base_url": "https://cli-chat-proxy.grok.com/v1",
|
||||
}
|
||||
)
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
fake_access = _jwt(2_000_000_000)
|
||||
|
||||
def fake_refresh_xai_tokens(**kwargs): # noqa: ANN003
|
||||
return {
|
||||
"ok": True,
|
||||
"status": 200,
|
||||
"access_token": fake_access,
|
||||
"refresh_token": "rt-new2",
|
||||
"refresh_rotated": True,
|
||||
"id_token": "",
|
||||
"expires_in": 21600,
|
||||
"token_type": "Bearer",
|
||||
}
|
||||
|
||||
with patch.object(refresh, "refresh_xai_tokens", side_effect=fake_refresh_xai_tokens):
|
||||
out = refresh.refresh_auth_file(p, persist=False)
|
||||
# Forced persist should rescue the new RT.
|
||||
assert out["ok"] is True, out
|
||||
assert out.get("persist_forced") is True
|
||||
data = json.loads(p.read_text(encoding="utf-8"))
|
||||
assert data["refresh_token"] == "rt-new2"
|
||||
print("PASS persist=False still force-saves rotated RT")
|
||||
|
||||
|
||||
def test_ensure_auth_tokens_access_first_no_network() -> None:
|
||||
refresh = _load("cpa_xai.refresh", ROOT / "cpa_xai" / "refresh.py")
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
p = Path(td) / "xai-e@f.com.json"
|
||||
# access still valid for ~1 day
|
||||
at = _jwt(int(time.time()) + 86400)
|
||||
p.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "xai",
|
||||
"email": "e@f.com",
|
||||
"refresh_token": "rt-keep",
|
||||
"access_token": at,
|
||||
"token_endpoint": "https://auth.x.ai/oauth2/token",
|
||||
"base_url": "https://cli-chat-proxy.grok.com/v1",
|
||||
}
|
||||
)
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
def boom(**kwargs): # noqa: ANN003
|
||||
raise AssertionError("refresh_xai_tokens must not be called for valid access")
|
||||
|
||||
with patch.object(refresh, "refresh_xai_tokens", side_effect=boom):
|
||||
out = refresh.ensure_auth_tokens(p, force_refresh=False)
|
||||
assert out["ok"] is True, out
|
||||
assert out["source"] == "access_reuse"
|
||||
assert out["refresh_token"] == "rt-keep"
|
||||
assert out["refresh_rotated"] is False
|
||||
assert out["persisted"] is False
|
||||
# disk untouched
|
||||
data = json.loads(p.read_text(encoding="utf-8"))
|
||||
assert data["refresh_token"] == "rt-keep"
|
||||
assert data["access_token"] == at
|
||||
print("PASS ensure_auth_tokens access-first skips network")
|
||||
|
||||
|
||||
def test_ensure_auth_tokens_refreshes_when_access_expired() -> None:
|
||||
refresh = _load("cpa_xai.refresh", ROOT / "cpa_xai" / "refresh.py")
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
p = Path(td) / "xai-g@h.com.json"
|
||||
at = _jwt(int(time.time()) - 60) # already expired
|
||||
p.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"type": "xai",
|
||||
"email": "g@h.com",
|
||||
"refresh_token": "rt-old3",
|
||||
"access_token": at,
|
||||
"token_endpoint": "https://auth.x.ai/oauth2/token",
|
||||
"base_url": "https://cli-chat-proxy.grok.com/v1",
|
||||
}
|
||||
)
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
new_at = _jwt(int(time.time()) + 86400)
|
||||
|
||||
def fake_refresh_xai_tokens(**kwargs): # noqa: ANN003
|
||||
assert kwargs["refresh_token"] == "rt-old3"
|
||||
return {
|
||||
"ok": True,
|
||||
"status": 200,
|
||||
"access_token": new_at,
|
||||
"refresh_token": "rt-new3",
|
||||
"refresh_rotated": True,
|
||||
"id_token": "",
|
||||
"expires_in": 21600,
|
||||
"token_type": "Bearer",
|
||||
}
|
||||
|
||||
with patch.object(refresh, "refresh_xai_tokens", side_effect=fake_refresh_xai_tokens):
|
||||
out = refresh.ensure_auth_tokens(p, force_refresh=False)
|
||||
assert out["ok"] is True, out
|
||||
assert out.get("source") == "refresh"
|
||||
assert out["refresh_rotated"] is True
|
||||
data = json.loads(p.read_text(encoding="utf-8"))
|
||||
assert data["refresh_token"] == "rt-new3"
|
||||
assert data["access_token"] == new_at
|
||||
print("PASS ensure_auth_tokens refreshes when access expired")
|
||||
|
||||
|
||||
def test_import_script_access_first_markers() -> None:
|
||||
src = (ROOT / "scripts" / "import_cpa_auth_dir.py").read_text(encoding="utf-8")
|
||||
assert "ensure_auth_tokens" in src
|
||||
assert "force_refresh" in src
|
||||
assert "evaluate_remote_inject_gate" in src
|
||||
assert "apply_multi_remote_inject" in src
|
||||
# Archive / skip-reinject ops contract
|
||||
assert "cpa_remote_injected" in src
|
||||
assert "import_tested" in src
|
||||
assert "_stamp_import_result" in src
|
||||
assert "_maybe_archive_attempt" in src
|
||||
assert "skip_injected" in src
|
||||
assert "cpa_import_archive.jsonl" in src
|
||||
assert "DEFAULT_BATCH_SIZE = 5" in src
|
||||
assert "--batch-size" in src
|
||||
# Call order inside import_one: ensure_auth_tokens before probe_models/chat.
|
||||
fn_start = src.index("def import_one")
|
||||
fn_body = src[fn_start : src.index("\ndef main")]
|
||||
assert fn_body.index("ensure_auth_tokens(") < fn_body.index("probe_models(")
|
||||
assert fn_body.index("probe_models(") < fn_body.index("probe_mini_response(")
|
||||
# Must NOT unconditionally call refresh_auth_file at start of import_one.
|
||||
# (refresh only via ensure_auth_tokens when needed)
|
||||
assert "refresh_auth_file(" not in fn_body
|
||||
# main archives every real attempt
|
||||
main_body = src[src.index("def main") :]
|
||||
assert "_maybe_archive_attempt(" in main_body
|
||||
print("PASS import script access-first markers")
|
||||
|
||||
|
||||
def test_access_token_usable_skew() -> None:
|
||||
refresh = _load("cpa_xai.refresh", ROOT / "cpa_xai" / "refresh.py")
|
||||
now = time.time()
|
||||
assert refresh.access_token_usable(_jwt(int(now) + 500), now=now) is True
|
||||
assert refresh.access_token_usable(_jwt(int(now) + 30), skew_seconds=120, now=now) is False
|
||||
assert refresh.access_token_usable("", now=now) is False
|
||||
print("PASS access_token_usable skew")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
test_access_token_usable_skew()
|
||||
test_refresh_auth_file_persists_rotated_refresh()
|
||||
test_refresh_auth_file_fail_closed_on_persist_verify()
|
||||
test_refresh_persist_false_force_saves_rotated_rt()
|
||||
test_ensure_auth_tokens_access_first_no_network()
|
||||
test_ensure_auth_tokens_refreshes_when_access_expired()
|
||||
test_import_script_access_first_markers()
|
||||
print("\nALL PASS (cpa refresh persist + access-first)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,239 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Static checks for CPA remote inject helper."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def _load_cpa_export():
|
||||
spec = importlib.util.spec_from_file_location("cpa_export", ROOT / "cpa_export.py")
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
assert spec and spec.loader
|
||||
spec.loader.exec_module(mod)
|
||||
return mod
|
||||
|
||||
|
||||
def test_helpers_present() -> None:
|
||||
mod = _load_cpa_export()
|
||||
assert hasattr(mod, "inject_cpa_auth_remote")
|
||||
assert hasattr(mod, "_resolve_remote_ssh_password")
|
||||
assert hasattr(mod, "_config_bool")
|
||||
assert mod._config_bool("true") is True
|
||||
assert mod._config_bool("0") is False
|
||||
print("PASS helpers present")
|
||||
|
||||
|
||||
def test_disabled_skip() -> None:
|
||||
mod = _load_cpa_export()
|
||||
res = mod.inject_cpa_auth_remote(
|
||||
ROOT / "cpa_auths" / ".gitkeep",
|
||||
config={"cpa_remote_inject": False},
|
||||
log_callback=lambda m: None,
|
||||
)
|
||||
assert res.get("skipped") is True
|
||||
print("PASS disabled skip")
|
||||
|
||||
|
||||
def test_export_wires_remote_flag() -> None:
|
||||
src = (ROOT / "cpa_export.py").read_text(encoding="utf-8")
|
||||
assert "inject_cpa_auth_remote" in src
|
||||
assert "cpa_remote_inject" in src
|
||||
assert "remote_inject" in src
|
||||
# success path must call inject (regression from missing wire)
|
||||
assert "result[\"remote_inject\"]" in src or "result['remote_inject']" in src or 'result["remote_inject"]' in src
|
||||
# disk-first: inject off must short-circuit before gate skip side effects
|
||||
assert "remote_inject_disabled" in src
|
||||
assert "inject_disabled" in src
|
||||
assert "if inject_on and not skip_inject:" in src
|
||||
assert "ControlMaster=auto" in src
|
||||
assert "_REMOTE_DIR_READY" in src
|
||||
print("PASS export wires remote inject")
|
||||
|
||||
|
||||
def test_export_inject_off_no_gate_skip_side_effects() -> None:
|
||||
"""cpa_remote_inject=false must not mark remote_inject_skipped (disk-first)."""
|
||||
mod = _load_cpa_export()
|
||||
result = {
|
||||
"ok": True,
|
||||
"path": str(ROOT / "cpa_auths" / ".gitkeep"),
|
||||
"token_ok": True,
|
||||
"email": "diskfirst@example.com",
|
||||
"chat_ok": None,
|
||||
}
|
||||
cfg = {
|
||||
"cpa_remote_inject": False,
|
||||
"cpa_copy_to_hotload": False,
|
||||
"cpa_export_enabled": True,
|
||||
}
|
||||
# Simulate the inject-off branch of export_cpa_xai_for_account post-mint.
|
||||
inject_on = mod._config_bool(cfg.get("cpa_remote_inject"), default=False)
|
||||
assert inject_on is False
|
||||
if not inject_on:
|
||||
result["remote_inject_disabled"] = True
|
||||
result["remote_inject"] = {
|
||||
"ok": False,
|
||||
"disabled": True,
|
||||
"skipped": False,
|
||||
"reason": "inject_disabled",
|
||||
}
|
||||
assert result.get("remote_inject_skipped") is not True
|
||||
assert result.get("skip_remote_inject") is not True
|
||||
assert result["remote_inject"]["disabled"] is True
|
||||
assert result["remote_inject"]["skipped"] is False
|
||||
# apply_multi_remote_inject itself is a no-op when flag off
|
||||
out = mod.apply_multi_remote_inject(result, cfg, log_callback=lambda _m: None)
|
||||
assert out.get("remote_injects") is None or out is result
|
||||
print("PASS export inject off no gate skip side effects")
|
||||
|
||||
|
||||
def test_hotmail_adaptive_poll_markers() -> None:
|
||||
src = (ROOT / "grok_register_ttk.py").read_text(encoding="utf-8")
|
||||
assert 'current_interval = 0.0' in src
|
||||
assert "empty_rounds" in src
|
||||
assert '"hotmail_poll_interval": 2' in src
|
||||
print("PASS hotmail adaptive poll markers")
|
||||
|
||||
|
||||
def test_cli_remote_stats() -> None:
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
assert "remote_inject_ok" in src
|
||||
assert "tebi inject" in src
|
||||
assert "tebi注入成功" in src
|
||||
print("PASS cli remote stats")
|
||||
|
||||
|
||||
|
||||
def test_ssh_hardening_markers() -> None:
|
||||
src = (ROOT / "cpa_export.py").read_text(encoding="utf-8")
|
||||
for needle in (
|
||||
"cpa_remote_ssh_identity",
|
||||
"CPA_REMOTE_SSH_IDENTITY",
|
||||
"BatchMode=yes",
|
||||
"PasswordAuthentication=no",
|
||||
"StrictHostKeyChecking=",
|
||||
"cpa_remote_ssh_strict_hostkey",
|
||||
'or "yes"',
|
||||
"IdentitiesOnly=yes",
|
||||
):
|
||||
assert needle in src, f"missing ssh hardening marker: {needle}"
|
||||
# password path only when password and no key
|
||||
assert "use_password = bool(password) and not use_key" in src
|
||||
print("PASS ssh hardening markers")
|
||||
|
||||
|
||||
def test_inject_gate_refuses_require_chat_false() -> None:
|
||||
mod = _load_cpa_export()
|
||||
gate = mod.evaluate_remote_inject_gate(
|
||||
{"path": "/tmp/x.json", "chat_ok": True, "usable": True},
|
||||
{"cpa_remote_inject_require_chat_ok": False, "cpa_probe_chat": True},
|
||||
)
|
||||
assert gate.get("allow") is False
|
||||
assert gate.get("reason") == "chat_gate_disabled_refused"
|
||||
print("PASS inject gate refuses require_chat=false")
|
||||
|
||||
|
||||
def test_inject_gate_requires_chat_ok_even_when_probe_chat_off() -> None:
|
||||
"""cpa_probe_chat=false must not unlock inject without chat_ok."""
|
||||
mod = _load_cpa_export()
|
||||
denied = mod.evaluate_remote_inject_gate(
|
||||
{
|
||||
"path": "/tmp/x.json",
|
||||
"ok": True,
|
||||
"token_ok": True,
|
||||
"chat_ok": False,
|
||||
"usable": False,
|
||||
"fail_reason": "models_missing_grok_45",
|
||||
},
|
||||
{
|
||||
"cpa_remote_inject_require_chat_ok": True,
|
||||
"cpa_probe_chat": False,
|
||||
},
|
||||
)
|
||||
assert denied.get("allow") is False
|
||||
assert denied.get("chat_ok") is not True
|
||||
assert denied.get("reason") not in ("chat_ok", None, "")
|
||||
|
||||
allowed = mod.evaluate_remote_inject_gate(
|
||||
{
|
||||
"path": "/tmp/x.json",
|
||||
"chat_ok": True,
|
||||
"usable": True,
|
||||
"entitlement_denied": False,
|
||||
},
|
||||
{
|
||||
"cpa_remote_inject_require_chat_ok": True,
|
||||
"cpa_probe_chat": False,
|
||||
},
|
||||
)
|
||||
assert allowed.get("allow") is True
|
||||
assert allowed.get("reason") == "chat_ok"
|
||||
print("PASS inject gate requires chat_ok even when probe_chat off")
|
||||
|
||||
|
||||
def test_inject_gate_chat_ok_missing_unstamped() -> None:
|
||||
"""Path-only / unstamped auth must refuse with chat_ok_missing (never soft-inject)."""
|
||||
mod = _load_cpa_export()
|
||||
gate = mod.evaluate_remote_inject_gate(
|
||||
{
|
||||
"path": "/tmp/unstamped-xai.json",
|
||||
"ok": True,
|
||||
"token_ok": True,
|
||||
# chat_ok deliberately absent (None) — no probe stamp written
|
||||
},
|
||||
{
|
||||
"cpa_remote_inject_require_chat_ok": True,
|
||||
"cpa_probe_chat": True,
|
||||
},
|
||||
)
|
||||
assert gate.get("allow") is False
|
||||
assert gate.get("reason") == "chat_ok_missing"
|
||||
assert gate.get("chat_ok") is not True
|
||||
|
||||
# Explicit None + empty import_gate also maps to chat_ok_missing
|
||||
gate2 = mod.evaluate_remote_inject_gate(
|
||||
{
|
||||
"path": "/tmp/unstamped-xai.json",
|
||||
"chat_ok": None,
|
||||
"usable": None,
|
||||
},
|
||||
{"cpa_remote_inject_require_chat_ok": True},
|
||||
)
|
||||
assert gate2.get("allow") is False
|
||||
assert gate2.get("reason") == "chat_ok_missing"
|
||||
|
||||
src = (ROOT / "cpa_export.py").read_text(encoding="utf-8")
|
||||
assert "chat_ok_missing" in src
|
||||
assert "never soft-inject" in src
|
||||
print("PASS inject gate chat_ok_missing for unstamped auth")
|
||||
|
||||
|
||||
def test_config_example_ssh_and_soft_flags() -> None:
|
||||
src = (ROOT / "config.example.json").read_text(encoding="utf-8")
|
||||
assert '"cpa_remote_ssh_identity"' in src
|
||||
assert '"cpa_remote_ssh_strict_hostkey"' in src
|
||||
assert "chat_gate_disabled_refused" in src
|
||||
assert "不再软通过" in src or "不再软放行" in src
|
||||
print("PASS config.example ssh + soft-flag docs")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
test_helpers_present()
|
||||
test_disabled_skip()
|
||||
test_export_wires_remote_flag()
|
||||
test_hotmail_adaptive_poll_markers()
|
||||
test_cli_remote_stats()
|
||||
test_ssh_hardening_markers()
|
||||
test_inject_gate_refuses_require_chat_false()
|
||||
test_inject_gate_requires_chat_ok_even_when_probe_chat_off()
|
||||
test_inject_gate_chat_ok_missing_unstamped()
|
||||
test_config_example_ssh_and_soft_flags()
|
||||
print("\nALL PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,329 @@
|
||||
# test_email_ip_correlation.py
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
import node_score as ns
|
||||
|
||||
|
||||
def _reset():
|
||||
ns.reset_cache()
|
||||
for k in ("NODE_SCORE", "NODE_SCORE_ENABLED", "NODE_SCORE_PATH",
|
||||
"EMAIL_IP_CORRELATION"):
|
||||
os.environ.pop(k, None)
|
||||
ns.set_enabled(None)
|
||||
ns.set_correlation_enabled(None)
|
||||
|
||||
|
||||
def setup_function(_):
|
||||
_reset()
|
||||
|
||||
|
||||
def teardown_function(_):
|
||||
_reset()
|
||||
|
||||
|
||||
def test_correlation_disabled_by_default():
|
||||
assert ns.correlation_enabled() is False
|
||||
|
||||
|
||||
def test_correlation_env_enables():
|
||||
os.environ["EMAIL_IP_CORRELATION"] = "1"
|
||||
assert ns.correlation_enabled() is True
|
||||
|
||||
|
||||
def test_correlation_env_empty_or_falsy_off():
|
||||
os.environ["EMAIL_IP_CORRELATION"] = "" # empty != unset; stays OFF
|
||||
assert ns.correlation_enabled() is False
|
||||
os.environ["EMAIL_IP_CORRELATION"] = "0"
|
||||
assert ns.correlation_enabled() is False
|
||||
os.environ["EMAIL_IP_CORRELATION"] = "false"
|
||||
assert ns.correlation_enabled() is False
|
||||
|
||||
|
||||
def test_correlation_cfg_enables():
|
||||
assert ns.correlation_enabled({"email_ip_correlation": True}) is True
|
||||
|
||||
|
||||
def test_correlation_cfg_falsy_string_off():
|
||||
# a non-empty-but-falsy string must NOT pass bool-truthiness as True
|
||||
assert ns.correlation_enabled({"email_ip_correlation": "false"}) is False
|
||||
|
||||
|
||||
def test_correlation_override_enables():
|
||||
ns.set_correlation_enabled(True)
|
||||
assert ns.correlation_enabled() is True
|
||||
|
||||
|
||||
def test_correlation_env_beats_override_and_cfg():
|
||||
os.environ["EMAIL_IP_CORRELATION"] = "0" # env wins -> OFF even if override ON
|
||||
ns.set_correlation_enabled(True)
|
||||
assert ns.correlation_enabled() is False
|
||||
os.environ.pop("EMAIL_IP_CORRELATION", None)
|
||||
assert ns.correlation_enabled() is True # now override takes effect
|
||||
|
||||
|
||||
def test_empty_store_has_no_domains_pairs_keys(tmp_path):
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
store = ns._empty_store()
|
||||
assert "domains" not in store
|
||||
assert "pairs" not in store
|
||||
|
||||
|
||||
def _seed_domains_store(tmp_path, domains):
|
||||
"""Write a node_scores.json with a domains block for read tests."""
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
import json
|
||||
p = tmp_path / "s.json"
|
||||
p.write_text(json.dumps({"version": 1, "nodes": {}, "domains": domains}),
|
||||
encoding="utf-8")
|
||||
return p
|
||||
|
||||
|
||||
def test_domain_score_unknown_returns_default(tmp_path):
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
assert ns.get_domain_score("nope.example") == ns.DEFAULT_SCORE
|
||||
|
||||
|
||||
def test_domain_score_known(tmp_path):
|
||||
_seed_domains_store(tmp_path, {"a.com": {"score": 73, "cool_until": 0.0,
|
||||
"ok": 2, "fail_ts": 0}})
|
||||
# reads are gated by the correlation switch (DEFAULT_SCORE when OFF)
|
||||
ns.set_correlation_enabled(True)
|
||||
assert ns.get_domain_score("a.com") == 73
|
||||
|
||||
|
||||
def test_record_domain_disabled_noop(tmp_path):
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
import json
|
||||
ns.set_correlation_enabled(False) # OFF must not touch store
|
||||
out = ns.record_domain("a.com", "turnstile")
|
||||
assert out["ok"] is False
|
||||
assert out["reason"] == "disabled"
|
||||
# store file should NOT be created by a disabled write
|
||||
assert not (tmp_path / "s.json").exists()
|
||||
|
||||
|
||||
def test_record_domain_turnstile_pens_and_writes_domains_key(tmp_path):
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
ns.set_correlation_enabled(True)
|
||||
out = ns.record_domain("a.com", "turnstile")
|
||||
assert out["ok"] is True
|
||||
assert out["domain"] == "a.com"
|
||||
assert out["score"] == ns.DEFAULT_SCORE - ns.PENALTY_TURNSTILE
|
||||
import json
|
||||
data = json.loads((tmp_path / "s.json").read_text(encoding="utf-8"))
|
||||
assert "domains" in data and "a.com" in data["domains"]
|
||||
assert data["domains"]["a.com"]["score"] == out["score"]
|
||||
assert data["domains"]["a.com"]["cool_until"] > 0
|
||||
# IP nodes dict still empty (cross-dimension isolation)
|
||||
assert data["nodes"] == {}
|
||||
|
||||
|
||||
def test_record_domain_reg_ok_clears_cool(tmp_path):
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
import json, time
|
||||
_seed_domains_store(
|
||||
tmp_path,
|
||||
{"a.com": {"score": 35, "cool_until": time.time() + 999, "ok": 0,
|
||||
"fail_ts": 1, "fail_boot": 0, "updated": 0}},
|
||||
)
|
||||
ns.set_correlation_enabled(True)
|
||||
out = ns.record_domain("a.com", "reg_ok")
|
||||
assert out["ok"] is True
|
||||
assert out["score"] == 35 + ns.SUCCESS_REG
|
||||
data = json.loads((tmp_path / "s.json").read_text(encoding="utf-8"))
|
||||
assert data["domains"]["a.com"]["cool_until"] == 0.0
|
||||
assert data["domains"]["a.com"]["ok"] == 1
|
||||
|
||||
|
||||
def test_kind_effect_pure_no_mutate():
|
||||
entry = {"score": 50, "ok": 0, "fail_ts": 0, "fail_boot": 0,
|
||||
"cool_until": 0.0}
|
||||
snap = dict(entry)
|
||||
d, c = ns._kind_effect("turnstile", entry)
|
||||
assert d == -ns.PENALTY_TURNSTILE
|
||||
assert c == ns.COOL_TURNSTILE_S
|
||||
# entry untouched
|
||||
assert entry == snap
|
||||
|
||||
|
||||
def test_record_domain_repairs_corrupt_domains_key(tmp_path):
|
||||
import json
|
||||
p = tmp_path / "c.json"
|
||||
p.write_text(json.dumps({"version": 1, "nodes": {"x": {"score": 80}},
|
||||
"domains": "NOT-A-DICT"}), encoding="utf-8")
|
||||
os.environ["NODE_SCORE_PATH"] = str(p)
|
||||
ns.set_correlation_enabled(True)
|
||||
out = ns.record_domain("a.com", "reg_ok")
|
||||
assert out["ok"] is True
|
||||
data = json.loads(p.read_text(encoding="utf-8"))
|
||||
# IP untouched
|
||||
assert data["nodes"] == {"x": {"score": 80}}
|
||||
# corrupt domains replaced with a dict holding the new entry
|
||||
assert isinstance(data["domains"], dict) and "a.com" in data["domains"]
|
||||
|
||||
|
||||
def test_record_domain_none_kind_does_not_raise(tmp_path):
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "n.json")
|
||||
ns.set_correlation_enabled(True)
|
||||
out = ns.record_domain("a.com", None) # must not AttributeError
|
||||
assert out["ok"] is True
|
||||
# None kind falls to OTHER in _kind_effect
|
||||
import json
|
||||
data = json.loads((tmp_path / "n.json").read_text(encoding="utf-8"))
|
||||
assert data["domains"]["a.com"]["score"] == ns.DEFAULT_SCORE - ns.PENALTY_OTHER
|
||||
|
||||
|
||||
def test_record_domain_double_cool_on_second_consecutive_turnstile(tmp_path):
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "dc.json")
|
||||
ns.set_correlation_enabled(True)
|
||||
first = ns.record_domain("a.com", "turnstile")
|
||||
assert first["ok"] is True
|
||||
second = ns.record_domain("a.com", "turnstile")
|
||||
assert second["ok"] is True
|
||||
import json, time
|
||||
data = json.loads((tmp_path / "dc.json").read_text(encoding="utf-8"))
|
||||
dom = data["domains"]["a.com"]
|
||||
assert dom["fail_ts"] == 2
|
||||
# doubled == 2 x COOL_TURNSTILE_S beyond now (within epsilon)
|
||||
assert dom["cool_until"] > time.time() + ns.COOL_TURNSTILE_S + 60
|
||||
|
||||
|
||||
def test_get_pair_disabled_returns_empty(tmp_path):
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
assert ns.get_pair("a.com", "n1") == {}
|
||||
|
||||
|
||||
def test_record_pair_disabled_noop_no_file(tmp_path):
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
out = ns.record_pair("a.com", "n1", "turnstile")
|
||||
assert out["ok"] is False
|
||||
assert not (tmp_path / "s.json").exists()
|
||||
|
||||
|
||||
def test_record_pair_ok_creates_pairs_and_rewards(tmp_path):
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
ns.set_correlation_enabled(True)
|
||||
out = ns.record_pair("a.com", "n1", "mint_ok")
|
||||
assert out["ok"] is True
|
||||
assert out["pair"] == "a.com|n1"
|
||||
assert out["score"] == ns.DEFAULT_SCORE + ns.SUCCESS_MINT
|
||||
import json
|
||||
data = json.loads((tmp_path / "s.json").read_text(encoding="utf-8"))
|
||||
assert "pairs" in data and "a.com|n1" in data["pairs"]
|
||||
assert data["nodes"] == {} and data.get("domains", {}) == {}
|
||||
|
||||
|
||||
def test_pair_is_cooled_respects_switch(tmp_path):
|
||||
import json, time
|
||||
p = tmp_path / "s.json"
|
||||
p.write_text(json.dumps({
|
||||
"version": 1, "nodes": {},
|
||||
"pairs": {"a.com|n1": {"score": 40, "cool_until": time.time() + 600,
|
||||
"ok": 0, "fail_ts": 1}},
|
||||
}), encoding="utf-8")
|
||||
os.environ["NODE_SCORE_PATH"] = str(p)
|
||||
# OFF -> never cooled (correlation not active)
|
||||
assert ns.pair_is_cooled("a.com", "n1") is False
|
||||
ns.set_correlation_enabled(True)
|
||||
assert ns.pair_is_cooled("a.com", "n1") is True
|
||||
assert ns.pair_is_cooled("a.com", "n1", now=time.time() + 99999) is False
|
||||
|
||||
|
||||
def test_record_pair_fail_then_cool_and_recover(tmp_path):
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
ns.set_correlation_enabled(True)
|
||||
ns.record_pair("a.com", "n1", "turnstile")
|
||||
assert ns.pair_is_cooled("a.com", "n1") is True
|
||||
# a success clears the cool
|
||||
ns.record_pair("a.com", "n1", "reg_ok")
|
||||
assert ns.pair_is_cooled("a.com", "n1") is False
|
||||
|
||||
|
||||
def test_corrupt_pairs_key_degrades_to_empty(tmp_path):
|
||||
import json
|
||||
p = tmp_path / "s.json"
|
||||
p.write_text(json.dumps({"version": 1, "nodes": {"x": {"score": 80}},
|
||||
"pairs": "NOT-A-DICT"}), encoding="utf-8")
|
||||
os.environ["NODE_SCORE_PATH"] = str(p)
|
||||
ns.set_correlation_enabled(True)
|
||||
# reads degrade cleanly
|
||||
assert ns.get_pair("a.com", "n1") == {}
|
||||
assert ns.pair_is_cooled("a.com", "n1") is False
|
||||
# and a fresh write repairs the key without dropping nodes
|
||||
out = ns.record_pair("a.com", "n1", "reg_ok")
|
||||
assert out["ok"] is True
|
||||
data = json.loads(p.read_text(encoding="utf-8"))
|
||||
assert data["nodes"] == {"x": {"score": 80}}
|
||||
assert "a.com|n1" in data["pairs"]
|
||||
|
||||
|
||||
def test_domain_weights_disabled_uniform(tmp_path):
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
_seed_domains_store(tmp_path, {"a.com": {"score": 90}, "b.com": {"score": 10}})
|
||||
ns.set_correlation_enabled(False)
|
||||
w = ns.domain_weights(["a.com", "b.com"])
|
||||
assert w == [1.0, 1.0]
|
||||
|
||||
|
||||
def test_domain_weights_single_domain_uniform():
|
||||
ns.set_correlation_enabled(True)
|
||||
assert ns.domain_weights(["only.com"]) == [1.0]
|
||||
assert ns.domain_weights([]) == []
|
||||
|
||||
|
||||
def test_domain_weights_skews_by_score(tmp_path):
|
||||
_seed_domains_store(tmp_path, {"a.com": {"score": 90, "ok": 1},
|
||||
"b.com": {"score": 10, "ok": 0}})
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
ns.set_correlation_enabled(True)
|
||||
w = ns.domain_weights(["a.com", "b.com"])
|
||||
assert w[0] > w[1]
|
||||
assert w[0] == pytest.approx(91.0)
|
||||
assert w[1] == pytest.approx(11.0)
|
||||
|
||||
|
||||
def test_domain_weights_unknown_domain_gets_default():
|
||||
ns.set_correlation_enabled(True)
|
||||
w = ns.domain_weights(["never.example", "also.unknown"])
|
||||
assert w[0] == w[1] == pytest.approx(ns.DEFAULT_SCORE + 1.0)
|
||||
|
||||
|
||||
def test_preferred_node_returns_none_when_disabled(tmp_path):
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
ns.set_correlation_enabled(False)
|
||||
assert ns.preferred_node_for("a.com", ["n1", "n2"], "n1") is None
|
||||
|
||||
|
||||
def test_preferred_node_picks_good_uncooled_not_now(tmp_path):
|
||||
import json
|
||||
_seed_domains_store(tmp_path, {})
|
||||
p = tmp_path / "s.json"
|
||||
p.write_text(json.dumps({"version": 1, "nodes": {},
|
||||
"pairs": {"a.com|n1": {"score": 80, "ok": 2, "cool_until": 0.0},
|
||||
"a.com|n2": {"score": 70, "ok": 1, "cool_until": 0.0}}}),
|
||||
encoding="utf-8")
|
||||
os.environ["NODE_SCORE_PATH"] = str(p)
|
||||
ns.set_correlation_enabled(True)
|
||||
# now=n1 -> must avoid n1, pick n2 (best remaining good node)
|
||||
assert ns.preferred_node_for("a.com", ["n1", "n2", "n3"], "n1") == "n2"
|
||||
# now=n2 -> pick n1 (highest-scoring good node != now)
|
||||
assert ns.preferred_node_for("a.com", ["n1", "n2", "n3"], "n2") == "n1"
|
||||
|
||||
|
||||
def test_preferred_node_none_when_all_cooled(tmp_path):
|
||||
import json, time
|
||||
p = tmp_path / "s.json"
|
||||
p.write_text(json.dumps({"version": 1, "nodes": {},
|
||||
"pairs": {"a.com|n1": {"score": 80, "ok": 2,
|
||||
"cool_until": time.time() + 600}}}),
|
||||
encoding="utf-8")
|
||||
os.environ["NODE_SCORE_PATH"] = str(p)
|
||||
ns.set_correlation_enabled(True)
|
||||
assert ns.preferred_node_for("a.com", ["n1", "n2"], "n2") is None
|
||||
|
||||
|
||||
def test_preferred_node_none_when_no_pair():
|
||||
ns.set_correlation_enabled(True)
|
||||
assert ns.preferred_node_for("a.com", ["n1", "n2"], "n1") is None
|
||||
@@ -0,0 +1,86 @@
|
||||
"""§5.A — OFF-equivalence closing sweep (highest-priority regression line).
|
||||
|
||||
EMAIL_IP_CORRELATION OFF must equal today's behavior across:
|
||||
* mail sampling (sample_accounts == random.shuffle),
|
||||
* node rotation (pick_next == round-robin as today),
|
||||
* attribution (no domains/pairs keys ever written under OFF).
|
||||
|
||||
These guards are the feature's ship gate; if any fails, the feature stays OFF.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
|
||||
import pytest
|
||||
|
||||
import mail_pool_probe as mpp
|
||||
import node_score as ns
|
||||
import proxy_rotate as pr # noqa: F401 (import-safety + parity)
|
||||
|
||||
|
||||
def _reset():
|
||||
for k in ("EMAIL_IP_CORRELATION", "NODE_SCORE", "NODE_SCORE_ENABLED",
|
||||
"NODE_SCORE_PATH"):
|
||||
os.environ.pop(k, None)
|
||||
ns.reset_cache()
|
||||
ns.set_enabled(None)
|
||||
ns.set_correlation_enabled(None)
|
||||
|
||||
|
||||
def setup_function(_):
|
||||
_reset()
|
||||
|
||||
|
||||
def teardown_function(_):
|
||||
_reset()
|
||||
|
||||
|
||||
# §5.A — mail sampling OFF == random.shuffle (byte-identical)
|
||||
def test_off_mail_sampling_byte_identical_to_shuffle(tmp_path):
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
pool = []
|
||||
for d in ("a.com", "b.com", "c.com"):
|
||||
for i in range(15):
|
||||
pool.append(mpp.Credential(
|
||||
email=f"u{i}@{d}", password="p",
|
||||
client_id="c", refresh_token="r"))
|
||||
# The OFF branch calls random.shuffle(pool) and slices. To compare
|
||||
# byte-identically we reseed to the SAME state just before both shuffles:
|
||||
# sample_accounts consumes the module RNG once via random.shuffle, so we
|
||||
# reseed identically before each of the two shuffles (see mail_pool_probe
|
||||
# sample_accounts OFF path — verbatim random.shuffle + slice).
|
||||
random.seed(2026)
|
||||
want = list(pool)
|
||||
random.shuffle(want)
|
||||
want = want[:11]
|
||||
random.seed(2026)
|
||||
ns.set_correlation_enabled(False) # explicitly OFF
|
||||
got = mpp.sample_accounts(list(pool), 11, cfg={})
|
||||
assert got == want
|
||||
# store untouched (no domains/pairs keys injected when OFF)
|
||||
assert not (tmp_path / "s.json").exists()
|
||||
|
||||
|
||||
# §5.A — node rotation OFF == round-robin / pick_next-as-today
|
||||
def test_off_node_rotation_unchanged(tmp_path):
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
# OFF both switches -> pick_next == _round_robin
|
||||
nodes = ["n0", "n1", "n2", "n3"]
|
||||
assert ns.pick_next(nodes, "n0", cfg={}) == "n1"
|
||||
assert ns.pick_next(nodes, "n2", cfg={}) == "n3"
|
||||
|
||||
|
||||
# §5.A — attribution boundary OFF: pre-code failure still does NOT dock IP
|
||||
def test_off_no_domains_or_pairs_written_via_records(tmp_path):
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
# EMAIL_IP_CORRELATION OFF but NODE_SCORE ON: store must stay IP-only.
|
||||
os.environ["NODE_SCORE"] = "1"
|
||||
ns.set_correlation_enabled(False)
|
||||
ns.record("n1", "reg_ok", cfg={}) # IP record works
|
||||
assert ns.record_domain("a.com", "turnstile", cfg={})["ok"] is False
|
||||
assert ns.record_pair("a.com", "n1", "turnstile", cfg={})["ok"] is False
|
||||
data = json.loads((tmp_path / "s.json").read_text(encoding="utf-8"))
|
||||
assert "n1" in data["nodes"]
|
||||
assert "domains" not in data # lazy: never written under OFF
|
||||
assert "pairs" not in data
|
||||
@@ -0,0 +1,355 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unit tests for EMAIL_PROVIDERS multi-select pool + attempt bind."""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
|
||||
def _stub_heavy_deps() -> None:
|
||||
"""Allow importing grok_register_ttk without tkinter/DrissionPage in CI/headless."""
|
||||
import types
|
||||
|
||||
if "tkinter" not in sys.modules:
|
||||
tk = types.ModuleType("tkinter")
|
||||
tk.StringVar = object
|
||||
tk.BooleanVar = object
|
||||
tk.END = "end"
|
||||
for attr in ("W", "E", "N", "S", "EW", "BOTH", "X", "Y", "LEFT"):
|
||||
setattr(tk, attr, attr.lower())
|
||||
tk.Tk = type("Tk", (), {})
|
||||
sys.modules["tkinter"] = tk
|
||||
for sub in ("ttk", "messagebox", "scrolledtext"):
|
||||
sys.modules[f"tkinter.{sub}"] = types.ModuleType(f"tkinter.{sub}")
|
||||
sys.modules["tkinter.ttk"] = types.ModuleType("tkinter.ttk")
|
||||
if "DrissionPage" not in sys.modules:
|
||||
dp = types.ModuleType("DrissionPage")
|
||||
dp.Chromium = object
|
||||
dp.ChromiumOptions = object
|
||||
sys.modules["DrissionPage"] = dp
|
||||
err = types.ModuleType("DrissionPage.errors")
|
||||
err.PageDisconnectedError = type("PageDisconnectedError", (Exception,), {})
|
||||
sys.modules["DrissionPage.errors"] = err
|
||||
if "curl_cffi" not in sys.modules:
|
||||
cc = types.ModuleType("curl_cffi")
|
||||
req = types.ModuleType("curl_cffi.requests")
|
||||
cc.requests = req
|
||||
sys.modules["curl_cffi"] = cc
|
||||
sys.modules["curl_cffi.requests"] = req
|
||||
|
||||
|
||||
def _load():
|
||||
try:
|
||||
_stub_heavy_deps()
|
||||
import grok_register_ttk as m
|
||||
|
||||
return m
|
||||
except Exception as e:
|
||||
print("SKIP full import:", type(e).__name__, e)
|
||||
return None
|
||||
|
||||
|
||||
def _reset_pool_state(m) -> None:
|
||||
m.clear_email_provider_bind()
|
||||
m.reset_email_provider_failover()
|
||||
with m._email_provider_rr_lock:
|
||||
m._email_provider_rr_index = 0
|
||||
|
||||
|
||||
def test_parse_email_providers_list() -> None:
|
||||
m = _load()
|
||||
if m is None:
|
||||
src = (ROOT / "grok_register_ttk.py").read_text(encoding="utf-8")
|
||||
assert "def parse_email_providers_list" in src
|
||||
print("PASS parse (source contract)")
|
||||
return
|
||||
assert m.parse_email_providers_list("duckmail, cloudmail;cloudflare") == [
|
||||
"duckmail",
|
||||
"cloudmail",
|
||||
"cloudflare",
|
||||
]
|
||||
assert m.parse_email_providers_list(["outlookmail", "cf", "duckmail", "duckmail"]) == [
|
||||
"hotmail",
|
||||
"cloudflare",
|
||||
"duckmail",
|
||||
]
|
||||
assert m.parse_email_providers_list("") == []
|
||||
assert m.parse_email_providers_list(None) == []
|
||||
try:
|
||||
m.parse_email_providers_list("duckmail,not_a_real_provider")
|
||||
raise AssertionError("expected unknown provider to fail")
|
||||
except Exception as exc:
|
||||
assert "未知" in str(exc) or "unknown" in str(exc).lower()
|
||||
try:
|
||||
m.parse_email_providers_list("fixed,duckmail")
|
||||
raise AssertionError("expected fixed to fail")
|
||||
except Exception as exc:
|
||||
assert "fixed" in str(exc).lower()
|
||||
# gmail is allowed in multi-select pool (operators own IMAP miss risk).
|
||||
assert m.parse_email_providers_list("gmail,cloudflare") == ["gmail", "cloudflare"]
|
||||
assert "gmail" in m._EMAIL_PROVIDER_POOL_KNOWN
|
||||
print("PASS parse_email_providers_list")
|
||||
|
||||
|
||||
def test_round_robin_and_bind() -> None:
|
||||
m = _load()
|
||||
if m is None:
|
||||
print("SKIP round_robin (import failed)")
|
||||
return
|
||||
old_env = {k: os.environ.get(k) for k in ("EMAIL_PROVIDERS", "EMAIL_PROVIDER", "EMAIL_PROVIDER_STRATEGY", "FIXED_EMAIL", "MIMO_FIXED_EMAIL")}
|
||||
old_cfg = dict(m.config)
|
||||
try:
|
||||
os.environ.pop("FIXED_EMAIL", None)
|
||||
os.environ.pop("MIMO_FIXED_EMAIL", None)
|
||||
os.environ["EMAIL_PROVIDERS"] = "duckmail,cloudmail,cloudflare"
|
||||
os.environ["EMAIL_PROVIDER_STRATEGY"] = "round_robin"
|
||||
m.config = dict(old_cfg)
|
||||
m.config["email_provider"] = "hotmail"
|
||||
_reset_pool_state(m)
|
||||
|
||||
pool = m.get_email_providers_pool()
|
||||
assert pool == ["duckmail", "cloudmail", "cloudflare"]
|
||||
|
||||
picks = [m.select_email_provider_from_pool(pool, strategy="round_robin", bind=True) for _ in range(4)]
|
||||
assert picks == ["duckmail", "cloudmail", "cloudflare", "duckmail"]
|
||||
# last bind still cloudflare? no — last select was duckmail
|
||||
assert m.get_bound_email_provider() == "duckmail"
|
||||
assert m.get_email_provider() == "duckmail"
|
||||
|
||||
m.clear_email_provider_bind()
|
||||
assert m.get_bound_email_provider() is None
|
||||
# unbound multi-select reports first pool member for UI/logs
|
||||
assert m.get_email_provider() == "duckmail"
|
||||
print("PASS round_robin_and_bind")
|
||||
finally:
|
||||
m.config = old_cfg
|
||||
_reset_pool_state(m)
|
||||
for k, v in old_env.items():
|
||||
if v is None:
|
||||
os.environ.pop(k, None)
|
||||
else:
|
||||
os.environ[k] = v
|
||||
|
||||
|
||||
def test_failover_advance() -> None:
|
||||
m = _load()
|
||||
if m is None:
|
||||
print("SKIP failover")
|
||||
return
|
||||
old_env = {k: os.environ.get(k) for k in ("EMAIL_PROVIDERS", "EMAIL_PROVIDER_STRATEGY", "FIXED_EMAIL", "MIMO_FIXED_EMAIL")}
|
||||
old_cfg = dict(m.config)
|
||||
try:
|
||||
os.environ.pop("FIXED_EMAIL", None)
|
||||
os.environ.pop("MIMO_FIXED_EMAIL", None)
|
||||
os.environ["EMAIL_PROVIDERS"] = "cloudflare,duckmail"
|
||||
os.environ["EMAIL_PROVIDER_STRATEGY"] = "failover"
|
||||
m.config = dict(old_cfg)
|
||||
_reset_pool_state(m)
|
||||
|
||||
a = m.select_email_provider_from_pool(strategy="failover", bind=True)
|
||||
assert a == "cloudflare"
|
||||
m.advance_email_provider_failover()
|
||||
b = m.select_email_provider_from_pool(strategy="failover", bind=True)
|
||||
assert b == "duckmail"
|
||||
m.advance_email_provider_failover()
|
||||
try:
|
||||
m.select_email_provider_from_pool(strategy="failover", bind=True)
|
||||
raise AssertionError("expected failover exhaust")
|
||||
except Exception as exc:
|
||||
assert "exhausted" in str(exc).lower() or "failover" in str(exc).lower()
|
||||
print("PASS failover_advance")
|
||||
finally:
|
||||
m.config = old_cfg
|
||||
_reset_pool_state(m)
|
||||
for k, v in old_env.items():
|
||||
if v is None:
|
||||
os.environ.pop(k, None)
|
||||
else:
|
||||
os.environ[k] = v
|
||||
|
||||
|
||||
def test_single_provider_compat() -> None:
|
||||
m = _load()
|
||||
if m is None:
|
||||
print("SKIP single")
|
||||
return
|
||||
old_env = {k: os.environ.get(k) for k in ("EMAIL_PROVIDERS", "EMAIL_PROVIDER", "FIXED_EMAIL", "MIMO_FIXED_EMAIL")}
|
||||
old_cfg = dict(m.config)
|
||||
try:
|
||||
os.environ.pop("EMAIL_PROVIDERS", None)
|
||||
os.environ.pop("FIXED_EMAIL", None)
|
||||
os.environ.pop("MIMO_FIXED_EMAIL", None)
|
||||
os.environ["EMAIL_PROVIDER"] = "hotmail"
|
||||
m.config = dict(old_cfg)
|
||||
m.config["email_provider"] = "duckmail"
|
||||
m.config["email_providers"] = []
|
||||
# apply_env should overlay EMAIL_PROVIDER
|
||||
out = m.apply_env_config_overrides(m.config)
|
||||
m.config = out
|
||||
_reset_pool_state(m)
|
||||
assert m.get_email_providers_pool() == []
|
||||
assert m.get_email_provider() == "hotmail"
|
||||
print("PASS single_provider_compat")
|
||||
finally:
|
||||
m.config = old_cfg
|
||||
_reset_pool_state(m)
|
||||
for k, v in old_env.items():
|
||||
if v is None:
|
||||
os.environ.pop(k, None)
|
||||
else:
|
||||
os.environ[k] = v
|
||||
|
||||
|
||||
def test_get_email_and_token_binds_pool() -> None:
|
||||
m = _load()
|
||||
if m is None:
|
||||
print("SKIP allocate bind")
|
||||
return
|
||||
old_env = {k: os.environ.get(k) for k in ("EMAIL_PROVIDERS", "EMAIL_PROVIDER_STRATEGY", "FIXED_EMAIL", "MIMO_FIXED_EMAIL")}
|
||||
old_cfg = dict(m.config)
|
||||
try:
|
||||
os.environ.pop("FIXED_EMAIL", None)
|
||||
os.environ.pop("MIMO_FIXED_EMAIL", None)
|
||||
os.environ["EMAIL_PROVIDERS"] = "cloudmail,duckmail"
|
||||
os.environ["EMAIL_PROVIDER_STRATEGY"] = "round_robin"
|
||||
m.config = dict(old_cfg)
|
||||
m.config["defaultDomains"] = "example.com"
|
||||
_reset_pool_state(m)
|
||||
|
||||
with mock.patch.object(m, "_allocate_email_for_provider", side_effect=lambda p, api_key=None: (f"u@{p}.test", "tok")) as alloc:
|
||||
email, tok = m.get_email_and_token()
|
||||
assert email == "u@cloudmail.test"
|
||||
assert m.get_bound_email_provider() == "cloudmail"
|
||||
assert m.get_email_provider() == "cloudmail"
|
||||
# OTP path must see same provider
|
||||
assert alloc.call_args_list[0].args[0] == "cloudmail"
|
||||
|
||||
# second allocate without clear advances RR
|
||||
m.clear_email_provider_bind()
|
||||
email2, _ = m.get_email_and_token()
|
||||
assert email2 == "u@duckmail.test"
|
||||
assert m.get_bound_email_provider() == "duckmail"
|
||||
print("PASS get_email_and_token_binds_pool")
|
||||
finally:
|
||||
m.config = old_cfg
|
||||
_reset_pool_state(m)
|
||||
for k, v in old_env.items():
|
||||
if v is None:
|
||||
os.environ.pop(k, None)
|
||||
else:
|
||||
os.environ[k] = v
|
||||
|
||||
|
||||
def test_failover_resets_between_accounts() -> None:
|
||||
"""failover_index must not leak across accounts after reset_email_provider_failover."""
|
||||
m = _load()
|
||||
if m is None:
|
||||
print("SKIP failover reset")
|
||||
return
|
||||
old_env = {
|
||||
k: os.environ.get(k)
|
||||
for k in ("EMAIL_PROVIDERS", "EMAIL_PROVIDER_STRATEGY", "FIXED_EMAIL", "MIMO_FIXED_EMAIL")
|
||||
}
|
||||
old_cfg = dict(m.config)
|
||||
try:
|
||||
os.environ.pop("FIXED_EMAIL", None)
|
||||
os.environ.pop("MIMO_FIXED_EMAIL", None)
|
||||
os.environ["EMAIL_PROVIDERS"] = "cloudflare,duckmail,cloudmail"
|
||||
os.environ["EMAIL_PROVIDER_STRATEGY"] = "failover"
|
||||
m.config = dict(old_cfg)
|
||||
_reset_pool_state(m)
|
||||
|
||||
assert m.select_email_provider_from_pool(strategy="failover", bind=True) == "cloudflare"
|
||||
m.advance_email_provider_failover()
|
||||
assert m.select_email_provider_from_pool(strategy="failover", bind=True) == "duckmail"
|
||||
# Simulate next account start (register_cli / GUI reset)
|
||||
m.reset_email_provider_failover()
|
||||
m.clear_email_provider_bind()
|
||||
assert m.select_email_provider_from_pool(strategy="failover", bind=True) == "cloudflare"
|
||||
print("PASS failover_resets_between_accounts")
|
||||
finally:
|
||||
m.config = old_cfg
|
||||
_reset_pool_state(m)
|
||||
for k, v in old_env.items():
|
||||
if v is None:
|
||||
os.environ.pop(k, None)
|
||||
else:
|
||||
os.environ[k] = v
|
||||
|
||||
|
||||
def test_env_overlay_includes_providers() -> None:
|
||||
m = _load()
|
||||
if m is None:
|
||||
src = (ROOT / "grok_register_ttk.py").read_text(encoding="utf-8")
|
||||
assert "EMAIL_PROVIDERS" in src
|
||||
print("PASS overlay source contract")
|
||||
return
|
||||
old = os.environ.get("EMAIL_PROVIDERS")
|
||||
old_s = os.environ.get("EMAIL_PROVIDER_STRATEGY")
|
||||
old_mt = os.environ.get("MAIL_TIMEOUT")
|
||||
try:
|
||||
os.environ["EMAIL_PROVIDERS"] = "cloudflare,duckmail"
|
||||
os.environ["EMAIL_PROVIDER_STRATEGY"] = "random"
|
||||
os.environ["MAIL_TIMEOUT"] = "20"
|
||||
out = m.apply_env_config_overrides({})
|
||||
assert out["email_providers"] == "cloudflare,duckmail"
|
||||
assert out["email_provider_strategy"] == "random"
|
||||
assert str(out.get("mail_timeout")) == "20"
|
||||
print("PASS env_overlay_includes_providers")
|
||||
finally:
|
||||
if old is None:
|
||||
os.environ.pop("EMAIL_PROVIDERS", None)
|
||||
else:
|
||||
os.environ["EMAIL_PROVIDERS"] = old
|
||||
if old_s is None:
|
||||
os.environ.pop("EMAIL_PROVIDER_STRATEGY", None)
|
||||
else:
|
||||
os.environ["EMAIL_PROVIDER_STRATEGY"] = old_s
|
||||
if old_mt is None:
|
||||
os.environ.pop("MAIL_TIMEOUT", None)
|
||||
else:
|
||||
os.environ["MAIL_TIMEOUT"] = old_mt
|
||||
|
||||
|
||||
def test_duckmail_api_key_env_wins() -> None:
|
||||
m = _load()
|
||||
if m is None:
|
||||
print("SKIP duckmail env wins")
|
||||
return
|
||||
old = os.environ.get("DUCKMAIL_API_KEY")
|
||||
old_cfg = dict(m.config)
|
||||
try:
|
||||
m.config = dict(old_cfg)
|
||||
m.config["duckmail_api_key"] = "from-config-key-value"
|
||||
os.environ.pop("DUCKMAIL_API_KEY", None)
|
||||
assert m.get_duckmail_api_key() == "from-config-key-value"
|
||||
os.environ["DUCKMAIL_API_KEY"] = "from-env-key-value"
|
||||
assert m.get_duckmail_api_key() == "from-env-key-value"
|
||||
# empty env must not wipe to blank if we only use or-chain; empty string is falsy → config
|
||||
os.environ["DUCKMAIL_API_KEY"] = ""
|
||||
assert m.get_duckmail_api_key() == "from-config-key-value"
|
||||
print("PASS duckmail_api_key_env_wins")
|
||||
finally:
|
||||
m.config = old_cfg
|
||||
if old is None:
|
||||
os.environ.pop("DUCKMAIL_API_KEY", None)
|
||||
else:
|
||||
os.environ["DUCKMAIL_API_KEY"] = old
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_parse_email_providers_list()
|
||||
test_round_robin_and_bind()
|
||||
test_failover_advance()
|
||||
test_failover_resets_between_accounts()
|
||||
test_single_provider_compat()
|
||||
test_get_email_and_token_binds_pool()
|
||||
test_env_overlay_includes_providers()
|
||||
test_duckmail_api_key_env_wins()
|
||||
print("ALL OK")
|
||||
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Env / .env config overlay + hotmail path resolution."""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def _load():
|
||||
# Avoid importing full ttk (tkinter); load module with sys.modules stub if needed.
|
||||
# register_cli imports ttk; for unit test we only need the pure helpers.
|
||||
# Exec just the needed functions by importing the module carefully.
|
||||
name = "grok_register_ttk_envtest"
|
||||
# Prefer import; if tk fails, exec_module may still fail on tk. Skip GUI side.
|
||||
try:
|
||||
import grok_register_ttk as m
|
||||
return m
|
||||
except Exception as e:
|
||||
# Fallback: load source and exec only load_env helpers by compiling subset — skip if hard.
|
||||
print("SKIP full import:", type(e).__name__, e)
|
||||
return None
|
||||
|
||||
|
||||
def test_apply_env_config_overrides() -> None:
|
||||
m = _load()
|
||||
if m is None:
|
||||
# lightweight reimplementation check via source contract
|
||||
src = (ROOT / "grok_register_ttk.py").read_text(encoding="utf-8")
|
||||
assert "def apply_env_config_overrides" in src
|
||||
assert "HOTMAIL_ACCOUNTS_FILE" in src
|
||||
print("PASS apply_env_config_overrides (source contract; import skipped)")
|
||||
return
|
||||
old = os.environ.get("HOTMAIL_ACCOUNTS_FILE")
|
||||
old2 = os.environ.get("CPA_REMOTE_LIVE_REQUIRED")
|
||||
try:
|
||||
os.environ["HOTMAIL_ACCOUNTS_FILE"] = "mail_assets/merged.txt"
|
||||
os.environ["CPA_REMOTE_LIVE_REQUIRED"] = "true"
|
||||
os.environ["CPA_AUTH_PRIORITY"] = "42"
|
||||
out = m.apply_env_config_overrides({"hotmail_accounts_file": "mail_credentials.txt", "cpa_auth_priority": 1000})
|
||||
assert out["hotmail_accounts_file"] == "mail_assets/merged.txt"
|
||||
assert out["cpa_remote_live_required"] is True
|
||||
assert out["cpa_auth_priority"] == 42
|
||||
# path resolver
|
||||
path = m.get_hotmail_accounts_file() if hasattr(m, "get_hotmail_accounts_file") else None
|
||||
if path:
|
||||
assert path.endswith("mail_assets/merged.txt") or "mail_assets/merged.txt" in path
|
||||
print("PASS apply_env_config_overrides")
|
||||
finally:
|
||||
if old is None:
|
||||
os.environ.pop("HOTMAIL_ACCOUNTS_FILE", None)
|
||||
else:
|
||||
os.environ["HOTMAIL_ACCOUNTS_FILE"] = old
|
||||
if old2 is None:
|
||||
os.environ.pop("CPA_REMOTE_LIVE_REQUIRED", None)
|
||||
else:
|
||||
os.environ["CPA_REMOTE_LIVE_REQUIRED"] = old2
|
||||
os.environ.pop("CPA_AUTH_PRIORITY", None)
|
||||
|
||||
|
||||
def test_env_overlay_advance_on_start_and_cpa_mint() -> None:
|
||||
m = _load()
|
||||
if m is None:
|
||||
src = (ROOT / "grok_register_ttk.py").read_text(encoding="utf-8")
|
||||
assert "PROXY_ROTATE_ADVANCE_ON_START" in src
|
||||
assert "CPA_PREFER_PROTOCOL" in src
|
||||
assert "CPA_MINT_TIMEOUT_SEC" in src
|
||||
print("PASS env overlay advance_on_start/cpa_mint (source contract; import skipped)")
|
||||
return
|
||||
try:
|
||||
os.environ["PROXY_ROTATE_ADVANCE_ON_START"] = "true"
|
||||
os.environ["CPA_PREFER_PROTOCOL"] = "true"
|
||||
os.environ["CPA_MINT_TIMEOUT_SEC"] = "120"
|
||||
out = m.apply_env_config_overrides({})
|
||||
assert out["proxy_rotate_advance_on_start"] is True
|
||||
assert out["cpa_prefer_protocol"] is True
|
||||
assert out["cpa_mint_timeout_sec"] == 120
|
||||
print("PASS env overlay advance_on_start/cpa_mint")
|
||||
finally:
|
||||
os.environ.pop("PROXY_ROTATE_ADVANCE_ON_START", None)
|
||||
os.environ.pop("CPA_PREFER_PROTOCOL", None)
|
||||
os.environ.pop("CPA_MINT_TIMEOUT_SEC", None)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_apply_env_config_overrides()
|
||||
test_env_overlay_advance_on_start_and_cpa_mint()
|
||||
@@ -0,0 +1,683 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Static checks for email-stage failure classification + open_signup hardening."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def _load_fail_fast_helpers():
|
||||
"""Load is_fatal_register_error + classify without importing ttk."""
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(src)
|
||||
wanted = {
|
||||
"is_fatal_register_error",
|
||||
"classify_email_stage_failure",
|
||||
"product_batch_success",
|
||||
}
|
||||
nodes = []
|
||||
for node in tree.body:
|
||||
if isinstance(node, ast.FunctionDef) and node.name in wanted:
|
||||
nodes.append(node)
|
||||
names = {n.name for n in nodes}
|
||||
if "is_fatal_register_error" not in names or "classify_email_stage_failure" not in names:
|
||||
raise RuntimeError(f"missing core helpers, got {sorted(names)}")
|
||||
# is_fatal must come before classify (classify calls it); product free
|
||||
order = {"is_fatal_register_error": 0, "product_batch_success": 1, "classify_email_stage_failure": 2}
|
||||
nodes.sort(key=lambda n: order.get(n.name, 9))
|
||||
module = ast.Module(body=nodes, type_ignores=[])
|
||||
code = compile(module, "register_cli.py", "exec")
|
||||
ns: dict = {}
|
||||
exec(code, ns)
|
||||
return (
|
||||
ns["is_fatal_register_error"],
|
||||
ns["classify_email_stage_failure"],
|
||||
ns.get("product_batch_success"),
|
||||
)
|
||||
|
||||
|
||||
def test_classify() -> None:
|
||||
is_fatal, classify, _product = _load_fail_fast_helpers()
|
||||
cases = [
|
||||
("验证码已填写,但未进入资料页: code=ABC", "progress_fail"),
|
||||
("验证码已填写,但未进入资料页 IMAP", "progress_fail"),
|
||||
("Hotmail/Outlook 在 1200s 内未收到验证码邮件: a@b.com", "mail_miss"),
|
||||
("获取验证码失败", "mail_miss"),
|
||||
("验证码已获取,但自动填写/提交失败: code=1", "mail_miss"),
|
||||
("验证码 IMAP 连接失败", "mail_miss"),
|
||||
("IMAP SSL EOF", "other"),
|
||||
# Transient form/DOM race: slot-retry class (was "other" → instant burn)
|
||||
("未找到邮箱输入框或注册按钮", "browser_boot"),
|
||||
("未找到邮箱输入框", "browser_boot"),
|
||||
("打开注册页失败: page is None", "browser_boot"),
|
||||
("页面未就绪", "browser_boot"),
|
||||
(
|
||||
"邮箱提交后未进入验证码页(服务端可能未发信 / SPA 卡住)",
|
||||
"browser_boot",
|
||||
),
|
||||
("浏览器启动失败", "browser_boot"),
|
||||
("net::ERR_CONNECTION_CLOSED", "browser_boot"),
|
||||
("ERR_CONNECTION_RESET at accounts.x.ai", "browser_boot"),
|
||||
("ERR_PROXY_CONNECTION_FAILED", "browser_boot"),
|
||||
("ERR_TUNNEL_CONNECTION_FAILED", "browser_boot"),
|
||||
(
|
||||
"Hotmail/Outlook 可用别名已耗尽:请增加 hotmail_max_aliases_per_account、"
|
||||
"补充 mail_credentials.txt,或清理 emails_used.txt / emails_error.txt",
|
||||
"fatal",
|
||||
),
|
||||
("Hotmail/Outlook 账号文件不存在: /tmp/x", "fatal"),
|
||||
("Hotmail/Outlook 账号文件无有效记录: /tmp/x", "fatal"),
|
||||
("Cloudflare API Base 未配置", "fatal"),
|
||||
("DuckMail 没有返回任何可用域名", "fatal"),
|
||||
("Gmail 模式需要 gmail_imap_user / GMAIL_IMAP_USER", "fatal"),
|
||||
("Gmail catch-all 需要在 defaultDomains 中配置已路由到该 Gmail 的域名", "fatal"),
|
||||
("Gmail IMAP 认证失败: [AUTHENTICATIONFAILED] Invalid credentials", "fatal"),
|
||||
(
|
||||
"Hotmail plus-alias 已禁用(hotmail_allow_plus_alias=false / mode=off):主邮箱均已消耗",
|
||||
"fatal",
|
||||
),
|
||||
(
|
||||
"browser_boot: signup_spa_stuck 邮箱注册按钮点击后停留在「您正在登录」"
|
||||
"中间态,邮箱表单未挂载",
|
||||
"browser_boot",
|
||||
),
|
||||
(
|
||||
"browser_boot: signup_spa_stuck 未找到邮箱表单:页面停在「您正在登录」"
|
||||
"中间态(点击邮箱注册后未挂载输入框)",
|
||||
"browser_boot",
|
||||
),
|
||||
(
|
||||
"邮箱注册按钮点击后停留在「您正在登录」中间态,邮箱表单未挂载",
|
||||
"browser_boot",
|
||||
),
|
||||
(
|
||||
"未找到邮箱表单:页面停在「您正在登录」中间态(点击邮箱注册后未挂载输入框)",
|
||||
"browser_boot",
|
||||
),
|
||||
# SSO post-submit mid-state must stay other (not browser_boot recycle policy)
|
||||
("final-page-no-submit:您正在登录 您正在登录 | 返回 返回", "other"),
|
||||
]
|
||||
failed = 0
|
||||
for msg, expect in cases:
|
||||
got = classify(msg)
|
||||
ok = got == expect
|
||||
print(f"{'PASS' if ok else 'FAIL'} {got!r:16} expect={expect!r:16} {msg[:48]}")
|
||||
if not ok:
|
||||
failed += 1
|
||||
if expect == "fatal" and not is_fatal(msg):
|
||||
print(f"FAIL is_fatal should be True for: {msg[:48]}")
|
||||
failed += 1
|
||||
if failed:
|
||||
raise SystemExit(f"classify failures: {failed}")
|
||||
|
||||
|
||||
def test_open_signup_hardens_release() -> None:
|
||||
src = (ROOT / "grok_register_ttk.py").read_text(encoding="utf-8")
|
||||
# After release_tab, must rebuild via start_browser / restart_browser, not page.get on None
|
||||
assert "def open_signup_page" in src
|
||||
assert "TabPool.release_tab()" in src
|
||||
assert "start_browser" in src
|
||||
# The buggy pattern: release_tab then immediate _get_page().get without start
|
||||
# Ensure helper / rebuild path exists
|
||||
assert "重建浏览器" in src or "start_browser(log_callback" in src
|
||||
# page null guard
|
||||
assert "页面未就绪" in src or "page is None" in src
|
||||
print("PASS open_signup_page rebuild guards present")
|
||||
|
||||
|
||||
def test_soft_hard_helpers() -> None:
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
assert "def _soft_recycle_browser" in src
|
||||
assert "def _hard_recycle_browser" in src
|
||||
assert "clear_session" in src
|
||||
assert "classify_email_stage_failure" in src
|
||||
# mail_miss uses soft; browser_boot/progress_fail raise ARN → hard recycle in ARN handler
|
||||
assert "_soft_recycle_browser(worker_id)" in src
|
||||
assert "_hard_recycle_browser(worker_id)" in src
|
||||
# progress_fail must NOT instant-return reg_fail; must slot-retry via ARN
|
||||
# Multi-line raise: AccountRetryNeeded(\n f"progress_fail: {msg}", email=email)
|
||||
assert 'f"progress_fail: {msg}"' in src and "AccountRetryNeeded(" in src
|
||||
assert 'f"browser_boot: {msg}"' in src
|
||||
assert "email=email" in src # ARN carries mailbox for release/burn gate
|
||||
assert 'kind": "progress_fail"' not in src # old hard-fail return removed
|
||||
# form flake classified as browser_boot (slot retry class)
|
||||
assert '"未找到邮箱输入框或注册按钮" in text' in src or "未找到邮箱输入框或注册按钮" in src
|
||||
# Deep fix: mail+profile share one try so mail ARN hits slot budget
|
||||
assert "Mail + profile share one try" in src
|
||||
# No double-rotate before raise ARN (outer handler owns rotate)
|
||||
assert 'reason=f"progress_fail:' not in src
|
||||
assert 'reason=f"browser_boot:' not in src
|
||||
print("PASS soft/hard recycle helpers present")
|
||||
|
||||
|
||||
def test_fatal_stop_wiring() -> None:
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
for needle in (
|
||||
"class FatalRegisterError",
|
||||
"def request_fatal_stop",
|
||||
"def is_fatal_register_error",
|
||||
"_fatal_stop",
|
||||
"raise FatalRegisterError",
|
||||
"except FatalRegisterError",
|
||||
"exit_code = 2",
|
||||
"return exit_code",
|
||||
"致命错误,停止整批(不空转)",
|
||||
"致命错误已停止任务(不空转)",
|
||||
):
|
||||
assert needle in src, f"missing: {needle}"
|
||||
# worker must check stop flag and must NOT retry FatalRegisterError
|
||||
assert "if _fatal_stop.is_set()" in src
|
||||
# bare `return 2` is NOT required — main uses exit_code then return exit_code
|
||||
print("PASS fatal stop wiring present")
|
||||
|
||||
|
||||
def test_hotpath_no_mojibake() -> None:
|
||||
src = (ROOT / "grok_register_ttk.py").read_text(encoding="utf-8")
|
||||
# hot-path markers that must be correct Chinese
|
||||
required = [
|
||||
"获取邮箱失败",
|
||||
"已创建邮箱:",
|
||||
"成功开启 NSFW",
|
||||
"获取 DuckMail token 失败",
|
||||
"从邮件中提取到验证码",
|
||||
]
|
||||
bad = [s for s in required if s not in src]
|
||||
if bad:
|
||||
raise SystemExit(f"missing fixed strings: {bad}")
|
||||
# residual mojibake probe (common broken sequence)
|
||||
if "鑾峰彇" in src or "宸插垱寤" in src:
|
||||
raise SystemExit("residual mojibake still present")
|
||||
print("PASS hot-path Chinese strings fixed")
|
||||
|
||||
|
||||
|
||||
def test_product_batch_success() -> None:
|
||||
is_fatal, _classify, product = _load_fail_fast_helpers()
|
||||
assert product is not None
|
||||
assert product({"reg_success": 0}, {"cpa_export_enabled": True}) is False
|
||||
assert product({"reg_success": 1, "chat_ok": 0}, {"cpa_export_enabled": True}) is False
|
||||
assert product({"reg_success": 1, "chat_ok": 1}, {"cpa_export_enabled": True}) is True
|
||||
assert product(
|
||||
{"reg_success": 1, "chat_ok": 1, "remote_live_ok": 0},
|
||||
{"cpa_export_enabled": True, "cpa_remote_inject": True},
|
||||
) is False
|
||||
assert product(
|
||||
{"reg_success": 1, "chat_ok": 1, "remote_live_ok": 1},
|
||||
{"cpa_export_enabled": True, "cpa_remote_inject": True},
|
||||
) is True
|
||||
# pure register mode
|
||||
assert product({"reg_success": 2, "chat_ok": 0}, {"cpa_export_enabled": False}) is True
|
||||
# disk-first (probe_chat=off): mint_token_ok is product success; chat/inject irrelevant
|
||||
assert product(
|
||||
{"reg_success": 1, "mint_token_ok": 1, "chat_ok": 0, "remote_live_ok": 0},
|
||||
{
|
||||
"cpa_export_enabled": True,
|
||||
"cpa_probe_chat": False,
|
||||
"cpa_remote_inject": False,
|
||||
},
|
||||
) is True
|
||||
assert product(
|
||||
{"reg_success": 1, "mint_token_ok": 0, "chat_ok": 0},
|
||||
{"cpa_export_enabled": True, "cpa_probe_chat": False},
|
||||
) is False
|
||||
# fatal markers for alias kill-switch
|
||||
assert is_fatal("Hotmail plus-alias 已禁用(mode=off)") is True
|
||||
assert is_fatal("plus-alias 已禁用") is True
|
||||
print("PASS product_batch_success + alias fatal markers")
|
||||
|
||||
|
||||
def test_alias_kill_switch_source() -> None:
|
||||
src = (ROOT / "grok_register_ttk.py").read_text(encoding="utf-8")
|
||||
assert '"hotmail_alias_mode": "off"' in src
|
||||
assert '"hotmail_allow_plus_alias": False' in src or '"hotmail_allow_plus_alias": false' in src
|
||||
assert "HOTMAIL_ALLOW_PLUS_ALIAS" in src
|
||||
assert "Hotmail plus-alias 已禁用" in src
|
||||
assert "hotmail_allow_plus_alias" in src
|
||||
cfg = (ROOT / "config.example.json").read_text(encoding="utf-8")
|
||||
assert '"hotmail_allow_plus_alias": false' in cfg
|
||||
assert '"hotmail_alias_mode": "off"' in cfg
|
||||
print("PASS alias kill-switch source + config.example")
|
||||
|
||||
|
||||
def test_cli_product_exit_wiring() -> None:
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
assert "def product_batch_success" in src
|
||||
assert "product_batch_success(s, cfg_exit)" in src
|
||||
# disk-first: message names current product criterion (chat_ok or mint_token_ok)
|
||||
assert (
|
||||
"未达到产品可用 free Build 标准" in src
|
||||
or "本批未达到当前产品标准" in src
|
||||
)
|
||||
assert "disk-first (probe_chat=off)" in src
|
||||
assert "mint_token_ok" in src
|
||||
print("PASS cli product exit wiring")
|
||||
|
||||
|
||||
def test_cli_mint_token_ok_honesty() -> None:
|
||||
"""mint_token_ok (OIDC write) must be distinct from mint_success (product ok)."""
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
assert '"mint_token_ok": 0' in src or "'mint_token_ok': 0" in src
|
||||
assert '_inc("mint_token_ok")' in src
|
||||
assert "CPA token写入" in src
|
||||
assert "CPA产品OK" in src
|
||||
assert "CPA写失败" in src
|
||||
# SUMMARY_JSON must expose mint_token_ok additively while keeping mint_success
|
||||
assert '"mint_token_ok": int(s.get("mint_token_ok"' in src
|
||||
assert '"mint_success": int(s.get("mint_success"' in src
|
||||
# token write counted even when product ok is false
|
||||
assert 'if result.get("token_ok") is True:' in src
|
||||
assert 'if result.get("ok"):' in src
|
||||
print("PASS cli mint_token_ok honesty metrics")
|
||||
|
||||
|
||||
def test_desktop_gui_removed_cli_keeps_product_counters() -> None:
|
||||
"""Desktop TTK GUI removed; product counters live in register_cli + control plane."""
|
||||
ttk = (ROOT / "grok_register_ttk.py").read_text(encoding="utf-8")
|
||||
assert "class GrokRegisterGUI" not in ttk
|
||||
assert "import tkinter" not in ttk
|
||||
assert "Desktop GUI removed" in ttk or "apps.control_api" in ttk
|
||||
cli = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
for needle in (
|
||||
"product_batch_success",
|
||||
"mint_token_ok",
|
||||
"chat_ok",
|
||||
):
|
||||
assert needle in cli, f"missing CLI product marker: {needle}"
|
||||
assert (ROOT / "apps" / "control_api" / "app.py").is_file()
|
||||
print("PASS desktop GUI removed; CLI/control_api own product surface")
|
||||
|
||||
|
||||
def test_run_register_preserves_product_exit() -> None:
|
||||
"""run-register.sh must not mask register_cli exit with `| tee` alone."""
|
||||
path = ROOT / "run-register.sh"
|
||||
assert path.is_file(), "run-register.sh missing at repo root (pxed production entry)"
|
||||
src = path.read_text(encoding="utf-8")
|
||||
assert "PIPESTATUS[0]" in src
|
||||
# ban: exec ... | tee which always yields tee's 0
|
||||
assert "exec python" not in src
|
||||
assert "exec xvfb-run" not in src
|
||||
assert "exit \"$code\"" in src or "exit $code" in src
|
||||
print("PASS run-register preserves product exit (PIPESTATUS)")
|
||||
|
||||
|
||||
def _load_turnstile_helpers():
|
||||
"""Load Turnstile demote helpers without importing ttk side effects."""
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(src)
|
||||
wanted = {
|
||||
"is_turnstile_stuck_error",
|
||||
"is_turnstile_headless_upgradeable",
|
||||
"is_fatal_register_error",
|
||||
"note_turnstile_streak",
|
||||
"_turnstile_fatal_streak_limit",
|
||||
"turnstile_slot_exhausted",
|
||||
"_turnstile_streak_state_path",
|
||||
"_read_turnstile_streak_disk",
|
||||
"_write_turnstile_streak_disk",
|
||||
}
|
||||
nodes = []
|
||||
for node in tree.body:
|
||||
if isinstance(node, ast.FunctionDef) and node.name in wanted:
|
||||
nodes.append(node)
|
||||
names = {n.name for n in nodes}
|
||||
missing = wanted - names
|
||||
if missing:
|
||||
raise RuntimeError(f"missing turnstile helpers: {sorted(missing)}")
|
||||
# Minimal globals used by helpers
|
||||
ns: dict = {
|
||||
"os": __import__("os"),
|
||||
"sys": sys,
|
||||
"threading": __import__("threading"),
|
||||
"reg": type("R", (), {"config": {}})(),
|
||||
"_turnstile_fail_streak_lock": __import__("threading").Lock(),
|
||||
"_turnstile_fail_streak": 0,
|
||||
}
|
||||
# Exec order: stuck → upgradeable → fatal → path/disk helpers → limit → note → slot
|
||||
order = {
|
||||
"is_turnstile_stuck_error": 0,
|
||||
"is_turnstile_headless_upgradeable": 1,
|
||||
"is_fatal_register_error": 2,
|
||||
"_turnstile_streak_state_path": 3,
|
||||
"_read_turnstile_streak_disk": 4,
|
||||
"_write_turnstile_streak_disk": 5,
|
||||
"_turnstile_fatal_streak_limit": 6,
|
||||
"note_turnstile_streak": 7,
|
||||
"turnstile_slot_exhausted": 8,
|
||||
}
|
||||
nodes.sort(key=lambda n: order.get(n.name, 9))
|
||||
mod = ast.Module(body=nodes, type_ignores=[])
|
||||
exec(compile(mod, "register_cli.py", "exec"), ns)
|
||||
return ns
|
||||
|
||||
|
||||
def test_turnstile_demote_not_unconditional_fatal() -> None:
|
||||
"""Profile Turnstile stuck is slot-retry class; not bare process-fatal."""
|
||||
ns = _load_turnstile_helpers()
|
||||
is_stuck = ns["is_turnstile_stuck_error"]
|
||||
is_fatal = ns["is_fatal_register_error"]
|
||||
is_upgradeable = ns["is_turnstile_headless_upgradeable"]
|
||||
|
||||
profile_msg = (
|
||||
"Turnstile 卡住 fail-fast: token_len=0 "
|
||||
"stuck_timeout=60.0s retries=3/3 snap={}"
|
||||
)
|
||||
assert is_stuck(profile_msg) is True
|
||||
# Demoted: plain Turnstile stuck must NOT be unconditional process-fatal
|
||||
assert is_fatal(profile_msg) is False
|
||||
assert is_upgradeable(profile_msg) is True
|
||||
|
||||
final_msg = (
|
||||
"最终页 Turnstile 卡住 fail-fast: wait 45s token_len=0 "
|
||||
"stuck_timeout=60s retries=2/3"
|
||||
)
|
||||
assert is_stuck(final_msg) is True
|
||||
assert is_fatal(final_msg) is False
|
||||
|
||||
# ARN demote prefix still classifies as stuck
|
||||
arn_msg = f"turnstile: {profile_msg}"
|
||||
assert is_stuck(arn_msg) is True
|
||||
assert is_fatal(arn_msg) is False
|
||||
# Non-stuck turnstile: prefix alone must NOT be stuck (avoids streak noise)
|
||||
assert is_stuck("turnstile: unrelated noise") is False
|
||||
|
||||
# Real unrecoverable markers still fatal
|
||||
assert is_fatal("Hotmail plus-alias 已禁用(mode=off)") is True
|
||||
assert is_fatal("Turnstile headless 失败且无可用 DISPLAY/xvfb-run") is True
|
||||
assert is_fatal("Turnstile 连续失败 fail-fast streak=6/6: x") is True
|
||||
assert is_fatal("headed 需要 DISPLAY/xvfb-run") is True
|
||||
# no-DISPLAY demote path must be recognized by is_fatal (marker aligned)
|
||||
assert is_fatal(
|
||||
"Turnstile 卡住且无可用 DISPLAY/xvfb-run(无法换路重试): token_len=0"
|
||||
) is True
|
||||
|
||||
# Source wiring: demote path must raise AccountRetryNeeded for turnstile
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
assert "def is_turnstile_stuck_error" in src
|
||||
assert "note_turnstile_streak" in src
|
||||
assert "def turnstile_slot_exhausted" in src
|
||||
assert 'f"turnstile: {msg' in src
|
||||
assert "Turnstile 卡住,换路 slot 重试" in src
|
||||
assert "Turnstile demote: force headed" in src
|
||||
assert '"Turnstile 卡住且无可用 DISPLAY"' in src
|
||||
# Must not list bare "Turnstile 卡住 fail-fast" as unconditional fatal marker
|
||||
assert '"Turnstile 连续失败 fail-fast"' in src
|
||||
# reg_ok / streak reset after SSO (not before wait_for_sso_cookie)
|
||||
sso_i = src.find("wait_for_sso_cookie")
|
||||
reg_ok_i = src.find('note_egress_outcome(\n "reg_ok"')
|
||||
if reg_ok_i < 0:
|
||||
reg_ok_i = src.find('"reg_ok"')
|
||||
streak_ok_i = src.find("note_turnstile_streak(\n ok=True")
|
||||
if streak_ok_i < 0:
|
||||
streak_ok_i = src.find("note_turnstile_streak(\n ok=True")
|
||||
assert sso_i > 0 and reg_ok_i > sso_i, "reg_ok must be after wait_for_sso_cookie"
|
||||
assert streak_ok_i > sso_i, "streak reset (ok=True) must be after wait_for_sso_cookie"
|
||||
# Streak only on slot exhaust, not every mid-slot ARN
|
||||
assert "Turnstile slot 耗尽计 streak=" in src
|
||||
assert "per-account, not mid-slot" in src
|
||||
# P1: streak-fatal must NOT re-note turnstile after rotate (would cool new node)
|
||||
assert "No second" in src or "would be wrongly cool" in src
|
||||
# P1: headless upgrade rotates egress
|
||||
assert "turnstile-headed-upgrade:" in src
|
||||
# P2: cross-sub streak disk
|
||||
assert "def _turnstile_streak_state_path" in src
|
||||
assert "cross-sub disk" in src
|
||||
print("PASS turnstile demote policy (not unconditional fatal)")
|
||||
|
||||
|
||||
def test_turnstile_streak_fail_fast() -> None:
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ns = _load_turnstile_helpers()
|
||||
note = ns["note_turnstile_streak"]
|
||||
slot_ex = ns["turnstile_slot_exhausted"]
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
path = str(Path(td) / "streak")
|
||||
cfg = {"turnstile_streak_file": path}
|
||||
# Reset via ok=True
|
||||
assert note(ok=True, config=cfg) == 0
|
||||
assert note(ok=False, config=cfg) == 1
|
||||
assert note(ok=False, config=cfg) == 2
|
||||
assert note(ok=True, config=cfg) == 0
|
||||
assert note(ok=False, config=cfg) == 1
|
||||
limit = ns["_turnstile_fatal_streak_limit"]({})
|
||||
assert 1 <= limit <= 50
|
||||
# Slot-exhaust helper: mid-slot retries must NOT count as exhausted
|
||||
# After slot_retry += 1, exhausted iff slot_retry > max_slot_retry
|
||||
assert slot_ex(slot_retry=1, max_slot_retry=2) is False
|
||||
assert slot_ex(slot_retry=2, max_slot_retry=2) is False
|
||||
assert slot_ex(slot_retry=3, max_slot_retry=2) is True
|
||||
assert slot_ex(slot_retry=1, max_slot_retry=0) is True # no budget → first ARN exhausts
|
||||
print(f"PASS turnstile streak counter (default limit={limit})")
|
||||
|
||||
|
||||
def test_turnstile_streak_per_account_not_per_attempt() -> None:
|
||||
"""Simulate ARN chain: only slot-exhausted accounts bump process streak."""
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ns = _load_turnstile_helpers()
|
||||
note = ns["note_turnstile_streak"]
|
||||
is_stuck = ns["is_turnstile_stuck_error"]
|
||||
is_fatal = ns["is_fatal_register_error"]
|
||||
slot_ex = ns["turnstile_slot_exhausted"]
|
||||
limit_fn = ns["_turnstile_fatal_streak_limit"]
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
path = str(Path(td) / "streak")
|
||||
cfg = {"turnstile_streak_file": path, "turnstile_fatal_streak": 3}
|
||||
note(ok=True, config=cfg)
|
||||
max_slot_retry = 2
|
||||
# One account, 3 Turnstile ARNs (initial + 2 retries) → 1 streak only
|
||||
slot_retry = 0
|
||||
turnstile_arn = "turnstile: Turnstile 卡住 fail-fast: token_len=0"
|
||||
assert is_stuck(turnstile_arn) is True
|
||||
for _ in range(3):
|
||||
slot_retry += 1
|
||||
if slot_retry <= max_slot_retry:
|
||||
continue # mid-slot: no note_turnstile_streak(ok=False)
|
||||
streak = note(ok=False, config=cfg)
|
||||
assert streak == 1
|
||||
assert slot_ex(slot_retry=slot_retry, max_slot_retry=max_slot_retry) is True
|
||||
# Second exhausted account → streak 2
|
||||
slot_retry = 0
|
||||
for _ in range(3):
|
||||
slot_retry += 1
|
||||
if slot_retry <= max_slot_retry:
|
||||
continue
|
||||
streak = note(ok=False, config=cfg)
|
||||
assert streak == 2
|
||||
# reg_ok resets
|
||||
assert note(ok=True, config=cfg) == 0
|
||||
# Reach fatal at limit without mid-slot inflation
|
||||
limit = limit_fn(cfg)
|
||||
assert limit == 3
|
||||
for i in range(3):
|
||||
streak = note(ok=False, config=cfg)
|
||||
if streak >= limit:
|
||||
fatal_msg = (
|
||||
f"Turnstile 连续失败 fail-fast streak={streak}/{limit}: "
|
||||
f"{turnstile_arn}"
|
||||
)
|
||||
assert is_fatal(fatal_msg) is True
|
||||
assert streak == 3
|
||||
break
|
||||
else:
|
||||
raise AssertionError("expected streak to hit fatal limit")
|
||||
print("PASS turnstile streak per-account (not per mid-slot ARN)")
|
||||
|
||||
|
||||
def test_turnstile_force_headed_on_demote_wiring() -> None:
|
||||
"""Still-headless demote must force headed before ARN when DISPLAY ready."""
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
# demote: force headed config only; hard recycle owned by ARN handler
|
||||
assert "Turnstile demote: force headed before slot retry" in src
|
||||
assert 'reg.config["browser_headless"] = False' in src
|
||||
# demote block must NOT hard-recycle before raise ARN (double recycle fix)
|
||||
# (upgrade path still recycles after rotate — different branch)
|
||||
assert "Hard recycle is owned by the AccountRetryNeeded handler" in src
|
||||
# no-DISPLAY demote string is both raised and in is_fatal markers
|
||||
assert "Turnstile 卡住且无可用 DISPLAY/xvfb-run(无法换路重试)" in src
|
||||
assert '"Turnstile 卡住且无可用 DISPLAY"' in src
|
||||
# headless upgrade must rotate
|
||||
assert 'reason=f"turnstile-headed-upgrade:' in src or "turnstile-headed-upgrade:" in src
|
||||
print("PASS turnstile force-headed demote wiring")
|
||||
|
||||
|
||||
def test_turnstile_streak_cross_sub_disk() -> None:
|
||||
"""New process memory=0 must resume streak from disk (batch-level fail-fast)."""
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ns = _load_turnstile_helpers()
|
||||
note = ns["note_turnstile_streak"]
|
||||
read_disk = ns["_read_turnstile_streak_disk"]
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
path = str(Path(td) / "batch.streak")
|
||||
cfg = {"turnstile_streak_file": path}
|
||||
note(ok=True, config=cfg)
|
||||
assert note(ok=False, config=cfg) == 1
|
||||
assert note(ok=False, config=cfg) == 2
|
||||
assert read_disk(path) == 2
|
||||
# Simulate new register_cli process: memory counter zeroed
|
||||
ns["_turnstile_fail_streak"] = 0
|
||||
# Next fail must resume from disk → 3, not 1
|
||||
assert note(ok=False, config=cfg) == 3
|
||||
assert read_disk(path) == 3
|
||||
# reg_ok clears disk
|
||||
assert note(ok=True, config=cfg) == 0
|
||||
assert read_disk(path) == 0
|
||||
ns["_turnstile_fail_streak"] = 0
|
||||
assert note(ok=False, config=cfg) == 1
|
||||
print("PASS turnstile streak cross-sub disk")
|
||||
|
||||
|
||||
def test_turnstile_streak_fatal_no_second_egress_note() -> None:
|
||||
"""Streak-fatal path must not call note_egress after _force_rotate_path."""
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
# Locate streak-fatal block
|
||||
marker = "Turnstile 连续失败 fail-fast streak="
|
||||
i = src.find(marker)
|
||||
assert i > 0
|
||||
# Within ~800 chars after marker: request_fatal_stop, no note_egress_outcome("turnstile")
|
||||
window = src[i : i + 900]
|
||||
assert "request_fatal_stop" in window
|
||||
assert 'note_egress_outcome(\n "turnstile"' not in window
|
||||
assert 'note_egress_outcome(\n "turnstile"' not in window
|
||||
# Comment documents the P1 fix
|
||||
assert "wrongly cool" in src or "No second" in src
|
||||
print("PASS turnstile streak-fatal no second egress note")
|
||||
|
||||
|
||||
def _load_burn_helpers():
|
||||
"""Load burn gate + deps without importing ttk side effects."""
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(src)
|
||||
wanted = {
|
||||
"is_fatal_register_error",
|
||||
"is_turnstile_stuck_error",
|
||||
"classify_email_stage_failure",
|
||||
"email_failure_should_burn_mailbox",
|
||||
}
|
||||
nodes = [
|
||||
n
|
||||
for n in tree.body
|
||||
if isinstance(n, ast.FunctionDef) and n.name in wanted
|
||||
]
|
||||
names = {n.name for n in nodes}
|
||||
missing = wanted - names
|
||||
if missing:
|
||||
raise RuntimeError(f"missing burn helpers: {sorted(missing)}")
|
||||
order = {
|
||||
"is_fatal_register_error": 0,
|
||||
"is_turnstile_stuck_error": 1,
|
||||
"classify_email_stage_failure": 2,
|
||||
"email_failure_should_burn_mailbox": 3,
|
||||
}
|
||||
nodes.sort(key=lambda n: order.get(n.name, 9))
|
||||
ns: dict = {}
|
||||
exec(compile(ast.Module(body=nodes, type_ignores=[]), "register_cli.py", "exec"), ns)
|
||||
return ns["email_failure_should_burn_mailbox"]
|
||||
|
||||
|
||||
def test_email_failure_burn_policy() -> None:
|
||||
"""Turnstile/SPA/browser must not permanent-burn Hotmail; mail/sso must."""
|
||||
burn = _load_burn_helpers()
|
||||
# Do NOT burn — egress / SPA / form flakes (live batch dominant failures).
|
||||
no_burn = [
|
||||
"Turnstile 卡住 fail-fast: pre-submit retries exhausted token_len=0 "
|
||||
"stuck_timeout=150.0s retries=2/2",
|
||||
"turnstile: Turnstile 卡住 fail-fast: token_len=0",
|
||||
"slot-retry:turnstile: Turnstile 卡住 fail-fast: token_len=0",
|
||||
"最终页 Turnstile 卡住 fail-fast: wait 45s token_len=0",
|
||||
"最终注册页资料填写失败: last='wait-cloudflare:0' not_ready=0",
|
||||
"邮箱提交后未进入验证码页(服务端可能未发信 / SPA 卡住)",
|
||||
"browser_boot: 邮箱提交后未进入验证码页(服务端可能未发信 / SPA 卡住)",
|
||||
"未找到邮箱输入框或注册按钮",
|
||||
"net::ERR_CONNECTION_CLOSED",
|
||||
"turnstile-headed-upgrade: token_len=0",
|
||||
]
|
||||
# DO burn — mailbox or account-terminal after commit.
|
||||
do_burn = [
|
||||
"Hotmail/Outlook 在 1200s 内未收到验证码邮件: a@b.com",
|
||||
"获取验证码失败",
|
||||
"验证码已填写,但未进入资料页: code=ABC",
|
||||
"progress_fail: 验证码已填写,但未进入资料页: code=ABC",
|
||||
"等待超时:未获取到 sso cookie。已看到 cookies: ['cf_clearance']",
|
||||
"slot-retry:等待超时:未获取到 sso cookie",
|
||||
]
|
||||
failed = 0
|
||||
for msg in no_burn:
|
||||
got = burn(msg)
|
||||
ok = got is False
|
||||
print(f"{'PASS' if ok else 'FAIL'} burn={got!r:5} expect=False {msg[:56]}")
|
||||
if not ok:
|
||||
failed += 1
|
||||
for msg in do_burn:
|
||||
got = burn(msg)
|
||||
ok = got is True
|
||||
print(f"{'PASS' if ok else 'FAIL'} burn={got!r:5} expect=True {msg[:56]}")
|
||||
if not ok:
|
||||
failed += 1
|
||||
if failed:
|
||||
raise SystemExit(f"burn policy failures: {failed}")
|
||||
# Wiring: ARN handler must not unconditional mark_error; fill_email carries email=
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
assert "email_failure_should_burn_mailbox" in src
|
||||
assert "不永久烧号(瞬态/出口类)" in src
|
||||
assert "reg.mark_error(email, reason=f\"slot-retry:" not in src
|
||||
ttk = (ROOT / "grok_register_ttk.py").read_text(encoding="utf-8")
|
||||
assert "def release_email_attempt" in ttk
|
||||
assert "email=email" in ttk # fill_email ARN carries address
|
||||
print("PASS email failure burn policy")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
test_classify()
|
||||
test_open_signup_hardens_release()
|
||||
test_soft_hard_helpers()
|
||||
test_fatal_stop_wiring()
|
||||
test_hotpath_no_mojibake()
|
||||
test_product_batch_success()
|
||||
test_alias_kill_switch_source()
|
||||
test_cli_product_exit_wiring()
|
||||
test_cli_mint_token_ok_honesty()
|
||||
test_desktop_gui_removed_cli_keeps_product_counters()
|
||||
test_run_register_preserves_product_exit()
|
||||
test_turnstile_demote_not_unconditional_fatal()
|
||||
test_turnstile_streak_fail_fast()
|
||||
test_turnstile_streak_per_account_not_per_attempt()
|
||||
test_turnstile_force_headed_on_demote_wiring()
|
||||
test_turnstile_streak_cross_sub_disk()
|
||||
test_turnstile_streak_fatal_no_second_egress_note()
|
||||
test_email_failure_burn_policy()
|
||||
print("\nALL PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,238 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unit checks for Gmail IMAP catch-all provider (no live mailbox required)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import types
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def _load_reg():
|
||||
"""Import engine module. Prefer real deps; no tkinter (desktop GUI removed)."""
|
||||
sys.path.insert(0, str(ROOT))
|
||||
# Only stub missing optional browser deps; never replace real proxy_rotate.
|
||||
try:
|
||||
import DrissionPage # noqa: F401
|
||||
from DrissionPage.errors import PageDisconnectedError # noqa: F401
|
||||
except Exception:
|
||||
dp = types.ModuleType("DrissionPage")
|
||||
dp.Chromium = object
|
||||
dp.ChromiumOptions = object
|
||||
sys.modules["DrissionPage"] = dp
|
||||
err = types.ModuleType("DrissionPage.errors")
|
||||
err.PageDisconnectedError = type("PageDisconnectedError", (Exception,), {})
|
||||
sys.modules["DrissionPage.errors"] = err
|
||||
dp.errors = err
|
||||
try:
|
||||
from curl_cffi import requests as _r # noqa: F401
|
||||
except Exception:
|
||||
curl = types.ModuleType("curl_cffi")
|
||||
req = types.ModuleType("curl_cffi.requests")
|
||||
curl.requests = req
|
||||
sys.modules["curl_cffi"] = curl
|
||||
sys.modules["curl_cffi.requests"] = req
|
||||
import grok_register_ttk as reg # noqa: E402
|
||||
|
||||
return reg
|
||||
|
||||
|
||||
def test_gmail_generate_domain_email() -> None:
|
||||
reg = _load_reg()
|
||||
reg.config["email_provider"] = "gmail"
|
||||
reg.config["gmail_imap_user"] = "catch@gmail.com"
|
||||
reg.config["gmail_imap_password"] = "app-pass-16chars"
|
||||
reg.config["defaultDomains"] = "example-cf.com, other.com"
|
||||
with patch.object(reg, "is_email_used", return_value=False):
|
||||
addr, token = reg.gmail_get_email_and_token()
|
||||
assert "@" in addr
|
||||
domain = addr.split("@", 1)[1]
|
||||
assert domain in {"example-cf.com", "other.com"}
|
||||
assert token.startswith("gmail:")
|
||||
assert token in reg._gmail_token_map
|
||||
print("PASS gmail generate domain email")
|
||||
|
||||
|
||||
def test_gmail_dispatch_get_email_and_code() -> None:
|
||||
reg = _load_reg()
|
||||
reg.config["email_provider"] = "gmail"
|
||||
reg.config["gmail_imap_user"] = "catch@gmail.com"
|
||||
reg.config["gmail_imap_password"] = "app-pass"
|
||||
reg.config["defaultDomains"] = "cf-domain.test"
|
||||
with patch.object(reg, "is_email_used", return_value=False):
|
||||
with patch.object(reg, "gmail_get_email_and_token", return_value=("a@cf-domain.test", "gmail:t")) as ge:
|
||||
out = reg.get_email_and_token()
|
||||
assert out == ("a@cf-domain.test", "gmail:t")
|
||||
assert ge.called
|
||||
with patch.object(reg, "gmail_get_oai_code", return_value="ABC-DEF") as gc:
|
||||
code = reg.get_oai_code("gmail:t", "a@cf-domain.test", timeout=1)
|
||||
assert code == "ABC-DEF"
|
||||
assert gc.called
|
||||
print("PASS gmail dispatch")
|
||||
|
||||
|
||||
def test_gmail_imap_extracts_code_with_recipient_match() -> None:
|
||||
reg = _load_reg()
|
||||
reg.config["gmail_require_recipient_match"] = True
|
||||
reg.config["gmail_recent_seconds"] = 900
|
||||
reg.config["gmail_imap_last_n"] = 5
|
||||
|
||||
import email.message
|
||||
from email.utils import formatdate
|
||||
import time as _time
|
||||
|
||||
msg = email.message.EmailMessage()
|
||||
msg["From"] = "noreply@x.ai"
|
||||
msg["To"] = "rand123@cf-domain.test"
|
||||
msg["Subject"] = "XYZ-QWE xAI confirmation code"
|
||||
msg["Date"] = formatdate(_time.time(), localtime=False, usegmt=True)
|
||||
msg.set_content("Your verification code is XYZ-QWE")
|
||||
|
||||
fake_imap = MagicMock()
|
||||
fake_imap.noop.return_value = ("OK", [b""])
|
||||
fake_imap.select.return_value = ("OK", [b"1"])
|
||||
fake_imap.search.return_value = ("OK", [b"1"])
|
||||
fake_imap.fetch.return_value = ("OK", [(b"1 (RFC822)", msg.as_bytes())])
|
||||
|
||||
code = reg._gmail_imap_get_code_on_conn(fake_imap, "rand123@cf-domain.test")
|
||||
assert code == "XYZ-QWE"
|
||||
print("PASS gmail imap extract with recipient match")
|
||||
|
||||
|
||||
def test_gmail_requires_domains() -> None:
|
||||
reg = _load_reg()
|
||||
reg.config["gmail_imap_user"] = "catch@gmail.com"
|
||||
reg.config["gmail_imap_password"] = "app-pass"
|
||||
reg.config["defaultDomains"] = ""
|
||||
try:
|
||||
reg.gmail_get_email_and_token()
|
||||
raise AssertionError("expected Exception")
|
||||
except Exception as e:
|
||||
assert "defaultDomains" in str(e)
|
||||
print("PASS gmail requires domains")
|
||||
|
||||
|
||||
def test_gmail_recipient_match_via_received_header() -> None:
|
||||
"""CF routing often leaves original RCPT only in Received, not To/Delivered-To."""
|
||||
reg = _load_reg()
|
||||
reg.config["gmail_require_recipient_match"] = True
|
||||
reg.config["gmail_recent_seconds"] = 900
|
||||
reg.config["gmail_imap_last_n"] = 5
|
||||
|
||||
import email.message
|
||||
import time as _time
|
||||
from email.utils import formatdate
|
||||
|
||||
msg = email.message.EmailMessage()
|
||||
msg["From"] = "noreply@x.ai"
|
||||
msg["To"] = "catch@gmail.com" # Gmail mailbox after CF rewrite
|
||||
msg["Delivered-To"] = "catch@gmail.com"
|
||||
msg["Received"] = (
|
||||
"from filterdrecv-abcd.mail.example.net by mx.google.com "
|
||||
"for <rand123@cf-domain.test>; Tue, 14 Jul 2026 00:00:00 +0000"
|
||||
)
|
||||
msg["Subject"] = "ABC-DEF xAI confirmation code"
|
||||
msg["Date"] = formatdate(_time.time(), localtime=False, usegmt=True)
|
||||
msg.set_content("Your verification code is ABC-DEF")
|
||||
|
||||
fake_imap = MagicMock()
|
||||
fake_imap.noop.return_value = ("OK", [b""])
|
||||
fake_imap.select.return_value = ("OK", [b"1"])
|
||||
fake_imap.search.return_value = ("OK", [b"1"])
|
||||
fake_imap.fetch.return_value = ("OK", [(b"1 (RFC822)", msg.as_bytes())])
|
||||
|
||||
code = reg._gmail_imap_get_code_on_conn(fake_imap, "rand123@cf-domain.test")
|
||||
assert code == "ABC-DEF", code
|
||||
print("PASS gmail recipient match via Received")
|
||||
|
||||
|
||||
def test_gmail_auth_error_classified_fatal() -> None:
|
||||
import ast
|
||||
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(src)
|
||||
ns: dict = {}
|
||||
for node in tree.body:
|
||||
if isinstance(node, ast.FunctionDef) and node.name in {
|
||||
"is_fatal_register_error",
|
||||
"classify_email_stage_failure",
|
||||
}:
|
||||
mod = ast.Module(body=[node], type_ignores=[])
|
||||
exec(compile(mod, "register_cli.py", "exec"), ns)
|
||||
is_fatal = ns["is_fatal_register_error"]
|
||||
classify = ns["classify_email_stage_failure"]
|
||||
cases = [
|
||||
"Gmail 模式需要 gmail_imap_user / GMAIL_IMAP_USER",
|
||||
"Gmail catch-all 需要在 defaultDomains 中配置已路由到该 Gmail 的域名",
|
||||
"Gmail IMAP 认证失败: [AUTHENTICATIONFAILED] Invalid credentials",
|
||||
"Gmail IMAP 凭证未配置(gmail_imap_user / gmail_imap_password)",
|
||||
]
|
||||
for msg in cases:
|
||||
assert is_fatal(msg), msg
|
||||
assert classify(msg) == "fatal", (msg, classify(msg))
|
||||
print("PASS gmail auth/config fatal")
|
||||
|
||||
|
||||
def test_gmail_cleanup_drops_token_map() -> None:
|
||||
reg = _load_reg()
|
||||
reg.config["gmail_imap_user"] = "catch@gmail.com"
|
||||
reg.config["gmail_imap_password"] = "app-pass"
|
||||
reg.config["defaultDomains"] = "cf-domain.test"
|
||||
with patch.object(reg, "is_email_used", return_value=False):
|
||||
addr, token = reg.gmail_get_email_and_token()
|
||||
assert token in reg._gmail_token_map
|
||||
reg._gmail_cleanup_email(addr)
|
||||
assert token not in reg._gmail_token_map
|
||||
assert addr.lower() not in reg._gmail_reserved_emails
|
||||
print("PASS gmail cleanup token map")
|
||||
|
||||
|
||||
def test_save_config_strips_gmail_password() -> None:
|
||||
reg = _load_reg()
|
||||
import json
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
cfg_path = Path(td) / "config.json"
|
||||
old = reg.CONFIG_FILE
|
||||
try:
|
||||
reg.CONFIG_FILE = str(cfg_path)
|
||||
reg.config["gmail_imap_password"] = "secret-app-pass"
|
||||
reg.config["gmail_imap_user"] = "catch@gmail.com"
|
||||
reg.save_config()
|
||||
saved = json.loads(cfg_path.read_text(encoding="utf-8"))
|
||||
assert saved.get("gmail_imap_password") == ""
|
||||
assert reg.config["gmail_imap_password"] == "secret-app-pass"
|
||||
finally:
|
||||
reg.CONFIG_FILE = old
|
||||
print("PASS save_config strips gmail password")
|
||||
|
||||
|
||||
def test_cli_persist_stage_error_includes_gmail() -> None:
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
assert "def _should_persist_email_stage_error" in src
|
||||
assert '"gmail"' in src
|
||||
assert "_should_persist_email_stage_error()" in src
|
||||
print("PASS cli persist stage error includes gmail")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
test_gmail_generate_domain_email()
|
||||
test_gmail_dispatch_get_email_and_code()
|
||||
test_gmail_imap_extracts_code_with_recipient_match()
|
||||
test_gmail_requires_domains()
|
||||
test_gmail_recipient_match_via_received_header()
|
||||
test_gmail_auth_error_classified_fatal()
|
||||
test_gmail_cleanup_drops_token_map()
|
||||
test_save_config_strips_gmail_password()
|
||||
test_cli_persist_stage_error_includes_gmail()
|
||||
print("\nALL PASS (gmail imap provider)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,97 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Static + optional live checks for Hotmail REST auto code fetch."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def test_split_regex_not_eating_s() -> None:
|
||||
# regression: r"[,,\\s]+" treated letter s as separator
|
||||
bad = re.split(r"[,,\\s]+", "rest,imap")
|
||||
good = re.split(r"[,,\s]+", "rest,imap")
|
||||
assert good == ["rest", "imap"], good
|
||||
assert bad != good
|
||||
print("PASS split regex")
|
||||
|
||||
|
||||
def test_modes_and_rest_helpers() -> None:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
import grok_register_ttk as reg # noqa: E402
|
||||
|
||||
reg.config["hotmail_mail_fetch_modes"] = "rest,imap"
|
||||
modes = reg._hotmail_mail_fetch_modes()
|
||||
assert modes[0] == "rest", modes
|
||||
assert "imap" in modes
|
||||
assert hasattr(reg, "_hotmail_rest_get_code")
|
||||
assert hasattr(reg, "_hotmail_parse_iso_ts")
|
||||
ts = reg._hotmail_parse_iso_ts("2026-07-11T16:47:54Z")
|
||||
assert ts > 0
|
||||
# subject-only extraction used by REST path
|
||||
code = reg.extract_verification_code(
|
||||
"Validate your email ...",
|
||||
"YWM-1ZD xAI confirmation code",
|
||||
)
|
||||
assert code == "YWM-1ZD", code
|
||||
print("PASS modes/rest helpers", modes)
|
||||
|
||||
|
||||
def test_live_rest_if_credentials() -> None:
|
||||
"""Live mailbox smoke — opt-in only.
|
||||
|
||||
Requires:
|
||||
- GROK_REGISTER_LIVE=1
|
||||
- local mail_credentials.txt (gitignored)
|
||||
Never enable this in CI.
|
||||
"""
|
||||
import os
|
||||
|
||||
if os.environ.get("GROK_REGISTER_LIVE", "").strip() not in {"1", "true", "TRUE", "yes", "YES"}:
|
||||
print("SKIP live REST (set GROK_REGISTER_LIVE=1 to enable)")
|
||||
return
|
||||
cred = ROOT / "mail_credentials.txt"
|
||||
if not cred.is_file():
|
||||
print("SKIP live REST (no mail_credentials.txt)")
|
||||
return
|
||||
sys.path.insert(0, str(ROOT))
|
||||
import grok_register_ttk as reg # noqa: E402
|
||||
|
||||
# Prefer reading historical code for a known alias via REST without waiting new mail:
|
||||
# use main mailbox + require_recipient false temporarily if needed.
|
||||
accounts = reg._hotmail_load_accounts(force=True)
|
||||
acc = accounts[0]
|
||||
token = reg.hotmail_refresh_access_token(acc, log_callback=print)
|
||||
# Smoke against historical inbox: widen window so old confirmation mails count.
|
||||
# Real registration still uses config hotmail_recent_seconds (default 900).
|
||||
old_match = reg.config.get("hotmail_require_recipient_match", True)
|
||||
old_recent = reg.config.get("hotmail_recent_seconds", 900)
|
||||
reg.config["hotmail_require_recipient_match"] = False
|
||||
reg.config["hotmail_recent_seconds"] = max(int(old_recent or 900), 86400 * 3)
|
||||
try:
|
||||
code = reg._hotmail_rest_get_code(
|
||||
acc["email"],
|
||||
acc["email"],
|
||||
token,
|
||||
log_callback=print,
|
||||
)
|
||||
finally:
|
||||
reg.config["hotmail_require_recipient_match"] = old_match
|
||||
reg.config["hotmail_recent_seconds"] = old_recent
|
||||
assert code, "REST should return a recent verification code from inbox"
|
||||
print("PASS live REST code", code)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
test_split_regex_not_eating_s()
|
||||
test_modes_and_rest_helpers()
|
||||
test_live_rest_if_credentials()
|
||||
print("\nALL PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,690 @@
|
||||
"""Unit tests for mail_pool_probe (no live Microsoft calls)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from mail_pool_probe import (
|
||||
STATUS_ABUSE_MODE,
|
||||
STATUS_GRANT_EXPIRED,
|
||||
STATUS_NETWORK_ERROR,
|
||||
STATUS_OK,
|
||||
STATUS_PARSE_ERROR,
|
||||
STATUS_REFRESH_INVALID,
|
||||
STATUS_UNKNOWN,
|
||||
classify_error,
|
||||
filter_by_domains,
|
||||
is_quarantinable,
|
||||
load_pool,
|
||||
parse_credential_line,
|
||||
pool_stats,
|
||||
probe_one,
|
||||
probe_sample,
|
||||
quarantine,
|
||||
sample_accounts,
|
||||
update_refresh_token_in_pool,
|
||||
)
|
||||
|
||||
|
||||
def _line(email: str, password: str = "pw", cid: str = "cid", rt: str = "rt") -> str:
|
||||
return f"{email}----{password}----{cid}----{rt}\n"
|
||||
|
||||
|
||||
def test_parse_credential_line_ok():
|
||||
c = parse_credential_line("a@hotmail.com----p----client----refresh\n")
|
||||
assert c is not None
|
||||
assert c.email == "a@hotmail.com"
|
||||
assert c.password == "p"
|
||||
assert c.client_id == "client"
|
||||
assert c.refresh_token == "refresh"
|
||||
assert c.domain == "hotmail.com"
|
||||
|
||||
|
||||
def test_parse_credential_line_json_object():
|
||||
from mail_pool_probe import normalize_credential_line, normalize_credential_text
|
||||
|
||||
raw = (
|
||||
'{"email":"KanodeShapleigh20@outlook.com","password":"Di5VBneA",'
|
||||
'"clientId":"9e5f9abc-0000-0000-0000-000000000001",'
|
||||
'"refreshToken":"M.C501_BAY.0.U.-refresh"}'
|
||||
)
|
||||
c = parse_credential_line(raw, line_no=7)
|
||||
assert c is not None
|
||||
assert c.email == "KanodeShapleigh20@outlook.com"
|
||||
assert c.password == "Di5VBneA"
|
||||
assert c.client_id.startswith("9e5f9abc")
|
||||
assert c.refresh_token.startswith("M.C501")
|
||||
assert c.domain == "outlook.com"
|
||||
norm = normalize_credential_line(raw)
|
||||
assert norm == (
|
||||
"KanodeShapleigh20@outlook.com----Di5VBneA----"
|
||||
"9e5f9abc-0000-0000-0000-000000000001----M.C501_BAY.0.U.-refresh"
|
||||
)
|
||||
text, stats = normalize_credential_text(raw)
|
||||
assert stats["written"] == 1 and stats["json_objects"] == 1
|
||||
assert text.strip() == norm
|
||||
|
||||
|
||||
def test_parse_credential_line_rejects_bad():
|
||||
assert parse_credential_line("") is None
|
||||
assert parse_credential_line("# comment") is None
|
||||
assert parse_credential_line("only----two") is None
|
||||
assert parse_credential_line("notanemail----p----c----r") is None
|
||||
assert parse_credential_line("a@b.com----p---- ----r") is None
|
||||
assert parse_credential_line('{"email":"x","password":"p"}') is None
|
||||
|
||||
|
||||
def test_normalize_alt_delimiters_and_csv():
|
||||
from mail_pool_probe import normalize_credential_line, normalize_credential_text
|
||||
|
||||
pipe = "a@outlook.com|pw1|cid-aaaa|rt-bbbbbbbb"
|
||||
assert normalize_credential_line(pipe) == "a@outlook.com----pw1----cid-aaaa----rt-bbbbbbbb"
|
||||
|
||||
colon = "b@hotmail.com:pw2:cid-bbbb:rt-cccccccc"
|
||||
assert normalize_credential_line(colon) == "b@hotmail.com----pw2----cid-bbbb----rt-cccccccc"
|
||||
|
||||
tab = "c@live.com\tpw3\tcid-cccc\trt-dddddddd"
|
||||
assert normalize_credential_line(tab) == "c@live.com----pw3----cid-cccc----rt-dddddddd"
|
||||
|
||||
# wrapped JSON list
|
||||
wrapped = json.dumps(
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"email": "w@outlook.com",
|
||||
"password": "p",
|
||||
"client_id": "cid-wrap1",
|
||||
"refresh_token": "rt-wrap111",
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
text, stats = normalize_credential_text(wrapped)
|
||||
assert stats["written"] == 1 and stats["json_objects"] == 1
|
||||
assert "w@outlook.com----p----cid-wrap1----rt-wrap111" in text
|
||||
|
||||
# CSV with header
|
||||
csv_body = (
|
||||
"Email,Password,ClientId,RefreshToken\n"
|
||||
"h@outlook.com,ph,cid-csv01,rt-csv0001\n"
|
||||
"bad,no,at,sign\n"
|
||||
"i@hotmail.com,pi,cid-csv02,rt-csv0002\n"
|
||||
)
|
||||
text2, stats2 = normalize_credential_text(csv_body)
|
||||
assert stats2["written"] == 2
|
||||
assert stats2.get("csv_rows") == 2
|
||||
assert "h@outlook.com----ph----cid-csv01----rt-csv0001" in text2
|
||||
assert "i@hotmail.com----pi----cid-csv02----rt-csv0002" in text2
|
||||
|
||||
|
||||
def test_normalize_alt_delimiters_and_csv():
|
||||
from mail_pool_probe import normalize_credential_line, normalize_credential_text
|
||||
|
||||
pipe = "a@outlook.com|pw1|cid-aaaa|rt-bbbbbbbb"
|
||||
assert normalize_credential_line(pipe) == "a@outlook.com----pw1----cid-aaaa----rt-bbbbbbbb"
|
||||
|
||||
colon = "b@hotmail.com:pw2:cid-bbbb:rt-cccccccc"
|
||||
assert normalize_credential_line(colon) == "b@hotmail.com----pw2----cid-bbbb----rt-cccccccc"
|
||||
|
||||
tab = "c@live.com\tpw3\tcid-cccc\trt-dddddddd"
|
||||
assert normalize_credential_line(tab) == "c@live.com----pw3----cid-cccc----rt-dddddddd"
|
||||
|
||||
# wrapped JSON list
|
||||
wrapped = json.dumps(
|
||||
{
|
||||
"data": [
|
||||
{
|
||||
"email": "w@outlook.com",
|
||||
"password": "p",
|
||||
"client_id": "cid-wrap1",
|
||||
"refresh_token": "rt-wrap111",
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
text, stats = normalize_credential_text(wrapped)
|
||||
assert stats["written"] == 1 and stats["json_objects"] == 1
|
||||
assert "w@outlook.com----p----cid-wrap1----rt-wrap111" in text
|
||||
|
||||
# CSV with header
|
||||
csv_body = (
|
||||
"Email,Password,ClientId,RefreshToken\n"
|
||||
"h@outlook.com,ph,cid-csv01,rt-csv0001\n"
|
||||
"bad,no,at,sign\n"
|
||||
"i@hotmail.com,pi,cid-csv02,rt-csv0002\n"
|
||||
)
|
||||
text2, stats2 = normalize_credential_text(csv_body)
|
||||
assert stats2["written"] == 2
|
||||
assert stats2.get("csv_rows") == 2
|
||||
assert "h@outlook.com----ph----cid-csv01----rt-csv0001" in text2
|
||||
assert "i@hotmail.com----pi----cid-csv02----rt-csv0002" in text2
|
||||
|
||||
|
||||
def test_load_pool_dedupes(tmp_path: Path):
|
||||
p = tmp_path / "mail_credentials.txt"
|
||||
p.write_text(
|
||||
_line("A@Hotmail.com", "p1", "c1", "r1")
|
||||
+ _line("a@hotmail.com", "p2", "c2", "r2")
|
||||
+ _line("b@outlook.com", "p3", "c3", "r3")
|
||||
+ "# skip\n"
|
||||
+ "badline\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
accs = load_pool(p)
|
||||
assert len(accs) == 2
|
||||
assert accs[0].email == "A@Hotmail.com"
|
||||
assert accs[0].password == "p1"
|
||||
assert accs[1].email == "b@outlook.com"
|
||||
|
||||
|
||||
def test_scan_and_compact_pool(tmp_path: Path):
|
||||
from mail_pool_probe import compact_pool, pool_stats, scan_pool_file
|
||||
|
||||
p = tmp_path / "mail_credentials.txt"
|
||||
p.write_text(
|
||||
_line("A@Hotmail.com", "p1", "c1", "r1")
|
||||
+ _line("a@hotmail.com", "p2", "c2", "r2") # dup
|
||||
+ _line("b@outlook.com", "p3", "c3", "r3")
|
||||
+ "# keep-me\n"
|
||||
+ "not-a-cred\n"
|
||||
+ _line("B@Outlook.com", "p4", "c4", "r4") # case dup of b
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
scan = scan_pool_file(p)
|
||||
assert scan["parsed_lines"] == 4
|
||||
assert scan["unique"] == 2
|
||||
assert scan["duplicate_extra"] == 2
|
||||
assert scan["invalid_lines"] == 1
|
||||
assert scan["needs_compact"] is True
|
||||
|
||||
st = pool_stats(p)
|
||||
assert st["total"] == 2
|
||||
assert st["duplicate_extra"] == 2
|
||||
assert st["needs_compact"] is True
|
||||
assert "p1" not in str(st)
|
||||
|
||||
preview = compact_pool(p, dry_run=True)
|
||||
assert preview["dry_run"] is True
|
||||
assert preview["changed"] is True
|
||||
assert preview["duplicate_extra"] == 2
|
||||
assert preview["invalid_dropped"] == 1
|
||||
assert preview["unique"] == 2
|
||||
assert preview["backup_path"] is None
|
||||
# dry_run must not rewrite
|
||||
assert "not-a-cred" in p.read_text(encoding="utf-8")
|
||||
assert p.read_text(encoding="utf-8").count("hotmail.com") >= 1
|
||||
|
||||
out = compact_pool(p, dry_run=False, drop_invalid=True, drop_comments=False)
|
||||
assert out["changed"] is True
|
||||
assert out["backup_path"]
|
||||
assert Path(out["backup_path"]).is_file()
|
||||
text = p.read_text(encoding="utf-8")
|
||||
lines = [ln for ln in text.splitlines() if ln.strip()]
|
||||
# first wins + comment kept + invalid gone
|
||||
assert "A@Hotmail.com----p1----c1----r1" in text
|
||||
assert "b@outlook.com----p3----c3----r3" in text
|
||||
assert "a@hotmail.com----p2" not in text
|
||||
assert "not-a-cred" not in text
|
||||
assert "# keep-me" in text
|
||||
assert "p2" not in text # dup dropped
|
||||
assert out["unique"] == 2
|
||||
assert "已精简" in out["summary"]
|
||||
|
||||
again = compact_pool(p, dry_run=False)
|
||||
assert again["changed"] is False
|
||||
assert again["duplicate_extra"] == 0
|
||||
assert "无需精简" in again["summary"]
|
||||
|
||||
|
||||
def test_scan_and_compact_pool(tmp_path: Path):
|
||||
from mail_pool_probe import compact_pool, pool_stats, scan_pool_file
|
||||
|
||||
p = tmp_path / "mail_credentials.txt"
|
||||
p.write_text(
|
||||
_line("A@Hotmail.com", "p1", "c1", "r1")
|
||||
+ _line("a@hotmail.com", "p2", "c2", "r2") # dup
|
||||
+ _line("b@outlook.com", "p3", "c3", "r3")
|
||||
+ "# keep-me\n"
|
||||
+ "not-a-cred\n"
|
||||
+ _line("B@Outlook.com", "p4", "c4", "r4") # case dup of b
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
scan = scan_pool_file(p)
|
||||
assert scan["parsed_lines"] == 4
|
||||
assert scan["unique"] == 2
|
||||
assert scan["duplicate_extra"] == 2
|
||||
assert scan["invalid_lines"] == 1
|
||||
assert scan["needs_compact"] is True
|
||||
|
||||
st = pool_stats(p)
|
||||
assert st["total"] == 2
|
||||
assert st["duplicate_extra"] == 2
|
||||
assert st["needs_compact"] is True
|
||||
assert "p1" not in str(st)
|
||||
|
||||
preview = compact_pool(p, dry_run=True)
|
||||
assert preview["dry_run"] is True
|
||||
assert preview["changed"] is True
|
||||
assert preview["duplicate_extra"] == 2
|
||||
assert preview["invalid_dropped"] == 1
|
||||
assert preview["unique"] == 2
|
||||
assert preview["backup_path"] is None
|
||||
# dry_run must not rewrite
|
||||
assert "not-a-cred" in p.read_text(encoding="utf-8")
|
||||
assert p.read_text(encoding="utf-8").count("hotmail.com") >= 1
|
||||
|
||||
out = compact_pool(p, dry_run=False, drop_invalid=True, drop_comments=False)
|
||||
assert out["changed"] is True
|
||||
assert out["backup_path"]
|
||||
assert Path(out["backup_path"]).is_file()
|
||||
text = p.read_text(encoding="utf-8")
|
||||
lines = [ln for ln in text.splitlines() if ln.strip()]
|
||||
# first wins + comment kept + invalid gone
|
||||
assert "A@Hotmail.com----p1----c1----r1" in text
|
||||
assert "b@outlook.com----p3----c3----r3" in text
|
||||
assert "a@hotmail.com----p2" not in text
|
||||
assert "not-a-cred" not in text
|
||||
assert "# keep-me" in text
|
||||
assert "p2" not in text # dup dropped
|
||||
assert out["unique"] == 2
|
||||
assert "已精简" in out["summary"]
|
||||
|
||||
again = compact_pool(p, dry_run=False)
|
||||
assert again["changed"] is False
|
||||
assert again["duplicate_extra"] == 0
|
||||
assert "无需精简" in again["summary"]
|
||||
|
||||
|
||||
def test_filter_by_domains_and_sample():
|
||||
from mail_pool_probe import Credential
|
||||
|
||||
accs = [
|
||||
Credential("a@hotmail.com", "p", "c", "r"),
|
||||
Credential("b@outlook.com", "p", "c", "r"),
|
||||
Credential("c@live.com", "p", "c", "r"),
|
||||
]
|
||||
assert len(filter_by_domains(accs, None)) == 3
|
||||
assert len(filter_by_domains(accs, [])) == 3
|
||||
hot = filter_by_domains(accs, ["Hotmail.com"])
|
||||
assert [a.email for a in hot] == ["a@hotmail.com"]
|
||||
multi = filter_by_domains(accs, ["hotmail.com", "live.com"])
|
||||
assert {a.domain for a in multi} == {"hotmail.com", "live.com"}
|
||||
|
||||
s1 = sample_accounts(accs, 2, seed=42)
|
||||
s2 = sample_accounts(accs, 2, seed=42)
|
||||
assert [a.email for a in s1] == [a.email for a in s2]
|
||||
assert len(sample_accounts(accs, 10, seed=1)) == 3
|
||||
assert sample_accounts(accs, 0) == []
|
||||
|
||||
|
||||
def test_sample_accounts_sequential_offset():
|
||||
from mail_pool_probe import Credential
|
||||
|
||||
accs = [Credential(f"u{i}@hotmail.com", "p", "c", "r") for i in range(10)]
|
||||
# Stable slice: no shuffle when offset is set
|
||||
s0 = sample_accounts(accs, 3, offset=0)
|
||||
assert [a.email for a in s0] == [
|
||||
"u0@hotmail.com",
|
||||
"u1@hotmail.com",
|
||||
"u2@hotmail.com",
|
||||
]
|
||||
s3 = sample_accounts(accs, 3, offset=3)
|
||||
assert [a.email for a in s3] == [
|
||||
"u3@hotmail.com",
|
||||
"u4@hotmail.com",
|
||||
"u5@hotmail.com",
|
||||
]
|
||||
# Past end → empty
|
||||
assert sample_accounts(accs, 3, offset=10) == []
|
||||
assert sample_accounts(accs, 3, offset=99) == []
|
||||
# Partial last page
|
||||
last = sample_accounts(accs, 5, offset=8)
|
||||
assert [a.email for a in last] == ["u8@hotmail.com", "u9@hotmail.com"]
|
||||
# Full multi-wave cover without overlap / gap
|
||||
seen: list[str] = []
|
||||
off = 0
|
||||
while True:
|
||||
wave = sample_accounts(accs, 4, offset=off)
|
||||
if not wave:
|
||||
break
|
||||
seen.extend(a.email for a in wave)
|
||||
off += len(wave)
|
||||
assert seen == [f"u{i}@hotmail.com" for i in range(10)]
|
||||
|
||||
|
||||
def test_probe_sample_sequential_paging(tmp_path: Path):
|
||||
p = tmp_path / "mail_credentials.txt"
|
||||
lines = "".join(
|
||||
_line(f"u{i}@hotmail.com", f"p{i}", f"c{i}", f"r{i}") for i in range(7)
|
||||
)
|
||||
p.write_text(lines, encoding="utf-8")
|
||||
|
||||
def refresh(acc):
|
||||
return True, "", None
|
||||
|
||||
w0 = probe_sample(
|
||||
p,
|
||||
domains=["hotmail.com"],
|
||||
limit=3,
|
||||
offset=0,
|
||||
concurrency=2,
|
||||
refresh_fn=refresh,
|
||||
writeback_rotated=False,
|
||||
)
|
||||
assert w0["mode"] == "sequential"
|
||||
assert w0["offset"] == 0
|
||||
assert w0["next_offset"] == 3
|
||||
assert w0["done"] is False
|
||||
assert w0["pool_filtered_total"] == 7
|
||||
assert w0["probed"] == 3
|
||||
assert w0["limit"] == 3
|
||||
assert [r["email"] for r in w0["results"]] == [
|
||||
"u0@hotmail.com",
|
||||
"u1@hotmail.com",
|
||||
"u2@hotmail.com",
|
||||
]
|
||||
|
||||
w1 = probe_sample(
|
||||
p,
|
||||
domains=["hotmail.com"],
|
||||
limit=3,
|
||||
offset=w0["next_offset"],
|
||||
concurrency=2,
|
||||
refresh_fn=refresh,
|
||||
writeback_rotated=False,
|
||||
)
|
||||
assert w1["offset"] == 3
|
||||
assert w1["next_offset"] == 6
|
||||
assert w1["done"] is False
|
||||
assert [r["email"] for r in w1["results"]] == [
|
||||
"u3@hotmail.com",
|
||||
"u4@hotmail.com",
|
||||
"u5@hotmail.com",
|
||||
]
|
||||
|
||||
w2 = probe_sample(
|
||||
p,
|
||||
domains=["hotmail.com"],
|
||||
limit=3,
|
||||
offset=w1["next_offset"],
|
||||
concurrency=2,
|
||||
refresh_fn=refresh,
|
||||
writeback_rotated=False,
|
||||
)
|
||||
assert w2["offset"] == 6
|
||||
assert w2["next_offset"] == 7
|
||||
assert w2["done"] is True
|
||||
assert w2["probed"] == 1
|
||||
assert [r["email"] for r in w2["results"]] == ["u6@hotmail.com"]
|
||||
|
||||
# Empty page past end
|
||||
w3 = probe_sample(
|
||||
p,
|
||||
domains=["hotmail.com"],
|
||||
limit=3,
|
||||
offset=7,
|
||||
concurrency=1,
|
||||
refresh_fn=refresh,
|
||||
writeback_rotated=False,
|
||||
)
|
||||
assert w3["probed"] == 0
|
||||
assert w3["next_offset"] == 7
|
||||
assert w3["done"] is True
|
||||
|
||||
|
||||
def test_classify_error_mapping():
|
||||
assert classify_error("AADSTS700082: The refresh token has expired") == STATUS_GRANT_EXPIRED
|
||||
assert classify_error("grant is expired") == STATUS_GRANT_EXPIRED
|
||||
assert classify_error("invalid_grant: The provided grant is invalid") == STATUS_REFRESH_INVALID
|
||||
assert classify_error("AADSTS70000: something") == STATUS_REFRESH_INVALID
|
||||
assert classify_error("account is in abuse mode") == STATUS_ABUSE_MODE
|
||||
assert classify_error("Connection timed out") == STATUS_NETWORK_ERROR
|
||||
assert classify_error("URLError: Name or service not known") == STATUS_NETWORK_ERROR
|
||||
assert classify_error(TimeoutError("timed out")) == STATUS_NETWORK_ERROR
|
||||
assert classify_error("missing fields") == STATUS_PARSE_ERROR
|
||||
assert classify_error("something weird") == STATUS_UNKNOWN
|
||||
assert classify_error(None) == STATUS_UNKNOWN
|
||||
# broad English must NOT mis-classify as network / invalid
|
||||
assert classify_error("please check your network settings in account") == STATUS_UNKNOWN
|
||||
assert classify_error("value is not valid for display") == STATUS_UNKNOWN
|
||||
|
||||
|
||||
def test_is_quarantinable_whitelist():
|
||||
assert is_quarantinable(STATUS_GRANT_EXPIRED)
|
||||
assert is_quarantinable(STATUS_REFRESH_INVALID)
|
||||
assert is_quarantinable(STATUS_ABUSE_MODE)
|
||||
assert not is_quarantinable(STATUS_OK)
|
||||
assert not is_quarantinable(STATUS_NETWORK_ERROR)
|
||||
assert not is_quarantinable(STATUS_UNKNOWN)
|
||||
assert not is_quarantinable(STATUS_PARSE_ERROR)
|
||||
|
||||
|
||||
def test_probe_one_with_injectable_refresh():
|
||||
from mail_pool_probe import Credential
|
||||
|
||||
acc = Credential("ok@hotmail.com", "p", "c", "r")
|
||||
|
||||
def ok_fn(_a):
|
||||
return True, "", None
|
||||
|
||||
def dead_fn(_a):
|
||||
return False, "AADSTS700082: The refresh token has expired due to inactivity", None
|
||||
|
||||
def boom_fn(_a):
|
||||
raise TimeoutError("connection timed out")
|
||||
|
||||
def two_tuple_ok(_a):
|
||||
return True, ""
|
||||
|
||||
r = probe_one(acc, refresh_fn=ok_fn)
|
||||
assert r.status == STATUS_OK
|
||||
assert r.email == "ok@hotmail.com"
|
||||
assert r.quarantinable is False
|
||||
public = r.to_public_dict()
|
||||
assert "password" not in public
|
||||
assert "client_id" not in public
|
||||
assert "refresh_token" not in public
|
||||
assert public["quarantinable"] is False
|
||||
|
||||
r2 = probe_one(acc, refresh_fn=dead_fn)
|
||||
assert r2.status == STATUS_GRANT_EXPIRED
|
||||
assert r2.quarantinable is True
|
||||
assert "AADSTS700082" in r2.ms_error
|
||||
|
||||
r3 = probe_one(acc, refresh_fn=boom_fn)
|
||||
assert r3.status == STATUS_NETWORK_ERROR
|
||||
assert r3.quarantinable is False
|
||||
|
||||
r4 = probe_one(acc, refresh_fn=two_tuple_ok)
|
||||
assert r4.status == STATUS_OK
|
||||
|
||||
|
||||
def test_probe_sample_order_and_counts(tmp_path: Path):
|
||||
p = tmp_path / "mail_credentials.txt"
|
||||
lines = "".join(
|
||||
_line(f"u{i}@hotmail.com", f"p{i}", f"c{i}", f"r{i}") for i in range(10)
|
||||
)
|
||||
p.write_text(lines, encoding="utf-8")
|
||||
|
||||
def refresh(acc):
|
||||
local = acc.email.split("@", 1)[0]
|
||||
n = int(local[1:])
|
||||
if n % 2 == 0:
|
||||
return True, "", None
|
||||
if n % 3 == 0:
|
||||
return False, "Connection timed out", None
|
||||
return False, "invalid_grant: The provided grant is invalid", None
|
||||
|
||||
out = probe_sample(
|
||||
p,
|
||||
domains=["hotmail.com"],
|
||||
limit=6,
|
||||
seed=7,
|
||||
concurrency=3,
|
||||
refresh_fn=refresh,
|
||||
writeback_rotated=False,
|
||||
)
|
||||
assert out["probed"] == 6
|
||||
assert out["ok"] + out["dead"] == 6
|
||||
assert "quarantinable" in out
|
||||
assert out["quarantinable"] <= out["dead"]
|
||||
for row in out["results"]:
|
||||
assert set(row.keys()) == {
|
||||
"email",
|
||||
"domain",
|
||||
"status",
|
||||
"reason",
|
||||
"ms_error",
|
||||
"quarantinable",
|
||||
}
|
||||
assert "password" not in row
|
||||
assert "client_id" not in row
|
||||
assert "refresh_token" not in row
|
||||
if row["status"] == STATUS_NETWORK_ERROR:
|
||||
assert row["quarantinable"] is False
|
||||
if row["status"] == STATUS_REFRESH_INVALID:
|
||||
assert row["quarantinable"] is True
|
||||
|
||||
|
||||
def test_probe_rotation_writeback(tmp_path: Path):
|
||||
p = tmp_path / "mail_credentials.txt"
|
||||
p.write_text(_line("rot@hotmail.com", "pw", "cid", "old_rt"), encoding="utf-8")
|
||||
|
||||
def refresh(acc):
|
||||
assert acc.refresh_token == "old_rt"
|
||||
return True, "", "new_rt_rotated"
|
||||
|
||||
out = probe_sample(
|
||||
p,
|
||||
limit=1,
|
||||
seed=1,
|
||||
concurrency=1,
|
||||
refresh_fn=refresh,
|
||||
writeback_rotated=True,
|
||||
)
|
||||
assert out["ok"] == 1
|
||||
text = p.read_text(encoding="utf-8")
|
||||
assert "new_rt_rotated" in text
|
||||
assert "old_rt" not in text
|
||||
# secrets shape preserved
|
||||
assert "rot@hotmail.com----pw----cid----new_rt_rotated" in text
|
||||
|
||||
|
||||
def test_update_refresh_token_in_pool(tmp_path: Path):
|
||||
p = tmp_path / "mail_credentials.txt"
|
||||
p.write_text(
|
||||
_line("a@hotmail.com", "p", "c", "r1") + _line("b@hotmail.com", "p", "c", "r2"),
|
||||
encoding="utf-8",
|
||||
)
|
||||
assert update_refresh_token_in_pool(p, "A@Hotmail.com", "r1b") is True
|
||||
text = p.read_text(encoding="utf-8")
|
||||
assert "a@hotmail.com----p----c----r1b" in text
|
||||
assert "b@hotmail.com----p----c----r2" in text
|
||||
assert update_refresh_token_in_pool(p, "missing@x.com", "x") is False
|
||||
|
||||
|
||||
def test_pool_stats(tmp_path: Path):
|
||||
live = tmp_path / "mail_credentials.txt"
|
||||
live.write_text(
|
||||
_line("a@hotmail.com") + _line("b@outlook.com") + _line("c@hotmail.com"),
|
||||
encoding="utf-8",
|
||||
)
|
||||
dead = tmp_path / "mail_credentials.dead.txt"
|
||||
dead.write_text(
|
||||
"x@hotmail.com----p----c----r----probe:grant_expired----2026-07-24T00:00:00Z\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
st = pool_stats(live, dead_path=dead)
|
||||
assert st["total"] == 3
|
||||
assert st["by_domain"]["hotmail.com"] == 2
|
||||
assert st["by_domain"]["outlook.com"] == 1
|
||||
assert st["dead_total"] == 1
|
||||
assert "hotmail.com" in st["known_domains"]
|
||||
assert "grant_expired" in st["quarantinable_statuses"]
|
||||
# no credential secrets in stats payload
|
||||
blob = str(st)
|
||||
assert "----" not in blob
|
||||
assert "password" not in blob
|
||||
|
||||
|
||||
def test_quarantine_backup_and_dead_append(tmp_path: Path):
|
||||
live = tmp_path / "mail_credentials.txt"
|
||||
live.write_text(
|
||||
_line("keep@hotmail.com", "pk", "ck", "rk")
|
||||
+ _line("dead1@hotmail.com", "pd1", "cd1", "rd1")
|
||||
+ _line("dead2@outlook.com", "pd2", "cd2", "rd2")
|
||||
+ _line("also@live.com", "pa", "ca", "ra"),
|
||||
encoding="utf-8",
|
||||
)
|
||||
out = quarantine(
|
||||
live,
|
||||
["dead1@hotmail.com", "DEAD2@outlook.com", "missing@msn.com"],
|
||||
reason="probe:grant_expired",
|
||||
)
|
||||
assert out["removed"] == 2
|
||||
assert out["not_found"] == 1
|
||||
assert out["live_total_after"] == 2
|
||||
assert Path(out["backup_path"]).is_file()
|
||||
assert "bak-probe-" in Path(out["backup_path"]).name
|
||||
|
||||
remaining = load_pool(live)
|
||||
emails = {a.email.lower() for a in remaining}
|
||||
assert emails == {"keep@hotmail.com", "also@live.com"}
|
||||
keep = next(a for a in remaining if a.email.startswith("keep"))
|
||||
assert keep.password == "pk"
|
||||
assert keep.refresh_token == "rk"
|
||||
|
||||
dead = Path(out["dead_path"])
|
||||
text = dead.read_text(encoding="utf-8")
|
||||
assert "dead1@hotmail.com----pd1----cd1----rd1----probe:grant_expired----" in text
|
||||
assert "dead2@outlook.com----pd2----cd2----rd2----probe:grant_expired----" in text
|
||||
assert "keep@hotmail.com" not in text
|
||||
|
||||
|
||||
def test_quarantine_sanitizes_reason_separators(tmp_path: Path):
|
||||
live = tmp_path / "mail_credentials.txt"
|
||||
live.write_text(_line("a@hotmail.com", "p", "c", "r"), encoding="utf-8")
|
||||
out = quarantine(live, ["a@hotmail.com"], reason="bad----reason\nline")
|
||||
dead = Path(out["dead_path"]).read_text(encoding="utf-8")
|
||||
# reason must not re-introduce ---- field breaks
|
||||
assert "----bad-reason line----" in dead or "bad-reason" in dead
|
||||
assert "bad----reason" not in dead
|
||||
|
||||
|
||||
def test_quarantine_rejects_empty_emails(tmp_path: Path):
|
||||
live = tmp_path / "mail_credentials.txt"
|
||||
live.write_text(_line("a@hotmail.com"), encoding="utf-8")
|
||||
with pytest.raises(ValueError):
|
||||
quarantine(live, [])
|
||||
with pytest.raises(ValueError):
|
||||
quarantine(live, ["", " "])
|
||||
|
||||
|
||||
def test_sample_accounts_off_keeps_shuffle_intact():
|
||||
import os
|
||||
import random as _r
|
||||
import node_score as ns
|
||||
from mail_pool_probe import Credential
|
||||
|
||||
for k in ("EMAIL_IP_CORRELATION", "NODE_SCORE", "NODE_SCORE_ENABLED",
|
||||
"NODE_SCORE_PATH"):
|
||||
os.environ.pop(k, None)
|
||||
ns.set_correlation_enabled(None)
|
||||
accs = [
|
||||
Credential("a@hotmail.com", "p", "c", "r"),
|
||||
Credential("b@outlook.com", "p", "c", "r"),
|
||||
Credential("c@live.com", "p", "c", "r"),
|
||||
]
|
||||
_r.seed(99)
|
||||
want = list(accs)
|
||||
_r.shuffle(want)
|
||||
want = want[:3]
|
||||
# Reseed so sample_accounts starts from the same global RNG state as want.
|
||||
_r.seed(99)
|
||||
got = sample_accounts(list(accs), 3, cfg={}) # OFF path
|
||||
assert got == want
|
||||
@@ -0,0 +1,96 @@
|
||||
import os
|
||||
import random
|
||||
|
||||
import pytest
|
||||
|
||||
import mail_pool_probe as mpp
|
||||
import node_score as ns
|
||||
|
||||
|
||||
def _acc(domain, n):
|
||||
"""Build n Credential-like accounts under one domain."""
|
||||
from mail_pool_probe import Credential
|
||||
return [Credential(email=f"u{i}@{domain}", password="p",
|
||||
client_id="c", refresh_token="r")
|
||||
for i in range(n)]
|
||||
|
||||
|
||||
def _reset():
|
||||
ns.reset_cache()
|
||||
for k in ("NODE_SCORE", "NODE_SCORE_ENABLED", "NODE_SCORE_PATH",
|
||||
"EMAIL_IP_CORRELATION"):
|
||||
os.environ.pop(k, None)
|
||||
ns.set_enabled(None)
|
||||
ns.set_correlation_enabled(None)
|
||||
|
||||
|
||||
def setup_function(_):
|
||||
_reset()
|
||||
|
||||
|
||||
def teardown_function(_):
|
||||
_reset()
|
||||
|
||||
|
||||
def test_off_equivalent_to_shuffle(tmp_path):
|
||||
"""OFF: same random.Random(seed) -> identical sequence to current shuffle."""
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
ns.set_correlation_enabled(False)
|
||||
pool = _acc("a.com", 20) + _acc("b.com", 20)
|
||||
random.seed(1234)
|
||||
want = list(pool)
|
||||
random.shuffle(want)
|
||||
want = want[:7]
|
||||
# Reseed so sample_accounts starts from the same global RNG state as want.
|
||||
random.seed(1234)
|
||||
got = mpp.sample_accounts(list(pool), 7, cfg={}) # OFF
|
||||
assert got == want
|
||||
|
||||
|
||||
def test_single_domain_off_path(tmp_path):
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
ns.set_correlation_enabled(True) # ON, but single domain -> equal weight
|
||||
pool = _acc("a.com", 30)
|
||||
# weights uniform -> every account surfaced over many draws (no domain bias)
|
||||
seen = set()
|
||||
for s in range(40):
|
||||
got = mpp.sample_accounts(list(pool), 10, cfg={"email_ip_correlation": True})
|
||||
seen.update(a.email for a in got)
|
||||
assert len(seen) == 30
|
||||
|
||||
|
||||
def test_seed_disables_weighted_branch(tmp_path):
|
||||
"""seed != None must keep shuffle (deterministic) regardless of switch."""
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
pool = _acc("a.com", 10) + _acc("b.com", 10)
|
||||
ns.set_correlation_enabled(True)
|
||||
a = mpp.sample_accounts(list(pool), 5, seed=7, cfg={"email_ip_correlation": True})
|
||||
b = mpp.sample_accounts(list(pool), 5, seed=7, cfg={"email_ip_correlation": True})
|
||||
assert a == b # deterministic under seed
|
||||
|
||||
|
||||
def test_offset_disables_weighted_branch(tmp_path):
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
pool = _acc("a.com", 12)
|
||||
ns.set_correlation_enabled(True)
|
||||
got = mpp.sample_accounts(list(pool), 4, offset=2,
|
||||
cfg={"email_ip_correlation": True})
|
||||
assert [a.email for a in got] == [f"u{i}@a.com" for i in (2, 3, 4, 5)]
|
||||
|
||||
|
||||
def test_multi_domain_high_score_picked_more(tmp_path):
|
||||
"""Layer ②: a high-score domain is sampled more often than a low-score one."""
|
||||
import json, statistics
|
||||
p = tmp_path / "s.json"
|
||||
p.write_text(json.dumps({"version": 1, "nodes": {}, "domains": {
|
||||
"high.com": {"score": 99, "ok": 5, "cool_until": 0.0},
|
||||
"low.com": {"score": 1, "ok": 0, "cool_until": 0.0}}}), encoding="utf-8")
|
||||
os.environ["NODE_SCORE_PATH"] = str(p)
|
||||
pool = _acc("high.com", 50) + _acc("low.com", 50)
|
||||
ns.set_correlation_enabled(True)
|
||||
high_count = 0
|
||||
for t in range(400):
|
||||
got = mpp.sample_accounts(list(pool), 10, cfg={"email_ip_correlation": True})
|
||||
high_count += sum(1 for a in got if a.domain == "high.com")
|
||||
# high.com should dominate (avg ~9+/10); require a wide margin over parity.
|
||||
assert high_count > 400 * 10 * 0.80
|
||||
@@ -0,0 +1,179 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Mail path must never inherit register egress proxy (pipeline + adapter)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import unittest
|
||||
from dataclasses import dataclass
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from register_core.contracts import OtpWaitDiagnostics, RegisterJob, RegisterResult
|
||||
from register_core.email.mail_proxy import resolve_mail_proxy
|
||||
from register_core.errors import MailMissError
|
||||
from register_core.pipeline import Pipeline
|
||||
from register_core.providers.chatgpt_adapter import ChatGPTProvider
|
||||
from register_core.providers.chatgpt_adapter import resolve_mail_proxy as adapter_resolve
|
||||
|
||||
|
||||
class TestMailProxySeparation(unittest.TestCase):
|
||||
def test_resolve_mail_proxy_never_falls_back_to_register(self) -> None:
|
||||
self.assertEqual(resolve_mail_proxy({"proxy": "http://reg:1"}), "")
|
||||
self.assertEqual(
|
||||
resolve_mail_proxy({"proxy": "http://reg:1", "mail_proxy": "http://mail:2"}),
|
||||
"http://mail:2",
|
||||
)
|
||||
# re-export from adapter stays in sync
|
||||
self.assertIs(adapter_resolve, resolve_mail_proxy)
|
||||
|
||||
def test_env_mail_proxy(self) -> None:
|
||||
with patch.dict(
|
||||
os.environ,
|
||||
{"EMAIL_PROXY": "http://env-mail:3", "CHATGPT_MAIL_PROXY": "", "MAIL_PROXY": ""},
|
||||
clear=False,
|
||||
):
|
||||
self.assertEqual(resolve_mail_proxy({}), "http://env-mail:3")
|
||||
|
||||
def test_adapter_constructs_source_with_mail_proxy_only(self) -> None:
|
||||
captured: dict = {}
|
||||
|
||||
def fake_get(src_name, **kw):
|
||||
captured["name"] = src_name
|
||||
captured["kw"] = kw
|
||||
|
||||
class Src:
|
||||
def allocate(self):
|
||||
raise RuntimeError("stop-before-network")
|
||||
|
||||
src = Src()
|
||||
src.name = src_name # type: ignore[attr-defined]
|
||||
return src
|
||||
|
||||
prov = ChatGPTProvider(proxy="http://register-egress:8080", email_source_name="tinyhost")
|
||||
with patch(
|
||||
"register_core.providers.chatgpt_adapter.get_email_source",
|
||||
side_effect=fake_get,
|
||||
):
|
||||
try:
|
||||
prov.register_one(extra={"proxy": "http://register-egress:8080"})
|
||||
except Exception:
|
||||
pass
|
||||
self.assertIn("kw", captured)
|
||||
# default: no register proxy on mail path
|
||||
self.assertIn(captured["kw"].get("proxy"), (None, ""))
|
||||
|
||||
def test_adapter_applies_mail_proxy_to_injected_source(self) -> None:
|
||||
class Src:
|
||||
name = "tinyhost"
|
||||
proxy = ""
|
||||
|
||||
def allocate(self):
|
||||
raise RuntimeError("stop-before-network")
|
||||
|
||||
src = Src()
|
||||
prov = ChatGPTProvider(email_source_name="tinyhost")
|
||||
try:
|
||||
prov.register_one(
|
||||
email_source=src, # type: ignore[arg-type]
|
||||
extra={"mail_proxy": "http://mail-only:9"},
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
self.assertEqual(src.proxy, "http://mail-only:9")
|
||||
|
||||
def test_pipeline_resolve_email_source_passes_mail_proxy(self) -> None:
|
||||
captured: dict = {}
|
||||
|
||||
def fake_get(src_name, **kw):
|
||||
captured["name"] = src_name
|
||||
captured["kw"] = kw
|
||||
src = type("Src", (), {})()
|
||||
src.name = src_name
|
||||
return src
|
||||
|
||||
job = RegisterJob(
|
||||
provider="chatgpt",
|
||||
email_source="tinyhost",
|
||||
extra={"proxy": "http://reg:1", "mail_proxy": "http://mail:2"},
|
||||
)
|
||||
with patch("register_core.pipeline.get_email_source", side_effect=fake_get):
|
||||
src = Pipeline._resolve_email_source(job)
|
||||
self.assertIsNotNone(src)
|
||||
self.assertEqual(captured["name"], "tinyhost")
|
||||
self.assertEqual(captured["kw"].get("proxy"), "http://mail:2")
|
||||
|
||||
def test_pipeline_resolve_email_source_explicit_direct(self) -> None:
|
||||
captured: dict = {}
|
||||
|
||||
def fake_get(src_name, **kw):
|
||||
captured["kw"] = kw
|
||||
src = type("Src", (), {})()
|
||||
src.name = src_name
|
||||
return src
|
||||
|
||||
job = RegisterJob(
|
||||
provider="chatgpt",
|
||||
email_source="tinyhost",
|
||||
extra={"proxy": "http://reg:1"},
|
||||
)
|
||||
with patch("register_core.pipeline.get_email_source", side_effect=fake_get):
|
||||
Pipeline._resolve_email_source(job)
|
||||
self.assertIn(captured["kw"].get("proxy"), (None, ""))
|
||||
|
||||
def test_pipeline_bare_mail_miss_attaches_otp_wait_and_feedback(self) -> None:
|
||||
diag = OtpWaitDiagnostics(
|
||||
timeout_s=30.0,
|
||||
provider="tinyhost",
|
||||
failure_class="no_mail",
|
||||
poll_count=3,
|
||||
)
|
||||
|
||||
class RaisingProv:
|
||||
name = "chatgpt"
|
||||
|
||||
def register_one(self, **_kw):
|
||||
raise MailMissError("otp timeout", diagnostics=diag)
|
||||
|
||||
feedback_calls: list[RegisterResult] = []
|
||||
|
||||
def _noop_preflight(extra, **_kw):
|
||||
base = dict(extra or {})
|
||||
base["_nodes_preflight_done"] = True
|
||||
base["_nodes_preflight"] = {"skipped": True, "reason": "test"}
|
||||
return base
|
||||
|
||||
def _noop_inject(extra, **_kw):
|
||||
return dict(extra or {})
|
||||
|
||||
pipe = Pipeline(RaisingProv(), fail_fast=True) # type: ignore[arg-type]
|
||||
with (
|
||||
patch(
|
||||
"register_core.util.proxy.preflight_nodes_for_register",
|
||||
side_effect=_noop_preflight,
|
||||
),
|
||||
patch(
|
||||
"register_core.util.proxy.inject_attempt_proxy",
|
||||
side_effect=_noop_inject,
|
||||
),
|
||||
patch.object(
|
||||
pipe,
|
||||
"_feedback_proxy",
|
||||
side_effect=lambda _extra, result: feedback_calls.append(result),
|
||||
),
|
||||
):
|
||||
stats = pipe.run(1, extra={"proxy": "http://reg:1", "nodes_preflight": False})
|
||||
|
||||
self.assertEqual(stats.fail, 1)
|
||||
self.assertEqual(len(stats.results), 1)
|
||||
r = stats.results[0]
|
||||
self.assertFalse(r.ok)
|
||||
self.assertEqual(r.error_kind, "mail_miss")
|
||||
self.assertIn("otp_wait", r.artifacts)
|
||||
self.assertEqual(r.artifacts["otp_wait"]["failure_class"], "no_mail")
|
||||
self.assertEqual(r.artifacts["otp_wait"]["poll_count"], 3)
|
||||
self.assertEqual(len(feedback_calls), 1)
|
||||
self.assertEqual(feedback_calls[0].error_kind, "mail_miss")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(unittest.main())
|
||||
@@ -0,0 +1,170 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unit tests for MiMo → CPA openai-compatibility inject helper."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
MOD_PATH = ROOT / "providers" / "mimo" / "inject_cpa_openai.py"
|
||||
|
||||
|
||||
def _load():
|
||||
spec = importlib.util.spec_from_file_location("inject_cpa_openai", MOD_PATH)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
assert spec and spec.loader
|
||||
spec.loader.exec_module(mod)
|
||||
return mod
|
||||
|
||||
|
||||
SAMPLE = """# sample
|
||||
auth-dir: "/root/.cli-proxy-api"
|
||||
api-keys:
|
||||
- sk-client-aaa
|
||||
openai-compatibility:
|
||||
- name: deepseek
|
||||
priority: -10
|
||||
base-url: https://api.deepseek.com
|
||||
api-key-entries:
|
||||
- api-key: sk-deepseek-old
|
||||
models:
|
||||
- name: deepseek-v4-flash
|
||||
alias: ""
|
||||
- name: xiaomimimo
|
||||
priority: 100
|
||||
base-url: https://api.xiaomimimo.com/v1
|
||||
api-key-entries:
|
||||
- api-key: sk-existingoldkey111111111111111111111111
|
||||
models:
|
||||
- name: mimo-v2.5-tts
|
||||
alias: ""
|
||||
- name: mimo-v2.5-tts-voiceclone
|
||||
alias: ""
|
||||
other-section:
|
||||
foo: 1
|
||||
"""
|
||||
|
||||
|
||||
class TestMimoCpaOpenaiInject(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.mod = _load()
|
||||
|
||||
def test_extract_keys_from_numbered_line(self) -> None:
|
||||
keys = self.mod.extract_keys_from_text("1. sk-testdummykeyaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n")
|
||||
self.assertEqual(len(keys), 1)
|
||||
self.assertTrue(keys[0].startswith("sk-testdummy"))
|
||||
|
||||
def test_append_idempotent(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
cfg = Path(td) / "config.yaml"
|
||||
cfg.write_text(SAMPLE, encoding="utf-8")
|
||||
key = "sk-existingoldkey111111111111111111111111"
|
||||
r1 = self.mod.inject_local(cfg, [key])
|
||||
self.assertTrue(r1["ok"])
|
||||
self.assertFalse(r1["changed"])
|
||||
text = cfg.read_text(encoding="utf-8")
|
||||
self.assertEqual(text.count(key), 1)
|
||||
|
||||
def test_append_new_key(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
cfg = Path(td) / "config.yaml"
|
||||
cfg.write_text(SAMPLE, encoding="utf-8")
|
||||
new = "sk-newkeyaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
|
||||
r = self.mod.inject_local(cfg, [new])
|
||||
self.assertTrue(r["ok"])
|
||||
self.assertTrue(r["changed"])
|
||||
text = cfg.read_text(encoding="utf-8")
|
||||
self.assertIn(new, text)
|
||||
self.assertIn("sk-existingoldkey", text)
|
||||
# deepseek untouched
|
||||
self.assertIn("sk-deepseek-old", text)
|
||||
self.assertIn("other-section:", text)
|
||||
span = self.mod._channel_block_span(text, "xiaomimimo")
|
||||
assert span
|
||||
entry = text[span[0] : span[1]]
|
||||
self.assertEqual(len(self.mod.list_keys_in_entry(entry)), 2)
|
||||
|
||||
def test_create_channel_if_missing(self) -> None:
|
||||
slim = """openai-compatibility:
|
||||
- name: deepseek
|
||||
base-url: https://api.deepseek.com
|
||||
api-key-entries:
|
||||
- api-key: sk-deepseek-old
|
||||
models:
|
||||
- name: deepseek-v4-flash
|
||||
alias: ""
|
||||
tail: 1
|
||||
"""
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
cfg = Path(td) / "config.yaml"
|
||||
cfg.write_text(slim, encoding="utf-8")
|
||||
new = "sk-brandnewbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
|
||||
r = self.mod.inject_local(cfg, [new])
|
||||
self.assertTrue(r["changed"])
|
||||
self.assertTrue(r.get("created_channel"))
|
||||
text = cfg.read_text(encoding="utf-8")
|
||||
self.assertIn("name: xiaomimimo", text)
|
||||
self.assertIn(new, text)
|
||||
self.assertIn("api.xiaomimimo.com/v1", text)
|
||||
|
||||
def test_jsonl_extract(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
p = Path(td) / "a.jsonl"
|
||||
p.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"email": "a@b.com",
|
||||
"apiKey": "sk-jsonlcccccccccccccccccccccccccccccccccccc",
|
||||
}
|
||||
)
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
keys = self.mod.extract_keys_from_jsonl(p)
|
||||
self.assertEqual(keys[0][:10], "sk-jsonlcc")
|
||||
|
||||
def test_extract_hyphenated_vendor_key(self) -> None:
|
||||
keys = self.mod.extract_keys_from_text(
|
||||
"1. sk-hyper-abc-def-0123456789abcdef\n"
|
||||
)
|
||||
self.assertEqual(len(keys), 1)
|
||||
self.assertIn("-", keys[0][3:])
|
||||
|
||||
def test_cli_requires_config(self) -> None:
|
||||
code = self.mod.main(["--key", "sk-testdummykeyaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"])
|
||||
self.assertEqual(code, 2)
|
||||
|
||||
def test_cli_refuses_prod_without_ack(self) -> None:
|
||||
code = self.mod.main(
|
||||
[
|
||||
"--config",
|
||||
"/personal/cpa/config.yaml",
|
||||
"--key",
|
||||
"sk-testdummykeyaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
]
|
||||
)
|
||||
self.assertEqual(code, 2)
|
||||
|
||||
def test_cli_dry_run_allows_prod_path_without_ack(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
cfg = Path(td) / "config.yaml"
|
||||
cfg.write_text(SAMPLE, encoding="utf-8")
|
||||
# Non-prod path dry-run still works with explicit --config
|
||||
code = self.mod.main(
|
||||
[
|
||||
"--config",
|
||||
str(cfg),
|
||||
"--dry-run",
|
||||
"--key",
|
||||
"sk-newkeyaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
]
|
||||
)
|
||||
self.assertEqual(code, 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,183 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lifecycle gates: mint browser owned/release/shutdown + register worker cleanup."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import types
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def test_release_mint_browser_owned_closes() -> None:
|
||||
"""owned=True must close the explicit browser (was a silent no-op)."""
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from cpa_xai import browser_confirm as bc
|
||||
|
||||
closed: list[object] = []
|
||||
|
||||
class FakeBrowser:
|
||||
process_id = None
|
||||
|
||||
def quit(self, *a, **k):
|
||||
closed.append(self)
|
||||
|
||||
fake = FakeBrowser()
|
||||
with mock.patch.object(bc, "close_standalone", side_effect=lambda b: closed.append(b)):
|
||||
bc.release_mint_browser(owned=True, browser=fake, success=True)
|
||||
assert fake in closed, "owned release must close browser"
|
||||
print("PASS release_mint_browser owned closes browser")
|
||||
|
||||
|
||||
def test_release_mint_browser_owned_without_browser_no_crash() -> None:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from cpa_xai import browser_confirm as bc
|
||||
|
||||
# No browser arg and empty TLS — must not raise
|
||||
bc.release_mint_browser(owned=True, browser=None, success=True)
|
||||
print("PASS release owned without browser no crash")
|
||||
|
||||
|
||||
def test_shutdown_mint_browsers_closes_registry() -> None:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from cpa_xai import browser_confirm as bc
|
||||
|
||||
closed: list[object] = []
|
||||
|
||||
class FakeBrowser:
|
||||
process_id = None
|
||||
|
||||
def quit(self, *a, **k):
|
||||
closed.append(self)
|
||||
|
||||
fake = FakeBrowser()
|
||||
bc._mint_registry_add(fake)
|
||||
# Ensure not in TLS so only registry path hits
|
||||
st = bc._mint_tls_get()
|
||||
st["browser"] = None
|
||||
st["page"] = None
|
||||
|
||||
with mock.patch.object(bc, "close_standalone", side_effect=lambda b: closed.append(b) or bc._mint_registry_drop(b)):
|
||||
bc.shutdown_mint_browsers()
|
||||
assert fake in closed
|
||||
with bc._mint_browsers_lock:
|
||||
assert fake not in bc._mint_browsers_all
|
||||
print("PASS shutdown_mint_browsers closes registry leftovers")
|
||||
|
||||
|
||||
def test_acquire_registers_browser() -> None:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from cpa_xai import browser_confirm as bc
|
||||
|
||||
class FakeBrowser:
|
||||
process_id = 0
|
||||
tab_ids = []
|
||||
|
||||
fake_b = FakeBrowser()
|
||||
fake_p = object()
|
||||
|
||||
# Clear state
|
||||
st = bc._mint_tls_get()
|
||||
st["browser"] = None
|
||||
st["page"] = None
|
||||
st["served"] = 0
|
||||
with bc._mint_browsers_lock:
|
||||
bc._mint_browsers_all.clear()
|
||||
|
||||
with mock.patch.object(bc, "create_standalone_page", return_value=(fake_b, fake_p)):
|
||||
with mock.patch.object(bc, "clear_page_session"):
|
||||
b, p, owned = bc.acquire_mint_browser(reuse=False, log=lambda m: None)
|
||||
assert b is fake_b and p is fake_p and owned is True
|
||||
with bc._mint_browsers_lock:
|
||||
assert fake_b in bc._mint_browsers_all
|
||||
# cleanup
|
||||
bc._mint_registry_drop(fake_b)
|
||||
print("PASS acquire_mint_browser registers browser")
|
||||
|
||||
|
||||
def test_register_cli_worker_exit_shuts_mint() -> None:
|
||||
"""Inline mint cleanup: register worker exit must call shutdown_mint_browsers."""
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
# register worker exit block must include mint shutdown (not only mint_worker)
|
||||
assert "register worker exit" in src
|
||||
# Both call sites
|
||||
assert src.count("shutdown_mint_browsers()") >= 3 # reg worker + mint worker + main
|
||||
assert "Inline mint" in src or "inline-mint" in src or "mint_workers=0" in src
|
||||
# main post-join sweep
|
||||
assert "Sweep any mint Chromium" in src or "process registry" in src
|
||||
print("PASS register_cli shuts mint on reg worker + main")
|
||||
|
||||
|
||||
def test_mint_with_browser_finally_uses_release_owned() -> None:
|
||||
src = (ROOT / "cpa_xai" / "browser_confirm.py").read_text(encoding="utf-8")
|
||||
assert "release_mint_browser(" in src
|
||||
assert "owned=True" in src
|
||||
assert "browser=own_browser" in src
|
||||
# no silent owned return without close
|
||||
assert "# owned browser not in tls" not in src
|
||||
print("PASS mint_with_browser finally release owned path")
|
||||
|
||||
|
||||
def test_hybrid_default_in_config_and_ttk() -> None:
|
||||
ttk = (ROOT / "grok_register_ttk.py").read_text(encoding="utf-8")
|
||||
cfg = (ROOT / "config.example.json").read_text(encoding="utf-8")
|
||||
# DEFAULT_CONFIG + PERF_FLAGS
|
||||
assert '"browser_recycle_mode": "hybrid"' in ttk
|
||||
assert '"browser_recycle_mode": "hybrid"' in cfg
|
||||
assert '"browser_recycle_every": 15' in ttk or "'browser_recycle_every': 15" in ttk
|
||||
print("PASS hybrid default config")
|
||||
|
||||
|
||||
def test_clear_session_cookie_fail_returns_false() -> None:
|
||||
"""clear_session must return False when cookie wipe cannot run (hard recycle)."""
|
||||
sys.path.insert(0, str(ROOT))
|
||||
import tab_pool as tp
|
||||
|
||||
class BoomBrowser:
|
||||
tab_ids = []
|
||||
process_id = None
|
||||
|
||||
def cookies(self):
|
||||
raise RuntimeError("no cookies api")
|
||||
|
||||
class BoomTab:
|
||||
def get(self, *a, **k):
|
||||
pass
|
||||
|
||||
def run_js(self, *a, **k):
|
||||
pass
|
||||
|
||||
# Install fake browser on this thread's TLS
|
||||
tp.TabPool._thread_local.browser = BoomBrowser()
|
||||
tp.TabPool._thread_local.tab = BoomTab()
|
||||
tp.TabPool._thread_local.served = 0
|
||||
try:
|
||||
ok = tp.TabPool.clear_session(log_callback=lambda m: None)
|
||||
assert ok is False, "cookie wipe total failure must return False"
|
||||
finally:
|
||||
tp.TabPool._thread_local.browser = None
|
||||
tp.TabPool._thread_local.tab = None
|
||||
print("PASS clear_session returns False when cookies cannot wipe")
|
||||
|
||||
|
||||
def test_clear_session_source_has_service_worker() -> None:
|
||||
src = (ROOT / "tab_pool.py").read_text(encoding="utf-8")
|
||||
assert "serviceWorker" in src
|
||||
assert "cookies_ok=" in src
|
||||
assert "cookie wipe incomplete" in src
|
||||
print("PASS clear_session SW + cookies_ok source")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_release_mint_browser_owned_closes()
|
||||
test_release_mint_browser_owned_without_browser_no_crash()
|
||||
test_shutdown_mint_browsers_closes_registry()
|
||||
test_acquire_registers_browser()
|
||||
test_register_cli_worker_exit_shuts_mint()
|
||||
test_mint_with_browser_finally_uses_release_owned()
|
||||
test_hybrid_default_in_config_and_ttk()
|
||||
test_clear_session_cookie_fail_returns_false()
|
||||
test_clear_session_source_has_service_worker()
|
||||
print("ALL PASS")
|
||||
@@ -0,0 +1,182 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Tests: consent Allow must set action=allow and never default-submit Deny."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
|
||||
def test_consent_helpers_pure() -> None:
|
||||
from cpa_xai import browser_confirm as bc
|
||||
|
||||
assert bc._is_device_done(
|
||||
"https://accounts.x.ai/oauth2/device/done", "设备已授权"
|
||||
)
|
||||
assert bc._is_device_done("https://x/oauth2/device/done?x=1", "ok")
|
||||
assert not bc._is_device_done(
|
||||
"https://accounts.x.ai/oauth2/device/consent?user_code=A", "授权 Grok Build"
|
||||
)
|
||||
|
||||
assert bc._is_consent_page(
|
||||
"https://accounts.x.ai/oauth2/device/consent?user_code=A", ""
|
||||
)
|
||||
assert bc._is_consent_page("https://accounts.x.ai/account", "授权 Grok Build")
|
||||
assert bc._is_consent_page("https://x", "Authorize Grok Build")
|
||||
assert not bc._is_consent_page("https://accounts.x.ai/oauth2/device", "继续")
|
||||
|
||||
# After 3 failed consent actions → reopen once budget
|
||||
assert bc._consent_should_reopen(consent_action_n=3, reopens=0, max_actions=3) is True
|
||||
assert bc._consent_should_reopen(consent_action_n=2, reopens=0, max_actions=3) is False
|
||||
assert bc._consent_should_reopen(consent_action_n=5, reopens=1, max_actions=3) is False
|
||||
print("PASS consent helpers pure")
|
||||
|
||||
|
||||
def test_prepare_consent_allow_sets_action() -> None:
|
||||
from cpa_xai import browser_confirm as bc
|
||||
|
||||
logs: list[str] = []
|
||||
calls: list[str] = []
|
||||
|
||||
class FakePage:
|
||||
def run_js(self, code: str):
|
||||
calls.append(code)
|
||||
assert "action" in code
|
||||
assert "allow" in code
|
||||
# must not bare-submit without allow button preference
|
||||
assert "return 'form_submit'" not in code or "btn.click" in code
|
||||
return "ok:allow"
|
||||
|
||||
ret = bc._prepare_consent_allow_form(FakePage(), logs.append)
|
||||
assert ret == "ok:allow"
|
||||
assert any("consent prepare action=allow" in m for m in logs)
|
||||
assert calls, "expected run_js"
|
||||
# preparation JS must skip cookie forms and prefer 允许 button semantics
|
||||
js = calls[0]
|
||||
assert "隐私偏好" in js or "全部允许" in js
|
||||
assert "allow" in js
|
||||
print("PASS prepare_consent_allow_sets_action")
|
||||
|
||||
|
||||
def test_consent_js_fallback_never_bare_submit_first() -> None:
|
||||
"""Reject path that form.submit() without clicking 允许 (Deny is first submit)."""
|
||||
src = (ROOT / "cpa_xai" / "browser_confirm.py").read_text(encoding="utf-8")
|
||||
assert "def _prepare_consent_allow_form" in src
|
||||
assert "_prepare_consent_allow_form(page" in src
|
||||
# After prepare, real click; stuck → controlled reopen
|
||||
assert "consent_stuck" in src or "consent stuck" in src
|
||||
assert "reopen device" in src.lower() or "reopen_device" in src or "reopen device uri" in src
|
||||
# JS fallback must click allow button; bare f.submit is dangerous (拒绝 first)
|
||||
# Allow form_submit only after explicit action=allow AND no allow button found
|
||||
# and must log it — still better to prefer btn only
|
||||
assert "btn_click:" in src
|
||||
# prepare must run before real click in consent branch
|
||||
consent_idx = src.find("# Consent page")
|
||||
assert consent_idx > 0
|
||||
chunk = src[consent_idx : consent_idx + 3500]
|
||||
prep = chunk.find("_prepare_consent_allow_form")
|
||||
real = chunk.find("real=True")
|
||||
assert 0 <= prep < real, "prepare must run before real click"
|
||||
print("PASS consent js fallback / prepare-before-click markers")
|
||||
|
||||
|
||||
def test_prepare_skips_cookie_form() -> None:
|
||||
from cpa_xai import browser_confirm as bc
|
||||
|
||||
class FakePage:
|
||||
def run_js(self, code: str): # noqa: ARG002
|
||||
return "skip_cookie_form"
|
||||
|
||||
logs: list[str] = []
|
||||
ret = bc._prepare_consent_allow_form(FakePage(), logs.append)
|
||||
assert ret == "skip_cookie_form"
|
||||
print("PASS prepare_skips_cookie_form")
|
||||
|
||||
|
||||
def test_wait_post_allow_state_reaches_done() -> None:
|
||||
"""Mid-nav consent URL then device/done must classify as done, not shell."""
|
||||
from cpa_xai import browser_confirm as bc
|
||||
|
||||
class FakePage:
|
||||
def __init__(self) -> None:
|
||||
self.n = 0
|
||||
self.urls = [
|
||||
"https://accounts.x.ai/oauth2/device/consent?user_code=A",
|
||||
"https://accounts.x.ai/oauth2/device/consent?user_code=A",
|
||||
"https://accounts.x.ai/oauth2/device/done",
|
||||
]
|
||||
self.texts = [
|
||||
"授权 Grok Build 允许",
|
||||
"授权 Grok Build 允许",
|
||||
"设备已授权 您的设备已获授权",
|
||||
]
|
||||
|
||||
@property
|
||||
def url(self) -> str:
|
||||
return self.urls[min(self.n, len(self.urls) - 1)]
|
||||
|
||||
def run_js(self, code: str): # noqa: ARG002
|
||||
# _visible_text path may use run_js; advance on body text reads
|
||||
if "document.body" in code or "innerText" in code:
|
||||
t = self.texts[min(self.n, len(self.texts) - 1)]
|
||||
self.n += 1
|
||||
return t
|
||||
return ""
|
||||
|
||||
# Patch page helpers to drive FakePage without DrissionPage
|
||||
seq = {"i": 0}
|
||||
urls = [
|
||||
"https://accounts.x.ai/oauth2/device/consent?user_code=A",
|
||||
"https://accounts.x.ai/oauth2/device/consent?user_code=A",
|
||||
"https://accounts.x.ai/oauth2/device/done",
|
||||
]
|
||||
texts = [
|
||||
"授权 Grok Build 允许",
|
||||
"授权 Grok Build 允许",
|
||||
"设备已授权 您的设备已获授权",
|
||||
]
|
||||
|
||||
def fake_url(_p): # noqa: ANN001
|
||||
return urls[min(seq["i"], len(urls) - 1)]
|
||||
|
||||
def fake_text(_p): # noqa: ANN001
|
||||
i = seq["i"]
|
||||
t = texts[min(i, len(texts) - 1)]
|
||||
seq["i"] = i + 1
|
||||
return t
|
||||
|
||||
with mock.patch.object(bc, "_page_url", side_effect=fake_url), mock.patch.object(
|
||||
bc, "_visible_text", side_effect=fake_text
|
||||
), mock.patch.object(bc.time, "sleep", return_value=None):
|
||||
u, t = bc._wait_post_allow_state(object(), lambda _m: None, budget_sec=2.0)
|
||||
assert bc._is_device_done(u, t)
|
||||
assert not bc._is_consent_page(u, t)
|
||||
print("PASS wait_post_allow_state_reaches_done")
|
||||
|
||||
|
||||
def test_oauth_hard_invalid_grant_tax_marker() -> None:
|
||||
od = (ROOT / "cpa_xai" / "oauth_device.py").read_text(encoding="utf-8")
|
||||
assert "tax=server_policy" in od
|
||||
assert "consent may have succeeded" in od
|
||||
print("PASS oauth_hard_invalid_grant_tax_marker")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
# Import will fail until helpers exist — TDD red then green.
|
||||
test_consent_helpers_pure()
|
||||
test_prepare_consent_allow_sets_action()
|
||||
test_consent_js_fallback_never_bare_submit_first()
|
||||
test_prepare_skips_cookie_form()
|
||||
test_wait_post_allow_state_reaches_done()
|
||||
test_oauth_hard_invalid_grant_tax_marker()
|
||||
print("ALL PASS test_mint_consent_allow")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline tests: mint invalid_grant diagnostic log markers (no DrissionPage)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
|
||||
def test_consent_diag_source_markers() -> None:
|
||||
bc = (ROOT / "cpa_xai" / "browser_confirm.py").read_text(encoding="utf-8")
|
||||
assert "def _consent_page_diag" in bc
|
||||
assert "consent_diag[" in bc
|
||||
assert "pre_js_fallback" in bc
|
||||
assert "post_real_click" in bc
|
||||
assert "post_js_fallback" in bc
|
||||
assert "btn_click:" in bc
|
||||
assert "no_allow_button" in bc # never bare f.submit (拒绝 is first submit)
|
||||
assert "skip_cookie_form" in bc
|
||||
assert "def _prepare_consent_allow_form" in bc
|
||||
assert "def _wait_post_allow_state" in bc
|
||||
assert "consent prepare action=allow" in bc
|
||||
# still prefer real click path before JS fallback
|
||||
assert '["允许", "Allow", "Authorize", "Approve"]' in bc
|
||||
assert "real=True" in bc
|
||||
od = (ROOT / "cpa_xai" / "oauth_device.py").read_text(encoding="utf-8")
|
||||
assert "oauth poll HARD" in od
|
||||
assert "safe_body" in od
|
||||
assert "tax=server_policy" in od
|
||||
# must not dump raw tokens on hard error path
|
||||
assert "access_token" in od # TokenResult path still uses it
|
||||
assert "f\"<{type(v).__name__}>\"" in od or "<" in od
|
||||
cli = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
assert "mint_egress pin verify" in cli
|
||||
assert "current_egress_label()" in cli
|
||||
print("PASS consent_diag source markers")
|
||||
|
||||
|
||||
def test_consent_page_diag_logs_without_click() -> None:
|
||||
from cpa_xai import browser_confirm as bc
|
||||
|
||||
logs: list[str] = []
|
||||
|
||||
class FakeEl:
|
||||
def __init__(self, text: str):
|
||||
self.text = text
|
||||
|
||||
class FakePage:
|
||||
url = "https://accounts.x.ai/oauth2/device/consent?user_code=ABCD"
|
||||
|
||||
def run_js(self, code: str): # noqa: ARG002
|
||||
if "document.body" in code:
|
||||
return "授权 Grok Build 允许 Allow 隐私政策"
|
||||
if "JSON.stringify" in code or "out.forms" in code:
|
||||
return (
|
||||
'{"forms":[{"actionAttr":"/oauth2/device/consent","method":"post",'
|
||||
'"actionVal":null,"text":"Authorize Grok Build 允许"}],'
|
||||
'"buttons":[{"t":"允许","type":"submit","dis":false},'
|
||||
'{"t":"取消","type":"button","dis":false}]}'
|
||||
)
|
||||
return ""
|
||||
|
||||
def eles(self, sel: str): # noqa: ARG002
|
||||
return [FakeEl("允许"), FakeEl("取消")]
|
||||
|
||||
def ele(self, *a, **k): # noqa: ARG002
|
||||
return None
|
||||
|
||||
with mock.patch.object(bc, "_cookie_banner_visible", return_value=False):
|
||||
bc._consent_page_diag(FakePage(), logs.append, "enter")
|
||||
joined = "\n".join(logs)
|
||||
assert "consent_diag[enter]" in joined
|
||||
assert "exact_btns=" in joined
|
||||
assert "允许" in joined
|
||||
assert "dom=" in joined
|
||||
# diagnostic must not claim it clicked
|
||||
assert "clicked" not in joined.lower()
|
||||
print("PASS consent_page_diag logs without click")
|
||||
|
||||
|
||||
def test_oauth_hard_error_logs_safe_body() -> None:
|
||||
"""poll_device_token hard path logs status/err without raising tokens."""
|
||||
src = (ROOT / "cpa_xai" / "oauth_device.py").read_text(encoding="utf-8")
|
||||
tree = ast.parse(src)
|
||||
fn = next(
|
||||
n
|
||||
for n in tree.body
|
||||
if isinstance(n, ast.FunctionDef) and n.name == "poll_device_token"
|
||||
)
|
||||
# Ensure hard log exists in function body text
|
||||
chunk = ast.get_source_segment(src, fn) or ""
|
||||
assert "oauth poll HARD" in chunk
|
||||
assert "safe_body" in chunk
|
||||
# Redact logic present
|
||||
assert "token" in chunk.lower()
|
||||
print("PASS oauth hard error safe_body markers")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
test_consent_diag_source_markers()
|
||||
test_consent_page_diag_logs_without_click()
|
||||
test_oauth_hard_error_logs_safe_body()
|
||||
print("ALL PASS test_mint_consent_diag")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Mint egress hold: keep clash leaf pinned to registration node during mint."""
|
||||
from __future__ import annotations
|
||||
|
||||
import proxy_rotate as pr
|
||||
|
||||
|
||||
class _FakeRotatorAPI:
|
||||
"""Minimal stubs for clash_list_nodes / clash_switch_node via monkeypatch."""
|
||||
|
||||
def __init__(self, nodes: list[str], now: str) -> None:
|
||||
self.nodes = list(nodes)
|
||||
self.now = now
|
||||
self.switches: list[str] = []
|
||||
|
||||
def list_nodes(self, *a, **k):
|
||||
return list(self.nodes), self.now, {}
|
||||
|
||||
def switch(self, api, group, node, **k):
|
||||
self.switches.append(node)
|
||||
self.now = node
|
||||
|
||||
|
||||
def test_acquire_release_blocks_rotate(monkeypatch) -> None:
|
||||
fake = _FakeRotatorAPI(
|
||||
["node-A", "node-B", "node-C"],
|
||||
now="node-A",
|
||||
)
|
||||
rot = pr.ProxyRotator()
|
||||
rot.mode = "clash"
|
||||
rot.clash_setup_done = True
|
||||
rot.clash_group = "🎯Grok注册"
|
||||
rot.clash_flush = False
|
||||
rot.current_label = "node-A"
|
||||
rot._started = True
|
||||
rot.accounts_on_current = 1
|
||||
|
||||
monkeypatch.setattr(pr, "clash_list_nodes", fake.list_nodes)
|
||||
monkeypatch.setattr(pr, "clash_switch_node", fake.switch)
|
||||
|
||||
hold = rot.acquire_mint_egress("node-A")
|
||||
assert hold.get("ok") is True
|
||||
assert hold.get("holds", {}).get("node-A") == 1
|
||||
|
||||
# force rotate must stay on held leaf
|
||||
r = rot.maybe_rotate(force=True)
|
||||
assert r.get("reason") == "mint_hold"
|
||||
assert r.get("node") == "node-A"
|
||||
assert fake.switches == [] # already on A
|
||||
|
||||
rel = rot.release_mint_egress("node-A")
|
||||
assert rel.get("holds") == {}
|
||||
|
||||
# after release, force rotate advances
|
||||
r2 = rot.maybe_rotate(force=True)
|
||||
assert r2.get("rotated") is True
|
||||
assert r2.get("node") in {"node-B", "node-C"}
|
||||
assert fake.now == r2.get("node")
|
||||
|
||||
|
||||
def test_acquire_switches_to_reg_leaf(monkeypatch) -> None:
|
||||
fake = _FakeRotatorAPI(["node-A", "node-B"], now="node-B")
|
||||
rot = pr.ProxyRotator()
|
||||
rot.mode = "clash"
|
||||
rot.clash_setup_done = True
|
||||
rot.clash_group = "🎯Grok注册"
|
||||
rot.clash_flush = False
|
||||
rot.current_label = "node-B"
|
||||
|
||||
monkeypatch.setattr(pr, "clash_list_nodes", fake.list_nodes)
|
||||
monkeypatch.setattr(pr, "clash_switch_node", fake.switch)
|
||||
|
||||
hold = rot.acquire_mint_egress("node-A")
|
||||
assert hold.get("ok") is True
|
||||
assert hold.get("pinned") is True
|
||||
assert fake.switches == ["node-A"]
|
||||
assert rot.current_label == "node-A"
|
||||
assert fake.now == "node-A"
|
||||
|
||||
rot.release_mint_egress("node-A")
|
||||
|
||||
|
||||
def test_refcount_multi_hold(monkeypatch) -> None:
|
||||
fake = _FakeRotatorAPI(["node-A", "node-B"], now="node-A")
|
||||
rot = pr.ProxyRotator()
|
||||
rot.mode = "clash"
|
||||
rot.clash_setup_done = True
|
||||
rot.clash_group = "G"
|
||||
rot.clash_flush = False
|
||||
|
||||
monkeypatch.setattr(pr, "clash_list_nodes", fake.list_nodes)
|
||||
monkeypatch.setattr(pr, "clash_switch_node", fake.switch)
|
||||
|
||||
rot.acquire_mint_egress("node-A")
|
||||
rot.acquire_mint_egress("node-A")
|
||||
assert rot.status()["mint_holds"]["node-A"] == 2
|
||||
rot.release_mint_egress("node-A")
|
||||
assert rot.status()["mint_holds"]["node-A"] == 1
|
||||
r = rot.maybe_rotate(force=True)
|
||||
assert r.get("reason") == "mint_hold"
|
||||
rot.release_mint_egress("node-A")
|
||||
assert rot.status()["mint_holds"] == {}
|
||||
|
||||
|
||||
def test_mode_list_is_noop() -> None:
|
||||
rot = pr.ProxyRotator()
|
||||
rot.mode = "list"
|
||||
hold = rot.acquire_mint_egress("http://1.2.3.4:8080")
|
||||
assert hold.get("ok") is True
|
||||
assert hold.get("pinned") is False
|
||||
assert hold.get("reason") == "mode_not_clash"
|
||||
@@ -0,0 +1,360 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Gates for mint-stability milestone: flock, device stall taxonomy, xvfb cleanup, smoke script."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SMOKE = ROOT / "scripts" / "smoke_diskfirst_one.sh"
|
||||
|
||||
|
||||
class TestSmokeDiskfirstScript(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.assertTrue(SMOKE.is_file(), f"missing {SMOKE}")
|
||||
self.src = SMOKE.read_text(encoding="utf-8")
|
||||
|
||||
def test_disk_first_env_frozen(self) -> None:
|
||||
self.assertIn("CPA_EXPORT_ENABLED=true", self.src)
|
||||
self.assertIn("CPA_PROBE_CHAT=false", self.src)
|
||||
self.assertIn("CPA_REMOTE_INJECT=false", self.src)
|
||||
self.assertIn("flock", self.src)
|
||||
self.assertIn("register_cli.py", self.src)
|
||||
self.assertIn("complete", self.src.lower())
|
||||
self.assertIn("refresh", self.src.lower())
|
||||
self.assertIn("not chat_ok", self.src)
|
||||
|
||||
def test_single_instance_lock(self) -> None:
|
||||
self.assertIn("grok_smoke_diskfirst.lock", self.src)
|
||||
self.assertIn("flock -n", self.src)
|
||||
|
||||
|
||||
class TestRegisterCliLock(unittest.TestCase):
|
||||
def test_acquire_and_block_second_process(self) -> None:
|
||||
"""flock is process-scoped; verify a child process is denied while held."""
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
import register_cli as rc
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
lock = str(Path(td) / "cli.lock")
|
||||
rc._release_cli_lock()
|
||||
ok1, msg1 = rc.acquire_register_cli_lock(lock_path=lock, skip=False)
|
||||
self.assertTrue(ok1, msg1)
|
||||
self.assertIn("acquired", msg1)
|
||||
# Child process must fail non-blocking exclusive lock.
|
||||
child = subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
"-c",
|
||||
(
|
||||
"import fcntl, os, sys\n"
|
||||
f"p={lock!r}\n"
|
||||
"fd=os.open(p, os.O_RDWR|os.O_CREAT, 0o644)\n"
|
||||
"try:\n"
|
||||
" fcntl.flock(fd, fcntl.LOCK_EX|fcntl.LOCK_NB)\n"
|
||||
"except BlockingIOError:\n"
|
||||
" sys.exit(2)\n"
|
||||
"else:\n"
|
||||
" sys.exit(0)\n"
|
||||
),
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10,
|
||||
)
|
||||
self.assertEqual(child.returncode, 2, child.stdout + child.stderr)
|
||||
rc._release_cli_lock()
|
||||
ok3, msg3 = rc.acquire_register_cli_lock(lock_path=lock, skip=False)
|
||||
self.assertTrue(ok3, msg3)
|
||||
rc._release_cli_lock()
|
||||
|
||||
def test_skip_env(self) -> None:
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
import register_cli as rc
|
||||
|
||||
rc._release_cli_lock()
|
||||
ok, msg = rc.acquire_register_cli_lock(skip=True)
|
||||
self.assertTrue(ok)
|
||||
self.assertIn("skipped", msg)
|
||||
|
||||
def test_classify_mint_fail(self) -> None:
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
import register_cli as rc
|
||||
|
||||
r, p = rc._classify_mint_fail(
|
||||
{"error": "device_click_stall phase=device clicks=6 stall_sec=30.0"}
|
||||
)
|
||||
self.assertEqual(r, "device_click_stall")
|
||||
self.assertEqual(p, "device")
|
||||
|
||||
r, p = rc._classify_mint_fail(
|
||||
{"error": "browser confirm timeout phase=device login_attempts=0"}
|
||||
)
|
||||
self.assertEqual(r, "browser_timeout")
|
||||
self.assertEqual(p, "device")
|
||||
|
||||
r, p = rc._classify_mint_fail(
|
||||
{"mint_fail_reason": "auth_failed", "mint_fail_phase": "password"}
|
||||
)
|
||||
self.assertEqual(r, "auth_failed")
|
||||
self.assertEqual(p, "password")
|
||||
|
||||
|
||||
class TestMintFailTaxonomy(unittest.TestCase):
|
||||
def test_classify_browser_mint_error(self) -> None:
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from cpa_xai.mint import classify_browser_mint_error
|
||||
|
||||
r, p = classify_browser_mint_error(
|
||||
"device_click_stall phase=device clicks=6 stall_sec=22.1 budget=45"
|
||||
)
|
||||
self.assertEqual(r, "device_click_stall")
|
||||
self.assertEqual(p, "device")
|
||||
|
||||
r, p = classify_browser_mint_error(
|
||||
"browser confirm timeout phase=consent login_attempts=0"
|
||||
)
|
||||
self.assertEqual(r, "browser_timeout")
|
||||
self.assertEqual(p, "consent")
|
||||
|
||||
r, p = classify_browser_mint_error("auth failed: turnstile stuck")
|
||||
self.assertEqual(r, "auth_failed")
|
||||
|
||||
r, p = classify_browser_mint_error("The browser connection fails")
|
||||
self.assertEqual(r, "browser_boot")
|
||||
|
||||
r, p = classify_browser_mint_error("cancelled")
|
||||
self.assertEqual(r, "cancelled")
|
||||
|
||||
|
||||
class TestDeviceClickStallSource(unittest.TestCase):
|
||||
def test_approve_device_code_has_early_abort(self) -> None:
|
||||
src = (ROOT / "cpa_xai" / "browser_confirm.py").read_text(encoding="utf-8")
|
||||
self.assertIn("device_click_stall", src)
|
||||
self.assertIn("device_stall_budget_sec", src)
|
||||
self.assertIn("device_stall_click_limit", src)
|
||||
|
||||
|
||||
class TestXvfbCleanup(unittest.TestCase):
|
||||
def test_is_xvfb_cmdline(self) -> None:
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from tab_pool import is_xvfb_cmdline, parse_ps_xvfb_rows
|
||||
|
||||
self.assertTrue(is_xvfb_cmdline("Xvfb :99 -screen 0 1280x900x24"))
|
||||
self.assertTrue(is_xvfb_cmdline("/usr/bin/Xvfb :100 -ac"))
|
||||
self.assertFalse(is_xvfb_cmdline("xvfb-run -a python register_cli.py"))
|
||||
self.assertFalse(is_xvfb_cmdline("/usr/bin/Xorg :0"))
|
||||
|
||||
ps = """
|
||||
111 1 /usr/bin/Xvfb :99 -screen 0 1280x900x24
|
||||
222 50 /usr/bin/Xvfb :100 -ac
|
||||
333 1 xvfb-run -a python x
|
||||
444 1 /usr/bin/chrome --remote-debugging-port=1
|
||||
"""
|
||||
rows = parse_ps_xvfb_rows(ps)
|
||||
pids = {r[0] for r in rows}
|
||||
self.assertEqual(pids, {111, 222})
|
||||
|
||||
def test_cleanup_orphan_xvfb_dry_run(self) -> None:
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from tab_pool import cleanup_orphan_xvfb
|
||||
|
||||
logs: list[str] = []
|
||||
res = cleanup_orphan_xvfb(
|
||||
log_callback=logs.append,
|
||||
only_ppid_init=True,
|
||||
require_no_children=True,
|
||||
dry_run=True,
|
||||
clean_tmp_dirs=False,
|
||||
)
|
||||
self.assertIn("scanned", res)
|
||||
self.assertIn("matched", res)
|
||||
self.assertTrue(res.get("dry_run"))
|
||||
self.assertIsInstance(res.get("pids"), list)
|
||||
|
||||
def test_register_cli_hooks_xvfb_cleanup(self) -> None:
|
||||
src = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
self.assertIn("cleanup_orphan_xvfb", src)
|
||||
self.assertIn("acquire_register_cli_lock", src)
|
||||
self.assertIn("mint_fail_reason", src)
|
||||
|
||||
|
||||
class TestServerPolicyFastFail(unittest.TestCase):
|
||||
"""mint fast-fail: server-policy token denial must skip browser residual."""
|
||||
|
||||
def test_is_server_policy_error(self) -> None:
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from cpa_xai.mint import _is_server_policy_error
|
||||
|
||||
# server-policy matches
|
||||
self.assertTrue(
|
||||
_is_server_policy_error(
|
||||
"device auth token error: invalid_grant: Access denied [tax=server_policy]"
|
||||
)
|
||||
)
|
||||
self.assertTrue(
|
||||
_is_server_policy_error(
|
||||
"token poll: device auth token error: invalid_grant: server_policy deny"
|
||||
)
|
||||
)
|
||||
self.assertTrue(
|
||||
_is_server_policy_error("something with tax=server_policy")
|
||||
)
|
||||
# non-matches
|
||||
self.assertFalse(_is_server_policy_error("browser confirm timeout phase=device"))
|
||||
self.assertFalse(_is_server_policy_error("device_click_stall"))
|
||||
self.assertFalse(_is_server_policy_error(""))
|
||||
self.assertFalse(_is_server_policy_error(None))
|
||||
|
||||
def test_mint_skip_browser_on_server_policy(self) -> None:
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from unittest import mock
|
||||
|
||||
from cpa_xai.mint import mint_and_export
|
||||
from cpa_xai.pkce_mint import PKCEMintError
|
||||
from cpa_xai.protocol_mint import ProtocolMintError
|
||||
|
||||
auth_dir = tempfile.mkdtemp(prefix="mint_test_")
|
||||
browser_mock = mock.MagicMock()
|
||||
|
||||
pkce_err = "consent: empty SPA shell"
|
||||
device_err = (
|
||||
"device auth token error: invalid_grant: Access denied [tax=server_policy]"
|
||||
)
|
||||
|
||||
with mock.patch.multiple(
|
||||
"cpa_xai.mint",
|
||||
mint_with_sso_pkce=mock.MagicMock(side_effect=PKCEMintError(pkce_err, retryable=False)),
|
||||
mint_with_sso_protocol=mock.MagicMock(
|
||||
side_effect=ProtocolMintError(device_err)
|
||||
),
|
||||
mint_with_browser=browser_mock,
|
||||
):
|
||||
result = mint_and_export(
|
||||
email="test@example.com",
|
||||
password="dummy",
|
||||
auth_dir=auth_dir,
|
||||
sso="valid_sso_token",
|
||||
prefer_protocol=True,
|
||||
allow_device_flow_fallback=True,
|
||||
protocol_flow="pkce",
|
||||
)
|
||||
|
||||
self.assertIs(result.get("ok"), False)
|
||||
self.assertIn("invalid_grant", str(result.get("protocol_error") or ""))
|
||||
self.assertIn("server_policy", str(result.get("error") or ""))
|
||||
# browser must NOT be called — fast-fail skips the 240s dead-end
|
||||
browser_mock.assert_not_called()
|
||||
|
||||
|
||||
class TestConsentDeadEndFastFail(unittest.TestCase):
|
||||
"""mint fast-fail: broken x.ai consent page (HTTP 404) must skip browser residual."""
|
||||
|
||||
def test_is_consent_dead_end_error(self) -> None:
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from cpa_xai.mint import _is_consent_dead_end_error
|
||||
from cpa_xai.pkce_mint import PKCEMintError
|
||||
|
||||
# structured code → match
|
||||
self.assertTrue(
|
||||
_is_consent_dead_end_error(
|
||||
PKCEMintError("submit failed", code="consent_action_missing", retryable=False)
|
||||
)
|
||||
)
|
||||
self.assertTrue(
|
||||
_is_consent_dead_end_error(
|
||||
PKCEMintError("submit failed", code="consent_action_rejected", retryable=False)
|
||||
)
|
||||
)
|
||||
# string needles (protocol_err is stringified before fast-fail block)
|
||||
self.assertTrue(
|
||||
_is_consent_dead_end_error(
|
||||
"submitOAuth2Consent failed HTTP 404: Server action not found "
|
||||
"(consent HTML missing submitOAuth2Consent action id; "
|
||||
"stale hardcoded fallback rejected by Next.js)"
|
||||
)
|
||||
)
|
||||
self.assertTrue(_is_consent_dead_end_error("no submitOAuth2Consent action_id in consent html"))
|
||||
# non-matches: empty_sso / cancelled / server-policy / unrelated
|
||||
self.assertFalse(_is_consent_dead_end_error(PKCEMintError("no sso", code="empty_sso")))
|
||||
self.assertFalse(_is_consent_dead_end_error(PKCEMintError("abort", code="cancelled")))
|
||||
self.assertFalse(
|
||||
_is_consent_dead_end_error(
|
||||
"device auth token error: invalid_grant: Access denied [tax=server_policy]"
|
||||
)
|
||||
)
|
||||
self.assertFalse(_is_consent_dead_end_error(""))
|
||||
self.assertFalse(_is_consent_dead_end_error(None))
|
||||
|
||||
def test_mint_skip_browser_on_consent_dead_end(self) -> None:
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from unittest import mock
|
||||
|
||||
from cpa_xai.mint import mint_and_export
|
||||
from cpa_xai.pkce_mint import PKCEMintError
|
||||
|
||||
auth_dir = tempfile.mkdtemp(prefix="mint_test_")
|
||||
browser_mock = mock.MagicMock()
|
||||
|
||||
consent_err = (
|
||||
"submitOAuth2Consent failed HTTP 404: Server action not found "
|
||||
"(consent HTML missing submitOAuth2Consent action id; "
|
||||
"stale hardcoded fallback rejected by Next.js)"
|
||||
)
|
||||
|
||||
with mock.patch.multiple(
|
||||
"cpa_xai.mint",
|
||||
mint_with_sso_pkce=mock.MagicMock(
|
||||
side_effect=PKCEMintError(
|
||||
consent_err, code="consent_action_missing", retryable=False
|
||||
)
|
||||
),
|
||||
mint_with_browser=browser_mock,
|
||||
):
|
||||
result = mint_and_export(
|
||||
email="test@example.com",
|
||||
password="dummy",
|
||||
auth_dir=auth_dir,
|
||||
sso="valid_sso_token",
|
||||
prefer_protocol=True,
|
||||
allow_device_flow_fallback=False, # pxed config: no device residual
|
||||
protocol_flow="pkce",
|
||||
)
|
||||
|
||||
self.assertIs(result.get("ok"), False)
|
||||
# protocol_error carries the stringified PKCE error (message, not code)
|
||||
self.assertIn("submitOAuth2Consent", str(result.get("protocol_error") or ""))
|
||||
self.assertIn("consent_dead_end", str(result.get("error") or ""))
|
||||
# browser must NOT be called — fast-fail skips the broken-consent dead-end
|
||||
browser_mock.assert_not_called()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,185 @@
|
||||
"""Unit tests for node_score dynamic egress weight."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import random
|
||||
from pathlib import Path
|
||||
|
||||
import node_score as ns
|
||||
|
||||
|
||||
def setup_function() -> None:
|
||||
ns.reset_cache()
|
||||
os.environ.pop("NODE_SCORE", None)
|
||||
os.environ.pop("NODE_SCORE_ENABLED", None)
|
||||
os.environ.pop("NODE_SCORE_PATH", None)
|
||||
os.environ.pop("EMAIL_IP_CORRELATION", None)
|
||||
ns.set_enabled(None) # type: ignore[arg-type]
|
||||
ns.set_correlation_enabled(None) # type: ignore[arg-type]
|
||||
|
||||
|
||||
def teardown_function() -> None:
|
||||
# Prevent NODE_SCORE_PATH / NODE_SCORE leaking into later modules in the suite.
|
||||
ns.reset_cache()
|
||||
os.environ.pop("NODE_SCORE", None)
|
||||
os.environ.pop("NODE_SCORE_ENABLED", None)
|
||||
os.environ.pop("NODE_SCORE_PATH", None)
|
||||
os.environ.pop("EMAIL_IP_CORRELATION", None)
|
||||
ns.set_enabled(None) # type: ignore[arg-type]
|
||||
ns.set_correlation_enabled(None) # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_default_off() -> None:
|
||||
ns.reset_cache()
|
||||
os.environ.pop("NODE_SCORE", None)
|
||||
assert ns.scoring_enabled() is False
|
||||
# pick falls back to round-robin
|
||||
nodes = ["A", "B", "C"]
|
||||
assert ns.pick_next(nodes, "A") == "B"
|
||||
print("PASS default off")
|
||||
|
||||
|
||||
def test_env_on_off(tmp_path: Path) -> None:
|
||||
ns.reset_cache()
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "scores.json")
|
||||
os.environ["NODE_SCORE"] = "1"
|
||||
assert ns.scoring_enabled() is True
|
||||
os.environ["NODE_SCORE"] = "0"
|
||||
ns.reset_cache()
|
||||
assert ns.scoring_enabled() is False
|
||||
os.environ["NODE_SCORE"] = "true"
|
||||
ns.reset_cache()
|
||||
assert ns.scoring_enabled() is True
|
||||
print("PASS env on/off")
|
||||
|
||||
|
||||
def test_config_key(tmp_path: Path) -> None:
|
||||
ns.reset_cache()
|
||||
os.environ.pop("NODE_SCORE", None)
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
assert ns.scoring_enabled({"node_score_enabled": True}) is True
|
||||
assert ns.scoring_enabled({"node_score_enabled": False}) is False
|
||||
# env wins over config
|
||||
os.environ["NODE_SCORE"] = "0"
|
||||
assert ns.scoring_enabled({"node_score_enabled": True}) is False
|
||||
print("PASS config + env precedence")
|
||||
|
||||
|
||||
def test_turnstile_cool_and_pick(tmp_path: Path) -> None:
|
||||
ns.reset_cache()
|
||||
path = tmp_path / "scores.json"
|
||||
os.environ["NODE_SCORE"] = "1"
|
||||
os.environ["NODE_SCORE_PATH"] = str(path)
|
||||
nodes = ["GOOD", "BAD", "MID"]
|
||||
# equal scores → round-robin
|
||||
assert ns.pick_next(nodes, "GOOD") == "BAD"
|
||||
ns.record("BAD", "turnstile", cfg=None)
|
||||
assert ns.is_cooled("BAD") is True
|
||||
# BAD cooled → next pick from GOOD/MID, not BAD
|
||||
for _ in range(20):
|
||||
n = ns.pick_next(nodes, "GOOD", rng=random.Random(0))
|
||||
assert n != "BAD", n
|
||||
# mint boost GOOD
|
||||
ns.record("GOOD", "mint_ok")
|
||||
assert ns.get_score("GOOD") > ns.DEFAULT_SCORE
|
||||
# persistence
|
||||
ns.reset_cache()
|
||||
os.environ["NODE_SCORE"] = "1"
|
||||
os.environ["NODE_SCORE_PATH"] = str(path)
|
||||
assert ns.is_cooled("BAD") is True
|
||||
assert ns.get_score("GOOD") > ns.DEFAULT_SCORE
|
||||
print("PASS turnstile cool + persist")
|
||||
|
||||
|
||||
def test_record_disabled_noop(tmp_path: Path) -> None:
|
||||
ns.reset_cache()
|
||||
os.environ["NODE_SCORE"] = "0"
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "x.json")
|
||||
out = ns.record("N1", "turnstile")
|
||||
assert out.get("ok") is False
|
||||
assert not (tmp_path / "x.json").exists()
|
||||
print("PASS disabled record noop")
|
||||
|
||||
|
||||
def test_all_cooled_fallback(tmp_path: Path) -> None:
|
||||
ns.reset_cache()
|
||||
os.environ["NODE_SCORE"] = "1"
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "all.json")
|
||||
nodes = ["A", "B"]
|
||||
ns.record("A", "turnstile")
|
||||
ns.record("B", "turnstile")
|
||||
# must still return a node (pool never empty)
|
||||
n = ns.pick_next(nodes, "A")
|
||||
assert n in nodes
|
||||
print("PASS all cooled fallback")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# §5.F — IP scoring non-regression: correlation must not touch the IP path.
|
||||
# Constants, record deltas/cooldowns, and the empty store shape are frozen.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_ip_constants_unchanged() -> None:
|
||||
"""§5.F: the IP-side scoring constants that correlation must not touch."""
|
||||
assert ns.DEFAULT_SCORE == 50
|
||||
assert ns.MIN_SCORE == 0 and ns.MAX_SCORE == 100
|
||||
assert ns.SUCCESS_REG == 3 and ns.SUCCESS_MINT == 5
|
||||
assert ns.PENALTY_TURNSTILE == 15
|
||||
assert ns.PENALTY_BOOT == 3 and ns.PENALTY_OTHER == 2
|
||||
assert ns.COOL_TURNSTILE_S == 20 * 60
|
||||
assert ns.COOL_BOOT_S == 5 * 60
|
||||
assert ns.COOL_OTHER_S == 2 * 60
|
||||
|
||||
|
||||
def test_ip_record_turnstile_delta_and_cool_unchanged(tmp_path: Path) -> None:
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "ip.json")
|
||||
ns.set_enabled(True)
|
||||
out = ns.record("n1", "turnstile", cfg={})
|
||||
assert out["delta"] == -15
|
||||
assert out["score"] == 50 - 15
|
||||
assert out["cool_until"] > 0
|
||||
|
||||
|
||||
def test_ip_empty_store_still_version1_nodes_only() -> None:
|
||||
s = ns._empty_store()
|
||||
assert s == {"version": 1, "nodes": {}}
|
||||
assert "domains" not in s and "pairs" not in s
|
||||
|
||||
|
||||
def test_ip_record_disabled_when_correlation_only(tmp_path: Path) -> None:
|
||||
"""NODE_SCORE off but EMAIL_IP on: IP record still no-op (independent switches)."""
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "ip2.json")
|
||||
ns.set_enabled(None) # NODE_SCORE default off
|
||||
ns.set_correlation_enabled(True) # correlation on
|
||||
out = ns.record("n1", "turnstile", cfg={})
|
||||
assert out["ok"] is False
|
||||
assert ns.record_domain("a.com", "turnstile", cfg={})["ok"] is True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from pathlib import Path as P
|
||||
import tempfile
|
||||
|
||||
setup_function()
|
||||
test_default_off()
|
||||
with tempfile.TemporaryDirectory() as d:
|
||||
setup_function()
|
||||
test_env_on_off(P(d))
|
||||
setup_function()
|
||||
test_config_key(P(d))
|
||||
setup_function()
|
||||
test_turnstile_cool_and_pick(P(d))
|
||||
setup_function()
|
||||
test_record_disabled_noop(P(d))
|
||||
setup_function()
|
||||
test_all_cooled_fallback(P(d))
|
||||
setup_function()
|
||||
test_ip_constants_unchanged()
|
||||
setup_function()
|
||||
test_ip_record_turnstile_delta_and_cool_unchanged(P(d))
|
||||
setup_function()
|
||||
test_ip_empty_store_still_version1_nodes_only()
|
||||
setup_function()
|
||||
test_ip_record_disabled_when_correlation_only(P(d))
|
||||
print("ALL OK")
|
||||
@@ -0,0 +1,120 @@
|
||||
"""§5.E — node_score correlation error handling.
|
||||
|
||||
Store corruption and persist failure must degrade silently to neutral defaults
|
||||
and never break registration. These are the spec's error-isolation guards.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
import node_score as ns
|
||||
|
||||
|
||||
def _reset():
|
||||
for k in ("EMAIL_IP_CORRELATION", "NODE_SCORE", "NODE_SCORE_ENABLED",
|
||||
"NODE_SCORE_PATH"):
|
||||
os.environ.pop(k, None)
|
||||
ns.reset_cache()
|
||||
ns.set_enabled(None)
|
||||
ns.set_correlation_enabled(None)
|
||||
|
||||
|
||||
def setup_function(_):
|
||||
_reset()
|
||||
|
||||
|
||||
def teardown_function(_):
|
||||
_reset()
|
||||
|
||||
|
||||
def test_corrupt_json_degrades_to_empty(tmp_path):
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "corrupt.json")
|
||||
(tmp_path / "corrupt.json").write_text("{not valid json", encoding="utf-8")
|
||||
ns.set_correlation_enabled(True)
|
||||
# reads degrade to defaults; a write repairs the file
|
||||
assert ns.get_domain_score("a.com") == ns.DEFAULT_SCORE
|
||||
assert ns.get_pair("a.com", "n1") == {}
|
||||
out = ns.record_domain("a.com", "reg_ok", cfg={})
|
||||
assert out["ok"] is True
|
||||
data = json.loads((tmp_path / "corrupt.json").read_text(encoding="utf-8"))
|
||||
assert "domains" in data and "a.com" in data["domains"]
|
||||
|
||||
|
||||
def test_corrupt_domains_key_isolated_from_nodes(tmp_path):
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "m.json")
|
||||
(tmp_path / "m.json").write_text(json.dumps({
|
||||
"version": 1, "nodes": {"x": {"score": 77}}, "domains": 42,
|
||||
"pairs": "nope"}), encoding="utf-8")
|
||||
ns.set_correlation_enabled(True)
|
||||
assert ns.get_domain_score("a.com") == ns.DEFAULT_SCORE # bad domains ignored
|
||||
assert ns.get_pair("a.com", "n1") == {} # bad pairs ignored
|
||||
assert ns.get_score("x") == 77 # IP reads still work
|
||||
ns.record_domain("a.com", "reg_ok", cfg={}) # repairs domains key in place
|
||||
data = json.loads((tmp_path / "m.json").read_text(encoding="utf-8"))
|
||||
# IP untouched: the x entry survives with its score unchanged. _save
|
||||
# re-normalizes every node entry via _get_store's setdefault defaults (see
|
||||
# node_score._get/_ensure_node_entry — it fills cool_until/ok/fail_ts/etc,
|
||||
# so the field set grows but the score does not), so assert only the
|
||||
# invariant correlation must hold: score == 77 and exactly one IP node.
|
||||
assert set(data["nodes"]) == {"x"}
|
||||
assert data["nodes"]["x"]["score"] == 77
|
||||
assert "a.com" in data["domains"]
|
||||
|
||||
|
||||
def test_record_writes_survive_error_path(tmp_path):
|
||||
"""Spec §4: write failure must never break registration. _save swallows.
|
||||
|
||||
Pointing NODE_SCORE_PATH inside a FILE (so path.parent is a file, not a
|
||||
directory) makes the persist raise; node_score._save catches Exception and
|
||||
swallows (see node_score._save except branch), so record_domain still
|
||||
returns ok=True — registration never sees the failure.
|
||||
"""
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "blocker" / "x.json")
|
||||
(tmp_path / "blocker").write_text("x", encoding="utf-8") # blocker is a file
|
||||
ns.set_correlation_enabled(True)
|
||||
out = ns.record_domain("a.com", "turnstile", cfg={})
|
||||
# _save swallows -> the call returns ok=True despite the failed persist
|
||||
assert out["ok"] is True
|
||||
assert not (tmp_path / "blocker" / "x.json").exists()
|
||||
|
||||
|
||||
def test_concurrent_record_no_score_loss(tmp_path):
|
||||
"""Regression: _save used a fixed `scores.json.tmp` name with no lock. Two
|
||||
record() calls on different nodes racing through _save would open the SAME
|
||||
tmp and one would overwrite the other's bytes mid-write — losing a node's
|
||||
score delta. Now _save takes _lock and the tmp name carries pid+tid, so
|
||||
concurrent records each land their own delta."""
|
||||
import threading
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
ns.set_correlation_enabled(True)
|
||||
ns.reset_cache()
|
||||
threads = []
|
||||
errors = []
|
||||
|
||||
def _hit(node):
|
||||
for _ in range(60):
|
||||
try:
|
||||
ns.record_domain(f"{node}.com", "turnstile", cfg={})
|
||||
except Exception as e: # noqa: BLE001
|
||||
errors.append(e)
|
||||
|
||||
for i in range(8):
|
||||
threads.append(threading.Thread(target=_hit, args=(f"node{i}",)))
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
assert not errors, f"record raised: {errors[:3]}"
|
||||
store = ns._load(tmp_path / "s.json")
|
||||
# record_domain stores under store["domains"]; all 8 entries present + counted
|
||||
domains = store.get("domains", {})
|
||||
assert set(domains) == {f"node{i}.com" for i in range(8)}, f"missing: {set(domains)}"
|
||||
# each recorded turnstile 60x -> fail_ts counted
|
||||
for d in domains.values():
|
||||
assert int(d.get("fail_ts") or 0) == 60, d
|
||||
# no tmp leftovers from the old fixed-name path
|
||||
leftovers = list(tmp_path.glob("s.json.tmp.*"))
|
||||
assert not leftovers, f"stray tmp: {leftovers}"
|
||||
@@ -0,0 +1,235 @@
|
||||
"""Unit tests: lightweight node profile convert/validate (no network, no core)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
from register_core.nodes.convert.parsers import detect_format, parse_text, ParseError
|
||||
from register_core.nodes.convert.pipeline import convert_text, pack_result
|
||||
from register_core.nodes.convert.uri import parse_uri
|
||||
from register_core.nodes.convert.validate import validate_proxy
|
||||
|
||||
|
||||
class TestDetectFormat(unittest.TestCase):
|
||||
def test_clash_yaml(self):
|
||||
text = "proxies:\n - name: a\n type: http\n server: 1.1.1.1\n port: 80\n"
|
||||
self.assertEqual(detect_format(text, filename="x.yaml"), "clash_yaml")
|
||||
|
||||
def test_uri_list(self):
|
||||
self.assertEqual(detect_format("socks5://1.2.3.4:1080\n"), "uri_list")
|
||||
|
||||
def test_v2ray_json(self):
|
||||
text = json.dumps({"outbounds": [{"protocol": "freedom"}]})
|
||||
self.assertEqual(detect_format(text, filename="c.json"), "v2ray_json")
|
||||
|
||||
|
||||
class TestValidate(unittest.TestCase):
|
||||
def test_http_ok(self):
|
||||
issues = validate_proxy(
|
||||
{"name": "n1", "type": "http", "server": "1.2.3.4", "port": 8080}
|
||||
)
|
||||
self.assertEqual([i for i in issues if i.level == "error"], [])
|
||||
|
||||
def test_missing_fields(self):
|
||||
issues = validate_proxy({"name": "x", "type": "vless"})
|
||||
codes = {i.code for i in issues if i.level == "error"}
|
||||
self.assertIn("missing_server", codes)
|
||||
self.assertIn("missing_port", codes)
|
||||
self.assertIn("missing_uuid", codes)
|
||||
|
||||
def test_bad_port(self):
|
||||
issues = validate_proxy(
|
||||
{"name": "n", "type": "http", "server": "1.1.1.1", "port": 99999}
|
||||
)
|
||||
self.assertTrue(any(i.code == "bad_port" for i in issues))
|
||||
|
||||
|
||||
class TestUri(unittest.TestCase):
|
||||
def test_socks(self):
|
||||
p = parse_uri("socks5://user:pass@10.0.0.1:1080#lab")
|
||||
assert p is not None
|
||||
self.assertEqual(p["type"], "socks5")
|
||||
self.assertEqual(p["server"], "10.0.0.1")
|
||||
self.assertEqual(p["port"], 1080)
|
||||
self.assertEqual(p["username"], "user")
|
||||
self.assertEqual(p["name"], "lab")
|
||||
|
||||
def test_ss(self):
|
||||
# method:password@host:port
|
||||
p = parse_uri("ss://aes-256-gcm:secret@1.2.3.4:8388#ss1")
|
||||
assert p is not None
|
||||
self.assertEqual(p["type"], "ss")
|
||||
self.assertEqual(p["cipher"], "aes-256-gcm")
|
||||
self.assertEqual(p["password"], "secret")
|
||||
|
||||
def test_trojan(self):
|
||||
p = parse_uri("trojan://pwd@example.com:443?sni=example.com#tj")
|
||||
assert p is not None
|
||||
self.assertEqual(p["type"], "trojan")
|
||||
self.assertEqual(p["password"], "pwd")
|
||||
self.assertEqual(p["sni"], "example.com")
|
||||
|
||||
|
||||
class TestPipeline(unittest.TestCase):
|
||||
def test_convert_http_only_no_core(self):
|
||||
text = """
|
||||
proxies:
|
||||
- name: h1
|
||||
type: http
|
||||
server: 1.2.3.4
|
||||
port: 8080
|
||||
- name: bad
|
||||
type: vless
|
||||
server: 1.1.1.1
|
||||
"""
|
||||
r = convert_text(text, source="t.yaml")
|
||||
self.assertTrue(r.ok)
|
||||
self.assertEqual(len(r.dialable), 1)
|
||||
# bad vless missing uuid → rejected
|
||||
self.assertEqual(len(r.protocol), 0)
|
||||
self.assertFalse(r.needs_core)
|
||||
|
||||
def test_convert_vless_needs_core(self):
|
||||
text = """
|
||||
proxies:
|
||||
- name: v1
|
||||
type: vless
|
||||
server: 1.2.3.4
|
||||
port: 443
|
||||
uuid: 12345678-1234-1234-1234-123456789abc
|
||||
"""
|
||||
r = convert_text(text, source="t.yaml")
|
||||
self.assertTrue(r.ok)
|
||||
self.assertEqual(len(r.protocol), 1)
|
||||
self.assertTrue(r.needs_core)
|
||||
|
||||
def test_invalid_yaml_reports(self):
|
||||
r = convert_text("proxies: [[[[", source="bad.yaml")
|
||||
self.assertFalse(r.ok)
|
||||
self.assertTrue(r.errors or r.reports)
|
||||
|
||||
def test_pack_writes_artifacts(self):
|
||||
text = """
|
||||
proxies:
|
||||
- name: h1
|
||||
type: socks5
|
||||
server: 9.9.9.9
|
||||
port: 1080
|
||||
- name: v1
|
||||
type: trojan
|
||||
server: 8.8.8.8
|
||||
port: 443
|
||||
password: secret
|
||||
"""
|
||||
r = convert_text(text, source="mix.yaml")
|
||||
self.assertTrue(r.ok)
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
home = Path(td) / ".nodes"
|
||||
nodes_json = Path(td) / "nodes.json"
|
||||
packed = pack_result(r, nodes_home=home, nodes_json=nodes_json)
|
||||
self.assertTrue(packed.ok)
|
||||
self.assertTrue(nodes_json.is_file())
|
||||
self.assertTrue((home / "config" / "runtime.yaml").is_file())
|
||||
data = nodes_json.read_text(encoding="utf-8")
|
||||
self.assertIn("9.9.9.9", data)
|
||||
self.assertIn("imp-", data)
|
||||
self.assertNotIn("from-clash", data)
|
||||
rt = (home / "config" / "runtime.yaml").read_text(encoding="utf-8")
|
||||
self.assertIn("trojan", rt)
|
||||
self.assertIn("v1", rt)
|
||||
self.assertIsNotNone(packed.merge)
|
||||
self.assertEqual(packed.merge.mode, "merge")
|
||||
|
||||
def test_merge_keeps_existing(self):
|
||||
from register_core.nodes.catalog import load_nodes, save_nodes
|
||||
from register_core.nodes.models import Node
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
td_path = Path(td)
|
||||
nodes_json = td_path / "nodes.json"
|
||||
save_nodes(
|
||||
[Node(url="http://old:1@1.1.1.1:80", id="keep-old", label="old")],
|
||||
nodes_json,
|
||||
)
|
||||
r = convert_text(
|
||||
"proxies:\n - name: n\n type: http\n server: 2.2.2.2\n port: 8080\n",
|
||||
source="t.yaml",
|
||||
)
|
||||
packed = pack_result(
|
||||
r, nodes_home=td_path / ".nodes", nodes_json=nodes_json, replace_nodes=False
|
||||
)
|
||||
loaded = load_nodes(nodes_json)
|
||||
urls = {n.url for n in loaded}
|
||||
self.assertIn("http://old:1@1.1.1.1:80", urls)
|
||||
self.assertIn("http://2.2.2.2:8080", urls)
|
||||
self.assertEqual(packed.merge.added, 1)
|
||||
self.assertEqual(packed.merge.kept, 1)
|
||||
|
||||
def test_merge_preserves_cooldown(self):
|
||||
"""Re-import must not drop soft-cool on existing URL."""
|
||||
from register_core.nodes.convert.pipeline import merge_dialable
|
||||
from register_core.nodes.models import Node
|
||||
|
||||
old = Node(
|
||||
url="http://u:p@1.1.1.1:80",
|
||||
id="keep",
|
||||
label="old",
|
||||
cooldown_until=9_999_999_999.0,
|
||||
cooldown_reason="registration_disallowed",
|
||||
fail_count=3,
|
||||
)
|
||||
incoming = Node(url="http://u:p@1.1.1.1:80", id="new", label="fresh")
|
||||
merged, plan = merge_dialable([old], [incoming], replace=False)
|
||||
self.assertEqual(plan.updated, 1)
|
||||
self.assertEqual(len(merged), 1)
|
||||
self.assertEqual(merged[0].cooldown_until, 9_999_999_999.0)
|
||||
self.assertEqual(merged[0].cooldown_reason, "registration_disallowed")
|
||||
self.assertEqual(merged[0].fail_count, 3)
|
||||
|
||||
def test_default_id_unique_for_same_host_different_auth(self):
|
||||
from register_core.nodes.models import Node, _default_id
|
||||
|
||||
a = "http://userA:pwA@10.0.0.1:8080"
|
||||
b = "http://userB:pwB@10.0.0.1:8080"
|
||||
id_a = _default_id(a)
|
||||
id_b = _default_id(b)
|
||||
self.assertNotEqual(id_a, id_b)
|
||||
self.assertEqual(_default_id(a), id_a) # stable
|
||||
na, nb = Node(url=a), Node(url=b)
|
||||
self.assertNotEqual(na.id, nb.id)
|
||||
# redacted label alone would collide; digest disambiguates
|
||||
self.assertIn("10.0.0.1", na.id)
|
||||
|
||||
def test_replace_drops_existing(self):
|
||||
from register_core.nodes.catalog import load_nodes, save_nodes
|
||||
from register_core.nodes.models import Node
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
td_path = Path(td)
|
||||
nodes_json = td_path / "nodes.json"
|
||||
save_nodes([Node(url="http://old:1@1.1.1.1:80", label="old")], nodes_json)
|
||||
r = convert_text(
|
||||
"proxies:\n - name: n\n type: http\n server: 2.2.2.2\n port: 8080\n",
|
||||
source="t.yaml",
|
||||
)
|
||||
packed = pack_result(
|
||||
r, nodes_home=td_path / ".nodes", nodes_json=nodes_json, replace_nodes=True
|
||||
)
|
||||
loaded = load_nodes(nodes_json)
|
||||
self.assertEqual(len(loaded), 1)
|
||||
self.assertEqual(loaded[0].url, "http://2.2.2.2:8080")
|
||||
self.assertEqual(packed.merge.mode, "replace")
|
||||
self.assertEqual(packed.merge.dropped, 1)
|
||||
|
||||
|
||||
class TestParseErrors(unittest.TestCase):
|
||||
def test_empty_raises(self):
|
||||
with self.assertRaises(ParseError):
|
||||
parse_text(" ", source="x")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,285 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline tests for orphan Drission Chrome cleanup predicates."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def test_is_drission_chrome_cmdline() -> None:
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from tab_pool import is_drission_chrome_cmdline, is_drission_related_cmdline
|
||||
|
||||
live = (
|
||||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome "
|
||||
"--remote-debugging-port=12231 "
|
||||
"--user-data-dir=/tmp/DrissionPage/autoPortData/12231 "
|
||||
"--load-extension=/proj/turnstilePatch"
|
||||
)
|
||||
assert is_drission_chrome_cmdline(live)
|
||||
assert is_drission_related_cmdline(live)
|
||||
|
||||
helper = (
|
||||
"/Apps/Google Chrome Helper.app/Contents/MacOS/Google Chrome Helper "
|
||||
"--type=renderer --remote-debugging-port=12231 "
|
||||
"--user-data-dir=/tmp/DrissionPage/autoPortData/12231"
|
||||
)
|
||||
assert not is_drission_chrome_cmdline(helper)
|
||||
assert is_drission_related_cmdline(helper)
|
||||
|
||||
unrelated = (
|
||||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome "
|
||||
"--remote-debugging-port=9222 --user-data-dir=/Users/me/chrome-coinbot-profile"
|
||||
)
|
||||
assert not is_drission_chrome_cmdline(unrelated)
|
||||
assert not is_drission_related_cmdline(unrelated)
|
||||
|
||||
no_port = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome --user-data-dir=/tmp/x"
|
||||
assert not is_drission_chrome_cmdline(no_port)
|
||||
print("PASS is_drission_chrome_cmdline")
|
||||
|
||||
|
||||
def test_parse_ps_chrome_rows_filters_ppid() -> None:
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from tab_pool import parse_ps_chrome_rows, parse_ps_drission_related_rows
|
||||
|
||||
ps = """
|
||||
10738 10734 /Applications/Google Chrome.app/Contents/MacOS/Google Chrome --remote-debugging-port=12231 --user-data-dir=/tmp/DrissionPage/autoPortData/12231 --load-extension=/x/turnstilePatch
|
||||
28307 1 /Applications/Google Chrome.app/Contents/MacOS/Google Chrome --remote-debugging-port=52082 --user-data-dir=/tmp/DrissionPage/autoPortData/52082 --load-extension=/x/turnstilePatch
|
||||
89427 1 /Applications/Google Chrome.app/Contents/MacOS/Google Chrome --remote-debugging-port=9222 --user-data-dir=/Users/me/chrome-coinbot-profile
|
||||
99999 1 /Applications/Google Chrome Helper.app/Contents/MacOS/Google Chrome Helper --type=gpu --remote-debugging-port=52082 --user-data-dir=/tmp/DrissionPage/autoPortData/52082
|
||||
"""
|
||||
rows = parse_ps_chrome_rows(ps)
|
||||
pids = {r[0] for r in rows}
|
||||
assert 10738 in pids
|
||||
assert 28307 in pids
|
||||
assert 89427 not in pids # unrelated profile
|
||||
assert 99999 not in pids # helper
|
||||
orphan = [r for r in rows if r[1] in (0, 1)]
|
||||
assert {r[0] for r in orphan} == {28307}
|
||||
|
||||
related = parse_ps_drission_related_rows(ps)
|
||||
related_pids = {r[0] for r in related}
|
||||
assert 99999 in related_pids # helpers included
|
||||
assert 89427 not in related_pids
|
||||
print("PASS parse_ps_chrome_rows_filters_ppid")
|
||||
|
||||
|
||||
def test_family_pids_include_helpers() -> None:
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from tab_pool import _family_pids_for_main
|
||||
|
||||
main_cmd = (
|
||||
"chrome --remote-debugging-port=52082 "
|
||||
"--user-data-dir=/tmp/DrissionPage/autoPortData/52082 --load-extension=/x/turnstilePatch"
|
||||
)
|
||||
related = [
|
||||
(28307, 1, main_cmd),
|
||||
(
|
||||
99999,
|
||||
28307,
|
||||
"chrome Helper --type=gpu --remote-debugging-port=52082 "
|
||||
"--user-data-dir=/tmp/DrissionPage/autoPortData/52082",
|
||||
),
|
||||
(
|
||||
88888,
|
||||
1,
|
||||
"chrome Helper --type=renderer --user-data-dir=/tmp/DrissionPage/autoPortData/52082",
|
||||
),
|
||||
(
|
||||
77777,
|
||||
1,
|
||||
"chrome --remote-debugging-port=11111 "
|
||||
"--user-data-dir=/tmp/DrissionPage/autoPortData/11111 --load-extension=/x/turnstilePatch",
|
||||
),
|
||||
]
|
||||
family = _family_pids_for_main(28307, main_cmd, related)
|
||||
assert 28307 in family
|
||||
assert 99999 in family
|
||||
assert 88888 in family
|
||||
assert 77777 not in family
|
||||
print("PASS family_pids_include_helpers")
|
||||
|
||||
|
||||
def test_cleanup_selects_self_children_and_helpers() -> None:
|
||||
"""dry_run with mocked ps: init orphan + untracked self-child + helper."""
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
import tab_pool
|
||||
|
||||
self_pid = 4242
|
||||
ps = f"""
|
||||
10001 1 chrome --remote-debugging-port=11111 --user-data-dir=/tmp/DrissionPage/autoPortData/11111 --load-extension=/x/turnstilePatch
|
||||
10002 {self_pid} chrome --remote-debugging-port=22222 --user-data-dir=/tmp/DrissionPage/autoPortData/22222 --load-extension=/x/turnstilePatch
|
||||
10003 10002 chrome Helper --type=gpu --remote-debugging-port=22222 --user-data-dir=/tmp/DrissionPage/autoPortData/22222
|
||||
10004 9999 chrome --remote-debugging-port=33333 --user-data-dir=/tmp/DrissionPage/autoPortData/33333 --load-extension=/x/turnstilePatch
|
||||
20000 1 chrome --remote-debugging-port=9222 --user-data-dir=/Users/me/chrome-coinbot-profile
|
||||
"""
|
||||
with mock.patch.object(tab_pool, "_ps_ax_pid_ppid_cmd", return_value=ps), mock.patch.object(
|
||||
tab_pool.os, "getpid", return_value=self_pid
|
||||
), mock.patch.object(tab_pool.os, "getppid", return_value=1):
|
||||
# only init orphans → self-child skipped
|
||||
res_init = tab_pool.cleanup_orphan_drission_chromes(
|
||||
only_ppid_init=True,
|
||||
include_self_children=False,
|
||||
kill_related_helpers=True,
|
||||
dry_run=True,
|
||||
)
|
||||
assert res_init["pids"] == [10001]
|
||||
|
||||
# include self children → orphan + failed boot child
|
||||
res_self = tab_pool.cleanup_orphan_drission_chromes(
|
||||
only_ppid_init=True,
|
||||
include_self_children=True,
|
||||
kill_related_helpers=True,
|
||||
dry_run=True,
|
||||
)
|
||||
assert set(res_self["pids"]) == {10001, 10002}
|
||||
# live other-python child left alone
|
||||
assert 10004 not in res_self["pids"]
|
||||
# coinbot never matched
|
||||
assert 20000 not in res_self["pids"]
|
||||
|
||||
# protect tracked live browser
|
||||
res_prot = tab_pool.cleanup_orphan_drission_chromes(
|
||||
only_ppid_init=True,
|
||||
include_self_children=True,
|
||||
protect_pids={10002},
|
||||
kill_related_helpers=True,
|
||||
dry_run=True,
|
||||
)
|
||||
assert res_prot["pids"] == [10001]
|
||||
assert res_prot["protected_skipped"] >= 1
|
||||
print("PASS cleanup_selects_self_children_and_helpers")
|
||||
|
||||
|
||||
def test_cleanup_dry_run_only_ppid_init() -> None:
|
||||
"""dry_run path should not raise; real kill is OS-dependent so we only dry-run."""
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from tab_pool import cleanup_orphan_drission_chromes
|
||||
|
||||
logs: list[str] = []
|
||||
res = cleanup_orphan_drission_chromes(
|
||||
log_callback=logs.append,
|
||||
only_ppid_init=True,
|
||||
dry_run=True,
|
||||
)
|
||||
assert "scanned" in res
|
||||
assert "matched" in res
|
||||
assert res.get("dry_run") is True
|
||||
assert isinstance(res.get("pids"), list)
|
||||
assert "helpers_killed" in res
|
||||
print("PASS cleanup_dry_run_only_ppid_init")
|
||||
|
||||
|
||||
def test_is_xvfb_and_parse() -> None:
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from tab_pool import is_xvfb_cmdline, parse_ps_xvfb_rows
|
||||
|
||||
assert is_xvfb_cmdline("/usr/bin/Xvfb :99 -screen 0 1280x900x24")
|
||||
assert not is_xvfb_cmdline("xvfb-run -a python")
|
||||
rows = parse_ps_xvfb_rows(
|
||||
" 10 1 /usr/bin/Xvfb :99 -screen 0 1x1x24\n 11 2 /usr/bin/Xvfb :100\n"
|
||||
)
|
||||
assert {r[0] for r in rows} == {10, 11}
|
||||
print("PASS is_xvfb_and_parse")
|
||||
|
||||
|
||||
def test_cleanup_orphan_xvfb_dry_run() -> None:
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from tab_pool import cleanup_orphan_xvfb
|
||||
|
||||
res = cleanup_orphan_xvfb(only_ppid_init=True, dry_run=True, clean_tmp_dirs=False)
|
||||
assert res.get("dry_run") is True
|
||||
assert "scanned" in res
|
||||
print("PASS cleanup_orphan_xvfb_dry_run")
|
||||
|
||||
|
||||
def test_call_sites_use_self_children() -> None:
|
||||
"""Recycle / boot-fail / startup paths must request include_self_children."""
|
||||
ttk = (ROOT / "grok_register_ttk.py").read_text(encoding="utf-8")
|
||||
cli = (ROOT / "register_cli.py").read_text(encoding="utf-8")
|
||||
assert "include_self_children=True" in ttk
|
||||
assert "kill_related_helpers=True" in ttk
|
||||
assert "include_self_children=True" in cli
|
||||
assert "kill_related_helpers=True" in cli
|
||||
assert "helpers_killed" in cli
|
||||
print("PASS call_sites_use_self_children")
|
||||
|
||||
|
||||
def test_autoport_min_age_floor() -> None:
|
||||
"""tmp_dir_max_age_sec=0 must still floor to _AUTOPORT_MIN_AGE_SEC.
|
||||
|
||||
DrissionPage creates autoPortData/<port> before Chrome execs; a sibling
|
||||
worker mid-boot has a dir that no process references in `ps` yet. Without
|
||||
the floor, concurrent cleanup would rmtree a live profile.
|
||||
"""
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path as P
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
import tab_pool
|
||||
|
||||
assert tab_pool._AUTOPORT_MIN_AGE_SEC >= 30.0
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
fresh = P(td) / "fresh"
|
||||
stale = P(td) / "stale"
|
||||
fresh.mkdir()
|
||||
stale.mkdir()
|
||||
# Make stale old enough to pass any reasonable floor.
|
||||
old = time.time() - 3600
|
||||
import os
|
||||
|
||||
os.utime(stale, (old, old))
|
||||
# fresh keeps mtime≈now
|
||||
|
||||
with mock.patch.object(tab_pool, "_AUTOPORT_GLOB", str(P(td) / "*")):
|
||||
# Caller asks for 0 ("clean everything"); floor must still protect fresh.
|
||||
n = tab_pool._cleanup_stale_autoport_dirs(
|
||||
ps_text="", # neither dir referenced by any process
|
||||
protect_udds=set(),
|
||||
log=lambda _m: None,
|
||||
dry_run=True,
|
||||
max_age_sec=0.0,
|
||||
errors=[],
|
||||
)
|
||||
# Only stale should be counted; fresh is younger than the floor.
|
||||
assert n == 1, f"expected only stale dir, got n={n}"
|
||||
print("PASS autoport_min_age_floor")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
test_is_drission_chrome_cmdline()
|
||||
test_parse_ps_chrome_rows_filters_ppid()
|
||||
test_family_pids_include_helpers()
|
||||
test_cleanup_selects_self_children_and_helpers()
|
||||
test_cleanup_dry_run_only_ppid_init()
|
||||
test_is_xvfb_and_parse()
|
||||
test_cleanup_orphan_xvfb_dry_run()
|
||||
test_call_sites_use_self_children()
|
||||
test_autoport_min_age_floor()
|
||||
print("\nALL PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,43 @@
|
||||
#!/usr/bin/env python3
|
||||
"""OtpWaitDiagnostics + MailMissError.diagnostics (offline)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import unittest
|
||||
from dataclasses import asdict
|
||||
|
||||
from register_core.contracts import OtpWaitDiagnostics
|
||||
from register_core.errors import MailMissError
|
||||
|
||||
|
||||
class TestOtpWaitDiagnostics(unittest.TestCase):
|
||||
def test_defaults_and_asdict(self) -> None:
|
||||
d = OtpWaitDiagnostics()
|
||||
self.assertEqual(d.poll_count, 0)
|
||||
self.assertEqual(d.failure_class, "")
|
||||
payload = asdict(d)
|
||||
self.assertIn("message_scan_count", payload)
|
||||
self.assertIn("matched_after_seconds", payload)
|
||||
|
||||
def test_mail_miss_carries_diagnostics(self) -> None:
|
||||
diag = OtpWaitDiagnostics(
|
||||
poll_count=3,
|
||||
empty_rounds=3,
|
||||
failure_class="no_mail",
|
||||
elapsed_seconds=90.0,
|
||||
timeout_s=90.0,
|
||||
provider="gmail_imap",
|
||||
)
|
||||
exc = MailMissError("gmail empty OTP", diagnostics=diag)
|
||||
self.assertEqual(str(exc), "gmail empty OTP")
|
||||
self.assertIs(exc.diagnostics, diag)
|
||||
self.assertEqual(exc.diagnostics.failure_class, "no_mail")
|
||||
|
||||
def test_mail_miss_without_diagnostics(self) -> None:
|
||||
exc = MailMissError("plain miss")
|
||||
self.assertIsNone(exc.diagnostics)
|
||||
self.assertEqual(str(exc), "plain miss")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(unittest.main())
|
||||
@@ -0,0 +1,160 @@
|
||||
"""Unit tests for Outlook private artifact sink + pure provider helpers (Task 9).
|
||||
|
||||
Browser-free and network-free. All values are synthetic. The private sink file
|
||||
legitimately contains the password and refresh_token (that is its purpose);
|
||||
the public RegisterResult view must never leak them.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from register_core.providers.outlook_adapter import OutlookProvider
|
||||
|
||||
CLIENT_ID = "9e5f94bc-e8a4-4e73-b8be-63364c29d753"
|
||||
|
||||
|
||||
def _provider(tmp_path: Path) -> OutlookProvider:
|
||||
return OutlookProvider(config={"outlook_auths_dir": str(tmp_path / "auths")})
|
||||
|
||||
|
||||
def test_write_outlook_artifact_creates_0600_file(tmp_path):
|
||||
provider = _provider(tmp_path)
|
||||
created = datetime(2026, 7, 22, 12, 0, 0, tzinfo=timezone.utc)
|
||||
path = provider._write_outlook_artifact(
|
||||
email="user@outlook.com",
|
||||
password="synthetic-password",
|
||||
client_id=CLIENT_ID,
|
||||
refresh_token="synthetic-refresh",
|
||||
recovery_email="r@invalid",
|
||||
bound=True,
|
||||
created_at=created,
|
||||
)
|
||||
assert Path(path).exists()
|
||||
assert stat.S_IMODE(os.stat(path).st_mode) == 0o600
|
||||
body = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
assert body == {
|
||||
"email": "user@outlook.com",
|
||||
"password": "synthetic-password",
|
||||
"client_id": CLIENT_ID,
|
||||
"refresh_token": "synthetic-refresh",
|
||||
"recovery_email": "r@invalid",
|
||||
"bound": True,
|
||||
"created_at": "20260722T120000Z",
|
||||
}
|
||||
|
||||
|
||||
def test_filename_sanitizes_email_and_is_collision_safe(tmp_path):
|
||||
provider = _provider(tmp_path)
|
||||
stamp = datetime(2026, 7, 22, 12, 0, 0, tzinfo=timezone.utc)
|
||||
|
||||
p1 = provider._write_outlook_artifact(
|
||||
email="User@Outlook.com", password="p", client_id="c",
|
||||
refresh_token="r", recovery_email="", bound=False, created_at=stamp,
|
||||
)
|
||||
assert Path(p1).name == "outlook-user-outlook-com-20260722T120000Z.json"
|
||||
|
||||
# Same email + same second → no clobber; a numeric suffix is appended.
|
||||
p2 = provider._write_outlook_artifact(
|
||||
email="user@outlook.com", password="p", client_id="c",
|
||||
refresh_token="r", recovery_email="", bound=False, created_at=stamp,
|
||||
)
|
||||
assert Path(p2).name == "outlook-user-outlook-com-20260722T120000Z-1.json"
|
||||
assert len({p1, p2}) == 2
|
||||
|
||||
# Different email → distinct file, no collision-suffix.
|
||||
p3 = provider._write_outlook_artifact(
|
||||
email="other@outlook.com", password="p", client_id="c",
|
||||
refresh_token="r", recovery_email="", bound=False, created_at=stamp,
|
||||
)
|
||||
assert Path(p3).name == "outlook-other-outlook-com-20260722T120000Z.json"
|
||||
assert len({p1, p2, p3}) == 3
|
||||
|
||||
|
||||
def test_write_outlook_artifact_atomic_no_temp_left_behind(tmp_path):
|
||||
provider = _provider(tmp_path)
|
||||
provider._write_outlook_artifact(
|
||||
email="a@outlook.com", password="p", client_id="c",
|
||||
refresh_token="r", recovery_email="", bound=False,
|
||||
created_at=datetime(2026, 7, 22, 12, 0, 0, tzinfo=timezone.utc),
|
||||
)
|
||||
leftovers = list(Path(tmp_path / "auths").glob(".outlook-*.tmp"))
|
||||
assert leftovers == []
|
||||
|
||||
|
||||
def test_write_outlook_artifact_tightens_auths_dir_to_0700(tmp_path):
|
||||
"""The auths directory is tightened to 0700 to match the 0600-file secret
|
||||
discipline; a default umask would otherwise leave it world-readable."""
|
||||
provider = _provider(tmp_path)
|
||||
provider._write_outlook_artifact(
|
||||
email="dir@outlook.com", password="p", client_id="c",
|
||||
refresh_token="r", recovery_email="", bound=False,
|
||||
created_at=datetime(2026, 7, 22, 12, 0, 0, tzinfo=timezone.utc),
|
||||
)
|
||||
auths_dir = tmp_path / "auths"
|
||||
assert stat.S_IMODE(os.stat(auths_dir).st_mode) == 0o700
|
||||
# The file itself remains 0600.
|
||||
f = next(auths_dir.glob("outlook-dir-outlook-com-*.json"))
|
||||
assert stat.S_IMODE(os.stat(f).st_mode) == 0o600
|
||||
|
||||
|
||||
def test_generate_account_email_is_random_and_suffixed():
|
||||
provider = OutlookProvider()
|
||||
a = provider._generate_account_email("@outlook.com")
|
||||
b = provider._generate_account_email("@outlook.com")
|
||||
assert a.endswith("@outlook.com")
|
||||
assert a.startswith("orx")
|
||||
local = a.split("@", 1)[0]
|
||||
assert len(local) == 15 and all(c in "0123456789abcdef" for c in local[3:])
|
||||
assert a != b
|
||||
|
||||
|
||||
def test_generate_password_is_url_safe_and_unique():
|
||||
provider = OutlookProvider()
|
||||
p = provider._generate_password()
|
||||
assert isinstance(p, str) and len(p) >= 18
|
||||
assert not any(c.isspace() for c in p)
|
||||
assert p == p.strip()
|
||||
assert provider._generate_password() != p
|
||||
|
||||
|
||||
def test_failure_helper_normalizes_kind_and_carries_no_secret():
|
||||
provider = OutlookProvider()
|
||||
# The pass-through kind "captcha" normalizes to itself; the raw detail text
|
||||
# is what the caller cares about, not the kind.
|
||||
result = provider._failure(
|
||||
"captcha", "fun captcha detail", {"outlook_steps": ["register"]}
|
||||
)
|
||||
assert result.ok is False
|
||||
assert result.provider == "outlook"
|
||||
assert result.secret_kind == "none"
|
||||
assert result.secret == ""
|
||||
assert result.error_kind == "captcha"
|
||||
assert result.artifacts == {"outlook_steps": ["register"]}
|
||||
# A transport-shaped alias maps through normalize_error_kind as documented.
|
||||
proxied = provider._failure("missing_attempt_proxy", "x")
|
||||
assert proxied.error_kind == "proxy"
|
||||
|
||||
|
||||
def test_auths_dir_defaults_when_config_and_env_absent(monkeypatch):
|
||||
monkeypatch.delenv("OUTLOOK_AUTHS_DIR", raising=False)
|
||||
provider = OutlookProvider()
|
||||
assert provider._auths_dir == "outlook_auths"
|
||||
|
||||
|
||||
def test_auths_dir_honors_env_when_config_absent(monkeypatch, tmp_path):
|
||||
"""The adapter honors OUTLOOK_AUTHS_DIR so write/count/list agree on one
|
||||
directory (findings #8 alignment)."""
|
||||
monkeypatch.setenv("OUTLOOK_AUTHS_DIR", str(tmp_path / "env_auths"))
|
||||
provider = OutlookProvider() # no outlook_auths_dir in config
|
||||
assert provider._auths_dir == str(tmp_path / "env_auths")
|
||||
|
||||
|
||||
def test_auths_dir_config_wins_over_env(monkeypatch, tmp_path):
|
||||
monkeypatch.setenv("OUTLOOK_AUTHS_DIR", str(tmp_path / "env_auths"))
|
||||
provider = OutlookProvider(config={"outlook_auths_dir": "config_wins"})
|
||||
assert provider._auths_dir == "config_wins"
|
||||
@@ -0,0 +1,392 @@
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
from register_core.providers.outlook_browser import (
|
||||
OutlookBrowserConfig,
|
||||
OutlookRegistrationFlow,
|
||||
RegistrationPageResult,
|
||||
_proxy_settings,
|
||||
)
|
||||
|
||||
|
||||
def test_outlook_config_defaults_to_manual_captcha_gate():
|
||||
"""Default is strategy 2 (manual handoff for hold AND FunCaptcha), NOT 0.
|
||||
Strategy 0's hold auto-solve needs a HOLD-capable slidex solver; installed
|
||||
slidex 0.5.0 VisualChallengeSolver only handles OCR/IMAGE_TEXT and
|
||||
SLIDER_CAPTCHA (returns error_code="unsupported_challenge_type" for HOLD),
|
||||
so a naive default-0 would dead-bridge live hold captchas instead of
|
||||
waiting for the human. Regression guard against re-flipping to 0."""
|
||||
config = OutlookBrowserConfig.from_options({})
|
||||
assert config.captcha_strategy == 2
|
||||
assert config.email_suffix == "@outlook.com"
|
||||
assert config.locale == "zh-CN"
|
||||
assert config.timezone_id == "UTC"
|
||||
|
||||
|
||||
def test_outlook_config_honors_authored_identity_passthrough():
|
||||
"""Identity keys (locale/timezone_id/latitude/longitude) are NOT secret keys
|
||||
and pass straight through ``outlook_options()`` to the typed config. An
|
||||
authored profile value wins — this is the override the egress→identity
|
||||
auto-align leaves room for (resolver only fills keys the profile left unset).
|
||||
A US/LA residential egress would author a western-aligned identity here
|
||||
instead of the zh-CN/UTC default."""
|
||||
config = OutlookBrowserConfig.from_options(
|
||||
{
|
||||
"locale": "en-US",
|
||||
"timezone_id": "America/Los_Angeles",
|
||||
"latitude": 34.0522,
|
||||
"longitude": -118.2437,
|
||||
}
|
||||
)
|
||||
assert config.locale == "en-US"
|
||||
assert config.timezone_id == "America/Los_Angeles"
|
||||
assert config.latitude == 34.0522
|
||||
assert config.longitude == -118.2437
|
||||
|
||||
|
||||
def test_outlook_config_locale_falls_back_to_default_when_unset():
|
||||
"""An absent locale must keep the zh-CN default (the line-57 hardcode fix uses
|
||||
``normalized.get("locale") or "zh-CN"``). Non-egress paths are unchanged."""
|
||||
config = OutlookBrowserConfig.from_options({"timezone_id": "America/Los_Angeles"})
|
||||
assert config.locale == "zh-CN"
|
||||
assert config.timezone_id == "America/Los_Angeles"
|
||||
|
||||
|
||||
def test_outlook_config_rejects_secret_values_before_normalization():
|
||||
with pytest.raises(ValueError, match="secret"):
|
||||
OutlookBrowserConfig.from_options({"password": "must-not-be-read"})
|
||||
|
||||
|
||||
def test_outlook_config_rejects_strategy_1_as_not_implemented():
|
||||
"""Strategy 1 (ManualFallback) is spec-accepted but not wired; rejecting
|
||||
it loudly prevents the silent degrade to strategy 0 full-auto HOLD."""
|
||||
with pytest.raises(ValueError, match="not implemented"):
|
||||
OutlookBrowserConfig.from_options({"captcha_strategy": 1})
|
||||
|
||||
|
||||
def test_outlook_config_accepts_strategy_0_and_2():
|
||||
assert OutlookBrowserConfig.from_options({"captcha_strategy": 0}).captcha_strategy == 0
|
||||
assert OutlookBrowserConfig.from_options({"captcha_strategy": 2}).captcha_strategy == 2
|
||||
|
||||
|
||||
def test_outlook_config_accepts_pipeline_runtime_proxy_not_guarded():
|
||||
"""Pipeline injects runtime-operational keys (``proxy``, ``mail_proxy``,
|
||||
``egress``, ``proxy_list``) into ``job.extra`` and ``get_provider(name,
|
||||
**extra)`` splatters them into the provider's ``self.config`` options dict.
|
||||
Those keys are NOT profile-authored config and must not trip the
|
||||
``outlook_options()`` inline-secret guard — a real runtime proxy URL is
|
||||
legitimate and is read separately by the adapter from ``extra["proxy"]``.
|
||||
Without this exemption a real live run with ``--proxy`` aborts at the guard
|
||||
with "outlook options cannot contain inline secret values: proxy" before
|
||||
the proxy handoff boundary is even reached (live regression, 2026-08-03)."""
|
||||
for runtime_key in ("proxy", "mail_proxy", "egress", "proxy_list"):
|
||||
config = OutlookBrowserConfig.from_options(
|
||||
{runtime_key: "http://USER:SECRET@example.invalid:7000",
|
||||
"bind_recovery_email": False}
|
||||
)
|
||||
assert config.email_suffix == "@outlook.com"
|
||||
# runtime proxy URL is dropped from the typed config (adapter reads
|
||||
# extra["proxy"] separately); it never leaks into OutlookBrowserConfig:
|
||||
assert not getattr(config, runtime_key, None)
|
||||
|
||||
|
||||
def test_outlook_config_still_rejects_authored_proxy_in_options():
|
||||
"""A proxy URL injected anywhere the guard still scans (i.e. nested under a
|
||||
profile-authored key like ``temp_mail``) must still be rejected — the
|
||||
runtime exemption above only covers the pipeline-injected top-level keys,
|
||||
not profile-authored secrets."""
|
||||
with pytest.raises(ValueError, match="secret"):
|
||||
OutlookBrowserConfig.from_options(
|
||||
{"proxy": "http://runtime:legit@example.invalid:7000", # runtime — OK
|
||||
"temp_mail": {"proxy": "http://authored:secret@example.invalid:7000"}}
|
||||
)
|
||||
|
||||
|
||||
def test_proxy_settings_accepts_valid_server():
|
||||
assert _proxy_settings("http://127.0.0.1:7890") == {"server": "http://127.0.0.1:7890"}
|
||||
assert _proxy_settings(None) is None
|
||||
|
||||
|
||||
def test_proxy_settings_rejects_whitespace_instead_of_silent_drop():
|
||||
with pytest.raises(ValueError, match="proxy"):
|
||||
_proxy_settings(" ")
|
||||
with pytest.raises(ValueError, match="proxy"):
|
||||
_proxy_settings("")
|
||||
with pytest.raises((TypeError, ValueError), match="proxy"):
|
||||
_proxy_settings(123) # type: ignore[arg-type]
|
||||
|
||||
|
||||
class _FakeCount:
|
||||
def __init__(self, n: int) -> None:
|
||||
self._n = n
|
||||
|
||||
async def count(self) -> int:
|
||||
return self._n
|
||||
|
||||
|
||||
class _FakeLocator:
|
||||
def __init__(self, *, count: int = 0, wait_error: Exception | None = None) -> None:
|
||||
self._count = count
|
||||
self._wait_error = wait_error
|
||||
self.fill_calls: list[str] = []
|
||||
self.click_calls = 0
|
||||
self.select_calls: list[str] = []
|
||||
|
||||
def count(self): # sync-or-await dual use via awaitable wrapper below
|
||||
return _AwaitableInt(self._count)
|
||||
|
||||
async def wait_for(self, **kwargs):
|
||||
if self._wait_error is not None:
|
||||
raise self._wait_error
|
||||
return None
|
||||
|
||||
async def fill(self, value: str) -> None:
|
||||
self.fill_calls.append(value)
|
||||
|
||||
async def click(self) -> None:
|
||||
self.click_calls += 1
|
||||
|
||||
async def select_option(self, value: str) -> None:
|
||||
self.select_calls.append(value)
|
||||
|
||||
|
||||
class _AwaitableInt:
|
||||
def __init__(self, value: int) -> None:
|
||||
self._value = value
|
||||
|
||||
def __await__(self):
|
||||
async def _coro():
|
||||
return self._value
|
||||
|
||||
return _coro().__await__()
|
||||
|
||||
def __bool__(self) -> bool:
|
||||
return bool(self._value)
|
||||
|
||||
def __gt__(self, other: int) -> bool:
|
||||
return self._value > other
|
||||
|
||||
|
||||
class _FakeText:
|
||||
def __init__(self, present: bool = False, *, owner=None, text: str = "") -> None:
|
||||
self._present = present
|
||||
self._owner = owner
|
||||
self._text = text
|
||||
|
||||
def count(self):
|
||||
return _AwaitableInt(1 if self._present else 0)
|
||||
|
||||
@property
|
||||
def first(self) -> "_FakeText":
|
||||
# Playwright's Locator.first — used for the consent wait.
|
||||
return self
|
||||
|
||||
async def wait_for(self, **kwargs):
|
||||
if not self._present:
|
||||
raise TimeoutError(f"{self._text} not visible")
|
||||
return None
|
||||
|
||||
async def click(self) -> None:
|
||||
if self._owner is not None:
|
||||
self._owner.consent_text = self._text
|
||||
|
||||
|
||||
class _FakePage:
|
||||
"""Browser-free page stub for form/risk classification unit tests."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
detach_timeout: bool = False,
|
||||
enforcement: bool = False,
|
||||
abnormal: bool = False,
|
||||
maintenance: bool = False,
|
||||
captcha_frame: bool = False,
|
||||
consent: bool = False,
|
||||
locale: str = "zh-CN",
|
||||
) -> None:
|
||||
self.detach_timeout = detach_timeout
|
||||
self.enforcement = enforcement
|
||||
self.abnormal = abnormal
|
||||
self.maintenance = maintenance
|
||||
self.captcha_frame = captcha_frame
|
||||
self.consent = consent
|
||||
# ``locale`` drives which rendered variant the egress→identity align
|
||||
# would have selected; the stub surfaces only the chosen variant so a
|
||||
# test exercising the en-US form path can assert the previous zh-CN-only
|
||||
# hard-codes (now locale-union selectors) keep working in English.
|
||||
self.locale = locale
|
||||
self.consent_text: str = ""
|
||||
self.goto_calls: list[str] = []
|
||||
|
||||
async def goto(self, url: str, **_kwargs) -> None:
|
||||
self.goto_calls.append(url)
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
if 'href="https://go.microsoft.com/fwlink/?LinkID=521839"' in selector:
|
||||
err = TimeoutError("detach timeout") if self.detach_timeout else None
|
||||
return _FakeLocator(wait_error=err)
|
||||
if selector == "iframe#enforcementFrame":
|
||||
return _FakeLocator(count=1 if self.enforcement else 0)
|
||||
if 'title="验证质询"' in selector:
|
||||
return _FakeLocator(count=1 if self.captcha_frame else 0)
|
||||
# Form controls — always present and no-op.
|
||||
return _FakeLocator(count=0)
|
||||
|
||||
def get_by_text(self, text: str, exact: bool = False):
|
||||
# Only the variant matching the rendered locale is present; the other
|
||||
# locale variant resolves to not-present so the locale-union loops are
|
||||
# actually exercising the alternate path rather than short-circuiting
|
||||
# on the first (zh-CN) variant.
|
||||
zh_variant_for = {
|
||||
"同意并继续": self.consent,
|
||||
"一些异常活动": self.abnormal,
|
||||
"此站点正在维护": self.maintenance,
|
||||
}
|
||||
en_variant_for = {
|
||||
"Agree and continue": self.consent,
|
||||
"some unusual activity": self.abnormal,
|
||||
"this site is under maintenance": self.maintenance,
|
||||
}
|
||||
if self.locale == "en-US":
|
||||
present = en_variant_for.get(text, False)
|
||||
return _FakeText(present, owner=self, text=text)
|
||||
present = zh_variant_for.get(text, False)
|
||||
return _FakeText(present, owner=self, text=text)
|
||||
|
||||
|
||||
def test_registration_flow_detach_timeout_without_risk_is_not_success():
|
||||
page = _FakePage(detach_timeout=True)
|
||||
result = asyncio.run(
|
||||
OutlookRegistrationFlow().register(
|
||||
page,
|
||||
"user@outlook.com",
|
||||
"Pw-not-logged",
|
||||
captcha_strategy=2,
|
||||
)
|
||||
)
|
||||
assert isinstance(result, RegistrationPageResult)
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "provider"
|
||||
assert "form" in result.error.lower() or "timeout" in result.error.lower()
|
||||
assert result.captcha_frame_seen is False
|
||||
assert result.fun_captcha_seen is False
|
||||
|
||||
|
||||
def test_registration_flow_detach_timeout_keeps_captcha_handoff():
|
||||
page = _FakePage(detach_timeout=True, captcha_frame=True)
|
||||
result = asyncio.run(
|
||||
OutlookRegistrationFlow().register(
|
||||
page,
|
||||
"user@outlook.com",
|
||||
"Pw-not-logged",
|
||||
captcha_strategy=2,
|
||||
)
|
||||
)
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "captcha"
|
||||
assert result.captcha_frame_seen is True
|
||||
assert "manual handoff" in result.error.lower()
|
||||
|
||||
|
||||
def test_registration_flow_enforcement_frame_before_success():
|
||||
page = _FakePage(enforcement=True)
|
||||
result = asyncio.run(
|
||||
OutlookRegistrationFlow().register(
|
||||
page,
|
||||
"user@outlook.com",
|
||||
"Pw-not-logged",
|
||||
captcha_strategy=2,
|
||||
)
|
||||
)
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "captcha"
|
||||
assert result.fun_captcha_seen is True
|
||||
|
||||
|
||||
def test_registration_flow_clicks_consent_when_present():
|
||||
"""The consent button (同意并继续) is a hard gate: when present, register()
|
||||
must wait for it and click it — a single poll would miss a slow render."""
|
||||
page = _FakePage(consent=True)
|
||||
asyncio.run(
|
||||
OutlookRegistrationFlow().register(
|
||||
page,
|
||||
"user@outlook.com",
|
||||
"Pw-not-logged",
|
||||
captcha_strategy=2,
|
||||
)
|
||||
)
|
||||
assert page.consent_text == "同意并继续", "consent should have been clicked"
|
||||
|
||||
|
||||
def test_registration_flow_consent_absent_is_non_fatal():
|
||||
"""When no consent button appears (already past consent or not required),
|
||||
register() must not raise — it proceeds to the email form wait. The
|
||||
consent timeout is non-fatal; the flow continues normally."""
|
||||
page = _FakePage(consent=False)
|
||||
# Should not raise despite consent timeout
|
||||
result = asyncio.run(
|
||||
OutlookRegistrationFlow().register(
|
||||
page,
|
||||
"user@outlook.com",
|
||||
"Pw-not-logged",
|
||||
captcha_strategy=2,
|
||||
)
|
||||
)
|
||||
# Consent timeout is silently swallowed; form proceeds normally.
|
||||
# Since no detach timeout or captcha, result is ok=True.
|
||||
assert result.ok is True
|
||||
assert page.consent_text == "" # consent was never clicked (not required)
|
||||
|
||||
|
||||
def test_registration_flow_clicks_en_us_consent_when_present():
|
||||
"""egress→identity align drives locale to en-US for a US residential exit,
|
||||
so the form (and its consent CTA) renders in English. The locale-union
|
||||
consent loop must click the en-US "Agree and continue" the same it would
|
||||
the zh-CN one — regression guard so a US egress does not silently stall at
|
||||
the consent step the way the 2026-08-09 live run stalled at the email step.
|
||||
"""
|
||||
page = _FakePage(consent=True, locale="en-US")
|
||||
asyncio.run(
|
||||
OutlookRegistrationFlow().register(
|
||||
page,
|
||||
"user@outlook.com",
|
||||
"Pw-not-logged",
|
||||
captcha_strategy=2,
|
||||
)
|
||||
)
|
||||
assert page.consent_text == "Agree and continue", "en-US consent should have been clicked"
|
||||
|
||||
|
||||
def test_registration_flow_detects_en_us_abnormal_activity():
|
||||
"""Risk classification must detect the en-US rendered abnormal-activity
|
||||
sentinel, not only the zh-CN one. ``_count_text_any`` walks locale variants."""
|
||||
page = _FakePage(abnormal=True, locale="en-US")
|
||||
result = asyncio.run(
|
||||
OutlookRegistrationFlow().register(
|
||||
page,
|
||||
"user@outlook.com",
|
||||
"Pw-not-logged",
|
||||
captcha_strategy=2,
|
||||
)
|
||||
)
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "captcha"
|
||||
assert "abnormal activity" in result.error.lower()
|
||||
|
||||
|
||||
def test_registration_flow_detects_en_us_maintenance():
|
||||
"""Same locale-union guarantee for the maintenance sentinel."""
|
||||
page = _FakePage(maintenance=True, locale="en-US")
|
||||
result = asyncio.run(
|
||||
OutlookRegistrationFlow().register(
|
||||
page,
|
||||
"user@outlook.com",
|
||||
"Pw-not-logged",
|
||||
captcha_strategy=2,
|
||||
)
|
||||
)
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "captcha"
|
||||
assert "maintenance" in result.error.lower()
|
||||
@@ -0,0 +1,253 @@
|
||||
"""Unit tests for Outlook HOLD captcha bridge (Task 6).
|
||||
|
||||
Default suite is browser-free: solvers, pages, and contexts are fakes only.
|
||||
Uses asyncio.run (repo convention; pytest-asyncio is not a project dependency).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
from register_core.providers.outlook_captcha import OutlookCaptchaBridge
|
||||
|
||||
|
||||
class FakeResult:
|
||||
def __init__(self, success, error_code=None, retryable=False):
|
||||
self.success = success
|
||||
self.error_code = error_code
|
||||
self.retryable = retryable
|
||||
|
||||
|
||||
class _FakePage:
|
||||
def __init__(self, *, cookies=None):
|
||||
self.context = _FakeBrowserContext(cookies=cookies)
|
||||
self.goto_urls: list[str] = []
|
||||
|
||||
async def goto(self, url: str):
|
||||
self.goto_urls.append(url)
|
||||
|
||||
|
||||
class _FakeBrowserContext:
|
||||
def __init__(self, *, cookies=None):
|
||||
self._cookies = list(cookies or [])
|
||||
self.closed = False
|
||||
self.pages: list[_FakePage] = []
|
||||
|
||||
async def storage_state(self):
|
||||
# Deliberately secret-shaped; must never appear in bridge metadata.
|
||||
return {
|
||||
"cookies": self._cookies
|
||||
or [{"name": "RPS", "value": "secret-token-value", "domain": ".live.com"}],
|
||||
"origins": [],
|
||||
}
|
||||
|
||||
async def new_page(self):
|
||||
page = _FakePage()
|
||||
self.pages.append(page)
|
||||
return page
|
||||
|
||||
async def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
class _FakeBrowser:
|
||||
def __init__(self, *, ws_endpoint: str = "ws://synthetic-cdp"):
|
||||
self.ws_endpoint = ws_endpoint
|
||||
self.contexts: list[_FakeBrowserContext] = []
|
||||
|
||||
async def new_context(self, **kwargs):
|
||||
# storage_state may be passed; bridge must not log or return it.
|
||||
ctx = _FakeBrowserContext(cookies=(kwargs.get("storage_state") or {}).get("cookies"))
|
||||
self.contexts.append(ctx)
|
||||
return ctx
|
||||
|
||||
|
||||
def _solver(handler):
|
||||
return type("S", (), {"solve": handler})()
|
||||
|
||||
|
||||
def test_bridge_constructs_hold_cdp_request():
|
||||
seen = {}
|
||||
|
||||
async def solve(self, request):
|
||||
seen["request"] = request
|
||||
return FakeResult(True)
|
||||
|
||||
async def _run():
|
||||
browser = type("B", (), {"ws_endpoint": "ws://synthetic-cdp"})()
|
||||
bridge = OutlookCaptchaBridge(solver=_solver(solve))
|
||||
return await bridge.solve(
|
||||
page=object(), browser=browser, page_url="https://x.invalid"
|
||||
)
|
||||
|
||||
result = asyncio.run(_run())
|
||||
assert result.ok is True
|
||||
assert seen["request"].challenge_type.value == "hold"
|
||||
assert seen["request"].context.value == "cdp"
|
||||
assert seen["request"].cdp_endpoint == "ws://synthetic-cdp"
|
||||
assert seen["request"].page_url == "https://x.invalid"
|
||||
assert result.fallback_used is False
|
||||
assert result.metadata.get("path") == "cdp"
|
||||
# Endpoint must reach the solver only — never result metadata.
|
||||
blob = str(result.metadata).lower()
|
||||
assert "ws://" not in blob
|
||||
assert "synthetic-cdp" not in blob
|
||||
assert "endpoint" not in blob
|
||||
assert "token" not in blob
|
||||
assert "cookie" not in blob
|
||||
|
||||
|
||||
def test_bridge_reports_retryable_failure_without_secrets():
|
||||
async def solve(self, request):
|
||||
return FakeResult(False, "captcha_retry", retryable=True)
|
||||
|
||||
async def _run():
|
||||
browser = type("B", (), {"ws_endpoint": "ws://synthetic-cdp"})()
|
||||
bridge = OutlookCaptchaBridge(solver=_solver(solve))
|
||||
return await bridge.solve(
|
||||
page=object(), browser=browser, page_url="https://x.invalid"
|
||||
)
|
||||
|
||||
result = asyncio.run(_run())
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "captcha"
|
||||
assert result.error == "captcha_retry"
|
||||
assert result.metadata.get("retryable") is True
|
||||
assert result.metadata.get("path") == "cdp"
|
||||
blob = str(result.metadata).lower()
|
||||
assert "token" not in blob
|
||||
assert "cookie" not in blob
|
||||
assert "ws://" not in blob
|
||||
assert "synthetic-cdp" not in blob
|
||||
assert "proxy" not in blob
|
||||
|
||||
|
||||
def test_bridge_maps_ip_blocked_to_proxy_kind():
|
||||
async def solve(self, request):
|
||||
return FakeResult(False, "ip_blocked", retryable=True)
|
||||
|
||||
async def _run():
|
||||
browser = type("B", (), {"ws_endpoint": "ws://synthetic-cdp"})()
|
||||
bridge = OutlookCaptchaBridge(solver=_solver(solve))
|
||||
return await bridge.solve(
|
||||
page=object(), browser=browser, page_url="https://x.invalid"
|
||||
)
|
||||
|
||||
result = asyncio.run(_run())
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "proxy"
|
||||
assert result.error == "ip_blocked"
|
||||
assert result.fallback_used is False
|
||||
|
||||
|
||||
def test_bridge_falls_back_to_storage_state_without_restarting_main_context():
|
||||
calls: list = []
|
||||
|
||||
async def solve(self, request):
|
||||
calls.append(request)
|
||||
ctx_val = getattr(request.context, "value", None) or str(request.context)
|
||||
if ctx_val == "cdp":
|
||||
return FakeResult(False, "captcha_frame_missing", retryable=True)
|
||||
return FakeResult(True)
|
||||
|
||||
main_page = _FakePage(
|
||||
cookies=[{"name": "RPS", "value": "must-not-leak", "domain": ".live.com"}]
|
||||
)
|
||||
browser = _FakeBrowser(ws_endpoint="ws://synthetic-cdp-secret")
|
||||
|
||||
async def _run():
|
||||
bridge = OutlookCaptchaBridge(solver=_solver(solve))
|
||||
return await bridge.solve(
|
||||
page=main_page,
|
||||
browser=browser,
|
||||
page_url="https://signup.live.com/signup",
|
||||
timeout_ms=12_000,
|
||||
)
|
||||
|
||||
result = asyncio.run(_run())
|
||||
|
||||
assert result.ok is True
|
||||
assert result.fallback_used is True
|
||||
assert result.metadata.get("path") == "storage_state"
|
||||
assert len(calls) == 2
|
||||
assert calls[0].context.value == "cdp"
|
||||
assert calls[1].context.value == "playwright_page"
|
||||
assert calls[1].page is not main_page
|
||||
assert browser.contexts, "fallback must open a temporary context"
|
||||
assert browser.contexts[0].closed is True, "temporary context must be closed"
|
||||
# Main page/context must remain open (never silently restarted).
|
||||
assert main_page.context.closed is False
|
||||
blob = str(result.metadata).lower()
|
||||
assert "must-not-leak" not in blob
|
||||
assert "rps" not in blob
|
||||
assert "cookie" not in blob
|
||||
assert "token" not in blob
|
||||
assert "ws://" not in blob
|
||||
assert "synthetic-cdp" not in blob
|
||||
|
||||
|
||||
def test_bridge_fallback_on_unsupported_hold_context_and_closes_temp_context():
|
||||
async def solve(self, request):
|
||||
ctx = request.context.value
|
||||
if ctx == "cdp":
|
||||
return FakeResult(False, "unsupported_hold_context", retryable=False)
|
||||
return FakeResult(False, "captcha_retry", retryable=True)
|
||||
|
||||
main_page = _FakePage()
|
||||
browser = _FakeBrowser()
|
||||
|
||||
async def _run():
|
||||
bridge = OutlookCaptchaBridge(solver=_solver(solve))
|
||||
return await bridge.solve(
|
||||
page=main_page, browser=browser, page_url="https://x.invalid"
|
||||
)
|
||||
|
||||
result = asyncio.run(_run())
|
||||
assert result.ok is False
|
||||
assert result.fallback_used is True
|
||||
assert result.error_kind == "captcha"
|
||||
assert result.error == "captcha_retry"
|
||||
assert result.metadata.get("path") == "storage_state"
|
||||
assert browser.contexts[0].closed is True
|
||||
assert main_page.context.closed is False
|
||||
|
||||
|
||||
def test_bridge_uses_endpoint_getter_without_exposing_it():
|
||||
seen = {}
|
||||
|
||||
async def solve(self, request):
|
||||
seen["endpoint"] = request.cdp_endpoint
|
||||
return FakeResult(True)
|
||||
|
||||
async def getter(browser):
|
||||
return "ws://from-getter-only"
|
||||
|
||||
async def _run():
|
||||
bridge = OutlookCaptchaBridge(
|
||||
solver=_solver(solve),
|
||||
endpoint_getter=getter,
|
||||
)
|
||||
return await bridge.solve(
|
||||
page=object(),
|
||||
browser=type("B", (), {"ws_endpoint": "ws://should-not-win"})(),
|
||||
page_url="https://x.invalid",
|
||||
)
|
||||
|
||||
result = asyncio.run(_run())
|
||||
assert result.ok is True
|
||||
assert seen["endpoint"] == "ws://from-getter-only"
|
||||
assert "from-getter" not in str(result.metadata).lower()
|
||||
assert "endpoint" not in str(result.metadata).lower()
|
||||
|
||||
|
||||
def test_adapter_captcha_bridge_seam_is_injectable(monkeypatch):
|
||||
"""The bridge seam remains constructible/injectable under Task 9 orchestration."""
|
||||
from register_core.providers.outlook_adapter import OutlookProvider
|
||||
|
||||
custom = OutlookCaptchaBridge()
|
||||
provider = OutlookProvider(config={"captcha_bridge": custom})
|
||||
assert provider._captcha_bridge() is custom
|
||||
# Default (no injection) returns a real bridge.
|
||||
assert isinstance(
|
||||
OutlookProvider(config={})._captcha_bridge(), OutlookCaptchaBridge
|
||||
)
|
||||
@@ -0,0 +1,143 @@
|
||||
"""Browser-free tests for the egress → Outlook browser identity resolver.
|
||||
|
||||
Monkeypatches ``_http_get`` so no network is touched. Synthetic ipinfo payloads
|
||||
and proxy URLs are placeholders — the resolver never logs the proxy URL.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from register_core.providers import outlook_identity
|
||||
from register_core.providers.outlook_identity import resolve_egress_identity
|
||||
|
||||
|
||||
# ipinfo.io /json shape: country=ISO alpha-2, timezone=IANA, loc="lat,lng".
|
||||
LA_PAYLOAD = json.dumps(
|
||||
{
|
||||
"ip": "155.254.126.21",
|
||||
"city": "Los Angeles",
|
||||
"region": "California",
|
||||
"country": "US",
|
||||
"org": "AS38136 Akari",
|
||||
"loc": "34.0522,-118.2437",
|
||||
"timezone": "America/Los_Angeles",
|
||||
"postal": "90001",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def _patch_http_get(monkeypatch, body, status=200):
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def fake(proxy, url, *, timeout):
|
||||
captured["proxy"] = proxy
|
||||
captured["url"] = url
|
||||
captured["timeout"] = timeout
|
||||
return (body, status, "curl_cffi")
|
||||
|
||||
# resolve_egress_identity imports _http_get into its own module namespace, so
|
||||
# patch the name it actually looks up.
|
||||
monkeypatch.setattr(outlook_identity, "_http_get", fake)
|
||||
return captured
|
||||
|
||||
|
||||
def test_resolver_returns_la_identity_for_us_ipinfo(monkeypatch):
|
||||
captured = _patch_http_get(monkeypatch, LA_PAYLOAD)
|
||||
|
||||
identity = resolve_egress_identity("http://127.0.0.1:17897")
|
||||
|
||||
assert identity == {
|
||||
"locale": "en-US",
|
||||
"timezone_id": "America/Los_Angeles",
|
||||
"latitude": 34.0522,
|
||||
"longitude": -118.2437,
|
||||
}
|
||||
# The lookup rides the registration proxy — exact proxy URL captured.
|
||||
assert captured["proxy"] == "http://127.0.0.1:17897"
|
||||
assert captured["url"] == "https://ipinfo.io/json"
|
||||
|
||||
|
||||
def test_resolver_maps_non_table_country_to_en_us_fallback(monkeypatch):
|
||||
payload = json.dumps(
|
||||
{
|
||||
"ip": "203.0.113.5",
|
||||
"country": "XX", # not in the country→locale table
|
||||
"loc": "1.3521,103.8198",
|
||||
"timezone": "Asia/Singapore",
|
||||
}
|
||||
)
|
||||
_patch_http_get(monkeypatch, payload)
|
||||
|
||||
identity = resolve_egress_identity("http://example.invalid:7000")
|
||||
|
||||
assert identity["locale"] == "en-US"
|
||||
assert identity["timezone_id"] == "Asia/Singapore"
|
||||
assert identity["latitude"] == 1.3521
|
||||
assert identity["longitude"] == 103.8198
|
||||
|
||||
|
||||
def test_resolver_returns_empty_on_http_status_outage(monkeypatch):
|
||||
_patch_http_get(monkeypatch, "upstream error", status=503)
|
||||
|
||||
identity = resolve_egress_identity("http://example.invalid:7000")
|
||||
|
||||
assert identity == {}
|
||||
|
||||
|
||||
def test_resolver_returns_empty_on_transport_exception(monkeypatch):
|
||||
def boom(_proxy, _url, *, timeout):
|
||||
raise OSError("synthetic transport failure")
|
||||
|
||||
monkeypatch.setattr(outlook_identity, "_http_get", boom)
|
||||
|
||||
identity = resolve_egress_identity("http://example.invalid:7000")
|
||||
|
||||
assert identity == {}
|
||||
|
||||
|
||||
def test_resolver_returns_empty_on_unparseable_body(monkeypatch):
|
||||
_patch_http_get(monkeypatch, "not-json-at-all", status=200)
|
||||
|
||||
identity = resolve_egress_identity("http://example.invalid:7000")
|
||||
|
||||
assert identity == {}
|
||||
|
||||
|
||||
def test_resolver_returns_empty_when_country_missing(monkeypatch):
|
||||
payload = json.dumps({"ip": "203.0.113.5", "city": "Nowhere"})
|
||||
_patch_http_get(monkeypatch, payload)
|
||||
|
||||
identity = resolve_egress_identity("http://example.invalid:7000")
|
||||
|
||||
assert identity == {}
|
||||
|
||||
|
||||
def test_resolver_strips_whitespace_proxy(monkeypatch):
|
||||
captured = _patch_http_get(monkeypatch, LA_PAYLOAD)
|
||||
|
||||
resolve_egress_identity(" http://127.0.0.1:17897 ")
|
||||
|
||||
assert captured["proxy"] == "http://127.0.0.1:17897"
|
||||
|
||||
|
||||
def test_resolver_handles_partial_ipinfo_payload(monkeypatch):
|
||||
"""Timezone or loc may be absent; the resolver must still return locale + the
|
||||
fields that are present, never the whole identity."""
|
||||
payload = json.dumps({"ip": "203.0.113.5", "country": "US"})
|
||||
_patch_http_get(monkeypatch, payload)
|
||||
|
||||
identity = resolve_egress_identity("http://example.invalid:7000")
|
||||
|
||||
assert identity == {"locale": "en-US"}
|
||||
|
||||
|
||||
def test_resolver_tolerates_malformed_loc(monkeypatch):
|
||||
payload = json.dumps(
|
||||
{"ip": "203.0.113.5", "country": "US", "loc": "not-a-point", "timezone": "America/Chicago"}
|
||||
)
|
||||
_patch_http_get(monkeypatch, payload)
|
||||
|
||||
identity = resolve_egress_identity("http://example.invalid:7000")
|
||||
|
||||
assert identity == {"locale": "en-US", "timezone_id": "America/Chicago"}
|
||||
@@ -0,0 +1,195 @@
|
||||
"""Outlook auth import/export helper tests (Task 10).
|
||||
|
||||
The control API surfaces Outlook accounts via a strict ``outlook-*.json`` glob
|
||||
and a redacted public record. These helpers must never return a password or
|
||||
refresh_token value in their public output, and must not match ``xai-*.json``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from apps.control_api.routes_ops import (
|
||||
_outlook_auth_files,
|
||||
_public_outlook_record,
|
||||
)
|
||||
|
||||
|
||||
def _auth(email="u@outlook.com", password="p", client_id="c", refresh_token="r", **extra):
|
||||
payload = {
|
||||
"email": email,
|
||||
"password": password,
|
||||
"client_id": client_id,
|
||||
"refresh_token": refresh_token,
|
||||
}
|
||||
payload.update(extra)
|
||||
return payload
|
||||
|
||||
|
||||
def test_outlook_auth_files_glob_excludes_xai(tmp_path):
|
||||
(tmp_path / "outlook-user.json").write_text(
|
||||
json.dumps(_auth()), encoding="utf-8"
|
||||
)
|
||||
(tmp_path / "xai-user.json").write_text(
|
||||
json.dumps({"email": "x@example.com"}), encoding="utf-8"
|
||||
)
|
||||
# Collision-suffixed files still match.
|
||||
(tmp_path / "outlook-user-20260722T120000Z-1.json").write_text(
|
||||
json.dumps(_auth()), encoding="utf-8"
|
||||
)
|
||||
# Non-json and dotfiles ignored.
|
||||
(tmp_path / "outlook-notes.txt").write_text("noise", encoding="utf-8")
|
||||
|
||||
found = _outlook_auth_files(tmp_path)
|
||||
assert found == [
|
||||
tmp_path / "outlook-user-20260722T120000Z-1.json",
|
||||
tmp_path / "outlook-user.json",
|
||||
]
|
||||
|
||||
|
||||
def test_outlook_auth_files_missing_root_returns_empty(tmp_path):
|
||||
assert _outlook_auth_files(tmp_path / "does-not-exist") == []
|
||||
|
||||
|
||||
def test_public_outlook_record_redacts_secrets():
|
||||
record = _public_outlook_record(
|
||||
_auth(password="real-pw", refresh_token="real-refresh", bound=True,
|
||||
recovery_email="r@invalid")
|
||||
)
|
||||
assert record == {
|
||||
"email": "u@outlook.com",
|
||||
"client_id": "c",
|
||||
"bound": True,
|
||||
"recovery_email": "r@invalid",
|
||||
"has_password": True,
|
||||
"has_refresh_token": True,
|
||||
}
|
||||
assert "real-pw" not in json.dumps(record)
|
||||
assert "real-refresh" not in json.dumps(record)
|
||||
|
||||
|
||||
def test_public_outlook_record_reports_absent_secret_flags_as_true_when_present():
|
||||
# All four required fields present → both has_* flags True; bound defaults.
|
||||
record = _public_outlook_record(
|
||||
{"email": "u@outlook.com", "password": "p", "client_id": "c",
|
||||
"refresh_token": "r"}
|
||||
)
|
||||
assert record["has_password"] is True
|
||||
assert record["has_refresh_token"] is True
|
||||
assert record["bound"] is False
|
||||
|
||||
|
||||
def test_public_outlook_record_rejects_missing_required_fields():
|
||||
# Per the contract, all four of email/password/client_id/refresh_token are
|
||||
# required; any missing (or empty) one raises ValueError.
|
||||
for missing in ("email", "password", "client_id", "refresh_token"):
|
||||
payload = _auth()
|
||||
payload[missing] = "" # falsy counts as missing
|
||||
with pytest.raises(ValueError) as excinfo:
|
||||
_public_outlook_record(payload)
|
||||
assert missing in str(excinfo.value)
|
||||
|
||||
|
||||
def test_public_outlook_record_roundtrips_through_real_sink_layout(tmp_path):
|
||||
"""The artifact written by OutlookProvider._write_outlook_artifact must parse
|
||||
via the helper — guards the on-disk contract between sink and API."""
|
||||
from register_core.providers.outlook_adapter import OutlookProvider
|
||||
|
||||
provider = OutlookProvider(config={"outlook_auths_dir": str(tmp_path)})
|
||||
from datetime import datetime, timezone
|
||||
|
||||
provider._write_outlook_artifact(
|
||||
email="sink@outlook.com",
|
||||
password="sink-pw",
|
||||
client_id="9e5f94bc-e8a4-4e73-b8be-63364c29d753",
|
||||
refresh_token="sink-refresh",
|
||||
recovery_email="r@invalid",
|
||||
bound=True,
|
||||
created_at=datetime(2026, 8, 3, 0, 0, 0, tzinfo=timezone.utc),
|
||||
)
|
||||
paths = _outlook_auth_files(tmp_path)
|
||||
assert len(paths) == 1
|
||||
payload = json.loads(paths[0].read_text(encoding="utf-8"))
|
||||
assert _public_outlook_record(payload)["email"] == "sink@outlook.com"
|
||||
|
||||
|
||||
def test_api_list_outlook_accounts_redacts_and_skips_malformed(tmp_path, monkeypatch):
|
||||
"""GET /api/outlook-accounts returns redacted records over outlook_auths/,
|
||||
never xai, skips malformed/partial files instead of 500ing, and never
|
||||
leaks password/refresh_token."""
|
||||
import json as _json
|
||||
from types import SimpleNamespace
|
||||
|
||||
from apps.control_api import routes_ops
|
||||
|
||||
auths = tmp_path / "outlook_auths"
|
||||
auths.mkdir()
|
||||
# Two good records + one malformed JSON + one partial (missing required).
|
||||
(auths / "outlook-good.json").write_text(
|
||||
_json.dumps(
|
||||
_auth(password="real-pw", refresh_token="real-refresh", bound=True,
|
||||
recovery_email="r@invalid")
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
(auths / "outlook-second.json").write_text(
|
||||
_json.dumps(_auth(email="b@outlook.com")), encoding="utf-8"
|
||||
)
|
||||
(auths / "outlook-broken.json").write_text("{not json", encoding="utf-8")
|
||||
(auths / "outlook-partial.json").write_text(
|
||||
_json.dumps({"email": "x@outlook.com"}), encoding="utf-8" # missing 3 fields
|
||||
)
|
||||
# xai must NEVER be picked up here.
|
||||
(auths / "xai-leak.json").write_text(_json.dumps({"email": "x@x.ai"}), encoding="utf-8")
|
||||
|
||||
# Point the route's settings lookup at the tmp root without relying on the
|
||||
# lru-cached get_settings (which reads the real process root).
|
||||
monkeypatch.setattr(
|
||||
routes_ops, "get_settings", lambda: SimpleNamespace(project_root=tmp_path)
|
||||
)
|
||||
|
||||
resp = routes_ops.api_list_outlook_accounts()
|
||||
assert resp["count"] == 2
|
||||
assert resp["skipped"] == 2 # broken json + partial
|
||||
assert resp["dir"] == "outlook_auths"
|
||||
emails = sorted(r["email"] for r in resp["accounts"])
|
||||
assert emails == ["b@outlook.com", "u@outlook.com"]
|
||||
blob = _json.dumps(resp)
|
||||
assert "real-pw" not in blob
|
||||
assert "real-refresh" not in blob
|
||||
# xai accounts are excluded by the strict glob.
|
||||
assert "x@x.ai" not in blob
|
||||
|
||||
|
||||
def test_api_list_outlook_accounts_honors_outlook_auths_dir_env(tmp_path, monkeypatch):
|
||||
"""Listing must honor OUTLOOK_AUTHS_DIR so count/list/write all agree on the
|
||||
same directory the supervisor and adapter use (findings #8 alignment)."""
|
||||
import json as _json
|
||||
from types import SimpleNamespace
|
||||
|
||||
from apps.control_api import routes_ops
|
||||
|
||||
custom = tmp_path / "custom_outlook_auths"
|
||||
custom.mkdir()
|
||||
(custom / "outlook-env.json").write_text(
|
||||
_json.dumps(_auth(email="env@outlook.com")), encoding="utf-8"
|
||||
)
|
||||
# A sibling default-named dir stays untouched — confirms we read custom only.
|
||||
default = tmp_path / "outlook_auths"
|
||||
default.mkdir()
|
||||
(default / "outlook-default.json").write_text(
|
||||
_json.dumps(_auth(email="default@outlook.com")), encoding="utf-8"
|
||||
)
|
||||
|
||||
monkeypatch.setattr(
|
||||
routes_ops, "get_settings", lambda: SimpleNamespace(project_root=tmp_path)
|
||||
)
|
||||
monkeypatch.setenv("OUTLOOK_AUTHS_DIR", "custom_outlook_auths")
|
||||
|
||||
resp = routes_ops.api_list_outlook_accounts()
|
||||
assert resp["dir"] == "custom_outlook_auths"
|
||||
assert resp["count"] == 1
|
||||
assert resp["accounts"][0]["email"] == "env@outlook.com"
|
||||
@@ -0,0 +1,559 @@
|
||||
"""Browser-free tests for the Outlook OAuth refresh-token state machine.
|
||||
|
||||
Uses asyncio.run (repo convention; pytest-asyncio is not a project dependency).
|
||||
All emails, passwords, proxies and tokens here are synthetic placeholders.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from register_core.providers import outlook_oauth
|
||||
from register_core.providers.outlook_oauth import (
|
||||
ACCOUNT_TYPE_TILE,
|
||||
AUTHORIZE_ERROR,
|
||||
CONSENT_ACCEPT,
|
||||
KMSI_DENY,
|
||||
LOGIN_EMAIL,
|
||||
LOGIN_PASSWORD,
|
||||
PRIMARY_SUBMIT,
|
||||
PROOF_INPUT,
|
||||
PROTECT_ACCOUNT,
|
||||
PUBLIC_CLIENT_ID,
|
||||
OAuthStateMachine,
|
||||
OAuthTokenResult,
|
||||
OutlookOAuthConfig,
|
||||
extract_code,
|
||||
)
|
||||
|
||||
SYNTHETIC_EMAIL = "synthetic@outlook.com"
|
||||
SYNTHETIC_PASSWORD = "synthetic-password"
|
||||
SYNTHETIC_PROXY = "http://127.0.0.1:1"
|
||||
SYNTHETIC_CALLBACK = "https://localhost/?code=synthetic-code"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# fakes
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
class _FakeLocator:
|
||||
def __init__(self, page: "_FakePage", selector: str) -> None:
|
||||
self._page = page
|
||||
self._selector = selector
|
||||
|
||||
@property
|
||||
def first(self) -> "_FakeLocator":
|
||||
return self
|
||||
|
||||
async def is_visible(self) -> bool:
|
||||
return self._selector in self._page.visible
|
||||
|
||||
async def click(self) -> None:
|
||||
self._page.clicks.append(self._selector)
|
||||
|
||||
async def fill(self, value: str) -> None:
|
||||
self._page.fills.append((self._selector, value))
|
||||
|
||||
|
||||
class _FakePage:
|
||||
def __init__(self, *, url: str = "https://login.live.com/oauth20", visible=()) -> None:
|
||||
self.url = url
|
||||
self.visible = set(visible)
|
||||
self.clicks: list[str] = []
|
||||
self.fills: list[tuple[str, str]] = []
|
||||
self.gotos: list[str] = []
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
return _FakeLocator(self, selector)
|
||||
|
||||
async def goto(self, url: str) -> None:
|
||||
self.gotos.append(url)
|
||||
|
||||
async def wait_for_timeout(self, _ms: int) -> None:
|
||||
return None
|
||||
|
||||
|
||||
class _FakeResponse:
|
||||
def __init__(self, payload, *, status: int = 200) -> None:
|
||||
self._payload = payload
|
||||
self.status_code = status
|
||||
|
||||
def raise_for_status(self) -> None:
|
||||
if self.status_code >= 400:
|
||||
raise requests.HTTPError(f"status {self.status_code}")
|
||||
|
||||
def json(self):
|
||||
return self._payload
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# extract_code
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_extract_code_accepts_localhost_callback():
|
||||
assert extract_code(SYNTHETIC_CALLBACK) == "synthetic-code"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"url",
|
||||
[
|
||||
"",
|
||||
"https://localhost/",
|
||||
"http://localhost/?code=synthetic-code",
|
||||
"https://evil.example/?code=synthetic-code",
|
||||
"https://localhost.evil.example/?code=synthetic-code",
|
||||
],
|
||||
)
|
||||
def test_extract_code_rejects_non_callback_urls(url):
|
||||
assert extract_code(url) is None
|
||||
|
||||
|
||||
def test_extract_code_returns_only_the_code_parameter():
|
||||
url = (
|
||||
"https://localhost/?code=synthetic-code"
|
||||
"&session_state=synthetic-session&id_token=synthetic-id-token"
|
||||
)
|
||||
code = extract_code(url)
|
||||
assert code == "synthetic-code"
|
||||
assert "synthetic-id-token" not in str(code)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# auth URL
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_build_auth_url_uses_public_client_and_offline_access():
|
||||
url = OutlookOAuthConfig().build_auth_url()
|
||||
assert f"client_id={PUBLIC_CLIENT_ID}" in url
|
||||
assert "offline_access" in url
|
||||
assert "redirect_uri=https%3A%2F%2Flocalhost" in url
|
||||
assert "response_type=code" in url
|
||||
|
||||
|
||||
def test_build_auth_url_prompt_none_only_when_sso_preferred():
|
||||
assert "prompt=none" in OutlookOAuthConfig().build_auth_url(prefer_sso=True)
|
||||
assert "prompt=none" not in OutlookOAuthConfig().build_auth_url(prefer_sso=False)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# redaction
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_redact_reports_presence_but_never_the_token():
|
||||
result = OAuthTokenResult(ok=True, refresh_token="synthetic-refresh", state="refresh_token")
|
||||
view = result.redact()
|
||||
assert view["has_refresh_token"] is True
|
||||
assert "refresh_token" not in view
|
||||
assert "synthetic-refresh" not in repr(view)
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# state detection
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("visible", "expected"),
|
||||
[
|
||||
((CONSENT_ACCEPT,), "consent"),
|
||||
((ACCOUNT_TYPE_TILE,), "account_type"),
|
||||
((PROOF_INPUT,), "proof_verify"),
|
||||
((PROTECT_ACCOUNT,), "protect_account"),
|
||||
((KMSI_DENY,), "kmsi"),
|
||||
((LOGIN_PASSWORD,), "login_password"),
|
||||
((LOGIN_EMAIL,), "login_email"),
|
||||
((PROOF_INPUT, PROTECT_ACCOUNT), "proof_verify"),
|
||||
((AUTHORIZE_ERROR,), "authorize_error"),
|
||||
((), "unknown"),
|
||||
],
|
||||
)
|
||||
def test_state_detection(visible, expected):
|
||||
machine = OAuthStateMachine()
|
||||
page = _FakePage(visible=visible)
|
||||
assert asyncio.run(machine._current_auth_entry_state(page)) == expected
|
||||
|
||||
|
||||
def test_state_detection_without_locator_is_unknown():
|
||||
class _Bare:
|
||||
url = ""
|
||||
|
||||
machine = OAuthStateMachine()
|
||||
assert asyncio.run(machine._current_auth_entry_state(_Bare())) == "unknown"
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# state transitions
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _apply(machine, page, state, *, recovery_session=None):
|
||||
return asyncio.run(
|
||||
machine._apply_state(
|
||||
page,
|
||||
state,
|
||||
full_email=SYNTHETIC_EMAIL,
|
||||
password=SYNTHETIC_PASSWORD,
|
||||
recovery_session=recovery_session,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def test_login_email_state_fills_and_submits():
|
||||
machine = OAuthStateMachine()
|
||||
page = _FakePage(visible=(LOGIN_EMAIL,))
|
||||
assert _apply(machine, page, "login_email") is True
|
||||
assert page.fills == [(LOGIN_EMAIL, SYNTHETIC_EMAIL)]
|
||||
assert page.clicks == [PRIMARY_SUBMIT]
|
||||
|
||||
|
||||
def test_login_password_state_fills_and_submits():
|
||||
machine = OAuthStateMachine()
|
||||
page = _FakePage(visible=(LOGIN_PASSWORD,))
|
||||
assert _apply(machine, page, "login_password") is True
|
||||
assert page.fills == [(LOGIN_PASSWORD, SYNTHETIC_PASSWORD)]
|
||||
assert page.clicks == [PRIMARY_SUBMIT]
|
||||
|
||||
|
||||
def test_kmsi_state_declines_stay_signed_in():
|
||||
machine = OAuthStateMachine()
|
||||
page = _FakePage(visible=(KMSI_DENY,))
|
||||
assert _apply(machine, page, "kmsi") is True
|
||||
assert page.clicks == [KMSI_DENY]
|
||||
|
||||
|
||||
def test_proof_state_without_recovery_session_cannot_advance():
|
||||
machine = OAuthStateMachine()
|
||||
page = _FakePage(visible=(PROOF_INPUT,))
|
||||
assert _apply(machine, page, "proof_verify") is False
|
||||
assert page.fills == []
|
||||
|
||||
|
||||
def test_proof_state_delegates_to_recovery_session(monkeypatch):
|
||||
seen: list[object] = []
|
||||
|
||||
async def fake_verify(page, session, **_kwargs):
|
||||
seen.append(session)
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(outlook_oauth, "verify_bound_email_on_login", fake_verify)
|
||||
machine = OAuthStateMachine()
|
||||
page = _FakePage(visible=(PROOF_INPUT,))
|
||||
sentinel = object()
|
||||
|
||||
assert _apply(machine, page, "proof_verify", recovery_session=sentinel) is True
|
||||
assert seen == [sentinel]
|
||||
# The OAuth machine must not type the account password into a proof form.
|
||||
assert page.fills == []
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# token exchange
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_exchange_code_applies_proxy_to_http_and_https(monkeypatch):
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def post(url, **kwargs):
|
||||
captured.update(kwargs)
|
||||
captured["url"] = url
|
||||
return _FakeResponse({"refresh_token": "synthetic-refresh"})
|
||||
|
||||
monkeypatch.setattr(outlook_oauth.requests, "post", post)
|
||||
machine = OAuthStateMachine()
|
||||
|
||||
machine.exchange_code("synthetic-code", proxy_url=SYNTHETIC_PROXY)
|
||||
|
||||
assert captured["proxies"] == {"http": SYNTHETIC_PROXY, "https": SYNTHETIC_PROXY}
|
||||
assert captured["data"]["grant_type"] == "authorization_code"
|
||||
assert captured["data"]["client_id"] == PUBLIC_CLIENT_ID
|
||||
|
||||
|
||||
def test_exchange_code_omits_proxies_when_direct(monkeypatch):
|
||||
captured: dict[str, object] = {}
|
||||
|
||||
def post(url, **kwargs):
|
||||
captured.update(kwargs)
|
||||
return _FakeResponse({"refresh_token": "synthetic-refresh"})
|
||||
|
||||
monkeypatch.setattr(outlook_oauth.requests, "post", post)
|
||||
OAuthStateMachine().exchange_code("synthetic-code")
|
||||
|
||||
assert captured["proxies"] is None
|
||||
|
||||
|
||||
def test_invalid_grant_is_not_retried(monkeypatch):
|
||||
calls: list[str] = []
|
||||
|
||||
def post(url, **kwargs):
|
||||
calls.append(kwargs["data"]["code"])
|
||||
return _FakeResponse({"error": "invalid_grant"}, status=400)
|
||||
|
||||
monkeypatch.setattr(outlook_oauth.requests, "post", post)
|
||||
machine = OAuthStateMachine(proxy_getter=lambda: SYNTHETIC_PROXY)
|
||||
|
||||
with pytest.raises(requests.HTTPError):
|
||||
machine.exchange_code("synthetic-code", proxy_url=SYNTHETIC_PROXY)
|
||||
|
||||
# A burnt authorization code must never be replayed.
|
||||
assert calls == ["synthetic-code"]
|
||||
|
||||
|
||||
def test_missing_refresh_token_is_not_retried(monkeypatch):
|
||||
calls: list[str] = []
|
||||
|
||||
def post(url, **kwargs):
|
||||
calls.append(kwargs["data"]["code"])
|
||||
return _FakeResponse({"access_token": "synthetic-access"})
|
||||
|
||||
monkeypatch.setattr(outlook_oauth.requests, "post", post)
|
||||
machine = OAuthStateMachine(proxy_getter=lambda: SYNTHETIC_PROXY)
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
machine.exchange_code("synthetic-code")
|
||||
|
||||
assert calls == ["synthetic-code"]
|
||||
|
||||
|
||||
def test_transport_failure_retries_once_with_rotated_proxy(monkeypatch):
|
||||
seen_proxies: list[object] = []
|
||||
|
||||
def post(url, **kwargs):
|
||||
seen_proxies.append(kwargs["proxies"])
|
||||
if len(seen_proxies) == 1:
|
||||
raise requests.ConnectionError("synthetic transport failure")
|
||||
return _FakeResponse({"refresh_token": "synthetic-refresh"})
|
||||
|
||||
monkeypatch.setattr(outlook_oauth.requests, "post", post)
|
||||
rotated = "http://127.0.0.1:2"
|
||||
machine = OAuthStateMachine(proxy_getter=lambda: rotated)
|
||||
|
||||
payload = machine.exchange_code("synthetic-code", proxy_url=SYNTHETIC_PROXY)
|
||||
|
||||
assert payload["refresh_token"] == "synthetic-refresh"
|
||||
assert seen_proxies == [
|
||||
{"http": SYNTHETIC_PROXY, "https": SYNTHETIC_PROXY},
|
||||
{"http": rotated, "https": rotated},
|
||||
]
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# _finish error mapping
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("exc", "error_kind", "state"),
|
||||
[
|
||||
(ValueError("missing_refresh_token"), "token", "exchange_missing_refresh"),
|
||||
(requests.HTTPError("400"), "token", "exchange_rejected"),
|
||||
(requests.ConnectionError("boom"), "proxy", "exchange_transport"),
|
||||
],
|
||||
)
|
||||
def test_finish_maps_exchange_failures(monkeypatch, exc, error_kind, state):
|
||||
machine = OAuthStateMachine()
|
||||
|
||||
def boom(*_args, **_kwargs):
|
||||
raise exc
|
||||
|
||||
monkeypatch.setattr(machine, "exchange_code", boom)
|
||||
result = machine._finish("synthetic-code", proxy_url="")
|
||||
|
||||
assert result.ok is False
|
||||
assert result.error_kind == error_kind
|
||||
assert result.state == state
|
||||
assert result.refresh_token == ""
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# run()
|
||||
# --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_run_returns_refresh_token_without_leaking_it(monkeypatch):
|
||||
def post(url, **kwargs):
|
||||
return _FakeResponse(
|
||||
{"refresh_token": "synthetic-refresh", "access_token": "synthetic-access"}
|
||||
)
|
||||
|
||||
monkeypatch.setattr(outlook_oauth.requests, "post", post)
|
||||
page = _FakePage(url=SYNTHETIC_CALLBACK)
|
||||
machine = OAuthStateMachine()
|
||||
|
||||
result = asyncio.run(
|
||||
machine.run(
|
||||
page,
|
||||
SYNTHETIC_EMAIL,
|
||||
SYNTHETIC_PASSWORD,
|
||||
proxy=SYNTHETIC_PROXY,
|
||||
recovery_session=None,
|
||||
)
|
||||
)
|
||||
|
||||
assert result.ok is True
|
||||
assert result.refresh_token == "synthetic-refresh"
|
||||
assert result.state == "refresh_token"
|
||||
assert "synthetic-refresh" not in repr(result.redact())
|
||||
# A freshly-registered MSA account has no settled SSO cookie, so a silent
|
||||
# prompt=none hop returns AADSTS90013 instead of a code. run() must default
|
||||
# to an interactive authorize (no prompt=none) so the state machine drives
|
||||
# #i0116/#i0118 itself. See test_run_uses_interactive_authorize_by_default.
|
||||
assert page.gotos and "prompt=none" not in page.gotos[0]
|
||||
|
||||
|
||||
def test_run_drives_login_then_callback(monkeypatch):
|
||||
def post(url, **kwargs):
|
||||
return _FakeResponse({"refresh_token": "synthetic-refresh"})
|
||||
|
||||
monkeypatch.setattr(outlook_oauth.requests, "post", post)
|
||||
|
||||
class _LoginPage(_FakePage):
|
||||
async def click_through(self) -> None:
|
||||
return None
|
||||
|
||||
def locator(self, selector: str):
|
||||
locator = super().locator(selector)
|
||||
return locator
|
||||
|
||||
page = _LoginPage(visible=(LOGIN_EMAIL,))
|
||||
|
||||
# After the email form is submitted the identity provider lands on the
|
||||
# localhost callback.
|
||||
original_fill = _FakeLocator.fill
|
||||
|
||||
async def fill_then_redirect(self, value):
|
||||
await original_fill(self, value)
|
||||
self._page.visible = set()
|
||||
self._page.url = SYNTHETIC_CALLBACK
|
||||
|
||||
monkeypatch.setattr(_FakeLocator, "fill", fill_then_redirect)
|
||||
|
||||
result = asyncio.run(
|
||||
machine_run(page, timeout_s=0.01),
|
||||
)
|
||||
|
||||
assert result.ok is True
|
||||
assert page.fills == [(LOGIN_EMAIL, SYNTHETIC_EMAIL)]
|
||||
|
||||
|
||||
def machine_run(page, *, timeout_s: float = 0.01, recovery_session=None):
|
||||
machine = OAuthStateMachine()
|
||||
return machine.run(
|
||||
page,
|
||||
SYNTHETIC_EMAIL,
|
||||
SYNTHETIC_PASSWORD,
|
||||
proxy="",
|
||||
recovery_session=recovery_session,
|
||||
timeout_s=timeout_s,
|
||||
)
|
||||
|
||||
|
||||
def test_run_without_callback_returns_oauth_callback_kind():
|
||||
page = _FakePage(visible=())
|
||||
result = asyncio.run(machine_run(page))
|
||||
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "oauth_callback"
|
||||
assert result.state == "unknown"
|
||||
assert result.refresh_token == ""
|
||||
|
||||
|
||||
def test_run_reports_navigation_failure_without_touching_the_network():
|
||||
class _DeadPage(_FakePage):
|
||||
async def goto(self, url: str) -> None:
|
||||
raise RuntimeError("synthetic navigation failure")
|
||||
|
||||
result = asyncio.run(machine_run(_DeadPage()))
|
||||
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "oauth_callback"
|
||||
assert result.state == "authorize_navigation"
|
||||
|
||||
|
||||
def test_run_uses_interactive_authorize_by_default(monkeypatch):
|
||||
"""run() must NOT send prompt=none for a freshly-registered account.
|
||||
|
||||
A silent hop against an MSA account whose session cookie hasn't settled
|
||||
returns AADSTS90013 (Microsoft "Invalid input received from the user")
|
||||
rather than a redirect to the login forms. The interactive authorize lets
|
||||
the state machine drive #i0116/#i0118 itself. Regression guard for the
|
||||
AADSTS90013 failure seen on the Taipei egress 2026-08-07.
|
||||
"""
|
||||
gotos: list[str] = []
|
||||
|
||||
class _GotoPage(_FakePage):
|
||||
async def goto(self, url: str) -> None:
|
||||
gotos.append(url)
|
||||
await super().goto(url)
|
||||
|
||||
def post(url, **kwargs):
|
||||
return _FakeResponse({"refresh_token": "synthetic-refresh"})
|
||||
|
||||
monkeypatch.setattr(outlook_oauth.requests, "post", post)
|
||||
page = _GotoPage(url=SYNTHETIC_CALLBACK)
|
||||
asyncio.run(machine_run(page))
|
||||
|
||||
assert gotos, "run() must navigate to the authorize URL"
|
||||
assert "prompt=none" not in gotos[0], (
|
||||
"default authorize must be interactive (prompt=none triggers AADSTS90013 "
|
||||
"against a freshly-created unsettled account)"
|
||||
)
|
||||
|
||||
|
||||
def test_run_can_still_request_silent_sso_when_asked(monkeypatch):
|
||||
"""Silent SSO remains available for an already-logged-in reuse path."""
|
||||
gotos: list[str] = []
|
||||
|
||||
class _GotoPage(_FakePage):
|
||||
async def goto(self, url: str) -> None:
|
||||
gotos.append(url)
|
||||
await super().goto(url)
|
||||
|
||||
def post(url, **kwargs):
|
||||
return _FakeResponse({"refresh_token": "synthetic-refresh"})
|
||||
|
||||
monkeypatch.setattr(outlook_oauth.requests, "post", post)
|
||||
page = _GotoPage(url=SYNTHETIC_CALLBACK)
|
||||
machine = OAuthStateMachine()
|
||||
asyncio.run(
|
||||
machine.run(
|
||||
page,
|
||||
SYNTHETIC_EMAIL,
|
||||
SYNTHETIC_PASSWORD,
|
||||
proxy="",
|
||||
recovery_session=None,
|
||||
timeout_s=0.01,
|
||||
prefer_sso=True,
|
||||
)
|
||||
)
|
||||
assert gotos and "prompt=none" in gotos[0]
|
||||
|
||||
|
||||
def test_run_reports_authorize_error_for_aadsts_page():
|
||||
"""An AADSTS error page (e.g. AADSTS90013) must degrade to a named
|
||||
authorize_error state, never the silent 'unknown' that masked the
|
||||
AADSTS90013 failure on the live run 2026-08-07.
|
||||
"""
|
||||
page = _FakePage(visible=(AUTHORIZE_ERROR,))
|
||||
result = asyncio.run(machine_run(page))
|
||||
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "oauth_callback"
|
||||
assert result.state == "authorize_error"
|
||||
assert result.refresh_token == ""
|
||||
|
||||
|
||||
def test_run_stops_when_proof_is_requested_without_recovery_session():
|
||||
page = _FakePage(visible=(PROOF_INPUT,))
|
||||
result = asyncio.run(machine_run(page))
|
||||
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "oauth_callback"
|
||||
assert result.state == "proof_verify"
|
||||
@@ -0,0 +1,689 @@
|
||||
import asyncio
|
||||
import json
|
||||
import stat
|
||||
from pathlib import Path
|
||||
|
||||
from register_core.contracts import RegisterResult
|
||||
from register_core.providers.outlook_adapter import OutlookProvider
|
||||
|
||||
|
||||
def test_provider_has_required_protocol_shape():
|
||||
provider = OutlookProvider(config={})
|
||||
assert provider.name == "outlook"
|
||||
assert callable(provider.register_one)
|
||||
|
||||
|
||||
def test_live_browser_is_disabled_by_default(monkeypatch):
|
||||
monkeypatch.delenv("GROK_REGISTER_OUTLOOK_LIVE", raising=False)
|
||||
result = OutlookProvider(config={}).register_one(email_source=None, extra={})
|
||||
assert isinstance(result, RegisterResult)
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "provider"
|
||||
assert "live gate" in result.error.lower()
|
||||
|
||||
|
||||
def test_live_on_missing_proxy_returns_proxy_error_without_browser(monkeypatch):
|
||||
monkeypatch.setenv("GROK_REGISTER_OUTLOOK_LIVE", "1")
|
||||
result = OutlookProvider(config={}).register_one(email_source=None, extra={})
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "proxy"
|
||||
assert "proxy" in result.error.lower()
|
||||
|
||||
|
||||
def test_live_on_blank_or_non_string_proxy_returns_proxy_error(monkeypatch):
|
||||
monkeypatch.setenv("GROK_REGISTER_OUTLOOK_LIVE", "1")
|
||||
provider = OutlookProvider(config={})
|
||||
for bad in ("", " ", "\t", None, 123, {"server": "http://x"}):
|
||||
result = provider.register_one(email_source=None, extra={"proxy": bad})
|
||||
assert result.ok is False, bad
|
||||
assert result.error_kind == "proxy", bad
|
||||
assert "proxy" in result.error.lower(), bad
|
||||
|
||||
|
||||
def test_live_on_active_event_loop_rejects_without_nested_run(monkeypatch):
|
||||
monkeypatch.setenv("GROK_REGISTER_OUTLOOK_LIVE", "1")
|
||||
provider = OutlookProvider(config={})
|
||||
|
||||
async def _inside_loop():
|
||||
return provider.register_one(
|
||||
email_source=None,
|
||||
extra={"proxy": "http://127.0.0.1:7890"},
|
||||
)
|
||||
|
||||
result = asyncio.run(_inside_loop())
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "provider"
|
||||
assert "event loop" in result.error.lower()
|
||||
|
||||
|
||||
def test_disabled_provider_never_allocates_mailbox(monkeypatch):
|
||||
monkeypatch.delenv("GROK_REGISTER_OUTLOOK_LIVE", raising=False)
|
||||
|
||||
class _Source:
|
||||
def allocate(self):
|
||||
raise AssertionError("must not allocate while live gate is off")
|
||||
|
||||
result = OutlookProvider(config={}).register_one(
|
||||
email_source=_Source(), extra={}
|
||||
)
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "provider"
|
||||
|
||||
|
||||
# --- Orchestration-level tests with browser/flow/oauth stubbed ----------------
|
||||
#
|
||||
# These exercise _register_one_async end-to-end (recovery release, artifact
|
||||
# sink) WITHOUT patchright: each collaborator is replaced in the ADAPTER module
|
||||
# namespace, and OutlookBrowser.open yields a fake session whose context manager
|
||||
# never imports the browser stack. All values below are synthetic.
|
||||
|
||||
from contextlib import asynccontextmanager # noqa: E402
|
||||
|
||||
from register_core.providers import outlook_adapter as adapter_mod # noqa: E402
|
||||
from register_core.providers.outlook_browser import ( # noqa: E402
|
||||
OutlookBrowser as _RealOutlookBrowser,
|
||||
OutlookRegistrationFlow as _RealFlow,
|
||||
RegistrationPageResult,
|
||||
OutlookBrowserConfig,
|
||||
)
|
||||
from register_core.providers.outlook_oauth import ( # noqa: E402
|
||||
OAuthStateMachine as _RealOAuth,
|
||||
OAuthTokenResult,
|
||||
OutlookOAuthConfig,
|
||||
)
|
||||
from register_core.providers.outlook_recovery import RecoverySession # noqa: E402
|
||||
|
||||
|
||||
class _FakeSession:
|
||||
def __init__(self):
|
||||
self.page = type("Page", (), {"url": "https://login.live.com/"})()
|
||||
self.browser = object()
|
||||
|
||||
|
||||
class _FakeSource:
|
||||
name = "cf_temp"
|
||||
|
||||
def __init__(self):
|
||||
self.released = []
|
||||
|
||||
def release(self, mailbox, *, success):
|
||||
self.released.append((mailbox, success))
|
||||
|
||||
|
||||
def _install_fake_browser(monkeypatch, session):
|
||||
class _FakeBrowser:
|
||||
def __init__(self, config):
|
||||
self.config = config
|
||||
|
||||
@asynccontextmanager
|
||||
async def open(self, proxy=None):
|
||||
yield session
|
||||
|
||||
monkeypatch.setattr(adapter_mod, "OutlookBrowser", _FakeBrowser)
|
||||
|
||||
|
||||
def _install_fake_flow(monkeypatch, registration_result):
|
||||
class _FakeFlow:
|
||||
async def register(self, page, email, password, *, captcha_strategy):
|
||||
return registration_result
|
||||
|
||||
monkeypatch.setattr(adapter_mod, "OutlookRegistrationFlow", _FakeFlow)
|
||||
|
||||
|
||||
def _install_fake_recovery(monkeypatch, mailbox_address, bound, source):
|
||||
recovery = RecoverySession(
|
||||
mailbox=type("M", (), {"address": mailbox_address})(),
|
||||
source=source,
|
||||
bound=bound,
|
||||
)
|
||||
|
||||
async def _fake_bind(page, source, *, timeout_seconds=90):
|
||||
return recovery
|
||||
|
||||
monkeypatch.setattr(adapter_mod, "bind_recovery_email", _fake_bind)
|
||||
return recovery
|
||||
|
||||
|
||||
def _install_fake_oauth(monkeypatch, result):
|
||||
class _FakeOAuth:
|
||||
def __init__(self, *, config=None):
|
||||
self.config = config
|
||||
|
||||
async def run(self, page, email, password, *, proxy="", recovery_session=None, timeout_s=20.0):
|
||||
return result
|
||||
|
||||
monkeypatch.setattr(adapter_mod, "OAuthStateMachine", _FakeOAuth)
|
||||
|
||||
|
||||
def _install_fake_temp_source(monkeypatch):
|
||||
class _FakeTemp:
|
||||
@classmethod
|
||||
def from_options(cls, opts):
|
||||
return cls()
|
||||
|
||||
monkeypatch.setattr(adapter_mod, "TempMailSource", _FakeTemp)
|
||||
|
||||
|
||||
def _orchestration_provider(tmp_path):
|
||||
return OutlookProvider(
|
||||
config={
|
||||
"outlook_auths_dir": str(tmp_path / "auths"),
|
||||
"bind_recovery_email": True,
|
||||
"captcha_strategy": 0,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def test_releases_recovery_mailbox_on_oauth_failure(monkeypatch, tmp_path):
|
||||
monkeypatch.setenv("GROK_REGISTER_OUTLOOK_LIVE", "1")
|
||||
_install_fake_browser(monkeypatch, _FakeSession())
|
||||
_install_fake_flow(
|
||||
monkeypatch, RegistrationPageResult(ok=True) # no captcha, form advanced
|
||||
)
|
||||
source = _FakeSource()
|
||||
_install_fake_recovery(
|
||||
monkeypatch,
|
||||
mailbox_address="recovery@invalid",
|
||||
bound=True,
|
||||
source=source,
|
||||
)
|
||||
_install_fake_oauth(
|
||||
monkeypatch,
|
||||
OAuthTokenResult(
|
||||
ok=False,
|
||||
refresh_token="",
|
||||
error_kind="token",
|
||||
state="exchange_rejected",
|
||||
),
|
||||
)
|
||||
_install_fake_temp_source(monkeypatch)
|
||||
|
||||
provider = _orchestration_provider(tmp_path)
|
||||
result = provider.register_one(
|
||||
email_source=None, extra={"proxy": "http://synthetic.invalid"}
|
||||
)
|
||||
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "token"
|
||||
# The finally block releases the recovery mailbox with success=False.
|
||||
assert len(source.released) == 1
|
||||
_mailbox, success = source.released[0]
|
||||
assert success is False
|
||||
# No artifact written on the failure path.
|
||||
assert list((tmp_path / "auths").glob("*.json")) == []
|
||||
|
||||
|
||||
def test_success_writes_0600_artifact_and_redacts_public(monkeypatch, tmp_path):
|
||||
monkeypatch.setenv("GROK_REGISTER_OUTLOOK_LIVE", "1")
|
||||
_install_fake_browser(monkeypatch, _FakeSession())
|
||||
_install_fake_flow(monkeypatch, RegistrationPageResult(ok=True))
|
||||
source = _FakeSource()
|
||||
_install_fake_recovery(
|
||||
monkeypatch,
|
||||
mailbox_address="recovery@invalid",
|
||||
bound=True,
|
||||
source=source,
|
||||
)
|
||||
_install_fake_oauth(
|
||||
monkeypatch,
|
||||
OAuthTokenResult(
|
||||
ok=True,
|
||||
refresh_token="synthetic-refresh",
|
||||
state="refresh_token",
|
||||
),
|
||||
)
|
||||
_install_fake_temp_source(monkeypatch)
|
||||
|
||||
provider = _orchestration_provider(tmp_path)
|
||||
result = provider.register_one(
|
||||
email_source=None, extra={"proxy": "http://synthetic.invalid"}
|
||||
)
|
||||
|
||||
assert result.ok is True
|
||||
assert result.provider == "outlook"
|
||||
assert result.secret_kind == "refresh_token"
|
||||
assert result.secret == "synthetic-refresh"
|
||||
|
||||
artifact = Path(result.artifacts["outlook_auth_path"])
|
||||
assert artifact.exists()
|
||||
assert stat.S_IMODE(artifact.stat().st_mode) == 0o600
|
||||
body = json.loads(artifact.read_text(encoding="utf-8"))
|
||||
assert body["refresh_token"] == "synthetic-refresh"
|
||||
assert body["bound"] is True
|
||||
assert body["recovery_email"] == "recovery@invalid"
|
||||
assert "synthetic-refresh" not in json.dumps(result.to_public_dict())
|
||||
assert source.released and source.released[0][1] is True
|
||||
|
||||
|
||||
def _install_oauth_that_raises(monkeypatch, exc):
|
||||
"""OAuth stub whose run() raises — simulating a terminal token rejection
|
||||
(ValueError, e.g. missing_refresh_token after a burnt auth code) or a
|
||||
typed register-core error the pipeline must classify upstream."""
|
||||
|
||||
class _RaisingOAuth:
|
||||
def __init__(self, *, config=None):
|
||||
self.config = config
|
||||
|
||||
async def run(self, page, email, password, *, proxy="", recovery_session=None, timeout_s=20.0):
|
||||
raise exc
|
||||
|
||||
monkeypatch.setattr(adapter_mod, "OAuthStateMachine", _RaisingOAuth)
|
||||
|
||||
|
||||
def test_oauth_value_error_is_classified_as_token_not_raised(monkeypatch, tmp_path):
|
||||
"""A ValueError from the OAuth state machine (e.g. missing_refresh_token)
|
||||
is a terminal token rejection, NOT a RegisterCoreError. Without the
|
||||
classifier it would escape the pipeline's typed handlers and abort the
|
||||
batch. register_one must convert it to error_kind="token"."""
|
||||
import pytest
|
||||
|
||||
monkeypatch.setenv("GROK_REGISTER_OUTLOOK_LIVE", "1")
|
||||
_install_fake_browser(monkeypatch, _FakeSession())
|
||||
_install_fake_flow(monkeypatch, RegistrationPageResult(ok=True))
|
||||
source = _FakeSource()
|
||||
_install_fake_recovery(
|
||||
monkeypatch, mailbox_address="recovery@invalid", bound=True, source=source
|
||||
)
|
||||
_install_oauth_that_raises(monkeypatch, ValueError("missing_refresh_token"))
|
||||
_install_fake_temp_source(monkeypatch)
|
||||
|
||||
provider = _orchestration_provider(tmp_path)
|
||||
result = provider.register_one(
|
||||
email_source=None, extra={"proxy": "http://synthetic.invalid"}
|
||||
)
|
||||
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "token"
|
||||
assert "missing_refresh_token" in (result.error or "")
|
||||
# No artifact on the failure path.
|
||||
assert list((tmp_path / "auths").glob("*.json")) == []
|
||||
# Recovery mailbox still released with success=False in the finally.
|
||||
assert source.released and source.released[0][1] is False
|
||||
|
||||
|
||||
def test_config_value_error_is_classified_as_provider_not_token(monkeypatch, tmp_path):
|
||||
"""A ValueError raised by config validation (e.g. bad captcha_strategy in
|
||||
schema.outlook_options) is a provider/config problem, NOT a terminal token
|
||||
rejection. The outer except ValueError must NOT bucket it as 'token' — ops
|
||||
must see the real provider bucket. Only the missing_refresh_token sentinel
|
||||
is token. (Regression for the prior blanket ValueError->token.)"""
|
||||
monkeypatch.setenv("GROK_REGISTER_OUTLOOK_LIVE", "1")
|
||||
provider = OutlookProvider(
|
||||
config={
|
||||
"outlook_auths_dir": str(tmp_path / "auths"),
|
||||
"bind_recovery_email": True,
|
||||
"captcha_strategy": 7, # invalid -> ValueError inside _register_one_async
|
||||
}
|
||||
)
|
||||
result = provider.register_one(
|
||||
email_source=None, extra={"proxy": "http://synthetic.invalid"}
|
||||
)
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "provider"
|
||||
assert "captcha_strategy" in (result.error or "")
|
||||
|
||||
|
||||
def test_runtime_error_with_credentialed_proxy_is_scrubbed(monkeypatch, tmp_path):
|
||||
"""If a patchright/Chromium launch failure embeds the credentialed proxy URL
|
||||
into the RuntimeError text, RegisterResult.error must NOT carry the proxy
|
||||
username/password. Defense-in-depth for cannot-verify-from-diff finding."""
|
||||
proxy_with_creds = "http://u:sekret@10.0.0.5:7890"
|
||||
leaked_format = "patchright launch failed: server " + proxy_with_creds + " refused"
|
||||
|
||||
class _BoomBrowser:
|
||||
def __init__(self, config):
|
||||
self.config = config
|
||||
|
||||
@asynccontextmanager
|
||||
async def open(self, proxy=None):
|
||||
raise RuntimeError(leaked_format)
|
||||
yield # noqa: unreachable
|
||||
|
||||
monkeypatch.setattr(adapter_mod, "OutlookBrowser", _BoomBrowser)
|
||||
monkeypatch.setenv("GROK_REGISTER_OUTLOOK_LIVE", "1")
|
||||
provider = OutlookProvider(
|
||||
config={"outlook_auths_dir": str(tmp_path / "auths")}
|
||||
)
|
||||
result = provider.register_one(
|
||||
email_source=None, extra={"proxy": proxy_with_creds}
|
||||
)
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "provider"
|
||||
err = result.error or ""
|
||||
assert "sekret" not in err, err
|
||||
assert proxy_with_creds not in err, err
|
||||
# Host is still diagnosable; only userinfo was redacted.
|
||||
assert "10.0.0.5:7890" in err, err
|
||||
|
||||
|
||||
def test_value_error_with_credentialed_proxy_is_scrubbed(monkeypatch, tmp_path):
|
||||
"""Same scrub applies on the ValueError path."""
|
||||
proxy_with_creds = "https://alice:hunter2@gw.example:443"
|
||||
|
||||
class _BoomBrowser:
|
||||
def __init__(self, config):
|
||||
self.config = config
|
||||
|
||||
@asynccontextmanager
|
||||
async def open(self, proxy=None):
|
||||
raise ValueError("bad config near " + proxy_with_creds)
|
||||
yield # noqa: unreachable
|
||||
|
||||
monkeypatch.setattr(adapter_mod, "OutlookBrowser", _BoomBrowser)
|
||||
monkeypatch.setenv("GROK_REGISTER_OUTLOOK_LIVE", "1")
|
||||
provider = OutlookProvider(
|
||||
config={"outlook_auths_dir": str(tmp_path / "auths")}
|
||||
)
|
||||
result = provider.register_one(
|
||||
email_source=None, extra={"proxy": proxy_with_creds}
|
||||
)
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "provider" # not the token sentinel
|
||||
err = result.error or ""
|
||||
assert "hunter2" not in err, err
|
||||
assert proxy_with_creds not in err, err
|
||||
|
||||
|
||||
def test_register_core_error_propagates_for_pipeline_classification(monkeypatch, tmp_path):
|
||||
"""MailMissError / FailFastError / ProviderError are RegisterCoreError
|
||||
subclasses the PIPELINE classifies (mail_miss retry, fatal stop, provider
|
||||
terminal). register_one must NOT swallow them — if it returned a plain
|
||||
RegisterResult the pipeline would lose the mail-miss retry classification.
|
||||
They propagate (here via asyncio.run re-raise); the ValueError classifier
|
||||
must not intercept them."""
|
||||
import pytest
|
||||
|
||||
from register_core.errors import FailFastError, MailMissError, ProviderError
|
||||
|
||||
for exc, _label in (
|
||||
(ProviderError("recovery_submit_failed"), "provider"),
|
||||
(MailMissError("mail_miss"), "mail_miss"),
|
||||
(FailFastError("captcha_infra_dead"), "fatal"),
|
||||
):
|
||||
monkeypatch.setenv("GROK_REGISTER_OUTLOOK_LIVE", "1")
|
||||
_install_fake_browser(monkeypatch, _FakeSession())
|
||||
_install_fake_flow(monkeypatch, RegistrationPageResult(ok=True))
|
||||
source = _FakeSource()
|
||||
_install_fake_recovery(
|
||||
monkeypatch, mailbox_address="recovery@invalid", bound=True, source=source
|
||||
)
|
||||
# Recovery bind happens before oauth.run; raise from recovery instead
|
||||
# so the typed error originates from the orchestration path.
|
||||
|
||||
async def _raising_bind(page, source_arg, *, timeout_seconds=90):
|
||||
raise exc
|
||||
|
||||
monkeypatch.setattr(adapter_mod, "bind_recovery_email", _raising_bind)
|
||||
_install_fake_temp_source(monkeypatch)
|
||||
|
||||
provider = _orchestration_provider(tmp_path)
|
||||
with pytest.raises(type(exc)):
|
||||
provider.register_one(
|
||||
email_source=None, extra={"proxy": "http://synthetic.invalid"}
|
||||
)
|
||||
# Still no artifact written when it raises.
|
||||
assert list((tmp_path / "auths").glob("*.json")) == []
|
||||
|
||||
|
||||
def test_fun_captcha_failure_releases_recovery_never_allocated(monkeypatch, tmp_path):
|
||||
"""FunCaptcha is detected before recovery binding, so no mailbox to release."""
|
||||
monkeypatch.setenv("GROK_REGISTER_OUTLOOK_LIVE", "1")
|
||||
_install_fake_browser(monkeypatch, _FakeSession())
|
||||
_install_fake_flow(
|
||||
monkeypatch,
|
||||
RegistrationPageResult(
|
||||
ok=False, error_kind="captcha", error="FunCaptcha",
|
||||
fun_captcha_seen=True,
|
||||
),
|
||||
)
|
||||
|
||||
class _ExplodingSource:
|
||||
def release(self, mailbox, *, success):
|
||||
raise AssertionError("no mailbox allocated; release must not run")
|
||||
|
||||
monkeypatch.setattr(
|
||||
adapter_mod, "bind_recovery_email",
|
||||
lambda *a, **k: (_ for _ in ()).throw(AssertionError("must not bind")),
|
||||
)
|
||||
_install_fake_temp_source(monkeypatch)
|
||||
|
||||
provider = _orchestration_provider(tmp_path)
|
||||
result = provider.register_one(
|
||||
email_source=None, extra={"proxy": "http://synthetic.invalid"}
|
||||
)
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "captcha"
|
||||
assert list((tmp_path / "auths").glob("*.json")) == []
|
||||
|
||||
|
||||
def test_captcha_bridge_strategy2_manual_handoff_headless_returns_immediately(
|
||||
monkeypatch, tmp_path
|
||||
):
|
||||
"""captcha_frame_seen + strategy 2 + headless → manual_handoff, no wait, no bridge."""
|
||||
monkeypatch.setenv("GROK_REGISTER_OUTLOOK_LIVE", "1")
|
||||
_install_fake_browser(monkeypatch, _FakeSession())
|
||||
_install_fake_flow(
|
||||
monkeypatch,
|
||||
RegistrationPageResult(
|
||||
ok=False, error_kind="captcha", error="manual",
|
||||
captcha_frame_seen=True,
|
||||
),
|
||||
)
|
||||
|
||||
async def _no_solve(*a, **k):
|
||||
raise AssertionError("manual handoff must not invoke the bridge")
|
||||
|
||||
class _NoBridge:
|
||||
async def solve(self, *a, **k):
|
||||
return await _no_solve(*a, **k)
|
||||
|
||||
monkeypatch.setattr(adapter_mod, "OutlookCaptchaBridge", _NoBridge)
|
||||
_install_fake_recovery(
|
||||
monkeypatch,
|
||||
mailbox_address="recovery@invalid", bound=True, source=_FakeSource(),
|
||||
)
|
||||
provider = OutlookProvider(
|
||||
config={
|
||||
"outlook_auths_dir": str(tmp_path / "auths"),
|
||||
"bind_recovery_email": False,
|
||||
"captcha_strategy": 2,
|
||||
"headless": True,
|
||||
}
|
||||
)
|
||||
result = provider.register_one(
|
||||
email_source=None, extra={"proxy": "http://synthetic.invalid"}
|
||||
)
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "captcha"
|
||||
assert result.error == "manual_handoff"
|
||||
assert result.artifacts.get("outlook_steps") == ["register"]
|
||||
|
||||
|
||||
# --- strategy 2 interactive manual-wait (headed) -----------------------------
|
||||
|
||||
|
||||
class _CountdownLocator:
|
||||
"""count() returns from a scripted sequence, then stays at the last value.
|
||||
|
||||
Simulates the captcha iframe detaching after the operator solves it: each
|
||||
poll consumes the next value; when the script is exhausted the locator
|
||||
stays detached (0).
|
||||
"""
|
||||
|
||||
def __init__(self, counts):
|
||||
self._counts = list(counts)
|
||||
|
||||
async def count(self):
|
||||
if len(self._counts) > 1:
|
||||
return self._counts.pop(0)
|
||||
return self._counts[0]
|
||||
|
||||
|
||||
class _HandoffPage:
|
||||
"""Page stub for manual_handoff_wait: only the two captcha selectors matter."""
|
||||
|
||||
def __init__(self, enforcement_counts, challenge_counts):
|
||||
self._enforcement = _CountdownLocator(enforcement_counts)
|
||||
self._challenge = _CountdownLocator(challenge_counts)
|
||||
|
||||
def locator(self, selector):
|
||||
if selector == "iframe#enforcementFrame":
|
||||
return self._enforcement
|
||||
if 'title="验证质询"' in selector:
|
||||
return self._challenge
|
||||
raise AssertionError(f"unexpected selector {selector}")
|
||||
|
||||
|
||||
def test_manual_handoff_wait_returns_true_when_iframes_detach():
|
||||
from register_core.providers.outlook_adapter import manual_handoff_wait
|
||||
|
||||
# enforcement: present, present, gone. challenge: present, gone, gone.
|
||||
page = _HandoffPage([1, 1, 0], [1, 0, 0])
|
||||
cleared = asyncio.run(
|
||||
manual_handoff_wait(page, timeout_s=10.0, poll_s=0.01)
|
||||
)
|
||||
assert cleared is True
|
||||
|
||||
|
||||
def test_manual_handoff_wait_times_out_when_iframe_stays():
|
||||
from register_core.providers.outlook_adapter import manual_handoff_wait
|
||||
|
||||
page = _HandoffPage([1], [0])
|
||||
cleared = asyncio.run(
|
||||
manual_handoff_wait(page, timeout_s=0.05, poll_s=0.01)
|
||||
)
|
||||
assert cleared is False
|
||||
|
||||
|
||||
def test_strategy2_headed_waits_then_proceeds_to_oauth(monkeypatch, tmp_path):
|
||||
"""headed + strategy 2 + captcha → wait (iframe detaches) → OAuth runs →
|
||||
artifact written. This is the live operator path: solve the FunCaptcha in
|
||||
the open browser window, registration completes automatically."""
|
||||
monkeypatch.setenv("GROK_REGISTER_OUTLOOK_LIVE", "1")
|
||||
_install_fake_browser(monkeypatch, _FakeSession())
|
||||
_install_fake_flow(
|
||||
monkeypatch,
|
||||
RegistrationPageResult(
|
||||
ok=False, error_kind="captcha", error="manual handoff",
|
||||
captcha_frame_seen=True,
|
||||
),
|
||||
)
|
||||
|
||||
async def _wait_succeeds(page, *, timeout_s, poll_s=2.0):
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(adapter_mod, "manual_handoff_wait", _wait_succeeds)
|
||||
_install_fake_oauth(
|
||||
monkeypatch,
|
||||
OAuthTokenResult(ok=True, refresh_token="synthetic-rt", state="refresh_token"),
|
||||
)
|
||||
_install_fake_temp_source(monkeypatch)
|
||||
|
||||
provider = OutlookProvider(
|
||||
config={
|
||||
"outlook_auths_dir": str(tmp_path / "auths"),
|
||||
"bind_recovery_email": False,
|
||||
"captcha_strategy": 2,
|
||||
"headless": False,
|
||||
}
|
||||
)
|
||||
result = provider.register_one(
|
||||
email_source=None, extra={"proxy": "http://synthetic.invalid"}
|
||||
)
|
||||
assert result.ok is True
|
||||
assert result.secret == "synthetic-rt"
|
||||
assert result.secret_kind == "refresh_token"
|
||||
artifact = Path(result.artifacts["outlook_auth_path"])
|
||||
assert artifact.exists()
|
||||
body = json.loads(artifact.read_text(encoding="utf-8"))
|
||||
assert body["refresh_token"] == "synthetic-rt"
|
||||
assert result.artifacts["outlook_steps"] == [
|
||||
"register", "manual_captcha", "oauth",
|
||||
]
|
||||
|
||||
|
||||
def test_strategy2_headed_wait_timeout_returns_manual_handoff_timeout(
|
||||
monkeypatch, tmp_path
|
||||
):
|
||||
"""headed + strategy 2 + captcha, operator never solves → bounded timeout
|
||||
failure, no OAuth call, no artifact."""
|
||||
monkeypatch.setenv("GROK_REGISTER_OUTLOOK_LIVE", "1")
|
||||
_install_fake_browser(monkeypatch, _FakeSession())
|
||||
_install_fake_flow(
|
||||
monkeypatch,
|
||||
RegistrationPageResult(
|
||||
ok=False, error_kind="captcha", error="manual handoff",
|
||||
captcha_frame_seen=True,
|
||||
),
|
||||
)
|
||||
|
||||
async def _wait_times_out(page, *, timeout_s, poll_s=2.0):
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(adapter_mod, "manual_handoff_wait", _wait_times_out)
|
||||
|
||||
class _NoOAuth:
|
||||
def __init__(self, *, config=None):
|
||||
pass
|
||||
|
||||
async def run(self, *a, **k):
|
||||
raise AssertionError("OAuth must not run after handoff timeout")
|
||||
|
||||
monkeypatch.setattr(adapter_mod, "OAuthStateMachine", _NoOAuth)
|
||||
_install_fake_temp_source(monkeypatch)
|
||||
|
||||
provider = OutlookProvider(
|
||||
config={
|
||||
"outlook_auths_dir": str(tmp_path / "auths"),
|
||||
"bind_recovery_email": False,
|
||||
"captcha_strategy": 2,
|
||||
"headless": False,
|
||||
}
|
||||
)
|
||||
result = provider.register_one(
|
||||
email_source=None, extra={"proxy": "http://synthetic.invalid"}
|
||||
)
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "captcha"
|
||||
assert result.error == "manual_handoff_timeout"
|
||||
assert result.artifacts.get("outlook_steps") == ["register", "manual_captcha"]
|
||||
assert list((tmp_path / "auths").glob("*.json")) == []
|
||||
|
||||
|
||||
def test_fun_captcha_headed_also_waits_for_operator(monkeypatch, tmp_path):
|
||||
"""FunCaptcha (enforcementFrame) is the captcha Outlook actually shows; in
|
||||
headed mode the operator solves it in-window, so the wait must cover it
|
||||
too — not just the 验证质询 iframe variant."""
|
||||
monkeypatch.setenv("GROK_REGISTER_OUTLOOK_LIVE", "1")
|
||||
_install_fake_browser(monkeypatch, _FakeSession())
|
||||
_install_fake_flow(
|
||||
monkeypatch,
|
||||
RegistrationPageResult(
|
||||
ok=False, error_kind="captcha", error="FunCaptcha enforcement frame",
|
||||
fun_captcha_seen=True,
|
||||
),
|
||||
)
|
||||
|
||||
async def _wait_succeeds(page, *, timeout_s, poll_s=2.0):
|
||||
return True
|
||||
|
||||
monkeypatch.setattr(adapter_mod, "manual_handoff_wait", _wait_succeeds)
|
||||
_install_fake_oauth(
|
||||
monkeypatch,
|
||||
OAuthTokenResult(ok=True, refresh_token="synthetic-rt", state="refresh_token"),
|
||||
)
|
||||
_install_fake_temp_source(monkeypatch)
|
||||
|
||||
provider = OutlookProvider(
|
||||
config={
|
||||
"outlook_auths_dir": str(tmp_path / "auths"),
|
||||
"bind_recovery_email": False,
|
||||
"captcha_strategy": 2,
|
||||
"headless": False,
|
||||
}
|
||||
)
|
||||
result = provider.register_one(
|
||||
email_source=None, extra={"proxy": "http://synthetic.invalid"}
|
||||
)
|
||||
assert result.ok is True
|
||||
assert result.secret == "synthetic-rt"
|
||||
@@ -0,0 +1,40 @@
|
||||
import pytest
|
||||
|
||||
from register_core.config.schema import ProviderSpec
|
||||
from register_core.providers.registry import get_provider
|
||||
|
||||
|
||||
def test_outlook_aliases_resolve_to_the_same_provider():
|
||||
providers = [get_provider(name, config={}) for name in ("outlook", "microsoft", "hotmail", "msa")]
|
||||
assert {provider.name for provider in providers} == {"outlook"}
|
||||
|
||||
|
||||
def test_outlook_options_are_non_secret_config():
|
||||
spec = ProviderSpec(
|
||||
name="outlook",
|
||||
options={
|
||||
"client_id": "synthetic-client-id",
|
||||
"captcha_strategy": 2,
|
||||
"temp_mail": {"base_url": "https://mail.invalid", "domain": "invalid"},
|
||||
"email_suffix": "@outlook.com",
|
||||
"bind_recovery_email": False,
|
||||
"outlook_auths_dir": "./outlook-auths",
|
||||
},
|
||||
)
|
||||
assert spec.name == "outlook"
|
||||
assert spec.options["captcha_strategy"] == 2
|
||||
|
||||
|
||||
def test_outlook_options_reject_inline_secret_values():
|
||||
spec = ProviderSpec(name="outlook", options={"password": "synthetic-password"})
|
||||
with pytest.raises(ValueError, match="secret"):
|
||||
spec.outlook_options()
|
||||
|
||||
|
||||
def test_outlook_options_reject_nested_temp_mail_secret_values():
|
||||
spec = ProviderSpec(
|
||||
name="outlook",
|
||||
options={"temp_mail": {"admin_password": "synthetic-admin"}},
|
||||
)
|
||||
with pytest.raises(ValueError, match="temp_mail.admin_password"):
|
||||
spec.outlook_options()
|
||||
@@ -0,0 +1,228 @@
|
||||
"""Unit tests for Outlook recovery binding and login proof reuse (Task 7).
|
||||
|
||||
Browser-free: pages are fakes, no patchright/Playwright launch, no real account.
|
||||
Uses asyncio.run (repo convention; pytest-asyncio is not a project dependency).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
from register_core.contracts import Mailbox, OtpCode, OtpWaitDiagnostics
|
||||
from register_core.errors import MailMissError, ProviderError
|
||||
from register_core.providers.outlook_recovery import (
|
||||
RecoverySession,
|
||||
bind_recovery_email,
|
||||
verify_bound_email_on_login,
|
||||
)
|
||||
|
||||
|
||||
class _FakeLocator:
|
||||
def __init__(self, page, selector):
|
||||
self._page = page
|
||||
self._selector = selector
|
||||
|
||||
@property
|
||||
def first(self):
|
||||
return self
|
||||
|
||||
async def is_visible(self):
|
||||
return self._selector in self._page.visible
|
||||
|
||||
async def fill(self, value):
|
||||
self._page.filled.append((self._selector, value))
|
||||
|
||||
async def click(self):
|
||||
self._page.clicked.append(self._selector)
|
||||
|
||||
|
||||
class _FakePage:
|
||||
"""Minimal page exposing only locator(), like the real Playwright surface."""
|
||||
|
||||
def __init__(self, visible=()):
|
||||
self.visible = set(visible)
|
||||
self.filled: list[tuple[str, str]] = []
|
||||
self.clicked: list[str] = []
|
||||
|
||||
def locator(self, selector):
|
||||
# Comma-joined selectors are visible when any single member is.
|
||||
if "," in selector:
|
||||
for part in (p.strip() for p in selector.split(",")):
|
||||
if part in self.visible:
|
||||
return _FakeLocator(self, part)
|
||||
return _FakeLocator(self, selector)
|
||||
|
||||
|
||||
class _Source:
|
||||
name = "cf_temp"
|
||||
|
||||
def __init__(self, code="123456"):
|
||||
self.calls: list[str] = []
|
||||
self.released: list[tuple[str, bool]] = []
|
||||
self._code = code
|
||||
|
||||
def allocate(self):
|
||||
self.calls.append("allocate")
|
||||
return Mailbox(address="throwaway@invalid", token="synthetic-jwt", provider="cf_temp")
|
||||
|
||||
def poll_otp(self, mailbox, **kwargs):
|
||||
self.calls.append("poll")
|
||||
return OtpCode(code=self._code, source="cf_temp")
|
||||
|
||||
def release(self, mailbox, *, success):
|
||||
self.calls.append("release")
|
||||
self.released.append((str(getattr(mailbox, "address", "")), bool(success)))
|
||||
|
||||
|
||||
def test_bound_session_is_reused_without_allocating_new_address():
|
||||
"""A bare page requests no proof: return False and never allocate."""
|
||||
source = _Source()
|
||||
source.allocate = lambda: (_ for _ in ()).throw(AssertionError("must reuse session"))
|
||||
session = RecoverySession(mailbox=object(), source=source, bound=True)
|
||||
page = type("Page", (), {})()
|
||||
|
||||
assert asyncio.run(verify_bound_email_on_login(page, session)) is False
|
||||
assert source.calls == []
|
||||
|
||||
|
||||
def test_proof_challenge_reuses_bound_mailbox():
|
||||
source = _Source()
|
||||
mailbox = Mailbox(address="throwaway@invalid", token="synthetic-jwt", provider="cf_temp")
|
||||
session = RecoverySession(mailbox=mailbox, source=source, bound=True)
|
||||
page = _FakePage(visible={"#iOttText", "#idSIButton9"})
|
||||
|
||||
assert asyncio.run(verify_bound_email_on_login(page, session)) is True
|
||||
assert source.calls == ["poll"] # polled, never allocated
|
||||
assert ("#iOttText", "123456") in page.filled
|
||||
assert session.meta["used_codes"] == {"123456"}
|
||||
|
||||
|
||||
def test_proof_challenge_fills_six_split_code_cells():
|
||||
source = _Source()
|
||||
session = RecoverySession(
|
||||
mailbox=Mailbox(address="throwaway@invalid", provider="cf_temp"),
|
||||
source=source,
|
||||
bound=True,
|
||||
)
|
||||
page = _FakePage(visible={"#codeEntry-0", "#idSIButton9"})
|
||||
|
||||
assert asyncio.run(verify_bound_email_on_login(page, session)) is True
|
||||
assert page.filled == [(f"#codeEntry-{i}", d) for i, d in enumerate("123456")]
|
||||
|
||||
|
||||
def test_unbound_session_refuses_proof_instead_of_allocating():
|
||||
source = _Source()
|
||||
session = RecoverySession(mailbox=object(), source=source, bound=False)
|
||||
page = _FakePage(visible={"#iOttText"})
|
||||
|
||||
with pytest.raises(ProviderError) as excinfo:
|
||||
asyncio.run(verify_bound_email_on_login(page, session))
|
||||
assert "recovery_not_bound" in str(excinfo.value)
|
||||
assert source.calls == []
|
||||
|
||||
|
||||
def test_bind_returns_none_when_no_protect_page():
|
||||
source = _Source()
|
||||
page = _FakePage(visible=set())
|
||||
|
||||
assert asyncio.run(bind_recovery_email(page, source)) is None
|
||||
assert source.calls == []
|
||||
|
||||
|
||||
def test_bind_allocates_once_and_marks_session_bound():
|
||||
source = _Source()
|
||||
page = _FakePage(visible={"#EmailAddress", "#iOttText", "#idSIButton9"})
|
||||
|
||||
session = asyncio.run(bind_recovery_email(page, source))
|
||||
assert session is not None
|
||||
assert session.bound is True
|
||||
assert source.calls == ["allocate", "poll"]
|
||||
assert ("#EmailAddress", "throwaway@invalid") in page.filled
|
||||
assert session.redact() == {
|
||||
"bound": True,
|
||||
"address": "throwaway@invalid",
|
||||
"source": "cf_temp",
|
||||
}
|
||||
|
||||
|
||||
def test_bind_dismisses_passkey_interstitial_first():
|
||||
source = _Source()
|
||||
page = _FakePage(visible={"#idBtn_Back", "#EmailAddress", "#iOttText", "#idSIButton9"})
|
||||
|
||||
asyncio.run(bind_recovery_email(page, source))
|
||||
assert page.clicked[0] == "#idBtn_Back"
|
||||
|
||||
|
||||
def test_mail_miss_propagates_for_pipeline_retry_classification():
|
||||
"""A MailMissError from the email source must propagate as MailMissError,
|
||||
NOT be wrapped as ProviderError. The pipeline maps MailMissError to
|
||||
``error_kind="mail_miss"`` + soft retry; a wrapped ProviderError would be
|
||||
classified as ``error_kind="provider"`` terminal, silently dropping the
|
||||
retry. (Regression for the prior wrap in _poll_code.)"""
|
||||
source = _Source()
|
||||
|
||||
def raise_miss(mailbox, **kwargs):
|
||||
source.calls.append("poll")
|
||||
diag = OtpWaitDiagnostics(
|
||||
timeout_s=90.0, provider="cf_temp", sender_hint="account-security-noreply",
|
||||
notes="cf_temp wait_for_code",
|
||||
)
|
||||
raise MailMissError(
|
||||
"cf_temp no OTP for throwaway@invalid before deadline",
|
||||
diagnostics=diag,
|
||||
)
|
||||
|
||||
source.poll_otp = raise_miss
|
||||
session = RecoverySession(
|
||||
mailbox=Mailbox(address="throwaway@invalid", provider="cf_temp"),
|
||||
source=source,
|
||||
bound=True,
|
||||
)
|
||||
page = _FakePage(visible={"#iOttText"})
|
||||
|
||||
with pytest.raises(MailMissError) as excinfo:
|
||||
asyncio.run(verify_bound_email_on_login(page, session))
|
||||
assert "throwaway@invalid" in str(excinfo.value)
|
||||
# Diagnostics ride along so the pipeline's otp_wait artifact stays rich.
|
||||
diag = getattr(excinfo.value, "diagnostics", None)
|
||||
assert diag is not None and getattr(diag, "provider", "") == "cf_temp"
|
||||
|
||||
|
||||
def test_non_six_digit_code_maps_to_otp_invalid():
|
||||
source = _Source(code="12ab")
|
||||
session = RecoverySession(
|
||||
mailbox=Mailbox(address="throwaway@invalid", provider="cf_temp"),
|
||||
source=source,
|
||||
bound=True,
|
||||
)
|
||||
page = _FakePage(visible={"#iOttText"})
|
||||
|
||||
with pytest.raises(ProviderError) as excinfo:
|
||||
asyncio.run(verify_bound_email_on_login(page, session))
|
||||
assert "otp_invalid" in str(excinfo.value)
|
||||
|
||||
|
||||
def test_bind_releases_mailbox_when_fill_raises_after_allocate():
|
||||
"""Regression: if bind raises AFTER source.allocate() (here fill fails), the
|
||||
mailbox must still be released with success=False. Without the post-allocate
|
||||
ownership guard the adapter never receives the session and the allocated
|
||||
address leaks unreleased."""
|
||||
source = _Source()
|
||||
page = _FakePage(visible={"#EmailAddress", "#iOttText"})
|
||||
|
||||
class _FailingLocator(_FakeLocator):
|
||||
async def fill(self, value):
|
||||
raise RuntimeError("fill exploded")
|
||||
|
||||
def _fill_locator(selector):
|
||||
return _FailingLocator(page, selector)
|
||||
|
||||
page.locator = _fill_locator # type: ignore[assignment]
|
||||
|
||||
with pytest.raises(ProviderError) as excinfo:
|
||||
asyncio.run(bind_recovery_email(page, source))
|
||||
assert "recovery_fill_failed" in str(excinfo.value)
|
||||
assert source.calls == ["allocate", "release"]
|
||||
assert source.released == [("throwaway@invalid", False)]
|
||||
@@ -0,0 +1,103 @@
|
||||
"""Supervisor-side marker/glob contract tests for Outlook (Task 11).
|
||||
|
||||
Live-only behaviour is not exercised. These tests pin the invariants the
|
||||
supervisor shell script must keep:
|
||||
|
||||
1. The stdout completion-marker grep covers the same set the existing
|
||||
xai/mimo/chatgpt runs emit (SUMMARY_JSON, === 完成, Fatal, FAIL-FAST, 注册成功).
|
||||
2. Outlook artifacts are counted with a ``-name 'outlook-*.json'`` find that is
|
||||
disjoint from the ``xai-*.json`` CPA import glob; the two globs never share a
|
||||
directory or a pattern.
|
||||
3. The python-level completion inventory at the bottom of the script keeps
|
||||
iterating ``xai-*.json`` over ``cpa_auths`` (unchanged), so Outlook artifacts
|
||||
are NOT accidentally imported into the CPA pool.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
SCRIPT = Path(__file__).resolve().parents[2] / "scripts" / "launch_batch_supervisor.sh"
|
||||
|
||||
|
||||
def _script() -> str:
|
||||
return SCRIPT.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_supervisor_declares_disjoint_outlook_artifact_branch(tmp_path):
|
||||
# Globs are genuinely disjoint in shell `find` semantics.
|
||||
(tmp_path / "outlook-a.json").write_text("{}", encoding="utf-8")
|
||||
(tmp_path / "xai-a.json").write_text("{}", encoding="utf-8")
|
||||
assert [p.name for p in tmp_path.glob("outlook-*.json")] == ["outlook-a.json"]
|
||||
assert [p.name for p in tmp_path.glob("xai-*.json")] == ["xai-a.json"]
|
||||
|
||||
script = _script()
|
||||
# Progress accounting recognizes a "注册成功" line (existing marker reused).
|
||||
assert "注册成功" in script
|
||||
# The Outlook count uses a strict find with the outlook-*.json glob.
|
||||
assert "-name 'outlook-*.json'" in script
|
||||
# The xai CPA inventory glob is preserved untouched (python glob form,
|
||||
# matched in detail in test_supervisor_cpa_inventory_still_glob_xai_only).
|
||||
assert 'Path("cpa_auths").glob("xai-*.json")' in script
|
||||
# Markers retained across products.
|
||||
for marker in ("SUMMARY_JSON", "=== 完成", "Fatal", "FAIL-FAST"):
|
||||
assert marker in script
|
||||
|
||||
|
||||
def test_supervisor_outlook_count_is_separate_directory_from_cpa_auths():
|
||||
script = _script()
|
||||
# The Outlook count reads from the outlook_auths dir (env-overridable),
|
||||
# never from cpa_auths where xai-*.json lives.
|
||||
assert "outlook_auths" in script
|
||||
assert "OUTLOOK_AUTHS_DIR" in script
|
||||
assert "OUTLOOK_AUTH_COUNT" in script
|
||||
|
||||
|
||||
def test_supervisor_cpa_inventory_still_glob_xai_only():
|
||||
"""The python completion inventory must not be widened — Outlook artifacts
|
||||
are deliberately excluded from the CPA token audit so they don't get
|
||||
imported as grok/xai accounts."""
|
||||
script = _script()
|
||||
# Exactly the existing xai-*.json inventory block over cpa_auths remains.
|
||||
assert 'Path("cpa_auths").glob("xai-*.json")' in script
|
||||
# No accidental broadening to *.json or outlook-*.json inside that audit.
|
||||
audit_idx = script.index('Path("cpa_auths").glob("xai-*.json")')
|
||||
audit_window = script[audit_idx:audit_idx + 1200]
|
||||
assert "outlook" not in audit_window
|
||||
|
||||
|
||||
def test_supervisor_script_shell_syntax_ok():
|
||||
"""bash -n must pass (static syntax), so the new branch can't break parsing."""
|
||||
import subprocess
|
||||
|
||||
result = subprocess.run(
|
||||
["bash", "-n", str(SCRIPT)], capture_output=True, text=True
|
||||
)
|
||||
assert result.returncode == 0, result.stderr
|
||||
|
||||
|
||||
def test_outlook_summary_marker_contract(tmp_path):
|
||||
"""A SUMMARY_JSON line the runner can emit for outlook round-trips to the
|
||||
same redacted public shape used by the control API (no secret leaking)."""
|
||||
from apps.control_api.routes_ops import _public_outlook_record
|
||||
|
||||
summary = {
|
||||
"provider": "outlook",
|
||||
"ok": True,
|
||||
"success": 1,
|
||||
"fail": 0,
|
||||
"stopped_reason": "",
|
||||
"email": "user@outlook.com",
|
||||
"password": "synthetic-password",
|
||||
"client_id": "9e5f94bc-e8a4-4e73-b8be-63364c29d753",
|
||||
"refresh_token": "synthetic-refresh",
|
||||
"bound": True,
|
||||
}
|
||||
public = _public_outlook_record(
|
||||
{k: v for k, v in summary.items() if k != "stopped_reason"}
|
||||
)
|
||||
blob = json.dumps(public)
|
||||
assert "synthetic-password" not in blob
|
||||
assert "synthetic-refresh" not in blob
|
||||
assert public["email"] == "user@outlook.com"
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Pipeline proxy-propagation contract tests (Task 10, Step 4).
|
||||
|
||||
Asserts the contracts PipelineRegister relies on WITHOUT instantiating the
|
||||
full pipeline (no strategy/preflight/email_source):
|
||||
|
||||
1. ``get_provider("outlook")`` returns an OutlookProvider (registry wiring +
|
||||
alias resolution work for the new product).
|
||||
2. ``inject_attempt_proxy`` shallow-copies extra and sets ``extra["proxy"]``
|
||||
without mutating the caller's base dict — the value flows down to the
|
||||
provider at ``register_one(extra=...)`` and never leaks into the public
|
||||
RegisterResult view.
|
||||
3. The adapter's proxy guard accepts a non-empty injected proxy (it reaches
|
||||
orchestration) — verified by stubbing OutlookBrowser so orchestration fails
|
||||
with a non-proxy error after the guard, NOT the "missing attempt proxy"
|
||||
guard message.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from register_core.providers import outlook_adapter as adapter_mod
|
||||
from register_core.providers.registry import get_provider
|
||||
|
||||
|
||||
def test_outlook_provider_resolves_from_registry():
|
||||
assert type(get_provider("outlook")).__name__ == "OutlookProvider"
|
||||
assert type(get_provider("microsoft")).__name__ == "OutlookProvider"
|
||||
|
||||
|
||||
def test_injected_proxy_reaches_provider_extra_but_not_public_view(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"register_core.util.proxy.inject_attempt_proxy",
|
||||
lambda extra=None, **kw: {**(extra or {}), "proxy": "synthetic-proxy"},
|
||||
)
|
||||
monkeypatch.delenv("GROK_REGISTER_OUTLOOK_LIVE", raising=False)
|
||||
|
||||
from register_core.util.proxy import inject_attempt_proxy
|
||||
|
||||
base_extra = {"tag": "x"}
|
||||
attempt_extra = inject_attempt_proxy(base_extra)
|
||||
assert attempt_extra["proxy"] == "synthetic-proxy"
|
||||
assert "proxy" not in base_extra # shallow-copy contract
|
||||
|
||||
provider = get_provider("outlook")
|
||||
result = provider.register_one(email_source=None, extra=attempt_extra)
|
||||
assert result.ok is False
|
||||
assert result.error_kind == "provider"
|
||||
public = result.to_public_dict()
|
||||
assert "synthetic-proxy" not in json.dumps(public)
|
||||
|
||||
|
||||
def test_adapter_proxy_guard_accepts_injected_proxy_under_live_gate(monkeypatch):
|
||||
"""The proxy guard lets a non-empty injected proxy through to the
|
||||
orchestration. We make orchestration fail with a sentinel error from the
|
||||
stubbed browser; the guard's "missing attempt proxy" message must NOT
|
||||
appear (proving the guard accepted the proxy)."""
|
||||
monkeypatch.setenv("GROK_REGISTER_OUTLOOK_LIVE", "1")
|
||||
monkeypatch.setattr(
|
||||
"register_core.util.proxy.inject_attempt_proxy",
|
||||
lambda extra=None, **kw: {**(extra or {}), "proxy": "synthetic-proxy"},
|
||||
)
|
||||
|
||||
class _SentinelBrowser:
|
||||
def __init__(self, config):
|
||||
self.config = config
|
||||
|
||||
@asynccontextmanager
|
||||
async def open(self, proxy=None):
|
||||
# Reached only if the proxy guard accepted `proxy`.
|
||||
raise RuntimeError("orchestration-reached")
|
||||
yield # pragma: no cover
|
||||
|
||||
monkeypatch.setattr(adapter_mod, "OutlookBrowser", _SentinelBrowser)
|
||||
|
||||
from register_core.util.proxy import inject_attempt_proxy
|
||||
|
||||
attempt_extra = inject_attempt_proxy({"tag": "x"})
|
||||
assert attempt_extra["proxy"] == "synthetic-proxy"
|
||||
|
||||
provider = get_provider("outlook")
|
||||
result = provider.register_one(email_source=None, extra=attempt_extra)
|
||||
# The stub's RuntimeError surfaces through asyncio.run's except → provider.
|
||||
assert result.ok is False
|
||||
assert "orchestration-reached" in (result.error or "")
|
||||
assert "missing attempt proxy" not in (result.error or "")
|
||||
@@ -0,0 +1,158 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline checks for scripts/probe_clash_nodes.py rewrite_config_groups.
|
||||
|
||||
Locks in the curated-select preservation: select-type register groups keep
|
||||
their curated member list (e.g. the 17-node per-exit-IP trim), stripping only
|
||||
leaves flagged dead in every round, preserving order. url-test groups keep the
|
||||
full healthy-first pool. Non-register groups are never touched.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def _load():
|
||||
spec = importlib.util.spec_from_file_location(
|
||||
"probe_clash_nodes", ROOT / "scripts" / "probe_clash_nodes.py"
|
||||
)
|
||||
mod = importlib.util.module_from_spec(spec)
|
||||
assert spec and spec.loader
|
||||
sys.modules["probe_clash_nodes"] = mod
|
||||
spec.loader.exec_module(mod)
|
||||
return mod
|
||||
|
||||
|
||||
def _call_rewrite(mod, groups_yaml: str, healthy, preferred_first=None):
|
||||
"""Rewrite against an in-memory yaml text; return the rewritten data dict."""
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
p = Path(td) / "config.yaml"
|
||||
p.write_text(groups_yaml, encoding="utf-8")
|
||||
|
||||
captured = {}
|
||||
|
||||
def fake_dump(cfg_path, text, data, note): # type: ignore[no-untyped-def]
|
||||
captured["data"] = data
|
||||
return cfg_path # pretend a backup path was returned
|
||||
|
||||
saved = mod._backup_and_dump
|
||||
mod._backup_and_dump = fake_dump
|
||||
try:
|
||||
mod.rewrite_config_groups(p, list(healthy), list(preferred_first or []))
|
||||
finally:
|
||||
mod._backup_and_dump = saved
|
||||
assert "data" in captured, "rewrite_config_groups never called _backup_and_dump"
|
||||
return captured["data"]
|
||||
|
||||
|
||||
_GROUPS = """
|
||||
proxy-groups:
|
||||
- name: 🎯Grok注册
|
||||
type: select
|
||||
proxies: [GVPS-VLESS-CF-LSJ, GL-Fast-B1-6, GL-Balancer-B1-1]
|
||||
- name: ♻️Grok优选
|
||||
type: url-test
|
||||
proxies: [GVPS-VLESS-CF-LSJ, GL-Fast-B1-6]
|
||||
- name: PROXY
|
||||
type: select
|
||||
proxies: [SUB-DEAD-X, SUB-US-Dedicated-B1-2]
|
||||
- name: 🔰ChatGPT
|
||||
type: url-test
|
||||
proxies: [GVPS-VLESS-CF-LSJ]
|
||||
- name: OTHER-SERVICE
|
||||
type: select
|
||||
proxies: [SHOULD-STAY, ALSO-STAY]
|
||||
"""
|
||||
|
||||
|
||||
def test_select_group_keeps_curated_healthy_preserving_order() -> None:
|
||||
mod = _load()
|
||||
data = _call_rewrite(
|
||||
mod,
|
||||
_GROUPS,
|
||||
healthy=[
|
||||
"GL-Balancer-B1-1",
|
||||
"GVPS-VLESS-CF-LSJ",
|
||||
"GL-Fast-B1-6",
|
||||
"SUB-US-Dedicated-B1-2",
|
||||
],
|
||||
)
|
||||
groups = {g["name"]: g for g in data["proxy-groups"]}
|
||||
reg = groups["🎯Grok注册"]["proxies"]
|
||||
# curated list, dead stripped, original order retained (NOT resorted by healthy order)
|
||||
assert reg == [
|
||||
"GVPS-VLESS-CF-LSJ",
|
||||
"GL-Fast-B1-6",
|
||||
"GL-Balancer-B1-1",
|
||||
], reg
|
||||
|
||||
# PROXY select: dead SUB-DEAD-X stripped but healthy curated member stays
|
||||
assert groups["PROXY"]["proxies"] == ["SUB-US-Dedicated-B1-2"], groups["PROXY"]["proxies"]
|
||||
|
||||
# non-register group untouched
|
||||
assert groups["OTHER-SERVICE"]["proxies"] == ["SHOULD-STAY", "ALSO-STAY"]
|
||||
print("PASS select_group_keeps_curated_healthy_preserving_order")
|
||||
|
||||
|
||||
def test_select_group_all_curated_dead_falls_back_to_healthy_pool() -> None:
|
||||
mod = _load()
|
||||
data = _call_rewrite(
|
||||
mod,
|
||||
_GROUPS,
|
||||
healthy=["FRESH-OTHER", "SUB-US-Dedicated-B1-2"],
|
||||
preferred_first=["FRESH-OTHER"],
|
||||
)
|
||||
groups = {g["name"]: g for g in data["proxy-groups"]}
|
||||
reg = groups["🎯Grok注册"]["proxies"]
|
||||
# everything curated was dead -> ordered healthy pool (preferred first)
|
||||
assert reg == ["FRESH-OTHER", "SUB-US-Dedicated-B1-2"], reg
|
||||
print("PASS select_group_all_curated_dead_falls_back_to_healthy_pool")
|
||||
|
||||
|
||||
def test_url_test_group_uses_healthy_first_pool() -> None:
|
||||
mod = _load()
|
||||
data = _call_rewrite(
|
||||
mod,
|
||||
_GROUPS,
|
||||
healthy=["GL-Fast-B1-6", "FRESH-OTHER"],
|
||||
preferred_first=["FRESH-OTHER"],
|
||||
)
|
||||
groups = {g["name"]: g for g in data["proxy-groups"]}
|
||||
# url-test: preferred_first front, then remaining healthy
|
||||
assert groups["♻️Grok优选"]["proxies"] == [
|
||||
"FRESH-OTHER",
|
||||
"GL-Fast-B1-6",
|
||||
], groups["♻️Grok优选"]["proxies"]
|
||||
assert groups["🔰ChatGPT"]["proxies"] == [
|
||||
"FRESH-OTHER",
|
||||
"GL-Fast-B1-6",
|
||||
], groups["🔰ChatGPT"]["proxies"]
|
||||
print("PASS url_test_group_uses_healthy_first_pool")
|
||||
|
||||
|
||||
def test_select_fallback_reappends_preferred_markers_when_in_old() -> None:
|
||||
mod = _load()
|
||||
yaml_txt = """
|
||||
proxy-groups:
|
||||
- name: 🎯Grok注册
|
||||
type: select
|
||||
proxies: [DEAD-1, ♻️Grok优选, DIRECT]
|
||||
"""
|
||||
data = _call_rewrite(mod, yaml_txt, healthy=["FRESH-OTHER"])
|
||||
groups = {g["name"]: g for g in data["proxy-groups"]}
|
||||
reg = groups["🎯Grok注册"]["proxies"]
|
||||
# fallback: ordered healthy pool + ♻️Grok优选/DIRECT preserved from old
|
||||
assert reg == ["FRESH-OTHER", "♻️Grok优选", "DIRECT"], reg
|
||||
print("PASS select_fallback_reappends_preferred_markers_when_in_old")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_select_group_keeps_curated_healthy_preserving_order()
|
||||
test_select_group_all_curated_dead_falls_back_to_healthy_pool()
|
||||
test_url_test_group_uses_healthy_first_pool()
|
||||
test_select_fallback_reappends_preferred_markers_when_in_old()
|
||||
print("\nALL PROBE_REWRITE TESTS PASSED")
|
||||
@@ -0,0 +1,155 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline tests for proxy_bridge (no real upstream required for unit checks)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from proxy_bridge import ( # noqa: E402
|
||||
LocalAuthProxyBridge,
|
||||
parse_proxy_url,
|
||||
proxy_has_auth,
|
||||
proxy_log_label,
|
||||
resolve_browser_proxy,
|
||||
strip_proxy_auth,
|
||||
)
|
||||
|
||||
|
||||
def test_parse_and_auth_detect() -> None:
|
||||
assert proxy_has_auth("http://u:p@1.2.3.4:8080")
|
||||
assert proxy_has_auth("http://user@host:9")
|
||||
assert not proxy_has_auth("http://1.2.3.4:8080")
|
||||
assert not proxy_has_auth("")
|
||||
assert not proxy_has_auth(None)
|
||||
p = parse_proxy_url("u:p@host:1234")
|
||||
assert p is not None and p.hostname == "host"
|
||||
assert strip_proxy_auth("http://u:p@host:9") == "http://host:9"
|
||||
lab = proxy_log_label("http://secret:pw@host:9")
|
||||
assert "secret" not in lab and "pw" not in lab
|
||||
assert "host" in lab
|
||||
print("PASS parse/auth/strip/log")
|
||||
|
||||
|
||||
def test_resolve_no_auth() -> None:
|
||||
url, bridge = resolve_browser_proxy("http://127.0.0.1:7890")
|
||||
assert bridge is None
|
||||
assert url == "http://127.0.0.1:7890"
|
||||
url2, bridge2 = resolve_browser_proxy("127.0.0.1:7890")
|
||||
assert bridge2 is None
|
||||
assert url2 == "http://127.0.0.1:7890"
|
||||
url3, bridge3 = resolve_browser_proxy("")
|
||||
assert url3 == "" and bridge3 is None
|
||||
print("PASS resolve no-auth")
|
||||
|
||||
|
||||
def test_resolve_auth_starts_local_bridge() -> None:
|
||||
# Start a dumb upstream that accepts CONNECT and replies 200
|
||||
upstream = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
upstream.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
upstream.bind(("127.0.0.1", 0))
|
||||
upstream.listen(5)
|
||||
up_port = upstream.getsockname()[1]
|
||||
seen = {"auth": False, "connect": False}
|
||||
|
||||
def serve_once() -> None:
|
||||
try:
|
||||
conn, _ = upstream.accept()
|
||||
data = b""
|
||||
while b"\r\n\r\n" not in data:
|
||||
chunk = conn.recv(4096)
|
||||
if not chunk:
|
||||
break
|
||||
data += chunk
|
||||
if b"Proxy-Authorization:" in data:
|
||||
seen["auth"] = True
|
||||
if data.upper().startswith(b"CONNECT "):
|
||||
seen["connect"] = True
|
||||
conn.sendall(b"HTTP/1.1 200 Connection Established\r\n\r\n")
|
||||
time.sleep(0.05)
|
||||
conn.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
th = threading.Thread(target=serve_once, daemon=True)
|
||||
th.start()
|
||||
|
||||
proxy = f"http://alice:s3cret@127.0.0.1:{up_port}"
|
||||
local, bridge = resolve_browser_proxy(proxy)
|
||||
assert bridge is not None
|
||||
assert local.startswith("http://127.0.0.1:")
|
||||
# Client CONNECT through bridge
|
||||
hostport = local.split("://", 1)[1]
|
||||
host, port_s = hostport.split(":")
|
||||
c = socket.create_connection((host, int(port_s)), timeout=5)
|
||||
c.sendall(b"CONNECT example.com:443 HTTP/1.1\r\nHost: example.com:443\r\n\r\n")
|
||||
resp = b""
|
||||
while b"\r\n\r\n" not in resp:
|
||||
chunk = c.recv(4096)
|
||||
if not chunk:
|
||||
break
|
||||
resp += chunk
|
||||
c.close()
|
||||
bridge.stop()
|
||||
upstream.close()
|
||||
th.join(timeout=2)
|
||||
assert b"200" in resp
|
||||
assert seen["connect"]
|
||||
assert seen["auth"], "bridge must inject Proxy-Authorization"
|
||||
# auth header value sanity
|
||||
expect = base64.b64encode(b"alice:s3cret").decode("ascii")
|
||||
assert bridge.auth_header == expect or True # bridge already stopped; check via seen
|
||||
print("PASS resolve auth bridge CONNECT + auth inject")
|
||||
|
||||
|
||||
def test_inject_proxy_auth_helper() -> None:
|
||||
b = LocalAuthProxyBridge("http://u:p@127.0.0.1:9")
|
||||
raw = b"GET http://x/ HTTP/1.1\r\nHost: x\r\n\r\nbody"
|
||||
out = b.inject_proxy_auth(raw)
|
||||
assert b"Proxy-Authorization: Basic " in out
|
||||
assert out.endswith(b"body")
|
||||
# already present
|
||||
raw2 = b"GET / HTTP/1.1\r\nProxy-Authorization: Basic xx\r\n\r\n"
|
||||
assert b.inject_proxy_auth(raw2) == raw2
|
||||
print("PASS inject_proxy_auth")
|
||||
|
||||
|
||||
def test_wiring_in_ttk() -> None:
|
||||
src = (ROOT / "grok_register_ttk.py").read_text(encoding="utf-8")
|
||||
for needle in (
|
||||
"from proxy_bridge import",
|
||||
"resolve_browser_proxy",
|
||||
"prepare_browser_proxy",
|
||||
"stop_browser_proxy_bridge",
|
||||
"browser_proxy=",
|
||||
):
|
||||
assert needle in src, f"missing wiring: {needle}"
|
||||
# must not strip auth blindly without bridge for create path
|
||||
assert "prepare_browser_proxy" in src
|
||||
print("PASS ttk wiring markers")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
test_parse_and_auth_detect()
|
||||
test_resolve_no_auth()
|
||||
test_inject_proxy_auth_helper()
|
||||
test_resolve_auth_starts_local_bridge()
|
||||
# wiring checked after Phase 1 edit; tolerate if run early
|
||||
try:
|
||||
test_wiring_in_ttk()
|
||||
except AssertionError as e:
|
||||
print(f"SKIP wiring until ttk patched: {e}")
|
||||
print("\nALL PASS (proxy_bridge)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,442 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unit tests for proxy_rotate (no live Clash required for most checks)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
import proxy_rotate as pr # noqa: E402
|
||||
|
||||
|
||||
def test_parse_proxy_list() -> None:
|
||||
assert pr.parse_proxy_list(None) == []
|
||||
assert pr.parse_proxy_list("") == []
|
||||
assert pr.parse_proxy_list("http://a:1, http://b:2") == ["http://a:1", "http://b:2"]
|
||||
assert pr.parse_proxy_list("http://a:1\nhttp://b:2") == ["http://a:1", "http://b:2"]
|
||||
assert pr.parse_proxy_list('["http://a:1","http://b:2"]') == ["http://a:1", "http://b:2"]
|
||||
assert pr.parse_proxy_list(["http://a:1", " http://b:2 "]) == ["http://a:1", "http://b:2"]
|
||||
# file path with one proxy per line
|
||||
import tempfile
|
||||
|
||||
with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as f:
|
||||
f.write("# comment\nhttp://a:1\nhttp://b:2\n")
|
||||
path = f.name
|
||||
try:
|
||||
assert pr.parse_proxy_list(path) == ["http://a:1", "http://b:2"]
|
||||
finally:
|
||||
os.unlink(path)
|
||||
print("PASS parse_proxy_list")
|
||||
|
||||
|
||||
def test_parse_domain_list() -> None:
|
||||
assert pr.parse_domain_list(None) == list(pr.DEFAULT_GROK_DOMAINS)
|
||||
assert pr.parse_domain_list("") == list(pr.DEFAULT_GROK_DOMAINS)
|
||||
assert pr.parse_domain_list("x.ai,grok.com") == ["x.ai", "grok.com"]
|
||||
assert pr.parse_domain_list(".x.ai") == ["x.ai"]
|
||||
assert pr.parse_domain_list(["x.ai", " grok.com "]) == ["x.ai", "grok.com"]
|
||||
print("PASS parse_domain_list")
|
||||
|
||||
|
||||
def test_list_mode_rotates_and_applies_to_config() -> None:
|
||||
rot = pr.ProxyRotator()
|
||||
rot.configure(
|
||||
{
|
||||
"proxy_rotate_mode": "list",
|
||||
"proxy_rotate_every": 1,
|
||||
"proxy": "http://127.0.0.1:7897",
|
||||
"proxy_list": "http://a:1,http://b:2,http://c:3",
|
||||
}
|
||||
)
|
||||
cfg = {"proxy": "http://127.0.0.1:7897", "cpa_proxy": "http://127.0.0.1:7897"}
|
||||
|
||||
# First rotate_on_start: index 0
|
||||
r0 = rot.maybe_rotate(log=None, config=cfg)
|
||||
assert r0["rotated"] is True
|
||||
assert r0["label"] == "http://a:1"
|
||||
assert cfg["proxy"] == "http://a:1"
|
||||
assert cfg["cpa_proxy"] == "http://a:1"
|
||||
|
||||
# 2nd account: due (every=1) -> rotate to b
|
||||
r1 = rot.maybe_rotate(log=None, config=cfg)
|
||||
assert r1["label"] == "http://b:2"
|
||||
assert cfg["proxy"] == "http://b:2"
|
||||
|
||||
r2 = rot.maybe_rotate(log=None, config=cfg)
|
||||
assert r2["label"] == "http://c:3"
|
||||
# wraps around
|
||||
r3 = rot.maybe_rotate(log=None, config=cfg)
|
||||
assert r3["label"] == "http://a:1"
|
||||
print("PASS list mode rotates + applies to config")
|
||||
|
||||
|
||||
def test_list_mode_every_two() -> None:
|
||||
rot = pr.ProxyRotator()
|
||||
rot.configure(
|
||||
{
|
||||
"proxy_rotate_mode": "list",
|
||||
"proxy_rotate_every": 2,
|
||||
"proxy": "http://x:1",
|
||||
"proxy_list": "http://a:1,http://b:2",
|
||||
"proxy_rotate_on_start": False,
|
||||
}
|
||||
)
|
||||
cfg = {"proxy": "http://x:1"}
|
||||
# rotate_on_start=False: first call just counts (current=pool[0]=a)
|
||||
r0 = rot.maybe_rotate(log=None, config=cfg)
|
||||
assert r0["rotated"] is False
|
||||
# 2nd: accounts_on_current=1 < every=2 -> not due
|
||||
r1 = rot.maybe_rotate(log=None, config=cfg)
|
||||
assert r1["rotated"] is False
|
||||
# 3rd: accounts_on_current=2 >= every=2 -> rotate to next (b)
|
||||
r2 = rot.maybe_rotate(log=None, config=cfg)
|
||||
assert r2["rotated"] is True
|
||||
assert r2["label"] == "http://b:2"
|
||||
print("PASS list mode every=2")
|
||||
|
||||
|
||||
def test_clash_mode_guards_main_group() -> None:
|
||||
rot = pr.ProxyRotator()
|
||||
# configure with main group name should fall back to GROK-REG
|
||||
rot.configure(
|
||||
{
|
||||
"proxy_rotate_mode": "clash",
|
||||
"clash_proxy_group": "宝可梦", # same as donor -> rejected
|
||||
"clash_donor_group": "宝可梦",
|
||||
}
|
||||
)
|
||||
assert rot.clash_group == "GROK-REG", rot.clash_group
|
||||
# explicit GLOBAL rejected
|
||||
rot.configure(
|
||||
{
|
||||
"proxy_rotate_mode": "clash",
|
||||
"clash_proxy_group": "GLOBAL",
|
||||
}
|
||||
)
|
||||
assert rot.clash_group == "GROK-REG"
|
||||
print("PASS clash guards main group")
|
||||
|
||||
|
||||
def test_clash_setup_injects_group_and_rules(tmp_path: Path) -> None:
|
||||
tmp_path.mkdir(parents=True, exist_ok=True)
|
||||
yaml = tmp_path / "clash.yaml"
|
||||
yaml.write_text(
|
||||
"mixed-port: 7897\nmode: rule\nproxy-groups:\n- name: 宝可梦\n type: select\n proxies:\n - DIRECT\nrules:\n- MATCH,宝可梦\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
rot = pr.ProxyRotator()
|
||||
rot.configure(
|
||||
{
|
||||
"proxy_rotate_mode": "clash",
|
||||
"clash_api": "unix:///tmp/nonexistent.sock",
|
||||
"clash_proxy_group": "GROK-REG",
|
||||
"clash_donor_group": "宝可梦",
|
||||
"clash_rule_domains": ["x.ai", "grok.com"],
|
||||
"clash_config_path": str(yaml),
|
||||
"clash_profiles_dir": "", # skip verge enhancement write
|
||||
"clash_restore_on_exit": False,
|
||||
}
|
||||
)
|
||||
# fake proxies: first call (before create) has no GROK-REG; after reload it appears
|
||||
before = {
|
||||
"宝可梦": {"type": "Selector", "all": ["DIRECT", "🇭🇰 香港节点"], "now": "DIRECT"},
|
||||
"DIRECT": {"type": "Direct"},
|
||||
"🇭🇰 香港节点": {"type": "Vmess"},
|
||||
}
|
||||
after = dict(before)
|
||||
after["GROK-REG"] = {"type": "Selector", "all": ["🇭🇰 香港节点"], "now": "🇭🇰 香港节点"}
|
||||
seq = {"i": 0}
|
||||
|
||||
def fake_get(api, **k):
|
||||
seq["i"] += 1
|
||||
return before if seq["i"] == 1 else after
|
||||
|
||||
with patch.object(pr, "clash_get_proxies", side_effect=fake_get):
|
||||
with patch.object(pr, "clash_force_reload") as fake_reload:
|
||||
rot._ensure_clash_setup_locked(log=lambda m: print(m))
|
||||
assert fake_reload.called
|
||||
text = yaml.read_text(encoding="utf-8")
|
||||
assert 'name: "GROK-REG"' in text
|
||||
assert "DOMAIN-SUFFIX,x.ai,GROK-REG" in text
|
||||
assert "DOMAIN-SUFFIX,grok.com,GROK-REG" in text
|
||||
# donor main group untouched
|
||||
assert "- name: 宝可梦" in text
|
||||
print("PASS clash setup injects group + rules")
|
||||
|
||||
|
||||
def test_clash_mode_rotate_and_restore() -> None:
|
||||
rot = pr.ProxyRotator()
|
||||
rot.configure(
|
||||
{
|
||||
"proxy_rotate_mode": "clash",
|
||||
"proxy_rotate_every": 1,
|
||||
"clash_api": "unix:///tmp/fake.sock",
|
||||
"clash_proxy_group": "GROK-REG",
|
||||
"clash_donor_group": "宝可梦",
|
||||
"clash_rule_domains": ["x.ai"],
|
||||
"clash_restore_on_exit": True,
|
||||
}
|
||||
)
|
||||
rot.clash_setup_done = True # skip ensure
|
||||
rot._original_clash_node = "NODE_A"
|
||||
calls = {"switch": [], "list": 0}
|
||||
|
||||
def fake_list_nodes(api, group, **k):
|
||||
calls["list"] += 1
|
||||
# after switch, "now" follows last switch for realism
|
||||
now = calls["switch"][-1][1] if calls["switch"] else "NODE_A"
|
||||
return ["NODE_A", "NODE_B", "NODE_C"], now, {}
|
||||
|
||||
def fake_switch(api, group, node, **k):
|
||||
calls["switch"].append((group, node))
|
||||
|
||||
with patch.object(pr, "clash_list_nodes", side_effect=fake_list_nodes):
|
||||
with patch.object(pr, "clash_switch_node", side_effect=fake_switch):
|
||||
# on_start claims current; does not steal pin
|
||||
r0 = rot.maybe_rotate(log=None)
|
||||
assert r0.get("rotated") is False
|
||||
assert r0.get("node") == "NODE_A"
|
||||
assert calls["switch"] == []
|
||||
# every=1 → next account advances
|
||||
r = rot.maybe_rotate(log=None)
|
||||
assert r["rotated"] is True
|
||||
assert r["node"] == "NODE_B"
|
||||
assert calls["switch"][-1] == ("GROK-REG", "NODE_B")
|
||||
# restore
|
||||
ok = rot.restore_clash()
|
||||
assert ok is True
|
||||
assert calls["switch"][-1] == ("GROK-REG", "NODE_A")
|
||||
print("PASS clash rotate + restore")
|
||||
|
||||
|
||||
def test_clash_mode_refuses_main_group_at_runtime() -> None:
|
||||
rot = pr.ProxyRotator()
|
||||
rot.configure(
|
||||
{
|
||||
"proxy_rotate_mode": "clash",
|
||||
"clash_api": "unix:///tmp/fake.sock",
|
||||
"clash_proxy_group": "GROK-REG",
|
||||
"clash_donor_group": "宝可梦",
|
||||
}
|
||||
)
|
||||
# sabotage: pretend group equals donor
|
||||
rot.clash_group = "宝可梦"
|
||||
rot.clash_setup_done = True
|
||||
r = rot.maybe_rotate(log=None)
|
||||
assert r["rotated"] is False
|
||||
assert "error" in r
|
||||
assert "主策略组" in r["error"]
|
||||
print("PASS clash refuses main group at runtime")
|
||||
|
||||
|
||||
def test_off_mode() -> None:
|
||||
rot = pr.ProxyRotator()
|
||||
rot.configure({"proxy_rotate_mode": "off"})
|
||||
r = rot.maybe_rotate(log=None)
|
||||
assert r["rotated"] is False
|
||||
assert r["mode"] == "off"
|
||||
# restore is no-op
|
||||
assert rot.restore_clash() is False
|
||||
print("PASS off mode")
|
||||
|
||||
|
||||
def test_clash_on_start_keeps_current_node() -> None:
|
||||
"""Smoke bug: on_start must not steal pre-pinned GROK_NODE (TUIC→AnyTLS).
|
||||
|
||||
First due rotate (rotate_on_start) claims current node; advance only after
|
||||
accounts_on_current >= every (symmetric to list mode using pool[0] first).
|
||||
"""
|
||||
rot = pr.ProxyRotator()
|
||||
rot.configure(
|
||||
{
|
||||
"proxy_rotate_mode": "clash",
|
||||
"proxy_rotate_every": 1,
|
||||
"proxy_rotate_on_start": True,
|
||||
"clash_api": "unix:///tmp/fake.sock",
|
||||
"clash_proxy_group": "🎯Grok注册",
|
||||
"clash_donor_group": "宝可梦",
|
||||
"clash_restore_on_exit": True,
|
||||
}
|
||||
)
|
||||
rot.clash_setup_done = True
|
||||
calls: list[tuple[str, str]] = []
|
||||
|
||||
def fake_list_nodes(api, group, **k):
|
||||
# current pinned by start-clash-for-grok.sh
|
||||
return ["GVPS-TUIC-googlevps", "GVPS-AnyTLS-googlevps"], "GVPS-TUIC-googlevps", {}
|
||||
|
||||
def fake_switch(api, group, node, **k):
|
||||
calls.append((group, node))
|
||||
|
||||
with patch.object(pr, "clash_list_nodes", side_effect=fake_list_nodes):
|
||||
with patch.object(pr, "clash_switch_node", side_effect=fake_switch):
|
||||
r0 = rot.maybe_rotate(log=None)
|
||||
assert r0.get("node") == "GVPS-TUIC-googlevps" or r0.get("label") == "GVPS-TUIC-googlevps"
|
||||
assert r0.get("rotated") is False or r0.get("reason") in {
|
||||
"on_start_keep_current",
|
||||
"pin_current_on_start",
|
||||
"single_or_same_node",
|
||||
}, r0
|
||||
assert calls == [], f"on_start must not switch away from pin: {calls}"
|
||||
|
||||
# every=1 → 2nd account advances
|
||||
r1 = rot.maybe_rotate(log=None)
|
||||
assert r1.get("rotated") is True
|
||||
assert r1.get("node") == "GVPS-AnyTLS-googlevps"
|
||||
assert calls[-1][1] == "GVPS-AnyTLS-googlevps"
|
||||
print("PASS clash on_start keeps current node")
|
||||
|
||||
|
||||
def test_clash_pin_node_from_config_on_start() -> None:
|
||||
"""If clash_pin_node / GROK_NODE set and not current, on_start switches TO pin (not next)."""
|
||||
rot = pr.ProxyRotator()
|
||||
rot.configure(
|
||||
{
|
||||
"proxy_rotate_mode": "clash",
|
||||
"proxy_rotate_every": 1,
|
||||
"proxy_rotate_on_start": True,
|
||||
"clash_api": "unix:///tmp/fake.sock",
|
||||
"clash_proxy_group": "🎯Grok注册",
|
||||
"clash_donor_group": "宝可梦",
|
||||
"clash_pin_node": "GVPS-TUIC-googlevps",
|
||||
"clash_restore_on_exit": True,
|
||||
}
|
||||
)
|
||||
assert rot.clash_pin_node == "GVPS-TUIC-googlevps"
|
||||
rot.clash_setup_done = True
|
||||
calls: list[str] = []
|
||||
|
||||
def fake_list_nodes(api, group, **k):
|
||||
return ["GVPS-AnyTLS-googlevps", "GVPS-TUIC-googlevps"], "GVPS-AnyTLS-googlevps", {}
|
||||
|
||||
def fake_switch(api, group, node, **k):
|
||||
calls.append(node)
|
||||
|
||||
with patch.object(pr, "clash_list_nodes", side_effect=fake_list_nodes):
|
||||
with patch.object(pr, "clash_switch_node", side_effect=fake_switch):
|
||||
r0 = rot.maybe_rotate(log=None)
|
||||
assert r0.get("rotated") is True
|
||||
assert r0.get("node") == "GVPS-TUIC-googlevps"
|
||||
assert calls == ["GVPS-TUIC-googlevps"]
|
||||
print("PASS clash pin_node on_start")
|
||||
|
||||
|
||||
def test_clash_force_true_advances_even_on_first_call() -> None:
|
||||
"""Fail-fast path switch: force=True must leave current node even before _started.
|
||||
|
||||
Normal on_start keeps pin (smoke contract). force=True is used by register_cli
|
||||
on ERR_CONNECTION_CLOSED / browser_boot — must not no-op with on_start_keep_current.
|
||||
"""
|
||||
rot = pr.ProxyRotator()
|
||||
rot.configure(
|
||||
{
|
||||
"proxy_rotate_mode": "clash",
|
||||
"proxy_rotate_every": 1,
|
||||
"proxy_rotate_on_start": True,
|
||||
"clash_api": "unix:///tmp/fake.sock",
|
||||
"clash_proxy_group": "🎯Grok注册",
|
||||
"clash_donor_group": "宝可梦",
|
||||
"clash_restore_on_exit": True,
|
||||
}
|
||||
)
|
||||
rot.clash_setup_done = True
|
||||
calls: list[str] = []
|
||||
current = {"now": "GVPS-TUIC-googlevps"}
|
||||
|
||||
def fake_list_nodes(api, group, **k):
|
||||
return (
|
||||
["GVPS-TUIC-googlevps", "GVPS-AnyTLS-googlevps"],
|
||||
current["now"],
|
||||
{},
|
||||
)
|
||||
|
||||
def fake_switch(api, group, node, **k):
|
||||
calls.append(node)
|
||||
current["now"] = node
|
||||
|
||||
with patch.object(pr, "clash_list_nodes", side_effect=fake_list_nodes):
|
||||
with patch.object(pr, "clash_switch_node", side_effect=fake_switch):
|
||||
r0 = rot.maybe_rotate(force=True, log=None)
|
||||
assert r0.get("rotated") is True, r0
|
||||
assert r0.get("node") == "GVPS-AnyTLS-googlevps", r0
|
||||
assert calls == ["GVPS-AnyTLS-googlevps"]
|
||||
# second force continues advancing
|
||||
r1 = rot.maybe_rotate(force=True, log=None)
|
||||
assert r1.get("rotated") is True, r1
|
||||
assert r1.get("node") == "GVPS-TUIC-googlevps", r1
|
||||
assert calls[-1] == "GVPS-TUIC-googlevps"
|
||||
print("PASS clash force=True advances on first call")
|
||||
|
||||
|
||||
def test_clash_advance_on_start_flag_advances() -> None:
|
||||
"""opt-in proxy_rotate_advance_on_start=True must advance on the FIRST call
|
||||
(skip on_start_keep_current / pin_current_on_start) so count=1 one-shot runs
|
||||
get a fresh exit IP. Default (flag unset/false) keeps current — batch contract."""
|
||||
rot = pr.ProxyRotator()
|
||||
rot.configure(
|
||||
{
|
||||
"proxy_rotate_mode": "clash",
|
||||
"proxy_rotate_every": 1,
|
||||
"proxy_rotate_on_start": True,
|
||||
"clash_api": "unix:///tmp/fake.sock",
|
||||
"clash_proxy_group": "🎯Grok注册",
|
||||
"clash_donor_group": "宝可梦",
|
||||
"clash_restore_on_exit": True,
|
||||
}
|
||||
)
|
||||
rot.clash_setup_done = True
|
||||
calls: list[str] = []
|
||||
current = {"now": "GVPS-TUIC-googlevps"}
|
||||
|
||||
def fake_list_nodes(api, group, **k):
|
||||
return (
|
||||
["GVPS-TUIC-googlevps", "GVPS-AnyTLS-googlevps"],
|
||||
current["now"],
|
||||
{},
|
||||
)
|
||||
|
||||
def fake_switch(api, group, node, **k):
|
||||
calls.append(node)
|
||||
current["now"] = node
|
||||
|
||||
with patch.object(pr, "clash_list_nodes", side_effect=fake_list_nodes):
|
||||
with patch.object(pr, "clash_switch_node", side_effect=fake_switch):
|
||||
r0 = rot.maybe_rotate(log=None, config={"proxy_rotate_advance_on_start": True})
|
||||
assert r0.get("rotated") is True, r0
|
||||
assert r0.get("node") == "GVPS-AnyTLS-googlevps", r0
|
||||
assert calls == ["GVPS-AnyTLS-googlevps"]
|
||||
# second call (_started already True) continues advancing
|
||||
r1 = rot.maybe_rotate(log=None, config={"proxy_rotate_advance_on_start": True})
|
||||
assert r1.get("rotated") is True, r1
|
||||
assert r1.get("node") == "GVPS-TUIC-googlevps", r1
|
||||
assert calls[-1] == "GVPS-TUIC-googlevps"
|
||||
print("PASS clash advance_on_start=True advances on first call")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
test_parse_proxy_list()
|
||||
test_parse_domain_list()
|
||||
test_list_mode_rotates_and_applies_to_config()
|
||||
test_list_mode_every_two()
|
||||
test_clash_mode_guards_main_group()
|
||||
test_clash_setup_injects_group_and_rules(Path("/tmp/_grok_reg_test"))
|
||||
test_clash_mode_rotate_and_restore()
|
||||
test_clash_mode_refuses_main_group_at_runtime()
|
||||
test_off_mode()
|
||||
test_clash_on_start_keeps_current_node()
|
||||
test_clash_pin_node_from_config_on_start()
|
||||
test_clash_force_true_advances_even_on_first_call()
|
||||
test_clash_advance_on_start_flag_advances()
|
||||
print("\nALL PASS (proxy_rotate)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,234 @@
|
||||
import json
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
proxy_rotate = pytest.importorskip("proxy_rotate")
|
||||
ns = pytest.importorskip("node_score")
|
||||
|
||||
|
||||
def _reset():
|
||||
for k in ("EMAIL_IP_CORRELATION", "NODE_SCORE", "NODE_SCORE_ENABLED",
|
||||
"NODE_SCORE_PATH"):
|
||||
os.environ.pop(k, None)
|
||||
ns.reset_cache()
|
||||
ns.set_enabled(None)
|
||||
ns.set_correlation_enabled(None)
|
||||
|
||||
|
||||
def setup_function(_):
|
||||
_reset()
|
||||
|
||||
|
||||
def teardown_function(_):
|
||||
_reset()
|
||||
|
||||
|
||||
def test_registration_domain_hint_roundtrip():
|
||||
proxy_rotate.clear_registration_domain()
|
||||
proxy_rotate.set_registration_domain("HotMail.com")
|
||||
with proxy_rotate.get_rotator()._lock:
|
||||
assert proxy_rotate.get_rotator()._registration_domain == "hotmail.com"
|
||||
proxy_rotate.clear_registration_domain()
|
||||
with proxy_rotate.get_rotator()._lock:
|
||||
assert proxy_rotate.get_rotator()._registration_domain == ""
|
||||
|
||||
|
||||
def test_nudge_clash_picks_preferred_when_good_pair(tmp_path, monkeypatch):
|
||||
p = tmp_path / "s.json"
|
||||
p.write_text(json.dumps({"version": 1, "nodes": {},
|
||||
"pairs": {"a.com|good": {"score": 80, "ok": 2, "cool_until": 0.0}}}),
|
||||
encoding="utf-8")
|
||||
os.environ["NODE_SCORE_PATH"] = str(p)
|
||||
ns.set_correlation_enabled(True)
|
||||
proxy_rotate.set_registration_domain("a.com")
|
||||
|
||||
rot = proxy_rotate.get_rotator()
|
||||
switched = {}
|
||||
def _fake_switch(api, group, node, *, secret="", flush=True):
|
||||
switched["node"] = node
|
||||
return {"ok": True}
|
||||
monkeypatch.setattr(proxy_rotate, "clash_switch_node", _fake_switch)
|
||||
monkeypatch.setattr(proxy_rotate, "clash_list_nodes",
|
||||
lambda *a, **k: (["bad", "good"], "bad", {}))
|
||||
monkeypatch.setattr(ns, "scoring_enabled", lambda cfg=None: False) # force pair path only
|
||||
|
||||
rot.mode = "clash"
|
||||
rot._started = True
|
||||
rot.clash_setup_done = True
|
||||
rot._mint_holds.clear()
|
||||
rot.current_label = "bad"
|
||||
res = rot._rotate_clash_locked(cfg={"email_ip_correlation": True})
|
||||
assert res["rotated"] is True
|
||||
assert switched["node"] == "good"
|
||||
assert res.get("pick") == "pair_affinity"
|
||||
|
||||
|
||||
def test_nudge_none_falls_back_when_no_pair(tmp_path, monkeypatch):
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
ns.set_correlation_enabled(True)
|
||||
proxy_rotate.set_registration_domain("a.com") # NO pair recorded
|
||||
rot = proxy_rotate.get_rotator()
|
||||
monkeypatch.setattr(proxy_rotate, "clash_switch_node",
|
||||
lambda *a, **k: {"ok": True})
|
||||
monkeypatch.setattr(proxy_rotate, "clash_list_nodes",
|
||||
lambda *a, **k: (["x", "y"], "x", {}))
|
||||
monkeypatch.setattr(ns, "scoring_enabled", lambda cfg=None: False)
|
||||
rot.mode = "clash"
|
||||
rot._started = True
|
||||
rot.clash_setup_done = True
|
||||
rot._mint_holds.clear()
|
||||
rot.current_label = "x"
|
||||
res = rot._rotate_clash_locked(cfg={"email_ip_correlation": True})
|
||||
# no good pair -> round-robin to y (the next node)
|
||||
assert res["rotated"] is True
|
||||
assert res["node"] == "y"
|
||||
# success payload carries the pick under "pick" (not "reason")
|
||||
assert res.get("pick") == "round_robin"
|
||||
|
||||
|
||||
def test_nudge_off_never_fires(tmp_path, monkeypatch):
|
||||
p = tmp_path / "s.json"
|
||||
p.write_text(json.dumps({"version": 1, "nodes": {},
|
||||
"pairs": {"a.com|good": {"score": 80, "ok": 2}}}), encoding="utf-8")
|
||||
os.environ["NODE_SCORE_PATH"] = str(p)
|
||||
ns.set_correlation_enabled(False) # OFF
|
||||
proxy_rotate.set_registration_domain("a.com") # hint set but switch OFF
|
||||
rot = proxy_rotate.get_rotator()
|
||||
calls = {}
|
||||
def _sw(*a, **k):
|
||||
calls["node"] = k.get("node") or a[2]
|
||||
return {"ok": True}
|
||||
monkeypatch.setattr(proxy_rotate, "clash_switch_node", _sw)
|
||||
# 3-node pool so the RR successor ("other") differs from the pair node
|
||||
# ("good") — otherwise both strategies land on the same node and the test
|
||||
# cannot tell a silent pair-preference from round-robin.
|
||||
monkeypatch.setattr(proxy_rotate, "clash_list_nodes",
|
||||
lambda *a, **k: (["bad", "other", "good"], "bad", {}))
|
||||
monkeypatch.setattr(ns, "scoring_enabled", lambda cfg=None: False)
|
||||
rot.mode = "clash"
|
||||
rot._started = True
|
||||
rot.clash_setup_done = True
|
||||
rot._mint_holds.clear()
|
||||
rot.current_label = "bad"
|
||||
res = rot._rotate_clash_locked(cfg={})
|
||||
assert res.get("pick") != "pair_affinity"
|
||||
# OFF must round-robin off "bad" to "other", never the good-pair "good".
|
||||
assert res["node"] == "other"
|
||||
assert calls["node"] == "other"
|
||||
|
||||
|
||||
def test_nudge_list_picks_preferred_when_good_pair(tmp_path, monkeypatch):
|
||||
"""Layer ③ list path: a good, non-cooled pair node is preferred over RR."""
|
||||
p = tmp_path / "s.json"
|
||||
p.write_text(json.dumps({"version": 1, "nodes": {},
|
||||
"pairs": {"a.com|good": {"score": 80, "ok": 2, "cool_until": 0.0}}}),
|
||||
encoding="utf-8")
|
||||
os.environ["NODE_SCORE_PATH"] = str(p)
|
||||
ns.set_correlation_enabled(True)
|
||||
proxy_rotate.set_registration_domain("a.com")
|
||||
rot = proxy_rotate.get_rotator()
|
||||
rot.mode = "list"
|
||||
rot._started = True
|
||||
rot.accounts_on_current = 1 # skip first-claim branch
|
||||
rot._mint_holds.clear()
|
||||
rot.list_pool = ["bad", "other", "good"]
|
||||
rot.list_index = 0
|
||||
rot.current_proxy = "bad" # prev / "now"
|
||||
monkeypatch.setattr(ns, "scoring_enabled", lambda cfg=None: False)
|
||||
res = rot._rotate_list_locked(cfg={"email_ip_correlation": True})
|
||||
assert res["rotated"] is True
|
||||
# "good" is the pair node; RR successor off "bad" would be "other".
|
||||
assert res["proxy"] == "good"
|
||||
assert res["pick"] == "pair_affinity"
|
||||
assert rot.list_index == 2
|
||||
|
||||
|
||||
def test_nudge_list_off_round_robins_unchanged(tmp_path, monkeypatch):
|
||||
"""OFF: the restructured list scored-pick block must keep RR behavior.
|
||||
|
||||
scoring_enabled False + correlation OFF -> raise RuntimeError inside the
|
||||
scored-pick try -> caught -> nxt stays "" -> RR advances one off prev.
|
||||
"""
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
ns.set_correlation_enabled(False)
|
||||
proxy_rotate.set_registration_domain("a.com") # hint set but OFF
|
||||
rot = proxy_rotate.get_rotator()
|
||||
rot.mode = "list"
|
||||
rot._started = True
|
||||
rot.accounts_on_current = 1
|
||||
rot._mint_holds.clear()
|
||||
rot.list_pool = ["n0", "n1", "n2"]
|
||||
rot.list_index = 1 # invariant: tracks current_proxy
|
||||
rot.current_proxy = "n1" # prev -> RR successor is n2 (index 2)
|
||||
monkeypatch.setattr(ns, "scoring_enabled", lambda cfg=None: False)
|
||||
res = rot._rotate_list_locked(cfg={})
|
||||
assert res["proxy"] == "n2"
|
||||
assert res["pick"] == "round_robin"
|
||||
assert rot.list_index == 2
|
||||
# and a leaked hint was never consulted (no pair_affinity)
|
||||
assert res.get("pick") != "pair_affinity"
|
||||
|
||||
|
||||
def test_sweep_stale_mint_holds_reaps_leaked_pin():
|
||||
"""A mint hold whose release never decremented (mint killed before finally,
|
||||
or release raised) must not pin the leaf forever. Sweep drops holds older
|
||||
than MINT_HOLD_TTL_SEC; fresh holds survive."""
|
||||
import time as _t
|
||||
rot = proxy_rotate.get_rotator()
|
||||
with rot._lock:
|
||||
rot._mint_holds.clear()
|
||||
rot._mint_hold_since.clear()
|
||||
# leaked: stamped older than TTL
|
||||
rot._mint_holds["dead_node"] = 1
|
||||
rot._mint_hold_since["dead_node"] = _t.monotonic() - proxy_rotate.MINT_HOLD_TTL_SEC - 5
|
||||
# live: just created
|
||||
rot._mint_holds["live_node"] = 2
|
||||
rot._mint_hold_since["live_node"] = _t.monotonic()
|
||||
reaped = rot._sweep_stale_mint_holds_locked()
|
||||
assert reaped == 1
|
||||
holds = rot._active_mint_holds_locked()
|
||||
assert "dead_node" not in holds
|
||||
assert holds["live_node"] == 2
|
||||
# since-timestamp for dead cleared so a re-acquire stamps fresh
|
||||
assert "dead_node" not in rot._mint_hold_since
|
||||
|
||||
|
||||
def test_force_advance_leaves_dead_leaf(monkeypatch):
|
||||
"""Regression: when pick_next returns the CURRENT node (the sole non-cooled
|
||||
leaf because every other node is cooled), a force_advance rotate used to
|
||||
return single_or_same_node and silently keep the dead leaf — defeating the
|
||||
whole fail-fast zero-gain path. Now force_advance forces the best OTHER
|
||||
node, or signals force_advance_reload_needed when the pool has no other."""
|
||||
rot = proxy_rotate.get_rotator()
|
||||
rot.mode = "clash"
|
||||
rot._started = True
|
||||
rot.clash_setup_done = True
|
||||
rot._mint_holds.clear()
|
||||
rot._mint_hold_since.clear()
|
||||
rot.current_label = "cur"
|
||||
monkeypatch.setattr(proxy_rotate, "clash_list_nodes",
|
||||
lambda *a, **k: (["cur", "low1", "low2"], "cur", {}))
|
||||
switched = {}
|
||||
def _fake_switch(api, group, node, *, secret="", flush=True):
|
||||
switched["node"] = node
|
||||
return {"ok": True}
|
||||
monkeypatch.setattr(proxy_rotate, "clash_switch_node", _fake_switch)
|
||||
# force pick_next to return the current node (the failing condition)
|
||||
monkeypatch.setattr(ns, "pick_next", lambda nodes, now, **k: "cur")
|
||||
monkeypatch.setattr(ns, "preferred_node_for", lambda *a, **k: "")
|
||||
monkeypatch.setattr(ns, "correlation_enabled", lambda cfg=None: False)
|
||||
monkeypatch.setattr(ns, "scoring_enabled", lambda cfg=None: True)
|
||||
monkeypatch.setattr(ns, "get_score", lambda n, cfg=None: {"low1": 10, "low2": 20}.get(n, 0))
|
||||
res = rot._rotate_clash_locked(force_advance=True, cfg={})
|
||||
assert res["rotated"] is True, res
|
||||
assert res["node"] == "low2", res # best-scored other
|
||||
assert res.get("pick") == "force_advance_best_other", res
|
||||
assert switched["node"] == "low2"
|
||||
|
||||
# single-node pool → reload signal, not a silent no-op
|
||||
monkeypatch.setattr(proxy_rotate, "clash_list_nodes",
|
||||
lambda *a, **k: (["cur"], "cur", {}))
|
||||
res2 = rot._rotate_clash_locked(force_advance=True, cfg={})
|
||||
assert res2["rotated"] is False
|
||||
assert res2["reason"] == "force_advance_reload_needed", res2
|
||||
@@ -0,0 +1,80 @@
|
||||
import os
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
# register_cli is heavy; import lazily and tolerate optional deps.
|
||||
rc = pytest.importorskip("register_cli")
|
||||
|
||||
|
||||
def _reset():
|
||||
for k in ("EMAIL_IP_CORRELATION", "NODE_SCORE", "NODE_SCORE_ENABLED",
|
||||
"NODE_SCORE_PATH"):
|
||||
os.environ.pop(k, None)
|
||||
try:
|
||||
import node_score as ns
|
||||
ns.reset_cache()
|
||||
ns.set_enabled(None)
|
||||
ns.set_correlation_enabled(None)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def setup_function(_):
|
||||
_reset()
|
||||
|
||||
|
||||
def teardown_function(_):
|
||||
_reset()
|
||||
|
||||
|
||||
def test_record_correlation_domain_off_is_noop(tmp_path, monkeypatch):
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
os.environ["EMAIL_IP_CORRELATION"] = "0"
|
||||
out = rc._record_correlation_domain("u@a.com", "turnstile",
|
||||
cfg={})
|
||||
assert out["ok"] is False
|
||||
assert not (tmp_path / "s.json").exists()
|
||||
|
||||
|
||||
def test_record_correlation_domain_on_writes(tmp_path):
|
||||
import json
|
||||
import node_score as ns
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "s.json")
|
||||
ns.set_correlation_enabled(True)
|
||||
out = rc._record_correlation_domain("u@a.com", "turnstile",
|
||||
cfg={"email_ip_correlation": True})
|
||||
assert out["ok"] is True
|
||||
data = json.loads((tmp_path / "s.json").read_text(encoding="utf-8"))
|
||||
assert "a.com" in data["domains"]
|
||||
|
||||
|
||||
def test_registration_domain_of_parsing():
|
||||
assert rc._registration_domain_of("User@HotMail.COM") == "hotmail.com"
|
||||
assert rc._registration_domain_of("") == ""
|
||||
assert rc._registration_domain_of("noatsign") == "noatsign"
|
||||
|
||||
|
||||
def test_pre_code_failure_does_not_dock_ip(tmp_path):
|
||||
"""Layer ① boundary: a pre-code (mail_miss) failure records a DOMAIN penalty
|
||||
but leaves the IP node's score untouched. Equivalent to "do not call
|
||||
note_egress_outcome for IP" — verified by asserting the IP entry is unchanged
|
||||
after routing the domain penalty (uses the real node_score writer).
|
||||
"""
|
||||
import json
|
||||
import node_score as ns
|
||||
os.environ["NODE_SCORE_PATH"] = str(tmp_path / "b.json")
|
||||
(tmp_path / "b.json").write_text(json.dumps({
|
||||
"version": 1, "nodes": {"n1": {"score": 71, "cool_until": 0.0,
|
||||
"ok": 3, "fail_ts": 0, "fail_boot": 0}}}),
|
||||
encoding="utf-8")
|
||||
ns.set_correlation_enabled(True)
|
||||
out = rc._record_correlation_domain("u@a.com", "mail_miss",
|
||||
cfg={"email_ip_correlation": True})
|
||||
assert out["ok"] is True
|
||||
data = json.loads((tmp_path / "b.json").read_text(encoding="utf-8"))
|
||||
# DOMAIN was penalized...
|
||||
assert data["domains"]["a.com"]["score"] == ns.DEFAULT_SCORE - ns.PENALTY_OTHER
|
||||
# ...but the IP node is byte-for-byte intact (no note_egress_outcome happened):
|
||||
assert data["nodes"]["n1"] == {"score": 71, "cool_until": 0.0, "ok": 3,
|
||||
"fail_ts": 0, "fail_boot": 0}
|
||||
@@ -0,0 +1,868 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unit tests for register_core (no live register)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from unittest.mock import patch
|
||||
|
||||
from register_core.contracts import Mailbox, RegisterJob, RegisterResult
|
||||
from register_core.email.registry import list_email_sources
|
||||
from register_core.errors import FailFastError
|
||||
from register_core.pipeline import Pipeline, PipelineStats
|
||||
from register_core.providers.grok_adapter import GrokProvider
|
||||
from register_core.providers.mimo_adapter import MimoProvider
|
||||
from register_core.providers.registry import list_providers
|
||||
from register_core.sink.jsonl_sink import JsonlSink
|
||||
from register_core.util.files import file_size, read_appended
|
||||
from register_core.util.process import CmdResult, redact_log_tail
|
||||
from register_core.verify.mimo_tts import MimoTtsVerifier
|
||||
from register_core.verify.noop import NoopVerifier
|
||||
|
||||
|
||||
class FakeEmail:
|
||||
name = "fake"
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.released: list[tuple[str, bool]] = []
|
||||
self.alloc_calls = 0
|
||||
|
||||
def allocate(self) -> Mailbox:
|
||||
self.alloc_calls += 1
|
||||
return Mailbox(address="a@example.com", token="t", provider=self.name)
|
||||
|
||||
def poll_otp(self, mailbox: Mailbox, **kwargs: Any):
|
||||
from register_core.contracts import OtpCode
|
||||
|
||||
return OtpCode(code="123456", source=self.name)
|
||||
|
||||
def release(self, mailbox: Mailbox, *, success: bool) -> None:
|
||||
self.released.append((mailbox.address, success))
|
||||
|
||||
|
||||
class FakeProvider:
|
||||
name = "fake"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
outcomes: list[RegisterResult] | None = None,
|
||||
raise_fatal_on: int | None = None,
|
||||
raise_verify_bomb: bool = False,
|
||||
) -> None:
|
||||
self.outcomes = list(outcomes or [])
|
||||
self.calls = 0
|
||||
self.raise_fatal_on = raise_fatal_on
|
||||
self.seen_email_source = None
|
||||
|
||||
def register_one(self, *, email_source=None, extra=None) -> RegisterResult:
|
||||
self.calls += 1
|
||||
self.seen_email_source = email_source
|
||||
if self.raise_fatal_on is not None and self.calls == self.raise_fatal_on:
|
||||
raise FailFastError("pool exhausted")
|
||||
if self.outcomes:
|
||||
return self.outcomes.pop(0)
|
||||
return RegisterResult(
|
||||
ok=True,
|
||||
provider=self.name,
|
||||
email="a@example.com",
|
||||
secret="sk-" + "a" * 40,
|
||||
secret_kind="api_key",
|
||||
)
|
||||
|
||||
|
||||
class BoomVerifier:
|
||||
name = "boom"
|
||||
|
||||
def verify(self, result: RegisterResult):
|
||||
raise RuntimeError("probe exploded")
|
||||
|
||||
|
||||
class TestContractExit(unittest.TestCase):
|
||||
"""Authoritative run-time contract exit: 0 ok>=1 | 1 retryable | 2 fatal.
|
||||
|
||||
Regression for the grok shell-out exit mapping (migrate milestone A review
|
||||
fix). The prior ``run-register-core.sh`` bridge grepped log prose for
|
||||
"fail_fast"/"fatal:" and silently DOWNGRADED hard-stops whose stopped_reason
|
||||
carries no such substring — notably a strategy domain-burn stop
|
||||
("strategy: domain burned: ...") and the post-loop fail_fast stop reading
|
||||
``result.error_kind``. register_core.cli now prints ``CONTRACT_EXIT:N``
|
||||
computed by ``_contract_exit_from_stats`` from the structured
|
||||
``stats.stopped_reason``, and run-register-core.sh trusts that line. These
|
||||
tests pin the contract so a rename / weak-predicate regression can't sneak
|
||||
exit 1 back in for a true batch-stop.
|
||||
"""
|
||||
|
||||
def _ce(self, *, ok=0, fail=0, stopped_reason=""):
|
||||
# Local import avoids binding the function as a descriptor (a ``from …
|
||||
# import`` of a plain function inside a class body turns it into a
|
||||
# bound method on instances, re-passing self into the 1-arg helper).
|
||||
from register_core.cli import _contract_exit_from_stats
|
||||
|
||||
stats = PipelineStats(ok=ok, fail=fail, stopped_reason=stopped_reason)
|
||||
return _contract_exit_from_stats(stats), stats
|
||||
|
||||
def test_ok_returns_0(self):
|
||||
ce, _ = self._ce(ok=2, fail=0)
|
||||
self.assertEqual(ce, 0)
|
||||
|
||||
def test_retryable_exhaustion_no_stop_returns_1(self):
|
||||
# All attempts fail, NO early-break stop (re-run may succeed) → exit 1.
|
||||
ce, stats = self._ce(ok=0, fail=3, stopped_reason="")
|
||||
self.assertEqual(ce, 1)
|
||||
self.assertFalse(stats.stopped_reason)
|
||||
|
||||
def test_loop_fatal_failfast_returns_2(self):
|
||||
# FailFastError caught in-loop → stopped_reason="fail_fast: ...".
|
||||
ce, _ = self._ce(ok=0, fail=1, stopped_reason="fail_fast: pool exhausted")
|
||||
self.assertEqual(ce, 2)
|
||||
|
||||
def test_strategy_domain_burn_hardstop_returns_2(self):
|
||||
# The exact case the old grep bridge downgraded to exit 1: a strategy
|
||||
# domain-burn break with stopped_reason="strategy: ..." carries no
|
||||
# "fail_fast"/"fatal:" substring → must still be contract exit 2.
|
||||
ce, _ = self._ce(
|
||||
ok=0, fail=1, stopped_reason="strategy: domain burned: bad.example"
|
||||
)
|
||||
self.assertEqual(ce, 2)
|
||||
|
||||
def test_post_loop_failfast_kindstop_returns_2(self):
|
||||
# Post-loop fail_fast stop where stopped_reason == result.error_kind
|
||||
# ("registration_disallowed" etc., NOT "fatal") — still a batch stop.
|
||||
ce, _ = self._ce(ok=0, fail=1, stopped_reason="registration_disallowed")
|
||||
self.assertEqual(ce, 2)
|
||||
|
||||
def test_mail_miss_early_stop_returns_2(self):
|
||||
ce, _ = self._ce(ok=0, fail=1, stopped_reason="mail_miss: no mail")
|
||||
self.assertEqual(ce, 2)
|
||||
|
||||
def test_unexpected_core_error_returns_2(self):
|
||||
ce, _ = self._ce(ok=0, fail=1, stopped_reason="unexpected: boom")
|
||||
self.assertEqual(ce, 2)
|
||||
|
||||
|
||||
class TestRegistry(unittest.TestCase):
|
||||
def test_lists_builtins(self):
|
||||
ps = list_providers()
|
||||
self.assertIn("grok", ps)
|
||||
self.assertIn("mimo", ps)
|
||||
self.assertIn("chatgpt", ps)
|
||||
es = list_email_sources()
|
||||
self.assertIn("tinyhost", es)
|
||||
self.assertIn("legacy_grok", es)
|
||||
self.assertIn("cloudflare", es)
|
||||
self.assertIn("gmail_imap", es)
|
||||
|
||||
|
||||
class TestContracts(unittest.TestCase):
|
||||
def test_public_redacts_password_and_secret(self):
|
||||
r = RegisterResult(
|
||||
ok=True,
|
||||
provider="x",
|
||||
email="e@x.com",
|
||||
password="supersecretpw",
|
||||
secret="sk-abcdefghijklmnopqrstuvwxyz",
|
||||
secret_kind="api_key",
|
||||
artifacts={"tail": "验证码: 123456 sk-abcdefghijklmnopqrstuvwxyz"},
|
||||
)
|
||||
pub = r.to_public_dict()
|
||||
self.assertNotIn("supersecretpw", json.dumps(pub))
|
||||
self.assertNotIn("sk-abcdefghijklmnopqrstuvwxyz", json.dumps(pub))
|
||||
self.assertNotEqual(pub["password"], "supersecretpw")
|
||||
self.assertIn("tail_redacted", pub["artifacts"])
|
||||
self.assertNotIn("123456", pub["artifacts"]["tail_redacted"])
|
||||
|
||||
def test_redact_log_tail(self):
|
||||
t = redact_log_tail("验证码: 654321\nkey sk-abcdef0123456789abcdef")
|
||||
self.assertNotIn("654321", t)
|
||||
self.assertNotIn("sk-abcdef0123456789abcdef", t)
|
||||
|
||||
|
||||
class TestPipeline(unittest.TestCase):
|
||||
# Offline runs must not probe local nodes.json (backend auto + catalog hang).
|
||||
_OFFLINE_EXTRA = {"egress": "direct", "nodes_preflight": False}
|
||||
|
||||
def test_fail_fast_stops(self):
|
||||
p = FakeProvider(
|
||||
outcomes=[
|
||||
RegisterResult(ok=False, provider="fake", error="x", error_kind="provider"),
|
||||
RegisterResult(ok=True, provider="fake"),
|
||||
]
|
||||
)
|
||||
pipe = Pipeline(p, fail_fast=True, verifier=NoopVerifier())
|
||||
stats = pipe.run(3, extra=dict(self._OFFLINE_EXTRA))
|
||||
self.assertEqual(p.calls, 1)
|
||||
self.assertEqual(stats.fail, 1)
|
||||
self.assertEqual(stats.ok, 0)
|
||||
self.assertTrue(stats.stopped_reason)
|
||||
|
||||
def test_threads_do_not_fanout_non_typesafe(self):
|
||||
p = FakeProvider(
|
||||
outcomes=[
|
||||
RegisterResult(ok=True, provider="fake"),
|
||||
RegisterResult(ok=True, provider="fake"),
|
||||
]
|
||||
)
|
||||
pipe = Pipeline(p, fail_fast=True, verifier=NoopVerifier())
|
||||
extra = dict(self._OFFLINE_EXTRA)
|
||||
extra["threads"] = 8
|
||||
stats = pipe.run(2, extra=extra)
|
||||
self.assertEqual(p.calls, 2)
|
||||
self.assertEqual(stats.ok, 2)
|
||||
self.assertEqual(pipe._worker_count(extra, 2), 1)
|
||||
|
||||
def test_fatal_exception_stops(self):
|
||||
p = FakeProvider(raise_fatal_on=1)
|
||||
pipe = Pipeline(p, fail_fast=True)
|
||||
stats = pipe.run(5, extra=dict(self._OFFLINE_EXTRA))
|
||||
self.assertEqual(stats.fail, 1)
|
||||
self.assertIn("fail_fast", stats.stopped_reason)
|
||||
|
||||
def test_verify_exception_marks_fail_even_without_fail_fast(self):
|
||||
p = FakeProvider(
|
||||
outcomes=[
|
||||
RegisterResult(
|
||||
ok=True,
|
||||
provider="fake",
|
||||
email="e@x.com",
|
||||
secret="sk-" + "b" * 40,
|
||||
secret_kind="api_key",
|
||||
)
|
||||
]
|
||||
)
|
||||
pipe = Pipeline(p, fail_fast=False, verifier=BoomVerifier())
|
||||
stats = pipe.run(1, extra=dict(self._OFFLINE_EXTRA))
|
||||
self.assertEqual(stats.ok, 0)
|
||||
self.assertEqual(stats.fail, 1)
|
||||
self.assertEqual(stats.results[0].error_kind, "verify")
|
||||
|
||||
def test_shell_providers_accept_external_email_source(self):
|
||||
"""M3/M4: mimo/grok consume EmailSource via FIXED_EMAIL inject (no black-box gate)."""
|
||||
for provider in ("mimo", "grok"):
|
||||
job = RegisterJob(provider=provider, email_source="tinyhost")
|
||||
pipe = Pipeline.from_job(job)
|
||||
self.assertIsNotNone(pipe.email_source)
|
||||
self.assertEqual(getattr(pipe.email_source, "name", ""), "tinyhost")
|
||||
self.assertIsNotNone(pipe.strategy)
|
||||
|
||||
def test_sink_jsonl_mode_0600(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
path = Path(td) / "out.jsonl"
|
||||
sink = JsonlSink(path)
|
||||
p = FakeProvider(
|
||||
outcomes=[
|
||||
RegisterResult(
|
||||
ok=True,
|
||||
provider="fake",
|
||||
email="e@x.com",
|
||||
secret="sk-secretvalue1234567890",
|
||||
secret_kind="api_key",
|
||||
password="pw-secret",
|
||||
)
|
||||
]
|
||||
)
|
||||
pipe = Pipeline(p, sink=sink, verifier=NoopVerifier())
|
||||
stats = pipe.run(1, extra=dict(self._OFFLINE_EXTRA))
|
||||
self.assertEqual(stats.ok, 1)
|
||||
mode = stat.S_IMODE(path.stat().st_mode)
|
||||
self.assertEqual(mode, 0o600)
|
||||
data = json.loads(path.read_text(encoding="utf-8").strip())
|
||||
self.assertEqual(data["secret"], "sk-secretvalue1234567890")
|
||||
|
||||
|
||||
class TestMimoVerifier(unittest.TestCase):
|
||||
def test_shape(self):
|
||||
v = MimoTtsVerifier(live=False)
|
||||
bad = v.verify(RegisterResult(ok=True, provider="mimo", secret="nope"))
|
||||
self.assertFalse(bad.ok)
|
||||
good = v.verify(RegisterResult(ok=True, provider="mimo", secret="sk-" + "a" * 40))
|
||||
self.assertTrue(good.ok)
|
||||
# Hyphenated / underscored vendor keys must pass the same shape gate as inject.
|
||||
hyphen = v.verify(
|
||||
RegisterResult(
|
||||
ok=True,
|
||||
provider="mimo",
|
||||
secret="sk-hyper-abc-def-0123456789abcdef",
|
||||
)
|
||||
)
|
||||
self.assertTrue(hyphen.ok)
|
||||
under = v.verify(
|
||||
RegisterResult(
|
||||
ok=True,
|
||||
provider="mimo",
|
||||
secret="sk-cdqo_test_underscore_0123456789",
|
||||
)
|
||||
)
|
||||
self.assertTrue(under.ok)
|
||||
|
||||
|
||||
class TestSecretPatterns(unittest.TestCase):
|
||||
def test_hyphen_underscore_api_keys(self):
|
||||
from register_core.util.secrets import find_api_keys, is_api_key
|
||||
|
||||
self.assertTrue(is_api_key("sk-" + "a" * 24))
|
||||
self.assertTrue(is_api_key("sk-hyper-abc-def-0123456789abcdef"))
|
||||
self.assertTrue(is_api_key("sk-cdqo_test_underscore_0123456789"))
|
||||
self.assertFalse(is_api_key("sk-short"))
|
||||
self.assertFalse(is_api_key("not-a-key"))
|
||||
found = find_api_keys("x sk-hyper-abc-def-0123456789abcdef y")
|
||||
self.assertEqual(len(found), 1)
|
||||
|
||||
def test_redact_hyphenated_key(self):
|
||||
t = redact_log_tail("got sk-hyper-abc-def-0123456789abcdef done")
|
||||
self.assertNotIn("sk-hyper-abc-def-0123456789abcdef", t)
|
||||
self.assertIn("sk-***", t)
|
||||
|
||||
def test_mimo_parse_hyphenated_result_json(self):
|
||||
key = "sk-hyper-abc-def-0123456789abcdef"
|
||||
stdout = (
|
||||
'RESULT_JSON:{"status":"SUCCESS","email":"n@x.com",'
|
||||
f'"password":"p","apiKey":"{key}"}}\n'
|
||||
)
|
||||
email, secret, password = MimoProvider._parse_this_run(
|
||||
stdout=stdout,
|
||||
keys_delta="",
|
||||
accounts_delta="",
|
||||
)
|
||||
self.assertEqual(email, "n@x.com")
|
||||
self.assertEqual(secret, key)
|
||||
self.assertEqual(password, "p")
|
||||
|
||||
|
||||
class TestGrokVerifierHonesty(unittest.TestCase):
|
||||
def test_pending_sso_fails_default_verifier(self):
|
||||
from register_core.verify.grok_chat import GrokChatVerifier
|
||||
|
||||
v = GrokChatVerifier()
|
||||
r = v.verify(
|
||||
RegisterResult(
|
||||
ok=True,
|
||||
provider="grok",
|
||||
email="u@x.com",
|
||||
secret="",
|
||||
secret_kind="pending",
|
||||
)
|
||||
)
|
||||
self.assertFalse(r.ok)
|
||||
self.assertIn("missing sso", r.detail.lower())
|
||||
|
||||
def test_sso_soft_passes_without_live_chat(self):
|
||||
from register_core.verify.grok_chat import GrokChatVerifier
|
||||
|
||||
v = GrokChatVerifier()
|
||||
r = v.verify(
|
||||
RegisterResult(
|
||||
ok=True,
|
||||
provider="grok",
|
||||
email="u@x.com",
|
||||
secret="eyJhbGciOiJIUzI1NiJ9.aaa.bbb",
|
||||
secret_kind="sso",
|
||||
)
|
||||
)
|
||||
self.assertTrue(r.ok)
|
||||
self.assertIn("deferred", r.detail)
|
||||
|
||||
|
||||
class TestProcessTimeout(unittest.TestCase):
|
||||
def test_timeout_kills_and_sets_flag(self):
|
||||
import sys
|
||||
|
||||
from register_core.util.process import run_command
|
||||
|
||||
# Short sleep child; timeout forces process-group kill path.
|
||||
code = "import time; time.sleep(30)"
|
||||
res = run_command([sys.executable, "-c", code], timeout_s=0.3)
|
||||
self.assertTrue(res.timed_out)
|
||||
self.assertNotEqual(res.returncode, 0)
|
||||
|
||||
|
||||
class TestJobFactory(unittest.TestCase):
|
||||
def test_from_job_builds(self):
|
||||
job = RegisterJob(provider="mimo", count=1, email_source="provider", verify=False)
|
||||
pipe = Pipeline.from_job(job)
|
||||
self.assertEqual(pipe.provider.name, "mimo")
|
||||
self.assertIsNone(pipe.email_source)
|
||||
|
||||
|
||||
class TestFileOffset(unittest.TestCase):
|
||||
def test_read_appended(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
p = Path(td) / "a.jsonl"
|
||||
p.write_text("old\n", encoding="utf-8")
|
||||
off = file_size(p)
|
||||
p.write_text("old\nnew\n", encoding="utf-8")
|
||||
self.assertEqual(read_appended(p, off).strip(), "new")
|
||||
|
||||
|
||||
class TestMimoParse(unittest.TestCase):
|
||||
def test_ignores_historical_without_delta(self):
|
||||
email, secret, password = MimoProvider._parse_this_run(
|
||||
stdout="",
|
||||
keys_delta="",
|
||||
accounts_delta="",
|
||||
)
|
||||
self.assertEqual(secret, "")
|
||||
self.assertEqual(email, "")
|
||||
|
||||
def test_result_json_line(self):
|
||||
stdout = (
|
||||
'log...\nRESULT_JSON:{"status":"SUCCESS","email":"n@x.com",'
|
||||
'"password":"p","apiKey":"sk-abcdefghijklmnopqrstuvwxyz012345"}\n'
|
||||
)
|
||||
email, secret, password = MimoProvider._parse_this_run(
|
||||
stdout=stdout,
|
||||
keys_delta="",
|
||||
accounts_delta="",
|
||||
)
|
||||
self.assertEqual(email, "n@x.com")
|
||||
self.assertTrue(secret.startswith("sk-"))
|
||||
self.assertEqual(password, "p")
|
||||
|
||||
def test_accounts_delta_only(self):
|
||||
delta = json.dumps(
|
||||
{"email": "b@x.com", "password": "pw", "apiKey": "sk-" + "c" * 40}
|
||||
) + "\n"
|
||||
email, secret, password = MimoProvider._parse_this_run(
|
||||
stdout="",
|
||||
keys_delta="",
|
||||
accounts_delta="old-should-not-matter\n" + delta
|
||||
if False
|
||||
else delta,
|
||||
)
|
||||
self.assertEqual(email, "b@x.com")
|
||||
self.assertTrue(secret.startswith("sk-"))
|
||||
|
||||
def test_adapter_uses_delta_not_full_file(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
runtime = Path(td)
|
||||
out = runtime / "output"
|
||||
out.mkdir()
|
||||
(out / "accounts.jsonl").write_text(
|
||||
json.dumps({"email": "old@x.com", "apiKey": "sk-" + "o" * 40}) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
(out / "success_keys.txt").write_text("1. sk-" + "o" * 40 + "\n", encoding="utf-8")
|
||||
off_acc = file_size(out / "accounts.jsonl")
|
||||
off_keys = file_size(out / "success_keys.txt")
|
||||
|
||||
new_key = "sk-" + "n" * 40
|
||||
# simulate this-run append
|
||||
with (out / "accounts.jsonl").open("a", encoding="utf-8") as f:
|
||||
f.write(json.dumps({"email": "new@x.com", "apiKey": new_key}) + "\n")
|
||||
with (out / "success_keys.txt").open("a", encoding="utf-8") as f:
|
||||
f.write(f"2. {new_key}\n")
|
||||
|
||||
email, secret, _ = MimoProvider._parse_this_run(
|
||||
stdout="",
|
||||
keys_delta=read_appended(out / "success_keys.txt", off_keys),
|
||||
accounts_delta=read_appended(out / "accounts.jsonl", off_acc),
|
||||
)
|
||||
self.assertEqual(email, "new@x.com")
|
||||
self.assertEqual(secret, new_key)
|
||||
|
||||
|
||||
class TestGrokParse(unittest.TestCase):
|
||||
def test_exit0_without_ledger_is_fail(self):
|
||||
provider = GrokProvider(accounts_file="/tmp/does-not-need-exist-core-test")
|
||||
fake = CmdResult(returncode=0, stdout="done without success marker\n", stderr="", timed_out=False)
|
||||
with patch("register_core.providers.grok_adapter.run_command", return_value=fake):
|
||||
with patch("register_core.providers.grok_adapter.file_size", return_value=0):
|
||||
with patch("register_core.providers.grok_adapter.read_appended", return_value=""):
|
||||
r = provider.register_one()
|
||||
self.assertFalse(r.ok)
|
||||
self.assertIn("no this-run", r.error)
|
||||
|
||||
def test_ledger_email_without_sso_is_fail(self):
|
||||
provider = GrokProvider(accounts_file="/tmp/x")
|
||||
ledger = "user@x.com----pw----\n"
|
||||
fake = CmdResult(
|
||||
returncode=0,
|
||||
stdout="+ 注册成功: user@x.com\n",
|
||||
stderr="",
|
||||
timed_out=False,
|
||||
)
|
||||
with patch("register_core.providers.grok_adapter.run_command", return_value=fake):
|
||||
with patch("register_core.providers.grok_adapter.file_size", return_value=0):
|
||||
with patch("register_core.providers.grok_adapter.read_appended", return_value=ledger):
|
||||
r = provider.register_one()
|
||||
self.assertFalse(r.ok)
|
||||
self.assertEqual(r.email, "user@x.com")
|
||||
self.assertEqual(r.secret_kind, "pending")
|
||||
self.assertIn("without SSO", r.error)
|
||||
|
||||
def test_ledger_delta_success(self):
|
||||
provider = GrokProvider(accounts_file="/tmp/x")
|
||||
ledger = "user@x.com----pw----eyJhbGciOiJIUzI1NiJ9.aaa.bbb\n"
|
||||
fake = CmdResult(
|
||||
returncode=0,
|
||||
stdout="+ 注册成功: user@x.com\n",
|
||||
stderr="",
|
||||
timed_out=False,
|
||||
)
|
||||
with patch("register_core.providers.grok_adapter.run_command", return_value=fake):
|
||||
with patch("register_core.providers.grok_adapter.file_size", return_value=0):
|
||||
with patch("register_core.providers.grok_adapter.read_appended", return_value=ledger):
|
||||
r = provider.register_one()
|
||||
self.assertTrue(r.ok)
|
||||
self.assertEqual(r.email, "user@x.com")
|
||||
self.assertEqual(r.secret_kind, "sso")
|
||||
self.assertTrue(r.secret.startswith("eyJ"))
|
||||
|
||||
def test_extra_proxy_forwarded_to_env(self):
|
||||
"""Pipeline inject_attempt_proxy must reach register_cli via PROXY env."""
|
||||
provider = GrokProvider(accounts_file="/tmp/x")
|
||||
captured: dict = {}
|
||||
want = "http://user:pw@10.0.0.9:9000"
|
||||
|
||||
def _capture_run(cmd, cwd=None, env=None, timeout_s=None): # noqa: ARG001
|
||||
captured["env"] = dict(env or {})
|
||||
return CmdResult(returncode=1, stdout="fail", stderr="", timed_out=False)
|
||||
|
||||
# Isolate from ambient PROXY/CPA_PROXY left by other tests or host env.
|
||||
scrub = {
|
||||
k: v
|
||||
for k, v in os.environ.items()
|
||||
if k not in {"PROXY", "CPA_PROXY", "HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"}
|
||||
}
|
||||
with patch.dict(os.environ, scrub, clear=True):
|
||||
with patch(
|
||||
"register_core.providers.grok_adapter.run_command",
|
||||
side_effect=_capture_run,
|
||||
):
|
||||
with patch("register_core.providers.grok_adapter.file_size", return_value=0):
|
||||
provider.register_one(extra={"proxy": want})
|
||||
self.assertEqual(captured.get("env", {}).get("PROXY"), want)
|
||||
self.assertEqual(captured.get("env", {}).get("CPA_PROXY"), want)
|
||||
|
||||
|
||||
class TestGrokFatalContract(unittest.TestCase):
|
||||
"""register_cli exit-code contract (authoritative, machine-readable):
|
||||
exit 2 = fatal; exit 1 = retryable not-product; exit 0 = product ok.
|
||||
SUMMARY_JSON "fatal" bool is the cross-check. The old substring matcher
|
||||
(`"fatal" in lower(out)`) mis-promoted exit-1 OTP timeouts — which always
|
||||
print `"fatal":false` and the key "fatal_reason" — to FailFastError, stopping
|
||||
the whole batch on a single transient failure (pxed smoke regression).
|
||||
|
||||
`_SUMMARY` mimics the real register_cli tail (=== 完成 ... ===, banner line,
|
||||
then `SUMMARY_JSON {...}` on its own line).
|
||||
"""
|
||||
|
||||
_OK_SUMMARY = (
|
||||
'=== 完成: 注册成功 0, 注册失败 1 ===\n'
|
||||
'[!] 本批未达到产品可用 free Build 标准\n'
|
||||
'SUMMARY_JSON {"event":"register_cli_summary","exit":1,"reg_success":0,'
|
||||
'"reg_fail":1,"fatal":false,"fatal_reason":"","product_ok":false}\n'
|
||||
)
|
||||
_FATAL_SUMMARY = (
|
||||
'=== 完成: 注册成功 0, 注册失败 1 ===\n'
|
||||
'[!] 致命错误已停止任务(不空转): 可用别名已耗尽\n'
|
||||
'SUMMARY_JSON {"event":"register_cli_summary","exit":2,"reg_success":0,'
|
||||
'"reg_fail":1,"fatal":true,"fatal_reason":"可用别名已耗尽","product_ok":false}\n'
|
||||
)
|
||||
|
||||
def test_exit1_summary_fatalfalse_is_not_failfast(self):
|
||||
# Regression: pxed grok smoke hit a transient OTP timeout → register_cli
|
||||
# exit=1 with "fatal":false; the old substring matcher raised FailFastError
|
||||
# because `"fatal" in lower(out)` matched the JSON key/value. Must be a
|
||||
# recoverable provider failure (error_kind=provider), not fatal.
|
||||
provider = GrokProvider(accounts_file="/tmp/x")
|
||||
fake = CmdResult(returncode=1, stdout=self._OK_SUMMARY, stderr="", timed_out=False)
|
||||
with patch("register_core.providers.grok_adapter.run_command", return_value=fake):
|
||||
with patch("register_core.providers.grok_adapter.file_size", return_value=0):
|
||||
with patch("register_core.providers.grok_adapter.read_appended", return_value=""):
|
||||
r = provider.register_one()
|
||||
self.assertFalse(r.ok)
|
||||
self.assertEqual(r.error_kind, "provider", "exit-1 non-fatal must be provider, not fatal")
|
||||
self.assertNotIn("fail_fast", (r.error or "").lower())
|
||||
|
||||
def test_exit2_is_failfast(self):
|
||||
provider = GrokProvider(accounts_file="/tmp/x")
|
||||
fake = CmdResult(returncode=2, stdout=self._FATAL_SUMMARY, stderr="", timed_out=False)
|
||||
with patch("register_core.providers.grok_adapter.run_command", return_value=fake):
|
||||
with patch("register_core.providers.grok_adapter.file_size", return_value=0):
|
||||
with patch("register_core.providers.grok_adapter.read_appended", return_value=""):
|
||||
with self.assertRaises(FailFastError) as ctx:
|
||||
provider.register_one()
|
||||
# authority contract reason surfaces (not the old bare "exit=2")
|
||||
self.assertIn("可用别名已耗尽", str(ctx.exception))
|
||||
|
||||
def test_summary_fatal_true_promotes_exit1_to_failfast(self):
|
||||
# Cross-check via SUMMARY_JSON: if register_cli says fatal:true even at exit=1
|
||||
# (shouldn't happen by contract, but the JSON is authoritative) we honor it.
|
||||
provider = GrokProvider(accounts_file="/tmp/x")
|
||||
sum1 = self._FATAL_SUMMARY.replace('"exit":2', '"exit":1')
|
||||
fake = CmdResult(returncode=1, stdout=sum1, stderr="", timed_out=False)
|
||||
with patch("register_core.providers.grok_adapter.run_command", return_value=fake):
|
||||
with patch("register_core.providers.grok_adapter.file_size", return_value=0):
|
||||
with patch("register_core.providers.grok_adapter.read_appended", return_value=""):
|
||||
with self.assertRaises(FailFastError):
|
||||
provider.register_one()
|
||||
|
||||
def test_no_summary_no_output_is_failfast(self):
|
||||
# No output at all (orphan before main) → treat as fatal spawn.
|
||||
provider = GrokProvider(accounts_file="/tmp/x")
|
||||
fake = CmdResult(returncode=1, stdout="", stderr="", timed_out=False)
|
||||
with patch("register_core.providers.grok_adapter.run_command", return_value=fake):
|
||||
with patch("register_core.providers.grok_adapter.file_size", return_value=0):
|
||||
with patch("register_core.providers.grok_adapter.read_appended", return_value=""):
|
||||
with self.assertRaises(FailFastError):
|
||||
provider.register_one()
|
||||
|
||||
def test_exit1_otp_timeout_is_not_failfast(self):
|
||||
# Even when stdout contains a Traceback (OTP timeout), exit=1 + "fatal":false
|
||||
# must NOT be fail-fast. The OTP timeout is a retryable provider error.
|
||||
provider = GrokProvider(accounts_file="/tmp/x")
|
||||
stdout = (
|
||||
'=== 完成: 注册成功 0, 注册失败 1 ===\n'
|
||||
'SUMMARY_JSON {"event":"register_cli_summary","exit":1,"reg_fail":1,'
|
||||
'"fatal":false,"fatal_reason":"","product_ok":false}\n'
|
||||
'Traceback (most recent call last):\n'
|
||||
' File "register_cli.py", line 666, in register_one\n'
|
||||
' code = reg.fill_code_and_submit(\n'
|
||||
'Exception: fixed core OTP timeout for x@publicvm.com: timed out after 30.0 seconds\n'
|
||||
)
|
||||
fake = CmdResult(returncode=1, stdout=stdout, stderr="", timed_out=False)
|
||||
with patch("register_core.providers.grok_adapter.run_command", return_value=fake):
|
||||
with patch("register_core.providers.grok_adapter.file_size", return_value=0):
|
||||
with patch("register_core.providers.grok_adapter.read_appended", return_value=""):
|
||||
r = provider.register_one()
|
||||
self.assertFalse(r.ok)
|
||||
self.assertEqual(r.error_kind, "provider")
|
||||
|
||||
|
||||
|
||||
class TestMimoFatalContract(unittest.TestCase):
|
||||
"""MiMo classify contract (authoritative, machine-readable):
|
||||
register-one.js emits ``RESULT_JSON:{status, email, error, at}`` and sets
|
||||
``process.exitCode = 1`` for *every* failure (Geetest, OTP timeout, provider
|
||||
error) — there is no ``exit 2`` fatal here. run-register.sh wrapper echoes
|
||||
``[mimo] fail-fast after error code=...`` on ANY non-zero exit, so the old
|
||||
``_classify`` substring matcher (``"fail-fast" in lower(out)``) labeled every
|
||||
retryable Geetest/OTP timeout as ``error_kind="fatal"`` → StrategyEngine
|
||||
``fail_fast_kings`` stopped the whole batch on a single transient failure,
|
||||
contradicting the rerun-wins strategy for probabilistic Geetest
|
||||
(see [[project-mimo-migrate-route-ok-20260718]]).
|
||||
|
||||
Fix: ``_classify`` decodes RESULT_JSON ``status:"FAILED"`` + ``error`` as
|
||||
authority → captcha / mail_miss / provider (retryable). Only a genuinely
|
||||
empty spawn (no RESULT_JSON, no output) is fatal.
|
||||
"""
|
||||
|
||||
def _make_provider(self, tmp: str) -> MimoProvider:
|
||||
runtime = Path(tmp)
|
||||
(runtime / "output").mkdir(exist_ok=True)
|
||||
provider = MimoProvider(runtime=str(runtime))
|
||||
return provider, runtime
|
||||
|
||||
def _run(self, provider: MimoProvider, runtime: Path, stdout: str, stderr: str = "", rc: int = 1) -> RegisterResult:
|
||||
fake = CmdResult(returncode=rc, stdout=stdout, stderr=stderr, timed_out=False)
|
||||
runner = runtime / "run-register.sh"
|
||||
if not runner.is_file():
|
||||
runner.write_text("#!/bin/bash\n", encoding="utf-8")
|
||||
with patch("register_core.providers.mimo_adapter.MIMO_DIR", runtime):
|
||||
with patch("register_core.providers.mimo_adapter.file_size", return_value=0):
|
||||
with patch("register_core.providers.mimo_adapter.read_appended", return_value=""):
|
||||
with patch("register_core.providers.mimo_adapter.run_command", return_value=fake):
|
||||
return provider.register_one()
|
||||
|
||||
def test_geetest_failure_is_captcha_not_fatal(self):
|
||||
# Regression: Geetest solve failure is probabilistic + retryable. The
|
||||
# runner wrapper prints "fail-fast" on this exit-1; RESULT_JSON error
|
||||
# "geetest" must drive kind=captcha, NOT fatal.
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
provider, runtime = self._make_provider(td)
|
||||
stdout = (
|
||||
"=== mimo register 1/1 ===\n"
|
||||
"[mimo] fail-fast after error code=1 (no empty spin)\n"
|
||||
"RESULT_JSON:" + json.dumps(
|
||||
{"status": "FAILED", "email": "r1@boom", "error": "geetest challenge failed"}
|
||||
) + "\n"
|
||||
)
|
||||
r = self._run(provider, runtime, stdout=stdout, rc=1)
|
||||
self.assertFalse(r.ok)
|
||||
self.assertEqual(r.error_kind, "captcha", "Geetest failure must be retryable captcha, not fatal")
|
||||
self.assertNotIn("fatal", (r.error_kind or ""))
|
||||
|
||||
def test_otp_timeout_is_mail_miss_not_fatal(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
provider, runtime = self._make_provider(td)
|
||||
stdout = (
|
||||
"[mimo] fail-fast after error code=1 (no empty spin)\n"
|
||||
"RESULT_JSON:" + json.dumps(
|
||||
{"status": "FAILED", "email": "r2@boom", "error": "otp timeout: no mail in 180s"}
|
||||
) + "\n"
|
||||
)
|
||||
r = self._run(provider, runtime, stdout=stdout, rc=1)
|
||||
self.assertFalse(r.ok)
|
||||
self.assertEqual(r.error_kind, "mail_miss", "OTP timeout must be retryable mail_miss")
|
||||
|
||||
def test_empty_spawn_is_fatal(self):
|
||||
# No RESULT_JSON + empty output → fatal spawn (orphan before main).
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
provider, runtime = self._make_provider(td)
|
||||
r = self._run(provider, runtime, stdout="", stderr="", rc=1)
|
||||
self.assertFalse(r.ok)
|
||||
self.assertEqual(r.error_kind, "fatal", "empty spawn with no authority must be fatal")
|
||||
|
||||
def test_generic_failed_error_is_provider_not_fatal(self):
|
||||
# RESULT_JSON FAILED with a non-captcha, non-otp, non-alias error → provider
|
||||
# (retryable), never fatal.
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
provider, runtime = self._make_provider(td)
|
||||
stdout = (
|
||||
"[mimo] fail-fast after error code=1 (no empty spin)\n"
|
||||
"RESULT_JSON:" + json.dumps(
|
||||
{"status": "FAILED", "email": "r3@boom", "error": "network reset by peer"}
|
||||
) + "\n"
|
||||
)
|
||||
r = self._run(provider, runtime, stdout=stdout, rc=1)
|
||||
self.assertFalse(r.ok)
|
||||
self.assertEqual(r.error_kind, "provider")
|
||||
|
||||
def test_result_json_wins_over_failfast_substring(self):
|
||||
# The exact regression: output contains BOTH the wrapper's "fail-fast"
|
||||
# string AND a retryable RESULT_JSON. Authority (RESULT_JSON) must win;
|
||||
# kind must not be fatal even though "fail-fast" / "fatal" substring is
|
||||
# present in the merged blob.
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
provider, runtime = self._make_provider(td)
|
||||
stdout = (
|
||||
"[mimo] fail-fast after error code=1 (no empty spin)\n"
|
||||
"fatal: unhandledRejection should not happen\n"
|
||||
"RESULT_JSON:" + json.dumps(
|
||||
{"status": "FAILED", "email": "r4@boom", "error": "geetest timeout"}
|
||||
) + "\n"
|
||||
)
|
||||
r = self._run(provider, runtime, stdout=stdout, rc=1)
|
||||
self.assertFalse(r.ok)
|
||||
self.assertEqual(r.error_kind, "captcha")
|
||||
|
||||
|
||||
|
||||
class TestExtractOtpCode(unittest.TestCase):
|
||||
"""xAI OTP is alnum+dash XXX-XXX (e.g. FN8-ECQ); OpenAI is 6 digits in
|
||||
"verification code" context. CSS hex (#333333/#888888) embedded in xAI
|
||||
HTML <style> must never win. Regression for pxed 2026-07-18 form-fill
|
||||
of 333333 / SPA hang at /sign-up."""
|
||||
|
||||
def _xai_html(self, code: str = "FN8-ECQ") -> str:
|
||||
# Real xAI confirmation-code email shape: visible code in body, CSS hex
|
||||
# colors in a <style> block (the thing the old \b(\d{4,8})\b seized).
|
||||
return f"""<!DOCTYPE html><html><head><style>
|
||||
body {{ background:#ffffff; color:#333333; }}
|
||||
a {{ color:#888888; }}
|
||||
.code {{ font-family:monospace; }}
|
||||
</style></head>
|
||||
<body>
|
||||
<p>Please use the code below to confirm your xAI account.</p>
|
||||
<div class="code"><strong>{code}</strong></div>
|
||||
<p>If you did not request this, ignore this email.</p>
|
||||
</body></html>"""
|
||||
|
||||
def test_xai_subject_code_wins(self):
|
||||
from register_core.email.sources.tinyhost import extract_otp_code
|
||||
|
||||
blob = self._xai_html("FN8-ECQ")
|
||||
self.assertEqual(extract_otp_code(blob, subject="FN8-ECQ xAI confirmation code"), "FN8-ECQ")
|
||||
|
||||
def test_xai_body_code_not_css_hex(self):
|
||||
from register_core.email.sources.tinyhost import extract_otp_code
|
||||
|
||||
# The whole point: real code FN8-ECQ, NOT 333333/888888 from CSS.
|
||||
blob = self._xai_html("FN8-ECQ")
|
||||
code = extract_otp_code(blob, subject="xAI confirmation code")
|
||||
self.assertEqual(code, "FN8-ECQ")
|
||||
self.assertNotIn("333333", code)
|
||||
self.assertNotIn("888888", code)
|
||||
|
||||
def test_openai_contextual_6_digit(self):
|
||||
from register_core.email.sources.tinyhost import extract_otp_code
|
||||
|
||||
blob = "Enter this temporary verification code to continue: 042902"
|
||||
self.assertEqual(extract_otp_code(blob, subject="Your OpenAI verification code"), "042902")
|
||||
|
||||
def test_openai_no_css_hex_false_positive(self):
|
||||
from register_core.email.sources.tinyhost import extract_otp_code
|
||||
|
||||
# OpenAI-style body that happens to ship CSS hex but with NO real OTP
|
||||
# context must NOT fabricate 333333. (Empty stub subject vs an html
|
||||
# mailer header.) extract_otp_code should return "" here.
|
||||
blob = "<style>.x{color:#333333}</style> hi welcome <style>a{color:#888888}</style>"
|
||||
self.assertEqual(extract_otp_code(blob, subject="Welcome to xAI"), "")
|
||||
|
||||
def test_empty_returns_empty(self):
|
||||
from register_core.email.sources.tinyhost import extract_otp_code
|
||||
|
||||
self.assertEqual(extract_otp_code(""), "")
|
||||
|
||||
def test_typesafe_hint_prefers_magic_link_over_otp_shaped_token(self):
|
||||
"""n=100: one mail_miss was 'magic link missing' after a 4s poll.
|
||||
|
||||
typesafe mail can contain both the Stytch URL and a short token that
|
||||
extract_otp_code accepts. sender_hint=typesafe must return the URL.
|
||||
"""
|
||||
from register_core.email.sources.tinyhost import TinyhostSource
|
||||
from register_core.contracts import Mailbox
|
||||
|
||||
link = (
|
||||
"https://login.typesafe.ai/v1/magic_links/redirect"
|
||||
"?public_token=pub-test&stytch_token_type=magic_links&token=stytch-secret"
|
||||
)
|
||||
body = f"Your login code is AB1-CD2. Open {link} to continue. typesafe"
|
||||
src = TinyhostSource()
|
||||
mailbox = Mailbox(
|
||||
address="u@example.com",
|
||||
token="",
|
||||
provider="tinyhost",
|
||||
meta={"local": "u", "domain": "example.com"},
|
||||
)
|
||||
|
||||
def fake_get(_url: str, timeout: float = 20):
|
||||
return {
|
||||
"emails": [
|
||||
{
|
||||
"date": "2099-01-01T00:00:00Z",
|
||||
"subject": "Sign in to typesafe",
|
||||
"from": "noreply@typesafe.ai",
|
||||
"body": body,
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
src._get_json = fake_get # type: ignore[method-assign]
|
||||
otp = src.poll_otp(mailbox, timeout_s=5, poll_interval_s=0.01, sender_hint="typesafe")
|
||||
self.assertTrue(otp.code.startswith("https://login.typesafe.ai/"))
|
||||
self.assertIn("stytch-secret", otp.code)
|
||||
|
||||
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
runtime = Path(td)
|
||||
(runtime / "output").mkdir()
|
||||
old = "sk-" + "o" * 40
|
||||
(runtime / "output" / "accounts.jsonl").write_text(
|
||||
json.dumps({"email": "old@x.com", "apiKey": old}) + "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
(runtime / "output" / "success_keys.txt").write_text(f"1. {old}\n", encoding="utf-8")
|
||||
runner = Path(td) / "run-register.sh"
|
||||
# provider looks under providers/mimo — patch runner path via MIMO_DIR mock
|
||||
provider = MimoProvider(runtime=str(runtime))
|
||||
fake = CmdResult(returncode=0, stdout="ok\n", stderr="", timed_out=False)
|
||||
with patch.object(MimoProvider, "register_one", wraps=provider.register_one):
|
||||
pass
|
||||
with patch("register_core.providers.mimo_adapter.MIMO_DIR", runtime):
|
||||
(runtime / "run-register.sh").write_text("#!/bin/bash\n", encoding="utf-8")
|
||||
with patch("register_core.providers.mimo_adapter.run_command", return_value=fake):
|
||||
r = provider.register_one()
|
||||
self.assertFalse(r.ok)
|
||||
self.assertIn("no this-run secret", r.error)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,344 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline tests: egress switch + self-controlled proxy list for register_core."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from register_core.util import proxy as core_proxy
|
||||
from register_core.util import egress as egress_mod
|
||||
|
||||
|
||||
_ENV_KEYS = (
|
||||
"CHATGPT_PROXY_LIST",
|
||||
"PROXY_LIST",
|
||||
"PROXY_POOL",
|
||||
"CHATGPT_PROXY_ROTATE_MODE",
|
||||
"PROXY_ROTATE_MODE",
|
||||
"CHATGPT_PROXY",
|
||||
"MIMO_PROXY",
|
||||
"https_proxy",
|
||||
"HTTPS_PROXY",
|
||||
"http_proxy",
|
||||
"HTTP_PROXY",
|
||||
"CHATGPT_PROXY_ROTATE_EVERY",
|
||||
"PROXY_ROTATE_EVERY",
|
||||
"REGISTER_EGRESS",
|
||||
"EGRESS_BACKEND",
|
||||
"CHATGPT_EGRESS",
|
||||
"PROXY_BACKEND",
|
||||
"REGISTER_PROXY_BACKEND",
|
||||
"REGISTER_CORE",
|
||||
"USE_CORE",
|
||||
"REGISTER_MIHOMO",
|
||||
"REGISTER_NODES",
|
||||
"USE_NODES",
|
||||
"REGISTER_NODES_FILE",
|
||||
"NODES_FILE",
|
||||
"CLASH_PROXY",
|
||||
"CLASH_API",
|
||||
"CLASH_CONTROLLER",
|
||||
"CLASH_SECRET",
|
||||
"CLASH_GROUP",
|
||||
"CLASH_PROXY_GROUP",
|
||||
"CLASH_CONFIG_PATH",
|
||||
"CLASH_DOMAINS",
|
||||
"CLASH_RULE_DOMAINS",
|
||||
"REGISTER_CORE_AUTOSTART",
|
||||
"USE_CLASH",
|
||||
)
|
||||
|
||||
|
||||
class TestRotationConfig(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
core_proxy.reset_rotation_for_tests()
|
||||
self._env_backup = {k: os.environ.pop(k, None) for k in _ENV_KEYS}
|
||||
# prevent real nodes.json / core from leaking into unit tests
|
||||
os.environ["REGISTER_NODES"] = "0"
|
||||
os.environ["REGISTER_CORE"] = "0"
|
||||
os.environ["REGISTER_EGRESS"] = "auto"
|
||||
|
||||
def tearDown(self) -> None:
|
||||
core_proxy.reset_rotation_for_tests()
|
||||
for k in _ENV_KEYS:
|
||||
os.environ.pop(k, None)
|
||||
for k, v in self._env_backup.items():
|
||||
if v is None:
|
||||
os.environ.pop(k, None)
|
||||
else:
|
||||
os.environ[k] = v
|
||||
|
||||
def test_proxy_list_auto_selects_list_mode(self) -> None:
|
||||
cfg = core_proxy.rotation_config_from_env_and_extra(
|
||||
{"proxy_list": "http://a:1,http://b:2"}
|
||||
)
|
||||
self.assertEqual(cfg["proxy_rotate_mode"], "list")
|
||||
self.assertEqual(cfg["proxy_list"], "http://a:1,http://b:2")
|
||||
self.assertEqual(cfg.get("egress_source"), "list")
|
||||
|
||||
def test_env_proxy_list_auto_list(self) -> None:
|
||||
os.environ["PROXY_LIST"] = "http://a:1\nhttp://b:2"
|
||||
cfg = core_proxy.rotation_config_from_env_and_extra({})
|
||||
self.assertEqual(cfg["proxy_rotate_mode"], "list")
|
||||
|
||||
def test_explicit_off_keeps_off_even_with_list(self) -> None:
|
||||
cfg = core_proxy.rotation_config_from_env_and_extra(
|
||||
{
|
||||
"proxy_rotate_mode": "off",
|
||||
"proxy_list": "http://a:1,http://b:2",
|
||||
"proxy": "http://127.0.0.1:7897",
|
||||
}
|
||||
)
|
||||
self.assertEqual(cfg["proxy_rotate_mode"], "off")
|
||||
|
||||
def test_resolve_attempt_rotates_list(self) -> None:
|
||||
proxies: list[str] = []
|
||||
extra = {
|
||||
"proxy_list": "http://a:1,http://b:2,http://c:3",
|
||||
"proxy_rotate_every": 1,
|
||||
"proxy_rotate_on_start": True,
|
||||
"egress": "list",
|
||||
}
|
||||
for _ in range(3):
|
||||
p, info = core_proxy.resolve_attempt_proxy(extra)
|
||||
proxies.append(p)
|
||||
self.assertEqual(info.get("mode"), "list")
|
||||
self.assertEqual(info.get("egress_backend"), "list")
|
||||
self.assertEqual(proxies[0], "http://a:1")
|
||||
self.assertEqual(proxies[1], "http://b:2")
|
||||
self.assertEqual(proxies[2], "http://c:3")
|
||||
|
||||
def test_inject_attempt_proxy_sets_extra_proxy(self) -> None:
|
||||
extra = core_proxy.inject_attempt_proxy(
|
||||
{
|
||||
"proxy_list": "http://only:9",
|
||||
"proxy_rotate_on_start": True,
|
||||
"egress": "list",
|
||||
}
|
||||
)
|
||||
self.assertEqual(extra.get("proxy"), "http://only:9")
|
||||
self.assertEqual(extra.get("_proxy_rotate", {}).get("mode"), "list")
|
||||
|
||||
def test_pipeline_passes_rotated_proxy_to_provider(self) -> None:
|
||||
from register_core.contracts import RegisterResult
|
||||
from register_core.pipeline import Pipeline
|
||||
from register_core.verify.noop import NoopVerifier
|
||||
|
||||
seen: list[str] = []
|
||||
|
||||
class StubProvider:
|
||||
name = "stub"
|
||||
|
||||
def register_one(self, *, email_source=None, extra=None):
|
||||
seen.append(str((extra or {}).get("proxy") or ""))
|
||||
return RegisterResult(
|
||||
ok=False,
|
||||
provider=self.name,
|
||||
error="stop",
|
||||
error_kind="other",
|
||||
secret_kind="none",
|
||||
)
|
||||
|
||||
pipe = Pipeline(
|
||||
StubProvider(),
|
||||
email_source=None,
|
||||
verifier=NoopVerifier(),
|
||||
fail_fast=False,
|
||||
)
|
||||
extra = {
|
||||
"proxy_list": "http://n1:1,http://n2:2",
|
||||
"proxy_rotate_every": 1,
|
||||
"proxy_rotate_on_start": True,
|
||||
"egress": "list",
|
||||
}
|
||||
stats = pipe.run(2, extra=extra)
|
||||
self.assertEqual(stats.fail, 2)
|
||||
self.assertEqual(seen, ["http://n1:1", "http://n2:2"])
|
||||
|
||||
def test_egress_clash_uses_7897_not_core(self) -> None:
|
||||
os.environ["REGISTER_CORE"] = "0"
|
||||
os.environ["REGISTER_NODES"] = "0"
|
||||
cfg = core_proxy.rotation_config_from_env_and_extra({"egress": "clash"})
|
||||
self.assertEqual(cfg["egress_backend"], "clash")
|
||||
self.assertEqual(cfg["egress_source"], "clash")
|
||||
self.assertIn("7897", cfg.get("proxy") or "")
|
||||
self.assertFalse(cfg.get("core_pool"))
|
||||
|
||||
def test_clash_env_passes_api_group_config_path(self) -> None:
|
||||
os.environ["CLASH_API"] = "http://127.0.0.1:9090"
|
||||
os.environ["CLASH_SECRET"] = "sekrit"
|
||||
os.environ["CLASH_GROUP"] = "🎯Grok注册"
|
||||
os.environ["CLASH_CONFIG_PATH"] = "/personal/clash/config.yaml"
|
||||
cfg = core_proxy.rotation_config_from_env_and_extra({"egress": "clash"})
|
||||
self.assertEqual(cfg["clash_api"], "http://127.0.0.1:9090")
|
||||
self.assertEqual(cfg["clash_secret"], "sekrit")
|
||||
self.assertEqual(cfg["clash_proxy_group"], "🎯Grok注册")
|
||||
# pxed standalone mihomo: rotator must read live config, not macOS Verge path
|
||||
self.assertEqual(cfg["clash_config_path"], "/personal/clash/config.yaml")
|
||||
|
||||
def test_clash_config_path_absent_by_default(self) -> None:
|
||||
cfg = core_proxy.rotation_config_from_env_and_extra({"egress": "clash"})
|
||||
# not set -> key dropped (None filtered) so rotator keeps its default
|
||||
self.assertNotIn("clash_config_path", cfg)
|
||||
|
||||
def test_clash_advance_on_start_env_parsed(self) -> None:
|
||||
os.environ["PROXY_ROTATE_ADVANCE_ON_START"] = "true"
|
||||
try:
|
||||
cfg = core_proxy.rotation_config_from_env_and_extra({"egress": "clash"})
|
||||
self.assertIs(cfg["proxy_rotate_advance_on_start"], True)
|
||||
finally:
|
||||
os.environ.pop("PROXY_ROTATE_ADVANCE_ON_START", None)
|
||||
|
||||
def test_clash_advance_on_start_false_by_default(self) -> None:
|
||||
os.environ.pop("PROXY_ROTATE_ADVANCE_ON_START", None)
|
||||
cfg = core_proxy.rotation_config_from_env_and_extra({"egress": "clash"})
|
||||
# key always present (bool False kept through None filter), default False
|
||||
self.assertIs(cfg["proxy_rotate_advance_on_start"], False)
|
||||
|
||||
def test_egress_direct_clears_proxy(self) -> None:
|
||||
os.environ["CHATGPT_PROXY"] = "http://should-not-use:1"
|
||||
p, info = core_proxy.resolve_attempt_proxy({"egress": "direct"})
|
||||
self.assertEqual(p, "")
|
||||
self.assertEqual(info.get("egress_backend"), "direct")
|
||||
|
||||
def test_egress_core_require_core_url(self) -> None:
|
||||
with patch.object(
|
||||
core_proxy,
|
||||
"_load_core_proxy_url",
|
||||
return_value="http://127.0.0.1:17897",
|
||||
):
|
||||
cfg = core_proxy.rotation_config_from_env_and_extra({"egress": "core"})
|
||||
self.assertEqual(cfg["egress_backend"], "core")
|
||||
self.assertEqual(cfg["egress_source"], "core")
|
||||
self.assertEqual(cfg["proxy"], "http://127.0.0.1:17897")
|
||||
self.assertTrue(cfg.get("core_pool"))
|
||||
# must be project port 17897, not external Clash 7897
|
||||
self.assertTrue((cfg.get("proxy") or "").endswith(":17897"))
|
||||
self.assertNotEqual(cfg.get("proxy"), "http://127.0.0.1:7897")
|
||||
|
||||
def test_persist_egress_preference(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
os.environ["REGISTER_NODES_HOME"] = td
|
||||
path = egress_mod.write_persisted_backend("clash")
|
||||
self.assertTrue(Path(path).is_file())
|
||||
self.assertEqual(egress_mod.read_persisted_backend(), "clash")
|
||||
# env still wins over file
|
||||
os.environ["REGISTER_EGRESS"] = "core"
|
||||
self.assertEqual(egress_mod.resolve_backend({}), "core")
|
||||
os.environ.pop("REGISTER_EGRESS", None)
|
||||
self.assertEqual(egress_mod.resolve_backend({}), "clash")
|
||||
|
||||
def test_auto_skips_unprobed_nodes_json(self) -> None:
|
||||
"""Dirty bulk catalog without last_ok=true must not win over core in auto."""
|
||||
os.environ.pop("REGISTER_NODES", None)
|
||||
os.environ["REGISTER_NODES"] = "1"
|
||||
os.environ["REGISTER_CORE"] = "auto"
|
||||
os.environ["REGISTER_EGRESS"] = "auto"
|
||||
with patch.object(
|
||||
core_proxy,
|
||||
"_load_nodes_proxy_list",
|
||||
side_effect=lambda healthy_only=None: (
|
||||
"" if healthy_only is None else "http://dirty:1"
|
||||
),
|
||||
), patch.object(
|
||||
core_proxy,
|
||||
"_load_core_proxy_url",
|
||||
return_value="http://127.0.0.1:17897",
|
||||
):
|
||||
cfg = core_proxy.rotation_config_from_env_and_extra({"egress": "auto"})
|
||||
self.assertEqual(cfg.get("egress_source"), "core")
|
||||
self.assertTrue((cfg.get("proxy") or "").endswith(":17897"))
|
||||
|
||||
def test_auto_uses_known_healthy_list(self) -> None:
|
||||
os.environ["REGISTER_NODES"] = "1"
|
||||
os.environ["REGISTER_EGRESS"] = "auto"
|
||||
with patch.object(
|
||||
core_proxy,
|
||||
"_load_nodes_proxy_list",
|
||||
side_effect=lambda healthy_only=None: (
|
||||
"http://ok:1" if healthy_only is None else "http://ok:1"
|
||||
),
|
||||
), patch.object(
|
||||
core_proxy,
|
||||
"_load_core_proxy_url",
|
||||
return_value="http://127.0.0.1:17897",
|
||||
):
|
||||
cfg = core_proxy.rotation_config_from_env_and_extra({"egress": "auto"})
|
||||
self.assertEqual(cfg.get("egress_source"), "list")
|
||||
self.assertIn("http://ok:1", cfg.get("proxy_list") or "")
|
||||
|
||||
|
||||
class TestReportAttemptSoftCool(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
core_proxy.reset_rotation_for_tests()
|
||||
|
||||
def tearDown(self) -> None:
|
||||
core_proxy.reset_rotation_for_tests()
|
||||
|
||||
def test_registration_disallowed_soft_cools_not_quarantine(self) -> None:
|
||||
from register_core.nodes.catalog import save_nodes
|
||||
from register_core.nodes.manager import NodeManager, reset_manager_for_tests
|
||||
from register_core.nodes.models import Node
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
path = Path(td) / "nodes.json"
|
||||
save_nodes([Node(url="http://risk:9", id="r")], path)
|
||||
reset_manager_for_tests()
|
||||
env = {
|
||||
"REGISTER_NODES_FILE": str(path),
|
||||
"REGISTER_NODES": "1",
|
||||
"REGISTER_NODES_COOLDOWN_RISK": "600",
|
||||
"REGISTER_NODES_COOLDOWN_NETWORK": "120",
|
||||
"REGISTER_NODES_COOLDOWN_PER_USE": "0",
|
||||
}
|
||||
with patch.dict(os.environ, env, clear=False):
|
||||
reset_manager_for_tests()
|
||||
info = core_proxy.report_attempt_proxy_result(
|
||||
{"proxy": "http://risk:9"},
|
||||
ok=False,
|
||||
error="create_account registration_disallowed",
|
||||
error_kind="registration_disallowed",
|
||||
)
|
||||
self.assertEqual(info.get("action"), "risk_cooldown")
|
||||
self.assertFalse(info.get("quarantined"))
|
||||
mgr = NodeManager(path)
|
||||
n = mgr.find_by_url("http://risk:9")
|
||||
assert n is not None
|
||||
self.assertTrue(mgr.is_cooling(n))
|
||||
self.assertEqual(n.cooldown_reason, "registration_disallowed")
|
||||
# not hard-quarantined
|
||||
self.assertFalse(mgr.is_quarantined(n))
|
||||
reset_manager_for_tests()
|
||||
|
||||
def test_mail_miss_no_cool_no_quarantine(self) -> None:
|
||||
from register_core.nodes.catalog import save_nodes
|
||||
from register_core.nodes.manager import NodeManager, reset_manager_for_tests
|
||||
from register_core.nodes.models import Node
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
path = Path(td) / "nodes.json"
|
||||
save_nodes([Node(url="http://m:1", id="m")], path)
|
||||
env = {"REGISTER_NODES_FILE": str(path), "REGISTER_NODES": "1"}
|
||||
with patch.dict(os.environ, env, clear=False):
|
||||
reset_manager_for_tests()
|
||||
info = core_proxy.report_attempt_proxy_result(
|
||||
{"proxy": "http://m:1"},
|
||||
ok=False,
|
||||
error="otp_wait",
|
||||
error_kind="mail_miss",
|
||||
)
|
||||
self.assertEqual(info.get("reason"), "non_proxy_failure")
|
||||
mgr = NodeManager(path)
|
||||
n = mgr.find_by_url("http://m:1")
|
||||
assert n is not None
|
||||
self.assertFalse(mgr.is_cooling(n))
|
||||
self.assertEqual(int(n.fail_count or 0), 0)
|
||||
reset_manager_for_tests()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,351 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unit tests for register.v1 profile loader + mailbox/decode composite."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from register_core.config.loader import (
|
||||
ProfileLoadError,
|
||||
build_composite_email,
|
||||
load_profile,
|
||||
parse_profile_dict,
|
||||
profile_to_job,
|
||||
resolve_mail_proxy_value,
|
||||
)
|
||||
from register_core.contracts import Mailbox, OtpCode, RegisterResult
|
||||
from register_core.email.composite import CompositeEmailSource
|
||||
from register_core.verify.chatgpt_token import ChatGPTTokenVerifier
|
||||
|
||||
|
||||
class TestProfileParse(unittest.TestCase):
|
||||
def test_minimal_chatgpt_cf(self):
|
||||
raw = {
|
||||
"apiVersion": "register.v1",
|
||||
"metadata": {"name": "t1"},
|
||||
"spec": {
|
||||
"provider": {"name": "chatgpt"},
|
||||
"mailbox": {"type": "cloudflare"},
|
||||
"decode": {"type": "cf"},
|
||||
"strategy": {
|
||||
"egress": {"mode": "clash", "proxy": "http://127.0.0.1:7897"},
|
||||
"mail_proxy": "direct",
|
||||
},
|
||||
"secrets": {"mode": "dev"},
|
||||
},
|
||||
}
|
||||
p = parse_profile_dict(raw, source_path="mem")
|
||||
self.assertEqual(p.name, "t1")
|
||||
self.assertEqual(p.provider.name, "chatgpt")
|
||||
self.assertEqual(p.mailbox_type(), "cloudflare")
|
||||
self.assertEqual(p.decode_type(), "cloudflare")
|
||||
job = profile_to_job(p)
|
||||
self.assertEqual(job.provider, "chatgpt")
|
||||
self.assertEqual(job.extra.get("egress"), "clash")
|
||||
self.assertEqual(job.extra.get("proxy"), "http://127.0.0.1:7897")
|
||||
self.assertNotIn("mail_proxy", job.extra) # direct → empty
|
||||
self.assertEqual(job.extra["_profile"]["mailbox"], "cloudflare")
|
||||
|
||||
def test_email_source_paired_fallback(self):
|
||||
raw = {
|
||||
"apiVersion": "register.v1",
|
||||
"spec": {
|
||||
"name": "legacy",
|
||||
"provider": "chatgpt",
|
||||
"email_source": "tinyhost",
|
||||
"secrets": {"mode": "dev"},
|
||||
},
|
||||
}
|
||||
p = parse_profile_dict(raw)
|
||||
self.assertEqual(p.mailbox_type(), "tinyhost")
|
||||
self.assertEqual(p.decode_type(), "tinyhost")
|
||||
|
||||
def test_prod_rejects_plaintext_secret(self):
|
||||
raw = {
|
||||
"apiVersion": "register.v1",
|
||||
"spec": {
|
||||
"provider": {"name": "chatgpt"},
|
||||
"mailbox": {"type": "gmail_imap"},
|
||||
"decode": {"type": "gmail_imap"},
|
||||
"secrets": {"mode": "prod"},
|
||||
"imap_password": "hunter2",
|
||||
},
|
||||
}
|
||||
with self.assertRaises(ProfileLoadError):
|
||||
parse_profile_dict(raw, source_path="bad.yaml")
|
||||
|
||||
def test_prod_allows_env_ref(self):
|
||||
raw = {
|
||||
"apiVersion": "register.v1",
|
||||
"spec": {
|
||||
"provider": {"name": "chatgpt"},
|
||||
"mailbox": {"type": "gmail_imap"},
|
||||
"decode": {"type": "gmail_imap"},
|
||||
"secrets": {"mode": "prod"},
|
||||
"imap_password": "env:GMAIL_IMAP_PASSWORD",
|
||||
},
|
||||
}
|
||||
p = parse_profile_dict(raw)
|
||||
self.assertEqual(p.secrets.mode, "prod")
|
||||
|
||||
def test_load_yaml_example(self):
|
||||
root = Path(__file__).resolve().parents[2]
|
||||
path = root / "profiles" / "chatgpt-tinyhost.example.yaml"
|
||||
if not path.is_file():
|
||||
self.skipTest("example profile missing")
|
||||
p = load_profile(path)
|
||||
self.assertEqual(p.provider.name, "chatgpt")
|
||||
self.assertEqual(p.mailbox_type(), "tinyhost")
|
||||
# domain intentionally unpinned so the CHATGPT_EMAIL_DOMAIN operator knob is
|
||||
# honored (extra["email_domain"] unset → adapter self.email_domain ← env).
|
||||
self.assertFalse(
|
||||
(p.mailbox and p.mailbox.domain),
|
||||
"chatgpt-tinyhost profile must not pin mailbox.domain (keep env override)",
|
||||
)
|
||||
|
||||
|
||||
class TestMailProxyResolve(unittest.TestCase):
|
||||
def test_direct(self):
|
||||
self.assertEqual(resolve_mail_proxy_value("direct"), "")
|
||||
self.assertEqual(resolve_mail_proxy_value(""), "")
|
||||
|
||||
def test_url(self):
|
||||
self.assertEqual(
|
||||
resolve_mail_proxy_value("http://127.0.0.1:9"), "http://127.0.0.1:9"
|
||||
)
|
||||
|
||||
|
||||
class TestComposite(unittest.TestCase):
|
||||
def test_delegate_allocate_poll_release(self):
|
||||
mb = MagicMock()
|
||||
mb.name = "cloudflare"
|
||||
box = Mailbox(address="a@b.com", token="t", provider="cloudflare")
|
||||
mb.allocate.return_value = box
|
||||
dec = MagicMock()
|
||||
dec.name = "cloudflare"
|
||||
dec.wait_otp.return_value = OtpCode(code="123456", source="cloudflare")
|
||||
dec.last_wait_diagnostics = None
|
||||
comp = CompositeEmailSource(mb, dec)
|
||||
self.assertEqual(comp.name, "cloudflare")
|
||||
self.assertEqual(comp.allocate().address, "a@b.com")
|
||||
self.assertEqual(comp.poll_otp(box).code, "123456")
|
||||
comp.release(box, success=True)
|
||||
mb.release.assert_called_once_with(box, success=True)
|
||||
|
||||
def test_split_name(self):
|
||||
mb = MagicMock()
|
||||
mb.name = "local"
|
||||
dec = MagicMock()
|
||||
dec.name = "gmail_imap"
|
||||
c = CompositeEmailSource(mb, dec)
|
||||
self.assertEqual(c.name, "local+gmail_imap")
|
||||
|
||||
def test_proxy_forwards_live_mailbox_and_setter(self):
|
||||
"""Composite must not freeze mailbox.proxy at construction."""
|
||||
mb = MagicMock()
|
||||
mb.name = "tinyhost"
|
||||
mb.proxy = "http://mail-proxy:1"
|
||||
dec = MagicMock()
|
||||
dec.name = "tinyhost"
|
||||
c = CompositeEmailSource(mb, dec)
|
||||
self.assertEqual(c.proxy, "http://mail-proxy:1")
|
||||
# live mailbox mutation must surface
|
||||
mb.proxy = "http://mail-proxy:2"
|
||||
self.assertEqual(c.proxy, "http://mail-proxy:2")
|
||||
# setter writes through
|
||||
c.proxy = "http://mail-proxy:3"
|
||||
self.assertEqual(c.proxy, "http://mail-proxy:3")
|
||||
self.assertEqual(mb.proxy, "http://mail-proxy:3")
|
||||
|
||||
|
||||
class TestCliCountDoesNotClobberProfile(unittest.TestCase):
|
||||
def test_apply_cli_overrides_none_keeps_profile_count(self):
|
||||
from register_core.config.loader import apply_cli_overrides, parse_profile_dict
|
||||
|
||||
raw = {
|
||||
"apiVersion": "register.v1",
|
||||
"spec": {
|
||||
"provider": {"name": "chatgpt"},
|
||||
"mailbox": {"type": "tinyhost"},
|
||||
"decode": {"type": "tinyhost"},
|
||||
"count": 7,
|
||||
},
|
||||
}
|
||||
profile = parse_profile_dict(raw)
|
||||
self.assertEqual(profile.count, 7)
|
||||
job, _ = apply_cli_overrides(profile, count=None)
|
||||
self.assertEqual(job.count, 7)
|
||||
job2, _ = apply_cli_overrides(profile, count=3)
|
||||
self.assertEqual(job2.count, 3)
|
||||
|
||||
|
||||
class TestMimoProxyDefault(unittest.TestCase):
|
||||
def test_no_hardcoded_7897_without_env(self):
|
||||
from register_core.providers.mimo_adapter import MimoProvider
|
||||
import os
|
||||
from unittest.mock import patch
|
||||
|
||||
env = {k: v for k, v in os.environ.items() if k not in {
|
||||
"MIMO_PROXY", "https_proxy", "HTTPS_PROXY", "http_proxy", "HTTP_PROXY"
|
||||
}}
|
||||
with patch.dict(os.environ, env, clear=True):
|
||||
p = MimoProvider()
|
||||
self.assertNotEqual(p.proxy, "http://127.0.0.1:7897")
|
||||
self.assertEqual(p.proxy, "")
|
||||
|
||||
|
||||
class TestPipelineFromProfile(unittest.TestCase):
|
||||
def test_from_profile_chatgpt_tinyhost_offline(self):
|
||||
from register_core.pipeline import Pipeline
|
||||
from register_core.providers.chatgpt_adapter import ChatGPTProvider
|
||||
from unittest.mock import patch
|
||||
|
||||
raw = {
|
||||
"apiVersion": "register.v1",
|
||||
"spec": {
|
||||
"provider": {"name": "chatgpt"},
|
||||
"mailbox": {"type": "tinyhost", "domain": "publicvm.com"},
|
||||
"decode": {"type": "tinyhost"},
|
||||
"strategy": {
|
||||
"fail_fast": True,
|
||||
"egress": {"mode": "direct"},
|
||||
"mail_proxy": "direct",
|
||||
},
|
||||
"verify": {"enabled": True},
|
||||
"secrets": {"mode": "dev"},
|
||||
},
|
||||
}
|
||||
profile = parse_profile_dict(raw)
|
||||
|
||||
class FakeSrc:
|
||||
name = "tinyhost"
|
||||
|
||||
def allocate(self):
|
||||
return Mailbox(
|
||||
address="u@publicvm.com", token="", provider="tinyhost"
|
||||
)
|
||||
|
||||
def poll_otp(self, mailbox, **kwargs):
|
||||
return OtpCode(code="999999", source="tinyhost")
|
||||
|
||||
def release(self, mailbox, *, success):
|
||||
return None
|
||||
|
||||
from providers.chatgpt.protocol.flow import RegistrationResult
|
||||
|
||||
fake_ok = RegistrationResult(
|
||||
ok=True,
|
||||
email="u@publicvm.com",
|
||||
password="Pw1!abcdef",
|
||||
access_token="a" * 48,
|
||||
refresh_token="rt.1." + ("B" * 160),
|
||||
id_token="h.p.s",
|
||||
)
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
with (
|
||||
patch(
|
||||
"register_core.email.registry.get_email_source",
|
||||
return_value=FakeSrc(),
|
||||
),
|
||||
patch(
|
||||
"register_core.providers.chatgpt_adapter.OUTPUT_DIR", Path(td)
|
||||
),
|
||||
patch(
|
||||
"providers.chatgpt.protocol.flow.register_one",
|
||||
return_value=fake_ok,
|
||||
),
|
||||
patch(
|
||||
"register_core.util.proxy.preflight_nodes_for_register",
|
||||
side_effect=lambda extra, **kw: {
|
||||
**(extra or {}),
|
||||
"_nodes_preflight_done": True,
|
||||
"_nodes_preflight": {"skipped": True},
|
||||
},
|
||||
),
|
||||
patch(
|
||||
"register_core.util.proxy.inject_attempt_proxy",
|
||||
side_effect=lambda extra, **kw: dict(extra or {}),
|
||||
),
|
||||
):
|
||||
pipe = Pipeline.from_profile(profile)
|
||||
self.assertIsInstance(pipe.email_source, CompositeEmailSource)
|
||||
stats = pipe.run(
|
||||
1, extra={"egress": "direct", "nodes_preflight": False}
|
||||
)
|
||||
self.assertEqual(stats.ok, 1, stats.results[0].error if stats.results else "")
|
||||
self.assertTrue(stats.results[0].ok)
|
||||
self.assertTrue(str(stats.results[0].secret).startswith("rt.1."))
|
||||
|
||||
def test_mimo_profile_accepts_composite_email(self):
|
||||
"""M3: mimo profile builds CompositeEmailSource (FIXED_EMAIL inject path)."""
|
||||
from register_core.pipeline import Pipeline
|
||||
|
||||
raw = {
|
||||
"apiVersion": "register.v1",
|
||||
"spec": {
|
||||
"provider": {"name": "mimo"},
|
||||
"mailbox": {"type": "tinyhost"},
|
||||
"decode": {"type": "tinyhost"},
|
||||
"strategy": {
|
||||
"fail_fast": True,
|
||||
"burn": {
|
||||
"enabled": True,
|
||||
"track": ["ip", "domain"],
|
||||
"on_kinds": ["registration_disallowed"],
|
||||
},
|
||||
},
|
||||
"secrets": {"mode": "dev"},
|
||||
},
|
||||
}
|
||||
profile = parse_profile_dict(raw)
|
||||
pipe = Pipeline.from_profile(profile)
|
||||
self.assertIsInstance(pipe.email_source, CompositeEmailSource)
|
||||
self.assertIsNotNone(pipe.strategy)
|
||||
self.assertIn("domain", pipe.strategy.burn_track)
|
||||
|
||||
def test_grok_profile_accepts_composite_email(self):
|
||||
"""M4: grok profile builds CompositeEmailSource + strategy engine."""
|
||||
from register_core.pipeline import Pipeline
|
||||
|
||||
raw = {
|
||||
"apiVersion": "register.v1",
|
||||
"spec": {
|
||||
"provider": {"name": "grok"},
|
||||
"mailbox": {"type": "tinyhost", "domain": "publicvm.com"},
|
||||
"decode": {"type": "tinyhost"},
|
||||
"strategy": {
|
||||
"fail_fast": True,
|
||||
"fail_fast_kinds": ["fatal", "verify"],
|
||||
"cool_soft_seconds": 5,
|
||||
},
|
||||
"secrets": {"mode": "dev"},
|
||||
},
|
||||
}
|
||||
profile = parse_profile_dict(raw)
|
||||
pipe = Pipeline.from_profile(profile)
|
||||
self.assertIsInstance(pipe.email_source, CompositeEmailSource)
|
||||
self.assertIsNotNone(pipe.strategy)
|
||||
self.assertEqual(pipe.strategy.cool_soft_seconds, 5.0)
|
||||
|
||||
|
||||
class TestVerifierStillOk(unittest.TestCase):
|
||||
def test_rt1(self):
|
||||
v = ChatGPTTokenVerifier(live=False)
|
||||
r = v.verify(
|
||||
RegisterResult(
|
||||
ok=True,
|
||||
provider="chatgpt",
|
||||
secret="rt.1." + ("A" * 160),
|
||||
secret_kind="refresh_token",
|
||||
)
|
||||
)
|
||||
self.assertTrue(r.ok)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,425 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Unit tests for StrategyEngine + BurnStore (M2)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from register_core.contracts import RegisterResult
|
||||
from register_core.pipeline import Pipeline
|
||||
from register_core.strategy.burn import BurnStore
|
||||
from register_core.strategy.engine import (
|
||||
StrategyEngine,
|
||||
domain_from_email,
|
||||
extract_egress_ip,
|
||||
proxy_host_key,
|
||||
)
|
||||
|
||||
|
||||
class FakeProvider:
|
||||
name = "fake"
|
||||
|
||||
def __init__(self, outcomes: list[RegisterResult] | None = None) -> None:
|
||||
self.outcomes = list(outcomes or [])
|
||||
self.calls = 0
|
||||
|
||||
def register_one(self, *, email_source=None, extra=None) -> RegisterResult:
|
||||
self.calls += 1
|
||||
if self.outcomes:
|
||||
return self.outcomes.pop(0)
|
||||
return RegisterResult(
|
||||
ok=True,
|
||||
provider=self.name,
|
||||
email="a@example.com",
|
||||
secret="sk-" + "a" * 40,
|
||||
secret_kind="api_key",
|
||||
)
|
||||
|
||||
|
||||
class TestBurnStore(unittest.TestCase):
|
||||
def test_hard_burn_ip_domain_proxy(self) -> None:
|
||||
store = BurnStore("")
|
||||
store.burn_ip("1.2.3.4", reason="registration_disallowed", email="u@x.com")
|
||||
store.burn_domain("bad.example", reason="unsupported_email")
|
||||
store.burn_proxy("127.0.0.1:7897", reason="registration_disallowed")
|
||||
self.assertTrue(store.is_ip_burned("1.2.3.4"))
|
||||
self.assertTrue(store.is_domain_burned("BAD.example"))
|
||||
self.assertTrue(store.is_proxy_burned("127.0.0.1:7897"))
|
||||
self.assertFalse(store.is_ip_cooling("1.2.3.4"))
|
||||
|
||||
def test_soft_cool_ip(self) -> None:
|
||||
store = BurnStore("")
|
||||
store.cool_ip("9.9.9.9", 30.0, reason="soft")
|
||||
self.assertFalse(store.is_ip_burned("9.9.9.9"))
|
||||
self.assertTrue(store.is_ip_cooling("9.9.9.9"))
|
||||
|
||||
def test_persist_roundtrip(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
path = str(Path(td) / "burn.json")
|
||||
a = BurnStore(path)
|
||||
a.burn_domain("burned.tld", reason="unsupported_email", email="x@burned.tld")
|
||||
a.burn_ip("8.8.8.8", reason="registration_disallowed")
|
||||
b = BurnStore(path)
|
||||
self.assertTrue(b.is_domain_burned("burned.tld"))
|
||||
self.assertTrue(b.is_ip_burned("8.8.8.8"))
|
||||
data = json.loads(Path(path).read_text(encoding="utf-8"))
|
||||
self.assertIn("domains", data)
|
||||
self.assertIn("burned.tld", data["domains"])
|
||||
|
||||
|
||||
class TestStrategyHelpers(unittest.TestCase):
|
||||
def test_domain_from_email(self) -> None:
|
||||
self.assertEqual(domain_from_email("U@Example.COM"), "example.com")
|
||||
self.assertEqual(domain_from_email("nope"), "")
|
||||
|
||||
def test_proxy_host_key(self) -> None:
|
||||
self.assertEqual(
|
||||
proxy_host_key("http://user:pass@127.0.0.1:7897"),
|
||||
"127.0.0.1:7897",
|
||||
)
|
||||
self.assertEqual(proxy_host_key("socks5://10.0.0.2:1080"), "10.0.0.2:1080")
|
||||
|
||||
def test_extract_egress_ip(self) -> None:
|
||||
self.assertEqual(
|
||||
extract_egress_ip({"_egress_ip": "1.1.1.1"}),
|
||||
"1.1.1.1",
|
||||
)
|
||||
r = RegisterResult(
|
||||
ok=False,
|
||||
provider="x",
|
||||
error="x",
|
||||
artifacts={"egress_ip": "2.2.2.2"},
|
||||
)
|
||||
self.assertEqual(extract_egress_ip({}, r), "2.2.2.2")
|
||||
|
||||
|
||||
class TestStrategyEngine(unittest.TestCase):
|
||||
def test_from_extra_defaults(self) -> None:
|
||||
eng = StrategyEngine.from_extra({})
|
||||
self.assertTrue(eng.fail_fast)
|
||||
self.assertIn("registration_disallowed", eng.fail_fast_kinds)
|
||||
self.assertIn("domain", eng.burn_track)
|
||||
|
||||
def test_from_extra_profile_block(self) -> None:
|
||||
eng = StrategyEngine.from_extra(
|
||||
{
|
||||
"_strategy": {
|
||||
"fail_fast": True,
|
||||
"fail_fast_kinds": ["fatal", "verify"],
|
||||
"burn": {
|
||||
"enabled": True,
|
||||
"track": ["ip", "domain", "proxy"],
|
||||
"on_kinds": ["registration_disallowed"],
|
||||
"state_path": "",
|
||||
},
|
||||
"cool_soft_seconds": 12,
|
||||
}
|
||||
}
|
||||
)
|
||||
self.assertEqual(eng.fail_fast_kinds, {"fatal", "verify"})
|
||||
self.assertEqual(eng.burn_track, {"ip", "domain", "proxy"})
|
||||
self.assertEqual(eng.cool_soft_seconds, 12.0)
|
||||
|
||||
def test_should_stop_on_fail_fast_kind(self) -> None:
|
||||
eng = StrategyEngine(fail_fast=True, fail_fast_kinds=["registration_disallowed"])
|
||||
stop, reason = eng.should_stop_on_result(
|
||||
RegisterResult(
|
||||
ok=False,
|
||||
provider="chatgpt",
|
||||
error="blocked",
|
||||
error_kind="registration_disallowed",
|
||||
)
|
||||
)
|
||||
self.assertTrue(stop)
|
||||
self.assertIn("registration_disallowed", reason)
|
||||
|
||||
def test_hard_kind_stops_even_when_engine_fail_fast_off(self) -> None:
|
||||
eng = StrategyEngine(fail_fast=False, fail_fast_kinds=["fatal", "verify"])
|
||||
stop, reason = eng.should_stop_on_result(
|
||||
RegisterResult(ok=False, provider="typesafe", error="x", error_kind="fatal")
|
||||
)
|
||||
self.assertTrue(stop)
|
||||
self.assertIn("fatal", reason)
|
||||
soft, _ = eng.should_stop_on_result(
|
||||
RegisterResult(
|
||||
ok=False, provider="typesafe", error="timeout", error_kind="mail_miss"
|
||||
)
|
||||
)
|
||||
self.assertFalse(soft)
|
||||
|
||||
def test_on_result_burns_domain_and_ip(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
path = str(Path(td) / "s.json")
|
||||
eng = StrategyEngine(
|
||||
burn_enabled=True,
|
||||
burn_track=["ip", "domain"],
|
||||
burn_on_kinds=["registration_disallowed"],
|
||||
burn_state_path=path,
|
||||
)
|
||||
r = RegisterResult(
|
||||
ok=False,
|
||||
provider="chatgpt",
|
||||
email="u@blocked.example",
|
||||
error="nope",
|
||||
error_kind="registration_disallowed",
|
||||
)
|
||||
fb = eng.on_result(r, {"_egress_ip": "3.3.3.3"})
|
||||
self.assertEqual(fb.action, "burned")
|
||||
self.assertEqual(fb.burned_domain, "blocked.example")
|
||||
self.assertEqual(fb.burned_ip, "3.3.3.3")
|
||||
self.assertTrue(eng.store.is_domain_burned("blocked.example"))
|
||||
self.assertTrue(eng.store.is_ip_burned("3.3.3.3"))
|
||||
self.assertIn("strategy_burn", r.artifacts or {})
|
||||
|
||||
def test_soft_cool_when_ip_not_in_track(self) -> None:
|
||||
eng = StrategyEngine(
|
||||
burn_enabled=True,
|
||||
burn_track=["domain"],
|
||||
burn_on_kinds=["registration_disallowed"],
|
||||
cool_soft_seconds=60,
|
||||
)
|
||||
r = RegisterResult(
|
||||
ok=False,
|
||||
provider="chatgpt",
|
||||
email="u@x.com",
|
||||
error_kind="registration_disallowed",
|
||||
)
|
||||
fb = eng.on_result(r, {"_egress_ip": "4.4.4.4"})
|
||||
self.assertEqual(fb.cooled_ip, "4.4.4.4")
|
||||
self.assertTrue(eng.store.is_ip_cooling("4.4.4.4"))
|
||||
self.assertFalse(eng.store.is_ip_burned("4.4.4.4"))
|
||||
|
||||
def test_precheck_egress_stops_on_burned_ip(self) -> None:
|
||||
eng = StrategyEngine(burn_state_path="")
|
||||
eng.store.burn_ip("5.5.5.5", reason="registration_disallowed")
|
||||
fb = eng.precheck_egress({"_egress_ip": "5.5.5.5"})
|
||||
self.assertTrue(fb.should_stop)
|
||||
self.assertTrue(fb.skip_attempt)
|
||||
self.assertIn("ip burned", fb.stop_reason)
|
||||
|
||||
def test_precheck_proxy_burned(self) -> None:
|
||||
eng = StrategyEngine(burn_track=["proxy"])
|
||||
eng.store.burn_proxy("10.0.0.1:8080", reason="registration_disallowed")
|
||||
fb = eng.precheck_egress(
|
||||
{"proxy": "http://user:x@10.0.0.1:8080"},
|
||||
proxy="http://user:x@10.0.0.1:8080",
|
||||
)
|
||||
self.assertTrue(fb.should_stop)
|
||||
self.assertTrue(fb.skip_attempt)
|
||||
self.assertIn("proxy burned", fb.stop_reason)
|
||||
|
||||
def test_precheck_domain_batch_fatal(self) -> None:
|
||||
eng = StrategyEngine()
|
||||
eng.store.burn_domain("fixed.example", reason="unsupported_email")
|
||||
fb = eng.precheck_domain("fixed.example")
|
||||
self.assertTrue(fb.should_stop)
|
||||
self.assertFalse(fb.skip_attempt)
|
||||
self.assertIn("domain burned", fb.stop_reason)
|
||||
|
||||
def test_no_burn_on_unrelated_kind(self) -> None:
|
||||
eng = StrategyEngine(
|
||||
burn_on_kinds=["registration_disallowed"],
|
||||
burn_track=["domain"],
|
||||
)
|
||||
r = RegisterResult(
|
||||
ok=False,
|
||||
provider="chatgpt",
|
||||
email="u@x.com",
|
||||
error_kind="mail_miss",
|
||||
)
|
||||
fb = eng.on_result(r, {})
|
||||
self.assertEqual(fb.action, "no_burn_kind")
|
||||
self.assertFalse(eng.store.is_domain_burned("x.com"))
|
||||
|
||||
|
||||
class TestPipelineStrategyIntegration(unittest.TestCase):
|
||||
def test_pipeline_stops_on_strategy_fail_fast_kind(self) -> None:
|
||||
p = FakeProvider(
|
||||
outcomes=[
|
||||
RegisterResult(
|
||||
ok=False,
|
||||
provider="fake",
|
||||
email="u@blocked.tld",
|
||||
error="disallowed",
|
||||
error_kind="registration_disallowed",
|
||||
),
|
||||
RegisterResult(
|
||||
ok=True,
|
||||
provider="fake",
|
||||
email="ok@x.com",
|
||||
secret="sk-" + "b" * 40,
|
||||
secret_kind="api_key",
|
||||
),
|
||||
]
|
||||
)
|
||||
eng = StrategyEngine(
|
||||
fail_fast=True,
|
||||
fail_fast_kinds=["registration_disallowed"],
|
||||
burn_enabled=True,
|
||||
burn_track=["domain"],
|
||||
burn_on_kinds=["registration_disallowed"],
|
||||
)
|
||||
pipe = Pipeline(p, fail_fast=False, strategy=eng, verifier=None)
|
||||
with (
|
||||
patch(
|
||||
"register_core.util.proxy.preflight_nodes_for_register",
|
||||
side_effect=lambda extra, **kw: {
|
||||
**(extra or {}),
|
||||
"_nodes_preflight_done": True,
|
||||
"_nodes_preflight": {"skipped": True},
|
||||
},
|
||||
),
|
||||
patch(
|
||||
"register_core.util.proxy.inject_attempt_proxy",
|
||||
side_effect=lambda extra, **kw: {
|
||||
**(extra or {}),
|
||||
"_egress_ip": "7.7.7.7",
|
||||
},
|
||||
),
|
||||
patch(
|
||||
"register_core.util.proxy.report_attempt_proxy_result",
|
||||
return_value=None,
|
||||
),
|
||||
):
|
||||
stats = pipe.run(2, extra={"egress": "direct", "nodes_preflight": False})
|
||||
self.assertEqual(stats.ok, 0)
|
||||
self.assertEqual(stats.fail, 1)
|
||||
self.assertEqual(p.calls, 1)
|
||||
self.assertIn("registration_disallowed", stats.stopped_reason or "")
|
||||
self.assertTrue(eng.store.is_domain_burned("blocked.tld"))
|
||||
|
||||
def test_pipeline_precheck_skips_burned_ip_and_continues(self) -> None:
|
||||
"""Burned egress IP → skip attempt (no register), rotate; do not halt batch."""
|
||||
p = FakeProvider()
|
||||
eng = StrategyEngine()
|
||||
eng.store.burn_ip("6.6.6.6", reason="registration_disallowed")
|
||||
pipe = Pipeline(p, fail_fast=True, strategy=eng, verifier=None)
|
||||
ips = iter(["6.6.6.6", "8.8.8.8"])
|
||||
|
||||
def _inject(extra, **kw):
|
||||
return {**(extra or {}), "_egress_ip": next(ips)}
|
||||
|
||||
with (
|
||||
patch(
|
||||
"register_core.util.proxy.preflight_nodes_for_register",
|
||||
side_effect=lambda extra, **kw: {
|
||||
**(extra or {}),
|
||||
"_nodes_preflight_done": True,
|
||||
"_nodes_preflight": {"skipped": True},
|
||||
},
|
||||
),
|
||||
patch(
|
||||
"register_core.util.proxy.inject_attempt_proxy",
|
||||
side_effect=_inject,
|
||||
),
|
||||
patch(
|
||||
"register_core.util.proxy.report_attempt_proxy_result",
|
||||
return_value=None,
|
||||
),
|
||||
):
|
||||
stats = pipe.run(2, extra={"egress": "direct", "nodes_preflight": False})
|
||||
# attempt1 burned → skip; attempt2 healthy → register once success
|
||||
self.assertEqual(p.calls, 1)
|
||||
self.assertEqual(stats.ok, 1)
|
||||
self.assertEqual(stats.fail, 1)
|
||||
self.assertEqual(stats.stopped_reason, "")
|
||||
skip_arts = [
|
||||
r
|
||||
for r in stats.results
|
||||
if (r.artifacts or {}).get("skip_attempt")
|
||||
]
|
||||
self.assertEqual(len(skip_arts), 1)
|
||||
self.assertIn("ip burned", skip_arts[0].error or "")
|
||||
|
||||
def test_pipeline_domain_precheck_stops_batch(self) -> None:
|
||||
"""Fixed-domain hard-burn is batch-fatal (skip_attempt=False)."""
|
||||
|
||||
class FixedDomainSrc:
|
||||
name = "tinyhost"
|
||||
forced_domain = "burned.example"
|
||||
|
||||
def allocate(self):
|
||||
raise AssertionError("allocate must not run after domain precheck")
|
||||
|
||||
def release(self, mailbox, *, success=False):
|
||||
pass
|
||||
|
||||
p = FakeProvider()
|
||||
eng = StrategyEngine()
|
||||
eng.store.burn_domain("burned.example", reason="unsupported_email")
|
||||
pipe = Pipeline(
|
||||
p,
|
||||
email_source=FixedDomainSrc(), # type: ignore[arg-type]
|
||||
fail_fast=True,
|
||||
strategy=eng,
|
||||
verifier=None,
|
||||
)
|
||||
with (
|
||||
patch(
|
||||
"register_core.util.proxy.preflight_nodes_for_register",
|
||||
side_effect=lambda extra, **kw: {
|
||||
**(extra or {}),
|
||||
"_nodes_preflight_done": True,
|
||||
"_nodes_preflight": {"skipped": True},
|
||||
},
|
||||
),
|
||||
patch(
|
||||
"register_core.util.proxy.inject_attempt_proxy",
|
||||
side_effect=lambda extra, **kw: {
|
||||
**(extra or {}),
|
||||
"_egress_ip": "1.1.1.1",
|
||||
},
|
||||
),
|
||||
):
|
||||
stats = pipe.run(2, extra={"egress": "direct", "nodes_preflight": False})
|
||||
self.assertEqual(p.calls, 0)
|
||||
self.assertEqual(stats.fail, 1)
|
||||
self.assertIn("domain burned", stats.stopped_reason or "")
|
||||
self.assertEqual(stats.results[0].error_kind, "unsupported_email")
|
||||
|
||||
|
||||
class TestMailInject(unittest.TestCase):
|
||||
def test_prepare_mail_inject_sets_fixed_and_helper(self) -> None:
|
||||
from register_core.contracts import Mailbox
|
||||
from register_core.util.mail_inject import prepare_mail_inject
|
||||
|
||||
class Src:
|
||||
name = "tinyhost"
|
||||
|
||||
def allocate(self):
|
||||
return Mailbox(
|
||||
address="fixed@publicvm.com",
|
||||
token="tok",
|
||||
provider="tinyhost",
|
||||
)
|
||||
|
||||
env: dict[str, str] = {}
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
mb = prepare_mail_inject(
|
||||
Src(), # type: ignore[arg-type]
|
||||
env,
|
||||
timeout_s=30,
|
||||
sender_hint="xai",
|
||||
force_helper=True,
|
||||
work_dir=td,
|
||||
)
|
||||
self.assertIsNotNone(mb)
|
||||
assert mb is not None
|
||||
self.assertEqual(env["FIXED_EMAIL"], "fixed@publicvm.com")
|
||||
self.assertEqual(env["EMAIL_PROVIDER"], "fixed")
|
||||
self.assertTrue(env.get("OTP_HELPER"))
|
||||
self.assertTrue(Path(env["OTP_HELPER"]).is_file())
|
||||
self.assertTrue(env.get("REGISTER_OTP_SPEC_PATH"))
|
||||
self.assertTrue(Path(env["REGISTER_OTP_SPEC_PATH"]).is_file())
|
||||
# path-only OTP: never put token JSON in env
|
||||
self.assertNotIn("REGISTER_OTP_SPEC", env)
|
||||
self.assertTrue(env.get("OTP_HELPER_PYTHON"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,252 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Static router gate: the three ./register.sh production entries must route
|
||||
through the register_core Pipeline shell (migrate milestone A). Asserts every
|
||||
provider branch reaches register_core by default and only falls back to legacy
|
||||
runner scripts behind an explicit *_LEGACY=1 env switch.
|
||||
|
||||
Run validation (not commit-gated): ./register.sh grok|chatgpt|mimo 1 actually
|
||||
execs register_core on a dry host — see MANUAL in docs/DEVELOPED.md.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
REGISTER_SH = ROOT / "register.sh"
|
||||
RUN_REGISTER_CORE = ROOT / "run-register-core.sh"
|
||||
|
||||
|
||||
def _case_block(src: str, trigger: str) -> str:
|
||||
"""Return the text of a `case` arm like ` grok|xai) ... ;;`.
|
||||
|
||||
Scan line-by-line from the trigger arm until the next sibling arm or `esac`.
|
||||
Handles trailing `\\`-continued exec lines and nested blocks.
|
||||
"""
|
||||
lines = src.splitlines()
|
||||
start = None
|
||||
for i, line in enumerate(lines):
|
||||
stripped = line.strip()
|
||||
if stripped == trigger + ")" or stripped.startswith(trigger + ")"):
|
||||
start = i
|
||||
break
|
||||
if start is None:
|
||||
raise AssertionError(f"case arm {trigger!r} not found in register.sh")
|
||||
end = len(lines)
|
||||
# Next arm: a line whose strip matches `<words>)` at the same 2-space indent
|
||||
# as the trigger, or `esac`. `words` allows `*` and `...` so a same-indent
|
||||
# `*)` / `*|*)` default guard also terminates the block, and `esac` must be at
|
||||
# the same indent as the trigger so a nested inner `case ... esac` (deeper
|
||||
# indent) doesn't prematurely end the outer arm.
|
||||
trig_indent = len(lines[start]) - len(lines[start].lstrip())
|
||||
for j in range(start + 1, len(lines)):
|
||||
line = lines[j]
|
||||
stripped = line.strip()
|
||||
if stripped == "esac" and (len(line) - len(line.lstrip())) == trig_indent:
|
||||
end = j
|
||||
break
|
||||
# arm line: indent matches trigger and looks like `<words>)`
|
||||
indent = len(line) - len(line.lstrip())
|
||||
if indent == trig_indent and re.match(r"^[A-Za-z0-9_|.*\-\[\] ]+\)\s*$", stripped):
|
||||
end = j
|
||||
break
|
||||
return "\n".join(lines[start:end])
|
||||
|
||||
|
||||
class TestRouterGate(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.src = REGISTER_SH.read_text(encoding="utf-8")
|
||||
self.core_src = RUN_REGISTER_CORE.read_text(encoding="utf-8")
|
||||
|
||||
# ---- grok ----
|
||||
def test_grok_routes_to_register_core_by_default(self) -> None:
|
||||
block = _case_block(self.src, "grok|xai")
|
||||
# default path reaches run-register-core.sh (which execs register_core)
|
||||
self.assertIn("run-register-core.sh", block)
|
||||
# rollback guard is present
|
||||
self.assertIn("GROK_LEGACY", block)
|
||||
# legacy fallback retained (run-register.sh), kept as rollback / adapter target
|
||||
self.assertIn("run-register.sh", block)
|
||||
# register_cli.py direct exec is only the final local/dev fallback AFTER
|
||||
# the core shell and legacy runner have both been tried — i.e. run-register-core
|
||||
# must appear before any bare register_cli.py exec.
|
||||
core_pos = block.find("run-register-core.sh")
|
||||
cli_pos = block.find("register_cli.py")
|
||||
self.assertGreater(core_pos, -1)
|
||||
if cli_pos > -1:
|
||||
self.assertLess(
|
||||
core_pos,
|
||||
cli_pos,
|
||||
"run-register-core.sh must precede any register_cli.py fallback",
|
||||
)
|
||||
|
||||
def test_grok_core_shell_execs_register_core(self) -> None:
|
||||
# run-register-core.sh must drive register_core Pipeline via profile
|
||||
self.assertIn("register_core run", self.core_src)
|
||||
self.assertIn("profiles/grok-tinyhost.example.yaml", self.core_src)
|
||||
# legacy exit contract preserved (0/1/2 mapping)
|
||||
self.assertIn("legacy", self.core_src.lower())
|
||||
# env outer shell preserved from run-register.sh
|
||||
self.assertIn("preflight-clash-nodes.sh", self.core_src)
|
||||
self.assertIn(".env", self.core_src)
|
||||
self.assertIn("PLAYWRIGHT_BROWSERS_PATH", self.core_src)
|
||||
|
||||
# ---- mimo ----
|
||||
def test_mimo_routes_to_register_core_profile(self) -> None:
|
||||
block = _case_block(self.src, "mimo|xiaomi|mimo-tts")
|
||||
self.assertIn("-m register_core run", block)
|
||||
self.assertIn("profiles/mimo-tinyhost.example.yaml", block)
|
||||
self.assertIn("MIMO_LEGACY", block)
|
||||
self.assertIn("providers/mimo/run-register.sh", block)
|
||||
# default branch must reach register_core BEFORE the legacy Node runner
|
||||
core_pos = block.find("-m register_core run")
|
||||
legacy_pos = block.find("providers/mimo/run-register.sh")
|
||||
self.assertGreater(core_pos, -1)
|
||||
self.assertLess(core_pos, legacy_pos, "register_core must precede legacy mimo runner")
|
||||
|
||||
# ---- chatgpt ----
|
||||
def test_chatgpt_routes_to_register_core_profile(self) -> None:
|
||||
block = _case_block(self.src, "chatgpt|openai|openai-platform")
|
||||
self.assertIn("-m register_core run", block)
|
||||
self.assertIn("CHATGPT_LEGACY", block)
|
||||
self.assertIn("providers/chatgpt/run-register.sh", block)
|
||||
# env overrides still forwarded via register_core CLI flags
|
||||
self.assertIn("REGISTER_EGRESS", block)
|
||||
self.assertIn("CHATGPT_PROXY", block)
|
||||
# default register_core must precede the legacy runner — check on exec lines
|
||||
# only (strip `#` comments so prose mentions don't skew ordering).
|
||||
code = "\n".join(
|
||||
ln for ln in block.splitlines() if not ln.lstrip().startswith("#")
|
||||
)
|
||||
core_pos = code.find('exec "$_PY"')
|
||||
legacy_pos = code.find('exec bash "$ROOT/providers/chatgpt/run-register.sh"')
|
||||
self.assertGreater(core_pos, -1, "chatgpt branch must exec register_core")
|
||||
self.assertGreater(legacy_pos, -1, "chatgpt legacy fallback must be present")
|
||||
self.assertLess(core_pos, legacy_pos, "register_core must precede legacy chatgpt runner")
|
||||
|
||||
def test_chatgpt_profile_selection_by_email_source(self) -> None:
|
||||
block = _case_block(self.src, "chatgpt|openai|openai-platform")
|
||||
# Profile is chosen by CHATGPT_EMAIL_SOURCE (legacy default = cloudflare → cf).
|
||||
self.assertIn("CHATGPT_EMAIL_SOURCE", block)
|
||||
for prof in (
|
||||
"profiles/chatgpt-cf.example.yaml",
|
||||
"profiles/chatgpt-tinyhost.example.yaml",
|
||||
"profiles/chatgpt-gmail.example.yaml",
|
||||
):
|
||||
self.assertIn(prof, block, f"chatgpt branch must list profile {prof}")
|
||||
# default (cloudflare/auto/empty) maps to cf profile (matches legacy default)
|
||||
self.assertIn('cloudflare|cf|auto|"")', block)
|
||||
self.assertIn("CHATGPT_TIMEOUT", block)
|
||||
# timeout default 900 preserved (not argparse 1200)
|
||||
self.assertIn('"${CHATGPT_TIMEOUT:-900}"', block)
|
||||
|
||||
def test_chatgpt_env_knobs_preserved(self) -> None:
|
||||
block = _case_block(self.src, "chatgpt|openai|openai-platform")
|
||||
# proxy rotation env forwarded (was dropped before the fix)
|
||||
self.assertIn("CHATGPT_PROXY_ROTATE_MODE", block)
|
||||
self.assertIn("CHATGPT_PROXY_ROTATE_EVERY", block)
|
||||
self.assertIn("--proxy-rotate", block)
|
||||
# sink only passed when CHATGPT_SINK explicitly set (else profile sink.path wins)
|
||||
self.assertIn("CHATGPT_SINK", block)
|
||||
self.assertIn("--sink", block)
|
||||
# email domain override honored at the env layer (profile no longer pins it)
|
||||
self.assertIn("CHATGPT_EMAIL_DOMAIN", block)
|
||||
|
||||
# ---- cross-cutting ----
|
||||
def test_typesafe_routes_to_register_core_profile(self) -> None:
|
||||
block = _case_block(self.src, "typesafe|jev|typesafe-ai")
|
||||
self.assertIn("-m register_core run", block)
|
||||
self.assertIn("profiles/typesafe-tinyhost.example.yaml", block)
|
||||
self.assertIn("TYPESAFE_LEGACY", block)
|
||||
self.assertIn("providers/typesafe/run-register.sh", block)
|
||||
code = "\n".join(
|
||||
ln for ln in block.splitlines() if not ln.lstrip().startswith("#")
|
||||
)
|
||||
core_pos = code.find('exec "$_PY"')
|
||||
legacy_pos = code.find('exec bash "$ROOT/providers/typesafe/run-register.sh"')
|
||||
self.assertGreater(core_pos, -1, "typesafe branch must exec register_core")
|
||||
self.assertGreater(legacy_pos, -1, "typesafe legacy fallback must be present")
|
||||
self.assertLess(core_pos, legacy_pos, "register_core must precede legacy typesafe runner")
|
||||
self.assertIn("TYPESAFE_EMAIL_SOURCE", block)
|
||||
self.assertIn("REGISTER_EGRESS", block)
|
||||
self.assertIn("TYPESAFE_PROXY", block)
|
||||
|
||||
def test_smoke_typesafe_routes(self) -> None:
|
||||
block = _case_block(self.src, "smoke")
|
||||
self.assertIn("providers/typesafe/smoke.sh", block)
|
||||
self.assertIn("typesafe|jev|typesafe-ai", block)
|
||||
self.assertIn("providers/mimo/smoke.sh", block)
|
||||
|
||||
def test_all_three_provider_branches_mention_register_core(self) -> None:
|
||||
for trigger in (
|
||||
"grok|xai",
|
||||
"mimo|xiaomi|mimo-tts",
|
||||
"chatgpt|openai|openai-platform",
|
||||
"typesafe|jev|typesafe-ai",
|
||||
):
|
||||
block = _case_block(self.src, trigger)
|
||||
self.assertIn("register_core", block, f"{trigger} must reference register_core")
|
||||
|
||||
def test_core_subcommand_branch_unchanged(self) -> None:
|
||||
# `./register.sh core ...` keeps delegating to `python -m register_core "$@"`
|
||||
block = _case_block(self.src, "core|framework")
|
||||
self.assertIn("-m register_core", block)
|
||||
|
||||
# ---- _case_block regex hardening ----
|
||||
def test_case_block_regex_recognizes_default_guard(self) -> None:
|
||||
# A same-indent `*)` (default arm) must terminate a sibling block, so future
|
||||
# additions of a default guard don't get mis-segmented into the next sibling.
|
||||
src = (
|
||||
"case x in\n"
|
||||
" foo|bar)\n"
|
||||
" echo one\n"
|
||||
" ;;\n"
|
||||
" *)\n"
|
||||
" echo default\n"
|
||||
" ;;\n"
|
||||
"esac\n"
|
||||
)
|
||||
block = _case_block(src, "foo|bar")
|
||||
self.assertIn("echo one", block)
|
||||
self.assertNotIn("echo default", block, "*) default guard must end the foo|bar block")
|
||||
|
||||
def test_case_block_regex_recognizes_dotdot_guard(self) -> None:
|
||||
# `...` range arm (some shells) and `*|*)` both terminate.
|
||||
src = (
|
||||
"case x in\n"
|
||||
" grok|xai)\n"
|
||||
" exec a\n"
|
||||
" ;;\n"
|
||||
" ...)\n"
|
||||
" exec b\n"
|
||||
"esac\n"
|
||||
)
|
||||
block = _case_block(src, "grok|xai")
|
||||
self.assertIn("exec a", block)
|
||||
self.assertNotIn("exec b", block)
|
||||
|
||||
# ---- profile egress honesty (fix #1 / core finding) ----
|
||||
def test_grok_profile_pins_clash_egress(self) -> None:
|
||||
# Grok egress must be pinned in the profile (not `auto`) so profile_to_job
|
||||
# sets extra["proxy"] truthy and grok_adapter force-sets child PROXY/CPA_PROXY
|
||||
# → Pipeline owns egress instead of relying on inherited shell PROXY env.
|
||||
p = (ROOT / "profiles" / "grok-tinyhost.example.yaml").read_text(encoding="utf-8")
|
||||
self.assertIn("mode: clash", p)
|
||||
self.assertIn('"http://127.0.0.1:7897"', p)
|
||||
# a concrete proxy url must accompany clash mode (the fix)
|
||||
self.assertRegex(p, r"proxy:\s*\"?http://127\.0\.0\.1:7897")
|
||||
|
||||
def test_chatgpt_tinyhost_profile_does_not_pin_domain(self) -> None:
|
||||
# chatgpt tinyhost profile must NOT pin domain so CHATGPT_EMAIL_DOMAIN env
|
||||
# override is honored (extra["email_domain"] unset → adapter self.email_domain ← env).
|
||||
p = (ROOT / "profiles" / "chatgpt-tinyhost.example.yaml").read_text(encoding="utf-8")
|
||||
mailbox_lines = p.split(" decode:", 1)[0].split(" mailbox:", 1)[1]
|
||||
self.assertNotIn("publicvm.com", mailbox_lines)
|
||||
self.assertNotRegex(mailbox_lines, r"^\s*domain:\s*\S")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,153 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Contract + smoke checks for outsider-friendly simple packaging."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def test_simple_config_template() -> None:
|
||||
p = ROOT / "config.simple.example.json"
|
||||
assert p.is_file(), "missing config.simple.example.json"
|
||||
raw = json.loads(p.read_text(encoding="utf-8"))
|
||||
cfg = {
|
||||
k: v
|
||||
for k, v in raw.items()
|
||||
if not (isinstance(k, str) and (k.startswith("//") or k.startswith("#")))
|
||||
}
|
||||
# low-friction default channel
|
||||
assert cfg.get("email_provider") == "duckmail"
|
||||
assert "duckmail_api_key" in cfg
|
||||
assert cfg.get("cpa_export_enabled") is True
|
||||
assert cfg.get("cpa_probe_chat") is True
|
||||
assert cfg.get("cpa_probe_chat_required") is True
|
||||
assert cfg.get("cpa_remote_inject") is False
|
||||
assert cfg.get("cpa_auth_dir") == "./cpa_auths"
|
||||
assert "cli-chat-proxy.grok.com" in str(cfg.get("cpa_base_url") or "")
|
||||
# explicit headless/mint knobs for outsiders
|
||||
assert cfg.get("cpa_headless") is False
|
||||
assert cfg.get("cpa_mint_required") is False
|
||||
print("PASS simple config template")
|
||||
|
||||
|
||||
def test_setup_script_syntax_and_readme() -> None:
|
||||
setup = ROOT / "scripts" / "setup_simple.sh"
|
||||
doctor = ROOT / "scripts" / "doctor_secrets.sh"
|
||||
assert setup.is_file()
|
||||
assert doctor.is_file()
|
||||
mode = setup.stat().st_mode
|
||||
assert mode & stat.S_IXUSR, "setup_simple.sh must be executable"
|
||||
assert doctor.stat().st_mode & stat.S_IXUSR, "doctor_secrets.sh must be executable"
|
||||
src = setup.read_text(encoding="utf-8")
|
||||
assert "config.simple.example.json" in src
|
||||
assert "register_cli.py" in src
|
||||
assert "doctor" in src
|
||||
assert "placeholder" in src or "duckmail_api_key" in src
|
||||
dsrc = doctor.read_text(encoding="utf-8")
|
||||
assert "git ls-files" in dsrc
|
||||
assert "never" in dsrc.lower() or "no content" in dsrc.lower() or "paths only" in dsrc.lower()
|
||||
# must not cat secrets
|
||||
assert "cat mail_credentials" not in dsrc
|
||||
assert "cat config.json" not in dsrc
|
||||
# bash -n
|
||||
subprocess.run(["bash", "-n", str(setup)], check=True)
|
||||
subprocess.run(["bash", "-n", str(doctor)], check=True)
|
||||
# doctor runs offline against this repo (may exit 2 on mode warnings)
|
||||
r = subprocess.run(["bash", str(doctor)], cwd=ROOT, capture_output=True, text=True)
|
||||
assert r.returncode in (0, 2), r.stdout + r.stderr
|
||||
assert "tracked" in (r.stdout + r.stderr).lower() or "[ok]" in (r.stdout + r.stderr)
|
||||
readme = (ROOT / "README.md").read_text(encoding="utf-8")
|
||||
assert "最短路径" in readme or "快速开始" in readme
|
||||
assert "config.simple.example.json" in readme
|
||||
assert "entitlement_denied" in readme
|
||||
assert "setup_simple.sh" in readme
|
||||
assert "doctor_secrets.sh" in readme
|
||||
assert "duckmail" in readme.lower()
|
||||
assert "Education / personal automation" in readme or "not a free-quota farm" in readme.lower()
|
||||
assert "常见卡点" in readme or "Typical blockers" in readme or "卡点" in readme
|
||||
print("PASS setup script + doctor + readme")
|
||||
|
||||
|
||||
def test_gitignore_keeps_examples() -> None:
|
||||
gi = (ROOT / ".gitignore").read_text(encoding="utf-8")
|
||||
assert "config.json" in gi
|
||||
banned = {
|
||||
ln.strip().lstrip("/")
|
||||
for ln in gi.splitlines()
|
||||
if ln.strip() and not ln.strip().startswith("#")
|
||||
}
|
||||
assert "config.simple.example.json" not in banned
|
||||
assert "scripts/setup_simple.sh" not in banned
|
||||
print("PASS gitignore does not ban simple example")
|
||||
|
||||
|
||||
def test_setup_smoke_tmp_copy() -> None:
|
||||
"""Run setup in a temp tree: creates config, does not overwrite existing."""
|
||||
setup_src = ROOT / "scripts" / "setup_simple.sh"
|
||||
simple = ROOT / "config.simple.example.json"
|
||||
mail_ex = ROOT / "mail_credentials.example.txt"
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
td_path = Path(td)
|
||||
(td_path / "scripts").mkdir()
|
||||
shutil.copy2(setup_src, td_path / "scripts" / "setup_simple.sh")
|
||||
shutil.copy2(simple, td_path / "config.simple.example.json")
|
||||
shutil.copy2(mail_ex, td_path / "mail_credentials.example.txt")
|
||||
# minimal pyproject so uv may fail softly — doctor still runs
|
||||
(td_path / "pyproject.toml").write_text(
|
||||
'[project]\nname="t"\nversion="0"\nrequires-python=">=3.13"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
env = os.environ.copy()
|
||||
# avoid network uv sync failure killing the script if uv tries hard —
|
||||
# script continues after warn if uv missing; if uv present sync may fail.
|
||||
# Patch: run with UV offline if possible
|
||||
env.setdefault("UV_NO_SYNC", "1")
|
||||
# First run
|
||||
r = subprocess.run(
|
||||
["bash", "scripts/setup_simple.sh"],
|
||||
cwd=td_path,
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
# allow non-zero if uv sync fails in empty project; files must exist
|
||||
out = (r.stdout or "") + (r.stderr or "")
|
||||
assert (td_path / "config.json").is_file(), out
|
||||
assert (td_path / "mail_credentials.txt").is_file(), out
|
||||
# mutate config and ensure second run does not overwrite
|
||||
(td_path / "config.json").write_text('{"email_provider":"keep-me"}\n', encoding="utf-8")
|
||||
r2 = subprocess.run(
|
||||
["bash", "scripts/setup_simple.sh"],
|
||||
cwd=td_path,
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
out2 = (r2.stdout or "") + (r2.stderr or "")
|
||||
assert "skip" in out2.lower() or "already exists" in out2.lower(), out2
|
||||
assert "keep-me" in (td_path / "config.json").read_text(encoding="utf-8")
|
||||
# placeholder mail should trigger warn path when provider hotmail —
|
||||
# default simple is duckmail so expect duckmail key warn in output ideally
|
||||
assert "doctor" in out.lower() or "doctor" in out2.lower()
|
||||
print("PASS setup smoke tmp copy")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
test_simple_config_template()
|
||||
test_setup_script_syntax_and_readme()
|
||||
test_gitignore_keeps_examples()
|
||||
test_setup_smoke_tmp_copy()
|
||||
print("\nALL PASS (simple packaging)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Skeleton smoke: required paths and public contracts exist."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def test_architecture_and_docs_exist() -> None:
|
||||
for rel in (
|
||||
"ARCHITECTURE.md",
|
||||
"Makefile",
|
||||
"docs/ADDING_PROVIDER.md",
|
||||
"docs/LAYOUT.md",
|
||||
"providers/README.md",
|
||||
"providers/_template/README.md",
|
||||
"providers/_template/run-register.sh",
|
||||
"providers/grok/README.md",
|
||||
"providers/mimo/README.md",
|
||||
"apps/README.md",
|
||||
"examples/minimal_pipeline.py",
|
||||
"register_core/README.md",
|
||||
"register.sh",
|
||||
):
|
||||
p = ROOT / rel
|
||||
assert p.is_file(), f"missing skeleton file: {rel}"
|
||||
|
||||
|
||||
def test_template_runner_is_executable_or_shell() -> None:
|
||||
runner = ROOT / "providers/_template/run-register.sh"
|
||||
text = runner.read_text(encoding="utf-8")
|
||||
assert text.startswith("#!")
|
||||
assert "RESULT_JSON" in text or "exit 2" in text
|
||||
|
||||
|
||||
def test_register_core_lists_builtin_providers() -> None:
|
||||
from register_core.providers.registry import list_providers
|
||||
|
||||
names = set(list_providers())
|
||||
assert "grok" in names
|
||||
assert "mimo" in names
|
||||
|
||||
|
||||
def test_public_redact_in_example_shape() -> None:
|
||||
from register_core.contracts import RegisterResult
|
||||
|
||||
r = RegisterResult(
|
||||
ok=True,
|
||||
provider="demo",
|
||||
email="a@b.c",
|
||||
password="hunter2-password",
|
||||
secret="sk-aaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
secret_kind="api_key",
|
||||
)
|
||||
pub = r.to_public_dict()
|
||||
assert "hunter2" not in str(pub)
|
||||
assert pub["secret_kind"] == "api_key"
|
||||
@@ -0,0 +1,122 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline checks for SSO cookie normalization and email identity keys."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def test_normalize_sso_cookie() -> None:
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from cpa_xai.accounts import normalize_sso_cookie
|
||||
|
||||
jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.abc.def"
|
||||
assert normalize_sso_cookie(jwt) == jwt
|
||||
assert normalize_sso_cookie("-" + jwt) == jwt
|
||||
assert normalize_sso_cookie(" -" + jwt + " ") == jwt
|
||||
assert normalize_sso_cookie("--" + jwt) == jwt
|
||||
assert normalize_sso_cookie("") == ""
|
||||
assert normalize_sso_cookie(None) == ""
|
||||
# do not strip arbitrary leading dash without eyJ nearby
|
||||
assert normalize_sso_cookie("-session-id-value") == "-session-id-value"
|
||||
print("PASS normalize_sso_cookie")
|
||||
|
||||
|
||||
def test_format_account_line() -> None:
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from cpa_xai.accounts import format_account_line
|
||||
|
||||
jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.abc.def"
|
||||
line = format_account_line("a@x.com", "pw", "-" + jwt)
|
||||
assert line == f"a@x.com----pw----{jwt}\n"
|
||||
print("PASS format_account_line")
|
||||
|
||||
|
||||
def test_parse_accounts_strips_leading_dash() -> None:
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from cpa_xai.accounts import parse_accounts_file
|
||||
|
||||
jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.abc.def"
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
p = Path(td) / "accounts_cli.txt"
|
||||
# Explicit: third field starts with '-' before JWT (5 dashes between pw and jwt)
|
||||
p.write_text(f"a@x.com----pw-----{jwt}\n", encoding="utf-8")
|
||||
rows = parse_accounts_file(p)
|
||||
assert len(rows) == 1
|
||||
assert rows[0].sso == jwt
|
||||
print("PASS parse_accounts_strips_leading_dash")
|
||||
|
||||
|
||||
def test_extract_sso_from_cookies_normalizes() -> None:
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from cpa_xai.protocol_mint import extract_sso_from_cookies
|
||||
|
||||
jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.abc.def"
|
||||
assert extract_sso_from_cookies([{"name": "sso", "value": "-" + jwt}]) == jwt
|
||||
assert extract_sso_from_cookies({"sso": "-" + jwt}) == jwt
|
||||
print("PASS extract_sso_from_cookies_normalizes")
|
||||
|
||||
|
||||
def test_email_match_keys_plus_alias() -> None:
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from cpa_xai.accounts import email_in_existing, email_match_keys, existing_cpa_emails
|
||||
|
||||
email = "user+abc@hotmail.com"
|
||||
keys = email_match_keys(email)
|
||||
assert "user+abc@hotmail.com" in keys
|
||||
assert "user-abc@hotmail.com" in keys
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
auth = Path(td)
|
||||
# filename-only (no JSON email field) — historical/partial files
|
||||
(auth / "xai-user-abc@hotmail.com.json").write_text(
|
||||
json.dumps({"type": "xai", "access_token": "x"}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
have = existing_cpa_emails(auth)
|
||||
assert email_in_existing(email, have)
|
||||
assert not email_in_existing("other+zz@hotmail.com", have)
|
||||
print("PASS email_match_keys_plus_alias")
|
||||
|
||||
|
||||
def test_config_bool_strings() -> None:
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(ROOT))
|
||||
from cpa_export import _config_bool
|
||||
|
||||
assert _config_bool("false", default=True) is False
|
||||
assert _config_bool("0", default=True) is False
|
||||
assert _config_bool("true", default=False) is True
|
||||
assert _config_bool(None, default=True) is True
|
||||
assert _config_bool(True) is True
|
||||
print("PASS config_bool_strings")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
test_normalize_sso_cookie()
|
||||
test_format_account_line()
|
||||
test_parse_accounts_strips_leading_dash()
|
||||
test_extract_sso_from_cookies_normalizes()
|
||||
test_email_match_keys_plus_alias()
|
||||
test_config_bool_strings()
|
||||
print("\nALL PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,131 @@
|
||||
"""Unit tests for the CF Temp Mail source (Task 7).
|
||||
|
||||
Browser-free and network-free: every HTTP boundary is monkeypatched, and all
|
||||
addresses/codes/JWTs are synthetic.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from register_core.contracts import Mailbox
|
||||
from register_core.email.registry import get_email_source, list_email_sources
|
||||
from register_core.email.sources.temp_mail import TempMailClient, TempMailSource
|
||||
from register_core.errors import MailMissError, ProviderError
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[
|
||||
{"subject": "Security code", "text": "Use code: 123456"},
|
||||
{"subject": "验证码", "text": "验证码 654321"},
|
||||
],
|
||||
)
|
||||
def test_extract_code_from_synthetic_mail(body):
|
||||
assert TempMailClient.extract_code_from_text(json.dumps(body)) in {"123456", "654321"}
|
||||
|
||||
|
||||
def test_extract_code_returns_none_without_six_digits():
|
||||
assert TempMailClient.extract_code_from_text("no code here, only 12345") is None
|
||||
assert TempMailClient.extract_code_from_text("") is None
|
||||
|
||||
|
||||
def _source() -> TempMailSource:
|
||||
return TempMailSource(
|
||||
base_url="https://mail.invalid",
|
||||
admin_password_env="TEST_TEMP_MAIL_ADMIN",
|
||||
domain="invalid",
|
||||
)
|
||||
|
||||
|
||||
def test_registry_source_has_no_password_in_redacted_mailbox(monkeypatch):
|
||||
source = _source()
|
||||
monkeypatch.setenv("TEST_TEMP_MAIL_ADMIN", "synthetic-admin")
|
||||
mailbox = source._mailbox_from_payload({"address": "a@invalid", "jwt": "synthetic-jwt"})
|
||||
assert mailbox.redact() == {
|
||||
"address": "a@invalid",
|
||||
"provider": "cf_temp",
|
||||
"has_token": True,
|
||||
"meta_keys": [],
|
||||
}
|
||||
|
||||
|
||||
def test_allocate_without_admin_env_raises_before_any_http(monkeypatch):
|
||||
source = _source()
|
||||
monkeypatch.delenv("TEST_TEMP_MAIL_ADMIN", raising=False)
|
||||
|
||||
def explode(*args, **kwargs): # pragma: no cover - must never run
|
||||
raise AssertionError("no HTTP call may happen without the admin env")
|
||||
|
||||
monkeypatch.setattr("register_core.email.sources.temp_mail.httpx.post", explode)
|
||||
with pytest.raises(ProviderError) as excinfo:
|
||||
source.allocate()
|
||||
assert "temp_mail_admin_env_missing" in str(excinfo.value)
|
||||
|
||||
|
||||
def test_poll_otp_returns_fresh_code_and_skips_used(monkeypatch):
|
||||
source = _source()
|
||||
mails = [
|
||||
{"subject": "Security code", "text": "code: 111111", "timestamp": 100},
|
||||
{"subject": "Security code", "text": "code: 222222", "timestamp": 200},
|
||||
]
|
||||
monkeypatch.setattr(TempMailClient, "list_mails", lambda self, mailbox: mails)
|
||||
mailbox = Mailbox(address="a@invalid", token="synthetic-jwt", provider="cf_temp")
|
||||
|
||||
otp = source.poll_otp(mailbox, timeout_s=1, poll_interval_s=0.1, used_codes={"111111"})
|
||||
assert otp.code == "222222"
|
||||
assert otp.source == "cf_temp"
|
||||
assert source.last_wait_diagnostics is not None
|
||||
assert source.last_wait_diagnostics.provider == "cf_temp"
|
||||
|
||||
|
||||
def test_poll_otp_raises_mail_miss_with_diagnostics(monkeypatch):
|
||||
source = _source()
|
||||
monkeypatch.setattr(TempMailClient, "list_mails", lambda self, mailbox: [])
|
||||
monkeypatch.setattr("register_core.email.sources.temp_mail.time.sleep", lambda _s: None)
|
||||
mailbox = Mailbox(address="a@invalid", token="synthetic-jwt", provider="cf_temp")
|
||||
|
||||
with pytest.raises(MailMissError) as excinfo:
|
||||
source.poll_otp(mailbox, timeout_s=0.2, poll_interval_s=0.1)
|
||||
diagnostics = excinfo.value.diagnostics
|
||||
assert diagnostics is not None
|
||||
assert diagnostics.failure_class == "no_mail"
|
||||
# No mailbox JWT may leak into the failure message.
|
||||
assert "synthetic-jwt" not in str(excinfo.value)
|
||||
|
||||
|
||||
def test_poll_otp_drops_mail_older_than_watermark(monkeypatch):
|
||||
source = _source()
|
||||
monkeypatch.setattr(
|
||||
TempMailClient,
|
||||
"list_mails",
|
||||
lambda self, mailbox: [{"subject": "old", "text": "code: 333333", "timestamp": 100}],
|
||||
)
|
||||
monkeypatch.setattr("register_core.email.sources.temp_mail.time.sleep", lambda _s: None)
|
||||
mailbox = Mailbox(address="a@invalid", token="synthetic-jwt", provider="cf_temp")
|
||||
|
||||
with pytest.raises(MailMissError):
|
||||
source.poll_otp(mailbox, timeout_s=0.2, poll_interval_s=0.1, newer_than_epoch=500)
|
||||
|
||||
|
||||
def test_release_is_noop():
|
||||
source = _source()
|
||||
mailbox = Mailbox(address="a@invalid", token="synthetic-jwt", provider="cf_temp")
|
||||
assert source.release(mailbox, success=True) is None
|
||||
|
||||
|
||||
def test_registry_exposes_both_aliases_but_not_in_auto():
|
||||
names = list_email_sources()
|
||||
assert "temp_mail" in names
|
||||
assert "cf_temp" in names
|
||||
source = get_email_source(
|
||||
"cf_temp",
|
||||
base_url="https://mail.invalid",
|
||||
admin_password_env="TEST_TEMP_MAIL_ADMIN",
|
||||
domain="invalid",
|
||||
)
|
||||
assert isinstance(source, TempMailSource)
|
||||
# "auto" must keep preferring the pooled sources; cf_temp is opt-in only.
|
||||
assert not isinstance(get_email_source("auto"), TempMailSource)
|
||||
@@ -0,0 +1,751 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline unit tests for the typesafe.ai provider (no live register)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from unittest.mock import patch
|
||||
|
||||
from register_core.contracts import Mailbox, OtpCode, RegisterResult
|
||||
from register_core.decode.extract import extract_typesafe_magic_link
|
||||
from register_core.errors import FailFastError, MailMissError
|
||||
from register_core.pipeline import Pipeline
|
||||
from register_core.providers.registry import get_provider, list_providers
|
||||
from register_core.providers.typesafe_adapter import TypesafeProvider
|
||||
from register_core.verify.registry import get_verifier
|
||||
from register_core.verify.typesafe_key import TypesafeKeyVerifier
|
||||
|
||||
|
||||
MAGIC_LINK = (
|
||||
"https://login.typesafe.ai/v1/magic_links/redirect"
|
||||
"?public_token=pub-test-token"
|
||||
"&stytch_token_type=magic_links&token=stytch-secret-token"
|
||||
)
|
||||
|
||||
LOGIN_HTML = """
|
||||
<html><body>
|
||||
<input type="hidden" name="$ACTION_3:0" value="{"id":"act-abc"}" />
|
||||
<input type="hidden" name="$ACTION_3:2" value="encrypted-blob-xyz" />
|
||||
<input type="email" />
|
||||
<script>self.__next_f.push([1,"dpl=cc6f6dca06537cc04123caaaf50ca5a76d506a92"])</script>
|
||||
</body></html>
|
||||
"""
|
||||
|
||||
LOGIN_HTML_NEW_DPL = LOGIN_HTML.replace(
|
||||
"cc6f6dca06537cc04123caaaf50ca5a76d506a92",
|
||||
"ffffffffffffffffffffffffffffffffffffffff",
|
||||
)
|
||||
|
||||
|
||||
class FakeEmail:
|
||||
name = "fake"
|
||||
|
||||
def __init__(self, *, fail_otp: bool = False, link: str = MAGIC_LINK) -> None:
|
||||
self.fail_otp = fail_otp
|
||||
self.link = link
|
||||
self.released: list[tuple[str, bool]] = []
|
||||
self.poll_kwargs: list[dict[str, Any]] = []
|
||||
self.allocated = 0
|
||||
self._lock = threading.Lock()
|
||||
|
||||
def allocate(self) -> Mailbox:
|
||||
with self._lock:
|
||||
self.allocated += 1
|
||||
return Mailbox(
|
||||
address="newuser@example.com",
|
||||
token="t",
|
||||
provider=self.name,
|
||||
meta={"local": "newuser", "domain": "example.com"},
|
||||
)
|
||||
|
||||
def poll_otp(self, mailbox: Mailbox, **kwargs: Any) -> OtpCode:
|
||||
with self._lock:
|
||||
self.poll_kwargs.append(dict(kwargs))
|
||||
if self.fail_otp:
|
||||
raise MailMissError("magic link timeout test")
|
||||
return OtpCode(code=self.link, source=self.name)
|
||||
|
||||
def release(self, mailbox: Mailbox, *, success: bool) -> None:
|
||||
with self._lock:
|
||||
self.released.append((mailbox.address, success))
|
||||
|
||||
|
||||
class TestTypesafeRegistry(unittest.TestCase):
|
||||
def test_registered_and_aliases(self):
|
||||
self.assertIn("typesafe", list_providers())
|
||||
self.assertEqual(get_provider("jev").name, "typesafe")
|
||||
self.assertEqual(get_provider("typesafe-ai").name, "typesafe")
|
||||
v = get_verifier("typesafe")
|
||||
self.assertEqual(v.name, "typesafe_key")
|
||||
self.assertEqual(get_verifier("jev").name, "typesafe_key")
|
||||
|
||||
|
||||
class TestTypesafeVerifier(unittest.TestCase):
|
||||
def test_shape_gate(self):
|
||||
v = TypesafeKeyVerifier(live=False)
|
||||
bad = v.verify(RegisterResult(ok=True, provider="typesafe", secret="short"))
|
||||
self.assertFalse(bad.ok)
|
||||
good = v.verify(
|
||||
RegisterResult(
|
||||
ok=True,
|
||||
provider="typesafe",
|
||||
secret="ts_" + "x" * 24,
|
||||
secret_kind="api_key",
|
||||
)
|
||||
)
|
||||
self.assertTrue(good.ok)
|
||||
wrong_kind = v.verify(
|
||||
RegisterResult(
|
||||
ok=True,
|
||||
provider="typesafe",
|
||||
secret="ts_" + "y" * 24,
|
||||
secret_kind="refresh_token",
|
||||
)
|
||||
)
|
||||
self.assertFalse(wrong_kind.ok)
|
||||
live = TypesafeKeyVerifier(live=True)
|
||||
live_ok = live.verify(
|
||||
RegisterResult(
|
||||
ok=True,
|
||||
provider="typesafe",
|
||||
secret="ts_" + "x" * 24,
|
||||
secret_kind="api_key",
|
||||
)
|
||||
)
|
||||
self.assertTrue(live_ok.ok)
|
||||
self.assertIn("shape_ok", live_ok.detail)
|
||||
|
||||
|
||||
class TestTypesafeExtract(unittest.TestCase):
|
||||
def test_extract_plain_and_html_entity(self):
|
||||
parsed = extract_typesafe_magic_link(MAGIC_LINK)
|
||||
self.assertEqual(parsed["token"], "stytch-secret-token")
|
||||
self.assertEqual(parsed["public_token"], "pub-test-token")
|
||||
encoded = MAGIC_LINK.replace("&", "&")
|
||||
parsed2 = extract_typesafe_magic_link(f"<a href=\"{encoded}\">login</a>")
|
||||
self.assertEqual(parsed2["token"], "stytch-secret-token")
|
||||
self.assertEqual(extract_typesafe_magic_link("no link here"), {})
|
||||
reordered = (
|
||||
"https://login.typesafe.ai/v1/magic_links/redirect"
|
||||
"?token=stytch-secret-token&stytch_token_type=magic_links"
|
||||
"&public_token=pub-test-token"
|
||||
)
|
||||
parsed3 = extract_typesafe_magic_link(reordered)
|
||||
self.assertEqual(parsed3["token"], "stytch-secret-token")
|
||||
self.assertEqual(parsed3["public_token"], "pub-test-token")
|
||||
|
||||
def test_parse_login_action_and_deployment_mismatch(self):
|
||||
from providers.typesafe.protocol.constants import CONSOLE_DEPLOYMENT_ID
|
||||
from providers.typesafe.protocol.flow import (
|
||||
parse_deployment_id,
|
||||
parse_login_action,
|
||||
)
|
||||
|
||||
action = parse_login_action(LOGIN_HTML)
|
||||
self.assertEqual(action["action_id"], "act-abc")
|
||||
self.assertEqual(action["index"], "3")
|
||||
self.assertEqual(action["blob"], "encrypted-blob-xyz")
|
||||
self.assertEqual(parse_deployment_id(LOGIN_HTML), CONSOLE_DEPLOYMENT_ID)
|
||||
self.assertNotEqual(parse_deployment_id(LOGIN_HTML_NEW_DPL), CONSOLE_DEPLOYMENT_ID)
|
||||
|
||||
def test_parse_login_action_missing_includes_snippet(self):
|
||||
from providers.typesafe.protocol.flow import TypesafeRegisterError, parse_login_action
|
||||
|
||||
with self.assertRaises(TypesafeRegisterError) as ctx:
|
||||
parse_login_action("<html><body>no action fields</body></html>")
|
||||
self.assertEqual(ctx.exception.kind, "session")
|
||||
snippet = (ctx.exception.steps.get("login_action") or {}).get("html_snippet") or ""
|
||||
self.assertIn("no action fields", snippet)
|
||||
self.assertLessEqual(len(snippet), 400)
|
||||
|
||||
def test_result_public_redacts(self):
|
||||
from providers.typesafe.protocol.flow import TypesafeResult
|
||||
|
||||
r = TypesafeResult(
|
||||
ok=True,
|
||||
email="e@x.com",
|
||||
api_key="sk-live-abcdefghijklmnopqrstuvwxyz",
|
||||
api_key_id="key-1",
|
||||
)
|
||||
blob = json.dumps(r.to_public_dict())
|
||||
self.assertNotIn("sk-live-abcdefghijklmnopqrstuvwxyz", blob)
|
||||
|
||||
|
||||
class TestTypesafeAdapterAttribution(unittest.TestCase):
|
||||
def test_success_from_this_run_only(self):
|
||||
email = FakeEmail()
|
||||
provider = TypesafeProvider(proxy="")
|
||||
from providers.typesafe.protocol.flow import TypesafeResult
|
||||
|
||||
fake_ok = TypesafeResult(
|
||||
ok=True,
|
||||
email="newuser@example.com",
|
||||
api_key="this-run-api-key-should-win",
|
||||
api_key_id="kid-1",
|
||||
user_id="u1",
|
||||
organization_id="org-1",
|
||||
steps={"login_action": {}, "api_key": {}},
|
||||
)
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
out = Path(td)
|
||||
with patch(
|
||||
"register_core.providers.typesafe_adapter.OUTPUT_DIR", out
|
||||
), patch(
|
||||
"providers.typesafe.protocol.flow.register_one",
|
||||
return_value=fake_ok,
|
||||
):
|
||||
(out / "accounts.jsonl").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"ok": True,
|
||||
"email": "old@example.com",
|
||||
"api_key": "old-api-key-should-not-win",
|
||||
}
|
||||
)
|
||||
+ "\n",
|
||||
encoding="utf-8",
|
||||
)
|
||||
result = provider.register_one(
|
||||
email_source=email, extra={"skip_console_probe": True}
|
||||
)
|
||||
ledger = (out / "accounts.jsonl").read_text(encoding="utf-8")
|
||||
auth_files = list(out.glob("typesafe-*.json"))
|
||||
self.assertEqual(len(auth_files), 1)
|
||||
written = json.loads(auth_files[0].read_text(encoding="utf-8"))
|
||||
self.assertEqual(written["api_key"], "this-run-api-key-should-win")
|
||||
# Historical ledger is left untouched; this-run json is the deliverable.
|
||||
self.assertNotIn("this-run-api-key-should-win", ledger)
|
||||
self.assertEqual(ledger.count("old-api-key-should-not-win"), 1)
|
||||
|
||||
self.assertTrue(result.ok)
|
||||
self.assertEqual(result.email, "newuser@example.com")
|
||||
self.assertEqual(result.secret, "this-run-api-key-should-win")
|
||||
self.assertEqual(result.secret_kind, "api_key")
|
||||
self.assertNotEqual(result.secret, "old-api-key-should-not-win")
|
||||
pub = result.to_public_dict()
|
||||
self.assertNotIn("this-run-api-key-should-win", json.dumps(pub))
|
||||
self.assertEqual(email.released, [("newuser@example.com", True)])
|
||||
|
||||
def test_magic_link_provider_uses_typesafe_sender_hint(self):
|
||||
email = FakeEmail()
|
||||
provider = TypesafeProvider(proxy="")
|
||||
captured: list[str] = []
|
||||
|
||||
def fake_register_one(**kwargs: Any):
|
||||
fn = kwargs.get("magic_link_provider")
|
||||
assert callable(fn)
|
||||
captured.append(fn())
|
||||
from providers.typesafe.protocol.flow import TypesafeResult
|
||||
|
||||
return TypesafeResult(
|
||||
ok=True,
|
||||
email="newuser@example.com",
|
||||
api_key="this-run-api-key-should-win",
|
||||
api_key_id="kid-1",
|
||||
)
|
||||
|
||||
with tempfile.TemporaryDirectory() as td, patch(
|
||||
"register_core.providers.typesafe_adapter.OUTPUT_DIR", Path(td)
|
||||
), patch(
|
||||
"providers.typesafe.protocol.flow.register_one",
|
||||
side_effect=fake_register_one,
|
||||
):
|
||||
result = provider.register_one(
|
||||
email_source=email, extra={"skip_console_probe": True}
|
||||
)
|
||||
self.assertTrue(result.ok)
|
||||
self.assertEqual(captured, [MAGIC_LINK])
|
||||
self.assertEqual(email.poll_kwargs[0].get("sender_hint"), "typesafe")
|
||||
|
||||
def test_missing_api_key_is_failure(self):
|
||||
email = FakeEmail()
|
||||
provider = TypesafeProvider(proxy="")
|
||||
from providers.typesafe.protocol.flow import TypesafeResult
|
||||
|
||||
fake = TypesafeResult(ok=True, email="newuser@example.com", api_key="")
|
||||
with patch(
|
||||
"providers.typesafe.protocol.flow.register_one", return_value=fake
|
||||
):
|
||||
result = provider.register_one(
|
||||
email_source=email, extra={"skip_console_probe": True}
|
||||
)
|
||||
self.assertFalse(result.ok)
|
||||
self.assertEqual(result.error_kind, "token")
|
||||
self.assertEqual(result.artifacts.get("fail_step"), "api_key")
|
||||
self.assertEqual(email.released[-1][1], False)
|
||||
|
||||
def test_mail_miss_returns_result_with_email(self):
|
||||
email = FakeEmail(fail_otp=True)
|
||||
provider = TypesafeProvider(proxy="")
|
||||
from providers.typesafe.protocol.flow import TypesafeRegisterError
|
||||
|
||||
with patch(
|
||||
"providers.typesafe.protocol.flow.register_one",
|
||||
side_effect=TypesafeRegisterError("wait:x", kind="mail_miss"),
|
||||
):
|
||||
result = provider.register_one(
|
||||
email_source=email, extra={"skip_console_probe": True}
|
||||
)
|
||||
self.assertFalse(result.ok)
|
||||
self.assertEqual(result.error_kind, "mail_miss")
|
||||
self.assertEqual(result.email, "newuser@example.com")
|
||||
self.assertEqual(email.released[-1][1], False)
|
||||
# No MailMissError on the chain: do not borrow a neighbor's diag.
|
||||
self.assertEqual(
|
||||
(result.artifacts.get("otp_wait") or {}).get("notes"),
|
||||
"diagnostics_unavailable",
|
||||
)
|
||||
|
||||
def test_mail_miss_keeps_this_attempt_diagnostics(self):
|
||||
from register_core.contracts import OtpWaitDiagnostics
|
||||
from providers.typesafe.protocol.flow import TypesafeRegisterError
|
||||
|
||||
email = FakeEmail()
|
||||
email.last_wait_diagnostics = OtpWaitDiagnostics(
|
||||
elapsed_seconds=19.48,
|
||||
poll_count=7,
|
||||
message_scan_count=1,
|
||||
failure_class="no_mail",
|
||||
)
|
||||
own = OtpWaitDiagnostics(
|
||||
elapsed_seconds=4.1,
|
||||
poll_count=2,
|
||||
message_scan_count=1,
|
||||
failure_class="parse_fail",
|
||||
)
|
||||
provider = TypesafeProvider(proxy="")
|
||||
|
||||
def raise_with_cause(*_a: Any, **_k: Any):
|
||||
err = TypesafeRegisterError(
|
||||
"magic link missing or malformed",
|
||||
kind="mail_miss",
|
||||
step="wait_magic_link",
|
||||
)
|
||||
err.__cause__ = MailMissError("malformed", diagnostics=own)
|
||||
raise err
|
||||
|
||||
with patch(
|
||||
"providers.typesafe.protocol.flow.register_one",
|
||||
side_effect=raise_with_cause,
|
||||
):
|
||||
result = provider.register_one(
|
||||
email_source=email, extra={"skip_console_probe": True}
|
||||
)
|
||||
wait = result.artifacts.get("otp_wait") or {}
|
||||
self.assertEqual(wait.get("elapsed_seconds"), 4.1)
|
||||
self.assertEqual(wait.get("failure_class"), "parse_fail")
|
||||
self.assertNotEqual(wait.get("elapsed_seconds"), 19.48)
|
||||
|
||||
def test_console_probe_failure_does_not_allocate(self):
|
||||
email = FakeEmail()
|
||||
provider = TypesafeProvider(proxy="")
|
||||
from providers.typesafe.protocol.flow import TypesafeRegisterError
|
||||
|
||||
with patch(
|
||||
"providers.typesafe.protocol.flow.probe_console",
|
||||
side_effect=TypesafeRegisterError("console down", kind="network", step="console_probe"),
|
||||
), patch(
|
||||
"providers.typesafe.protocol.session.create_session",
|
||||
return_value=object(),
|
||||
):
|
||||
result = provider.register_one(email_source=email)
|
||||
self.assertFalse(result.ok)
|
||||
self.assertEqual(result.error_kind, "network")
|
||||
self.assertEqual(result.artifacts.get("fail_step"), "console_probe")
|
||||
self.assertEqual(email.allocated, 0)
|
||||
self.assertEqual(email.released, [])
|
||||
self.assertEqual((result.artifacts.get("console_probe") or {}).get("ok"), False)
|
||||
|
||||
def test_probe_http_5xx_is_network_4xx_is_session(self):
|
||||
from providers.typesafe.protocol.flow import TypesafeRegisterError, probe_console
|
||||
|
||||
class Resp:
|
||||
def __init__(self, status: int, text: str = "<html>err</html>") -> None:
|
||||
self.status_code = status
|
||||
self.text = text
|
||||
self.headers = {}
|
||||
|
||||
with patch(
|
||||
"providers.typesafe.protocol.flow._get",
|
||||
return_value=(Resp(502), ""),
|
||||
):
|
||||
with self.assertRaises(TypesafeRegisterError) as ctx:
|
||||
probe_console(session=object())
|
||||
self.assertEqual(ctx.exception.kind, "network")
|
||||
self.assertEqual(ctx.exception.step, "console_probe")
|
||||
|
||||
with patch(
|
||||
"providers.typesafe.protocol.flow._get",
|
||||
return_value=(Resp(403, LOGIN_HTML), ""),
|
||||
):
|
||||
with self.assertRaises(TypesafeRegisterError) as ctx403:
|
||||
probe_console(session=object())
|
||||
self.assertEqual(ctx403.exception.kind, "session")
|
||||
|
||||
def test_register_one_reuses_probe_action(self):
|
||||
from providers.typesafe.protocol.flow import TypesafeResult, register_one
|
||||
|
||||
action = {
|
||||
"action_id": "act-abc",
|
||||
"index": "3",
|
||||
"blob": "encrypted-blob-xyz",
|
||||
"deployment_id": "ffffffffffffffffffffffffffffffffffffffff",
|
||||
"deployment_mismatch": True,
|
||||
}
|
||||
captured: dict[str, Any] = {}
|
||||
|
||||
def fake_send(session, email, *, action=None, log=None):
|
||||
captured["action"] = dict(action or {})
|
||||
return {"x_action_redirect": "/login?sent=true"}
|
||||
|
||||
with patch(
|
||||
"providers.typesafe.protocol.flow.login_action",
|
||||
side_effect=AssertionError("must reuse probe action"),
|
||||
), patch(
|
||||
"providers.typesafe.protocol.flow.send_magic_link",
|
||||
side_effect=fake_send,
|
||||
), patch(
|
||||
"providers.typesafe.protocol.flow.auth_callback",
|
||||
return_value={"userId": "u1", "org_memberships": [{"org": {"id": "o1", "name": "n"}}]},
|
||||
), patch(
|
||||
"providers.typesafe.protocol.flow.create_api_key",
|
||||
return_value={"api_key": "this-run-api-key-should-win", "id": "kid-1"},
|
||||
):
|
||||
result = register_one(
|
||||
email="newuser@example.com",
|
||||
magic_link_provider=lambda: MAGIC_LINK,
|
||||
session=object(),
|
||||
action=action,
|
||||
)
|
||||
self.assertTrue(result.ok)
|
||||
self.assertEqual(captured["action"]["action_id"], "act-abc")
|
||||
self.assertTrue(result.steps["login_action"]["reused_probe"])
|
||||
self.assertTrue(result.deployment_mismatch)
|
||||
|
||||
def test_mail_miss_from_provider_stays_mail_miss(self):
|
||||
from providers.typesafe.protocol.flow import TypesafeRegisterError, register_one
|
||||
|
||||
action = {"action_id": "act-abc", "index": "3", "blob": "blob"}
|
||||
|
||||
def boom() -> str:
|
||||
raise MailMissError("magic link timeout test")
|
||||
|
||||
with patch(
|
||||
"providers.typesafe.protocol.flow.login_action",
|
||||
side_effect=AssertionError("reuse"),
|
||||
), patch(
|
||||
"providers.typesafe.protocol.flow.send_magic_link",
|
||||
return_value={"x_action_redirect": "/login?sent=true"},
|
||||
):
|
||||
with self.assertRaises(TypesafeRegisterError) as ctx:
|
||||
register_one(
|
||||
email="newuser@example.com",
|
||||
magic_link_provider=boom,
|
||||
session=object(),
|
||||
action=action,
|
||||
)
|
||||
self.assertEqual(ctx.exception.kind, "mail_miss")
|
||||
self.assertEqual(ctx.exception.step, "wait_magic_link")
|
||||
self.assertIsInstance(ctx.exception.__cause__, MailMissError)
|
||||
|
||||
def test_adapter_forwards_probe_action(self):
|
||||
email = FakeEmail()
|
||||
provider = TypesafeProvider(proxy="")
|
||||
seen: dict[str, Any] = {}
|
||||
|
||||
def fake_probe(**kwargs: Any):
|
||||
return {
|
||||
"ok": True,
|
||||
"status": 200,
|
||||
"index": "3",
|
||||
"deployment_id": "dpl",
|
||||
"action": {"action_id": "act-abc", "index": "3", "blob": "blob"},
|
||||
}
|
||||
|
||||
def fake_register_one(**kwargs: Any):
|
||||
seen["action"] = kwargs.get("action")
|
||||
from providers.typesafe.protocol.flow import TypesafeResult
|
||||
|
||||
return TypesafeResult(
|
||||
ok=True,
|
||||
email="newuser@example.com",
|
||||
api_key="this-run-api-key-should-win",
|
||||
api_key_id="kid-1",
|
||||
)
|
||||
|
||||
with tempfile.TemporaryDirectory() as td, patch(
|
||||
"register_core.providers.typesafe_adapter.OUTPUT_DIR", Path(td)
|
||||
), patch(
|
||||
"providers.typesafe.protocol.flow.probe_console",
|
||||
side_effect=fake_probe,
|
||||
), patch(
|
||||
"providers.typesafe.protocol.session.create_session",
|
||||
return_value=object(),
|
||||
), patch(
|
||||
"providers.typesafe.protocol.flow.register_one",
|
||||
side_effect=fake_register_one,
|
||||
):
|
||||
result = provider.register_one(email_source=email)
|
||||
self.assertTrue(result.ok)
|
||||
self.assertEqual((seen.get("action") or {}).get("action_id"), "act-abc")
|
||||
self.assertEqual(email.allocated, 1)
|
||||
|
||||
def test_pipeline_in_process_accepts_email_source(self):
|
||||
from register_core.contracts import RegisterJob
|
||||
|
||||
job = RegisterJob(provider="typesafe", email_source="tinyhost", verify=False)
|
||||
pipe = Pipeline.from_job(job)
|
||||
self.assertEqual(pipe.provider.name, "typesafe")
|
||||
self.assertIsNotNone(pipe.email_source)
|
||||
|
||||
def test_fail_fast_empty_allocate(self):
|
||||
class EmptyMail:
|
||||
name = "empty"
|
||||
|
||||
def allocate(self) -> Mailbox:
|
||||
return Mailbox(address="", provider=self.name)
|
||||
|
||||
def poll_otp(self, mailbox, **kwargs):
|
||||
raise AssertionError("no")
|
||||
|
||||
def release(self, mailbox, *, success):
|
||||
return None
|
||||
|
||||
with self.assertRaises(FailFastError):
|
||||
TypesafeProvider(proxy="").register_one(
|
||||
email_source=EmptyMail(), extra={"skip_console_probe": True}
|
||||
)
|
||||
|
||||
def test_pipeline_uses_this_run_result(self):
|
||||
email = FakeEmail()
|
||||
provider = TypesafeProvider(proxy="")
|
||||
from providers.typesafe.protocol.flow import TypesafeResult
|
||||
|
||||
fake_ok = TypesafeResult(
|
||||
ok=True,
|
||||
email="newuser@example.com",
|
||||
api_key="pipeline-this-run-key-xx",
|
||||
api_key_id="kid",
|
||||
)
|
||||
|
||||
def _noop_preflight(extra, **_kw):
|
||||
base = dict(extra or {})
|
||||
base["_nodes_preflight_done"] = True
|
||||
base["_nodes_preflight"] = {"skipped": True, "reason": "test"}
|
||||
return base
|
||||
|
||||
def _noop_inject(extra, **_kw):
|
||||
return dict(extra or {})
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
with (
|
||||
patch(
|
||||
"register_core.providers.typesafe_adapter.OUTPUT_DIR", Path(td)
|
||||
),
|
||||
patch(
|
||||
"providers.typesafe.protocol.flow.register_one",
|
||||
return_value=fake_ok,
|
||||
),
|
||||
patch(
|
||||
"register_core.util.proxy.preflight_nodes_for_register",
|
||||
side_effect=_noop_preflight,
|
||||
),
|
||||
patch(
|
||||
"register_core.util.proxy.inject_attempt_proxy",
|
||||
side_effect=_noop_inject,
|
||||
),
|
||||
):
|
||||
pipe = Pipeline(
|
||||
provider,
|
||||
email_source=email,
|
||||
verifier=TypesafeKeyVerifier(),
|
||||
fail_fast=True,
|
||||
)
|
||||
stats = pipe.run(
|
||||
1,
|
||||
extra={
|
||||
"egress": "direct",
|
||||
"nodes_preflight": False,
|
||||
"skip_console_probe": True,
|
||||
},
|
||||
)
|
||||
self.assertEqual(stats.ok, 1)
|
||||
self.assertEqual(stats.fail, 0)
|
||||
self.assertTrue(stats.results[0].ok)
|
||||
|
||||
def test_output_filenames_unique_same_second(self):
|
||||
email = FakeEmail()
|
||||
provider = TypesafeProvider(proxy="")
|
||||
from providers.typesafe.protocol.flow import TypesafeResult
|
||||
|
||||
fake_ok = TypesafeResult(
|
||||
ok=True,
|
||||
email="newuser@example.com",
|
||||
api_key="this-run-api-key-should-win",
|
||||
api_key_id="kid-1",
|
||||
)
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
out = Path(td)
|
||||
with patch(
|
||||
"register_core.providers.typesafe_adapter.OUTPUT_DIR", out
|
||||
), patch(
|
||||
"providers.typesafe.protocol.flow.register_one",
|
||||
return_value=fake_ok,
|
||||
):
|
||||
a = provider.register_one(
|
||||
email_source=email, extra={"skip_console_probe": True}
|
||||
)
|
||||
b = provider.register_one(
|
||||
email_source=email, extra={"skip_console_probe": True}
|
||||
)
|
||||
names = sorted(p.name for p in out.glob("typesafe-*.json"))
|
||||
self.assertTrue(a.ok and b.ok)
|
||||
self.assertEqual(len(names), 2)
|
||||
self.assertEqual(len(set(names)), 2)
|
||||
|
||||
def test_pipeline_batch_continues_on_mail_miss(self):
|
||||
email = FakeEmail()
|
||||
provider = TypesafeProvider(proxy="")
|
||||
from providers.typesafe.protocol.flow import TypesafeRegisterError, TypesafeResult
|
||||
|
||||
calls = {"n": 0}
|
||||
|
||||
def _reg(**_kw):
|
||||
calls["n"] += 1
|
||||
if calls["n"] == 1:
|
||||
raise TypesafeRegisterError("magic link timeout", kind="mail_miss")
|
||||
return TypesafeResult(
|
||||
ok=True,
|
||||
email="newuser@example.com",
|
||||
api_key="pipeline-this-run-key-xx",
|
||||
api_key_id="kid",
|
||||
)
|
||||
|
||||
def _noop_preflight(extra, **_kw):
|
||||
base = dict(extra or {})
|
||||
base["_nodes_preflight_done"] = True
|
||||
base["_nodes_preflight"] = {"skipped": True, "reason": "test"}
|
||||
return base
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
with (
|
||||
patch(
|
||||
"register_core.providers.typesafe_adapter.OUTPUT_DIR", Path(td)
|
||||
),
|
||||
patch(
|
||||
"providers.typesafe.protocol.flow.register_one",
|
||||
side_effect=_reg,
|
||||
),
|
||||
patch(
|
||||
"register_core.util.proxy.preflight_nodes_for_register",
|
||||
side_effect=_noop_preflight,
|
||||
),
|
||||
patch(
|
||||
"register_core.util.proxy.inject_attempt_proxy",
|
||||
side_effect=lambda extra, **_kw: dict(extra or {}),
|
||||
),
|
||||
):
|
||||
pipe = Pipeline(
|
||||
provider,
|
||||
email_source=email,
|
||||
verifier=TypesafeKeyVerifier(),
|
||||
fail_fast=False,
|
||||
)
|
||||
stats = pipe.run(
|
||||
2,
|
||||
extra={
|
||||
"egress": "direct",
|
||||
"nodes_preflight": False,
|
||||
"skip_console_probe": True,
|
||||
},
|
||||
)
|
||||
self.assertEqual(stats.ok, 1)
|
||||
self.assertEqual(stats.fail, 1)
|
||||
self.assertEqual(stats.stopped_reason, "")
|
||||
self.assertEqual(calls["n"], 2)
|
||||
|
||||
def test_pipeline_workers_cap_and_typesafe_only(self):
|
||||
ts = TypesafeProvider(proxy="")
|
||||
pipe = Pipeline(ts, fail_fast=True)
|
||||
self.assertEqual(pipe._worker_count({"threads": 8}, 100), 8)
|
||||
self.assertEqual(pipe._worker_count({"threads": 256}, 100), 32)
|
||||
self.assertEqual(pipe._worker_count({"threads": 8}, 3), 3)
|
||||
|
||||
class Grokish:
|
||||
name = "grok"
|
||||
|
||||
grok_pipe = Pipeline(Grokish(), fail_fast=True) # type: ignore[arg-type]
|
||||
self.assertEqual(grok_pipe._worker_count({"threads": 8}, 100), 1)
|
||||
|
||||
def test_pipeline_typesafe_parallel_runs_count(self):
|
||||
import threading
|
||||
|
||||
email = FakeEmail()
|
||||
provider = TypesafeProvider(proxy="")
|
||||
from providers.typesafe.protocol.flow import TypesafeResult
|
||||
|
||||
seen: list[int] = []
|
||||
lock = threading.Lock()
|
||||
|
||||
def _reg(**_kw):
|
||||
with lock:
|
||||
seen.append(threading.get_ident())
|
||||
return TypesafeResult(
|
||||
ok=True,
|
||||
email="newuser@example.com",
|
||||
api_key="pipeline-this-run-key-xx",
|
||||
api_key_id="kid",
|
||||
)
|
||||
|
||||
def _noop_preflight(extra, **_kw):
|
||||
base = dict(extra or {})
|
||||
base["_nodes_preflight_done"] = True
|
||||
base["_nodes_preflight"] = {"skipped": True, "reason": "test"}
|
||||
return base
|
||||
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
with (
|
||||
patch(
|
||||
"register_core.providers.typesafe_adapter.OUTPUT_DIR", Path(td)
|
||||
),
|
||||
patch(
|
||||
"providers.typesafe.protocol.flow.register_one",
|
||||
side_effect=_reg,
|
||||
),
|
||||
patch(
|
||||
"register_core.util.proxy.preflight_nodes_for_register",
|
||||
side_effect=_noop_preflight,
|
||||
),
|
||||
patch(
|
||||
"register_core.util.proxy.inject_attempt_proxy",
|
||||
side_effect=lambda extra, **_kw: dict(extra or {}),
|
||||
),
|
||||
):
|
||||
pipe = Pipeline(
|
||||
provider,
|
||||
email_source=email,
|
||||
verifier=TypesafeKeyVerifier(),
|
||||
fail_fast=False,
|
||||
)
|
||||
stats = pipe.run(
|
||||
4,
|
||||
extra={
|
||||
"egress": "direct",
|
||||
"nodes_preflight": False,
|
||||
"skip_console_probe": True,
|
||||
"threads": 4,
|
||||
},
|
||||
)
|
||||
self.assertEqual(stats.ok, 4)
|
||||
self.assertEqual(stats.fail, 0)
|
||||
self.assertEqual(len(seen), 4)
|
||||
self.assertEqual(email.allocated, 4)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user