183 lines
8.4 KiB
Python
183 lines
8.4 KiB
Python
"""A guest computer's own-login run never inherits the hub's proxy pair — not
|
|
from the process env, not from a settings file (which outranks it): Akira's
|
|
computer billed the host for 21 runs routed to his own Pro that way."""
|
|
|
|
import json
|
|
|
|
import claude_accounts as acct # harness-claude's: ownLogin
|
|
import claude_env as ca
|
|
import claude_proxy
|
|
import config
|
|
import link
|
|
import proxy_pair as pp
|
|
|
|
|
|
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 (ca, claude_env, acct):
|
|
if name in vars(m):
|
|
mp.setattr(m, name, value)
|
|
|
|
HUB = "https://ai-agent.example.xyz"
|
|
PAIR = {"ANTHROPIC_BASE_URL": f"{HUB}/proxy/claude/personal",
|
|
"CLAUDE_CODE_OAUTH_TOKEN": "p" * 43}
|
|
|
|
|
|
def _computer(tmp_path, monkeypatch):
|
|
home = tmp_path / ".claude"
|
|
(home / "projects").mkdir(parents=True)
|
|
start = tmp_path / "PROJETS"
|
|
start.mkdir()
|
|
for mod in (ca, config):
|
|
monkeypatch.setattr(mod, "IS_WORKER", True) if "IS_WORKER" in vars(mod) else None
|
|
_set(monkeypatch, "CLAUDE_PROJECTS", home / "projects")
|
|
monkeypatch.setattr(claude_proxy, "CLAUDE_PROJECTS", home / "projects")
|
|
_set(monkeypatch, "DEFAULT_CWD", str(start))
|
|
for m in (ca, acct):
|
|
for c in ("_machine_login_cache", "_override_cache", "_own_credentials_cache"):
|
|
if c in vars(m):
|
|
monkeypatch.setattr(m, c, None)
|
|
monkeypatch.setattr(pp, "MANAGED", tmp_path / "managed-settings.json")
|
|
monkeypatch.setattr(link, "config", lambda: {"hub": HUB, "linkToken": "t"})
|
|
monkeypatch.setattr(claude_proxy, "config", lambda: {
|
|
"url": f"{HUB}/proxy/claude", "token": PAIR["CLAUDE_CODE_OAUTH_TOKEN"],
|
|
"accounts": ["personal"]})
|
|
for k in (*PAIR, "ANTHROPIC_AUTH_TOKEN"):
|
|
monkeypatch.delenv(k, raising=False)
|
|
return home, start
|
|
|
|
|
|
def _settings(args):
|
|
value = args[args.index("--settings") + 1]
|
|
# a flag carrying a credential names a 0600 file (claude_proxy.secrets_out_of_argv)
|
|
return json.loads(value if value.lstrip().startswith("{") else open(value).read())
|
|
|
|
|
|
def test_settings_json_pair_is_unset_for_an_own_login_run(tmp_path, monkeypatch):
|
|
home, start = _computer(tmp_path, monkeypatch)
|
|
(home / "settings.json").write_text(json.dumps({"env": {**PAIR, "FOO": "1"}}))
|
|
args = ["-p", "hi", "--settings", json.dumps({"permissions": {"allow": []}})]
|
|
out = claude_proxy.with_settings_env(args, "guest-akira", str(start))
|
|
s = _settings(out)
|
|
assert s["env"] == {"ANTHROPIC_BASE_URL": "", "CLAUDE_CODE_OAUTH_TOKEN": ""}
|
|
assert s["permissions"] == {"allow": []} # the rest kept
|
|
# a proxied run still gets the pair, a lab account nothing
|
|
assert _settings(claude_proxy.with_settings_env(args, "personal", str(start)))["env"][
|
|
"CLAUDE_CODE_OAUTH_TOKEN"] == PAIR["CLAUDE_CODE_OAUTH_TOKEN"]
|
|
status = acct.machine_login_status()
|
|
assert status["override"] == [{"source": "user", "path": str(home / "settings.json"),
|
|
"keys": ["ANTHROPIC_BASE_URL", "CLAUDE_CODE_OAUTH_TOKEN"]}]
|
|
|
|
|
|
def test_project_settings_and_no_settings_flag(tmp_path, monkeypatch):
|
|
home, start = _computer(tmp_path, monkeypatch)
|
|
(start / "app" / ".claude").mkdir(parents=True)
|
|
(start / ".claude").mkdir()
|
|
(start / ".claude" / "settings.local.json").write_text(json.dumps({"env": PAIR}))
|
|
out = claude_proxy.with_settings_env(["-p", "hi"], "guest-akira", str(start / "app"))
|
|
assert out[:2] == ["--settings", json.dumps(
|
|
{"env": {"ANTHROPIC_BASE_URL": "", "CLAUDE_CODE_OAUTH_TOKEN": ""}},
|
|
separators=(",", ":"))]
|
|
|
|
|
|
def test_process_env_pair_is_stripped(tmp_path, monkeypatch):
|
|
_computer(tmp_path, monkeypatch)
|
|
for k, v in PAIR.items():
|
|
monkeypatch.setenv(k, v)
|
|
env = ca._account_env("guest-akira")
|
|
assert not any(k in env for k in PAIR)
|
|
monkeypatch.setattr(pp, "origin", lambda ppid, keys: {"startedBy": "zsh",
|
|
"serviceManager": False})
|
|
got = acct.machine_login_status()["override"]
|
|
assert got == [{"source": "env", "path": None, "keys": list(PAIR),
|
|
"startedBy": "zsh", "serviceManager": False}]
|
|
# nothing in any file: the args are left as they were
|
|
assert claude_proxy.with_settings_env(["-p", "x"], "guest-akira", None) == ["-p", "x"]
|
|
|
|
|
|
def test_their_own_setup_untouched(tmp_path, monkeypatch):
|
|
home, start = _computer(tmp_path, monkeypatch)
|
|
# their own long-lived token, their own gateway: not the hub's pair
|
|
(home / "settings.json").write_text(json.dumps({"env": {
|
|
"CLAUDE_CODE_OAUTH_TOKEN": "sk-ant-oat01-theirs",
|
|
"ANTHROPIC_BASE_URL": "https://gateway.example.com/v1"}}))
|
|
monkeypatch.setenv("CLAUDE_CODE_OAUTH_TOKEN", "sk-ant-oat01-theirs")
|
|
assert claude_proxy.with_settings_env(["-p", "x"], "guest-akira", str(start)) == ["-p", "x"]
|
|
assert ca._account_env("guest-akira")["CLAUDE_CODE_OAUTH_TOKEN"] == "sk-ant-oat01-theirs"
|
|
assert acct.machine_login_status()["override"] == []
|
|
|
|
|
|
def test_the_proxy_token_alone_and_another_hub_host(tmp_path, monkeypatch):
|
|
home, start = _computer(tmp_path, monkeypatch)
|
|
# the token without the URL still is ours; the path on a foreign host isn't
|
|
(home / "settings.json").write_text(json.dumps({"env": {
|
|
"CLAUDE_CODE_OAUTH_TOKEN": PAIR["CLAUDE_CODE_OAUTH_TOKEN"],
|
|
"ANTHROPIC_BASE_URL": "https://elsewhere.example/proxy/claude/x"}}))
|
|
out = claude_proxy.with_settings_env(["-p", "x"], "guest-akira", str(start))
|
|
assert _settings(out)["env"] == {"CLAUDE_CODE_OAUTH_TOKEN": ""}
|
|
|
|
|
|
def test_managed_is_reported_not_overridden(tmp_path, monkeypatch):
|
|
home, start = _computer(tmp_path, monkeypatch)
|
|
pp.MANAGED.write_text(json.dumps({"env": PAIR}))
|
|
assert claude_proxy.with_settings_env(["-p", "x"], "guest-akira", str(start)) == ["-p", "x"]
|
|
assert [h["source"] for h in acct.machine_login_status()["override"]] == ["managed"]
|
|
|
|
|
|
def test_with_env_leaves_a_settings_file_flag_alone():
|
|
assert pp.with_env(["--settings", "/tmp/s.json"], {"A": ""}) is None
|
|
assert pp.with_env(["--settings=/tmp/s.json"], {"A": ""}) is None
|
|
assert pp.with_env(["-p"], {}) == ["-p"]
|
|
|
|
|
|
def _launcher():
|
|
import importlib.util
|
|
import pathlib
|
|
path = pathlib.Path(__file__).resolve().parent.parent / "worker" / "claude_launcher.py"
|
|
spec = importlib.util.spec_from_file_location("claude_launcher", path)
|
|
mod = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(mod)
|
|
return mod
|
|
|
|
|
|
def test_my_own_claude_in_the_terminal_drops_the_pair(tmp_path, monkeypatch, capsys):
|
|
cl = _launcher()
|
|
home = tmp_path / ".claude"
|
|
home.mkdir()
|
|
(home / "settings.json").write_text(json.dumps({"env": PAIR}))
|
|
monkeypatch.setenv("CLAUDE_CONFIG_DIR", str(home))
|
|
monkeypatch.setattr(pp, "MANAGED", tmp_path / "managed.json")
|
|
monkeypatch.setattr(cl.terminal, "hub_status", lambda: {})
|
|
monkeypatch.setattr(cl.terminal, "state_dir", lambda: tmp_path / "state")
|
|
for k, v in PAIR.items():
|
|
monkeypatch.setenv(k, v)
|
|
cfg = {"url": f"{HUB}/proxy/claude", "token": PAIR["CLAUDE_CODE_OAUTH_TOKEN"],
|
|
"account": "personal"}
|
|
p = cl.parse(["hello"])
|
|
args, env, _sid = cl.build("local", p, cfg, str(tmp_path), False)
|
|
assert not any(k in env for k in PAIR)
|
|
assert _settings(args)["env"] == {"ANTHROPIC_BASE_URL": "", "CLAUDE_CODE_OAUTH_TOKEN": ""}
|
|
assert "sends Claude to ai-agent's proxy" in capsys.readouterr().err
|
|
# ai-agent Claude still gets the pair
|
|
args, env, _sid = cl.build("ai-agent", p, cfg, str(tmp_path), False)
|
|
assert env["ANTHROPIC_BASE_URL"] == f"{HUB}/proxy/claude/personal"
|
|
# …and where settings.json would outrank it, the flag carries the pair
|
|
# from a 0600 file: the token is never on claude's command line
|
|
import os
|
|
flag = args[args.index("--settings") + 1]
|
|
assert flag == str(tmp_path / "state" / "claude-pair.settings.json")
|
|
assert PAIR["CLAUDE_CODE_OAUTH_TOKEN"] not in " ".join(args)
|
|
assert os.stat(flag).st_mode & 0o777 == 0o600
|
|
assert json.loads(open(flag).read())["env"]["CLAUDE_CODE_OAUTH_TOKEN"] \
|
|
== PAIR["CLAUDE_CODE_OAUTH_TOKEN"]
|
|
|
|
|
|
def test_origin_names_the_parent(monkeypatch):
|
|
import os
|
|
got = pp.origin(os.getpid(), ["ANTHROPIC_BASE_URL"])
|
|
assert got["startedBy"] # this test process's own name
|
|
assert got["serviceManager"] in (True, False, None)
|