Strict plugin-only: no model / account / harness table left in core.
- plugins/providers: an unbound or never-seeded store reads the seed dir's
provider-*/harness-* manifests (PLUGINS_SEED_DIR, else the plugins
checkout, else backend/fixtures/typed_plugins) — once seeded, only what is
installed. Harness↔vendor helpers (vendors_of_harness, login_harness,
hosted_harnesses, accounts_for_harness, provider_config/secret).
- models/catalog + presets: list_models / is_local / context_window /
opencode_model / agy_model / pi_provider / key_of / vendor_of / guest pool
delegate to the registry; DEFAULT_MODEL, FAMILIES… computed (PEP 562).
openrouter.py reads the provider-openrouter plugin's catalogueUrl and its
api_key hub secret (OPENROUTER_API_KEY fallback).
- accounts: provider-owned; vendor-native helpers (accounts_for_vendor,
vendor_of_account, resolve_alias, wire_id) + compat for_harness /
valid_for / harness_of joined through harness.supports[]. Clean provider
accounts: keyless evox2 (alias opencode-lab, still sent to the sidecar as
opencode-lab), openrouter's own account — pi no longer bills `personal`.
- profiles: profile-level ★ per vendor (profile.accounts), per-machine
overrides on workers[i].accounts; idempotent migration of the harness-keyed
runner ★ on load (file version 3); default_login takes a vendor or a
harness; PUT|PATCH /api/profiles/{id} edits accounts. The API keeps
harness keys beside vendor keys in each runner's accounts/logins.
- runs/cron/scheduled: harness tuples → the registry (caps lean/fork,
runsOn lab, hosted harnesses); a new run routes model → vendor → the
profile's ★ for it.
- cli: --harness accepts any active harness (checked against
/api/providers); MCP drops its static enum.
- tests: golden-tables.json pins the old tables' answers; new
test_provider_accounts.py (migration, clean accounts, routing by vendor).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
200 lines
10 KiB
Python
200 lines
10 KiB
Python
"""The Claude proxy (claudeproxy/): a worker's request is let through only with
|
|
its own token, for its own accounts, on an API path; the token is swapped for
|
|
the lab login's, a refused one is fetched again once; the config each worker
|
|
gets and how its standing reads. ``python -m unittest test_claude_proxy``
|
|
from ``backend/``."""
|
|
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import tempfile
|
|
import unittest
|
|
|
|
TMP = pathlib.Path(tempfile.mkdtemp())
|
|
for k, v in {"DB_PATH": TMP / "x.db", "TRANSCRIPTS_DIR": TMP / "t",
|
|
"WORKSPACE": TMP, "REPO_DIR": TMP, "ARCHIVE_DIR": TMP / "arch",
|
|
"META_PATH": TMP / "meta.json", "WORKERS_PATH": TMP / "w.json",
|
|
"WORKERS_TRANSCRIPTS_DIR": TMP / "mirror",
|
|
"CRON_PATH": TMP / "cron.json", "SIDECAR_TOKEN": "",
|
|
"PROFILES_PATH": TMP / "profiles.json", "PROXY_LEDGER_DIR": TMP / "ledger",
|
|
"PI_TRANSCRIPTS_DIR": ""}.items():
|
|
os.environ[k] = str(v)
|
|
|
|
import httpx # noqa: E402
|
|
from fastapi import HTTPException # noqa: E402
|
|
from fastapi.testclient import TestClient # noqa: E402
|
|
|
|
import main # noqa: E402
|
|
from claudeproxy import opencode, routes, service # noqa: E402
|
|
from profiles.store import worker_logins # noqa: E402
|
|
|
|
DEPS = main.app.state.ai
|
|
TOKEN = "w" * 43
|
|
|
|
|
|
class ProxyTest(unittest.TestCase):
|
|
def setUp(self):
|
|
self.store = DEPS.worker_store
|
|
for w in self.store.list():
|
|
self.store.delete(w["id"])
|
|
self.store.put({"id": "mac1", "name": "Mac", "url": "http://mac:8790",
|
|
"token": "bearer", "account": "work", "claudeMode": "proxy",
|
|
"claudeAccounts": ["personal"], "proxyToken": TOKEN,
|
|
"opencodeProxyAccounts": ["chatgpt-work", "opencode-lab"]})
|
|
self.fetched = []
|
|
self.lab = {"personal": "oat-1"}
|
|
|
|
def fetch(account, refresh=False):
|
|
self.fetched.append((account, refresh))
|
|
if account not in self.lab:
|
|
raise HTTPException(409, {"message": "signed out", "kind": "auth"})
|
|
return {"accessToken": self.lab[account], "expiresAt": 9_999_999_999_000}
|
|
|
|
service.TOKENS._fetch = fetch
|
|
service.TOKENS.forget()
|
|
opencode.TOKENS._fetch = lambda account, refresh=False: {
|
|
"accessToken": "chatgpt-access", "accountId": "acc-123", "expiresAt": 9_999_999_999_000}
|
|
opencode.TOKENS.forget()
|
|
self.seen = []
|
|
self.refuse = set()
|
|
|
|
def upstream(req: httpx.Request) -> httpx.Response:
|
|
self.seen.append(req)
|
|
tok = req.headers["authorization"].removeprefix("Bearer ")
|
|
if tok in self.refuse:
|
|
return httpx.Response(401, stream=httpx.ByteStream(b'{"type":"error"}'))
|
|
# A stream, as the real reply is (a Response built from `content`
|
|
# counts as read already).
|
|
return httpx.Response(200, headers={"anthropic-ratelimit-unified-status": "allowed"},
|
|
stream=httpx.ByteStream(b"event: message_start\ndata: {}\n\n"))
|
|
|
|
routes._client = httpx.AsyncClient(transport=httpx.MockTransport(upstream))
|
|
self.client = TestClient(main.app)
|
|
|
|
def post(self, path, token=TOKEN, **kw):
|
|
return self.client.post(path, headers={"Authorization": f"Bearer {token}",
|
|
"anthropic-beta": "claude-code-20250219",
|
|
"X-Forwarded-For": "1.2.3.4"},
|
|
content=json.dumps({"model": "haiku"}), **kw)
|
|
|
|
def test_swaps_the_token_and_streams(self):
|
|
seen = []
|
|
DEPS.usage_poller.observe = lambda a, snap: seen.append((a, snap))
|
|
r = self.post("/proxy/claude/personal/v1/messages?beta=true")
|
|
self.assertEqual(r.status_code, 200)
|
|
self.assertIn(b"message_start", r.content)
|
|
self.assertEqual(r.headers["anthropic-ratelimit-unified-status"], "allowed")
|
|
req = self.seen[0]
|
|
self.assertEqual(str(req.url), "https://api.anthropic.com/v1/messages?beta=true")
|
|
self.assertEqual(req.headers["authorization"], "Bearer oat-1")
|
|
self.assertTrue(req.headers["anthropic-beta"].startswith("oauth-2025-04-20,"))
|
|
self.assertNotIn("x-forwarded-for", req.headers)
|
|
self.assertEqual(self.store.status("mac1").get("proxyLastAccount"), "personal")
|
|
self.assertEqual(seen, []) # no rate-limit window in that reply
|
|
|
|
def test_opencode_swaps_token_and_account_id(self):
|
|
r = self.client.post("/proxy/opencode/chatgpt-work/responses",
|
|
headers={"Authorization": f"Bearer {TOKEN}", "originator": "opencode",
|
|
"chatgpt-account-id": "spoofed"}, content=b"{}")
|
|
self.assertEqual(r.status_code, 200)
|
|
req = self.seen[-1]
|
|
self.assertEqual(str(req.url), "https://chatgpt.com/backend-api/codex/responses")
|
|
self.assertEqual(req.headers["authorization"], "Bearer chatgpt-access")
|
|
self.assertEqual(req.headers["chatgpt-account-id"], "acc-123")
|
|
self.assertEqual(req.headers["originator"], "opencode")
|
|
# keyless (no login to lend), not ticked, not a Codex path
|
|
for path in ("/proxy/opencode/opencode-lab/responses", "/proxy/opencode/chatgpt-x/responses"):
|
|
self.assertEqual(self.client.post(path, headers={"Authorization": f"Bearer {TOKEN}"},
|
|
content=b"{}").status_code, 403)
|
|
self.assertEqual(self.client.post("/proxy/opencode/chatgpt-work/models",
|
|
headers={"Authorization": f"Bearer {TOKEN}"},
|
|
content=b"{}").status_code, 404)
|
|
|
|
def test_own_login_worker_is_refused(self):
|
|
self.store.patch("mac1", {"claudeMode": "own"})
|
|
self.assertEqual(self.post("/proxy/claude/work/v1/messages").status_code, 403)
|
|
|
|
def test_refusals(self):
|
|
self.assertEqual(self.post("/proxy/claude/personal/v1/messages", token="x" * 43)
|
|
.status_code, 401)
|
|
r = self.post("/proxy/claude/work/v1/messages") # not ticked
|
|
self.assertEqual(r.status_code, 403)
|
|
self.assertEqual(r.json()["error"]["type"], "permission_error")
|
|
self.assertEqual(self.post("/proxy/claude/personal/api/oauth/profile").status_code, 404)
|
|
self.assertEqual(self.seen, [])
|
|
|
|
def test_a_refused_token_is_fetched_again_once(self):
|
|
self.post("/proxy/claude/personal/v1/messages")
|
|
self.refuse.add("oat-1")
|
|
self.lab["personal"] = "oat-2"
|
|
r = self.post("/proxy/claude/personal/v1/messages")
|
|
self.assertEqual(r.status_code, 200)
|
|
self.assertEqual(self.fetched, [("personal", False), ("personal", True)])
|
|
self.assertEqual(self.seen[-1].headers["authorization"], "Bearer oat-2")
|
|
|
|
def test_signed_out_lab_login(self):
|
|
self.store.patch("mac1", {"claudeAccounts": ["personal", "work"]})
|
|
r = self.post("/proxy/claude/work/v1/messages")
|
|
self.assertEqual(r.status_code, 401)
|
|
self.assertIn("Settings → Accounts", r.json()["error"]["message"])
|
|
|
|
|
|
class ConfigTest(unittest.TestCase):
|
|
def test_modes_and_accounts(self):
|
|
# a record from before the proxy: its own login, nothing proxied
|
|
self.assertEqual(service.claude_accounts({"account": "work"}), ["work"])
|
|
self.assertEqual(service.proxied_accounts({"account": "work"}), [])
|
|
proxied = {"account": "work", "claudeMode": "proxy"}
|
|
self.assertEqual(service.proxied_accounts(proxied), ["work"])
|
|
self.assertEqual(service.proxied_accounts({"claudeMode": "proxy"}), ["personal"])
|
|
self.assertEqual(service.claude_accounts({**proxied, "claudeAccounts": []}), [])
|
|
# per vendor since profile-level ★ (Wave 3A)
|
|
self.assertEqual(worker_logins({**proxied, "claudeAccounts": ["personal", "bogus"]})["anthropic"],
|
|
["personal"])
|
|
self.assertEqual(service.clean_accounts(["work", "personal", "chatgpt-work", "x"]),
|
|
["personal", "work"])
|
|
|
|
def test_status_and_terminal_default(self):
|
|
store = DEPS.worker_store
|
|
w = {"id": "m", "claudeMode": "proxy", "claudeAccounts": ["personal", "work"],
|
|
"proxyToken": TOKEN}
|
|
store.star_of = lambda wid, held: "work"
|
|
d = service.desired(store, w)
|
|
self.assertEqual(d["default"], "work")
|
|
good = {"claudeProxy": {"hash": service.fingerprint(d["url"], TOKEN, d["accounts"], "work")}}
|
|
self.assertEqual(service.status(store, w, good), service.CURRENT)
|
|
self.assertEqual(service.status(store, w, {}), service.UNSUPPORTED)
|
|
self.assertEqual(service.status(store, w, {"claudeProxy": {"hash": "old"}}), service.OUTDATED)
|
|
own = {**w, "claudeMode": "own", "account": "work"}
|
|
self.assertEqual(service.status(store, own, {"claudeProxy": {"accounts": []}}), service.OFF)
|
|
self.assertEqual(service.status(store, own, good | {"claudeProxy": {"accounts": ["work"]}}),
|
|
service.OUTDATED) # still holds a config: the push drops it
|
|
self.assertEqual(service.terminal_account(store, own), "work")
|
|
|
|
def test_usage_from_headers(self):
|
|
snap = service.usage_from_headers({
|
|
"anthropic-ratelimit-unified-7d-utilization": "0.12",
|
|
"anthropic-ratelimit-unified-7d-reset": "1794160800",
|
|
"anthropic-ratelimit-unified-5h-utilization": "0.5",
|
|
"anthropic-ratelimit-unified-status": "allowed"}, now=100.0)
|
|
self.assertEqual(snap, {"updatedAt": 100.0, "windows": {
|
|
"seven_day": {"pct": 12.0, "resetsAt": 1794160800},
|
|
"five_hour": {"pct": 50.0, "resetsAt": None}}})
|
|
self.assertIsNone(service.usage_from_headers({"content-type": "x"}))
|
|
|
|
def test_fingerprint_matches_the_sidecar(self):
|
|
import importlib.util
|
|
spec = importlib.util.spec_from_file_location(
|
|
"sc_proxy_fp", pathlib.Path(__file__).resolve().parent.parent / "sidecar" / "claude_proxy.py")
|
|
src = spec.loader.get_source("sc_proxy_fp")
|
|
# The sidecar's function, run on its own (its module imports the sidecar's config).
|
|
ns: dict = {}
|
|
start = src.index("def fingerprint")
|
|
exec("import hashlib, json\n" + src[start:src.index("\ndef ", start + 1)], ns)
|
|
self.assertEqual(ns["fingerprint"]("u", "t", ["b", "a"], "a"),
|
|
service.fingerprint("u", "t", ["a", "b"], "a"))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|