"""Provider-free HTTP + real worker/process integration. Build the solution first. Never uses installed providers.""" import argparse import datetime as dt import getpass import http.cookiejar from http.cookies import SimpleCookie import json import os from pathlib import Path import socket import shutil import signal import subprocess import tempfile import time import unittest import urllib.error import urllib.request from urllib.parse import urlsplit ROOT = Path(__file__).resolve().parents[1] KEY = "synthetic-dashboard-key-for-local-tests-only-123456" WORKER_KEY = "synthetic-worker-key-for-local-tests-only-abcdef" def wait_for(check, timeout=30): end = time.monotonic() + timeout while time.monotonic() < end: value = check() if value: return value time.sleep(.1) raise AssertionError("Timed out waiting for synthetic integration condition") class Fixture: def __init__(self, port=None, public_origin=None, start_worker=True): self.temp = tempfile.TemporaryDirectory(prefix="finaltoken-web-test-") self.path = Path(self.temp.name) self.processes = [] if port is None: with socket.socket() as sock: sock.bind(("127.0.0.1", 0)) port = sock.getsockname()[1] self.url = f"http://127.0.0.1:{port}" self.ready_host = urlsplit(public_origin or self.url).netloc self.jar = http.cookiejar.CookieJar() self.browser = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.jar)) self.csrf = None self.now = dt.datetime.now(dt.timezone.utc) self.claude = self.path / "claude" self.codex = self.path / "codex" self.claude.mkdir() self.codex.mkdir() # Windows locks loaded assemblies. Run fixture-owned copies so builds can continue during visual QA. for project in ("FinalToken.Web", "FinalToken.Worker", "FinalToken.FakeCli"): shutil.copytree(ROOT / "artifacts/bin" / project / "Release/net10.0", self.path / project) self.json(self.path / "server.json", { "accounts": [{"id": "claude", "provider": "Claude", "label": "Personal Claude", "expectedEmail": "fixture@example.test"}, {"id": "codex", "provider": "Codex", "label": "Personal Codex", "expectedEmail": "fixture@example.test"}], "machines": [{"id": "a", "label": "Synthetic workstation", "osUser": getpass.getuser(), "profiles": [{"id": "main", "accountId": "claude"}, {"id": "code", "accountId": "codex"}]}]}) fake = self.path / "FinalToken.FakeCli" / ("FinalToken.FakeCli.exe" if os.name == "nt" else "FinalToken.FakeCli") if not fake.exists(): raise RuntimeError("Build FinalToken.slnx in Release before running this check") self.json(self.path / "worker.json", {"machineId": "a", "serverUrl": self.url, "stateDirectory": str(self.path / "worker-state"), "profiles": [ {"id": "main", "provider": "Claude", "expectedEmail": "fixture@example.test", "configDirectory": str(self.claude), "dataDirectory": str(self.path / "claude-data"), "cliPath": str(fake)}, {"id": "code", "provider": "Codex", "expectedEmail": "fixture@example.test", "configDirectory": str(self.codex), "dataDirectory": str(self.path / "codex-data"), "cliPath": str(fake)}]}) # Handwritten transcript/rollout metadata. No real messages or credentials. projects = self.claude / "projects" / "fixture" projects.mkdir(parents=True) transcript = {"type": "assistant", "timestamp": self.now.isoformat(), "requestId": "req-fixture", "message": {"id": "msg-fixture", "model": "claude-opus-4-6", "usage": {"input_tokens": 100, "output_tokens": 20}}} (projects / "fixture.jsonl").write_text(json.dumps(transcript) + "\n" + json.dumps(transcript) + "\n", encoding="utf-8") sessions = self.codex / "sessions" sessions.mkdir() rows = [{"type": "session_meta", "payload": {"id": "fixture-session"}}, {"type": "turn_context", "payload": {"model": "gpt-5.4"}}, {"type": "event_msg", "timestamp": self.now.isoformat(), "payload": {"type": "token_count", "info": {"total_token_usage": {"input_tokens": 100, "output_tokens": 20, "total_tokens": 120}}}}] (sessions / "rollout-fixture.jsonl").write_text("\n".join(map(json.dumps, rows)) + "\n", encoding="utf-8") env = os.environ.copy() env.update(FINALTOKEN_SERVER_CONFIG=str(self.path / "server.json"), FINALTOKEN_SERVER_DATA=str(self.path / "server-data"), FINALTOKEN_DASHBOARD_KEY=KEY, FINALTOKEN_MACHINE_a=WORKER_KEY, FINALTOKEN_PUBLIC_ORIGIN=public_origin or self.url, ASPNETCORE_URLS=self.url) self.spawn(["dotnet", str(self.path / "FinalToken.Web/FinalToken.Web.dll")], env, ROOT / "src/FinalToken.Web") wait_for(self.ready) worker_env = os.environ.copy() # Synthetic CLI must not inherit either real profile override from the host. worker_env.pop("CLAUDE_CONFIG_DIR", None) worker_env.pop("CODEX_HOME", None) worker_env["FINALTOKEN_WORKER_KEY"] = WORKER_KEY if start_worker: self.spawn(["dotnet", str(self.path / "FinalToken.Worker/finaltoken-worker.dll"), str(self.path / "worker.json")], worker_env, ROOT) @staticmethod def json(path, value): path.write_text(json.dumps(value), encoding="utf-8") def spawn(self, command, env, cwd): self.processes.append(subprocess.Popen(command, env=env, cwd=cwd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0, start_new_session=os.name != "nt")) def ready(self): try: return urllib.request.urlopen(urllib.request.Request(self.url, headers={"Host": self.ready_host}), timeout=1).status == 200 except (OSError, urllib.error.URLError): return False def call(self, path, body=None, opener=None, headers=None): h = {"Content-Type": "application/json", "X-FinalToken": "1"} if self.csrf: h["X-CSRF"] = self.csrf h.update(headers or {}) request = urllib.request.Request(self.url + path, data=None if body is None else json.dumps(body).encode(), headers=h) with (opener or self.browser).open(request, timeout=10) as response: data = response.read() return json.loads(data) if data else None def sign_in(self): self.csrf = self.call("/session", {"key": KEY})["csrf"] def online(self): return self.call("/api/dashboard")["machines"][0]["online"] def login_state(self, login, state): view = self.call("/api/logins/" + login["id"]) return view if view["state"] == state else None def authorize(self): self.sign_in() wait_for(self.online) login = self.call("/api/logins", {"machineId": "a", "profileId": "main"}) wait_for(lambda: self.login_state(login, "WaitingForCode")) self.call(f"/api/logins/{login['id']}/response", {"response": "fixture-code#fixture-state"}) wait_for(lambda: self.login_state(login, "Succeeded")) device = self.call("/api/logins", {"machineId": "a", "profileId": "code"}) wait_for(lambda: self.login_state(device, "WaitingForBrowser")) (self.codex / "authorize-device").touch() wait_for(lambda: self.login_state(device, "Succeeded")) return login, device def close(self): for process in reversed(self.processes): if process.poll() is None: if os.name == "nt": subprocess.run(["taskkill", "/PID", str(process.pid), "/T", "/F"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False) else: os.killpg(process.pid, signal.SIGTERM) process.wait(timeout=10) self.temp.cleanup() class IPAccessIntegration(unittest.TestCase): @classmethod def setUpClass(cls): cls.fixture = Fixture(public_origin="https://usage.example.com", start_worker=False) @classmethod def tearDownClass(cls): cls.fixture.close() def request(self, path, body=None, origin=None, cookie=None, csrf=None): f = self.fixture authority = "10.0.30.150:" + str(urlsplit(f.url).port) headers = {"Host": authority, "X-FinalToken": "1", "Content-Type": "application/json"} if origin: headers["Origin"] = origin if cookie: headers["Cookie"] = cookie if csrf: headers["X-CSRF"] = csrf request = urllib.request.Request(f.url + path, headers=headers, data=None if body is None else json.dumps(body).encode()) return urllib.request.urlopen(request, timeout=10) def test_ip_page_and_http_login_ignore_the_legacy_fixed_hostname(self): with self.request("/") as response: self.assertEqual(200, response.status) authority = "10.0.30.150:" + str(urlsplit(self.fixture.url).port) with self.request("/session", {"key": KEY}, origin="http://" + authority) as response: cookies = SimpleCookie(response.headers["Set-Cookie"]) csrf = json.load(response)["csrf"] self.assertFalse(cookies["finaltoken"]["secure"]) self.assertTrue(cookies["finaltoken"]["httponly"]) self.assertEqual("strict", cookies["finaltoken"]["samesite"].lower()) cookie = "finaltoken=" + cookies["finaltoken"].value with self.request("/api/dashboard", cookie=cookie) as response: self.assertEqual(200, response.status) with self.assertRaises(urllib.error.HTTPError) as error: self.request("/api/dashboard") self.assertEqual(401, error.exception.code) with self.assertRaises(urllib.error.HTTPError) as error: self.request("/api/logout", {}, origin="http://" + authority, cookie=cookie, csrf="wrong") self.assertEqual(403, error.exception.code) with self.assertRaises(urllib.error.HTTPError) as error: self.request("/api/logout", {}, origin="http://evil.test", cookie=cookie, csrf=csrf) self.assertEqual(403, error.exception.code) with self.request("/api/logout", {}, origin="http://" + authority, cookie=cookie, csrf=csrf) as response: self.assertEqual(204, response.status) def test_https_browser_origin_retains_secure_cookie_behind_a_proxy(self): authority = "10.0.30.150:" + str(urlsplit(self.fixture.url).port) with self.request("/session", {"key": KEY}, origin="https://" + authority) as response: cookie = SimpleCookie(response.headers["Set-Cookie"]) self.assertTrue(cookie["finaltoken"]["secure"]) class WebIntegration(unittest.TestCase): @classmethod def setUpClass(cls): cls.fixture = Fixture() @classmethod def tearDownClass(cls): cls.fixture.close() def test_end_to_end(self): f = self.fixture anonymous = urllib.request.build_opener() with self.assertRaises(urllib.error.HTTPError) as error: f.call("/api/dashboard", opener=anonymous) self.assertEqual(401, error.exception.code) f.sign_in() with self.assertRaises(urllib.error.HTTPError) as error: f.call("/api/logins", {"machineId": "a", "profileId": "main"}, headers={"X-CSRF": "wrong"}) self.assertEqual(403, error.exception.code) with self.assertRaises(urllib.error.HTTPError) as error: f.call("/api/logins", {}, headers={"Origin": "https://evil.test"}) self.assertEqual(403, error.exception.code) with self.assertRaises(urllib.error.HTTPError) as error: f.call("/worker/report", {}, opener=anonymous) self.assertEqual(401, error.exception.code) login, device = f.authorize() self.assertEqual("fixture@example.test", f.login_state(login, "Succeeded")["email"]) self.assertIsNone(f.login_state(login, "Succeeded")["url"]) wait_for(lambda: all(a["total"]["total"] == 120 for a in f.call("/api/dashboard")["accounts"])) dashboard = f.call("/api/dashboard") codex = next(a for a in dashboard["accounts"] if a["account"]["id"] == "codex") self.assertEqual(65, codex["windows"][0]["window"]["usedPercent"]) self.assertGreater(codex["windows"][0]["useAtReset"], 100) other = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar())) f.call("/session", {"key": KEY}, opener=other) with self.assertRaises(urllib.error.HTTPError) as error: f.call("/api/logins/" + login["id"], opener=other) self.assertEqual(404, error.exception.code) for path in (f.path / "server-data").rglob("*"): if path.is_file() and path.suffix == ".json": data = path.read_bytes() self.assertNotIn(b"fixture-code", data) self.assertNotIn(b"fixture-state", data) self.assertNotIn(b"ABCD-12345", data) # Real child process cancellation, then wrong-account verification. (f.codex / "authorize-device").unlink() cancel = f.call("/api/logins", {"machineId": "a", "profileId": "code"}) wait_for(lambda: f.login_state(cancel, "WaitingForBrowser")) f.call(f"/api/logins/{cancel['id']}/cancel", {}) wait_for(lambda: f.login_state(cancel, "Cancelled")) mismatch = f.call("/api/logins", {"machineId": "a", "profileId": "main"}) wait_for(lambda: f.login_state(mismatch, "WaitingForCode")) f.call(f"/api/logins/{mismatch['id']}/response", {"response": "wrong-code#fixture-state"}) wait_for(lambda: f.login_state(mismatch, "AccountMismatch")) (f.claude / "overflow-login").touch() overflow = f.call("/api/logins", {"machineId": "a", "profileId": "main"}) wait_for(lambda: f.login_state(overflow, "Failed"), timeout=15) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--serve-fixture", action="store_true", help="Keep synthetic server/worker running for local visual QA") args = parser.parse_args() if args.serve_fixture: fixture = Fixture(port=5187) try: fixture.authorize() print("Synthetic dashboard ready at " + fixture.url, flush=True) print("Access key: " + KEY, flush=True) while True: time.sleep(1) except KeyboardInterrupt: pass finally: fixture.close() else: unittest.main(argv=[__file__])