Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)
Python
Make proxy authentication bearer-only across every client (#1096)
Ali Khokhar0d5bec3dcd34
diff --git a/.env.example b/.env.exampleindex 7da57615..978b998c 100644--- a/.env.example+++ b/.env.example@@ -178,7 +178,7 @@ HTTP_WRITE_TIMEOUT=60HTTP_CONNECT_TIMEOUT=60-# Optional server API key (Anthropic-style)+# Optional proxy bearer tokenANTHROPIC_AUTH_TOKEN="freecc"diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex 5a785ee0..ddfb4272 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -353,11 +353,12 @@ and non-local origins.Admin routes live beside these in [api/admin_routes.py](src/free_claude_code/api/admin_routes.py).-Authentication is handled by `require_api_key()` in+Authentication is handled by `require_proxy_auth()` in[api/dependencies.py](src/free_claude_code/api/dependencies.py). If `ANTHROPIC_AUTH_TOKEN` is blank,-proxy auth is disabled. Otherwise the token may be supplied through `x-api-key`,-`Authorization: Bearer ...`, or `anthropic-auth-token`. Comparisons use-constant-time matching.+proxy auth is disabled. Otherwise FCC accepts exactly `Authorization: Bearer+<token>`. Other credential headers are ignored, so a stale provider API key+cannot mask valid proxy authorization. The complete bearer token is compared+in constant time; no model suffix or other token mutation is accepted.HTTP request correlation is owned at ingress. A pure ASGI boundary creates oneopaque FCC request ID before routing, places it in log context and request state,@@ -428,7 +429,7 @@ sequenceDiagramparticipant ProviderClient->>Route: POST /v1/messages- Route->>Route: require_api_key+ Route->>Route: require_proxy_authRoute->>Manager: acquire current generationManager-->>Route: Lease(settings, provider resolver)Route->>Handler: create message@@ -820,7 +821,10 @@ instead of stopping at its login gate.`model_catalog_json` file under `~/.fcc/`, and injects that path so Codex'snative `/model` picker lists FCC provider slugs. Catalog generation isfail-open: launch continues with a warning if the catalog cannot be prepared.-- It stores the proxy auth token in `FCC_CODEX_API_KEY` for Codex to read.+- Catalog discovery and inference both authenticate with HTTP bearer authorization.+- It stores the proxy auth token in `FCC_CODEX_API_KEY` for Codex's provider+ `env_key` to read. This process-local variable is a client credential carrier,+ not a second FCC setting.[cli/launchers/pi.py](src/free_claude_code/cli/launchers/pi.py) owns the installed`fcc-pi` launcher and [cli/launchers/pi_extension.ts](src/free_claude_code/cli/launchers/pi_extension.ts)@@ -833,6 +837,8 @@ is its bundled Pi adapter:only routable provider-model IDs, and registers an `anthropic-messages`provider targeting the local proxy. Catalog failure is fail-closed so Pi neversilently falls back to a different provider.+- Catalog discovery and provider inference use HTTP bearer authorization. Pi's+ provider API-key field remains its process-local credential carrier.- FCC connection values live only in child-process `FCC_PI_*` variables. NativePi credentials and persistent configuration remain untouched.- Pi package-management, configuration, help, and version commands pass throughdiff --git a/README.md b/README.mdindex f5522e91..7b2242b7 100644--- a/README.md+++ b/README.md@@ -247,11 +247,11 @@ model = "nvidia_nim/nvidia/nemotron-3-super-120b-a12b"[model_providers.fcc]name = "Free Claude Code"base_url = "http://127.0.0.1:8082/v1"-http_headers = { "X-API-Key" = "freecc" }+http_headers = { Authorization = "Bearer freecc" }wire_api = "responses"```-Match `model`, the port, and `X-API-Key` to the Admin UI, then restart VS Code. For WSL-backed Codex, edit the file inside WSL.+Match `model`, the port, and bearer token to the Admin UI, then restart VS Code. For WSL-backed Codex, edit the file inside WSL.</details>diff --git a/pyproject.toml b/pyproject.tomlindex 45131281..9d19ca7f 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "free-claude-code"-version = "4.2.0"+version = "4.3.0"description = "Local proxy connecting coding agents to OpenAI-compatible AI providers"readme = "README.md"requires-python = ">=3.14.0"diff --git a/smoke/README.md b/smoke/README.mdindex 4087a00a..ca7a51a7 100644--- a/smoke/README.md+++ b/smoke/README.md@@ -54,7 +54,7 @@ Default targets do not send real bot messages or load voice backends:| Target | Product scenarios | Required environment || --- | --- | --- || `api` | messages, count_tokens full payload, errors, `/stop`, optimizations | configured provider only for streaming messages |-| `auth` | x-api-key, bearer, anthropic-auth-token, invalid/missing auth | none; test sets an isolated token |+| `auth` | canonical bearer auth, conflicting legacy headers, invalid/missing auth | none; test sets an isolated token || `cli` | `fcc-init`, server entrypoint, Claude CLI adaptive thinking, session cleanup | Claude CLI binary and provider only for real CLI || `clients` | VS Code and JetBrains protocol payloads | configured provider || `config` | env precedence, removed-env migration, proxy/timeouts | none |diff --git a/smoke/capabilities.py b/smoke/capabilities.pyindex 8001d9f6..d7b88783 100644--- a/smoke/capabilities.py+++ b/smoke/capabilities.py@@ -99,14 +99,14 @@ CAPABILITY_CONTRACTS: tuple[CapabilityContract, ...] = (),CapabilityContract("auth",- "anthropic_headers",+ "bearer_authorization","optional_authentication",- "free_claude_code.api.dependencies.require_api_key",- "x-api-key, authorization, anthropic-auth-token",+ "free_claude_code.api.dependencies.require_proxy_auth",+ "authorization: bearer token","request accepted or 401",- "401 missing/invalid API key",+ "401 missing/invalid proxy authentication token",("tests/api/test_auth.py",),- ("test_auth_token_is_enforced_for_all_supported_header_shapes",),+ ("test_bearer_auth_is_the_only_supported_header_shape",),),CapabilityContract("provider_routing",diff --git a/smoke/features.py b/smoke/features.pyindex 73588056..6af73b78 100644--- a/smoke/features.py+++ b/smoke/features.py@@ -273,11 +273,11 @@ FEATURE_INVENTORY: tuple[FeatureCoverage, ...] = (),FeatureCoverage("optional_authentication",- "Anthropic-style auth headers are enforced and accepted",+ "Canonical bearer proxy authentication is enforced","readme",("tests/api/test_auth.py",),- ("test_auth_token_is_enforced_for_all_supported_header_shapes",),- ("test_api_auth_header_variants_e2e",),+ ("test_bearer_auth_is_the_only_supported_header_shape",),+ ("test_api_bearer_auth_contract_e2e",),("auth",),("ANTHROPIC_AUTH_TOKEN",),"product test starts an isolated token-protected server",diff --git a/smoke/lib/config.py b/smoke/lib/config.pyindex 41653402..78341d6c 100644--- a/smoke/lib/config.py+++ b/smoke/lib/config.py@@ -426,7 +426,7 @@ def auth_headers(token: str | None = None) -> dict[str, str]:"content-type": "application/json",}if resolved:- headers["x-api-key"] = resolved+ headers["authorization"] = f"Bearer {resolved}"return headersdiff --git a/smoke/lib/e2e.py b/smoke/lib/e2e.pyindex a366a7e4..21222f4b 100644--- a/smoke/lib/e2e.py+++ b/smoke/lib/e2e.py@@ -207,12 +207,8 @@ class ClientProtocolDriver:return headers@staticmethod- def jetbrains_headers(config: SmokeConfig) -> dict[str, str]:+ def jetbrains_headers() -> dict[str, str]:headers = auth_headers()- token = config.settings.anthropic_auth_token- if token:- headers.pop("x-api-key", None)- headers["authorization"] = f"Bearer {token}"headers["user-agent"] = "JetBrains-ACP product smoke"return headersdiff --git a/smoke/prereq/test_auth_prereq_live.py b/smoke/prereq/test_auth_prereq_live.pyindex ba353205..01396717 100644--- a/smoke/prereq/test_auth_prereq_live.py+++ b/smoke/prereq/test_auth_prereq_live.py@@ -9,7 +9,7 @@ from smoke.lib.server import start_serverpytestmark = [pytest.mark.live, pytest.mark.smoke_target("auth")]-def test_auth_token_is_enforced_for_all_supported_header_shapes(+def test_bearer_auth_is_the_only_supported_header_shape(smoke_config: SmokeConfig, tmp_path: Path) -> None:token = "fcc-smoke-token"@@ -32,7 +32,7 @@ def test_auth_token_is_enforced_for_all_supported_header_shapes()assert (httpx.get(f"{server.base_url}/", headers={"x-api-key": token}).status_code- == 200+ == 401)assert (httpx.get(@@ -46,5 +46,15 @@ def test_auth_token_is_enforced_for_all_supported_header_shapes(f"{server.base_url}/",headers={"anthropic-auth-token": token},).status_code+ == 401+ )+ assert (+ httpx.get(+ f"{server.base_url}/",+ headers={+ "authorization": f"Bearer {token}",+ "x-api-key": "stale-provider-key",+ },+ ).status_code== 200)diff --git a/smoke/prereq/test_client_shapes_prereq_live.py b/smoke/prereq/test_client_shapes_prereq_live.pyindex 3f173cb0..31d89552 100644--- a/smoke/prereq/test_client_shapes_prereq_live.py+++ b/smoke/prereq/test_client_shapes_prereq_live.py@@ -31,10 +31,6 @@ def test_vscode_and_jetbrains_shaped_requests(assert vscode.json()["content"][0]["text"] == "Quota check passed."jetbrains_headers = auth_headers()- token = smoke_config.settings.anthropic_auth_token- if token:- jetbrains_headers.pop("x-api-key", None)- jetbrains_headers["authorization"] = f"Bearer {token}"jetbrains_headers["user-agent"] = "JetBrains-ACP smoke"jetbrains = post_json(smoke_server,diff --git a/smoke/product/test_auth_product_live.py b/smoke/product/test_auth_product_live.pyindex 6bd259cf..623bd070 100644--- a/smoke/product/test_auth_product_live.py+++ b/smoke/product/test_auth_product_live.py@@ -7,7 +7,7 @@ from smoke.lib.e2e import SmokeServerDriverpytestmark = [pytest.mark.live, pytest.mark.smoke_target("auth")]-def test_api_auth_header_variants_e2e(smoke_config: SmokeConfig, tmp_path) -> None:+def test_api_bearer_auth_contract_e2e(smoke_config: SmokeConfig, tmp_path) -> None:token = "product-smoke-token"env_file = tmp_path / "auth-product.env"env_file.write_text(f'ANTHROPIC_AUTH_TOKEN="{token}"\n', encoding="utf-8")@@ -23,7 +23,7 @@ def test_api_auth_header_variants_e2e(smoke_config: SmokeConfig, tmp_path) -> Nounauth = httpx.get(f"{server.base_url}/v1/models", timeout=smoke_config.timeout_s)- x_api_key = httpx.get(+ x_api_key_only = httpx.get(f"{server.base_url}/v1/models",headers={"x-api-key": token},timeout=smoke_config.timeout_s,@@ -33,19 +33,31 @@ def test_api_auth_header_variants_e2e(smoke_config: SmokeConfig, tmp_path) -> Noheaders={"authorization": f"Bearer {token}"},timeout=smoke_config.timeout_s,)- anthropic = httpx.get(+ anthropic_auth_token_only = httpx.get(f"{server.base_url}/v1/models",headers={"anthropic-auth-token": token},timeout=smoke_config.timeout_s,)- invalid = httpx.get(+ bearer_with_stale_api_key = httpx.get(f"{server.base_url}/v1/models",- headers={"x-api-key": "wrong"},+ headers={+ "authorization": f"Bearer {token}",+ "x-api-key": "stale-provider-key",+ },+ timeout=smoke_config.timeout_s,+ )+ invalid_bearer_with_matching_api_key = httpx.get(+ f"{server.base_url}/v1/models",+ headers={+ "authorization": "Bearer wrong",+ "x-api-key": token,+ },timeout=smoke_config.timeout_s,)assert unauth.status_code == 401- assert x_api_key.status_code == 200+ assert x_api_key_only.status_code == 401assert bearer.status_code == 200- assert anthropic.status_code == 200- assert invalid.status_code == 401+ assert anthropic_auth_token_only.status_code == 401+ assert bearer_with_stale_api_key.status_code == 200+ assert invalid_bearer_with_matching_api_key.status_code == 401diff --git a/smoke/product/test_client_product_live.py b/smoke/product/test_client_product_live.pyindex fec8f664..9994ede9 100644--- a/smoke/product/test_client_product_live.py+++ b/smoke/product/test_client_product_live.py@@ -56,7 +56,7 @@ def test_jetbrains_protocol_e2e(smoke_config: SmokeConfig) -> None:driver = ConversationDriver(server, smoke_config)first = driver.stream(ClientProtocolDriver.tool_result_payload(),- headers=ClientProtocolDriver.jetbrains_headers(smoke_config),+ headers=ClientProtocolDriver.jetbrains_headers(),)assert_product_stream(first.events)diff --git a/src/free_claude_code/api/dependencies.py b/src/free_claude_code/api/dependencies.pyindex 3557c60b..ad45e188 100644--- a/src/free_claude_code/api/dependencies.py+++ b/src/free_claude_code/api/dependencies.py@@ -44,31 +44,35 @@ def resolve_provider(return provider-def require_api_key(+def require_proxy_auth(request: Request,settings: Settings = Depends(get_settings),) -> None:- """Require the configured Anthropic-style server API key."""+ """Require the configured proxy token as HTTP bearer authorization."""anthropic_auth_token = settings.anthropic_auth_token.strip()if not anthropic_auth_token:return- header = (- request.headers.get("x-api-key")- or request.headers.get("authorization")- or request.headers.get("anthropic-auth-token")- )- if not header:- raise HTTPException(status_code=401, detail="Missing API key")+ authorization = request.headers.get("authorization")+ if not authorization:+ raise HTTPException(+ status_code=401,+ detail="Missing proxy authentication token",+ )- token = header.strip()- if header.lower().startswith("bearer "):- token = header.split(" ", 1)[1].strip()- if token and ":" in token:- token = token.split(":", 1)[0].strip()+ parts = authorization.strip().split(maxsplit=1)+ if len(parts) != 2 or parts[0].casefold() != "bearer":+ raise HTTPException(+ status_code=401,+ detail="Invalid proxy authentication token",+ )+ token = parts[1].strip()- if not secrets.compare_digest(+ if not token or not secrets.compare_digest(token.encode("utf-8"),anthropic_auth_token.encode("utf-8"),):- raise HTTPException(status_code=401, detail="Invalid API key")+ raise HTTPException(+ status_code=401,+ detail="Invalid proxy authentication token",+ )diff --git a/src/free_claude_code/api/routes.py b/src/free_claude_code/api/routes.pyindex 2ff1813d..2b045b9f 100644--- a/src/free_claude_code/api/routes.py+++ b/src/free_claude_code/api/routes.py@@ -18,7 +18,7 @@ from free_claude_code.core.trace import trace_eventfrom .dependencies import (get_services,get_settings,- require_api_key,+ require_proxy_auth,resolve_provider,)from .handlers import MessagesHandler, ResponsesHandler, TokenCountHandler@@ -107,7 +107,7 @@ async def create_message(request: Request,request_data: MessagesRequest,services: ApiServices = Depends(get_services),- _auth=Depends(require_api_key),+ _auth=Depends(require_proxy_auth),):"""Create a message (streaming by default; stream=false gets aggregated JSON)."""return await _create_messages_response(@@ -118,7 +118,7 @@ async def create_message(@router.api_route("/v1/messages", methods=["HEAD", "OPTIONS"])-async def probe_messages(_auth=Depends(require_api_key)):+async def probe_messages(_auth=Depends(require_proxy_auth)):return _probe_response("POST, HEAD, OPTIONS")@@ -127,7 +127,7 @@ async def create_response(request: Request,request_data: OpenAIResponsesRequest,services: ApiServices = Depends(get_services),- _auth=Depends(require_api_key),+ _auth=Depends(require_proxy_auth),):"""Create an OpenAI Responses-compatible response through this proxy."""return await _create_responses_response(@@ -138,7 +138,7 @@ async def create_response(@router.api_route("/v1/responses", methods=["HEAD", "OPTIONS"])-async def probe_responses(_auth=Depends(require_api_key)):+async def probe_responses(_auth=Depends(require_proxy_auth)):return _probe_response("POST, HEAD, OPTIONS")@@ -147,7 +147,7 @@ async def count_tokens(request: Request,request_data: TokenCountRequest,settings: Settings = Depends(get_settings),- _auth=Depends(require_api_key),+ _auth=Depends(require_proxy_auth),):"""Count tokens for a request."""handler = TokenCountHandler(settings, token_counter=get_token_count)@@ -155,14 +155,14 @@ async def count_tokens(@router.api_route("/v1/messages/count_tokens", methods=["HEAD", "OPTIONS"])-async def probe_count_tokens(_auth=Depends(require_api_key)):+async def probe_count_tokens(_auth=Depends(require_proxy_auth)):return _probe_response("POST, HEAD, OPTIONS")@router.get("/")async def root(settings: Settings = Depends(get_settings),- _auth=Depends(require_api_key),+ _auth=Depends(require_proxy_auth),):return {"status": "ok",@@ -190,7 +190,7 @@ async def probe_health():async def list_models(services: ApiServices = Depends(get_services),settings: Settings = Depends(get_settings),- _auth=Depends(require_api_key),+ _auth=Depends(require_proxy_auth),):"""List the model ids this proxy advertises to compatible clients."""trace_event(stage="ingress", event="free_claude_code.api.models.list", source="api")@@ -200,7 +200,7 @@ async def list_models(@router.post("/stop")async def stop_cli(services: ApiServices = Depends(get_services),- _auth=Depends(require_api_key),+ _auth=Depends(require_proxy_auth),):"""Stop all CLI sessions and pending tasks."""result = await services.tasks.stop_all()diff --git a/src/free_claude_code/cli/launchers/codex.py b/src/free_claude_code/cli/launchers/codex.pyindex 3d195d4b..986b8d43 100644--- a/src/free_claude_code/cli/launchers/codex.py+++ b/src/free_claude_code/cli/launchers/codex.py@@ -162,7 +162,7 @@ def fetch_proxy_models_response(url = f"{proxy_root_url.rstrip('/')}/v1/models"headers: dict[str, str] = {}if token := auth_token.strip():- headers["X-API-Key"] = token+ headers["Authorization"] = f"Bearer {token}"request = Request(url, headers=headers, method="GET")with urlopen(request, timeout=PROXY_PREFLIGHT_TIMEOUT_SECONDS) as response:diff --git a/src/free_claude_code/cli/launchers/pi_extension.ts b/src/free_claude_code/cli/launchers/pi_extension.tsindex f738a711..4fe3c4e7 100644--- a/src/free_claude_code/cli/launchers/pi_extension.ts+++ b/src/free_claude_code/cli/launchers/pi_extension.ts@@ -112,7 +112,7 @@ async function fetchFccModels(baseUrl: string, apiKey: string): Promise<Providerlet response: Response;try {response = await fetch(`${baseUrl}/v1/models`, {- headers: { "X-API-Key": apiKey },+ headers: { Authorization: `Bearer ${apiKey}` },signal: controller.signal,});} catch (error) {@@ -151,6 +151,7 @@ export default async function freeClaudeCode(pi: ExtensionAPI): Promise<void> {name: "Free Claude Code",baseUrl,apiKey: `$${API_KEY_ENV}`,+ authHeader: true,api: "anthropic-messages",models,});diff --git a/src/free_claude_code/config/admin/manifest.py b/src/free_claude_code/config/admin/manifest.pyindex d7b25c5a..a1d2c400 100644--- a/src/free_claude_code/config/admin/manifest.py+++ b/src/free_claude_code/config/admin/manifest.py@@ -169,7 +169,7 @@ _NON_PROVIDER_FIELDS: tuple[ConfigFieldSpec, ...] = (default="freecc",secret=True,restart_required=True,- description="Protects Claude/API access. It is not admin-page login.",+ description="Bearer token protecting Claude/API access. It is not admin-page login.",),ConfigFieldSpec("PROVIDER_RATE_LIMIT",diff --git a/src/free_claude_code/config/settings.py b/src/free_claude_code/config/settings.pyindex b1b48b9a..3d8b8e45 100644--- a/src/free_claude_code/config/settings.py+++ b/src/free_claude_code/config/settings.py@@ -275,7 +275,7 @@ class Settings(BaseSettings):host: str = "0.0.0.0"port: int = 8082open_admin_browser: bool = Field(default=True, validation_alias="FCC_OPEN_BROWSER")- # Optional server API key to protect endpoints (Anthropic-style)+ # Optional proxy bearer token protecting public API endpoints.# Set via env `ANTHROPIC_AUTH_TOKEN`. When empty, no auth is required.anthropic_auth_token: str = Field(default="", validation_alias="ANTHROPIC_AUTH_TOKEN"diff --git a/tests/api/test_auth.py b/tests/api/test_auth.pyindex 6e94f2a2..c26ce2bd 100644--- a/tests/api/test_auth.py+++ b/tests/api/test_auth.py@@ -9,7 +9,7 @@ from tests.api.support import create_test_appapp = create_test_app()-def test_anthropic_auth_token_required_and_accepts_x_api_key():+def test_proxy_auth_requires_canonical_bearer_header():client = TestClient(app)settings = Settings()settings.anthropic_auth_token = "s3cr3t"@@ -21,15 +21,28 @@ def test_anthropic_auth_token_required_and_accepts_x_api_key():}with patch("free_claude_code.api.routes.get_token_count", return_value=1):- # No header -> 401r = client.post("/v1/messages/count_tokens", json=payload)assert r.status_code == 401+ assert r.json() == {"detail": "Missing proxy authentication token"}assert r.headers["request-id"].startswith("req_")assert "x-should-retry" not in r.headers- # X-API-Key header -> 200+ for headers in (+ {"X-API-Key": "s3cr3t"},+ {"anthropic-auth-token": "s3cr3t"},+ ):+ r = client.post(+ "/v1/messages/count_tokens",+ json=payload,+ headers=headers,+ )+ assert r.status_code == 401+ assert r.json() == {"detail": "Missing proxy authentication token"}+r = client.post(- "/v1/messages/count_tokens", json=payload, headers={"X-API-Key": "s3cr3t"}+ "/v1/messages/count_tokens",+ json=payload,+ headers={"Authorization": "Bearer s3cr3t"},)assert r.status_code == 200assert r.json()["input_tokens"] == 1@@ -37,7 +50,7 @@ def test_anthropic_auth_token_required_and_accepts_x_api_key():app.dependency_overrides.clear()-def test_anthropic_auth_token_accepts_bearer_authorization():+def test_proxy_auth_ignores_conflicting_legacy_headers():client = TestClient(app)settings = Settings()settings.anthropic_auth_token = "b3artoken"@@ -49,15 +62,29 @@ def test_anthropic_auth_token_accepts_bearer_authorization():}with patch("free_claude_code.api.routes.get_token_count", return_value=2):- # Authorization Bearer -> 200r = client.post("/v1/messages/count_tokens",json=payload,- headers={"Authorization": "Bearer b3artoken"},+ headers={+ "Authorization": "Bearer b3artoken",+ "X-API-Key": "stale-anthropic-key",+ "anthropic-auth-token": "stale-proxy-token",+ },)assert r.status_code == 200assert r.json()["input_tokens"] == 2+ r = client.post(+ "/v1/messages/count_tokens",+ json=payload,+ headers={+ "Authorization": "Bearer wrong",+ "X-API-Key": "b3artoken",+ },+ )+ assert r.status_code == 401+ assert r.json() == {"detail": "Invalid proxy authentication token"}+app.dependency_overrides.clear()@@ -95,7 +122,7 @@ def test_anthropic_auth_token_applies_to_models_endpoint():assert r.headers["x-request-id"] == r.headers["request-id"]assert "x-should-retry" not in r.headers- r = client.get("/v1/models", headers={"X-API-Key": "models-token"})+ r = client.get("/v1/models", headers={"Authorization": "Bearer models-token"})assert r.status_code == 200assert "data" in r.json()diff --git a/tests/api/test_dependencies.py b/tests/api/test_dependencies.pyindex d77830f6..0bffdeec 100644--- a/tests/api/test_dependencies.py+++ b/tests/api/test_dependencies.py@@ -6,7 +6,7 @@ from fastapi import HTTPException, Requestfrom free_claude_code.api.dependencies import (get_services,get_settings,- require_api_key,+ require_proxy_auth,resolve_provider,)from free_claude_code.api.ports import ApiServices@@ -106,42 +106,97 @@ def test_resolve_provider_unrelated_error_is_not_reclassified() -> None:resolve_provider("nvidia_nim", lease=lease)-def test_require_api_key_allows_when_no_token_configured():+def test_require_proxy_auth_allows_when_no_token_configured():request, settings = _request(headers={}, token="")- require_api_key(request, settings)+ require_proxy_auth(request, settings)-def test_require_api_key_rejects_missing_token():+def test_require_proxy_auth_rejects_missing_authorization():request, settings = _request(headers={}, token="secret")with pytest.raises(HTTPException) as exc_info:- require_api_key(request, settings)+ require_proxy_auth(request, settings)assert exc_info.value.status_code == 401- assert exc_info.value.detail == "Missing API key"+ assert exc_info.value.detail == "Missing proxy authentication token"-def test_require_api_key_accepts_x_api_key():- request, settings = _request(headers={"x-api-key": "secret"}, token="secret")[email protected]("header_name", ["x-api-key", "anthropic-auth-token"])+def test_require_proxy_auth_rejects_legacy_header_only(header_name: str):+ request, settings = _request(headers={header_name: "secret"}, token="secret")- require_api_key(request, settings)+ with pytest.raises(HTTPException) as exc_info:+ require_proxy_auth(request, settings)++ assert exc_info.value.status_code == 401+ assert exc_info.value.detail == "Missing proxy authentication token"+++def test_require_proxy_auth_accepts_exact_bearer_token():+ request, settings = _request(+ headers={"authorization": "bEaReR secret"},+ token="secret",+ )++ require_proxy_auth(request, settings)+++def test_require_proxy_auth_accepts_colons_in_configured_token():+ request, settings = _request(+ headers={"authorization": "Bearer secret:with:colons"},+ token="secret:with:colons",+ )++ require_proxy_auth(request, settings)-def test_require_api_key_accepts_bearer_token_and_strips_model_suffix():+def test_require_proxy_auth_accepts_valid_bearer_with_conflicting_legacy_headers():request, settings = _request(- headers={"authorization": "Bearer secret:claude-sonnet"},+ headers={+ "authorization": "Bearer secret",+ "x-api-key": "wrong",+ "anthropic-auth-token": "also-wrong",+ },token="secret",)- require_api_key(request, settings)+ require_proxy_auth(request, settings)-def test_require_api_key_rejects_invalid_token():- request, settings = _request(headers={"x-api-key": "wrong"}, token="secret")+ "authorization",+ [+ "secret",+ "Basic secret",+ "Bearer",+ "Bearer wrong",+ "Bearer secret:claude-sonnet",+ ],+)+def test_require_proxy_auth_rejects_malformed_or_invalid_authorization(+ authorization: str,+):+ request, settings = _request(+ headers={"authorization": authorization},+ token="secret",+ )++ with pytest.raises(HTTPException) as exc_info:+ require_proxy_auth(request, settings)++ assert exc_info.value.status_code == 401+ assert exc_info.value.detail == "Invalid proxy authentication token"+++def test_require_proxy_auth_rejects_invalid_bearer_when_legacy_header_matches():+ request, settings = _request(+ headers={"authorization": "Bearer wrong", "x-api-key": "secret"},+ token="secret",+ )with pytest.raises(HTTPException) as exc_info:- require_api_key(request, settings)+ require_proxy_auth(request, settings)assert exc_info.value.status_code == 401- assert exc_info.value.detail == "Invalid API key"+ assert exc_info.value.detail == "Invalid proxy authentication token"diff --git a/tests/api/test_ordinary_error_phases.py b/tests/api/test_ordinary_error_phases.pyindex 71d435ec..16556ee8 100644--- a/tests/api/test_ordinary_error_phases.py+++ b/tests/api/test_ordinary_error_phases.py@@ -226,12 +226,15 @@ def test_preflight_rejection_is_protocol_specific_400_without_terminal_header(@pytest.mark.parametrize(("headers", "detail"),[- ({}, "Missing API key"),- ({"x-api-key": "wrong"}, "Invalid API key"),+ ({}, "Missing proxy authentication token"),+ (+ {"authorization": "Bearer wrong"},+ "Invalid proxy authentication token",+ ),],ids=("missing", "invalid"),)-def test_proxy_auth_preserves_fastapi_detail_contract(+def test_proxy_auth_preserves_ingress_detail_contract(wire_api: str,path: str,payload: dict[str, object],diff --git a/tests/cli/test_entrypoints.py b/tests/cli/test_entrypoints.pyindex 581b4a35..80827d8a 100644--- a/tests/cli/test_entrypoints.py+++ b/tests/cli/test_entrypoints.py@@ -620,7 +620,8 @@ def test_launch_codex_passes_responses_config_and_child_env(request = requests[0]assert request.full_url == "http://127.0.0.1:9191/v1/models"headers = {key.lower(): value for key, value in request.header_items()}- assert headers["x-api-key"] == "proxy-token"+ assert headers["authorization"] == "Bearer proxy-token"+ assert "x-api-key" not in headerscatalog = json.loads(catalog_path.read_text(encoding="utf-8"))assert [model["slug"] for model in catalog["models"]] == ["nvidia_nim/provider-model"diff --git a/uv.lock b/uv.lockindex eb2f7a53..9d385036 100644--- a/uv.lock+++ b/uv.lock@@ -561,7 +561,7 @@ wheels = [[[package]]name = "free-claude-code"-version = "4.2.0"+version = "4.3.0"source = { editable = "." }dependencies = [{ name = "aiohttp" },