Files
ai-agent/sidecar/test_claude_proxy.py

201 lines
9.1 KiB
Python

"""The Claude proxy: a worker keeps the hub's config and turns a run on one of
its accounts into a proxied one; the host hands out an account's access
token, refreshing a stale one through the CLI once."""
import json
import os
import time
import pytest
from fastapi import FastAPI, HTTPException
from fastapi.testclient import TestClient
import claude_accounts
import claude_proxy
import config
def _set(mp, name, value):
"""A setting: the plugin reads ``config.<name>`` live, the core's
claude_env has its own copy — both see the test's value."""
import claude_env
mp.setattr(config, name, value)
for m in (claude_accounts, claude_env):
if name in vars(m):
mp.setattr(m, name, value)
TOKEN = "t" * 43
@pytest.fixture()
def worker(tmp_path, monkeypatch):
monkeypatch.setenv("WORKER_STATE_DIR", str(tmp_path / "state"))
monkeypatch.setattr(claude_proxy, "IS_WORKER", True)
monkeypatch.setattr(claude_proxy, "CLAUDE_PROJECTS", tmp_path / "dot-claude" / "projects")
claude_proxy._cache = None
def _auth(h):
if h != "Bearer hub":
raise HTTPException(401, "unauthorized")
app = FastAPI()
app.include_router(claude_proxy.make_router(_auth))
return TestClient(app)
def _push(client, accounts=("personal",), token=TOKEN, default=None):
return client.post("/claude-proxy", headers={"Authorization": "Bearer hub"},
json={"url": "https://ai-agent.lab.example/proxy/claude/",
"token": token, "accounts": list(accounts), "default": default})
def test_push_then_a_proxied_run(worker, monkeypatch):
assert not claude_proxy.proxied("personal")
r = _push(worker, ["work", "personal", "Bad!"])
assert r.status_code == 200
held = r.json()["claudeProxy"]
assert held["accounts"] == ["personal", "work"]
assert held["hash"] == claude_proxy.fingerprint(
"https://ai-agent.lab.example/proxy/claude", TOKEN, ["work", "personal"])
assert claude_proxy.proxied("work") and not claude_proxy.proxied("other")
_set(monkeypatch, "STRIP_API_KEY", False)
monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-should-go")
monkeypatch.setenv("CLAUDE_CODE_OAUTH_TOKEN", "the-macs-own")
env = claude_accounts._account_env("work")
assert env["ANTHROPIC_BASE_URL"] == "https://ai-agent.lab.example/proxy/claude/work"
assert env["CLAUDE_CODE_OAUTH_TOKEN"] == TOKEN
assert "ANTHROPIC_API_KEY" not in env
claude_accounts._require_login("work") # no login needed here
assert claude_accounts._valid_account("work") == "work"
def test_machine_default_in_settings_json(worker, tmp_path):
settings = tmp_path / "dot-claude" / "settings.json"
settings.parent.mkdir(parents=True)
settings.write_text(json.dumps({"model": "opus", "env": {
"ANTHROPIC_BASE_URL": "https://mine.example", "OTHER": "1"}}))
_push(worker, ["personal", "work"], default="work")
env = json.loads(settings.read_text())["env"]
assert env["ANTHROPIC_BASE_URL"] == "https://ai-agent.lab.example/proxy/claude/work"
assert env["CLAUDE_CODE_OAUTH_TOKEN"] == TOKEN and env["OTHER"] == "1"
# another default: rewritten, the user's own value still remembered
_push(worker, ["personal", "work"], default="personal")
assert json.loads(settings.read_text())["env"]["ANTHROPIC_BASE_URL"].endswith("/personal")
# a hub run on work: its pair rides --settings, which outranks the file
args = claude_proxy.with_settings_env(
["claude", "-p", "x", "--settings", '{"hooks":{}}', "--model", "opus"], "work")
# …in a 0600 file the flag names: the token is never on the command line
value = args[args.index("--settings") + 1]
assert TOKEN not in " ".join(args) and value.startswith(str(tmp_path / "run-settings"))
assert os.stat(value).st_mode & 0o777 == 0o600
assert os.stat(os.path.dirname(value)).st_mode & 0o777 == 0o700
flag = json.loads(open(value).read())
assert flag["env"]["ANTHROPIC_BASE_URL"].endswith("/work") and flag["hooks"] == {}
# the user's settings.json now holds the token too: theirs alone to read
assert os.stat(settings).st_mode & 0o777 == 0o600
assert claude_proxy.with_settings_env(["claude", "--settings", "{}"], "other") \
== ["claude", "--settings", "{}"]
# back to its own login: only our keys go, the user's value comes back
worker.delete("/claude-proxy", headers={"Authorization": "Bearer hub"})
assert json.loads(settings.read_text()) == {"model": "opus", "env": {
"ANTHROPIC_BASE_URL": "https://mine.example", "OTHER": "1"}}
def test_unpair_drops_the_settings_default(worker, tmp_path):
import pairing
settings = tmp_path / "dot-claude" / "settings.json"
_push(worker, ["personal"], default="personal")
assert "CLAUDE_CODE_OAUTH_TOKEN" in json.loads(settings.read_text())["env"]
pairing._drop_claude_proxy()
assert json.loads(settings.read_text()) == {}
assert not claude_proxy.proxied("personal")
def test_bad_pushes_and_unpaired(worker):
assert _push(worker, token="short").status_code == 400
assert worker.post("/claude-proxy", json={"url": "u", "token": TOKEN}).status_code == 401
_push(worker)
assert worker.delete("/claude-proxy", headers={"Authorization": "Bearer hub"}).json() \
== {"claudeProxy": {"hash": None, "accounts": []}}
assert not claude_proxy.proxied("personal")
def test_not_on_the_host(worker, monkeypatch):
monkeypatch.setattr(claude_proxy, "IS_WORKER", False)
assert _push(worker).status_code == 409
assert claude_proxy.public() is None
def test_access_token_refreshes_a_stale_one_through_the_cli(monkeypatch):
soon = (time.time() + 30) * 1000
later = (time.time() + 8 * 3600) * 1000
files = [{"accessToken": "old", "expiresAt": soon}]
probes = []
def probe(account):
probes.append(account)
files.append({"accessToken": "new", "expiresAt": later})
return {"ok": True}
monkeypatch.setattr(claude_accounts, "_oauth", lambda a: files[-1])
monkeypatch.setattr(claude_accounts, "_probe", probe)
claude_accounts._token_probed.clear()
assert claude_accounts._access_token("work")["accessToken"] == "new"
assert probes == ["work"]
# fresh now: no probe; a refused one probes again only after the pause
assert claude_accounts._access_token("work")["accessToken"] == "new"
assert claude_accounts._access_token("work", refresh=True)["accessToken"] == "new"
assert probes == ["work"]
def test_access_token_signed_out(monkeypatch):
monkeypatch.setattr(claude_accounts, "_oauth", lambda a: {})
monkeypatch.setattr(claude_accounts, "_probe",
lambda a: {"ok": False, "kind": "auth", "message": "expired"})
claude_accounts._token_probed.clear()
with pytest.raises(HTTPException) as e:
claude_accounts._access_token("personal")
assert e.value.status_code == 409 and e.value.detail["kind"] == "auth"
def test_a_credential_in_run_settings_leaves_the_command_line(tmp_path, monkeypatch):
"""A guest's tools token (claude_launch._scope_settings) on the lab, the proxy
token on a worker: `ps` must not show either."""
sid = "0199aaaa-bbbb-7ccc-8ddd-eeeeeeeeeeee"
secret = "aiat1.ana.1." + "x" * 30
flag = json.dumps({"hooks": {}, "env": {"AIA_TOOLS_URL": "https://h/proxy/tools",
"AIA_TOOLS_TOKEN": secret}})
args = ["claude", "-p", "hi", "--session-id", sid, "--settings", flag, "--model", "sonnet"]
out = claude_proxy.with_settings_env(args, "personal")
assert secret not in " ".join(out)
path = out[out.index("--settings") + 1]
assert os.path.basename(path).startswith(sid + "-")
assert json.loads(open(path).read()) == json.loads(flag)
assert os.stat(path).st_mode & 0o777 == 0o600
assert out[:5] == args[:5] and out[-2:] == ["--model", "sonnet"]
# nothing secret ⇒ the args are left exactly as they came
plain = ["claude", "--settings", json.dumps({"hooks": {}, "env": {"AIA_GUEST": "ana"}})]
assert claude_proxy.with_settings_env(plain, "personal") == plain
assert claude_proxy.secrets_out_of_argv(["claude", "--settings", "/a/file.json"]) \
== ["claude", "--settings", "/a/file.json"]
# an unwritable dir never costs the run
monkeypatch.setattr(claude_proxy, "RUN_SETTINGS_DIR", tmp_path / "f" / "x")
(tmp_path / "f").write_text("a file, not a dir")
assert claude_proxy.with_settings_env(args, "personal") == args
def test_run_settings_files_go_once_their_run_ended(tmp_path, monkeypatch):
import pids
live, dead = "0199aaaa-bbbb-7ccc-8ddd-000000000001", "0199aaaa-bbbb-7ccc-8ddd-000000000002"
d = tmp_path / "run-settings"
d.mkdir()
for name in (f"{live}-aaaa.json", f"{dead}-bbbb.json", "run-cccc.json", f"{dead}-new.json"):
(d / name).write_text("{}")
old = 1_000_000
for name in (f"{live}-aaaa.json", f"{dead}-bbbb.json", "run-cccc.json"):
os.utime(d / name, (old, old))
monkeypatch.setattr(pids, "_live_record", lambda sid: {"pid": 1} if sid == live else None)
claude_proxy._sweep_run_settings()
assert sorted(p.name for p in d.iterdir()) == [f"{live}-aaaa.json", f"{dead}-new.json"]