diff --git a/.env.sample b/.env.sample index 45a2f01..d37a0b5 100644 --- a/.env.sample +++ b/.env.sample @@ -37,3 +37,15 @@ CLAUDE_MODEL_CAPACITY=25 # CLAUDE_BASE_URL=https://.services.ai.azure.com/anthropic # CLAUDE_DEPLOYMENT_NAME=claude-sonnet-4-6-abc123 # AZURE_TENANT_ID= # Optional: scope SDK token requests to the deployment tenant. + +# Portable SDK samples (process env; Python also loads gitignored .env.local). +# Canonical endpoint/model/key form one profile; do not mix it with CLAUDE_* keys. +# ANTHROPIC_BASE_URL=https://.services.ai.azure.com/anthropic +# ANTHROPIC_MODEL= +# AUTH_MODE=bearer # Required explicitly with ANTHROPIC_BASE_URL. +# AZURE_TOKEN_CREDENTIALS=AzureCliCredential +# TOKEN_SCOPE=https://ai.azure.com/.default +# API-key authentication defaults to Authorization: Bearer and preserves SDK API version. +# Optional legacy overrides: ANTHROPIC_API_VERSION=2023-06-01, API_KEY_HEADER=x-api-key. +# Native provider: AUTH_MODE=api_key, ANTHROPIC_BASE_URL=https://api.anthropic.com. +# Supply the native API key through a secret store or process environment. diff --git a/.github/agents/claude-on-foundry.agent.md b/.github/agents/claude-on-foundry.agent.md index b819691..f4bd5c4 100644 --- a/.github/agents/claude-on-foundry.agent.md +++ b/.github/agents/claude-on-foundry.agent.md @@ -64,7 +64,8 @@ Summarize what was deployed or changed, the resulting endpoint, and any manual f ## Rules - Follow the skill instructions precisely. Don't invent `azd` env vars, regions, or CLI flags. -- **Passwordless only.** Microsoft Entra ID via `DefaultAzureCredential` / `az login`. Never write `CLAUDE_API_KEY`, subscription IDs, tenant IDs, or tokens into any tracked file. +- **Standard SDK clients only.** Use generic client/authentication helpers returning ordinary SDK clients, not platform-specific client imports or SDK subclasses. Claude Code's built-in Foundry mode is separate. +- **Passwordless by default.** Select explicit Azure CLI, azd, or managed-identity credentials. Keys for native-provider/resource-key samples belong only in process env or secret storage. Never write real keys, subscription IDs, tenant IDs, or tokens into tracked files. - **Confirm before destructive actions** (`azd down`, `az cognitiveservices account purge`, `az role assignment delete`, deleting `.azure-cli/`, editing `~/.claude/settings.json`). State exactly what will be deleted and get explicit user confirmation. Never pass `--no-prompt` to skip hooks. - **Don't mix variants** in the same `azd env`. Use a separate env per Bicep / Terraform / region combination. - **Industry must be lowercase.** `technology`, `finance`, `healthcare`, `education`, `retail`, `manufacturing`, `government`, `media`, `other`. diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index fcaf065..9a59c2f 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -31,6 +31,7 @@ This is the **Claude on Foundry Starter Kit** ([`Azure-Samples/claude`](https:// | `CLAUDE_HAIKU_CAPACITY` / `CLAUDE_SONNET_CAPACITY` / `CLAUDE_OPUS_CAPACITY` | no | `25` | TPM ÷ 1000 per family | | `CLAUDE_MODEL_NAME` | no | `claude-sonnet-4-6` | **Legacy** single-deployment fallback (only used when all three `CLAUDE_*_MODEL` are empty) | | `AZURE_TENANT_ID` | no | credential default | SDK token-request tenant; real IDs belong only in process env or gitignored `.env.local` | +| `AZURE_TOKEN_CREDENTIALS` | SDK | `AzureCliCredential` | Explicit SDK credential selection; use `AzureDeveloperCliCredential` after azd login or `ManagedIdentityCredential` in hosted workloads | | `ASSIGN_RBAC` | no | `false` | `true` grants `Cognitive Services User` (least-privilege inference role) on the Foundry account to `AZURE_PRINCIPAL_ID` | | `CLAUDE_CODE_AUTO_INSTALL` | no | `false` | `true` installs the Claude Code CLI in the postprovision hook | | `CLAUDE_WRITE_VSCODE_SETTINGS` | no | `false` | `true` opts in to having the postprovision hook write `.vscode/settings.json` for the [Anthropic Claude Code VS Code extension](https://marketplace.visualstudio.com/items?itemName=anthropic.claude-code). Default skips it — the CLI / SDK don't need workspace settings. | @@ -51,6 +52,7 @@ Always set vars with `azd env set ` from inside the chosen variant - **Never mix the Bicep and Terraform variants in one environment.** Each variant uses its own `azd env`. If the user wants to switch, run `azd env new ` in the other folder. - **Don't suggest disabling RBAC propagation retries.** An intermittent `401 PermissionDenied` immediately after `azd up` with `ASSIGN_RBAC=true` is normal — wait 1-3 minutes. - **Honor the user's region.** `eastus2` and `swedencentral` host all three families; `westus2` is sonnet + opus only. Don't silently change `AZURE_LOCATION`. +- **Use standard Anthropic clients.** The generic helpers in [`src/`](../src/) and [`samples/`](../samples/) accept renewable-token callbacks and return ordinary SDK clients. Do not reintroduce platform-specific client imports or SDK subclasses. Claude Code's separate built-in Foundry mode remains enabled. ## Style diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index c9d1484..43e63f4 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -72,6 +72,89 @@ jobs: - name: Run offline SDK, catalog, and preflight regression tests run: python -m unittest discover -s tests -v + typescript: + name: TypeScript SDK sample + runs-on: ubuntu-latest + defaults: + run: + working-directory: samples/typescript + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6 + with: + node-version: "24" + cache: npm + cache-dependency-path: samples/typescript/package-lock.json + - run: npm ci + - run: npm run build + - run: npm test + + go: + name: Go SDK sample + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6 + with: + go-version-file: samples/go/go.mod + cache-dependency-path: samples/go/go.sum + - run: go vet ./... + working-directory: samples/go + - run: go test ./... + working-directory: samples/go + + dotnet: + name: C# SDK sample + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1 # v5 + with: + dotnet-version: "8.0.x" + - run: dotnet test samples/dotnet/AnthropicStandardSdk.sln --configuration Release + + java: + name: Java SDK sample + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5 + with: + distribution: temurin + java-version: "21" + cache: maven + cache-dependency-path: samples/java/pom.xml + - run: mvn --batch-mode test + working-directory: samples/java + + php: + name: PHP SDK sample + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: shivammathur/setup-php@eb7c497e18156a6bbabfef1d3a82760b9eda3962 # v2 + with: + php-version: "8.4" + tools: composer:v2 + coverage: none + - run: composer install --no-interaction --prefer-dist + working-directory: samples/php + - run: composer test + working-directory: samples/php + + ruby: + name: Ruby SDK sample + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: ruby/setup-ruby@7f797815d8adceb1c412e7abefdd1ab4abc47a5f # v1 + with: + ruby-version: "3.4" + bundler-cache: true + working-directory: samples/ruby + - run: bundle exec ruby test/run.rb + working-directory: samples/ruby + shell: name: Shellcheck + PSScriptAnalyzer runs-on: ubuntu-latest diff --git a/.gitignore b/.gitignore index bc7c648..b87f289 100644 --- a/.gitignore +++ b/.gitignore @@ -40,3 +40,11 @@ local-only/ # 'az login' / 'azd' done in this workspace never touch ~/.azure and # never leak into other VS Code windows. Pure runtime state — do not commit. .azure-cli/ + +# Language sample dependencies and build output +node_modules/ +**/bin/ +**/obj/ +**/target/ +**/vendor/ +.bundle/ diff --git a/AGENTS.md b/AGENTS.md index d903c52..5903c5c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,7 +24,8 @@ The always-on rules below are the same ones in [`.github/copilot-instructions.md - **Configure via `azd env set `** from inside the chosen variant folder. There is no `.env` file. See the env-var contract in [`.github/copilot-instructions.md`](.github/copilot-instructions.md). - **`INDUSTRY` is required with no default**: `technology`, `finance`, `healthcare`, `education`, `retail`, `manufacturing`, `government`, `media`, `other` (lowercase, per the [official guide](https://learn.microsoft.com/azure/developer/ai/how-to/deploy-claude-foundry#configure-required-deployment-values)). The `preup` hook prompts once and saves it; existing `CLAUDE_INDUSTRY` values migrate without prompting. - **Honor the user's region.** `eastus2` and `swedencentral` host all three families; `westus2` is sonnet + opus only. Don't silently change `AZURE_LOCATION`. -- **Passwordless only.** Microsoft Entra ID via `DefaultAzureCredential` / `az login`. Never write `CLAUDE_API_KEY`, subscription IDs, tenant IDs, or tokens into any tracked file. Real values live in env vars, the gitignored `.env.local`, or the gitignored `.azure-cli/` token cache. +- **Standard SDK clients only.** Use the generic client/authentication helpers in [`src/`](./src/) and [`samples/`](./samples/), not platform-specific SDK clients. Helpers return the standard client and accept renewable-token callbacks. Claude Code's built-in Foundry mode is separate. +- **Passwordless by default.** Select explicit Azure CLI, azd, or managed-identity credentials. Native-provider/resource-key samples must take keys only from process env or secret storage. Never write real keys, subscription IDs, tenant IDs, or tokens into any tracked file; gitignored `.env.local` and `.azure-cli/` hold local runtime state. - **Confirm before destructive actions.** Always get explicit user OK before: `azd down`, `az cognitiveservices account purge`, `az role assignment delete`, deleting `.azure-cli/`, editing `~/.claude/settings.json`. Never pass `--no-prompt` to skip hooks. - **Diagnose, don't guess.** When a deployment fails, identify the exact error fingerprint (`715-123420`, `InsufficientQuota`, `AnthropicOrganizationCreationException`, `403 Forbidden`, `401 PermissionDenied`) and follow the matching row in the skill's DIAGNOSE table. - **Run the existing scripts.** Don't invent ad-hoc `az` commands when [`Get-ClaudeCatalog.ps1`](./Get-ClaudeCatalog.ps1), [`scripts/preflight-claude.ps1`](./scripts/preflight-claude.ps1), [`scripts/configure-claude-code.ps1`](./scripts/configure-claude-code.ps1), [`scripts/verify-claude-code.ps1`](./scripts/verify-claude-code.ps1), or [`src/check_claude_quota.py`](./src/check_claude_quota.py) already cover the case. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d9d2d49..e501d8b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -53,6 +53,13 @@ The tests use mock HTTP transports and a fake Azure CLI; no Azure login, deployment, API keys, or model quota is needed. PowerShell 7 is required for the catalog and preflight tests. The SDK 2.x tests use its `httpx2` transport. +The [language samples](samples/README.md) each document their own offline build +and test commands. CI runs all seven SDK paths without cloud credentials. +Keep helpers generic and return standard Anthropic clients; do not introduce +platform-specific clients, custom token caches, or SDK retry implementations. +Live tests use the existing `azd up` deployment in one selected IaC variant; +keep real endpoint/account values and results in gitignored local files. + ## Trademark notice This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft diff --git a/README.md b/README.md index 123188b..23b9eff 100644 --- a/README.md +++ b/README.md @@ -7,12 +7,14 @@ languages: - go - csharp - java +- php +- ruby products: - azure-openai - azure urlFragment: claude name: The Claude on Foundry Starter Kit -description: Deploy Claude models in Microsoft Foundry using one CLI command with Bicep or Terraform. Includes Anthropic SDK for Python examples using the Messages API. Wires up Claude Code so you can run the agentic CLI against your fresh deployment immediately. +description: Deploy Claude models in Microsoft Foundry using one CLI command with Bicep or Terraform. Includes standard Anthropic SDK examples in seven languages using the Messages API and generic authentication helpers. Wires up Claude Code against your deployment. --- --> @@ -194,6 +196,10 @@ azd env get-values | Out-File -Encoding utf8 ..\.env.local cd .. python -m venv .venv && . .venv/Scripts/Activate.ps1 # macOS/Linux: source .venv/bin/activate pip install -r requirements.txt +# After azd auth login, select its credential explicitly. Alternatively, az login +# and leave the default AzureCliCredential. +$env:AZURE_TOKEN_CREDENTIALS = "AzureDeveloperCliCredential" +# macOS/Linux: export AZURE_TOKEN_CREDENTIALS=AzureDeveloperCliCredential python src/hello_claude.py # one-shot Messages call (Entra ID) python src/chat_stream.py # interactive streaming chat — type a message, `exit` to quit python src/hello_claude_token_refresh.py # long-running variant with per-request token refresh @@ -202,38 +208,36 @@ python src/hello_claude_token_refresh.py # long-running variant with per-requ
SDK call shape — the minimal Python snippet and long-running token refresh -We use the SDK's native `AnthropicFoundry` client with an Azure Identity token provider. Tokens are cached and refreshed before expiry, including in the streaming sample. This avoids platform-specific authentication changes in the generic `Anthropic` client. +Every sample uses the standard Anthropic client, not a platform-specific client. A small [client factory](./src/client_auth.py) supplies explicit authentication through public HTTP hooks. Azure Identity's [token provider](./src/token_provider.py) caches tokens and refreshes them before expiry, including during streaming sessions. ```python -import os - -from anthropic import AnthropicFoundry -from azure.identity import DefaultAzureCredential, get_bearer_token_provider - -os.environ.pop("ANTHROPIC_FOUNDRY_RESOURCE", None) -client = AnthropicFoundry( - azure_ad_token_provider=get_bearer_token_provider( - DefaultAzureCredential(), "https://ai.azure.com/.default" - ), - base_url="https://.services.ai.azure.com/anthropic", -) -msg = client.messages.create( - model="", - max_tokens=1024, - messages=[{"role": "user", "content": "Hi"}], -) +from azure.identity import AzureCliCredential, get_bearer_token_provider +from client_auth import create_client + +with AzureCliCredential() as credential: + with create_client( + base_url="https://.services.ai.azure.com/anthropic", + token_provider=get_bearer_token_provider( + credential, "https://ai.azure.com/.default" + ), + ) as client: + msg = client.messages.create( + model="", + max_tokens=1024, + messages=[{"role": "user", "content": "Hi"}], + ) ``` > Pass the **deployment name** (not the model id) as `model`. The SDK appends `/v1/messages` to the configured `base_url`. -The samples print only text blocks; Claude 5.5 can also return thinking blocks. An empty text response fails explicitly, with a token-budget hint, instead of reporting success. For a deployment in a non-default tenant, set `AZURE_TENANT_ID` in your process environment or gitignored `.env.local`. The shared [token provider](./src/claude_auth.py) forwards that tenant to the credential's token request, including its Azure CLI and azd authentication paths. +The samples print only text blocks; Claude 5.5 can also return thinking blocks. An empty text response fails explicitly, with a token-budget hint, instead of reporting success. For a deployment in a non-default tenant, set `AZURE_TENANT_ID` in your process environment or gitignored `.env.local`. The shared [token provider](./src/token_provider.py) forwards that tenant to the credential's token request, including its Azure CLI and azd authentication paths. -The shared client factory clears `ANTHROPIC_FOUNDRY_RESOURCE` only inside the Python process so the explicit `CLAUDE_BASE_URL` wins. This lets the SDK run after sourcing the Claude Code activator without a `base_url and resource are mutually exclusive` error; your parent shell's CLI settings are unchanged. +The standard client does not consume `ANTHROPIC_FOUNDRY_RESOURCE`. The explicit URL wins without changing the environment, so SDK samples and the Claude Code activator can share a shell. The factory binds credentials to the configured origin, disables automatic redirects, and prevents ambient native credentials from overriding the selected authentication. Native SDK API-version and bearer-key defaults are preserved; legacy header/version overrides remain optional.
Long-running processes: auto-refreshing the Entra ID token -A captured static token eventually expires. [src/hello_claude_token_refresh.py](./src/hello_claude_token_refresh.py) demonstrates `AnthropicFoundry(azure_ad_token_provider=...)` instead: Azure Identity caches the token and refreshes it before expiry. The one-shot and streaming samples use the same provider; no custom SDK `credentials=` adapter or OAuth beta header is needed. +A captured static token eventually expires. [src/hello_claude_token_refresh.py](./src/hello_claude_token_refresh.py) uses a cached bearer-token callback instead. The standard SDK's request hook asks for the current token on every request and retry; Azure Identity caches and renews it. There is no custom token cache, retry loop, SDK subclass, or automatic native OAuth beta header. [requirements.txt](./requirements.txt) targets Anthropic SDK **2.1+** and Azure Identity **1.26+**, with upper bounds at the next major version. SDK 2.x uses `httpx2` for custom transports; it is not interchangeable with `httpx`. @@ -241,6 +245,24 @@ A captured static token eventually expires. [src/hello_claude_token_refresh.py](
+### Same SDK client, seven languages + +| Language | Sample and instructions | +|---|---| +| Python | [One-shot](./src/hello_claude.py), [streaming](./src/chat_stream.py), [token refresh](./src/hello_claude_token_refresh.py) | +| TypeScript | [samples/typescript](./samples/typescript/README.md) | +| C# | [samples/dotnet](./samples/dotnet/README.md) | +| Go | [samples/go](./samples/go/README.md) | +| Java | [samples/java](./samples/java/README.md) | +| PHP | [samples/php](./samples/php/README.md) | +| Ruby | [samples/ruby](./samples/ruby/README.md) | + +Helpers return ordinary SDK clients; application code still calls the usual Messages and streaming APIs. [Shared configuration](./samples/README.md) selects the endpoint, model, authentication, key header and API version. The same samples can target Anthropic's native endpoint without changing imports or inference code. + +Python, TypeScript, C#, Go and Java use their official Azure Identity SDKs. PHP and Ruby accept a token-provider callback and use Azure CLI as a documented local fallback; this is **not** an official Azure Identity SDK for those languages. + +Claude Code's built-in Foundry mode below is independent of these SDK samples and remains unchanged. +
Claude Code CLI — optional agentic CLI against the same deployment @@ -714,7 +736,7 @@ The Terraform variant uses `azapi_resource` for both the Foundry account and the | `Project can only be created under AIServices Kind account with allowProjectManagement set to true` | Account property missing. Both variants here set it; check you didn't downgrade the API version. | | `404 Not Found` on inference | Base URL must end in `/anthropic` — `https://.services.ai.azure.com/anthropic`. | | `401 Unauthorized` | Token scope must be `https://ai.azure.com/.default`. Re-run `az login`. | -| `401 Unauthorized` after ~1 hour of running | A captured static token has expired. Use `AnthropicFoundry(azure_ad_token_provider=...)` — see [long-running processes](#advanced-long-running-processes-auto-refreshing-the-entra-id-token). All Entra ID samples cache and refresh tokens before expiry. | +| `401 Unauthorized` after ~1 hour of running | A captured static token has expired. Use the [cached token-provider callback](./src/token_provider.py) with the [standard client factory](./src/client_auth.py) — see [long-running processes](#advanced-long-running-processes-auto-refreshing-the-entra-id-token). | | `AttributeError: 'ThinkingBlock' object has no attribute 'text'` | Claude can return thinking or other non-text blocks. Check `block.type == "text"` before reading `block.text`, as the samples do. | | `403 Forbidden` | Missing a data-plane role on the Foundry account. Grant `Cognitive Services User`, `Foundry User` (formerly `Azure AI User`), or `Azure AI Developer` (see [Required permissions](#required-permissions)). | | `Region not available` | Deploy to `eastus2` or `swedencentral` (or `westus2` for opus-only). | diff --git a/samples/README.md b/samples/README.md new file mode 100644 index 0000000..29fa806 --- /dev/null +++ b/samples/README.md @@ -0,0 +1,97 @@ +# Portable Anthropic SDK samples + +Each language uses its standard Anthropic SDK client. Generic client/authentication helpers handle construction only: no alternate Messages API, SDK subclass, custom retry loop, or platform-specific client package. + +| Language | Instructions | Token acquisition | +|---|---|---| +| Python | [Root quickstart](../README.md#python-sdk) | Official Azure Identity SDK and cached bearer-token provider | +| TypeScript | [typescript](typescript/README.md) | Official `@azure/identity` | +| C# | [dotnet](dotnet/README.md) | Official `Azure.Identity` | +| Go | [go](go/README.md) | Official `azidentity` | +| Java | [java](java/README.md) | Official `com.azure:azure-identity` | +| PHP | [php](php/README.md) | Caller-supplied callback; Azure CLI local fallback | +| Ruby | [ruby](ruby/README.md) | Caller-supplied callback; Azure CLI local fallback | + +PHP/Ruby's CLI fallback is explicit because no current official Azure Identity SDK was identified for those languages. It is not a production managed-identity implementation. Supply an appropriate renewable-token callback in hosted applications. + +## Configuration + +Python loads the gitignored root `.env.local`; the other entrypoints read process environment variables. Export the selected `azd` environment before running them. Never put real keys, tokens, tenant IDs or subscription IDs in checked-in configuration. + +| Variable | Meaning | Starter default | +|---|---|---| +| `ANTHROPIC_BASE_URL` | Selects the canonical endpoint/model/key profile; otherwise use the legacy `CLAUDE_*` profile | Required | +| `ANTHROPIC_MODEL` | Canonical model; legacy profile uses `CLAUDE_DEPLOYMENT_NAME` | Required | +| `AUTH_MODE` | `bearer` or `api_key`; select explicitly with the canonical endpoint profile | `bearer` for the legacy azd profile | +| `AZURE_TOKEN_CREDENTIALS` | Explicit credential class: `AzureCliCredential`, `AzureDeveloperCliCredential`, or `ManagedIdentityCredential` | `AzureCliCredential` | +| `AZURE_TENANT_ID` | Tenant for local credential/token requests | Credential default | +| `AZURE_CLIENT_ID` | User-assigned managed identity client ID | Credential default | +| `TOKEN_SCOPE` | Scope requested by the identity integration | `https://ai.azure.com/.default` | +| `ANTHROPIC_API_KEY` | Key for the canonical profile; legacy profile uses only `CLAUDE_API_KEY` | No default | +| `API_KEY_HEADER` | `Authorization` for native SDK bearer-key semantics, or a raw key header such as `x-api-key` | `Authorization` | +| `ANTHROPIC_API_VERSION` | Optional `anthropic-version` override | Native SDK default | + +Credential selection belongs to sample setup, not the generic client helper. Use a deterministic managed identity in production; no sample silently switches credentials after a failure. + +Endpoint, model and key are resolved as a single profile, never mixed across the two variable families. For example, an ambient native `ANTHROPIC_API_KEY` cannot replace a Foundry `CLAUDE_API_KEY`. A canonical endpoint requires an explicit authentication mode so an ambient native URL cannot silently receive the legacy profile's default Entra token. When exporting `ANTHROPIC_BASE_URL` in the process environment, export `AUTH_MODE` there too; a Python dotenv-file default cannot authorize an ambient process endpoint. + +A local bearer run needs `az login` in the intended tenant/subscription. Where supported, select `AzureDeveloperCliCredential` instead if you authenticated with `azd auth login`. The PHP/Ruby fallback specifically requires Azure CLI. + +The credential-class selector applies to the five official Azure Identity SDK integrations. PHP/Ruby's local entrypoints support only the CLI selector and reject other explicit selections; hosted applications must supply their own renewable-token callback. + +The Python setup allows up to 60 seconds for cold CLI/azd credential-process startup, without falling back to another identity. The generic HTTP client preserves the SDK's own network timeout defaults. + +## Native provider versus Microsoft Foundry + +For Foundry, use the `CLAUDE_BASE_URL` and `CLAUDE_DEPLOYMENT_NAME` emitted by `azd up`. Bearer authentication uses Azure Identity. The native SDK bearer-key header and API version also worked in live tests; the older documented `x-api-key` / `2023-06-01` shape remains available through explicit overrides. + +For the native Anthropic endpoint, supply an Anthropic account key through the environment/secret store, then change configuration: + +```powershell +$env:AUTH_MODE = "api_key" +$env:ANTHROPIC_BASE_URL = "https://api.anthropic.com" +$env:ANTHROPIC_MODEL = "claude-sonnet-5-5" +# Set ANTHROPIC_API_KEY through your secret store or process environment. +``` + +The current native SDK generation uses bearer-style API-key authentication; a Foundry resource key is not an Anthropic account key. Endpoint-specific deployment names and service features are not made interchangeable by a helper. Only configuration changes; client types and Messages/streaming calls stay the same. + +A fresh Haiku 5.5 deployment accepted both `2023-06-01` and `2026-10-21`, both resource-key header shapes, and an incidental native OAuth beta header. These are observations against that deployment, not a claim of a published conformance guarantee for every model, region or native-provider feature. + +## What the helper owns + +- Explicit credential selection and final authentication-header placement. +- Origin binding and redirect restrictions so a copied or redirected request cannot send credentials to an unrelated service. +- Configurable API-key header and API version. +- A renewable-token callback on every attempt, without opting into Anthropic-native OAuth or federation flows. + +The SDK still owns HTTP requests, serialization, streaming, status errors and retries. The identity library or CLI owns token acquisition/renewal. Some CLI credentials run a subprocess when asked for a token; do not assume every identity implementation has the same cache. + +The Python factory uses an explicit non-secret SDK credential to disable ambient discovery, then a public request hook replaces it before transmission. Regression tests ensure it never reaches the transport, other requested beta headers are preserved, and environment/per-request credential canaries cannot override the selected credential. + +## Validation + +Use each language's README for its offline test command. Those tests use real SDKs with recording transports and require no Azure account or model quota. Each sample also supports a real Messages call and a streaming path against a deployment. + +Cloud provisioning remains the existing `azd up` workflow in one selected IaC variant. Claude Code CLI configuration is separate and still uses its built-in Foundry mode. + +The migration was live-tested against a freshly provisioned Haiku 5.5 version 2 deployment in `eastus2`: all seven languages passed Messages, SSE streaming and resource-key authentication with native SDK defaults. Python, TypeScript, C#, Go and Java also passed a configuration-only switch between Azure CLI and Azure Developer CLI credentials. Native Anthropic endpoint routing is covered by offline recording transports; no native-account live test is claimed. + +The TypeScript sample is pinned to the tested SDK 1.1.0 because the configured package feed did not provide 1.3.0 and direct public-registry access failed TLS negotiation in the test environment. Relevant 1.3.0 source was compared, but that package version was not executed. Other runtime/version details are in the language READMEs. + +## Upstream requests + +These are focused requests to reduce or retire the sample-local authentication glue, not requests for another platform-specific client: + +| Area | Issue | +|---|---| +| Python bearer-callable ergonomics and neutral authentication | [anthropics/anthropic-sdk-python#2044](https://github.com/anthropics/anthropic-sdk-python/issues/2044) | +| TypeScript standard-client recipe and explicit authentication policy | [anthropics/anthropic-sdk-typescript#1289](https://github.com/anthropics/anthropic-sdk-typescript/issues/1289) | +| C# external bearer credentials | [anthropics/anthropic-sdk-csharp#321](https://github.com/anthropics/anthropic-sdk-csharp/issues/321) | +| Go context-aware bearer-token option | [anthropics/anthropic-sdk-go#485](https://github.com/anthropics/anthropic-sdk-go/issues/485) | +| Java standard-client token-supplier integration | [anthropics/anthropic-sdk-java#432](https://github.com/anthropics/anthropic-sdk-java/issues/432) | +| PHP neutral external bearer providers | [anthropics/anthropic-sdk-php#110](https://github.com/anthropics/anthropic-sdk-php/issues/110) | +| Ruby neutral external bearer providers | [anthropics/anthropic-sdk-ruby#271](https://github.com/anthropics/anthropic-sdk-ruby/issues/271) | +| Foundry's documented native-SDK compatibility contract | [Azure/azure-rest-api-specs#47738](https://github.com/Azure/azure-rest-api-specs/issues/47738) | + +The service request records the successful protocol observations above and asks for a documented conformance guarantee. It does not claim that the tested service rejected native headers or API versions. diff --git a/samples/dotnet/AnthropicStandardSdk.sln b/samples/dotnet/AnthropicStandardSdk.sln new file mode 100644 index 0000000..b7b065e --- /dev/null +++ b/samples/dotnet/AnthropicStandardSdk.sln @@ -0,0 +1,56 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AnthropicStandardSdk", "src\AnthropicStandardSdk\AnthropicStandardSdk.csproj", "{E552DC7F-29EC-463C-8A2D-30680E6828B5}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AnthropicStandardSdk.Tests", "tests\AnthropicStandardSdk.Tests\AnthropicStandardSdk.Tests.csproj", "{5539170C-E5E4-49A6-BDC1-841DCE5FC132}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {E552DC7F-29EC-463C-8A2D-30680E6828B5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E552DC7F-29EC-463C-8A2D-30680E6828B5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E552DC7F-29EC-463C-8A2D-30680E6828B5}.Debug|x64.ActiveCfg = Debug|Any CPU + {E552DC7F-29EC-463C-8A2D-30680E6828B5}.Debug|x64.Build.0 = Debug|Any CPU + {E552DC7F-29EC-463C-8A2D-30680E6828B5}.Debug|x86.ActiveCfg = Debug|Any CPU + {E552DC7F-29EC-463C-8A2D-30680E6828B5}.Debug|x86.Build.0 = Debug|Any CPU + {E552DC7F-29EC-463C-8A2D-30680E6828B5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E552DC7F-29EC-463C-8A2D-30680E6828B5}.Release|Any CPU.Build.0 = Release|Any CPU + {E552DC7F-29EC-463C-8A2D-30680E6828B5}.Release|x64.ActiveCfg = Release|Any CPU + {E552DC7F-29EC-463C-8A2D-30680E6828B5}.Release|x64.Build.0 = Release|Any CPU + {E552DC7F-29EC-463C-8A2D-30680E6828B5}.Release|x86.ActiveCfg = Release|Any CPU + {E552DC7F-29EC-463C-8A2D-30680E6828B5}.Release|x86.Build.0 = Release|Any CPU + {5539170C-E5E4-49A6-BDC1-841DCE5FC132}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5539170C-E5E4-49A6-BDC1-841DCE5FC132}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5539170C-E5E4-49A6-BDC1-841DCE5FC132}.Debug|x64.ActiveCfg = Debug|Any CPU + {5539170C-E5E4-49A6-BDC1-841DCE5FC132}.Debug|x64.Build.0 = Debug|Any CPU + {5539170C-E5E4-49A6-BDC1-841DCE5FC132}.Debug|x86.ActiveCfg = Debug|Any CPU + {5539170C-E5E4-49A6-BDC1-841DCE5FC132}.Debug|x86.Build.0 = Debug|Any CPU + {5539170C-E5E4-49A6-BDC1-841DCE5FC132}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5539170C-E5E4-49A6-BDC1-841DCE5FC132}.Release|Any CPU.Build.0 = Release|Any CPU + {5539170C-E5E4-49A6-BDC1-841DCE5FC132}.Release|x64.ActiveCfg = Release|Any CPU + {5539170C-E5E4-49A6-BDC1-841DCE5FC132}.Release|x64.Build.0 = Release|Any CPU + {5539170C-E5E4-49A6-BDC1-841DCE5FC132}.Release|x86.ActiveCfg = Release|Any CPU + {5539170C-E5E4-49A6-BDC1-841DCE5FC132}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {E552DC7F-29EC-463C-8A2D-30680E6828B5} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {5539170C-E5E4-49A6-BDC1-841DCE5FC132} = {0AB3BF05-4346-4AA6-1389-037BE0695223} + EndGlobalSection +EndGlobal diff --git a/samples/dotnet/README.md b/samples/dotnet/README.md new file mode 100644 index 0000000..19d3f5b --- /dev/null +++ b/samples/dotnet/README.md @@ -0,0 +1,127 @@ +# C# sample: standard Anthropic SDK with explicit authentication + +One console app that makes a Messages call, or a streaming call with `--stream`, using the **standard** +`AnthropicClient` from the official [`Anthropic`](https://www.nuget.org/packages/Anthropic) package +(13.3.0). Authentication comes from the official +[`Azure.Identity`](https://www.nuget.org/packages/Azure.Identity) package (1.21.0) or from an API key. +There is no `Anthropic.Foundry` package, client subclass, alternate Messages API or custom retry loop. + +| File | Role | +|---|---| +| `src/AnthropicStandardSdk/ClientFactory.cs` | Generic helper. Builds the standard client with one explicit credential. Knows no identity library and reads no environment. Copy this one file (it needs only the `Anthropic` package). | +| `src/AnthropicStandardSdk/CredentialSelector.cs` | The only code that uses Azure Identity: selects one credential class and adapts it to the helper's `TokenProvider` callback. | +| `src/AnthropicStandardSdk/SampleSettings.cs`, `SampleRunner.cs`, `Program.cs` | Environment parsing, the Messages/streaming calls, output and exit codes. | +| `tests/AnthropicStandardSdk.Tests` | Offline tests: the real SDK against recording transports and loopback servers. | + +## Run + +Requires the .NET 8 SDK or later. For the default bearer mode sign in first (`az login`, or `azd auth login` +with `AZURE_TOKEN_CREDENTIALS=AzureDeveloperCliCredential`) in the intended tenant and subscription. + +```powershell +# The `azd up` outputs as they are (the legacy profile; bearer authentication by default) ... +$env:CLAUDE_BASE_URL = "https://.services.ai.azure.com/anthropic" +$env:CLAUDE_DEPLOYMENT_NAME = "" +# ... or the canonical profile, which must name its authentication mode: +# $env:ANTHROPIC_BASE_URL = "https://.services.ai.azure.com/anthropic" +# $env:ANTHROPIC_MODEL = "" +# $env:AUTH_MODE = "bearer" +dotnet run --project samples/dotnet/src/AnthropicStandardSdk -- "Say hello in one sentence." +dotnet run --project samples/dotnet/src/AnthropicStandardSdk -- --stream "Say hello in one sentence." +``` + +Output is the response text followed by `usage: input_tokens=N output_tokens=M`. With `--stream` the text is +printed as it arrives. A response without non-blank text (for example thinking blocks only), a stream that +ends before `message_stop`, and every transport, credential or HTTP error exit non-zero and print the typed +cause and HTTP status, never a token or key. Exit codes: `0` success, `1` request failure, `2` configuration +or usage error. Each call uses `max_tokens` 1024 and a 120 second per-call timeout. The timeout is this sample's own +policy, set explicitly in `SampleRunner`; `ClientFactory` keeps the SDK's timeout unless the caller sets `Timeout`. +The SDK's default retries and cancellation behavior are unchanged. + +## Configuration + +Read by the sample entrypoint only (never by `ClientFactory`). Real keys and IDs belong in the environment or a +secret store, not in tracked files. + +**The endpoint variable selects one profile, and the profile decides which model and key variables are read.** The two +families are never mixed, so an endpoint, deployment name or key left in the environment for another tool cannot be +paired with the wrong partner or silently receive an identity token. + +| | Canonical profile | Legacy profile (`azd` outputs) | +|---|---|---| +| Selected by | `ANTHROPIC_BASE_URL` is set (it wins when both URLs are set) | only `CLAUDE_BASE_URL` is set | +| Model or deployment | `ANTHROPIC_MODEL` (required) | `CLAUDE_DEPLOYMENT_NAME` (required) | +| Key in `AUTH_MODE=api_key` | `ANTHROPIC_API_KEY` | `CLAUDE_API_KEY` | +| `AUTH_MODE` | must be set: `bearer` or `api_key` | `bearer` unless set to `api_key` | + +The other family's variables are ignored, never a fallback. A missing model, key or (canonical) `AUTH_MODE` is a +configuration error, exit `2`, that names the variable. + +Both profiles also read: + +| Variable | Meaning | Default | +|---|---|---| +| `AZURE_TOKEN_CREDENTIALS` | One credential class: `AzureCliCredential`, `AzureDeveloperCliCredential` or `ManagedIdentityCredential`. Nothing falls back to another credential. | `AzureCliCredential` | +| `AZURE_TENANT_ID` | Tenant for the CLI credentials. | credential default | +| `AZURE_CLIENT_ID` | Client ID of a user-assigned managed identity. | system-assigned | +| `TOKEN_SCOPE` | Scope requested from the credential. | `https://ai.azure.com/.default` | +| `API_KEY_HEADER` | `Authorization` sends `Bearer ` (the SDK's own key semantics); any other name, such as `x-api-key`, sends the raw key. | `Authorization` | +| `ANTHROPIC_API_VERSION` | `anthropic-version` header. Unset keeps the SDK default. | unset | + +The base URL must be `https` (plain `http` only for loopback test servers) and the model or deployment name is sent +verbatim. `AzureCliCredential` and `AzureDeveloperCliCredential` are built with a 60 second `ProcessTimeout`, so a slow +CLI start is not reported as a failure; `ManagedIdentityCredential` has no such option. +## Use the helper in your own code + +```csharp +using AnthropicClient client = ClientFactory.Create(new ClientFactoryOptions +{ + BaseUrl = "https://.services.ai.azure.com/anthropic", + // Exactly one credential: a per-attempt bearer callback ... + TokenProvider = async cancellationToken => + (await credential.GetTokenAsync(new TokenRequestContext(["https://ai.azure.com/.default"]), cancellationToken)).Token, + // ... or ApiKey = key, ApiKeyHeader = "x-api-key" (default header: Authorization). +}); + +Message message = await client.Messages.Create(new MessageCreateParams { /* standard SDK call */ }); +``` + +`ClientFactory.Create` returns the unmodified SDK client; everything else is the SDK's own API. What it adds: + +- **One explicit credential.** `ApiKey` and `AuthToken` are cleared so `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN` + and profile/federation discovery are never used. A public SDK handler that runs last, on every attempt: + - refuses any request that is not for the configured origin (credentials are bound to it); + - removes every credential header (`Authorization`, `x-api-key`, `api-key`), then sets only the chosen one, so + ambient `ANTHROPIC_CUSTOM_HEADERS` or per-client extra headers cannot override it; + - leaves other headers, such as `anthropic-beta`, untouched. +- **Origin and redirects.** `https` only (loopback `http` for tests), no user info/query/fragment in the base URL. + The default transport does not follow redirects, and any 301/302/303/307/308 response is refused. +- **Plain token callback.** `TokenProvider` is invoked before every attempt, including SDK retries. The helper adds + no cache, retry or token logic, and it does not use the SDK's `Credentials` provider path (which always adds the + Anthropic-native `anthropic-beta: oauth-2025-04-20` header, keeps its own token cache and calls back with + `forceRefresh` after a 401, none of which `TokenCredential` can honor). Token errors surface with their own type. +- **Ownership.** The caller owns the credential and disposes it; disposing the client disposes only its HTTP resources. + +Token cost: the callback runs per request. `ManagedIdentityCredential` caches tokens inside Azure Identity, but a +CLI credential can start a subprocess on each call, so the per-request cost depends on the credential. This sample +reuses one credential instance and adds no cache of its own. + +## Test (offline) + +The tests use the real SDK against recording transports and loopback servers, with hostile canary values in +`ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_BASE_URL`, `ANTHROPIC_PROFILE`, +`ANTHROPIC_CUSTOM_HEADERS` and the federation variables. They need no Azure account, login or model quota. + +```powershell +dotnet test samples/dotnet/AnthropicStandardSdk.sln +``` + +## Known limits + +- The SDK reads `ANTHROPIC_CUSTOM_HEADERS` once, statically, and cannot be told to ignore it. Credential header + names from it are removed, but other custom headers set there are still sent to the bound origin. +- The sample's 120 second timeout (its own policy, see above) bounds each HTTP call, including a whole streamed response, + not the retries. +- `AzureCliCredential` and `AzureDeveloperCliCredential` need their CLI on `PATH`; use `ManagedIdentityCredential` in + hosted environments. +- Only the Messages and streaming calls are demonstrated. Other SDK APIs go through the same client and handler. \ No newline at end of file diff --git a/samples/dotnet/src/AnthropicStandardSdk/AnthropicStandardSdk.csproj b/samples/dotnet/src/AnthropicStandardSdk/AnthropicStandardSdk.csproj new file mode 100644 index 0000000..6367752 --- /dev/null +++ b/samples/dotnet/src/AnthropicStandardSdk/AnthropicStandardSdk.csproj @@ -0,0 +1,24 @@ + + + + Exe + net8.0 + AnthropicStandardSdk + AnthropicStandardSdk + enable + disable + true + + NU1901;NU1902;NU1903;NU1904 + + + + + + + + + + + + \ No newline at end of file diff --git a/samples/dotnet/src/AnthropicStandardSdk/ClientFactory.cs b/samples/dotnet/src/AnthropicStandardSdk/ClientFactory.cs new file mode 100644 index 0000000..e39ead4 --- /dev/null +++ b/samples/dotnet/src/AnthropicStandardSdk/ClientFactory.cs @@ -0,0 +1,309 @@ +using System; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Anthropic; +using Anthropic.Core; + +namespace AnthropicStandardSdk; + +/// +/// Returns the bearer token for ONE request attempt. +/// +/// +/// calls this before every attempt, including SDK retries, and never +/// caches the result. Expiry, refresh and caching belong to the supplier (for example an identity +/// library credential). The caller owns the supplier and whatever it wraps; disposing the client does +/// not dispose them. +/// +public delegate ValueTask TokenProvider(CancellationToken cancellationToken); + +/// Settings for . Configure exactly one credential. +public sealed class ClientFactoryOptions +{ + /// + /// Absolute service endpoint, for example https://api.anthropic.com. Must be https, except + /// that plain http is accepted for loopback test servers. The credential is bound to this origin. + /// + public required string BaseUrl { get; init; } + + /// Per-attempt bearer token, sent as Authorization: Bearer. + public TokenProvider? TokenProvider { get; init; } + + /// Static key, placed in . + public string? ApiKey { get; init; } + + /// + /// Header that carries . Authorization (the default) sends + /// Bearer <key>; any other name, such as x-api-key, sends the raw key. + /// + public string ApiKeyHeader { get; init; } = ClientFactory.DefaultApiKeyHeader; + + /// Value for anthropic-version. When null the SDK default is left untouched. + public string? ApiVersion { get; init; } + + /// + /// Maximum time for one HTTP call, not including SDK retries. When null the SDK default is kept + /// (the SDK sizes it per call from max_tokens); the helper never picks a timeout of its own. + /// + public TimeSpan? Timeout { get; init; } + + /// SDK retry count. When null the SDK default is kept. + public int? MaxRetries { get; init; } + + /// + /// Replaces the default transport (which never follows redirects). The client disposes it. Meant + /// for tests; a replacement transport must not follow redirects either. + /// + public HttpMessageHandler? Transport { get; init; } +} + +/// +/// Builds the standard with one explicitly chosen credential. It adds no +/// client subclass and no Messages API of its own; calls, streaming, status errors and retries stay +/// with the SDK. +/// +/// +/// The factory neither reads environment variables nor knows any identity library. It clears every +/// SDK credential slot (so ambient keys, tokens and profiles are not discovered) and registers one +/// public SDK handler that runs last. Per attempt that handler refuses a request that is not bound +/// for the configured origin, removes every credential header +/// (Authorization, x-api-key, api-key), sets the chosen one, and refuses +/// redirect responses. Other headers, such as anthropic-beta, are left as they are. +/// +public static class ClientFactory +{ + /// The header used for an API key when none is chosen: Authorization: Bearer. + public const string DefaultApiKeyHeader = "Authorization"; + + private static readonly string[] CredentialHeaderNames = ["Authorization", "x-api-key", "api-key"]; + + /// Creates the client. The caller disposes it. + /// The options are missing, ambiguous or unsafe. + public static AnthropicClient Create(ClientFactoryOptions options) + { + ArgumentNullException.ThrowIfNull(options); + + Uri baseUri = ParseBaseUrl(options.BaseUrl); + + if ((options.TokenProvider is null) == (options.ApiKey is null)) + { + throw new ArgumentException( + "Configure exactly one credential: set either TokenProvider or ApiKey.", + nameof(options)); + } + + if (options.ApiKey is not null && !IsCredentialValue(options.ApiKey)) + { + throw new ArgumentException("ApiKey is empty or contains whitespace or control characters.", nameof(options)); + } + + if (!IsHeaderName(options.ApiKeyHeader)) + { + throw new ArgumentException("ApiKeyHeader is not a valid HTTP header name.", nameof(options)); + } + + if (options.ApiVersion is not null && !IsCredentialValue(options.ApiVersion)) + { + throw new ArgumentException("ApiVersion is empty or contains whitespace or control characters.", nameof(options)); + } + + if (options.Timeout is { } timeout && timeout <= TimeSpan.Zero) + { + throw new ArgumentException("Timeout must be positive.", nameof(options)); + } + + if (options.MaxRetries is < 0) + { + throw new ArgumentException("MaxRetries must not be negative.", nameof(options)); + } + + RequestAuthorizer authorizer = new RequestAuthorizer( + baseUri, options.TokenProvider, options.ApiKey, options.ApiKeyHeader, options.ApiVersion); + + HttpMessageHandler transport = options.Transport ?? new HttpClientHandler + { + AllowAutoRedirect = false, + AutomaticDecompression = DecompressionMethods.All, + }; + + // The SDK applies its own per-call timeout, so the HttpClient one must not cut calls short. + HttpClient httpClient = new HttpClient(transport, disposeHandler: true) + { + Timeout = System.Threading.Timeout.InfiniteTimeSpan, + }; + + ClientOptions clientOptions = new ClientOptions + { + BaseUrl = baseUri.GetLeftPart(UriPartial.Path), + // Clearing both slots stops ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN and profile or + // federation discovery; the handler below supplies the only credential. + ApiKey = null, + AuthToken = null, + HttpClient = httpClient, + Handlers = [Handler.Create(authorizer.SendAsync)], + Timeout = options.Timeout, + MaxRetries = options.MaxRetries, + }; + + return new AnthropicClient(clientOptions); + } + + private static Uri ParseBaseUrl(string? baseUrl) + { + if (!Uri.TryCreate(baseUrl, UriKind.Absolute, out Uri? uri)) + { + throw new ArgumentException("BaseUrl must be an absolute URL.", nameof(baseUrl)); + } + + bool isHttps = uri.Scheme == Uri.UriSchemeHttps; + bool isLoopbackHttp = uri.Scheme == Uri.UriSchemeHttp && uri.IsLoopback; + if (!isHttps && !isLoopbackHttp) + { + throw new ArgumentException( + "BaseUrl must use https; plain http is accepted only for loopback test servers.", nameof(baseUrl)); + } + + if (uri.UserInfo.Length > 0 || uri.Query.Length > 0 || uri.Fragment.Length > 0) + { + throw new ArgumentException("BaseUrl must not contain user info, a query or a fragment.", nameof(baseUrl)); + } + + return uri; + } + + private static bool IsCredentialValue(string value) + { + if (value.Length == 0) + { + return false; + } + + foreach (char c in value) + { + if (c <= ' ' || c >= '\u007f') + { + return false; + } + } + + return true; + } + + private static bool IsHeaderName(string name) + { + if (name.Length == 0) + { + return false; + } + + foreach (char c in name) + { + bool isToken = char.IsAsciiLetterOrDigit(c) || "!#$%&'*+-.^_`|~".Contains(c, StringComparison.Ordinal); + if (!isToken) + { + return false; + } + } + + return true; + } + + private static bool IsRedirect(HttpStatusCode status) => + status is HttpStatusCode.MovedPermanently + or HttpStatusCode.Found + or HttpStatusCode.SeeOther + or HttpStatusCode.TemporaryRedirect + or HttpStatusCode.PermanentRedirect; + + private sealed class RequestAuthorizer + { + private readonly Uri _boundOrigin; + private readonly TokenProvider? _tokenProvider; + private readonly string? _apiKey; + private readonly string _apiKeyHeader; + private readonly string? _apiVersion; + + public RequestAuthorizer( + Uri boundOrigin, TokenProvider? tokenProvider, string? apiKey, string apiKeyHeader, string? apiVersion) + { + _boundOrigin = boundOrigin; + _tokenProvider = tokenProvider; + _apiKey = apiKey; + _apiKeyHeader = apiKeyHeader; + _apiVersion = apiVersion; + } + + public async Task SendAsync( + HttpRequestMessage request, NextHandler next, CancellationToken cancellationToken) + { + // Checked before the supplier runs so a request for another origin never costs a token. + EnsureBoundOrigin(request.RequestUri); + + string headerName; + string headerValue; + if (_tokenProvider is not null) + { + string token = await _tokenProvider(cancellationToken).ConfigureAwait(false); + if (!IsCredentialValue(token)) + { + throw new InvalidOperationException( + "The token provider returned an empty token or one with whitespace or control characters."); + } + + headerName = "Authorization"; + headerValue = "Bearer " + token; + } + else + { + headerName = _apiKeyHeader; + headerValue = string.Equals(_apiKeyHeader, "Authorization", StringComparison.OrdinalIgnoreCase) + ? "Bearer " + _apiKey + : _apiKey!; + } + + foreach (string name in CredentialHeaderNames) + { + request.Headers.Remove(name); + } + + request.Headers.Remove(headerName); + if (!request.Headers.TryAddWithoutValidation(headerName, headerValue)) + { + throw new InvalidOperationException("The credential header could not be set."); + } + + if (_apiVersion is not null) + { + request.Headers.Remove("anthropic-version"); + request.Headers.TryAddWithoutValidation("anthropic-version", _apiVersion); + } + + HttpResponseMessage response = await next(request, cancellationToken).ConfigureAwait(false); + if (IsRedirect(response.StatusCode)) + { + int status = (int)response.StatusCode; + response.Dispose(); + throw new InvalidOperationException( + $"Refused an HTTP {status} redirect: credentials are bound to {_boundOrigin.GetLeftPart(UriPartial.Authority)} and redirects are not followed."); + } + + return response; + } + + private void EnsureBoundOrigin(Uri? requestUri) + { + bool sameOrigin = requestUri is not null + && requestUri.IsAbsoluteUri + && string.Equals(requestUri.Scheme, _boundOrigin.Scheme, StringComparison.OrdinalIgnoreCase) + && string.Equals(requestUri.IdnHost, _boundOrigin.IdnHost, StringComparison.OrdinalIgnoreCase) + && requestUri.Port == _boundOrigin.Port; + if (!sameOrigin) + { + throw new InvalidOperationException( + $"Refused a request outside {_boundOrigin.GetLeftPart(UriPartial.Authority)}; credentials are bound to that origin."); + } + } + } +} \ No newline at end of file diff --git a/samples/dotnet/src/AnthropicStandardSdk/CredentialSelector.cs b/samples/dotnet/src/AnthropicStandardSdk/CredentialSelector.cs new file mode 100644 index 0000000..b78ade7 --- /dev/null +++ b/samples/dotnet/src/AnthropicStandardSdk/CredentialSelector.cs @@ -0,0 +1,100 @@ +using System; +using System.Collections.Generic; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Identity; + +namespace AnthropicStandardSdk; + +/// +/// The only place that knows Azure Identity: it selects exactly one explicit credential class and +/// adapts it to the generic . Nothing here falls back to another +/// credential, and the caller owns (and disposes) the credential. +/// +internal static class CredentialSelector +{ + /// How long a CLI credential waits for its CLI process to return a token. + internal static readonly TimeSpan CliProcessTimeout = TimeSpan.FromSeconds(60); + + internal static AzureCliCredentialOptions CliOptions(string? tenantId) => + new AzureCliCredentialOptions { TenantId = tenantId, ProcessTimeout = CliProcessTimeout }; + + internal static AzureDeveloperCliCredentialOptions DeveloperCliOptions(string? tenantId) => + new AzureDeveloperCliCredentialOptions { TenantId = tenantId, ProcessTimeout = CliProcessTimeout }; + + public static TokenCredential Create(SampleSettings settings) + { + switch (settings.CredentialName) + { + case "AzureCliCredential": + return new AzureCliCredential(CliOptions(settings.TenantId)); + case "AzureDeveloperCliCredential": + return new AzureDeveloperCliCredential(DeveloperCliOptions(settings.TenantId)); + case "ManagedIdentityCredential": + ManagedIdentityId identity = settings.ClientId is null + ? ManagedIdentityId.SystemAssigned + : ManagedIdentityId.FromUserAssignedClientId(settings.ClientId); + return new ManagedIdentityCredential(identity); + default: + throw new ConfigurationException( + "AZURE_TOKEN_CREDENTIALS must be one of: " + string.Join(", ", SampleSettings.CredentialNames) + "."); + } + } + + /// + /// Asks the credential for a token on every call. Caching and renewal stay with the credential; + /// some CLI credentials start a subprocess per call. + /// + public static TokenProvider CreateTokenProvider(TokenCredential credential, string scope, SecretRedactor redactor) + { + TokenRequestContext context = new TokenRequestContext(new string[] { scope }); + return async (CancellationToken cancellationToken) => + { + AccessToken token = await credential.GetTokenAsync(context, cancellationToken).ConfigureAwait(false); + redactor.Add(token.Token); + return token.Token; + }; + } +} + +/// Removes known secrets and bearer values from text before it is printed. +internal sealed class SecretRedactor +{ + private static readonly Regex BearerValue = + new Regex(@"Bearer\s+[A-Za-z0-9._~+/=-]+", RegexOptions.Compiled | RegexOptions.IgnoreCase); + + private readonly List _secrets = new List(); + private readonly object _gate = new object(); + + public void Add(string? secret) + { + if (string.IsNullOrEmpty(secret)) + { + return; + } + + lock (_gate) + { + if (!_secrets.Contains(secret)) + { + _secrets.Add(secret); + } + } + } + + public string Redact(string text) + { + string result = BearerValue.Replace(text, "Bearer [redacted]"); + lock (_gate) + { + foreach (string secret in _secrets) + { + result = result.Replace(secret, "[redacted]", StringComparison.Ordinal); + } + } + + return result; + } +} \ No newline at end of file diff --git a/samples/dotnet/src/AnthropicStandardSdk/Program.cs b/samples/dotnet/src/AnthropicStandardSdk/Program.cs new file mode 100644 index 0000000..5aeb4ca --- /dev/null +++ b/samples/dotnet/src/AnthropicStandardSdk/Program.cs @@ -0,0 +1,30 @@ +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace AnthropicStandardSdk; + +internal static class Program +{ + private static async Task Main(string[] args) + { + using CancellationTokenSource cancellation = new CancellationTokenSource(); + ConsoleCancelEventHandler onCancel = (object? sender, ConsoleCancelEventArgs eventArgs) => + { + eventArgs.Cancel = true; + cancellation.Cancel(); + }; + + Console.CancelKeyPress += onCancel; + try + { + return await SampleRunner + .RunAsync(args, Environment.GetEnvironmentVariable, Console.Out, Console.Error, cancellation.Token) + .ConfigureAwait(false); + } + finally + { + Console.CancelKeyPress -= onCancel; + } + } +} \ No newline at end of file diff --git a/samples/dotnet/src/AnthropicStandardSdk/SampleRunner.cs b/samples/dotnet/src/AnthropicStandardSdk/SampleRunner.cs new file mode 100644 index 0000000..e9f49b7 --- /dev/null +++ b/samples/dotnet/src/AnthropicStandardSdk/SampleRunner.cs @@ -0,0 +1,283 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net.Http; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using Anthropic; +using Anthropic.Exceptions; +using Anthropic.Models.Messages; +using Azure.Core; + +namespace AnthropicStandardSdk; + +/// Raised when a successful HTTP response cannot count as a result (for example, no text). +internal sealed class UnusableResponseException : Exception +{ + public UnusableResponseException(string message) + : base(message) + { + } +} + +internal static class SampleRunner +{ + public const int ExitOk = 0; + public const int ExitFailure = 1; + public const int ExitUsage = 2; + + private const long MaxTokens = 1024; + + // Application policy of this sample, set explicitly on the client; ClientFactory has no timeout default of its own. + internal static readonly TimeSpan RequestTimeout = TimeSpan.FromSeconds(120); + + private const string DefaultPrompt = "Say hello in one short sentence."; + private const string UsageText = "usage: AnthropicStandardSdk [--stream] [prompt...]"; + + private static readonly Regex Whitespace = new Regex(@"\s+", RegexOptions.Compiled); + + /// + /// Runs one Messages call (or one streaming call with --stream). Environment access, + /// credential creation and the HTTP transport are parameters so tests can supply recording fakes. + /// + public static async Task RunAsync( + string[] args, + Func getEnvironmentVariable, + TextWriter output, + TextWriter error, + CancellationToken cancellationToken, + HttpMessageHandler? transport = null, + Func? credentialFactory = null) + { + bool stream = false; + bool optionsEnded = false; + List promptWords = new List(); + foreach (string arg in args) + { + if (!optionsEnded && arg == "--") + { + optionsEnded = true; + } + else if (!optionsEnded && arg == "--stream") + { + stream = true; + } + else if (!optionsEnded && (arg == "-h" || arg == "--help")) + { + output.WriteLine(UsageText); + return ExitOk; + } + else if (!optionsEnded && arg.StartsWith("--", StringComparison.Ordinal)) + { + error.WriteLine("error: unknown option " + arg); + error.WriteLine(UsageText); + return ExitUsage; + } + else + { + promptWords.Add(arg); + } + } + + string prompt = promptWords.Count > 0 ? string.Join(" ", promptWords) : DefaultPrompt; + + SampleSettings settings; + try + { + settings = SampleSettings.FromEnvironment(getEnvironmentVariable); + } + catch (ConfigurationException exception) + { + error.WriteLine("error: " + exception.Message); + return ExitUsage; + } + + SecretRedactor redactor = new SecretRedactor(); + redactor.Add(settings.ApiKey); + TokenCredential? credential = null; + try + { + ClientFactoryOptions factoryOptions; + if (settings.AuthMode == AuthMode.Bearer) + { + Func createCredential = credentialFactory ?? CredentialSelector.Create; + credential = createCredential(settings); + factoryOptions = new ClientFactoryOptions + { + BaseUrl = settings.BaseUrl, + TokenProvider = CredentialSelector.CreateTokenProvider(credential, settings.TokenScope, redactor), + ApiVersion = settings.ApiVersion, + Timeout = RequestTimeout, + Transport = transport, + }; + } + else + { + factoryOptions = new ClientFactoryOptions + { + BaseUrl = settings.BaseUrl, + ApiKey = settings.ApiKey, + ApiKeyHeader = settings.ApiKeyHeader, + ApiVersion = settings.ApiVersion, + Timeout = RequestTimeout, + Transport = transport, + }; + } + + AnthropicClient client; + try + { + client = ClientFactory.Create(factoryOptions); + } + catch (ArgumentException exception) + { + error.WriteLine("error: " + redactor.Redact(exception.Message)); + return ExitUsage; + } + + using (client) + { + MessageCreateParams parameters = new MessageCreateParams + { + Model = settings.Model, + MaxTokens = MaxTokens, + Messages = [new UserMessageParam(prompt)], + }; + + if (stream) + { + await WriteStreamAsync(client, parameters, output, cancellationToken).ConfigureAwait(false); + } + else + { + await WriteMessageAsync(client, parameters, output, cancellationToken).ConfigureAwait(false); + } + } + + return ExitOk; + } + catch (Exception exception) + { + error.WriteLine("error: " + Describe(exception, redactor)); + return ExitFailure; + } + finally + { + // The factory does not own the credential, so the caller that created it releases it. + (credential as IDisposable)?.Dispose(); + } + } + + private static async Task WriteMessageAsync( + AnthropicClient client, MessageCreateParams parameters, TextWriter output, CancellationToken cancellationToken) + { + Message message = await client.Messages.Create(parameters, cancellationToken).ConfigureAwait(false); + + StringBuilder text = new StringBuilder(); + List blockKinds = new List(); + foreach (ContentBlock block in message.Content) + { + blockKinds.Add(block.Value?.GetType().Name ?? "unknown"); + if (block.TryPickText(out TextBlock? textBlock)) + { + text.Append(textBlock.Text); + } + } + + if (string.IsNullOrWhiteSpace(text.ToString())) + { + throw new UnusableResponseException( + "The response contained no text (content blocks: " + string.Join(", ", blockKinds) + ")."); + } + + output.WriteLine(text.ToString()); + output.WriteLine(FormatUsage(message.Usage.InputTokens, message.Usage.OutputTokens)); + } + + private static async Task WriteStreamAsync( + AnthropicClient client, MessageCreateParams parameters, TextWriter output, CancellationToken cancellationToken) + { + long inputTokens = 0; + long outputTokens = 0; + bool sawText = false; + bool sawStop = false; + + await foreach (RawMessageStreamEvent streamEvent in + client.Messages.CreateStreaming(parameters, cancellationToken).ConfigureAwait(false)) + { + if (streamEvent.TryPickStart(out RawMessageStartEvent? start)) + { + inputTokens = start.Message.Usage.InputTokens; + outputTokens = start.Message.Usage.OutputTokens; + } + else if (streamEvent.TryPickContentBlockDelta(out RawContentBlockDeltaEvent? blockDelta) + && blockDelta.Delta.TryPickText(out TextDelta? textDelta) + && textDelta.Text.Length > 0) + { + output.Write(textDelta.Text); + sawText |= !string.IsNullOrWhiteSpace(textDelta.Text); + } + else if (streamEvent.TryPickDelta(out RawMessageDeltaEvent? messageDelta)) + { + outputTokens = messageDelta.Usage.OutputTokens; + } + else if (streamEvent.TryPickStop(out RawMessageStopEvent? _)) + { + sawStop = true; + } + } + + if (!sawText) + { + throw new UnusableResponseException("The stream contained no text."); + } + + if (!sawStop) + { + throw new UnusableResponseException("The stream ended before message_stop."); + } + + output.WriteLine(); + output.WriteLine(FormatUsage(inputTokens, outputTokens)); + } + + private static string FormatUsage(long inputTokens, long outputTokens) => + $"usage: input_tokens={inputTokens} output_tokens={outputTokens}"; + + /// Typed root cause and HTTP status, never credentials. + internal static string Describe(Exception exception, SecretRedactor redactor) + { + StringBuilder text = new StringBuilder(); + Exception? current = exception; + for (int depth = 0; current is not null && depth < 4; depth++) + { + if (depth > 0) + { + text.Append(" <- "); + } + + text.Append(current.GetType().Name); + if (current is AnthropicApiException apiException) + { + text.Append(" (HTTP ").Append((int)apiException.StatusCode).Append(')'); + } + + string message = Whitespace.Replace(current.Message, " ").Trim(); + if (message.Length > 300) + { + message = message.Substring(0, 300) + "..."; + } + + if (message.Length > 0) + { + text.Append(": ").Append(message); + } + + current = current.InnerException; + } + + return redactor.Redact(text.ToString()); + } +} \ No newline at end of file diff --git a/samples/dotnet/src/AnthropicStandardSdk/SampleSettings.cs b/samples/dotnet/src/AnthropicStandardSdk/SampleSettings.cs new file mode 100644 index 0000000..b45dbdc --- /dev/null +++ b/samples/dotnet/src/AnthropicStandardSdk/SampleSettings.cs @@ -0,0 +1,173 @@ +using System; + +namespace AnthropicStandardSdk; + +internal enum AuthMode +{ + Bearer, + ApiKey, +} + +/// +/// Which family of environment variables a run uses. Families are never mixed: the URL decides, and the +/// model and key then come only from that family. +/// +internal enum ConfigProfile +{ + /// Selected by ANTHROPIC_BASE_URL; uses ANTHROPIC_MODEL and ANTHROPIC_API_KEY. + Canonical, + + /// Selected by CLAUDE_BASE_URL alone; uses CLAUDE_DEPLOYMENT_NAME and CLAUDE_API_KEY. + Legacy, +} + +/// Raised for missing or invalid configuration; the sample exits with status 2. +internal sealed class ConfigurationException : Exception +{ + public ConfigurationException(string message) + : base(message) + { + } +} + +/// +/// Environment-driven settings of this sample entrypoint. The reusable +/// never reads them. +/// +internal sealed class SampleSettings +{ + public const string DefaultTokenScope = "https://ai.azure.com/.default"; + public const string DefaultApiKeyHeader = ClientFactory.DefaultApiKeyHeader; + public const string DefaultCredential = "AzureCliCredential"; + + public static readonly string[] CredentialNames = + ["AzureCliCredential", "AzureDeveloperCliCredential", "ManagedIdentityCredential"]; + + public required ConfigProfile Profile { get; init; } + + public required string BaseUrl { get; init; } + + public required string Model { get; init; } + + public required AuthMode AuthMode { get; init; } + + public string? ApiKey { get; init; } + + public required string ApiKeyHeader { get; init; } + + /// Null keeps the SDK default anthropic-version. + public string? ApiVersion { get; init; } + + public required string TokenScope { get; init; } + + public required string CredentialName { get; init; } + + public string? TenantId { get; init; } + + public string? ClientId { get; init; } + + public static SampleSettings FromEnvironment(Func getEnvironmentVariable) + { + // The endpoint selects the whole profile. URL, model and key are never coalesced across the two + // families, so a native endpoint left in the environment cannot be paired with another family's + // deployment name or key, and the other family's values are ignored rather than used as fallbacks. + ConfigProfile profile; + string urlVariable; + string modelVariable; + string keyVariable; + string otherModelVariable; + string otherKeyVariable; + string? baseUrl = First(getEnvironmentVariable, "ANTHROPIC_BASE_URL"); + if (baseUrl is not null) + { + profile = ConfigProfile.Canonical; + urlVariable = "ANTHROPIC_BASE_URL"; + modelVariable = "ANTHROPIC_MODEL"; + keyVariable = "ANTHROPIC_API_KEY"; + otherModelVariable = "CLAUDE_DEPLOYMENT_NAME"; + otherKeyVariable = "CLAUDE_API_KEY"; + } + else + { + baseUrl = First(getEnvironmentVariable, "CLAUDE_BASE_URL"); + if (baseUrl is null) + { + throw new ConfigurationException( + "Set ANTHROPIC_BASE_URL (or CLAUDE_BASE_URL for the legacy profile)."); + } + + profile = ConfigProfile.Legacy; + urlVariable = "CLAUDE_BASE_URL"; + modelVariable = "CLAUDE_DEPLOYMENT_NAME"; + keyVariable = "CLAUDE_API_KEY"; + otherModelVariable = "ANTHROPIC_MODEL"; + otherKeyVariable = "ANTHROPIC_API_KEY"; + } + + string model = First(getEnvironmentVariable, modelVariable) + ?? throw new ConfigurationException( + $"{urlVariable} selects the {profile.ToString().ToLowerInvariant()} profile, so {modelVariable} is required; " + + $"{otherModelVariable} is not used with it."); + + string? modeText = First(getEnvironmentVariable, "AUTH_MODE"); + AuthMode mode; + if (modeText is null) + { + if (profile == ConfigProfile.Canonical) + { + throw new ConfigurationException( + "ANTHROPIC_BASE_URL selects the canonical profile, so AUTH_MODE must be set to 'bearer' or 'api_key'; " + + "this stops an endpoint left in the environment from silently receiving an identity token."); + } + + mode = AuthMode.Bearer; + } + else if (string.Equals(modeText, "bearer", StringComparison.OrdinalIgnoreCase)) + { + mode = AuthMode.Bearer; + } + else if (string.Equals(modeText, "api_key", StringComparison.OrdinalIgnoreCase)) + { + mode = AuthMode.ApiKey; + } + else + { + throw new ConfigurationException("AUTH_MODE must be 'bearer' or 'api_key'."); + } + + string? apiKey = null; + string credentialName = First(getEnvironmentVariable, "AZURE_TOKEN_CREDENTIALS") ?? DefaultCredential; + if (mode == AuthMode.ApiKey) + { + apiKey = First(getEnvironmentVariable, keyVariable) + ?? throw new ConfigurationException( + $"AUTH_MODE=api_key with {urlVariable} needs {keyVariable}; {otherKeyVariable} is not used with it."); + } + else if (Array.IndexOf(CredentialNames, credentialName) < 0) + { + throw new ConfigurationException( + "AZURE_TOKEN_CREDENTIALS must be one of: " + string.Join(", ", CredentialNames) + "."); + } + + return new SampleSettings + { + Profile = profile, + BaseUrl = baseUrl, + Model = model, + AuthMode = mode, + ApiKey = apiKey, + ApiKeyHeader = First(getEnvironmentVariable, "API_KEY_HEADER") ?? DefaultApiKeyHeader, + ApiVersion = First(getEnvironmentVariable, "ANTHROPIC_API_VERSION"), + TokenScope = First(getEnvironmentVariable, "TOKEN_SCOPE") ?? DefaultTokenScope, + CredentialName = credentialName, + TenantId = First(getEnvironmentVariable, "AZURE_TENANT_ID"), + ClientId = First(getEnvironmentVariable, "AZURE_CLIENT_ID"), + }; + } + + private static string? First(Func getEnvironmentVariable, string name) + { + string? value = getEnvironmentVariable(name)?.Trim(); + return string.IsNullOrEmpty(value) ? null : value; + } +} \ No newline at end of file diff --git a/samples/dotnet/tests/AnthropicStandardSdk.Tests/AnthropicStandardSdk.Tests.csproj b/samples/dotnet/tests/AnthropicStandardSdk.Tests/AnthropicStandardSdk.Tests.csproj new file mode 100644 index 0000000..3bc4ffe --- /dev/null +++ b/samples/dotnet/tests/AnthropicStandardSdk.Tests/AnthropicStandardSdk.Tests.csproj @@ -0,0 +1,24 @@ + + + + net8.0 + AnthropicStandardSdk.Tests + enable + disable + false + true + true + NU1901;NU1902;NU1903;NU1904 + + + + + + + + + + + + + \ No newline at end of file diff --git a/samples/dotnet/tests/AnthropicStandardSdk.Tests/ClientFactoryTests.cs b/samples/dotnet/tests/AnthropicStandardSdk.Tests/ClientFactoryTests.cs new file mode 100644 index 0000000..b01e363 --- /dev/null +++ b/samples/dotnet/tests/AnthropicStandardSdk.Tests/ClientFactoryTests.cs @@ -0,0 +1,604 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Anthropic; +using Anthropic.Core; +using Anthropic.Exceptions; +using Anthropic.Models.Messages; +using Xunit; + +namespace AnthropicStandardSdk.Tests; + +/// +/// Drives the real Anthropic SDK client built by against recording +/// transports and loopback servers. No test touches the network beyond loopback. +/// +public sealed class ClientFactoryTests +{ + private static string TextOf(Message message) + { + StringBuilder text = new StringBuilder(); + foreach (ContentBlock block in message.Content) + { + if (block.TryPickText(out TextBlock? textBlock)) + { + text.Append(textBlock.Text); + } + } + + return text.ToString(); + } + + [Theory] + [InlineData(TestClients.NativeUrl)] + [InlineData(TestClients.FoundryUrl)] + public async Task Bearer_UsesMessagesPathModelAndRotatingAuthorization(string baseUrl) + { + RecordingTransport transport = new RecordingTransport(); + RotatingTokens tokens = new RotatingTokens(); + using AnthropicClient client = TestClients.Bearer(transport, tokens.Provider, baseUrl); + + Message first = await client.Messages.Create(TestClients.Params("my-custom-deployment")); + await client.Messages.Create(TestClients.Params()); + + Assert.Equal("OK", TextOf(first)); + IReadOnlyList requests = transport.Requests; + Assert.Equal(2, requests.Count); + Assert.Equal(baseUrl + "/v1/messages", requests[0].Url.AbsoluteUri); + Assert.Equal("Bearer rotating-token-1", requests[0].Header("Authorization")); + Assert.Equal("Bearer rotating-token-2", requests[1].Header("Authorization")); + Assert.False(requests[0].Has("x-api-key")); + Assert.False(requests[0].Has("api-key")); + Assert.Equal(await TestClients.SdkDefaultHeaderAsync("X-Stainless-Timeout"), requests[0].Header("X-Stainless-Timeout")); + + JsonElement body = requests[0].BodyJson(); + Assert.Equal("my-custom-deployment", body.GetProperty("model").GetString()); + Assert.Equal(1024, body.GetProperty("max_tokens").GetInt32()); + Assert.False(body.TryGetProperty("stream", out JsonElement _)); + Assert.Equal(TestClients.Model, requests[1].BodyJson().GetProperty("model").GetString()); + Assert.Equal(2, tokens.Calls); + } + + [Theory] + [InlineData("x-api-key", "synthetic-resource-key")] + [InlineData("api-key", "synthetic-resource-key")] + [InlineData("X-Custom-Key", "synthetic-resource-key")] + [InlineData("Authorization", "Bearer synthetic-resource-key")] + public async Task ApiKey_PlacesTheKeyInTheChosenHeaderOnly(string header, string expectedValue) + { + RecordingTransport transport = new RecordingTransport(); + using AnthropicClient client = TestClients.ApiKey(transport, header: header); + + await client.Messages.Create(TestClients.Params()); + + RecordedRequest request = transport.Single; + Assert.Equal(expectedValue, request.Header(header)); + foreach (string closedName in new string[] { "Authorization", "x-api-key", "api-key" }) + { + if (!string.Equals(closedName, header, StringComparison.OrdinalIgnoreCase)) + { + Assert.False(request.Has(closedName), closedName + " must not be sent"); + } + } + } + + [Fact] + public async Task AChosenHeaderAlreadyOnTheRequestIsReplacedNotAppended() + { + RecordingTransport transport = new RecordingTransport(); + using AnthropicClient client = TestClients.ApiKey(transport, header: "X-Custom-Key"); + IAnthropicClient withExtras = client.WithOptions((ClientOptions options) => options with + { + ExtraHeaders = new Dictionary { ["X-Custom-Key"] = AmbientEnvironment.ExtraApiKey }, + }); + + await withExtras.Messages.Create(TestClients.Params()); + + RecordedRequest request = transport.Single; + Assert.Equal("synthetic-resource-key", request.Header("X-Custom-Key")); + AmbientEnvironment.AssertNoCanaryEgress(request); + } + + [Fact] + public async Task ApiKey_DefaultHeaderIsAuthorizationBearer() + { + RecordingTransport transport = new RecordingTransport(); + using AnthropicClient client = ClientFactory.Create(new ClientFactoryOptions + { + BaseUrl = TestClients.NativeUrl, + ApiKey = "synthetic-native-key", + Transport = transport, + }); + + await client.Messages.Create(TestClients.Params()); + + Assert.Equal("Bearer synthetic-native-key", transport.Single.Header("Authorization")); + Assert.False(transport.Single.Has("x-api-key")); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task AmbientNativeCredentials_NeverReachTheWire(bool bearer) + { + Assert.Equal(AmbientEnvironment.ApiKey, Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY")); + Assert.Equal(AmbientEnvironment.AuthToken, Environment.GetEnvironmentVariable("ANTHROPIC_AUTH_TOKEN")); + RecordingTransport transport = new RecordingTransport(); + using AnthropicClient client = bearer + ? TestClients.Bearer(transport, new RotatingTokens().Provider) + : TestClients.ApiKey(transport); + + await client.Messages.Create(TestClients.Params()); + + RecordedRequest request = transport.Single; + AmbientEnvironment.AssertNoCanaryEgress(request); + Assert.Equal(new Uri(TestClients.FoundryUrl).Host, request.Url.Host); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task SdkBuiltRequest_CarriesNoNativeCredential_BeforeTheLastHookRuns(bool bearer) + { + RecordingTransport transport = new RecordingTransport(); + using AnthropicClient client = bearer + ? TestClients.Bearer(transport, new RotatingTokens().Provider) + : TestClients.ApiKey(transport); + List seenBeforeTheHook = new List(); + DelegatingHandler observer = Handler.Create( + (HttpRequestMessage request, NextHandler next, CancellationToken cancellationToken) => + { + seenBeforeTheHook.Add(request.Headers.ToString()); + return next(request, cancellationToken); + }); + // Handlers are attached on first use, so an outer observer can still be added to a fresh client. + IAnthropicClient observed = client.WithOptions( + (ClientOptions options) => options with { Handlers = [observer, .. options.Handlers] }); + + await observed.Messages.Create(TestClients.Params()); + + string seen = Assert.Single(seenBeforeTheHook); + Assert.Contains(AmbientEnvironment.CustomApiKey, seen, StringComparison.Ordinal); + Assert.DoesNotContain("Authorization", seen, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain(AmbientEnvironment.AuthToken, seen, StringComparison.Ordinal); + Assert.DoesNotContain(AmbientEnvironment.ApiKey, seen, StringComparison.Ordinal); + AmbientEnvironment.AssertNoCanaryEgress(transport.Single); + } + + [Fact] + public async Task Bearer_NeverOptsIntoTheOAuthBeta_AndKeepsOtherHeaders() + { + RecordingTransport transport = new RecordingTransport(); + using AnthropicClient client = TestClients.Bearer(transport, new RotatingTokens().Provider); + IAnthropicClient withExtras = client.WithOptions((ClientOptions options) => options with + { + ExtraHeaders = new Dictionary + { + ["anthropic-beta"] = "files-api-2025-04-14", + ["Authorization"] = "Bearer " + AmbientEnvironment.ExtraAuthorization, + ["x-api-key"] = AmbientEnvironment.ExtraApiKey, + ["X-Request-Source"] = "sample", + }, + }); + + await client.Messages.Create(TestClients.Params()); + await withExtras.Messages.Create(TestClients.Params()); + + IReadOnlyList requests = transport.Requests; + Assert.False(requests[0].Has("anthropic-beta")); + Assert.Equal("files-api-2025-04-14", requests[1].Header("anthropic-beta")); + Assert.Equal("sample", requests[1].Header("X-Request-Source")); + Assert.False(requests[1].Has("x-api-key")); + Assert.StartsWith("Bearer rotating-token-", requests[1].Header("Authorization"), StringComparison.Ordinal); + foreach (RecordedRequest request in requests) + { + Assert.DoesNotContain("oauth-2025-04-20", request.Everything(), StringComparison.Ordinal); + AmbientEnvironment.AssertNoCanaryEgress(request); + } + } + + [Fact] + public async Task ApiVersion_NullKeepsTheSdkDefault_AndAValueReplacesIt() + { + RecordingTransport baseline = new RecordingTransport(); + using AnthropicClient plain = new AnthropicClient(new ClientOptions + { + BaseUrl = TestClients.FoundryUrl, + ApiKey = "baseline-key", + HttpClient = new HttpClient(baseline) { Timeout = System.Threading.Timeout.InfiniteTimeSpan }, + }); + await plain.Messages.Create(TestClients.Params()); + string? sdkDefault = baseline.Single.Header("anthropic-version"); + Assert.False(string.IsNullOrEmpty(sdkDefault)); + + RecordingTransport untouched = new RecordingTransport(); + using AnthropicClient keepsDefault = TestClients.Bearer(untouched, new RotatingTokens().Provider, apiVersion: null); + await keepsDefault.Messages.Create(TestClients.Params()); + + RecordingTransport configured = new RecordingTransport(); + using AnthropicClient replaces = TestClients.Bearer(configured, new RotatingTokens().Provider, apiVersion: "2023-06-01"); + await replaces.Messages.Create(TestClients.Params()); + + Assert.Equal(sdkDefault, untouched.Single.Header("anthropic-version")); + Assert.Equal("2023-06-01", configured.Single.Header("anthropic-version")); + Assert.NotEqual("2023-06-01", sdkDefault); + } + + [Fact] + public async Task Streaming_UsesTheSameStandardClientAndPerAttemptCredential() + { + RecordingTransport transport = new RecordingTransport(); + transport.Enqueue(Responses.Stream("Hel", "lo")); + RotatingTokens tokens = new RotatingTokens(); + using AnthropicClient client = TestClients.Bearer(transport, tokens.Provider); + + StringBuilder text = new StringBuilder(); + await foreach (RawMessageStreamEvent streamEvent in client.Messages.CreateStreaming(TestClients.Params())) + { + if (streamEvent.TryPickContentBlockDelta(out RawContentBlockDeltaEvent? delta) + && delta.Delta.TryPickText(out TextDelta? textDelta)) + { + text.Append(textDelta.Text); + } + } + + Assert.Equal("Hello", text.ToString()); + RecordedRequest request = transport.Single; + Assert.True(request.BodyJson().GetProperty("stream").GetBoolean()); + Assert.Equal("Bearer rotating-token-1", request.Header("Authorization")); + Assert.False(request.Has("anthropic-beta")); + Assert.Equal(TestClients.FoundryUrl + "/v1/messages", request.Url.AbsoluteUri); + } + + [Fact] + public async Task Retry_RequestsAFreshTokenForEveryAttempt() + { + RecordingTransport transport = new RecordingTransport(); + HttpResponseMessage unavailable = Responses.Error(HttpStatusCode.InternalServerError, "api_error", "try again"); + unavailable.Headers.TryAddWithoutValidation("Retry-After-Ms", "1"); + transport.Enqueue(unavailable); + RotatingTokens tokens = new RotatingTokens(); + using AnthropicClient client = TestClients.Bearer(transport, tokens.Provider, maxRetries: null); + + Message message = await client.Messages.Create(TestClients.Params()); + + Assert.Equal("OK", TextOf(message)); + IReadOnlyList requests = transport.Requests; + Assert.Equal(2, requests.Count); + Assert.Equal("Bearer rotating-token-1", requests[0].Header("Authorization")); + Assert.Equal("Bearer rotating-token-2", requests[1].Header("Authorization")); + Assert.Equal("0", requests[0].Header("x-stainless-retry-count")); + Assert.Equal("1", requests[1].Header("x-stainless-retry-count")); + Assert.Equal(2, tokens.Calls); + } + + [Theory] + [InlineData(HttpStatusCode.Unauthorized, "authentication_error")] + [InlineData(HttpStatusCode.Forbidden, "permission_error")] + public async Task AuthFailures_SurfaceTypedStatusWithoutHiddenRetries(HttpStatusCode status, string errorType) + { + RecordingTransport transport = new RecordingTransport(); + transport.Enqueue(Responses.Error(status, errorType, "rejected")); + RotatingTokens tokens = new RotatingTokens(); + using AnthropicClient client = TestClients.Bearer(transport, tokens.Provider, maxRetries: null); + + AnthropicApiException exception = await Assert.ThrowsAnyAsync( + () => client.Messages.Create(TestClients.Params())); + + Assert.Equal(status, exception.StatusCode); + if (status == HttpStatusCode.Unauthorized) + { + Assert.IsType(exception); + } + else + { + Assert.IsType(exception); + } + + Assert.Single(transport.Requests); + Assert.Equal(1, tokens.Calls); + Assert.DoesNotContain("rotating-token", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task ProviderFailure_PropagatesItsTypeWithoutRetriesOrRequests() + { + RecordingTransport transport = new RecordingTransport(); + int calls = 0; + TokenProvider failing = (CancellationToken _) => + { + calls++; + throw new InvalidOperationException("synthetic provider failure"); + }; + using AnthropicClient client = TestClients.Bearer(transport, failing, maxRetries: null); + + InvalidOperationException exception = await Assert.ThrowsAsync( + () => client.Messages.Create(TestClients.Params())); + + Assert.Equal("synthetic provider failure", exception.Message); + Assert.Equal(1, calls); + Assert.Empty(transport.Requests); + } + + [Theory] + [InlineData("")] + [InlineData("has space")] + [InlineData("line\r\nbreak")] + [InlineData("tab\there")] + public async Task MalformedTokens_AreRejectedBeforeAnyRequest(string token) + { + RecordingTransport transport = new RecordingTransport(); + using AnthropicClient client = TestClients.Bearer( + transport, (CancellationToken _) => ValueTask.FromResult(token), maxRetries: null); + + InvalidOperationException exception = await Assert.ThrowsAsync( + () => client.Messages.Create(TestClients.Params())); + + Assert.Empty(transport.Requests); + Assert.DoesNotContain("break", exception.Message, StringComparison.Ordinal); + } + + [Fact] + public async Task Cancellation_BeforeTheCallSendsNothing() + { + RecordingTransport transport = new RecordingTransport(); + RotatingTokens tokens = new RotatingTokens(); + using AnthropicClient client = TestClients.Bearer(transport, tokens.Provider, maxRetries: null); + using CancellationTokenSource cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + + await Assert.ThrowsAnyAsync( + () => client.Messages.Create(TestClients.Params(), cancellation.Token)); + + Assert.Empty(transport.Requests); + Assert.Equal(0, tokens.Calls); + } + + [Fact] + public async Task Cancellation_WhileTheProviderWaitsStopsTheCall() + { + RecordingTransport transport = new RecordingTransport(); + TaskCompletionSource waiting = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + TokenProvider slow = async (CancellationToken cancellationToken) => + { + waiting.TrySetResult(); + await Task.Delay(System.Threading.Timeout.Infinite, cancellationToken).ConfigureAwait(false); + return "unreachable-token"; + }; + using AnthropicClient client = TestClients.Bearer(transport, slow, maxRetries: null); + using CancellationTokenSource cancellation = new CancellationTokenSource(); + + Task call = client.Messages.Create(TestClients.Params(), cancellation.Token); + await waiting.Task.WaitAsync(TimeSpan.FromSeconds(10)); + cancellation.Cancel(); + + await Assert.ThrowsAnyAsync(() => call); + Assert.Empty(transport.Requests); + } + + [Fact] + public async Task Cancellation_InFlightIsNotRetriedByTheSdk() + { + RecordingTransport transport = new RecordingTransport(); + TaskCompletionSource inFlight = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + transport.Enqueue(async (RecordedRequest _, CancellationToken cancellationToken) => + { + inFlight.TrySetResult(); + await Task.Delay(System.Threading.Timeout.Infinite, cancellationToken).ConfigureAwait(false); + throw new InvalidOperationException("unreachable"); + }); + using AnthropicClient client = TestClients.Bearer(transport, new RotatingTokens().Provider, maxRetries: null); + using CancellationTokenSource cancellation = new CancellationTokenSource(); + + Task call = client.Messages.Create(TestClients.Params(), cancellation.Token); + await inFlight.Task.WaitAsync(TimeSpan.FromSeconds(10)); + cancellation.Cancel(); + + await Assert.ThrowsAnyAsync(() => call); + Assert.Single(transport.Requests); + } + + [Fact] + public async Task Timeout_KeepsTheSdkDefaultUntilTheCallerSetsOne() + { + RecordingTransport implicitTimeout = new RecordingTransport(); + using AnthropicClient keepsDefault = TestClients.Bearer(implicitTimeout, new RotatingTokens().Provider); + await keepsDefault.Messages.Create(TestClients.Params()); + + RecordingTransport explicitTimeout = new RecordingTransport(); + using AnthropicClient overrides = TestClients.Bearer( + explicitTimeout, new RotatingTokens().Provider, timeout: TimeSpan.FromSeconds(45)); + await overrides.Messages.Create(TestClients.Params()); + + string sdkDefault = await TestClients.SdkDefaultHeaderAsync("X-Stainless-Timeout"); + Assert.Equal(sdkDefault, implicitTimeout.Single.Header("X-Stainless-Timeout")); + Assert.Equal("45", explicitTimeout.Single.Header("X-Stainless-Timeout")); + Assert.NotEqual("45", sdkDefault); + } + + [Fact] + public async Task Timeout_IsAppliedPerCallAndRetriedBySdk() + { + RecordingTransport transport = new RecordingTransport(); + Responder hang = async (RecordedRequest _, CancellationToken cancellationToken) => + { + await Task.Delay(System.Threading.Timeout.Infinite, cancellationToken).ConfigureAwait(false); + throw new InvalidOperationException("unreachable"); + }; + transport.Enqueue(hang); + transport.Enqueue(hang); + using AnthropicClient client = TestClients.Bearer( + transport, new RotatingTokens().Provider, maxRetries: 1, timeout: TimeSpan.FromMilliseconds(150)); + + OperationCanceledException exception = await Assert.ThrowsAnyAsync( + () => client.Messages.Create(TestClients.Params())); + + Assert.IsType(exception.InnerException); + IReadOnlyList requests = transport.Requests; + Assert.Equal(2, requests.Count); + Assert.Equal("0.15", requests[0].Header("X-Stainless-Timeout")); + } + + [Theory] + [InlineData(HttpStatusCode.MovedPermanently)] + [InlineData(HttpStatusCode.Found)] + [InlineData(HttpStatusCode.SeeOther)] + [InlineData(HttpStatusCode.TemporaryRedirect)] + [InlineData(HttpStatusCode.PermanentRedirect)] + public async Task Redirects_AreRefusedWithoutFollowingOrRetrying(HttpStatusCode status) + { + RecordingTransport transport = new RecordingTransport(); + transport.Enqueue(Responses.Redirect(status, "https://attacker.example/collect")); + using AnthropicClient client = TestClients.ApiKey(transport, maxRetries: null); + + InvalidOperationException exception = await Assert.ThrowsAsync( + () => client.Messages.Create(TestClients.Params())); + + Assert.Contains("redirect", exception.Message, StringComparison.OrdinalIgnoreCase); + Assert.DoesNotContain("attacker.example", exception.Message, StringComparison.Ordinal); + Assert.Single(transport.Requests); + } + + [Fact] + public async Task DefaultTransport_SendsToLoopbackAndRefusesCrossOriginRedirects() + { + using LoopbackServer attacker = new LoopbackServer( + (string _) => LoopbackServer.Json(Responses.MessageJson("\"stolen\"", 1, 1))); + int served = 0; + using LoopbackServer origin = new LoopbackServer( + (string _) => Interlocked.Increment(ref served) == 1 + ? LoopbackServer.Json(Responses.MessageJson("\"loopback ok\"", 3, 4)) + : LoopbackServer.Raw("307 Temporary Redirect", $"Location: {attacker.BaseUrl}/steal")); + + using AnthropicClient bearer = ClientFactory.Create(new ClientFactoryOptions + { + BaseUrl = origin.BaseUrl, + TokenProvider = new RotatingTokens().Provider, + MaxRetries = 0, + }); + Message ok = await bearer.Messages.Create(TestClients.Params()); + Assert.Equal("loopback ok", TextOf(ok)); + string head = Assert.Single(origin.RequestHeads); + Assert.StartsWith("POST /v1/messages HTTP/1.1", head, StringComparison.Ordinal); + Assert.Contains("authorization: Bearer rotating-token-1", head, StringComparison.OrdinalIgnoreCase); + + using AnthropicClient keyed = ClientFactory.Create(new ClientFactoryOptions + { + BaseUrl = origin.BaseUrl, + ApiKey = "synthetic-resource-key", + ApiKeyHeader = "x-api-key", + }); + InvalidOperationException exception = await Assert.ThrowsAsync( + () => keyed.Messages.Create(TestClients.Params())); + + Assert.Contains("redirect", exception.Message, StringComparison.OrdinalIgnoreCase); + Assert.Equal(2, origin.RequestHeads.Count); + Assert.Empty(attacker.RequestHeads); + } + + [Fact] + public async Task OriginBinding_RefusesRequestsForAnotherOriginBeforeAskingForATokenOrSending() + { + RecordingTransport transport = new RecordingTransport(); + RotatingTokens tokens = new RotatingTokens(); + using AnthropicClient client = TestClients.Bearer(transport, tokens.Provider, maxRetries: null); + IAnthropicClient retargeted = client.WithOptions( + (ClientOptions options) => options with { BaseUrl = "https://attacker.example" }); + + InvalidOperationException exception = await Assert.ThrowsAsync( + () => retargeted.Messages.Create(TestClients.Params())); + + Assert.Contains("bound", exception.Message, StringComparison.Ordinal); + Assert.Empty(transport.Requests); + Assert.Equal(0, tokens.Calls); + } + + [Theory] + [InlineData("")] + [InlineData("not a url")] + [InlineData("/relative/path")] + [InlineData("http://example.com")] + [InlineData("ftp://example.com")] + [InlineData("https://user:pass@example.com")] + [InlineData("https://example.com/path?query=1")] + [InlineData("https://example.com/path#fragment")] + public void Create_RejectsUnsafeBaseUrls(string baseUrl) + { + Assert.Throws(() => ClientFactory.Create(new ClientFactoryOptions + { + BaseUrl = baseUrl, + ApiKey = "synthetic-key", + })); + } + + [Theory] + [InlineData("http://127.0.0.1:5000")] + [InlineData("http://localhost:5000")] + [InlineData("http://[::1]:5000")] + [InlineData("https://example.com")] + public void Create_AcceptsHttpsAndLoopbackHttp(string baseUrl) + { + using AnthropicClient client = ClientFactory.Create(new ClientFactoryOptions + { + BaseUrl = baseUrl, + ApiKey = "synthetic-key", + }); + + Assert.NotNull(client); + } + + [Fact] + public void Create_RequiresExactlyOneCredential() + { + RotatingTokens tokens = new RotatingTokens(); + Assert.Throws(() => ClientFactory.Create(new ClientFactoryOptions + { + BaseUrl = TestClients.FoundryUrl, + })); + Assert.Throws(() => ClientFactory.Create(new ClientFactoryOptions + { + BaseUrl = TestClients.FoundryUrl, + ApiKey = "synthetic-key", + TokenProvider = tokens.Provider, + })); + Assert.Throws(() => ClientFactory.Create(null!)); + } + + [Theory] + [InlineData("api-key-with-space ", null, null, null)] + [InlineData("synthetic-key", "bad header", null, null)] + [InlineData("synthetic-key", "bad:header", null, null)] + [InlineData("synthetic-key", "", null, null)] + [InlineData("synthetic-key", "x-api-key", "bad version", null)] + [InlineData("synthetic-key", "x-api-key", "", null)] + [InlineData("synthetic-key", "x-api-key", null, -1)] + public void Create_RejectsMalformedOptions(string apiKey, string? header, string? apiVersion, int? maxRetries) + { + Assert.Throws(() => ClientFactory.Create(new ClientFactoryOptions + { + BaseUrl = TestClients.FoundryUrl, + ApiKey = apiKey, + ApiKeyHeader = header ?? "x-api-key", + ApiVersion = apiVersion, + MaxRetries = maxRetries, + })); + } + + [Theory] + [InlineData(0)] + [InlineData(-5)] + public void Create_RejectsNonPositiveTimeouts(int seconds) + { + Assert.Throws(() => ClientFactory.Create(new ClientFactoryOptions + { + BaseUrl = TestClients.FoundryUrl, + ApiKey = "synthetic-key", + Timeout = TimeSpan.FromSeconds(seconds), + })); + } +} \ No newline at end of file diff --git a/samples/dotnet/tests/AnthropicStandardSdk.Tests/CredentialSelectorTests.cs b/samples/dotnet/tests/AnthropicStandardSdk.Tests/CredentialSelectorTests.cs new file mode 100644 index 0000000..3b7904a --- /dev/null +++ b/samples/dotnet/tests/AnthropicStandardSdk.Tests/CredentialSelectorTests.cs @@ -0,0 +1,197 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Identity; +using Xunit; + +namespace AnthropicStandardSdk.Tests; + +/// +/// Credential wiring through the real Azure Identity classes. Fake CLIs and a loopback identity +/// endpoint stand in for the cloud, so no account, login or network is involved. +/// +[Collection("ProcessEnvironment")] +public sealed class CredentialSelectorTests : IDisposable +{ + private const string TenantId = "00000000-0000-0000-0000-00000000aaaa"; + private const string ClientId = "00000000-0000-0000-0000-00000000bbbb"; + + private readonly string _directory = + Path.Combine(Path.GetTempPath(), "anthropic-sample-tests-" + Guid.NewGuid().ToString("N")); + + private readonly Dictionary _originalEnvironment = new Dictionary(); + + private static SampleSettings Settings(string credentialName, string? tenantId = null, string? clientId = null) => + new SampleSettings + { + Profile = ConfigProfile.Canonical, + BaseUrl = TestClients.FoundryUrl, + Model = TestClients.Model, + AuthMode = AuthMode.Bearer, + ApiKeyHeader = ClientFactory.DefaultApiKeyHeader, + TokenScope = SampleSettings.DefaultTokenScope, + CredentialName = credentialName, + TenantId = tenantId, + ClientId = clientId, + }; + + public void Dispose() + { + foreach (KeyValuePair original in _originalEnvironment) + { + Environment.SetEnvironmentVariable(original.Key, original.Value); + } + + if (Directory.Exists(_directory)) + { + Directory.Delete(_directory, recursive: true); + } + } + + [Theory] + [InlineData("AzureCliCredential", typeof(AzureCliCredential))] + [InlineData("AzureDeveloperCliCredential", typeof(AzureDeveloperCliCredential))] + [InlineData("ManagedIdentityCredential", typeof(ManagedIdentityCredential))] + public void Create_SelectsExactlyTheNamedCredentialClass(string name, Type expected) + { + Assert.IsType(expected, CredentialSelector.Create(Settings(name))); + } + + [Theory] + [InlineData("DefaultAzureCredential")] + [InlineData("EnvironmentCredential")] + [InlineData("")] + public void Create_RejectsAnyOtherCredentialName(string name) + { + Assert.Throws(() => CredentialSelector.Create(Settings(name))); + } + + [Fact] + public void CliCredentialOptions_AllowSixtySecondsForTheProcess() + { + TimeSpan expected = TimeSpan.FromSeconds(60); + + AzureCliCredentialOptions cli = CredentialSelector.CliOptions(TenantId); + AzureDeveloperCliCredentialOptions developerCli = CredentialSelector.DeveloperCliOptions(TenantId); + + Assert.Equal(expected, CredentialSelector.CliProcessTimeout); + Assert.Equal(expected, cli.ProcessTimeout); + Assert.Equal(expected, developerCli.ProcessTimeout); + Assert.Equal(TenantId, cli.TenantId); + Assert.Equal(TenantId, developerCli.TenantId); + } + + [Theory] + [InlineData("AzureCliCredential")] + [InlineData("AzureDeveloperCliCredential")] + public void CliCredentials_AreConstructedWithASixtySecondProcessTimeout(string name) + { + TokenCredential credential = CredentialSelector.Create(Settings(name, TenantId)); + + // The credential keeps the timeout it was constructed with in a non-public property. + PropertyInfo? property = credential.GetType().GetProperty( + "ProcessTimeout", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + Assert.True(property is not null, "Azure.Identity no longer exposes ProcessTimeout on " + credential.GetType().Name); + Assert.Equal(TimeSpan.FromSeconds(60), (TimeSpan)property!.GetValue(credential)!); + } + + [Fact] + public async Task AzureCliCredential_ReceivesTheScopeAndTenantFromConfiguration() + { + string argumentsFile = InstallFakeCli( + "az", + """{"accessToken":"fake-cli-token","expiresOn":"2099-01-01 00:00:00.000000","expires_on":4070908800,"tokenType":"Bearer"}"""); + TokenProvider provider = CredentialSelector.CreateTokenProvider( + CredentialSelector.Create(Settings("AzureCliCredential", TenantId)), + SampleSettings.DefaultTokenScope, + new SecretRedactor()); + + string token = await provider(CancellationToken.None); + + Assert.Equal("fake-cli-token", token); + string arguments = File.ReadAllText(argumentsFile); + Assert.Contains("get-access-token", arguments, StringComparison.Ordinal); + Assert.Contains("https://ai.azure.com", arguments, StringComparison.Ordinal); + Assert.Contains("--tenant " + TenantId, arguments, StringComparison.Ordinal); + } + + [Fact] + public async Task AzureDeveloperCliCredential_ReceivesTheScopeAndTenantFromConfiguration() + { + string argumentsFile = InstallFakeCli("azd", """{"token":"fake-azd-token","expiresOn":"2099-01-01T00:00:00Z"}"""); + TokenProvider provider = CredentialSelector.CreateTokenProvider( + CredentialSelector.Create(Settings("AzureDeveloperCliCredential", TenantId)), + SampleSettings.DefaultTokenScope, + new SecretRedactor()); + + string token = await provider(CancellationToken.None); + + Assert.Equal("fake-azd-token", token); + string arguments = File.ReadAllText(argumentsFile); + Assert.Contains("--scope " + SampleSettings.DefaultTokenScope, arguments, StringComparison.Ordinal); + Assert.Contains("--tenant-id " + TenantId, arguments, StringComparison.Ordinal); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task ManagedIdentityCredential_UsesTheUserAssignedClientIdWhenConfigured(bool userAssigned) + { + using LoopbackServer identityEndpoint = new LoopbackServer( + (string _) => LoopbackServer.Json("""{"access_token":"fake-mi-token","expires_on":"4070908800","resource":"https://ai.azure.com","token_type":"Bearer"}""")); + SetEnvironment("IDENTITY_ENDPOINT", identityEndpoint.BaseUrl + "/msi/token"); + SetEnvironment("IDENTITY_HEADER", "synthetic-identity-header"); + TokenProvider provider = CredentialSelector.CreateTokenProvider( + CredentialSelector.Create(Settings("ManagedIdentityCredential", clientId: userAssigned ? ClientId : null)), + SampleSettings.DefaultTokenScope, + new SecretRedactor()); + + string token = await provider(CancellationToken.None); + + Assert.Equal("fake-mi-token", token); + string head = Assert.Single(identityEndpoint.RequestHeads); + Assert.StartsWith("GET /msi/token?api-version=2019-08-01", head, StringComparison.Ordinal); + Assert.Contains("ai.azure.com", head, StringComparison.Ordinal); + Assert.Contains("x-identity-header: synthetic-identity-header", head, StringComparison.OrdinalIgnoreCase); + Assert.Equal(userAssigned, head.Contains("client_id=" + ClientId, StringComparison.Ordinal)); + } + + private void SetEnvironment(string name, string? value) + { + if (!_originalEnvironment.ContainsKey(name)) + { + _originalEnvironment[name] = Environment.GetEnvironmentVariable(name); + } + + Environment.SetEnvironmentVariable(name, value); + } + + /// Puts a fake CLI first on PATH; it records its arguments and prints the given JSON. + private string InstallFakeCli(string name, string outputJson) + { + Directory.CreateDirectory(_directory); + string variable = "FAKE_" + name.ToUpperInvariant() + "_ARGUMENTS"; + string argumentsFile = Path.Combine(_directory, name + ".arguments"); + SetEnvironment(variable, argumentsFile); + + if (OperatingSystem.IsWindows()) + { + File.WriteAllText( + Path.Combine(_directory, name + ".cmd"), + $"@echo off\r\necho %* >> \"%{variable}%\"\r\necho {outputJson}\r\n"); + } + else + { + string path = Path.Combine(_directory, name); + File.WriteAllText(path, $"#!/bin/sh\necho \"$@\" >> \"${variable}\"\necho '{outputJson}'\n"); + File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + } + + SetEnvironment("PATH", _directory + Path.PathSeparator + Environment.GetEnvironmentVariable("PATH")); + return argumentsFile; + } +} \ No newline at end of file diff --git a/samples/dotnet/tests/AnthropicStandardSdk.Tests/HelperBoundaryTests.cs b/samples/dotnet/tests/AnthropicStandardSdk.Tests/HelperBoundaryTests.cs new file mode 100644 index 0000000..ec1063f --- /dev/null +++ b/samples/dotnet/tests/AnthropicStandardSdk.Tests/HelperBoundaryTests.cs @@ -0,0 +1,52 @@ +using System; +using System.IO; +using System.Text.RegularExpressions; +using Xunit; + +namespace AnthropicStandardSdk.Tests; + +/// The generic helper stays generic: no identity library, no environment, no SDK credential provider. +public sealed class HelperBoundaryTests +{ + private static string SourceWithoutComments() + { + DirectoryInfo? directory = new DirectoryInfo(AppContext.BaseDirectory); + while (directory is not null) + { + string candidate = Path.Combine(directory.FullName, "src", "AnthropicStandardSdk", "ClientFactory.cs"); + if (File.Exists(candidate)) + { + string source = File.ReadAllText(candidate); + source = Regex.Replace(source, @"/\*.*?\*/", string.Empty, RegexOptions.Singleline); + return Regex.Replace(source, @"//.*$", string.Empty, RegexOptions.Multiline); + } + + directory = directory.Parent; + } + + throw new FileNotFoundException("ClientFactory.cs was not found above the test output directory."); + } + + [Theory] + [InlineData("Azure")] + [InlineData("Foundry")] + [InlineData("Environment.")] + [InlineData("GetEnvironmentVariable")] + [InlineData("Anthropic.Credentials")] + [InlineData("IAccessTokenProvider")] + [InlineData("TokenCache")] + [InlineData("Credentials =")] + public void ClientFactory_DoesNotUse(string fragment) + { + Assert.DoesNotContain(fragment, SourceWithoutComments(), StringComparison.Ordinal); + } + + [Theory] + [InlineData("ApiKey = null,")] + [InlineData("AuthToken = null,")] + [InlineData("AllowAutoRedirect = false,")] + public void ClientFactory_KeepsItsIsolationInvariants(string fragment) + { + Assert.Contains(fragment, SourceWithoutComments(), StringComparison.Ordinal); + } +} \ No newline at end of file diff --git a/samples/dotnet/tests/AnthropicStandardSdk.Tests/SampleRunnerTests.cs b/samples/dotnet/tests/AnthropicStandardSdk.Tests/SampleRunnerTests.cs new file mode 100644 index 0000000..5a19660 --- /dev/null +++ b/samples/dotnet/tests/AnthropicStandardSdk.Tests/SampleRunnerTests.cs @@ -0,0 +1,460 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Azure.Core; +using Azure.Identity; +using Xunit; + +namespace AnthropicStandardSdk.Tests; + +/// The sample entrypoint end to end: environment, credential wiring, real SDK, output, exit codes. +public sealed class SampleRunnerTests +{ + private const string Foundry = TestClients.FoundryUrl; + + // ANTHROPIC_BASE_URL selects the canonical profile; CLAUDE_BASE_URL alone selects the legacy one. + private const string CanonicalEnv = "ANTHROPIC_BASE_URL=" + Foundry + ";ANTHROPIC_MODEL=claude-sonnet-5-5"; + private const string BearerEnv = CanonicalEnv + ";AUTH_MODE=bearer"; + private const string KeyEnv = CanonicalEnv + ";AUTH_MODE=api_key"; + private const string LegacyEnv = "CLAUDE_BASE_URL=" + Foundry + ";CLAUDE_DEPLOYMENT_NAME=legacy-deployment"; + + // The other family's values, with canaries that must never be used or sent. + private const string LegacyCanaries = + "CLAUDE_BASE_URL=https://legacy-canary.invalid;CLAUDE_DEPLOYMENT_NAME=legacy-model-canary;CLAUDE_API_KEY=legacy-key-canary"; + + private const string NativeCanaries = "ANTHROPIC_MODEL=native-model-canary;ANTHROPIC_API_KEY=native-key-canary"; + + private static readonly string[] AllFamilyCanaries = + ["legacy-canary.invalid", "legacy-model-canary", "legacy-key-canary", "native-model-canary", "native-key-canary"]; + + private sealed record RunResult(int ExitCode, string Output, string Error); + + private sealed class FakeCredential : TokenCredential, IDisposable + { + private int _calls; + + public List Scopes { get; } = new List(); + + public bool Disposed { get; private set; } + + public Exception? Failure { get; init; } + + public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken) => + throw new NotSupportedException("The sample requests tokens asynchronously."); + + public override ValueTask GetTokenAsync( + TokenRequestContext requestContext, CancellationToken cancellationToken) + { + Scopes.Add(requestContext.Scopes); + if (Failure is not null) + { + throw Failure; + } + + return ValueTask.FromResult( + new AccessToken("fake-credential-token-" + Interlocked.Increment(ref _calls), DateTimeOffset.UtcNow.AddHours(1))); + } + + public void Dispose() => Disposed = true; + } + + private static Func Env(string spec) + { + Dictionary values = new Dictionary(StringComparer.Ordinal); + foreach (string pair in spec.Split(';', StringSplitOptions.RemoveEmptyEntries)) + { + int separator = pair.IndexOf('=', StringComparison.Ordinal); + values[pair.Substring(0, separator)] = pair.Substring(separator + 1); + } + + return (string name) => values.TryGetValue(name, out string? value) ? value : null; + } + + private static async Task Run( + string[] args, + string environment, + RecordingTransport transport, + FakeCredential? credential = null, + CancellationToken cancellationToken = default) + { + StringWriter output = new StringWriter(); + StringWriter error = new StringWriter(); + Func? factory = credential is null ? null : (SampleSettings _) => credential; + + int exitCode = await SampleRunner.RunAsync( + args, Env(environment), output, error, cancellationToken, transport, factory); + + return new RunResult( + exitCode, output.ToString().Replace("\r\n", "\n"), error.ToString().Replace("\r\n", "\n")); + } + + private static void AssertNoFamilyCanaries(RecordedRequest request) + { + string everything = request.Everything(); + foreach (string canary in AllFamilyCanaries) + { + Assert.DoesNotContain(canary, everything, StringComparison.OrdinalIgnoreCase); + } + } + + [Fact] + public async Task LegacyProfile_DefaultsToBearer_UsesItsOwnNames_AndPrintsTextThenUsage() + { + RecordingTransport transport = new RecordingTransport(); + FakeCredential credential = new FakeCredential(); + + RunResult result = await Run( + [], "CLAUDE_BASE_URL=" + Foundry + ";CLAUDE_DEPLOYMENT_NAME=my-deployment", transport, credential); + + Assert.Equal(0, result.ExitCode); + Assert.Equal("OK\nusage: input_tokens=11 output_tokens=5\n", result.Output); + Assert.Equal(string.Empty, result.Error); + RecordedRequest request = transport.Single; + Assert.Equal(Foundry + "/v1/messages", request.Url.AbsoluteUri); + Assert.Equal("Bearer fake-credential-token-1", request.Header("Authorization")); + Assert.Equal(await TestClients.SdkDefaultApiVersionAsync(), request.Header("anthropic-version")); + Assert.Equal("120", request.Header("X-Stainless-Timeout")); + JsonElement body = request.BodyJson(); + Assert.Equal("my-deployment", body.GetProperty("model").GetString()); + Assert.Equal(1024, body.GetProperty("max_tokens").GetInt32()); + Assert.Equal(new string[] { "https://ai.azure.com/.default" }, Assert.Single(credential.Scopes)); + AmbientEnvironment.AssertNoCanaryEgress(request); + } + + [Fact] + public async Task CanonicalProfile_WinsOverLegacy_AndHonorsScopeAndVersionOverrides() + { + RecordingTransport transport = new RecordingTransport(); + FakeCredential credential = new FakeCredential(); + string environment = + "ANTHROPIC_BASE_URL=https://preferred.example/anthropic;CLAUDE_BASE_URL=https://legacy.example/anthropic;" + + "ANTHROPIC_MODEL=preferred-model;CLAUDE_DEPLOYMENT_NAME=legacy-model;" + + "TOKEN_SCOPE=api://custom/.default;ANTHROPIC_API_VERSION=2023-06-01;AUTH_MODE=BEARER"; + + RunResult result = await Run([], environment, transport, credential); + + Assert.Equal(0, result.ExitCode); + RecordedRequest request = transport.Single; + Assert.Equal("https://preferred.example/anthropic/v1/messages", request.Url.AbsoluteUri); + Assert.Equal("preferred-model", request.BodyJson().GetProperty("model").GetString()); + Assert.Equal("2023-06-01", request.Header("anthropic-version")); + Assert.NotEqual("2023-06-01", await TestClients.SdkDefaultApiVersionAsync()); + Assert.Equal(new string[] { "api://custom/.default" }, Assert.Single(credential.Scopes)); + } + + [Fact] + public async Task CanonicalProfile_IgnoresEveryLegacyValue() + { + RecordingTransport transport = new RecordingTransport(); + FakeCredential credential = new FakeCredential(); + + RunResult result = await Run( + [], KeyEnv + ";ANTHROPIC_API_KEY=canonical-key;" + LegacyCanaries, transport, credential); + + Assert.Equal(0, result.ExitCode); + RecordedRequest request = transport.Single; + Assert.Equal(Foundry + "/v1/messages", request.Url.AbsoluteUri); + Assert.Equal("claude-sonnet-5-5", request.BodyJson().GetProperty("model").GetString()); + Assert.Equal("Bearer canonical-key", request.Header("Authorization")); + AssertNoFamilyCanaries(request); + Assert.Empty(credential.Scopes); + } + + [Fact] + public async Task LegacyProfile_IgnoresEveryAmbientNativeValue() + { + RecordingTransport transport = new RecordingTransport(); + + RunResult result = await Run( + [], LegacyEnv + ";AUTH_MODE=api_key;CLAUDE_API_KEY=legacy-key;" + NativeCanaries, transport); + + Assert.Equal(0, result.ExitCode); + RecordedRequest request = transport.Single; + Assert.Equal("legacy-deployment", request.BodyJson().GetProperty("model").GetString()); + Assert.Equal("Bearer legacy-key", request.Header("Authorization")); + AssertNoFamilyCanaries(request); + } + + [Fact] + public async Task LegacyBearerDefault_NeverUsesAnAmbientNativeKey() + { + RecordingTransport transport = new RecordingTransport(); + FakeCredential credential = new FakeCredential(); + + RunResult result = await Run([], LegacyEnv + ";" + NativeCanaries, transport, credential); + + Assert.Equal(0, result.ExitCode); + RecordedRequest request = transport.Single; + Assert.Equal("Bearer fake-credential-token-1", request.Header("Authorization")); + Assert.Equal("legacy-deployment", request.BodyJson().GetProperty("model").GetString()); + AssertNoFamilyCanaries(request); + } + + [Fact] + public async Task CanonicalBearer_WhenExplicit_IgnoresBothKeyFamilies() + { + RecordingTransport transport = new RecordingTransport(); + FakeCredential credential = new FakeCredential(); + + RunResult result = await Run( + [], BearerEnv + ";ANTHROPIC_API_KEY=native-key-canary;CLAUDE_API_KEY=legacy-key-canary", transport, credential); + + Assert.Equal(0, result.ExitCode); + RecordedRequest request = transport.Single; + Assert.Equal("Bearer fake-credential-token-1", request.Header("Authorization")); + AssertNoFamilyCanaries(request); + Assert.False(request.Has("x-api-key")); + } + + [Theory] + [InlineData(CanonicalEnv + ";AUTH_MODE=api_key;ANTHROPIC_API_KEY=canonical-key", "Authorization", "Bearer canonical-key")] + [InlineData(LegacyEnv + ";AUTH_MODE=api_key;CLAUDE_API_KEY=legacy-key", "Authorization", "Bearer legacy-key")] + [InlineData(CanonicalEnv + ";AUTH_MODE=api_key;ANTHROPIC_API_KEY=canonical-key;API_KEY_HEADER=x-api-key", "x-api-key", "canonical-key")] + [InlineData(CanonicalEnv + ";AUTH_MODE=api_key;ANTHROPIC_API_KEY=canonical-key;API_KEY_HEADER=api-key", "api-key", "canonical-key")] + public async Task ApiKeyMode_PlacesTheKeyInTheConfiguredHeader_WithoutAskingForAToken( + string environment, string header, string expected) + { + RecordingTransport transport = new RecordingTransport(); + FakeCredential credential = new FakeCredential(); + + RunResult result = await Run([], environment, transport, credential); + + Assert.Equal(0, result.ExitCode); + RecordedRequest request = transport.Single; + Assert.Equal(expected, request.Header(header)); + foreach (string closedName in new string[] { "Authorization", "x-api-key", "api-key" }) + { + Assert.Equal( + string.Equals(closedName, header, StringComparison.OrdinalIgnoreCase), + request.Has(closedName)); + } + + Assert.Equal(await TestClients.SdkDefaultApiVersionAsync(), request.Header("anthropic-version")); + Assert.Equal("120", request.Header("X-Stainless-Timeout")); + Assert.Empty(credential.Scopes); + AmbientEnvironment.AssertNoCanaryEgress(request); + } + + [Fact] + public async Task Stream_PrintsTextAsItArrivesThenUsage() + { + RecordingTransport transport = new RecordingTransport(); + transport.Enqueue(Responses.Stream("Hel", "lo")); + + RunResult result = await Run(["--stream", "Say", "hi"], BearerEnv, transport, new FakeCredential()); + + Assert.Equal(0, result.ExitCode); + Assert.Equal("Hello\nusage: input_tokens=11 output_tokens=7\n", result.Output); + Assert.Equal(string.Empty, result.Error); + RecordedRequest request = transport.Single; + Assert.True(request.BodyJson().GetProperty("stream").GetBoolean()); + Assert.Contains("Say hi", request.Body, StringComparison.Ordinal); + Assert.Equal("120", request.Header("X-Stainless-Timeout")); + } + + [Fact] + public async Task PromptWordsAreJoined_AndAfterDoubleDashOptionsAreLiteral() + { + RecordingTransport transport = new RecordingTransport(); + + RunResult result = await Run(["--", "--stream", "is", "text"], BearerEnv, transport, new FakeCredential()); + + Assert.Equal(0, result.ExitCode); + RecordedRequest request = transport.Single; + Assert.False(request.BodyJson().TryGetProperty("stream", out JsonElement _)); + Assert.Contains("--stream is text", request.Body, StringComparison.Ordinal); + } + + [Fact] + public async Task ThinkingOnlyResponse_IsAFailure_NotASuccess() + { + RecordingTransport transport = new RecordingTransport(); + transport.Enqueue(Responses.ThinkingOnly()); + + RunResult result = await Run([], BearerEnv, transport, new FakeCredential()); + + Assert.Equal(SampleRunner.ExitFailure, result.ExitCode); + Assert.Equal(string.Empty, result.Output); + Assert.Contains("UnusableResponseException", result.Error, StringComparison.Ordinal); + Assert.Contains("no text", result.Error, StringComparison.Ordinal); + Assert.Contains("ThinkingBlock", result.Error, StringComparison.Ordinal); + } + + [Theory] + [InlineData("")] + [InlineData(" \n ")] + public async Task EmptyOrBlankText_IsAFailure(string text) + { + RecordingTransport transport = new RecordingTransport(); + transport.Enqueue(Responses.Message(text)); + + RunResult result = await Run([], BearerEnv, transport, new FakeCredential()); + + Assert.Equal(SampleRunner.ExitFailure, result.ExitCode); + Assert.Equal(string.Empty, result.Output); + Assert.Contains("UnusableResponseException", result.Error, StringComparison.Ordinal); + } + + [Fact] + public async Task StreamWithoutTextOrWithoutMessageStop_IsAFailure() + { + RecordingTransport silent = new RecordingTransport(); + silent.Enqueue(Responses.Stream(string.Empty)); + RunResult noText = await Run(["--stream"], BearerEnv, silent, new FakeCredential()); + + RecordingTransport truncated = new RecordingTransport(); + truncated.Enqueue(Responses.TruncatedStream("partial")); + RunResult cutOff = await Run(["--stream"], BearerEnv, truncated, new FakeCredential()); + + Assert.Equal(SampleRunner.ExitFailure, noText.ExitCode); + Assert.Contains("no text", noText.Error, StringComparison.Ordinal); + Assert.Equal(SampleRunner.ExitFailure, cutOff.ExitCode); + Assert.Contains("before message_stop", cutOff.Error, StringComparison.Ordinal); + Assert.DoesNotContain("usage:", cutOff.Output, StringComparison.Ordinal); + } + + [Theory] + [InlineData(HttpStatusCode.Unauthorized, "AnthropicUnauthorizedException (HTTP 401)")] + [InlineData(HttpStatusCode.Forbidden, "AnthropicForbiddenException (HTTP 403)")] + public async Task AuthRejection_ShowsTypedStatus_AndNeverTheToken(HttpStatusCode status, string expected) + { + RecordingTransport transport = new RecordingTransport(); + transport.Enqueue(Responses.Error( + status, "authentication_error", "denied for Bearer fake-credential-token-1 and fake-credential-token-1")); + + RunResult result = await Run([], BearerEnv, transport, new FakeCredential()); + + Assert.Equal(SampleRunner.ExitFailure, result.ExitCode); + Assert.Equal(string.Empty, result.Output); + Assert.Contains(expected, result.Error, StringComparison.Ordinal); + Assert.Contains("[redacted]", result.Error, StringComparison.Ordinal); + Assert.DoesNotContain("fake-credential-token", result.Error, StringComparison.Ordinal); + } + + [Fact] + public async Task ApiKeyIsRedactedFromServerErrors() + { + RecordingTransport transport = new RecordingTransport(); + transport.Enqueue(Responses.Error(HttpStatusCode.Unauthorized, "authentication_error", "bad key super-secret-key-value")); + + RunResult result = await Run([], KeyEnv + ";ANTHROPIC_API_KEY=super-secret-key-value", transport); + + Assert.Equal(SampleRunner.ExitFailure, result.ExitCode); + Assert.Contains("[redacted]", result.Error, StringComparison.Ordinal); + Assert.DoesNotContain("super-secret-key-value", result.Error, StringComparison.Ordinal); + } + + [Fact] + public async Task CredentialFailure_ShowsItsTypeAndSendsNothing() + { + RecordingTransport transport = new RecordingTransport(); + FakeCredential credential = new FakeCredential + { + Failure = new CredentialUnavailableException("synthetic CLI is not signed in"), + }; + + RunResult result = await Run([], BearerEnv, transport, credential); + + Assert.Equal(SampleRunner.ExitFailure, result.ExitCode); + Assert.Contains("CredentialUnavailableException: synthetic CLI is not signed in", result.Error, StringComparison.Ordinal); + Assert.Empty(transport.Requests); + } + + [Fact] + public async Task TheCallerDisposesTheCredential_OnSuccessAndOnFailure() + { + FakeCredential succeeded = new FakeCredential(); + await Run([], BearerEnv, new RecordingTransport(), succeeded); + + FakeCredential failed = new FakeCredential(); + RecordingTransport rejecting = new RecordingTransport(); + rejecting.Enqueue(Responses.Error(HttpStatusCode.Forbidden, "permission_error", "no")); + await Run([], BearerEnv, rejecting, failed); + + Assert.True(succeeded.Disposed); + Assert.True(failed.Disposed); + } + + [Theory] + [InlineData("ANTHROPIC_MODEL=m", "ANTHROPIC_BASE_URL")] + [InlineData("ANTHROPIC_BASE_URL=https://x.example;AUTH_MODE=bearer", "ANTHROPIC_MODEL")] + [InlineData(CanonicalEnv + ";AUTH_MODE=oauth", "AUTH_MODE")] + [InlineData(KeyEnv, "ANTHROPIC_API_KEY")] + [InlineData(BearerEnv + ";AZURE_TOKEN_CREDENTIALS=DefaultAzureCredential", "AZURE_TOKEN_CREDENTIALS")] + [InlineData("ANTHROPIC_BASE_URL=http://example.com;ANTHROPIC_MODEL=m;AUTH_MODE=api_key;ANTHROPIC_API_KEY=k", "https")] + public async Task InvalidConfiguration_ExitsWithUsageStatusAndSendsNothing(string environment, string expected) + { + RecordingTransport transport = new RecordingTransport(); + + RunResult result = await Run([], environment, transport, new FakeCredential()); + + Assert.Equal(SampleRunner.ExitUsage, result.ExitCode); + Assert.Equal(string.Empty, result.Output); + Assert.Contains(expected, result.Error, StringComparison.Ordinal); + Assert.Empty(transport.Requests); + } + + [Theory] + // The canonical URL needs the canonical model and key: the legacy names are never a fallback. + [InlineData("ANTHROPIC_BASE_URL=" + Foundry + ";CLAUDE_DEPLOYMENT_NAME=legacy-model;AUTH_MODE=bearer", "ANTHROPIC_MODEL")] + [InlineData(CanonicalEnv + ";AUTH_MODE=api_key;CLAUDE_API_KEY=legacy-key", "ANTHROPIC_API_KEY")] + // The canonical profile never defaults to an identity token, even when legacy values are also present. + [InlineData(CanonicalEnv + ";ANTHROPIC_API_KEY=native-key;CLAUDE_API_KEY=legacy-key", "AUTH_MODE")] + [InlineData(CanonicalEnv + ";" + LegacyEnv, "AUTH_MODE")] + // A legacy-only URL needs the legacy model and key: ambient native names are never a fallback. + [InlineData("CLAUDE_BASE_URL=" + Foundry + ";ANTHROPIC_MODEL=native-model", "CLAUDE_DEPLOYMENT_NAME")] + [InlineData(LegacyEnv + ";AUTH_MODE=api_key;ANTHROPIC_API_KEY=native-key", "CLAUDE_API_KEY")] + public async Task ProfilesAreNeverMixed_AndTheErrorSaysWhichVariableIsMissing(string environment, string expected) + { + RecordingTransport transport = new RecordingTransport(); + FakeCredential credential = new FakeCredential(); + + RunResult result = await Run([], environment, transport, credential); + + Assert.Equal(SampleRunner.ExitUsage, result.ExitCode); + Assert.Equal(string.Empty, result.Output); + Assert.Contains(expected, result.Error, StringComparison.Ordinal); + Assert.Empty(transport.Requests); + Assert.Empty(credential.Scopes); + Assert.False(credential.Disposed, "no credential may be created for an invalid configuration"); + } + + [Fact] + public async Task HelpAndUnknownOptions() + { + RunResult help = await Run(["--help"], string.Empty, new RecordingTransport()); + RunResult unknown = await Run(["--verbose"], BearerEnv, new RecordingTransport()); + + Assert.Equal(SampleRunner.ExitOk, help.ExitCode); + Assert.Contains("usage:", help.Output, StringComparison.Ordinal); + Assert.Equal(SampleRunner.ExitUsage, unknown.ExitCode); + Assert.Contains("unknown option --verbose", unknown.Error, StringComparison.Ordinal); + } + + [Fact] + public async Task Cancellation_StopsTheCallAndReportsAFailure() + { + RecordingTransport transport = new RecordingTransport(); + TaskCompletionSource inFlight = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + transport.Enqueue(async (RecordedRequest _, CancellationToken cancellationToken) => + { + inFlight.TrySetResult(); + await Task.Delay(System.Threading.Timeout.Infinite, cancellationToken).ConfigureAwait(false); + throw new InvalidOperationException("unreachable"); + }); + using CancellationTokenSource cancellation = new CancellationTokenSource(); + + Task run = Run([], BearerEnv, transport, new FakeCredential(), cancellation.Token); + await inFlight.Task.WaitAsync(TimeSpan.FromSeconds(10)); + cancellation.Cancel(); + RunResult result = await run; + + Assert.Equal(SampleRunner.ExitFailure, result.ExitCode); + Assert.Contains("CanceledException", result.Error, StringComparison.Ordinal); + Assert.Single(transport.Requests); + } +} \ No newline at end of file diff --git a/samples/dotnet/tests/AnthropicStandardSdk.Tests/SdkBehaviorProbeTests.cs b/samples/dotnet/tests/AnthropicStandardSdk.Tests/SdkBehaviorProbeTests.cs new file mode 100644 index 0000000..eedb5da --- /dev/null +++ b/samples/dotnet/tests/AnthropicStandardSdk.Tests/SdkBehaviorProbeTests.cs @@ -0,0 +1,125 @@ +using System; +using System.Net; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +using Anthropic; +using Anthropic.Core; +using Anthropic.Credentials; +using Xunit; + +namespace AnthropicStandardSdk.Tests; + +/// +/// Records how the unmodified Anthropic 13.3.0 client behaves with the hostile ambient environment. +/// They explain why clears both credential slots and installs its own last +/// handler instead of using the SDK credential options. If one fails after an SDK upgrade, revisit +/// the helper and its documentation. +/// +public sealed class SdkBehaviorProbeTests +{ + private static HttpClient Http(RecordingTransport transport) => + new HttpClient(transport) { Timeout = System.Threading.Timeout.InfiniteTimeSpan }; + + [Fact] + public async Task StandardApiKey_IsAuthorizationBearer_NotTheXApiKeyHeader() + { + RecordingTransport transport = new RecordingTransport(); + using AnthropicClient client = new AnthropicClient(new ClientOptions + { + BaseUrl = TestClients.FoundryUrl, + ApiKey = "synthetic-key", + HttpClient = Http(transport), + MaxRetries = 0, + }); + + await client.Messages.Create(TestClients.Params()); + + RecordedRequest request = transport.Single; + Assert.Equal("Bearer synthetic-key", request.Header("Authorization")); + Assert.DoesNotContain("synthetic-key", request.Header("x-api-key") ?? string.Empty, StringComparison.Ordinal); + } + + [Fact] + public async Task ClearingOnlyApiKey_LeavesTheAmbientAuthTokenInPlace() + { + RecordingTransport transport = new RecordingTransport(); + using AnthropicClient client = new AnthropicClient(new ClientOptions + { + BaseUrl = TestClients.FoundryUrl, + ApiKey = null, + HttpClient = Http(transport), + MaxRetries = 0, + }); + + await client.Messages.Create(TestClients.Params()); + + Assert.Equal("Bearer " + AmbientEnvironment.AuthToken, transport.Single.Header("Authorization")); + } + + [Fact] + public async Task ClearingBothSlots_StopsAmbientKeysAndTokens_ButNotAmbientCustomHeaders() + { + RecordingTransport transport = new RecordingTransport(); + using AnthropicClient client = new AnthropicClient(new ClientOptions + { + BaseUrl = TestClients.FoundryUrl, + ApiKey = null, + AuthToken = null, + HttpClient = Http(transport), + MaxRetries = 0, + }); + + await client.Messages.Create(TestClients.Params()); + + RecordedRequest request = transport.Single; + Assert.False(request.Has("Authorization")); + Assert.Equal(AmbientEnvironment.CustomApiKey, request.Header("x-api-key")); + Assert.Equal(AmbientEnvironment.CustomApiKeyAlternate, request.Header("api-key")); + } + + [Fact] + public async Task CredentialsProvider_AddsTheNativeOAuthBetaToEveryRequest_AndForcesARefreshAfter401() + { + RecordingTransport transport = new RecordingTransport(); + transport.Enqueue(Responses.Error(HttpStatusCode.Unauthorized, "authentication_error", "expired")); + RenewingProvider provider = new RenewingProvider(); + using AnthropicClient client = new AnthropicClient(new ClientOptions + { + BaseUrl = TestClients.FoundryUrl, + Credentials = provider, + HttpClient = Http(transport), + MaxRetries = 0, + }); + + await client.Messages.Create(TestClients.Params()); + + System.Collections.Generic.IReadOnlyList requests = transport.Requests; + Assert.Equal(2, requests.Count); + Assert.Equal("Bearer provider-token-1", requests[0].Header("Authorization")); + Assert.Equal("Bearer provider-token-2", requests[1].Header("Authorization")); + Assert.All(requests, (RecordedRequest request) => + Assert.Contains("oauth-2025-04-20", request.Header("anthropic-beta"), StringComparison.Ordinal)); + Assert.Equal(new bool[] { false, true }, provider.ForceRefreshFlags); + } + + private sealed class RenewingProvider : IAccessTokenProvider + { + private int _calls; + + public System.Collections.Generic.List ForceRefreshFlags { get; } = new System.Collections.Generic.List(); + + public ValueTask GetTokenAsync( + bool forceRefresh = false, CancellationToken cancellationToken = default) + { + ForceRefreshFlags.Add(forceRefresh); + long expiresAt = DateTimeOffset.UtcNow.AddMinutes(10).ToUnixTimeSeconds(); + return ValueTask.FromResult( + new Anthropic.Credentials.AccessToken("provider-token-" + Interlocked.Increment(ref _calls), expiresAt)); + } + + public void Dispose() + { + } + } +} \ No newline at end of file diff --git a/samples/dotnet/tests/AnthropicStandardSdk.Tests/TestSupport.cs b/samples/dotnet/tests/AnthropicStandardSdk.Tests/TestSupport.cs new file mode 100644 index 0000000..99548cd --- /dev/null +++ b/samples/dotnet/tests/AnthropicStandardSdk.Tests/TestSupport.cs @@ -0,0 +1,503 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Anthropic; +using Anthropic.Core; +using Anthropic.Models.Messages; + +namespace AnthropicStandardSdk.Tests; + +/// +/// Hostile ambient environment for the whole test process. It is installed before any SDK type is +/// touched (the SDK reads some of these once, statically), so every test proves that none of it +/// reaches the wire. +/// +internal static class AmbientEnvironment +{ + public const string ApiKey = "canary-ambient-api-key"; + public const string AuthToken = "canary-ambient-auth-token"; + public const string BaseHost = "canary-ambient-base.invalid"; + public const string Profile = "canary-ambient-profile"; + public const string IdentityToken = "canary-ambient-identity-token"; + public const string CustomApiKey = "canary-ambient-custom-x-api-key"; + public const string CustomApiKeyAlternate = "canary-ambient-custom-api-key"; + public const string ExtraAuthorization = "canary-extra-authorization"; + public const string ExtraApiKey = "canary-extra-key"; + + public static readonly string[] AllCanaries = + [ + ApiKey, AuthToken, BaseHost, Profile, IdentityToken, CustomApiKey, CustomApiKeyAlternate, ExtraAuthorization, ExtraApiKey, + ]; + +#pragma warning disable CA2255 // The ambient environment must exist before any test or SDK type runs. + [ModuleInitializer] + internal static void Initialize() + { + Environment.SetEnvironmentVariable("ANTHROPIC_API_KEY", ApiKey); + Environment.SetEnvironmentVariable("ANTHROPIC_AUTH_TOKEN", AuthToken); + Environment.SetEnvironmentVariable("ANTHROPIC_BASE_URL", "https://" + BaseHost); + Environment.SetEnvironmentVariable("ANTHROPIC_PROFILE", Profile); + Environment.SetEnvironmentVariable("ANTHROPIC_CONFIG_DIR", Path.Combine(Path.GetTempPath(), Profile)); + Environment.SetEnvironmentVariable("ANTHROPIC_IDENTITY_TOKEN", IdentityToken); + Environment.SetEnvironmentVariable("ANTHROPIC_FEDERATION_RULE_ID", "canary-ambient-rule"); + Environment.SetEnvironmentVariable("ANTHROPIC_ORGANIZATION_ID", "canary-ambient-organization"); + // The SDK refuses to build a request that has both a custom Authorization header and its own + // credential, so the ambient custom headers use the other two credential header names; + // Authorization injection is covered through ExtraHeaders instead. + Environment.SetEnvironmentVariable( + "ANTHROPIC_CUSTOM_HEADERS", $"x-api-key: {CustomApiKey}\napi-key: {CustomApiKeyAlternate}"); + } +#pragma warning restore CA2255 + + public static void AssertNoCanaryEgress(RecordedRequest request) + { + string everything = request.Everything(); + foreach (string canary in AllCanaries) + { + Xunit.Assert.DoesNotContain(canary, everything, StringComparison.OrdinalIgnoreCase); + } + } +} + +internal sealed class RecordedRequest +{ + public required HttpMethod Method { get; init; } + + public required Uri Url { get; init; } + + public required IReadOnlyDictionary Headers { get; init; } + + public required string Body { get; init; } + + public bool Has(string name) => Headers.ContainsKey(name); + + public string? Header(string name) => Headers.TryGetValue(name, out string? value) ? value : null; + + public string Everything() + { + StringBuilder text = new StringBuilder(); + text.Append(Method).Append(' ').Append(Url).Append('\n'); + foreach (KeyValuePair header in Headers) + { + text.Append(header.Key).Append(": ").Append(header.Value).Append('\n'); + } + + return text.Append(Body).ToString(); + } + + public JsonElement BodyJson() + { + using JsonDocument document = JsonDocument.Parse(Body); + return document.RootElement.Clone(); + } +} + +internal delegate Task Responder(RecordedRequest request, CancellationToken cancellationToken); + +/// The lowest transport the real SDK talks to; records every request that reaches it. +internal sealed class RecordingTransport : HttpMessageHandler +{ + private readonly object _gate = new object(); + private readonly Queue _responders = new Queue(); + private readonly List _requests = new List(); + + public IReadOnlyList Requests + { + get + { + lock (_gate) + { + return _requests.ToArray(); + } + } + } + + public RecordedRequest Single + { + get + { + IReadOnlyList requests = Requests; + Xunit.Assert.Single(requests); + return requests[0]; + } + } + + public void Enqueue(HttpResponseMessage response) => + Enqueue((RecordedRequest _, CancellationToken _) => Task.FromResult(response)); + + public void Enqueue(Responder responder) + { + lock (_gate) + { + _responders.Enqueue(responder); + } + } + + protected override async Task SendAsync( + HttpRequestMessage request, CancellationToken cancellationToken) + { + Dictionary headers = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (KeyValuePair> header in request.Headers) + { + headers[header.Key] = string.Join(", ", header.Value); + } + + if (request.Content is not null) + { + foreach (KeyValuePair> header in request.Content.Headers) + { + headers[header.Key] = string.Join(", ", header.Value); + } + } + + string body = request.Content is null + ? string.Empty + : await request.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + RecordedRequest recorded = new RecordedRequest + { + Method = request.Method, + Url = request.RequestUri!, + Headers = headers, + Body = body, + }; + + Responder? responder = null; + lock (_gate) + { + _requests.Add(recorded); + if (_responders.Count > 0) + { + responder = _responders.Dequeue(); + } + } + + return responder is null + ? Responses.Message() + : await responder(recorded, cancellationToken).ConfigureAwait(false); + } +} + +internal static class Responses +{ + public static HttpResponseMessage Message(string text = "OK", long inputTokens = 11, long outputTokens = 5) => + Json(HttpStatusCode.OK, MessageJson(JsonSerializer.Serialize(text), inputTokens, outputTokens)); + + public static HttpResponseMessage ThinkingOnly() => + Json(HttpStatusCode.OK, """ + {"id":"msg_test","type":"message","role":"assistant","model":"test-model", + "content":[{"type":"thinking","thinking":"pondering","signature":"sig"}], + "stop_reason":"max_tokens","stop_sequence":null,"usage":{"input_tokens":11,"output_tokens":1024}} + """); + + public static HttpResponseMessage Error(HttpStatusCode status, string type, string message) => + Json(status, $$$"""{"type":"error","error":{"type":"{{{type}}}","message":"{{{message}}}"}}"""); + + public static HttpResponseMessage Redirect(HttpStatusCode status, string location) + { + HttpResponseMessage response = new HttpResponseMessage(status); + response.Headers.TryAddWithoutValidation("Location", location); + return response; + } + + /// A server-sent-event stream with one text delta per argument. + public static HttpResponseMessage Stream(params string[] textDeltas) => BuildStream(true, textDeltas); + + /// Like but the connection ends before message_stop. + public static HttpResponseMessage TruncatedStream(params string[] textDeltas) => BuildStream(false, textDeltas); + + private static HttpResponseMessage BuildStream(bool includeStop, string[] textDeltas) + { + StringBuilder sse = new StringBuilder(); + sse.Append(Event("message_start", """ + {"type":"message_start","message":{"id":"msg_stream","type":"message","role":"assistant","model":"test-model","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":11,"output_tokens":1}}} + """)); + sse.Append(Event("content_block_start", """{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}""")); + foreach (string delta in textDeltas) + { + sse.Append(Event( + "content_block_delta", + $$$"""{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":{{{JsonSerializer.Serialize(delta)}}}}}""")); + } + + sse.Append(Event("content_block_stop", """{"type":"content_block_stop","index":0}""")); + sse.Append(Event("message_delta", """{"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":7}}""")); + if (includeStop) + { + sse.Append(Event("message_stop", """{"type":"message_stop"}""")); + } + + return new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent(sse.ToString(), Encoding.UTF8, "text/event-stream"), + }; + } + + public static string MessageJson(string textLiteral, long inputTokens, long outputTokens) => + $$$""" + {"id":"msg_test","type":"message","role":"assistant","model":"test-model", + "content":[{"type":"text","text":{{{textLiteral}}}}], + "stop_reason":"end_turn","stop_sequence":null, + "usage":{"input_tokens":{{{inputTokens}}},"output_tokens":{{{outputTokens}}}}} + """; + + private static string Event(string name, string data) => $"event: {name}\ndata: {data.Trim()}\n\n"; + + private static HttpResponseMessage Json(HttpStatusCode status, string json) => + new HttpResponseMessage(status) { Content = new StringContent(json, Encoding.UTF8, "application/json") }; +} + +/// A token provider that hands out a different token per call, like a renewing credential. +internal sealed class RotatingTokens +{ + private int _calls; + + public int Calls => Volatile.Read(ref _calls); + + public TokenProvider Provider => (CancellationToken cancellationToken) => + { + cancellationToken.ThrowIfCancellationRequested(); + return ValueTask.FromResult("rotating-token-" + Interlocked.Increment(ref _calls)); + }; +} + +internal static class TestClients +{ + public const string FoundryUrl = "https://example-resource.services.ai.azure.com/anthropic"; + public const string NativeUrl = "https://api.anthropic.com"; + public const string Model = "claude-sonnet-5-5"; + + public static AnthropicClient Bearer( + RecordingTransport transport, + TokenProvider provider, + string baseUrl = FoundryUrl, + string? apiVersion = null, + int? maxRetries = 0, + TimeSpan? timeout = null) => + ClientFactory.Create(new ClientFactoryOptions + { + BaseUrl = baseUrl, + TokenProvider = provider, + ApiVersion = apiVersion, + MaxRetries = maxRetries, + Timeout = timeout, + Transport = transport, + }); + + public static AnthropicClient ApiKey( + RecordingTransport transport, + string key = "synthetic-resource-key", + string header = "x-api-key", + string baseUrl = FoundryUrl, + string? apiVersion = null, + int? maxRetries = 0) => + ClientFactory.Create(new ClientFactoryOptions + { + BaseUrl = baseUrl, + ApiKey = key, + ApiKeyHeader = header, + ApiVersion = apiVersion, + MaxRetries = maxRetries, + Transport = transport, + }); + + /// The anthropic-version an unconfigured standard SDK client sends. + public static Task SdkDefaultApiVersionAsync() => SdkDefaultHeaderAsync("anthropic-version"); + + /// A header an unconfigured standard SDK client sends for . + public static async Task SdkDefaultHeaderAsync(string name) + { + RecordingTransport baseline = new RecordingTransport(); + using AnthropicClient plain = new AnthropicClient(new ClientOptions + { + BaseUrl = FoundryUrl, + ApiKey = "baseline-key", + HttpClient = new HttpClient(baseline) { Timeout = System.Threading.Timeout.InfiniteTimeSpan }, + MaxRetries = 0, + }); + await plain.Messages.Create(Params()).ConfigureAwait(false); + return baseline.Single.Header(name)!; + } + + public static MessageCreateParams Params(string model = Model) => new MessageCreateParams + { + Model = model, + MaxTokens = 1024, + Messages = [new UserMessageParam("Hello")], + }; +} + +/// A minimal real HTTP server on the loopback interface; one response per connection. +internal sealed class LoopbackServer : IDisposable +{ + private readonly TcpListener _listener; + private readonly CancellationTokenSource _stop = new CancellationTokenSource(); + private readonly Func _respond; + private readonly object _gate = new object(); + private readonly List _requestHeads = new List(); + private readonly Task _loop; + + public LoopbackServer(Func respond) + { + _respond = respond; + _listener = new TcpListener(IPAddress.Loopback, 0); + _listener.Start(); + Port = ((IPEndPoint)_listener.LocalEndpoint).Port; + _loop = Task.Run(AcceptLoopAsync); + } + + public int Port { get; } + + public string BaseUrl => $"http://127.0.0.1:{Port}"; + + public IReadOnlyList RequestHeads + { + get + { + lock (_gate) + { + return _requestHeads.ToArray(); + } + } + } + + public static byte[] Raw(string statusLine, params string[] headers) + { + StringBuilder text = new StringBuilder(); + text.Append("HTTP/1.1 ").Append(statusLine).Append("\r\n"); + foreach (string header in headers) + { + text.Append(header).Append("\r\n"); + } + + text.Append("Content-Length: 0\r\nConnection: close\r\n\r\n"); + return Encoding.ASCII.GetBytes(text.ToString()); + } + + public static byte[] Json(string json) + { + byte[] body = Encoding.UTF8.GetBytes(json); + string head = $"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {body.Length}\r\nConnection: close\r\n\r\n"; + byte[] headBytes = Encoding.ASCII.GetBytes(head); + byte[] all = new byte[headBytes.Length + body.Length]; + headBytes.CopyTo(all, 0); + body.CopyTo(all, headBytes.Length); + return all; + } + + public void Dispose() + { + _stop.Cancel(); + _listener.Stop(); + try + { + _loop.Wait(TimeSpan.FromSeconds(5)); + } + catch (AggregateException) + { + } + + _stop.Dispose(); + } + + private async Task AcceptLoopAsync() + { + while (!_stop.IsCancellationRequested) + { + TcpClient client; + try + { + client = await _listener.AcceptTcpClientAsync(_stop.Token).ConfigureAwait(false); + } + catch (Exception exception) when (exception is OperationCanceledException or SocketException or ObjectDisposedException) + { + return; + } + + _ = Task.Run(() => HandleAsync(client)); + } + } + + private async Task HandleAsync(TcpClient client) + { + using (client) + { + try + { + NetworkStream stream = client.GetStream(); + MemoryStream received = new MemoryStream(); + byte[] buffer = new byte[4096]; + int headEnd = -1; + while (headEnd < 0) + { + int read = await stream.ReadAsync(buffer, _stop.Token).ConfigureAwait(false); + if (read == 0) + { + return; + } + + received.Write(buffer, 0, read); + headEnd = IndexOfHeadEnd(received.GetBuffer(), (int)received.Length); + } + + string head = Encoding.ASCII.GetString(received.GetBuffer(), 0, headEnd); + int contentLength = ContentLength(head); + while (received.Length < headEnd + 4 + contentLength) + { + int read = await stream.ReadAsync(buffer, _stop.Token).ConfigureAwait(false); + if (read == 0) + { + break; + } + + received.Write(buffer, 0, read); + } + + lock (_gate) + { + _requestHeads.Add(head); + } + + byte[] response = _respond(head); + await stream.WriteAsync(response, _stop.Token).ConfigureAwait(false); + await stream.FlushAsync(_stop.Token).ConfigureAwait(false); + } + catch (Exception exception) when (exception is IOException or SocketException or OperationCanceledException or ObjectDisposedException) + { + } + } + } + + private static int IndexOfHeadEnd(byte[] data, int length) + { + for (int i = 0; i + 3 < length; i++) + { + if (data[i] == '\r' && data[i + 1] == '\n' && data[i + 2] == '\r' && data[i + 3] == '\n') + { + return i; + } + } + + return -1; + } + + private static int ContentLength(string head) + { + foreach (string line in head.Split("\r\n")) + { + if (line.StartsWith("content-length:", StringComparison.OrdinalIgnoreCase)) + { + return int.Parse(line.Substring("content-length:".Length).Trim(), System.Globalization.CultureInfo.InvariantCulture); + } + } + + return 0; + } +} \ No newline at end of file diff --git a/samples/go/.gitignore b/samples/go/.gitignore new file mode 100644 index 0000000..300505e --- /dev/null +++ b/samples/go/.gitignore @@ -0,0 +1,4 @@ +/main +/main.exe +*.test +*.test.exe \ No newline at end of file diff --git a/samples/go/README.md b/samples/go/README.md new file mode 100644 index 0000000..8b24bbe --- /dev/null +++ b/samples/go/README.md @@ -0,0 +1,149 @@ +# Go sample: standard Anthropic SDK with explicit authentication + +Calls a Claude model with the stock `github.com/anthropics/anthropic-sdk-go/v2` client. The credential is +chosen explicitly and resolved again for every HTTP attempt: a Microsoft Entra ID bearer token (default) or an +API key. There is no provider-specific SDK package; `clientauth.CreateClient` returns a plain +`anthropic.Client`, so `Messages.New`, `Messages.NewStreaming`, retries and context cancellation work as +documented by the SDK. + +| Path | Purpose | +| --- | --- | +| `clientauth/client_auth.go` | Generic helper: `CreateClient(Options)` builds the client (no Azure code, no environment access). | +| `credential.go` | Selects one Azure Identity credential and turns it into a token provider. | +| `settings.go`, `sample_client.go` | Read the environment and build the client for the sample. | +| `main.go` | Command-line entrypoint. | +| `*_test.go`, `internal/testserver` | Offline tests: the real SDK against loopback servers, with the standard `testing` package. | + +## Requirements + +Go 1.25 or later. Tested with Go 1.27, `anthropic-sdk-go/v2` v2.4.0, `azidentity` v1.15.0 and `azcore` v1.23.3. + +## Run + +```powershell +cd samples\go + +$env:ANTHROPIC_BASE_URL = "https://.services.ai.azure.com/anthropic" # or https://api.anthropic.com +$env:ANTHROPIC_MODEL = "" +$env:AUTH_MODE = "bearer" # required with ANTHROPIC_BASE_URL: bearer or api_key +az login # the default credential is the Azure CLI + +go run . # prints the reply text and token usage +go run . -stream # streams the reply text as it arrives +go run . "Your prompt" # any other prompt (flags go before the prompt) +``` + +```bash +cd samples/go +export ANTHROPIC_BASE_URL="https://.services.ai.azure.com/anthropic" +export ANTHROPIC_MODEL="" +export AUTH_MODE=bearer +go run . +``` + +The starter kit's legacy variables work too: `CLAUDE_BASE_URL` and `CLAUDE_DEPLOYMENT_NAME` (see Configuration). + +The command exits 0 only when the reply contains text. A reply with only thinking, an empty reply, a +configuration problem or any request error exits nonzero (2 for a command-line usage error). Errors report the +HTTP status and error type, never the credential, the endpoint, the model name or the response body. + +## Configuration + +The sample reads one of two variable families and never mixes them, so a URL, a model and a key from different +families cannot be combined: an ambient `ANTHROPIC_BASE_URL` for the native API cannot receive an Azure token, and +an ambient first-party `ANTHROPIC_API_KEY` cannot be sent to another endpoint. + +| | Canonical profile | Legacy profile (starter kit) | +| --- | --- | --- | +| Selected by | `ANTHROPIC_BASE_URL`; it wins when both base URLs are set | `CLAUDE_BASE_URL`, when `ANTHROPIC_BASE_URL` is unset | +| Model | `ANTHROPIC_MODEL`, required | `CLAUDE_DEPLOYMENT_NAME`, required | +| `AUTH_MODE` | must be set explicitly: `bearer` or `api_key` | `bearer` when unset, or `api_key` | +| Key for `api_key` | `ANTHROPIC_API_KEY` only | `CLAUDE_API_KEY` only | + +A missing model or key is an error that names the variable the selected profile needs; the other family's +variables are never a fallback. + +These settings apply to both profiles: + +| Variable | Default | Meaning | +| --- | --- | --- | +| `AZURE_TOKEN_CREDENTIALS` | `AzureCliCredential` | `AzureCliCredential`, `AzureDeveloperCliCredential` or `ManagedIdentityCredential`. Exactly one is used; there is no fallback chain. | +| `AZURE_TENANT_ID` | unset | Tenant for the two CLI credentials. | +| `AZURE_CLIENT_ID` | unset | Client ID of a user-assigned managed identity. | +| `TOKEN_SCOPE` | `https://ai.azure.com/.default` | Scope requested for the bearer token. | +| `API_KEY_HEADER` | `Authorization` | `Authorization` sends `Bearer `, the SDK's own scheme. `x-api-key` (or another header name) sends the raw key. | +| `ANTHROPIC_API_VERSION` | unset | Sets `anthropic-version`. When unset the SDK's own value is used. | + +The base URL must be HTTPS; plain HTTP is accepted for loopback hosts. +## What `clientauth.CreateClient` guarantees + +```go +client, err := clientauth.CreateClient(clientauth.Options{ + BaseURL: baseURL, + TokenProvider: func(ctx context.Context) (string, error) { return token(ctx) }, // Authorization: Bearer + // or: APIKey: key, KeyHeader: "x-api-key", +}) +message, err := client.Messages.New(ctx, params) +``` + +- **One explicit credential.** `TokenProvider` is called for every HTTP attempt, including each SDK retry, with + that attempt's context, so a renewed token is picked up and cancellation reaches the provider. A static + `APIKey` goes in `KeyHeader` (`Authorization` by default). +- **No ambient credentials.** `option.WithoutEnvironmentDefaults` stops the SDK from reading + `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_PROFILE`, a profile on disk, `ANTHROPIC_BASE_URL` and + `ANTHROPIC_CUSTOM_HEADERS`. A public middleware, registered last so that it is closest to the network, then + replaces every credential header (`Authorization`, `X-Api-Key`, `Api-Key` and the selected header) before each + attempt, so credentials from per-call options cannot reach the wire. Other headers, including + `anthropic-beta`, are untouched. +- **No OAuth beta.** The SDK's credential-provider options, which add `anthropic-beta: oauth-2025-04-20` and keep + their own token cache, are not used. The helper has no cache and no retry of its own. +- **Bound to one origin.** The HTTPS base URL (loopback HTTP for local mocks) fixes the origin. A request to + another origin, for example `option.WithBaseURL` on a call or an absolute URL, fails with + `ErrDifferentOrigin` before the provider is called or anything is sent. The helper's HTTP client refuses + redirects (`ErrRedirectRefused`); a redirect target is never contacted. A client you supply through + `Options.HTTPClient` keeps its transport but gets this redirect policy. +- **SDK behaviour is preserved.** The helper leaves the SDK's retry and timeout defaults alone (`MaxRetries` and + `RequestTimeout` are applied only when set, and the HTTP client it installs keeps the SDK default client's + 10 minute response-header timeout). Context cancellation and deadlines, `*anthropic.Error` statuses and + streaming are the SDK's. +- **The 120 second limit is the sample's policy, not the helper's.** `main.go` ends the whole call, including + retries and streaming, after 120 seconds (`totalTimeout`, applied with `context.WithTimeout`) and sends + `MaxTokens` 1024. + +Keep in mind: + +- The SDK treats an error returned by the helper's middleware (a failing provider, an invalid credential value, + a different origin) as a transport error and retries it, so a failing provider is called up to + `MaxRetries + 1` times (three by default) before the call fails. Set `MaxRetries` to 0 to fail fast. A refused + redirect is final and is not retried. +- Do not pass `option.WithHTTPClient` or your own middleware that adds credentials to individual calls: a + per-call HTTP client replaces the redirect policy, and middleware added later runs closer to the network than + the helper's. + +## Tokens and caching + +`tokenProvider` in `credential.go` calls `GetToken` on every attempt and adds no cache or retry. What that costs +depends on the credential: `ManagedIdentityCredential` keeps the tokens it receives and refreshes them before +they expire, while `AzureCliCredential` and `AzureDeveloperCliCredential` run `az` or `azd` each time they are +asked, so every HTTP attempt with a CLI credential starts a short-lived process in the calling process. That +cost is accepted here for simplicity. `createCredential` passes `AZURE_TENANT_ID` only to the two CLI +credentials and `AZURE_CLIENT_ID` only to `ManagedIdentityCredential`. + +`azidentity` offers no process-timeout option for the two CLI credentials. It bounds the `az` or `azd` call at 10 +seconds only when the context it receives has no deadline; the sample's 120 second deadline is on that context, so +it applies instead. A caller that uses the helper with a context that has no deadline gets the 10 second default +and can add its own deadline. + +## Tests + +```powershell +go vet ./... +go test ./... # the SDK against loopback servers; no network, no credentials +``` + +The tests cover native and `/anthropic` paths, a fresh token for every request and retry, ambient credential and +header canaries (with a control proving the canaries are live), the selected key header and API version, no +OAuth beta, user header and beta pass-through, streaming, 401/403/429/500 statuses, cancellation and timeouts, +cross-origin and redirect safety, variable-family pairing (mixed `ANTHROPIC_*` and `CLAUDE_*` canaries), +credential selection and the command's exit codes (the test binary starts +itself as the command). \ No newline at end of file diff --git a/samples/go/clientauth/client_auth.go b/samples/go/clientauth/client_auth.go new file mode 100644 index 0000000..71b027b --- /dev/null +++ b/samples/go/clientauth/client_auth.go @@ -0,0 +1,227 @@ +// Package clientauth builds a stock anthropic.Client whose credential is chosen +// explicitly and resolved for every HTTP attempt. +// +// It only uses public SDK options. option.WithoutEnvironmentDefaults stops the SDK +// from reading ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, ANTHROPIC_PROFILE, a profile +// on disk, ANTHROPIC_BASE_URL and ANTHROPIC_CUSTOM_HEADERS. One middleware, registered +// last so that it sits closest to the network, then runs for each attempt (including +// SDK retries) and: +// +// - refuses any request whose origin differs from the configured base URL; +// - replaces every credential-bearing header (SDK, per-call and default headers) +// with the single selected credential; +// +// while the HTTP client it installs refuses to follow redirects. The SDK's +// credential-provider options are not used, so no OAuth beta header is added and the +// helper has no token cache or retry of its own. The SDK's retry and timeout defaults +// are preserved: MaxRetries and RequestTimeout are applied only when set. +// +// Errors returned by the middleware (a failing provider, an invalid credential value, a +// different origin) are transport errors to the SDK, which retries them up to MaxRetries +// times. A refused redirect is final: net/http returns the redirect response together +// with the error, and the SDK does not retry a 3xx response. Do not pass +// option.WithHTTPClient to individual calls: it would replace the redirect policy. +package clientauth + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "regexp" + "strings" + "time" + + "github.com/anthropics/anthropic-sdk-go/v2" + "github.com/anthropics/anthropic-sdk-go/v2/option" +) + +// sdkResponseHeaderTimeout is the response-header timeout of the SDK's own default HTTP client +// (internal/requestconfig.DefaultHTTPClient). The client installed here mirrors it so that +// replacing the redirect policy does not change the SDK's timeout behavior. +const sdkResponseHeaderTimeout = 10 * time.Minute + +// CredentialProvider returns the credential for one HTTP attempt; ctx is that +// attempt's request context. It is called again for every retry. +type CredentialProvider func(ctx context.Context) (string, error) + +// Options configures CreateClient. +type Options struct { + // BaseURL is the Messages API base URL. HTTPS only; plain HTTP is accepted for loopback hosts. + BaseURL string + // TokenProvider is a bearer-token callback, sent as "Authorization: Bearer ". + // Set this or APIKey. + TokenProvider CredentialProvider + // APIKey is a static key. Set this or TokenProvider. + APIKey string + // KeyHeader carries APIKey: "Authorization" (the default, sent as "Bearer ") or a + // raw-key header such as "x-api-key". + KeyHeader string + // APIVersion overrides the SDK's anthropic-version header; the SDK default applies when empty. + APIVersion string + // MaxRetries overrides the SDK retry count; the SDK default applies when nil. + MaxRetries *int + // RequestTimeout bounds one HTTP attempt; the SDK's default applies when zero. + RequestTimeout time.Duration + // HTTPClient supplies the transport. Its redirect policy is always replaced. + HTTPClient *http.Client +} + +var ( + // ErrDifferentOrigin is returned, before anything is sent, for a request whose origin differs from BaseURL. + ErrDifferentOrigin = errors.New("clientauth: refusing to send credentials to a different origin") + // ErrRedirectRefused is returned when the server answers with a redirect. + ErrRedirectRefused = errors.New("clientauth: refusing to follow a redirect") + // ErrCredentialProvider wraps a failure of the credential provider. + ErrCredentialProvider = errors.New("clientauth: the credential provider failed") + // ErrInvalidCredential is returned when the provider returns an empty or multi-line value. + ErrInvalidCredential = errors.New("clientauth: the credential must be a nonempty, single-line string") + + errInvalidBaseURL = errors.New("clientauth: BaseURL must be an HTTPS URL without credentials, query, or fragment") + headerName = regexp.MustCompile("^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$") + versionValue = regexp.MustCompile(`^[\x21-\x7e]+$`) +) + +var credentialHeaders = []string{"Authorization", "X-Api-Key", "Api-Key"} + +// CreateClient returns a stock anthropic.Client; see the package documentation. +func CreateClient(opts Options) (anthropic.Client, error) { + base, err := parseBaseURL(opts.BaseURL) + if err != nil { + return anthropic.Client{}, err + } + if (opts.TokenProvider == nil) == (opts.APIKey == "") { + return anthropic.Client{}, errors.New("clientauth: provide exactly one of TokenProvider or APIKey") + } + if opts.APIKey != "" && !validSecret(opts.APIKey) { + return anthropic.Client{}, errors.New("clientauth: APIKey must be a nonempty, single-line string") + } + keyHeader := opts.KeyHeader + if keyHeader == "" { + keyHeader = "Authorization" + } + if !headerName.MatchString(keyHeader) { + return anthropic.Client{}, errors.New("clientauth: KeyHeader must be a valid HTTP header name") + } + if opts.APIVersion != "" && !versionValue.MatchString(opts.APIVersion) { + return anthropic.Client{}, errors.New("clientauth: APIVersion must be a string of printable ASCII characters") + } + if opts.MaxRetries != nil && *opts.MaxRetries < 0 { + return anthropic.Client{}, errors.New("clientauth: MaxRetries must not be negative") + } + if opts.RequestTimeout < 0 { + return anthropic.Client{}, errors.New("clientauth: RequestTimeout must not be negative") + } + + provider := opts.TokenProvider + header := keyHeader + if provider != nil { + header = "Authorization" + } else { + key := opts.APIKey + provider = func(context.Context) (string, error) { return key, nil } + } + + sdkOptions := []option.RequestOption{ + option.WithoutEnvironmentDefaults(), + option.WithBaseURL(opts.BaseURL), + option.WithHTTPClient(httpClient(opts.HTTPClient)), + } + if opts.RequestTimeout > 0 { + sdkOptions = append(sdkOptions, option.WithRequestTimeout(opts.RequestTimeout)) + } + if opts.APIVersion != "" { + sdkOptions = append(sdkOptions, option.WithHeader("anthropic-version", opts.APIVersion)) + } + if opts.MaxRetries != nil { + sdkOptions = append(sdkOptions, option.WithMaxRetries(*opts.MaxRetries)) + } + sdkOptions = append(sdkOptions, option.WithMiddleware(authorizer(originOf(base), header, strings.EqualFold(header, "Authorization"), provider))) + return anthropic.NewClient(sdkOptions...), nil +} + +func authorizer(allowed origin, header string, bearer bool, provide CredentialProvider) option.Middleware { + return func(req *http.Request, next option.MiddlewareNext) (*http.Response, error) { + if originOf(req.URL) != allowed { + return nil, ErrDifferentOrigin + } + value, err := provide(req.Context()) + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrCredentialProvider, err) + } + if !validSecret(value) { + return nil, ErrInvalidCredential + } + for _, name := range credentialHeaders { + req.Header.Del(name) + } + req.Header.Del(header) + if bearer { + value = "Bearer " + value + } + req.Header.Set(header, value) + return next(req) + } +} + +func httpClient(supplied *http.Client) *http.Client { + client := &http.Client{} + if supplied != nil { + copied := *supplied + client = &copied + } else if transport, ok := http.DefaultTransport.(*http.Transport); ok { + cloned := transport.Clone() + cloned.ResponseHeaderTimeout = sdkResponseHeaderTimeout + client.Transport = cloned + } + // When the policy refuses, net/http returns the redirect response together with the + // error, which the SDK treats as final instead of retrying. + client.CheckRedirect = func(*http.Request, []*http.Request) error { return ErrRedirectRefused } + return client +} + +func parseBaseURL(raw string) (*url.URL, error) { + u, err := url.Parse(raw) + if err != nil || u.Hostname() == "" || u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" { + return nil, errInvalidBaseURL + } + switch strings.ToLower(u.Scheme) { + case "https": + case "http": + if !loopback(u.Hostname()) { + return nil, errInvalidBaseURL + } + default: + return nil, errInvalidBaseURL + } + return u, nil +} + +func loopback(host string) bool { + switch strings.ToLower(host) { + case "localhost", "127.0.0.1", "::1": + return true + } + return false +} + +type origin struct{ scheme, host, port string } + +func originOf(u *url.URL) origin { + scheme := strings.ToLower(u.Scheme) + port := u.Port() + if port == "" { + switch scheme { + case "https": + port = "443" + case "http": + port = "80" + } + } + return origin{scheme, strings.ToLower(u.Hostname()), port} +} + +func validSecret(value string) bool { + return strings.TrimSpace(value) != "" && !strings.ContainsAny(value, "\r\n\x00") +} diff --git a/samples/go/clientauth/client_auth_test.go b/samples/go/clientauth/client_auth_test.go new file mode 100644 index 0000000..eae96d5 --- /dev/null +++ b/samples/go/clientauth/client_auth_test.go @@ -0,0 +1,655 @@ +package clientauth_test + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/anthropics/anthropic-sdk-go/v2" + "github.com/anthropics/anthropic-sdk-go/v2/option" + + "github.com/Azure-Samples/claude/samples/go/clientauth" + "github.com/Azure-Samples/claude/samples/go/internal/testserver" +) + +func params() anthropic.MessageNewParams { + return anthropic.MessageNewParams{ + Model: "claude-test", + MaxTokens: 32, + Messages: []anthropic.MessageParam{anthropic.NewUserMessage(anthropic.NewTextBlock("Hello"))}, + } +} + +func retries(n int) *int { return &n } + +func testContext(t *testing.T) context.Context { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + t.Cleanup(cancel) + return ctx +} + +func newClient(t *testing.T, opts clientauth.Options) anthropic.Client { + t.Helper() + client, err := clientauth.CreateClient(opts) + if err != nil { + t.Fatalf("CreateClient: %v", err) + } + return client +} + +func headerValues(r testserver.Request, name string) []string { return r.Header.Values(name) } + +func requireAbsent(t *testing.T, r testserver.Request, names ...string) { + t.Helper() + for _, name := range names { + if values := headerValues(r, name); len(values) != 0 { + t.Errorf("header %s must be absent, got %q", name, values) + } + } +} + +func requireClean(t *testing.T, requests []testserver.Request) { + t.Helper() + for _, r := range requests { + for name, values := range r.Header { + for _, value := range values { + if strings.Contains(value, "oauth-2025-04-20") { + t.Errorf("the OAuth beta must not be added: %s: %s", name, value) + } + } + } + } +} + +func TestStockClientAndFreshTokenForEveryRequest(t *testing.T) { + testserver.CleanEnvironment(t) + server := testserver.New(t, testserver.Respond(testserver.OKMessage)) + var calls atomic.Int32 + client := newClient(t, clientauth.Options{ + BaseURL: server.URL, + TokenProvider: func(context.Context) (string, error) { + return fmt.Sprintf("token-%d", calls.Add(1)), nil + }, + MaxRetries: retries(0), + }) + if calls.Load() != 0 { + t.Fatal("the provider must not be called until a request is made") + } + + for range 2 { + if _, err := client.Messages.New(testContext(t), params()); err != nil { + t.Fatalf("Messages.New: %v", err) + } + } + + requests := server.Requests() + if len(requests) != 2 { + t.Fatalf("got %d requests", len(requests)) + } + for i, want := range []string{"Bearer token-1", "Bearer token-2"} { + if got := requests[i].Header.Get("Authorization"); got != want { + t.Errorf("request %d Authorization = %q, want %q", i, got, want) + } + } + if requests[0].URL != "/v1/messages" { + t.Errorf("path = %q", requests[0].URL) + } + if !strings.Contains(requests[0].Body, `"model":"claude-test"`) { + t.Errorf("body = %s", requests[0].Body) + } + requireAbsent(t, requests[0], "Anthropic-Beta") + requireClean(t, requests) +} + +func TestBaseURLPathPrefix(t *testing.T) { + testserver.CleanEnvironment(t) + server := testserver.New(t, testserver.Respond(testserver.OKMessage)) + for _, suffix := range []string{"/anthropic", "/anthropic/"} { + client := newClient(t, clientauth.Options{ + BaseURL: server.URL + suffix, + TokenProvider: func(context.Context) (string, error) { return "token", nil }, + MaxRetries: retries(0), + }) + if _, err := client.Messages.New(testContext(t), params()); err != nil { + t.Fatalf("Messages.New: %v", err) + } + } + for i, r := range server.Requests() { + if r.URL != "/anthropic/v1/messages" { + t.Errorf("request %d path = %q", i, r.URL) + } + } +} + +func TestAmbientAndPerCallCredentialsAreIgnored(t *testing.T) { + testserver.CleanEnvironment(t) + t.Setenv("ANTHROPIC_API_KEY", "ambient-key-canary") + t.Setenv("ANTHROPIC_AUTH_TOKEN", "ambient-token-canary") + t.Setenv("ANTHROPIC_PROFILE", "nonexistent-canary-profile") + t.Setenv("ANTHROPIC_BASE_URL", "https://wrong.example") + t.Setenv("ANTHROPIC_CUSTOM_HEADERS", "Authorization: Bearer custom-canary\nx-api-key: key-canary\napi-key: alias-canary\nx-note: ambient-header") + server := testserver.New(t, testserver.Respond(testserver.OKMessage)) + + // Control: a plain SDK client under the same environment does send the ambient credentials and headers. + stock := anthropic.NewClient(option.WithBaseURL(server.URL), option.WithMaxRetries(0)) + if _, err := stock.Messages.New(testContext(t), params()); err != nil { + t.Fatalf("control request: %v", err) + } + control := fmt.Sprint(server.Requests()[0].Header) + if !strings.Contains(control, "canary") { + t.Fatalf("the canaries must be live, control headers: %s", control) + } + + for _, mode := range []struct { + name string + options clientauth.Options + header string + want string + }{ + {"bearer", clientauth.Options{TokenProvider: func(context.Context) (string, error) { return "selected-token", nil }}, "Authorization", "Bearer selected-token"}, + {"x-api-key", clientauth.Options{APIKey: "selected-key", KeyHeader: "x-api-key"}, "X-Api-Key", "selected-key"}, + } { + t.Run(mode.name, func(t *testing.T) { + before := server.Count() + mode.options.BaseURL = server.URL + mode.options.MaxRetries = retries(0) + client := newClient(t, mode.options) + + _, err := client.Messages.New(testContext(t), params(), + option.WithHeader("Authorization", "Bearer request-canary"), + option.WithHeader("X-Api-Key", "request-key-canary"), + option.WithHeader("anthropic-beta", "a-requested-beta"), + option.WithHeader("X-Request-Note", "request-header"), + ) + if err != nil { + t.Fatalf("Messages.New: %v", err) + } + + r := server.Requests()[before] + if got := r.Header.Get(mode.header); got != mode.want { + t.Errorf("%s = %q, want %q", mode.header, got, mode.want) + } + for _, other := range []string{"Authorization", "X-Api-Key", "Api-Key"} { + if other != mode.header { + requireAbsent(t, r, other) + } + } + if got := r.Header.Get("Anthropic-Beta"); got != "a-requested-beta" { + t.Errorf("anthropic-beta = %q", got) + } + if got := r.Header.Get("X-Request-Note"); got != "request-header" { + t.Errorf("x-request-note = %q", got) + } + requireAbsent(t, r, "X-Note") + if strings.Contains(fmt.Sprint(r.Header), "canary") { + t.Errorf("a canary reached the wire: %v", r.Header) + } + }) + } +} + +func TestKeyHeaderAndAPIVersion(t *testing.T) { + testserver.CleanEnvironment(t) + server := testserver.New(t, testserver.Respond(testserver.OKMessage)) + stock := anthropic.NewClient(option.WithAPIKey("stock-key"), option.WithBaseURL(server.URL), option.WithMaxRetries(0)) + if _, err := stock.Messages.New(testContext(t), params()); err != nil { + t.Fatalf("stock request: %v", err) + } + sdkVersion := server.Requests()[0].Header.Get("Anthropic-Version") + if sdkVersion == "" { + t.Fatal("the SDK sends no anthropic-version") + } + + cases := []struct{ keyHeader, header, want string }{ + {"", "Authorization", "Bearer selected-key"}, + {"Authorization", "Authorization", "Bearer selected-key"}, + {"x-api-key", "X-Api-Key", "selected-key"}, + {"api-key", "Api-Key", "selected-key"}, + } + for _, c := range cases { + before := server.Count() + client := newClient(t, clientauth.Options{BaseURL: server.URL, APIKey: "selected-key", KeyHeader: c.keyHeader, MaxRetries: retries(0)}) + if _, err := client.Messages.New(testContext(t), params()); err != nil { + t.Fatalf("Messages.New: %v", err) + } + r := server.Requests()[before] + if got := r.Header.Get(c.header); got != c.want { + t.Errorf("keyHeader %q: %s = %q, want %q", c.keyHeader, c.header, got, c.want) + } + for _, other := range []string{"Authorization", "X-Api-Key", "Api-Key"} { + if other != c.header { + requireAbsent(t, r, other) + } + } + if got := r.Header.Get("Anthropic-Version"); got != sdkVersion { + t.Errorf("anthropic-version = %q, want the SDK default %q", got, sdkVersion) + } + } + + before := server.Count() + client := newClient(t, clientauth.Options{BaseURL: server.URL, APIKey: "selected-key", APIVersion: "2023-06-01", MaxRetries: retries(0)}) + if _, err := client.Messages.New(testContext(t), params()); err != nil { + t.Fatalf("Messages.New: %v", err) + } + if got := server.Requests()[before].Header.Get("Anthropic-Version"); got != "2023-06-01" { + t.Errorf("anthropic-version = %q", got) + } +} + +func TestUserHeadersAndBetasArePreserved(t *testing.T) { + testserver.CleanEnvironment(t) + server := testserver.New(t, testserver.Respond(testserver.OKMessage)) + client := newClient(t, clientauth.Options{BaseURL: server.URL, TokenProvider: func(context.Context) (string, error) { return "token", nil }, MaxRetries: retries(0)}) + + _, err := client.Messages.New(testContext(t), params(), option.WithHeader("X-Team", "platform"), option.WithHeader("anthropic-beta", "prompt-caching-2024-07-31")) + if err != nil { + t.Fatalf("Messages.New: %v", err) + } + + r := server.Requests()[0] + if r.Header.Get("X-Team") != "platform" || r.Header.Get("Anthropic-Beta") != "prompt-caching-2024-07-31" { + t.Errorf("headers = %v", r.Header) + } + requireClean(t, server.Requests()) +} + +func TestInvalidConfigurationFailsBeforeAnyRequest(t *testing.T) { + provider := func(context.Context) (string, error) { return "token", nil } + base := "https://example.services.ai.azure.com/anthropic" + cases := map[string]clientauth.Options{ + "no credential": {BaseURL: base}, + "two credentials": {BaseURL: base, APIKey: "key", TokenProvider: provider}, + "plain HTTP": {BaseURL: "http://insecure.example", APIKey: "key"}, + "HTTP on a lookalike host": {BaseURL: "http://localhost.example", APIKey: "key"}, + "embedded credentials": {BaseURL: "https://user:secret@example.com", APIKey: "key"}, + "query string": {BaseURL: "https://example.com/anthropic?x=1", APIKey: "key"}, + "fragment": {BaseURL: "https://example.com/anthropic#x", APIKey: "key"}, + "not a URL": {BaseURL: "not a url", APIKey: "key"}, + "empty base URL": {APIKey: "key"}, + "blank key": {BaseURL: base, APIKey: " "}, + "multi-line key": {BaseURL: base, APIKey: "key\nx-injected: 1"}, + "bad header name": {BaseURL: base, APIKey: "key", KeyHeader: "bad header"}, + "bad API version": {BaseURL: base, APIKey: "key", APIVersion: "bad\nversion"}, + "negative retries": {BaseURL: base, APIKey: "key", MaxRetries: retries(-1)}, + "negative timeout": {BaseURL: base, APIKey: "key", RequestTimeout: -time.Second}, + } + for name, opts := range cases { + t.Run(name, func(t *testing.T) { + if _, err := clientauth.CreateClient(opts); err == nil { + t.Fatal("expected an error") + } else if strings.Contains(err.Error(), "secret") { + t.Fatalf("the error echoes the URL credentials: %v", err) + } + }) + } +} + +func TestHTTPSAndLoopbackBaseURLsAreAccepted(t *testing.T) { + for _, base := range []string{"https://example.com", "https://example.com:8443/anthropic", "http://localhost:1", "http://127.0.0.1:1", "http://[::1]:1"} { + if _, err := clientauth.CreateClient(clientauth.Options{BaseURL: base, APIKey: "key"}); err != nil { + t.Errorf("%s: %v", base, err) + } + } +} + +func TestRedirectsAreNeverFollowed(t *testing.T) { + testserver.CleanEnvironment(t) + other := testserver.New(t, testserver.Respond(testserver.OKMessage)) + origin := testserver.New(t, testserver.Redirect(http.StatusTemporaryRedirect, other.URL+"/v1/messages")) + sameOrigin := testserver.New(t, testserver.Redirect(http.StatusPermanentRedirect, "/elsewhere")) + + for _, c := range []struct { + name string + server *testserver.Server + opts clientauth.Options + }{ + {"bearer, cross-origin", origin, clientauth.Options{TokenProvider: func(context.Context) (string, error) { return "selected-token", nil }}}, + {"x-api-key, cross-origin", origin, clientauth.Options{APIKey: "selected-key", KeyHeader: "x-api-key"}}, + {"bearer, same-origin", sameOrigin, clientauth.Options{TokenProvider: func(context.Context) (string, error) { return "selected-token", nil }}}, + } { + before := c.server.Count() + c.opts.BaseURL = c.server.URL + client := newClient(t, c.opts) + _, err := client.Messages.New(testContext(t), params()) + if !errors.Is(err, clientauth.ErrRedirectRefused) { + t.Errorf("%s: err = %v, want ErrRedirectRefused", c.name, err) + } + if got := c.server.Count() - before; got != 1 { + t.Errorf("%s: the origin saw %d requests; a refused redirect is final, so the SDK must not retry it", c.name, got) + } + } + if other.Count() != 0 { + t.Errorf("no credential may reach the redirect target, it saw %d requests", other.Count()) + } +} + +func TestRedirectPolicyOfASuppliedClientIsReplaced(t *testing.T) { + testserver.CleanEnvironment(t) + other := testserver.New(t, testserver.Respond(testserver.OKMessage)) + origin := testserver.New(t, testserver.Redirect(http.StatusTemporaryRedirect, other.URL+"/v1/messages")) + var used atomic.Int32 + supplied := &http.Client{ + Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { used.Add(1); return http.DefaultTransport.RoundTrip(r) }), + CheckRedirect: func(*http.Request, []*http.Request) error { return nil }, + } + client := newClient(t, clientauth.Options{BaseURL: origin.URL, APIKey: "selected-key", KeyHeader: "x-api-key", HTTPClient: supplied, MaxRetries: retries(0)}) + + _, err := client.Messages.New(testContext(t), params()) + + if !errors.Is(err, clientauth.ErrRedirectRefused) { + t.Errorf("err = %v", err) + } + if used.Load() != 1 || other.Count() != 0 { + t.Errorf("transport used %d times, redirect target saw %d requests", used.Load(), other.Count()) + } + if supplied.CheckRedirect == nil { + t.Error("the caller's client was modified") + } else if err := supplied.CheckRedirect(nil, nil); err != nil { + t.Error("the caller's client was modified") + } +} + +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +func TestCredentialsAreBoundToTheConfiguredOrigin(t *testing.T) { + testserver.CleanEnvironment(t) + other := testserver.New(t, testserver.Respond(testserver.OKMessage)) + origin := testserver.New(t, testserver.Respond(testserver.OKMessage)) + var calls atomic.Int32 + client := newClient(t, clientauth.Options{ + BaseURL: origin.URL, + TokenProvider: func(context.Context) (string, error) { calls.Add(1); return "selected-token", nil }, + MaxRetries: retries(0), + }) + + _, err := client.Messages.New(testContext(t), params(), option.WithBaseURL(other.URL)) + if !errors.Is(err, clientauth.ErrDifferentOrigin) { + t.Errorf("per-call base URL: err = %v", err) + } + err = client.Post(testContext(t), other.URL+"/v1/messages", params(), nil) + if !errors.Is(err, clientauth.ErrDifferentOrigin) { + t.Errorf("absolute URL: err = %v", err) + } + + if other.Count() != 0 || origin.Count() != 0 || calls.Load() != 0 { + t.Errorf("requests: other=%d origin=%d, provider calls=%d; nothing may be sent or resolved", other.Count(), origin.Count(), calls.Load()) + } +} + +func TestProviderFailureIsWrappedAndRetriedLikeATransportError(t *testing.T) { + testserver.CleanEnvironment(t) + server := testserver.New(t, testserver.Respond(testserver.OKMessage)) + failure := errors.New("credential unavailable") + var calls atomic.Int32 + client := newClient(t, clientauth.Options{ + BaseURL: server.URL, + TokenProvider: func(context.Context) (string, error) { calls.Add(1); return "", failure }, + MaxRetries: retries(1), + }) + + _, err := client.Messages.New(testContext(t), params()) + + if !errors.Is(err, failure) || !errors.Is(err, clientauth.ErrCredentialProvider) { + t.Errorf("err = %v", err) + } + if calls.Load() != 2 { + t.Errorf("provider called %d times, want 2 (one attempt and one retry)", calls.Load()) + } + if server.Count() != 0 { + t.Errorf("no request may be sent, got %d", server.Count()) + } +} + +func TestInvalidCredentialValuesAreRejected(t *testing.T) { + testserver.CleanEnvironment(t) + server := testserver.New(t, testserver.Respond(testserver.OKMessage)) + for _, value := range []string{"", " ", "a\nb", "a\r\nb"} { + client := newClient(t, clientauth.Options{ + BaseURL: server.URL, + TokenProvider: func(context.Context) (string, error) { return value, nil }, + MaxRetries: retries(0), + }) + if _, err := client.Messages.New(testContext(t), params()); !errors.Is(err, clientauth.ErrInvalidCredential) { + t.Errorf("value %q: err = %v", value, err) + } + } + if server.Count() != 0 { + t.Errorf("no request may be sent, got %d", server.Count()) + } +} + +func TestHTTPStatusesArePreserved(t *testing.T) { + testserver.CleanEnvironment(t) + for _, status := range []int{401, 403, 429, 500} { + server := testserver.New(t, testserver.Error(status)) + client := newClient(t, clientauth.Options{BaseURL: server.URL, TokenProvider: func(context.Context) (string, error) { return "token", nil }, MaxRetries: retries(0)}) + + _, err := client.Messages.New(testContext(t), params()) + + var apiErr *anthropic.Error + if !errors.As(err, &apiErr) || apiErr.StatusCode != status { + t.Errorf("status %d: err = %v", status, err) + } + } +} + +func TestAuthenticationAndPermissionFailuresAreNotRetried(t *testing.T) { + testserver.CleanEnvironment(t) + for _, status := range []int{401, 403} { + server := testserver.New(t, testserver.Error(status)) + client := newClient(t, clientauth.Options{BaseURL: server.URL, TokenProvider: func(context.Context) (string, error) { return "token", nil }}) + + _, err := client.Messages.New(testContext(t), params()) + + var apiErr *anthropic.Error + if !errors.As(err, &apiErr) || apiErr.StatusCode != status { + t.Errorf("status %d: err = %v", status, err) + } + if server.Count() != 1 { + t.Errorf("status %d: %d requests, want 1", status, server.Count()) + } + } +} + +func TestSDKRetryReacquiresTheCredential(t *testing.T) { + testserver.CleanEnvironment(t) + server := testserver.New(t, func(w http.ResponseWriter, r *http.Request, count int) { + if count < 3 { + testserver.Error(500, "retry-after-ms", "1")(w, r, count) + return + } + testserver.Respond(testserver.OKMessage)(w, r, count) + }) + var calls atomic.Int32 + client := newClient(t, clientauth.Options{BaseURL: server.URL, TokenProvider: func(context.Context) (string, error) { + return fmt.Sprintf("token-%d", calls.Add(1)), nil + }}) + + if _, err := client.Messages.New(testContext(t), params()); err != nil { + t.Fatalf("Messages.New: %v", err) + } + + requests := server.Requests() + if len(requests) != 3 { + t.Fatalf("got %d requests, want 3 (the SDK default of two retries)", len(requests)) + } + for i, r := range requests { + if got, want := r.Header.Get("Authorization"), fmt.Sprintf("Bearer token-%d", i+1); got != want { + t.Errorf("attempt %d Authorization = %q, want %q", i, got, want) + } + if got := r.Header.Get("X-Stainless-Retry-Count"); got != fmt.Sprint(i) { + t.Errorf("attempt %d retry count = %q", i, got) + } + } +} + +func TestStreamingThroughTheStandardSDKHelper(t *testing.T) { + testserver.CleanEnvironment(t) + server := testserver.New(t, testserver.Stream(testserver.Block{Kind: "thinking", Text: "not for display"}, testserver.Block{Kind: "text", Text: "OK"})) + client := newClient(t, clientauth.Options{BaseURL: server.URL, TokenProvider: func(context.Context) (string, error) { return "stream-token", nil }, MaxRetries: retries(0)}) + + stream := client.Messages.NewStreaming(testContext(t), params()) + defer stream.Close() + var text strings.Builder + for stream.Next() { + if event, ok := stream.Current().AsAny().(anthropic.ContentBlockDeltaEvent); ok { + if delta, ok := event.Delta.AsAny().(anthropic.TextDelta); ok { + text.WriteString(delta.Text) + } + } + } + if err := stream.Err(); err != nil { + t.Fatalf("stream: %v", err) + } + + if text.String() != "OK" { + t.Errorf("text = %q", text.String()) + } + r := server.Requests()[0] + if r.Header.Get("Authorization") != "Bearer stream-token" || !strings.Contains(r.Body, `"stream":true`) { + t.Errorf("request = %v %s", r.Header, r.Body) + } + requireClean(t, server.Requests()) +} + +func TestCancellationReachesTheProvider(t *testing.T) { + testserver.CleanEnvironment(t) + server := testserver.New(t, testserver.Respond(testserver.OKMessage)) + started := make(chan struct{}) + observed := make(chan error, 1) + client := newClient(t, clientauth.Options{ + BaseURL: server.URL, + TokenProvider: func(ctx context.Context) (string, error) { + close(started) + <-ctx.Done() + observed <- ctx.Err() + return "", ctx.Err() + }, + MaxRetries: retries(2), + }) + ctx, cancel := context.WithCancel(testContext(t)) + done := make(chan error, 1) + go func() { + _, err := client.Messages.New(ctx, params()) + done <- err + }() + + <-started + cancel() + + if err := <-done; !errors.Is(err, context.Canceled) { + t.Errorf("err = %v, want context.Canceled", err) + } + if err := <-observed; !errors.Is(err, context.Canceled) { + t.Errorf("the provider saw %v", err) + } + if server.Count() != 0 { + t.Errorf("no request may be sent, got %d", server.Count()) + } +} + +func TestCancellationAndDeadlinesOfARequestInFlight(t *testing.T) { + testserver.CleanEnvironment(t) + server := testserver.New(t, testserver.Hang) + client := newClient(t, clientauth.Options{BaseURL: server.URL, TokenProvider: func(context.Context) (string, error) { return "token", nil }, MaxRetries: retries(0)}) + + ctx, cancel := context.WithCancel(testContext(t)) + done := make(chan error, 1) + go func() { + _, err := client.Messages.New(ctx, params()) + done <- err + }() + for server.Count() == 0 { + time.Sleep(5 * time.Millisecond) + } + cancel() + if err := <-done; !errors.Is(err, context.Canceled) { + t.Errorf("cancel: err = %v", err) + } + + deadline, stop := context.WithTimeout(testContext(t), 100*time.Millisecond) + defer stop() + if _, err := client.Messages.New(deadline, params()); !errors.Is(err, context.DeadlineExceeded) { + t.Errorf("deadline: err = %v", err) + } +} + +func TestEachAttemptIsBoundedByTheRequestTimeout(t *testing.T) { + testserver.CleanEnvironment(t) + server := testserver.New(t, testserver.Hang) + client := newClient(t, clientauth.Options{ + BaseURL: server.URL, + TokenProvider: func(context.Context) (string, error) { return "token", nil }, + MaxRetries: retries(0), + RequestTimeout: 50 * time.Millisecond, + }) + + _, err := client.Messages.New(testContext(t), params()) + + if !errors.Is(err, context.DeadlineExceeded) { + t.Errorf("err = %v", err) + } + if server.Count() != 1 { + t.Errorf("server saw %d requests", server.Count()) + } +} + +func TestSDKTimeoutDefaultsArePreserved(t *testing.T) { + testserver.CleanEnvironment(t) + server := testserver.New(t, testserver.Respond(testserver.OKMessage)) + stock := anthropic.NewClient(option.WithAPIKey("stock-key"), option.WithBaseURL(server.URL), option.WithMaxRetries(0)) + if _, err := stock.Messages.New(testContext(t), params()); err != nil { + t.Fatalf("stock request: %v", err) + } + sdkTimeout := server.Requests()[0].Header.Get("X-Stainless-Timeout") + if sdkTimeout == "" { + t.Fatal("the SDK sends no timeout header") + } + + for _, c := range []struct { + name string + timeout time.Duration + want string + }{ + {"unset keeps the SDK default", 0, sdkTimeout}, + {"set is applied to each attempt", 30 * time.Second, "30"}, + } { + before := server.Count() + client := newClient(t, clientauth.Options{ + BaseURL: server.URL, + TokenProvider: func(context.Context) (string, error) { return "token", nil }, + MaxRetries: retries(0), + RequestTimeout: c.timeout, + }) + if _, err := client.Messages.New(testContext(t), params()); err != nil { + t.Fatalf("%s: %v", c.name, err) + } + if got := server.Requests()[before].Header.Get("X-Stainless-Timeout"); got != c.want { + t.Errorf("%s: X-Stainless-Timeout = %q, want %q", c.name, got, c.want) + } + } +} + +func TestMaxRetriesIsHonoured(t *testing.T) { + testserver.CleanEnvironment(t) + server := testserver.New(t, testserver.Error(500, "retry-after-ms", "1")) + client := newClient(t, clientauth.Options{BaseURL: server.URL, TokenProvider: func(context.Context) (string, error) { return "token", nil }, MaxRetries: retries(1)}) + + _, err := client.Messages.New(testContext(t), params()) + + var apiErr *anthropic.Error + if !errors.As(err, &apiErr) || apiErr.StatusCode != 500 { + t.Errorf("err = %v", err) + } + if server.Count() != 2 { + t.Errorf("server saw %d requests, want 2", server.Count()) + } +} diff --git a/samples/go/clientauth/http_client_test.go b/samples/go/clientauth/http_client_test.go new file mode 100644 index 0000000..c3cbd88 --- /dev/null +++ b/samples/go/clientauth/http_client_test.go @@ -0,0 +1,47 @@ +package clientauth + +import ( + "errors" + "net/http" + "testing" + "time" +) + +func TestDefaultHTTPClientMirrorsTheSDKDefaultAndRefusesRedirects(t *testing.T) { + shared := http.DefaultTransport.(*http.Transport) + client := httpClient(nil) + + transport, ok := client.Transport.(*http.Transport) + if !ok || transport == shared { + t.Fatalf("the transport must be a clone of http.DefaultTransport, got %T", client.Transport) + } + if transport.ResponseHeaderTimeout != 10*time.Minute { + t.Errorf("ResponseHeaderTimeout = %v, want the SDK default of 10 minutes", transport.ResponseHeaderTimeout) + } + if shared.ResponseHeaderTimeout != 0 { + t.Error("http.DefaultTransport must not be modified") + } + if err := client.CheckRedirect(nil, nil); !errors.Is(err, ErrRedirectRefused) { + t.Errorf("CheckRedirect = %v", err) + } +} + +func TestASuppliedClientKeepsItsTransportAndIsNotModified(t *testing.T) { + transport := &http.Transport{} + supplied := &http.Client{Transport: transport, Timeout: 7 * time.Second} + + client := httpClient(supplied) + + if client.Transport != transport || client.Timeout != 7*time.Second { + t.Errorf("transport or timeout changed: %T %v", client.Transport, client.Timeout) + } + if transport.ResponseHeaderTimeout != 0 { + t.Error("the supplied transport must not be modified") + } + if supplied.CheckRedirect != nil { + t.Error("the supplied client must not be modified") + } + if err := client.CheckRedirect(nil, nil); !errors.Is(err, ErrRedirectRefused) { + t.Errorf("CheckRedirect = %v", err) + } +} diff --git a/samples/go/credential.go b/samples/go/credential.go new file mode 100644 index 0000000..14ba97d --- /dev/null +++ b/samples/go/credential.go @@ -0,0 +1,84 @@ +package main + +import ( + "context" + "fmt" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + + "github.com/Azure-Samples/claude/samples/go/clientauth" +) + +// credentialFactories lets tests observe which credential is built and with which options. +type credentialFactories struct { + azureCLI func(*azidentity.AzureCLICredentialOptions) (azcore.TokenCredential, error) + azureDeveloperCLI func(*azidentity.AzureDeveloperCLICredentialOptions) (azcore.TokenCredential, error) + managedIdentity func(*azidentity.ManagedIdentityCredentialOptions) (azcore.TokenCredential, error) +} + +var azureIdentityCredentials = credentialFactories{ + azureCLI: func(o *azidentity.AzureCLICredentialOptions) (azcore.TokenCredential, error) { + credential, err := azidentity.NewAzureCLICredential(o) + if err != nil { + return nil, err + } + return credential, nil + }, + azureDeveloperCLI: func(o *azidentity.AzureDeveloperCLICredentialOptions) (azcore.TokenCredential, error) { + credential, err := azidentity.NewAzureDeveloperCLICredential(o) + if err != nil { + return nil, err + } + return credential, nil + }, + managedIdentity: func(o *azidentity.ManagedIdentityCredentialOptions) (azcore.TokenCredential, error) { + credential, err := azidentity.NewManagedIdentityCredential(o) + if err != nil { + return nil, err + } + return credential, nil + }, +} + +// createCredential builds exactly the credential named by AZURE_TOKEN_CREDENTIALS, with no +// fallback chain. The tenant applies to the two CLI credentials and the client ID to the +// managed identity. +func createCredential(source, tenantID, clientID string, factories credentialFactories) (azcore.TokenCredential, error) { + switch source { + case "AzureCliCredential": + return factories.azureCLI(&azidentity.AzureCLICredentialOptions{TenantID: tenantID}) + case "AzureDeveloperCliCredential": + return factories.azureDeveloperCLI(&azidentity.AzureDeveloperCLICredentialOptions{TenantID: tenantID}) + case "ManagedIdentityCredential": + options := &azidentity.ManagedIdentityCredentialOptions{} + if clientID != "" { + options.ID = azidentity.ClientID(clientID) + } + return factories.managedIdentity(options) + default: + return nil, &configError{"AZURE_TOKEN_CREDENTIALS must be AzureCliCredential, AzureDeveloperCliCredential, ManagedIdentityCredential."} + } +} + +// tokenProvider asks the credential for a token on every call, with no cache or retry of its +// own. ManagedIdentityCredential keeps the tokens it receives and refreshes them before they +// expire, while AzureCliCredential and AzureDeveloperCliCredential run their command each +// time they are asked, so each HTTP attempt with a CLI credential starts a short-lived process. +func tokenProvider(credential azcore.TokenCredential, scope string) clientauth.CredentialProvider { + return func(ctx context.Context) (string, error) { + token, err := credential.GetToken(ctx, policy.TokenRequestOptions{Scopes: []string{scope}}) + if err != nil { + return "", err + } + return token.Token, nil + } +} + +type credentialSetupError struct{ cause error } + +func (e *credentialSetupError) Error() string { + return fmt.Sprintf("could not create the Azure credential: %v", e.cause) +} +func (e *credentialSetupError) Unwrap() error { return e.cause } diff --git a/samples/go/go.mod b/samples/go/go.mod new file mode 100644 index 0000000..7636077 --- /dev/null +++ b/samples/go/go.mod @@ -0,0 +1,39 @@ +module github.com/Azure-Samples/claude/samples/go + +go 1.25.0 + +require ( + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.3 + github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.15.0 + github.com/anthropics/anthropic-sdk-go/v2 v2.4.0 +) + +require ( + github.com/Azure/azure-sdk-for-go/sdk/internal v1.13.0 // indirect + github.com/AzureAD/microsoft-authentication-library-for-go v1.10.1 // indirect + github.com/bahlo/generic-list-go v0.2.0 // indirect + github.com/buger/jsonparser v1.1.2 // indirect + github.com/go-logr/logr v1.4.2 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/golang-jwt/jwt/v5 v5.3.1 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/invopop/jsonschema v0.14.0 // indirect + github.com/kylelemons/godebug v1.1.0 // indirect + github.com/pb33f/ordered-map/v2 v2.3.1 // indirect + github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect + github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 // indirect + github.com/tidwall/gjson v1.18.0 // indirect + github.com/tidwall/match v1.1.1 // indirect + github.com/tidwall/pretty v1.2.1 // indirect + github.com/tidwall/sjson v1.2.5 // indirect + go.opentelemetry.io/auto/sdk v1.1.0 // indirect + go.opentelemetry.io/otel v1.33.0 // indirect + go.opentelemetry.io/otel/metric v1.33.0 // indirect + go.opentelemetry.io/otel/trace v1.33.0 // indirect + go.yaml.in/yaml/v4 v4.0.0-rc.2 // indirect + golang.org/x/crypto v0.55.0 // indirect + golang.org/x/net v0.58.0 // indirect + golang.org/x/sync v0.22.0 // indirect + golang.org/x/sys v0.47.0 // indirect + golang.org/x/text v0.41.0 // indirect +) diff --git a/samples/go/go.sum b/samples/go/go.sum new file mode 100644 index 0000000..2531fa5 --- /dev/null +++ b/samples/go/go.sum @@ -0,0 +1,154 @@ +cloud.google.com/go/auth v0.7.2 h1:uiha352VrCDMXg+yoBtaD0tUF4Kv9vrtrWPYXwutnDE= +cloud.google.com/go/auth v0.7.2/go.mod h1:VEc4p5NNxycWQTMQEDQF0bd6aTMb6VgYDXEwiJJQAbs= +cloud.google.com/go/auth/oauth2adapt v0.2.3 h1:MlxF+Pd3OmSudg/b1yZ5lJwoXCEaeedAguodky1PcKI= +cloud.google.com/go/auth/oauth2adapt v0.2.3/go.mod h1:tMQXOfZzFuNuUxOypHlQEXgdfX5cuhwU+ffUuXRJE8I= +cloud.google.com/go/compute/metadata v0.5.0 h1:Zr0eK8JbFv6+Wi4ilXAR8FJ3wyNdpxHKJNPos6LTZOY= +cloud.google.com/go/compute/metadata v0.5.0/go.mod h1:aHnloV2TPI38yx4s9+wAZhHykWvVCfu7hQbF+9CWoiY= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.3 h1:qgnWTiWs1G7AqcKZegFvkJD1bmXJcaDU3uC0ELSgZ5U= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.3/go.mod h1:XtxD48QPInqoj+GMlcRlXHEYsoOxFnP6w2JgIZ9rDS4= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.15.0 h1:w3gDUJlJ0BfBsHH02DCBDwbkmMSXJqBj6nBOCo9iocY= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.15.0/go.mod h1:7scl8mG/IFLVjJ9ef/ltdND2T1z0CkgVSaQoUxLvmeU= +github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.4.0 h1:xFaZZ+IubdftrDHnGGwZ6QvQ3KHTtWl2MCK+GMt2vxs= +github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.4.0/go.mod h1:mCBhUhlMjLLJKr5aqw2TNS/VqJOie8MzWq3DAMJeKso= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.13.0 h1:Terj1CMW4+NY5CpWjSRkqLoxh2DkYDdv/FH2z0897Uc= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.13.0/go.mod h1:7Ut2Qw9vcwpLW5Q4MBy43uSxXS7tK2yjs94OJ6j5thE= +github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1 h1:WJTmL004Abzc5wDB5VtZG2PJk5ndYDgVacGqfirKxjM= +github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1/go.mod h1:tCcJZ0uHAmvjsVYzEFivsRTN00oz5BEsRgQHu5JZ9WE= +github.com/AzureAD/microsoft-authentication-library-for-go v1.10.1 h1:0O6j18nQDoIff6/mtosT5LNU2WehEwp+LqfX6699oqY= +github.com/AzureAD/microsoft-authentication-library-for-go v1.10.1/go.mod h1:xdYAf5bjkOpsd3auA8riiJW4vneBubt9caavL7626jQ= +github.com/anthropics/anthropic-sdk-go/v2 v2.4.0 h1:r7bwP/ZaCeEbn5zM5vUacHfyD1DUxXbbzWEeCtViBQI= +github.com/anthropics/anthropic-sdk-go/v2 v2.4.0/go.mod h1:LAOInMKgn6reTIrPvKXa5weyqzxsJkxSBuzhnxzukpQ= +github.com/aws/aws-sdk-go-v2 v1.38.0 h1:UCRQ5mlqcFk9HJDIqENSLR3wiG1VTWlyUfLDEvY7RxU= +github.com/aws/aws-sdk-go-v2 v1.38.0/go.mod h1:9Q0OoGQoboYIAJyslFyF1f5K1Ryddop8gqMhWx/n4Wg= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.3 h1:tW1/Rkad38LA15X4UQtjXZXNKsCgkshC3EbmcUmghTg= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.3/go.mod h1:UbnqO+zjqk3uIt9yCACHJ9IVNhyhOCnYk8yA19SAWrM= +github.com/aws/aws-sdk-go-v2/config v1.27.27 h1:HdqgGt1OAP0HkEDDShEl0oSYa9ZZBSOmKpdpsDMdO90= +github.com/aws/aws-sdk-go-v2/config v1.27.27/go.mod h1:MVYamCg76dFNINkZFu4n4RjDixhVr51HLj4ErWzrVwg= +github.com/aws/aws-sdk-go-v2/credentials v1.17.27 h1:2raNba6gr2IfA0eqqiP2XiQ0UVOpGPgDSi0I9iAP+UI= +github.com/aws/aws-sdk-go-v2/credentials v1.17.27/go.mod h1:gniiwbGahQByxan6YjQUMcW4Aov6bLC3m+evgcoN4r4= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.11 h1:KreluoV8FZDEtI6Co2xuNk/UqI9iwMrOx/87PBNIKqw= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.11/go.mod h1:SeSUYBLsMYFoRvHE0Tjvn7kbxaUhl75CJi1sbfhMxkU= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.15 h1:SoNJ4RlFEQEbtDcCEt+QG56MY4fm4W8rYirAmq+/DdU= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.15/go.mod h1:U9ke74k1n2bf+RIgoX1SXFed1HLs51OgUSs+Ph0KJP8= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.15 h1:C6WHdGnTDIYETAm5iErQUiVNsclNx9qbJVPIt03B6bI= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.15/go.mod h1:ZQLZqhcu+JhSrA9/NXRm8SkDvsycE+JkV3WGY41e+IM= +github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0 h1:hT8rVHwugYE2lEfdFE0QWVo81lF7jMrYJVDWI+f+VxU= +github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0/go.mod h1:8tu/lYfQfFe6IGnaOdrpVgEL2IrrDOf6/m9RQum4NkY= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.3 h1:dT3MqvGhSoaIhRseqw2I0yH81l7wiR2vjs57O51EAm8= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.3/go.mod h1:GlAeCkHwugxdHaueRr4nhPuY+WW+gR8UjlcqzPr1SPI= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.17 h1:HGErhhrxZlQ044RiM+WdoZxp0p+EGM62y3L6pwA4olE= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.17/go.mod h1:RkZEx4l0EHYDJpWppMJ3nD9wZJAa8/0lq9aVC+r2UII= +github.com/aws/aws-sdk-go-v2/service/sso v1.22.4 h1:BXx0ZIxvrJdSgSvKTZ+yRBeSqqgPM89VPlulEcl37tM= +github.com/aws/aws-sdk-go-v2/service/sso v1.22.4/go.mod h1:ooyCOXjvJEsUw7x+ZDHeISPMhtwI3ZCB7ggFMcFfWLU= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4 h1:yiwVzJW2ZxZTurVbYWA7QOrAaCYQR72t0wrSBfoesUE= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4/go.mod h1:0oxfLkpz3rQ/CHlx5hB7H69YUpFiI1tql6Q6Ne+1bCw= +github.com/aws/aws-sdk-go-v2/service/sts v1.30.3 h1:ZsDKRLXGWHk8WdtyYMoGNO7bTudrvuKpDKgMVRlepGE= +github.com/aws/aws-sdk-go-v2/service/sts v1.30.3/go.mod h1:zwySh8fpFyXp9yOr/KVzxOl8SRqgf/IDw5aUt9UKFcQ= +github.com/aws/smithy-go v1.22.5 h1:P9ATCXPMb2mPjYBgueqJNCA5S9UfktsW0tTxi+a7eqw= +github.com/aws/smithy-go v1.22.5/go.mod h1:t1ufH5HMublsJYulve2RKmHDC15xu1f26kHCp/HgceI= +github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk= +github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg= +github.com/buger/jsonparser v1.1.2 h1:frqHqw7otoVbk5M8LlE/L7HTnIq2v9RX6EJ48i9AxJk= +github.com/buger/jsonparser v1.1.2/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= +github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI= +github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= +github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= +github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= +github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= +github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= +github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= +github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/jsonschema-go v0.4.2 h1:tmrUohrwoLZZS/P3x7ex0WAVknEkBZM46iALbcqoRA8= +github.com/google/jsonschema-go v0.4.2/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE= +github.com/google/s2a-go v0.1.7 h1:60BLSyTrOV4/haCDW4zb1guZItoSq8foHCXrAnjBo/o= +github.com/google/s2a-go v0.1.7/go.mod h1:50CgR4k1jNlWBu4UfS4AcfhVe1r6pdZPygJ3R8F0Qdw= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/googleapis/enterprise-certificate-proxy v0.3.2 h1:Vie5ybvEvT75RniqhfFxPRy3Bf7vr3h0cechB90XaQs= +github.com/googleapis/enterprise-certificate-proxy v0.3.2/go.mod h1:VLSiSSBs/ksPL8kq3OBOQ6WRI2QnaFynd1DCjZ62+V0= +github.com/invopop/jsonschema v0.14.0 h1:MHQqLhvpNUZfw+hM3AZDYK7jxO8FZoQeQM77g8iyZjg= +github.com/invopop/jsonschema v0.14.0/go.mod h1:ygm6C2EaVNMBDPpaPlnOA2pFAxBnxGjFlMZABxm9n2I= +github.com/keybase/go-keychain v0.0.1 h1:way+bWYa6lDppZoZcgMbYsvC7GxljxrskdNInRtuthU= +github.com/keybase/go-keychain v0.0.1/go.mod h1:PdEILRW3i9D8JcdM+FmY6RwkHGnhHxXwkPPMeUgOK1k= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/modelcontextprotocol/go-sdk v1.3.1 h1:TfqtNKOIWN4Z1oqmPAiWDC2Jq7K9OdJaooe0teoXASI= +github.com/modelcontextprotocol/go-sdk v1.3.1/go.mod h1:DgVX498dMD8UJlseK1S5i1T4tFz2fkBk4xogC3D15nw= +github.com/pb33f/ordered-map/v2 v2.3.1 h1:5319HDO0aw4DA4gzi+zv4FXU9UlSs3xGZ40wcP1nBjY= +github.com/pb33f/ordered-map/v2 v2.3.1/go.mod h1:qxFQgd0PkVUtOMCkTapqotNgzRhMPL7VvaHKbd1HnmQ= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= +github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc= +github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg= +github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0= +github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0= +github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 h1:uOfcYT+3QungH6tIGSVCR/Y3KJmgJiHcojJbMTPDZAI= +github.com/standard-webhooks/standard-webhooks/libraries v0.0.1/go.mod h1:L1MQhA6x4dn9r007T033lsaZMv9EmBAdXyU/+EF40fo= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= +github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY= +github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= +github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= +github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= +github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY= +github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28= +github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4= +github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4= +go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= +go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= +go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= +go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.49.0 h1:4Pp6oUg3+e/6M4C0A/3kJ2VYa++dsWVTtGgLVj5xtHg= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.49.0/go.mod h1:Mjt1i1INqiaoZOMGR1RIUJN+i3ChKoFRqzrRQhlkbs0= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 h1:jq9TW8u3so/bN+JPT166wjOI6/vQPF6Xe7nMNIltagk= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0/go.mod h1:p8pYQP+m5XfbZm9fxtSKAbM6oIllS7s2AfxrChvc7iw= +go.opentelemetry.io/otel v1.33.0 h1:/FerN9bax5LoK51X/sI0SVYrjSE0/yUL7DpxW4K3FWw= +go.opentelemetry.io/otel v1.33.0/go.mod h1:SUUkR6csvUQl+yjReHu5uM3EtVV7MBm5FHKRlNx4I8I= +go.opentelemetry.io/otel/metric v1.33.0 h1:r+JOocAyeRVXD8lZpjdQjzMadVZp2M4WmQ+5WtEnklQ= +go.opentelemetry.io/otel/metric v1.33.0/go.mod h1:L9+Fyctbp6HFTddIxClbQkjtubW6O9QS3Ann/M82u6M= +go.opentelemetry.io/otel/sdk v1.33.0 h1:iax7M131HuAm9QkZotNHEfstof92xM+N8sr3uHXc2IM= +go.opentelemetry.io/otel/sdk v1.33.0/go.mod h1:A1Q5oi7/9XaMlIWzPSxLRWOI8nG3FnzHJNbiENQuihM= +go.opentelemetry.io/otel/trace v1.33.0 h1:cCJuF7LRjUFso9LPnEAHJDB2pqzp+hbO8eu1qqW2d/s= +go.opentelemetry.io/otel/trace v1.33.0/go.mod h1:uIcdVUZMpTAmz0tI1z04GoVSezK37CbGV4fr1f2nBck= +go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= +go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= +go.yaml.in/yaml/v4 v4.0.0-rc.2 h1:/FrI8D64VSr4HtGIlUtlFMGsm7H7pWTbj6vOLVZcA6s= +go.yaml.in/yaml/v4 v4.0.0-rc.2/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0= +golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M= +golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis= +golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To= +golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU= +golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI= +golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= +golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= +golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk= +golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +google.golang.org/api v0.189.0 h1:equMo30LypAkdkLMBqfeIqtyAnlyig1JSZArl4XPwdI= +google.golang.org/api v0.189.0/go.mod h1:FLWGJKb0hb+pU2j+rJqwbnsF+ym+fQs73rbJ+KAUgy8= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240722135656-d784300faade h1:oCRSWfwGXQsqlVdErcyTt4A93Y8fo0/9D4b1gnI++qo= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240722135656-d784300faade/go.mod h1:Ue6ibwXGpU+dqIcODieyLOcgj7z8+IcskoNIgZxtrFY= +google.golang.org/grpc v1.64.1 h1:LKtvyfbX3UGVPFcGqJ9ItpVWW6oN/2XqTxfAnwRRXiA= +google.golang.org/grpc v1.64.1/go.mod h1:hiQF4LFZelK2WKaP6W0L92zGHtiQdZxk8CrSdvyjeP0= +google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= +google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= +gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/samples/go/internal/testserver/testserver.go b/samples/go/internal/testserver/testserver.go new file mode 100644 index 0000000..456fdc5 --- /dev/null +++ b/samples/go/internal/testserver/testserver.go @@ -0,0 +1,166 @@ +// Package testserver provides loopback servers and fixtures for the sample's offline tests. +package testserver + +import ( + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "strings" + "sync" + "testing" +) + +// Request is one request as the server saw it. +type Request struct { + Method string + URL string + Header http.Header + Body string +} + +// Handler answers a request; count is the number of requests received so far, including this one. +type Handler func(w http.ResponseWriter, r *http.Request, count int) + +// Server records every request before running its handler. +type Server struct { + *httptest.Server + mu sync.Mutex + requests []Request +} + +// New starts a loopback HTTP server that is closed when the test ends. +func New(t testing.TB, handler Handler) *Server { + t.Helper() + s := &Server{} + s.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + s.mu.Lock() + s.requests = append(s.requests, Request{Method: r.Method, URL: r.URL.RequestURI(), Header: r.Header.Clone(), Body: string(body)}) + count := len(s.requests) + s.mu.Unlock() + handler(w, r, count) + })) + t.Cleanup(func() { + s.CloseClientConnections() + s.Close() + }) + return s +} + +// Requests returns a copy of the recorded requests. +func (s *Server) Requests() []Request { + s.mu.Lock() + defer s.mu.Unlock() + return append([]Request(nil), s.requests...) +} + +// Count is the number of requests received. +func (s *Server) Count() int { + s.mu.Lock() + defer s.mu.Unlock() + return len(s.requests) +} + +// ThinkingBlock is a content block the samples must never print. +const ThinkingBlock = `{"type":"thinking","thinking":"not for display","signature":"sample"}` + +// TextBlock is a text content block. +func TextBlock(text string) string { + return fmt.Sprintf(`{"type":"text","text":%q}`, text) +} + +// Message builds a Messages API response with the given JSON content blocks. +func Message(stopReason string, blocks ...string) string { + return fmt.Sprintf(`{"id":"msg_test","type":"message","role":"assistant","model":"claude-test","content":[%s],"stop_reason":%q,"stop_sequence":null,"usage":{"input_tokens":1,"output_tokens":2}}`, + strings.Join(blocks, ","), stopReason) +} + +// OKMessage is a reply with the text "OK". +var OKMessage = Message("end_turn", TextBlock("OK")) + +// JSON answers with a JSON body. +func JSON(status int, body string, headers ...string) Handler { + return func(w http.ResponseWriter, _ *http.Request, _ int) { + w.Header().Set("Content-Type", "application/json") + for i := 0; i+1 < len(headers); i += 2 { + w.Header().Set(headers[i], headers[i+1]) + } + w.WriteHeader(status) + _, _ = io.WriteString(w, body) + } +} + +// Respond answers 200 with the given message. +func Respond(message string) Handler { return JSON(http.StatusOK, message) } + +// Error answers with an API error of the given status. +func Error(status int, headers ...string) Handler { + return JSON(status, `{"type":"error","error":{"type":"api_error","message":"test failure"}}`, headers...) +} + +// Hang never answers; it returns when the client gives up. +func Hang(_ http.ResponseWriter, r *http.Request, _ int) { <-r.Context().Done() } + +// Redirect answers with a redirect to location. +func Redirect(status int, location string) Handler { + return func(w http.ResponseWriter, _ *http.Request, _ int) { + w.Header().Set("Location", location) + w.WriteHeader(status) + } +} + +// Block is one streamed content block: Kind is "text" or "thinking". +type Block struct{ Kind, Text string } + +// EventStream builds a Messages API event stream for the blocks. +func EventStream(blocks ...Block) string { + var b strings.Builder + event := func(name, data string) { fmt.Fprintf(&b, "event: %s\ndata: %s\n\n", name, data) } + event("message_start", `{"type":"message_start","message":{"id":"msg_test","type":"message","role":"assistant","model":"claude-test","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"output_tokens":0}}}`) + for i, block := range blocks { + if block.Kind == "text" { + event("content_block_start", fmt.Sprintf(`{"type":"content_block_start","index":%d,"content_block":{"type":"text","text":""}}`, i)) + event("content_block_delta", fmt.Sprintf(`{"type":"content_block_delta","index":%d,"delta":{"type":"text_delta","text":%q}}`, i, block.Text)) + } else { + event("content_block_start", fmt.Sprintf(`{"type":"content_block_start","index":%d,"content_block":{"type":"thinking","thinking":"","signature":""}}`, i)) + event("content_block_delta", fmt.Sprintf(`{"type":"content_block_delta","index":%d,"delta":{"type":"thinking_delta","thinking":%q}}`, i, block.Text)) + } + event("content_block_stop", fmt.Sprintf(`{"type":"content_block_stop","index":%d}`, i)) + } + event("message_delta", `{"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":2}}`) + event("message_stop", `{"type":"message_stop"}`) + return b.String() +} + +// Stream answers with an event stream for the blocks. +func Stream(blocks ...Block) Handler { + return func(w http.ResponseWriter, _ *http.Request, _ int) { + w.Header().Set("Content-Type", "text/event-stream") + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, EventStream(blocks...)) + } +} + +var ambientPrefixes = []string{"ANTHROPIC_", "CLAUDE_", "AZURE_"} +var ambientNames = []string{"AUTH_MODE", "API_KEY_HEADER", "TOKEN_SCOPE"} + +// CleanEnvironment removes every variable the SDK or the samples read for this test. +func CleanEnvironment(t testing.TB) { + t.Helper() + for _, entry := range os.Environ() { + name, value, _ := strings.Cut(entry, "=") + ambient := false + for _, n := range ambientNames { + ambient = ambient || n == name + } + for _, p := range ambientPrefixes { + ambient = ambient || strings.HasPrefix(name, p) + } + if ambient { + _ = os.Unsetenv(name) + t.Cleanup(func() { _ = os.Setenv(name, value) }) + } + } +} diff --git a/samples/go/main.go b/samples/go/main.go new file mode 100644 index 0000000..c7ac73d --- /dev/null +++ b/samples/go/main.go @@ -0,0 +1,219 @@ +// Command main calls a Claude model through the standard Anthropic SDK. +// +// go run . print the reply text and token usage +// go run . -stream stream the reply text as it arrives +// go run . "your prompt" use your own prompt (flags go before the prompt) +// +// It exits 0 only when the reply has text; thinking-only or empty replies and every error +// exit nonzero. Errors report the HTTP status and error type but never the credential, the +// endpoint, the model name or the response body. +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "net/url" + "os" + "os/signal" + "regexp" + "strings" + "time" + + "github.com/anthropics/anthropic-sdk-go/v2" + + "github.com/Azure-Samples/claude/samples/go/clientauth" +) + +const ( + defaultPrompt = "What are 3 things to visit in Seattle?" + maxTokens = 1024 + usage = "Usage: go run . [-stream] [prompt...]" +) + +// totalTimeout is the application policy of this sample, not a helper default: the whole call, +// including SDK retries and streaming, ends after 120 seconds. The SDK's own per-attempt +// timeout and retry defaults are untouched. +const totalTimeout = 120 * time.Second + +type runOptions struct { + clientOverrides + // totalTimeout bounds the whole call, including SDK retries and streaming. + totalTimeout time.Duration +} + +func main() { + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) + code := run(ctx, os.Args[1:], os.Getenv, os.Stdout, os.Stderr, runOptions{}) + stop() + os.Exit(code) +} + +func run(ctx context.Context, args []string, getenv func(string) string, stdout, stderr io.Writer, options runOptions) int { + flags := flag.NewFlagSet("main", flag.ContinueOnError) + flags.SetOutput(io.Discard) + stream := flags.Bool("stream", false, "stream the reply text") + if err := flags.Parse(args); err != nil { + if errors.Is(err, flag.ErrHelp) { + fmt.Fprintln(stdout, usage) + return 0 + } + fmt.Fprintln(stderr, usage) + return 2 + } + prompt := strings.TrimSpace(strings.Join(flags.Args(), " ")) + if prompt == "" { + prompt = defaultPrompt + } + + total := options.totalTimeout + if total == 0 { + total = totalTimeout + } + ctx, cancel := context.WithTimeout(ctx, total) + defer cancel() + + loaded, err := loadSettings(getenv) + if err != nil { + fmt.Fprintln(stderr, describeError(ctx, err, total)) + return 1 + } + client, err := configuredClient(loaded, options.clientOverrides) + if err != nil { + fmt.Fprintln(stderr, describeError(ctx, err, total)) + return 1 + } + params := anthropic.MessageNewParams{ + Model: anthropic.Model(loaded.model), + MaxTokens: maxTokens, + Messages: []anthropic.MessageParam{anthropic.NewUserMessage(anthropic.NewTextBlock(prompt))}, + } + + var code int + if *stream { + code, err = streamReply(ctx, client, params, stdout, stderr) + } else { + code, err = printReply(ctx, client, params, stdout, stderr) + } + if err != nil { + fmt.Fprintln(stderr, describeError(ctx, err, total)) + return 1 + } + return code +} + +func printReply(ctx context.Context, client anthropic.Client, params anthropic.MessageNewParams, stdout, stderr io.Writer) (int, error) { + message, err := client.Messages.New(ctx, params) + if err != nil { + return 0, err + } + hasText := false + for _, block := range message.Content { + if block.Type == "text" && strings.TrimSpace(block.Text) != "" { + fmt.Fprintln(stdout, block.Text) + hasText = true + } + } + if !hasText { + return noText(string(message.StopReason), stderr), nil + } + fmt.Fprintf(stdout, "\n[usage] input=%d output=%d\n", message.Usage.InputTokens, message.Usage.OutputTokens) + return 0, nil +} + +func streamReply(ctx context.Context, client anthropic.Client, params anthropic.MessageNewParams, stdout, stderr io.Writer) (int, error) { + stream := client.Messages.NewStreaming(ctx, params) + defer stream.Close() + var message anthropic.Message + hasText := false + for stream.Next() { + event := stream.Current() + if err := message.Accumulate(event); err != nil { + return 0, err + } + if delta, ok := event.AsAny().(anthropic.ContentBlockDeltaEvent); ok { + if text, ok := delta.Delta.AsAny().(anthropic.TextDelta); ok { + hasText = hasText || strings.TrimSpace(text.Text) != "" + io.WriteString(stdout, text.Text) + } + } + } + if err := stream.Err(); err != nil { + return 0, err + } + io.WriteString(stdout, "\n") + if !hasText { + return noText(string(message.StopReason), stderr), nil + } + return 0, nil +} + +func noText(stopReason string, stderr io.Writer) int { + fmt.Fprintf(stderr, "No text response (stop_reason=%s). Increase max_tokens if the response exhausted its budget.\n", stopReason) + return 1 +} + +var errorType = regexp.MustCompile(`^[a-z_]{1,64}$`) + +func describeError(ctx context.Context, err error, total time.Duration) string { + var ( + config *configError + setup *credentialSetupError + api *anthropic.Error + transport *url.Error + ) + switch { + case errors.As(err, &config): + return config.Error() + case errors.As(err, &setup): + return "Could not create the Azure credential. Check AZURE_TOKEN_CREDENTIALS, AZURE_TENANT_ID and AZURE_CLIENT_ID." + case errors.Is(err, clientauth.ErrCredentialProvider): + return "The credential provider failed. Sign in with the Azure CLI or select another AZURE_TOKEN_CREDENTIALS." + case errors.Is(err, clientauth.ErrInvalidCredential): + return "The credential provider returned an invalid value." + case errors.Is(err, clientauth.ErrDifferentOrigin): + return "Refusing to send credentials to a different origin." + case errors.Is(err, clientauth.ErrRedirectRefused): + return "The endpoint answered with a redirect, which is never followed." + case errors.As(err, &api): + label := "" + if kind := string(api.Type()); errorType.MatchString(kind) { + label = " (" + kind + ")" + } + message := fmt.Sprintf("Request failed with HTTP %d%s.", api.StatusCode, label) + if hint := httpHint(api.StatusCode); hint != "" { + message += " " + hint + } + return message + case errors.Is(err, context.DeadlineExceeded): + if ctx.Err() != nil { + return fmt.Sprintf("Request timed out after %g seconds.", total.Seconds()) + } + return "Request timed out." + case errors.Is(err, context.Canceled): + return "Request was cancelled." + case errors.As(err, &transport): + return "Could not connect to the endpoint." + } + return fmt.Sprintf("Unexpected error (%T).", err) +} + +func httpHint(status int) string { + switch { + case status >= 300 && status < 400: + return "The endpoint answered with a redirect, which is never followed." + case status == 401: + return "The credential was rejected. Check AUTH_MODE, the token scope or the API key." + case status == 403: + return "The caller is not permitted to use this resource. Check its role assignment or key." + case status == 404: + return "The endpoint path or model name was not found. Check the base URL and model settings." + case status == 429: + return "The request was rate limited. Retry later." + case status >= 500: + return "The service reported an error. Retry later." + } + return "" +} diff --git a/samples/go/main_test.go b/samples/go/main_test.go new file mode 100644 index 0000000..bab29e4 --- /dev/null +++ b/samples/go/main_test.go @@ -0,0 +1,783 @@ +package main + +import ( + "bytes" + "context" + "errors" + "fmt" + "net/http" + "os" + "os/exec" + "reflect" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + + "github.com/Azure-Samples/claude/samples/go/internal/testserver" +) + +func env(pairs map[string]string) func(string) string { + return func(name string) string { return pairs[name] } +} + +func retries(n int) *int { return &n } + +type fakeCredential struct { + calls atomic.Int32 + scopes [][]string + err error +} + +func (f *fakeCredential) GetToken(_ context.Context, options policy.TokenRequestOptions) (azcore.AccessToken, error) { + f.scopes = append(f.scopes, options.Scopes) + n := f.calls.Add(1) + if f.err != nil { + return azcore.AccessToken{}, f.err + } + return azcore.AccessToken{Token: fmt.Sprintf("token-%d", n), ExpiresOn: time.Now().Add(time.Hour)}, nil +} + +const ( + canonicalURL = "https://example.services.ai.azure.com/anthropic" + legacyURL = "https://legacy.example" +) + +func canonicalEnv(extra map[string]string) map[string]string { + environment := map[string]string{"ANTHROPIC_BASE_URL": canonicalURL, "ANTHROPIC_MODEL": "sample-deployment"} + for k, v := range extra { + environment[k] = v + } + return environment +} + +func legacyEnv(extra map[string]string) map[string]string { + environment := map[string]string{"CLAUDE_BASE_URL": legacyURL, "CLAUDE_DEPLOYMENT_NAME": "legacy-deployment"} + for k, v := range extra { + environment[k] = v + } + return environment +} + +func TestCanonicalProfileRequiresAnExplicitAuthMode(t *testing.T) { + _, err := loadSettings(env(canonicalEnv(nil))) + var config *configError + if !errors.As(err, &config) || err.Error() != "ANTHROPIC_BASE_URL is set, so AUTH_MODE must be set explicitly to bearer or api_key." { + t.Fatalf("err = %v", err) + } + + got, err := loadSettings(env(canonicalEnv(map[string]string{"AUTH_MODE": "bearer"}))) + if err != nil { + t.Fatal(err) + } + want := settings{ + profile: "anthropic", + baseURL: canonicalURL, + model: "sample-deployment", + auth: authSettings{mode: "bearer", credential: "AzureCliCredential", scope: "https://ai.azure.com/.default"}, + } + if !reflect.DeepEqual(got, want) { + t.Errorf("settings = %+v, want %+v", got, want) + } +} + +func TestLegacyProfileDefaultsToBearer(t *testing.T) { + got, err := loadSettings(env(legacyEnv(nil))) + if err != nil { + t.Fatal(err) + } + if got.profile != "claude" || got.baseURL != legacyURL || got.model != "legacy-deployment" || got.auth.mode != "bearer" || got.apiVersion != "" { + t.Errorf("settings = %+v", got) + } +} + +func TestACompleteCanonicalProfileOverridesTheLegacyOneEntirely(t *testing.T) { + environment := canonicalEnv(map[string]string{ + "AUTH_MODE": "api_key", "ANTHROPIC_API_KEY": "native-key", + "CLAUDE_BASE_URL": legacyURL, "CLAUDE_DEPLOYMENT_NAME": "legacy-deployment", "CLAUDE_API_KEY": "legacy-key", + }) + got, err := loadSettings(env(environment)) + want := settings{ + profile: "anthropic", + baseURL: canonicalURL, + model: "sample-deployment", + auth: authSettings{mode: "api_key", apiKey: "native-key", keyHeader: "Authorization"}, + } + if err != nil || !reflect.DeepEqual(got, want) { + t.Errorf("settings = %+v, %v; want %+v", got, err, want) + } +} + +func TestLoadSettingsBearerAndAPIKeyDetails(t *testing.T) { + bearer, err := loadSettings(env(canonicalEnv(map[string]string{ + "AUTH_MODE": "bearer", "AZURE_TOKEN_CREDENTIALS": "ManagedIdentityCredential", "AZURE_TENANT_ID": "example-tenant", + "AZURE_CLIENT_ID": "example-client", "TOKEN_SCOPE": "https://example.test/.default", + }))) + want := authSettings{mode: "bearer", credential: "ManagedIdentityCredential", tenantID: "example-tenant", clientID: "example-client", scope: "https://example.test/.default"} + if err != nil || bearer.auth != want { + t.Errorf("bearer settings: %+v, %v", bearer.auth, err) + } + + keyed, err := loadSettings(env(legacyEnv(map[string]string{"AUTH_MODE": "api_key", "CLAUDE_API_KEY": "legacy-key"}))) + if err != nil || keyed.auth != (authSettings{mode: "api_key", apiKey: "legacy-key", keyHeader: "Authorization"}) || keyed.apiVersion != "" { + t.Errorf("legacy api key defaults: %+v, %v", keyed, err) + } + custom, err := loadSettings(env(canonicalEnv(map[string]string{ + "AUTH_MODE": "api_key", "ANTHROPIC_API_KEY": "native-key", "API_KEY_HEADER": "x-api-key", "ANTHROPIC_API_VERSION": "2023-06-01", + }))) + if err != nil || custom.auth.apiKey != "native-key" || custom.auth.keyHeader != "x-api-key" || custom.apiVersion != "2023-06-01" { + t.Errorf("api key overrides: %+v, %v", custom, err) + } +} + +func TestTheFamiliesAreNeverMixed(t *testing.T) { + cases := []struct { + name string + env map[string]string + want string + }{ + {"canonical URL, legacy model", + map[string]string{"ANTHROPIC_BASE_URL": "https://example.test", "AUTH_MODE": "bearer", "CLAUDE_DEPLOYMENT_NAME": "legacy-deployment"}, + "ANTHROPIC_BASE_URL is set, so ANTHROPIC_MODEL is required; CLAUDE_DEPLOYMENT_NAME is not used with it."}, + {"canonical URL, legacy key", + map[string]string{"ANTHROPIC_BASE_URL": "https://example.test", "ANTHROPIC_MODEL": "native-model", "AUTH_MODE": "api_key", "CLAUDE_API_KEY": "legacy-key-canary"}, + "AUTH_MODE=api_key with ANTHROPIC_BASE_URL requires ANTHROPIC_API_KEY; CLAUDE_API_KEY is not used with it."}, + {"legacy URL, canonical model", + map[string]string{"CLAUDE_BASE_URL": "https://example.test", "AUTH_MODE": "bearer", "ANTHROPIC_MODEL": "native-model"}, + "CLAUDE_BASE_URL is set, so CLAUDE_DEPLOYMENT_NAME is required; ANTHROPIC_MODEL is not used with it."}, + {"legacy URL, canonical key", + legacyEnv(map[string]string{"AUTH_MODE": "api_key", "ANTHROPIC_API_KEY": "native-key-canary"}), + "AUTH_MODE=api_key with CLAUDE_BASE_URL requires CLAUDE_API_KEY; ANTHROPIC_API_KEY is not used with it."}, + } + for _, c := range cases { + _, err := loadSettings(env(c.env)) + var config *configError + if !errors.As(err, &config) || err.Error() != c.want { + t.Errorf("%s: err = %v", c.name, err) + } + } +} + +func TestLoadSettingsReportsMissingOrInvalidConfigurationWithoutValues(t *testing.T) { + _, err := loadSettings(env(nil)) + want := "Set ANTHROPIC_BASE_URL, ANTHROPIC_MODEL and AUTH_MODE, or the legacy CLAUDE_BASE_URL and CLAUDE_DEPLOYMENT_NAME." + if err == nil || err.Error() != want { + t.Errorf("err = %v", err) + } + if _, err := loadSettings(env(map[string]string{"ANTHROPIC_MODEL": "native-model", "CLAUDE_DEPLOYMENT_NAME": "legacy"})); err == nil { + t.Error("a model without a base URL must not select a profile") + } + for _, family := range []map[string]string{canonicalEnv(nil), legacyEnv(nil)} { + family["AUTH_MODE"] = "basic" + if _, err := loadSettings(env(family)); err == nil || err.Error() != "AUTH_MODE must be bearer or api_key." { + t.Errorf("err = %v", err) + } + } +} + +type recordedFactory struct { + name string + options any +} + +func recordingFactories() (*[]recordedFactory, credentialFactories) { + var calls []recordedFactory + fake := &fakeCredential{} + return &calls, credentialFactories{ + azureCLI: func(o *azidentity.AzureCLICredentialOptions) (azcore.TokenCredential, error) { + calls = append(calls, recordedFactory{"AzureCliCredential", *o}) + return fake, nil + }, + azureDeveloperCLI: func(o *azidentity.AzureDeveloperCLICredentialOptions) (azcore.TokenCredential, error) { + calls = append(calls, recordedFactory{"AzureDeveloperCliCredential", *o}) + return fake, nil + }, + managedIdentity: func(o *azidentity.ManagedIdentityCredentialOptions) (azcore.TokenCredential, error) { + calls = append(calls, recordedFactory{"ManagedIdentityCredential", *o}) + return fake, nil + }, + } +} + +func TestCreateCredentialBuildsExactlyTheNamedCredential(t *testing.T) { + calls, factories := recordingFactories() + for _, source := range []string{"AzureCliCredential", "AzureDeveloperCliCredential", "ManagedIdentityCredential"} { + if _, err := createCredential(source, "example-tenant", "example-client", factories); err != nil { + t.Fatal(err) + } + } + if _, err := createCredential("ManagedIdentityCredential", "example-tenant", "", factories); err != nil { + t.Fatal(err) + } + + want := []recordedFactory{ + {"AzureCliCredential", azidentity.AzureCLICredentialOptions{TenantID: "example-tenant"}}, + {"AzureDeveloperCliCredential", azidentity.AzureDeveloperCLICredentialOptions{TenantID: "example-tenant"}}, + {"ManagedIdentityCredential", azidentity.ManagedIdentityCredentialOptions{ID: azidentity.ClientID("example-client")}}, + {"ManagedIdentityCredential", azidentity.ManagedIdentityCredentialOptions{}}, + } + if !reflect.DeepEqual(*calls, want) { + t.Errorf("factory calls = %+v\nwant %+v", *calls, want) + } +} + +func TestCreateCredentialHasNoFallback(t *testing.T) { + calls, factories := recordingFactories() + for _, source := range []string{"DefaultAzureCredential", "typo", "azureclicredential", ""} { + _, err := createCredential(source, "", "", factories) + var config *configError + if !errors.As(err, &config) || !strings.Contains(err.Error(), "AZURE_TOKEN_CREDENTIALS") { + t.Errorf("%q: err = %v", source, err) + } + } + if len(*calls) != 0 { + t.Errorf("no credential may be built, got %v", *calls) + } +} + +func TestCreateCredentialBuildsTheRealAzureIdentityTypesWithoutContactingAnything(t *testing.T) { + cli, err := createCredential("AzureCliCredential", "example-tenant", "", azureIdentityCredentials) + if _, ok := cli.(*azidentity.AzureCLICredential); !ok || err != nil { + t.Errorf("AzureCliCredential: %T, %v", cli, err) + } + azd, err := createCredential("AzureDeveloperCliCredential", "", "", azureIdentityCredentials) + if _, ok := azd.(*azidentity.AzureDeveloperCLICredential); !ok || err != nil { + t.Errorf("AzureDeveloperCliCredential: %T, %v", azd, err) + } + identity, err := createCredential("ManagedIdentityCredential", "", "example-client", azureIdentityCredentials) + if _, ok := identity.(*azidentity.ManagedIdentityCredential); !ok || err != nil { + t.Errorf("ManagedIdentityCredential: %T, %v", identity, err) + } +} + +func TestTokenProviderRequestsTheScopeOnEveryCallWithoutCachingOfItsOwn(t *testing.T) { + credential := &fakeCredential{} + provider := tokenProvider(credential, defaultTokenScope) + if credential.calls.Load() != 0 { + t.Fatal("the provider must be lazy") + } + + first, err1 := provider(context.Background()) + second, err2 := provider(context.Background()) + + if err1 != nil || err2 != nil || first != "token-1" || second != "token-2" { + t.Errorf("tokens = %q, %q (%v, %v)", first, second, err1, err2) + } + if want := [][]string{{defaultTokenScope}, {defaultTokenScope}}; !reflect.DeepEqual(credential.scopes, want) { + t.Errorf("scopes = %v", credential.scopes) + } + + failing := &fakeCredential{err: errors.New("login required")} + if _, err := tokenProvider(failing, defaultTokenScope)(context.Background()); !errors.Is(err, failing.err) { + t.Errorf("err = %v", err) + } +} + +type output struct{ stdout, stderr bytes.Buffer } + +func (o *output) run(args []string, environment map[string]string, options runOptions) int { + return run(context.Background(), args, env(environment), &o.stdout, &o.stderr, options) +} + +var ( + textReply = testserver.Message("end_turn", testserver.ThinkingBlock, testserver.TextBlock("OK")) + thinkingOnly = testserver.Message("max_tokens", testserver.ThinkingBlock) +) + +func sampleEnv(server *testserver.Server, extra map[string]string) map[string]string { + environment := map[string]string{ + "ANTHROPIC_BASE_URL": server.URL + "/anthropic", + "ANTHROPIC_MODEL": "sample-deployment", + "AUTH_MODE": "api_key", + "ANTHROPIC_API_KEY": "sample-key", + } + for k, v := range extra { + environment[k] = v + } + return environment +} + +func fastRetries() runOptions { + return runOptions{clientOverrides: clientOverrides{maxRetries: retries(0)}} +} + +func TestPrintsReplyTextAndUsageButNotThinking(t *testing.T) { + testserver.CleanEnvironment(t) + server := testserver.New(t, testserver.Respond(textReply)) + var out output + + if code := out.run(nil, sampleEnv(server, nil), runOptions{}); code != 0 { + t.Fatalf("exit code %d, stderr %q", code, out.stderr.String()) + } + + if got, want := out.stdout.String(), "OK\n\n[usage] input=1 output=2\n"; got != want { + t.Errorf("stdout = %q, want %q", got, want) + } + if out.stderr.Len() != 0 { + t.Errorf("stderr = %q", out.stderr.String()) + } + r := server.Requests()[0] + if r.URL != "/anthropic/v1/messages" || r.Header.Get("Authorization") != "Bearer sample-key" { + t.Errorf("request = %s %v", r.URL, r.Header) + } + for _, name := range []string{"X-Api-Key", "Anthropic-Beta"} { + if r.Header.Get(name) != "" { + t.Errorf("%s must be absent", name) + } + } + if r.Header.Get("Anthropic-Version") == "" || r.Header.Get("Anthropic-Version") == "2023-06-01" { + t.Errorf("the SDK's own anthropic-version must be used, got %q", r.Header.Get("Anthropic-Version")) + } + wantBody := `"max_tokens":1024` + if !strings.Contains(r.Body, wantBody) || !strings.Contains(r.Body, `"model":"sample-deployment"`) || !strings.Contains(r.Body, "What are 3 things to visit in Seattle?") { + t.Errorf("body = %s", r.Body) + } +} + +func TestHonoursAPIKeyHeaderAndAPIVersion(t *testing.T) { + testserver.CleanEnvironment(t) + server := testserver.New(t, testserver.Respond(textReply)) + var out output + + environment := sampleEnv(server, map[string]string{"API_KEY_HEADER": "x-api-key", "ANTHROPIC_API_VERSION": "2023-06-01"}) + if code := out.run(nil, environment, runOptions{}); code != 0 { + t.Fatalf("exit code %d, stderr %q", code, out.stderr.String()) + } + + r := server.Requests()[0] + if r.Header.Get("X-Api-Key") != "sample-key" || r.Header.Get("Authorization") != "" || r.Header.Get("Anthropic-Version") != "2023-06-01" { + t.Errorf("headers = %v", r.Header) + } +} + +func TestReadsTheLegacyVariableNames(t *testing.T) { + testserver.CleanEnvironment(t) + server := testserver.New(t, testserver.Respond(textReply)) + var out output + environment := map[string]string{"CLAUDE_BASE_URL": server.URL, "CLAUDE_DEPLOYMENT_NAME": "legacy-deployment", "AUTH_MODE": "api_key", "CLAUDE_API_KEY": "legacy-key"} + + if code := out.run(nil, environment, runOptions{}); code != 0 { + t.Fatalf("exit code %d, stderr %q", code, out.stderr.String()) + } + + r := server.Requests()[0] + if r.URL != "/v1/messages" || r.Header.Get("Authorization") != "Bearer legacy-key" || !strings.Contains(r.Body, `"model":"legacy-deployment"`) { + t.Errorf("request = %s %v %s", r.URL, r.Header, r.Body) + } +} + +func TestBearerTokenForEveryAttemptAndNoAmbientCredentials(t *testing.T) { + testserver.CleanEnvironment(t) + t.Setenv("ANTHROPIC_API_KEY", "ambient-key-canary") + t.Setenv("ANTHROPIC_AUTH_TOKEN", "ambient-token-canary") + t.Setenv("ANTHROPIC_PROFILE", "nonexistent-canary-profile") + t.Setenv("ANTHROPIC_CUSTOM_HEADERS", "x-api-key: header-canary") + server := testserver.New(t, func(w http.ResponseWriter, r *http.Request, count int) { + if count < 2 { + testserver.Error(500, "retry-after-ms", "1")(w, r, count) + return + } + testserver.Respond(textReply)(w, r, count) + }) + var calls atomic.Int32 + var out output + options := runOptions{clientOverrides: clientOverrides{tokenProvider: func(context.Context) (string, error) { + return fmt.Sprintf("entra-test-token-%d", calls.Add(1)), nil + }}} + + // The canonical profile needs an explicit AUTH_MODE. + code := out.run(nil, map[string]string{"ANTHROPIC_BASE_URL": server.URL, "ANTHROPIC_MODEL": "sample-deployment", "AUTH_MODE": "bearer"}, options) + + if code != 0 { + t.Fatalf("exit code %d, stderr %q", code, out.stderr.String()) + } + requests := server.Requests() + if len(requests) != 2 { + t.Fatalf("got %d requests", len(requests)) + } + for i, r := range requests { + if got, want := r.Header.Get("Authorization"), fmt.Sprintf("Bearer entra-test-token-%d", i+1); got != want { + t.Errorf("attempt %d Authorization = %q, want %q", i, got, want) + } + if r.Header.Get("X-Api-Key") != "" || r.Header.Get("Anthropic-Beta") != "" || strings.Contains(fmt.Sprint(r.Header), "canary") { + t.Errorf("headers = %v", r.Header) + } + } +} + +func TestStreamsOnlyTheTextAndUsesACustomPrompt(t *testing.T) { + testserver.CleanEnvironment(t) + for _, flagForm := range []string{"-stream", "--stream"} { + server := testserver.New(t, testserver.Stream( + testserver.Block{Kind: "thinking", Text: "not for display"}, + testserver.Block{Kind: "text", Text: "Hello"}, + testserver.Block{Kind: "text", Text: " there"}, + )) + var out output + + if code := out.run([]string{flagForm, "Say", "hi"}, sampleEnv(server, nil), runOptions{}); code != 0 { + t.Fatalf("%s: exit code %d, stderr %q", flagForm, code, out.stderr.String()) + } + + if got := out.stdout.String(); got != "Hello there\n" { + t.Errorf("%s: stdout = %q", flagForm, got) + } + body := server.Requests()[0].Body + for _, want := range []string{`"stream":true`, `"max_tokens":1024`, `"content":[{"text":"Say hi"`} { + if !strings.Contains(body, want) { + t.Errorf("%s: body %s lacks %s", flagForm, body, want) + } + } + } +} + +func TestRepliesWithoutTextExitNonzero(t *testing.T) { + testserver.CleanEnvironment(t) + cases := map[string]string{ + "thinking only": thinkingOnly, + "empty": testserver.Message("end_turn"), + "blank text": testserver.Message("end_turn", testserver.TextBlock(" \n")), + } + for name, reply := range cases { + server := testserver.New(t, testserver.Respond(reply)) + var out output + if code := out.run(nil, sampleEnv(server, nil), runOptions{}); code != 1 { + t.Errorf("%s: exit code %d", name, code) + } + if !strings.Contains(out.stderr.String(), "No text response (stop_reason=") { + t.Errorf("%s: stderr = %q", name, out.stderr.String()) + } + if strings.Contains(out.stdout.String(), "not for display") || strings.Contains(out.stdout.String(), "[usage]") { + t.Errorf("%s: stdout = %q", name, out.stdout.String()) + } + } + server := testserver.New(t, testserver.Respond(thinkingOnly)) + var out output + out.run(nil, sampleEnv(server, nil), runOptions{}) + if !strings.Contains(out.stderr.String(), "max_tokens") { + t.Errorf("stderr = %q", out.stderr.String()) + } +} + +func TestAStreamWithoutTextExitsNonzero(t *testing.T) { + testserver.CleanEnvironment(t) + server := testserver.New(t, testserver.Stream(testserver.Block{Kind: "thinking", Text: "not for display"})) + var out output + + if code := out.run([]string{"-stream"}, sampleEnv(server, nil), runOptions{}); code != 1 { + t.Errorf("exit code %d", code) + } + + if !strings.Contains(out.stderr.String(), "No text response") || strings.Contains(out.stdout.String(), "not for display") { + t.Errorf("stdout %q stderr %q", out.stdout.String(), out.stderr.String()) + } +} + +func TestHTTPFailuresAreReportedWithoutSecrets(t *testing.T) { + testserver.CleanEnvironment(t) + for _, stream := range []bool{false, true} { + for _, status := range []int{401, 403, 404, 429, 500} { + server := testserver.New(t, testserver.Error(status)) + var out output + args := []string(nil) + if stream { + args = []string{"-stream"} + } + + code := out.run(args, sampleEnv(server, nil), fastRetries()) + + if code != 1 { + t.Errorf("status %d: exit code %d", status, code) + } + if want := fmt.Sprintf("HTTP %d (api_error)", status); !strings.Contains(out.stderr.String(), want) { + t.Errorf("status %d: stderr = %q", status, out.stderr.String()) + } + for _, secret := range []string{"sample-key", server.URL, strings.TrimPrefix(server.URL, "http://"), "sample-deployment", "test failure", "Request-ID"} { + if strings.Contains(out.stderr.String(), secret) { + t.Errorf("status %d: %q leaked: %s", status, secret, out.stderr.String()) + } + } + if out.stdout.Len() != 0 && !(stream && out.stdout.String() == "\n") { + t.Errorf("status %d: stdout = %q", status, out.stdout.String()) + } + } + } +} + +func TestARedirectIsAnErrorAndIsNotFollowed(t *testing.T) { + testserver.CleanEnvironment(t) + other := testserver.New(t, testserver.Respond(textReply)) + server := testserver.New(t, testserver.Redirect(http.StatusTemporaryRedirect, other.URL+"/v1/messages")) + var out output + + if code := out.run(nil, sampleEnv(server, nil), fastRetries()); code != 1 { + t.Errorf("exit code %d", code) + } + + if !strings.Contains(out.stderr.String(), "redirect") || strings.Contains(out.stderr.String(), other.URL) { + t.Errorf("stderr = %q", out.stderr.String()) + } + if other.Count() != 0 { + t.Errorf("the redirect target saw %d requests", other.Count()) + } +} + +func TestCredentialFailuresDoNotPrintTheProviderMessage(t *testing.T) { + testserver.CleanEnvironment(t) + server := testserver.New(t, testserver.Respond(textReply)) + environment := map[string]string{"ANTHROPIC_BASE_URL": server.URL, "ANTHROPIC_MODEL": "sample-deployment", "AUTH_MODE": "bearer"} + options := runOptions{clientOverrides: clientOverrides{ + maxRetries: retries(0), + tokenProvider: func(context.Context) (string, error) { + return "", errors.New("tenant details that must not be printed") + }, + }} + for _, args := range [][]string{nil, {"-stream"}} { + var out output + + if code := out.run(args, environment, options); code != 1 { + t.Errorf("%v: exit code %d", args, code) + } + + if !strings.Contains(out.stderr.String(), "The credential provider failed.") || strings.Contains(out.stderr.String(), "tenant details") { + t.Errorf("%v: stderr = %q", args, out.stderr.String()) + } + } + if server.Count() != 0 { + t.Errorf("no request may be sent, got %d", server.Count()) + } +} + +func TestMissingConfigurationExitsNonzeroWithoutContactingAnything(t *testing.T) { + testserver.CleanEnvironment(t) + var out output + + if code := out.run(nil, nil, runOptions{}); code != 1 { + t.Errorf("exit code %d", code) + } + + if !strings.HasPrefix(out.stderr.String(), "Set ANTHROPIC_BASE_URL, ANTHROPIC_MODEL and AUTH_MODE, or the legacy CLAUDE_BASE_URL") || out.stdout.Len() != 0 { + t.Errorf("stdout %q stderr %q", out.stdout.String(), out.stderr.String()) + } +} + +func TestNoCredentialGoesToTheEndpointOfTheOtherVariableFamily(t *testing.T) { + testserver.CleanEnvironment(t) + native := testserver.New(t, testserver.Respond(textReply)) + legacy := testserver.New(t, testserver.Respond(textReply)) + cases := []struct { + name string + env map[string]string + want string + }{ + {"canonical URL, legacy model and key", + map[string]string{"ANTHROPIC_BASE_URL": native.URL, "AUTH_MODE": "api_key", "CLAUDE_DEPLOYMENT_NAME": "legacy-model", "CLAUDE_API_KEY": "legacy-key-canary"}, + "ANTHROPIC_MODEL is required"}, + {"canonical URL and model, legacy key", + map[string]string{"ANTHROPIC_BASE_URL": native.URL, "ANTHROPIC_MODEL": "native-model", "AUTH_MODE": "api_key", "CLAUDE_API_KEY": "legacy-key-canary"}, + "requires ANTHROPIC_API_KEY"}, + {"legacy URL and model, canonical key", + map[string]string{"CLAUDE_BASE_URL": legacy.URL, "CLAUDE_DEPLOYMENT_NAME": "legacy-model", "AUTH_MODE": "api_key", "ANTHROPIC_API_KEY": "native-key-canary"}, + "requires CLAUDE_API_KEY"}, + {"legacy URL, canonical model and key", + map[string]string{"CLAUDE_BASE_URL": legacy.URL, "ANTHROPIC_MODEL": "native-model", "AUTH_MODE": "api_key", "ANTHROPIC_API_KEY": "native-key-canary"}, + "CLAUDE_DEPLOYMENT_NAME is required"}, + } + for _, c := range cases { + var out output + if code := out.run(nil, c.env, runOptions{}); code != 1 { + t.Errorf("%s: exit code %d", c.name, code) + } + if !strings.Contains(out.stderr.String(), c.want) || strings.Contains(out.stderr.String(), "canary") { + t.Errorf("%s: stderr = %q", c.name, out.stderr.String()) + } + } + if native.Count()+legacy.Count() != 0 { + t.Errorf("nothing may be sent, got %d and %d requests", native.Count(), legacy.Count()) + } +} + +func TestOnlyTheSelectedFamilyIsUsedWhenBothAreComplete(t *testing.T) { + testserver.CleanEnvironment(t) + native := testserver.New(t, testserver.Respond(textReply)) + legacy := testserver.New(t, testserver.Respond(textReply)) + both := map[string]string{ + "ANTHROPIC_BASE_URL": native.URL + "/anthropic", "ANTHROPIC_MODEL": "native-model", "ANTHROPIC_API_KEY": "native-key", + "CLAUDE_BASE_URL": legacy.URL, "CLAUDE_DEPLOYMENT_NAME": "legacy-model", "CLAUDE_API_KEY": "legacy-key", + "AUTH_MODE": "api_key", + } + var first, second output + + if code := first.run(nil, both, runOptions{}); code != 0 { + t.Fatalf("canonical: exit code %d, stderr %q", code, first.stderr.String()) + } + legacyOnly := map[string]string{} + for k, v := range both { + if k != "ANTHROPIC_BASE_URL" && k != "ANTHROPIC_MODEL" { + legacyOnly[k] = v // an ambient ANTHROPIC_API_KEY stays, and must not matter + } + } + if code := second.run(nil, legacyOnly, runOptions{}); code != 0 { + t.Fatalf("legacy: exit code %d, stderr %q", code, second.stderr.String()) + } + + if native.Count() != 1 || legacy.Count() != 1 { + t.Fatalf("requests: native=%d legacy=%d", native.Count(), legacy.Count()) + } + nativeRequest, legacyRequest := native.Requests()[0], legacy.Requests()[0] + if nativeRequest.URL != "/anthropic/v1/messages" || nativeRequest.Header.Get("Authorization") != "Bearer native-key" || !strings.Contains(nativeRequest.Body, `"model":"native-model"`) { + t.Errorf("canonical request = %s %v %s", nativeRequest.URL, nativeRequest.Header, nativeRequest.Body) + } + if legacyRequest.Header.Get("Authorization") != "Bearer legacy-key" || !strings.Contains(legacyRequest.Body, `"model":"legacy-model"`) { + t.Errorf("legacy request = %v %s", legacyRequest.Header, legacyRequest.Body) + } +} + +func TestACanonicalURLGetsATokenOnlyWhenBearerIsChosenExplicitly(t *testing.T) { + testserver.CleanEnvironment(t) + server := testserver.New(t, testserver.Respond(textReply)) + var calls atomic.Int32 + options := runOptions{clientOverrides: clientOverrides{tokenProvider: func(context.Context) (string, error) { + return fmt.Sprintf("entra-test-token-%d", calls.Add(1)), nil + }}} + canonical := map[string]string{"ANTHROPIC_BASE_URL": server.URL, "ANTHROPIC_MODEL": "sample-deployment"} + + var implicit output + if code := implicit.run(nil, canonical, options); code != 1 || !strings.Contains(implicit.stderr.String(), "AUTH_MODE must be set explicitly") { + t.Errorf("implicit: exit code %d, stderr %q", code, implicit.stderr.String()) + } + if calls.Load() != 0 || server.Count() != 0 { + t.Errorf("no token may be acquired and nothing sent: calls=%d requests=%d", calls.Load(), server.Count()) + } + + var explicit output + canonical["AUTH_MODE"] = "bearer" + if code := explicit.run(nil, canonical, options); code != 0 { + t.Fatalf("explicit: exit code %d, stderr %q", code, explicit.stderr.String()) + } + var legacy output + if code := legacy.run(nil, map[string]string{"CLAUDE_BASE_URL": server.URL, "CLAUDE_DEPLOYMENT_NAME": "legacy-deployment"}, options); code != 0 { + t.Fatalf("legacy default: exit code %d, stderr %q", code, legacy.stderr.String()) + } + requests := server.Requests() + if len(requests) != 2 || requests[0].Header.Get("Authorization") != "Bearer entra-test-token-1" || requests[1].Header.Get("Authorization") != "Bearer entra-test-token-2" { + t.Errorf("requests = %v", requests) + } +} + +func TestAnUnreachableEndpointIsReportedWithoutNamingIt(t *testing.T) { + testserver.CleanEnvironment(t) + closed := testserver.New(t, testserver.Respond(textReply)) + environment := sampleEnv(closed, nil) + closed.CloseClientConnections() + closed.Close() + var out output + + if code := out.run(nil, environment, fastRetries()); code != 1 { + t.Errorf("exit code %d", code) + } + + if got := out.stderr.String(); got != "Could not connect to the endpoint.\n" { + t.Errorf("stderr = %q", got) + } +} + +func TestTheWholeCallHasADeadline(t *testing.T) { + testserver.CleanEnvironment(t) + server := testserver.New(t, testserver.Hang) + var out output + + code := out.run(nil, sampleEnv(server, nil), runOptions{totalTimeout: 100 * time.Millisecond}) + + if code != 1 || !strings.Contains(out.stderr.String(), "timed out after 0.1 seconds") || strings.Contains(out.stderr.String(), server.URL) { + t.Errorf("exit code %d, stderr %q", code, out.stderr.String()) + } +} + +func TestHelpAndUnknownFlags(t *testing.T) { + var help output + if code := help.run([]string{"-h"}, nil, runOptions{}); code != 0 || !strings.Contains(help.stdout.String(), "Usage: go run .") { + t.Errorf("help: exit code %d, stdout %q", code, help.stdout.String()) + } + var unknown output + if code := unknown.run([]string{"-nope"}, nil, runOptions{}); code != 2 || !strings.Contains(unknown.stderr.String(), "Usage: go run .") { + t.Errorf("unknown flag: exit code %d, stderr %q", code, unknown.stderr.String()) + } +} + +func TestTheProcessEnvironmentIsNotModified(t *testing.T) { + testserver.CleanEnvironment(t) + t.Setenv("ANTHROPIC_FOUNDRY_RESOURCE", "unchanged-resource") + server := testserver.New(t, testserver.Respond(textReply)) + before := strings.Join(os.Environ(), "\x00") + var out output + + out.run(nil, sampleEnv(server, nil), runOptions{}) + + if strings.Join(os.Environ(), "\x00") != before { + t.Error("the process environment changed") + } +} + +const helperEnv = "CLAUDE_SAMPLE_HELPER_PROCESS" + +// TestHelperProcess is the command itself, started again by TestRunsAsACommand. +func TestHelperProcess(t *testing.T) { + if os.Getenv(helperEnv) != "1" { + t.Skip("only runs as a helper process") + } + args := os.Args + for i, arg := range args { + if arg == "--" { + args = args[i+1:] + break + } + } + os.Exit(run(context.Background(), args, os.Getenv, os.Stdout, os.Stderr, runOptions{})) +} + +func TestRunsAsACommand(t *testing.T) { + testserver.CleanEnvironment(t) + ok := testserver.New(t, testserver.Respond(textReply)) + streamed := testserver.New(t, testserver.Stream(testserver.Block{Kind: "text", Text: "Hello"})) + denied := testserver.New(t, testserver.Error(401)) + command := func(args []string, extra map[string]string) (int, string, string) { + cmd := exec.Command(os.Args[0], append([]string{"-test.run=^TestHelperProcess$", "--"}, args...)...) + cmd.Env = append(os.Environ(), helperEnv+"=1") + for k, v := range extra { + cmd.Env = append(cmd.Env, k+"="+v) + } + var stdout, stderr bytes.Buffer + cmd.Stdout, cmd.Stderr = &stdout, &stderr + err := cmd.Run() + code := 0 + var exit *exec.ExitError + if errors.As(err, &exit) { + code = exit.ExitCode() + } else if err != nil { + t.Fatalf("running the command: %v", err) + } + return code, stdout.String(), stderr.String() + } + + if code, stdout, stderr := command(nil, sampleEnv(ok, nil)); code != 0 || stdout != "OK\n\n[usage] input=1 output=2\n" || stderr != "" { + t.Errorf("plain: %d %q %q", code, stdout, stderr) + } + if code, stdout, stderr := command([]string{"-stream"}, sampleEnv(streamed, nil)); code != 0 || stdout != "Hello\n" || stderr != "" { + t.Errorf("stream: %d %q %q", code, stdout, stderr) + } + code, stdout, stderr := command(nil, sampleEnv(denied, nil)) + if code != 1 || stdout != "" || !strings.Contains(stderr, "HTTP 401") || strings.Contains(stderr, "sample-key") { + t.Errorf("failure: %d %q %q", code, stdout, stderr) + } + if code, _, _ := command(nil, nil); code != 1 { + t.Errorf("missing configuration: exit code %d", code) + } + if code, _, _ := command([]string{"-bogus"}, nil); code != 2 { + t.Errorf("unknown flag: exit code %d", code) + } +} diff --git a/samples/go/sample_client.go b/samples/go/sample_client.go new file mode 100644 index 0000000..b90e763 --- /dev/null +++ b/samples/go/sample_client.go @@ -0,0 +1,48 @@ +package main + +import ( + "errors" + "net/http" + "time" + + "github.com/anthropics/anthropic-sdk-go/v2" + + "github.com/Azure-Samples/claude/samples/go/clientauth" +) + +// clientOverrides lets tests replace the Microsoft Entra ID token provider and the transport. +type clientOverrides struct { + tokenProvider clientauth.CredentialProvider + httpClient *http.Client + maxRetries *int + requestTimeout time.Duration +} + +func configuredClient(s settings, overrides clientOverrides) (anthropic.Client, error) { + options := clientauth.Options{ + BaseURL: s.baseURL, + APIVersion: s.apiVersion, + HTTPClient: overrides.httpClient, + MaxRetries: overrides.maxRetries, + RequestTimeout: overrides.requestTimeout, + } + if s.auth.mode == "api_key" { + options.APIKey = s.auth.apiKey + options.KeyHeader = s.auth.keyHeader + return clientauth.CreateClient(options) + } + + options.TokenProvider = overrides.tokenProvider + if options.TokenProvider == nil { + credential, err := createCredential(s.auth.credential, s.auth.tenantID, s.auth.clientID, azureIdentityCredentials) + if err != nil { + var config *configError + if errors.As(err, &config) { + return anthropic.Client{}, err + } + return anthropic.Client{}, &credentialSetupError{cause: err} + } + options.TokenProvider = tokenProvider(credential, s.auth.scope) + } + return clientauth.CreateClient(options) +} diff --git a/samples/go/settings.go b/samples/go/settings.go new file mode 100644 index 0000000..d5db34a --- /dev/null +++ b/samples/go/settings.go @@ -0,0 +1,114 @@ +package main + +import "fmt" + +// configError is a problem with the environment configuration. Its message names only +// variables, never values. +type configError struct{ message string } + +func (e *configError) Error() string { return e.message } + +const ( + defaultTokenScope = "https://ai.azure.com/.default" + defaultCredential = "AzureCliCredential" + + profileCanonical = "anthropic" // the ANTHROPIC_* variable family + profileLegacy = "claude" // the CLAUDE_* variable family +) + +type authSettings struct { + mode string // "bearer" or "api_key" + + // bearer + credential, tenantID, clientID, scope string + + // api_key + apiKey, keyHeader string +} + +type settings struct { + profile string + baseURL, model string + // apiVersion is sent as anthropic-version only when ANTHROPIC_API_VERSION is set; + // otherwise the SDK default applies. + apiVersion string + auth authSettings +} + +type profileVariables struct { + baseURL, model, apiKey string + // otherModel and otherKey name the other family's variables in errors; they are never + // read for this profile. + otherModel, otherKey string + // explicitAuthMode: the canonical profile never defaults to a token, so an ambient URL + // cannot silently receive one. + explicitAuthMode bool +} + +var profiles = map[string]profileVariables{ + profileCanonical: { + baseURL: "ANTHROPIC_BASE_URL", model: "ANTHROPIC_MODEL", apiKey: "ANTHROPIC_API_KEY", + otherModel: "CLAUDE_DEPLOYMENT_NAME", otherKey: "CLAUDE_API_KEY", + explicitAuthMode: true, + }, + profileLegacy: { + baseURL: "CLAUDE_BASE_URL", model: "CLAUDE_DEPLOYMENT_NAME", apiKey: "CLAUDE_API_KEY", + otherModel: "ANTHROPIC_MODEL", otherKey: "ANTHROPIC_API_KEY", + }, +} + +// loadSettings selects the canonical profile when ANTHROPIC_BASE_URL is set and the legacy one +// when only CLAUDE_BASE_URL is. The URL, model and key all come from the selected family, so a +// value from one family is never combined with another family's endpoint. +func loadSettings(getenv func(string) string) (settings, error) { + profile, baseURL := "", "" + if value := getenv("ANTHROPIC_BASE_URL"); value != "" { + profile, baseURL = profileCanonical, value + } else if value := getenv("CLAUDE_BASE_URL"); value != "" { + profile, baseURL = profileLegacy, value + } + if profile == "" { + return settings{}, &configError{"Set ANTHROPIC_BASE_URL, ANTHROPIC_MODEL and AUTH_MODE, or the legacy CLAUDE_BASE_URL and CLAUDE_DEPLOYMENT_NAME."} + } + names := profiles[profile] + + model := getenv(names.model) + if model == "" { + return settings{}, &configError{fmt.Sprintf("%s is set, so %s is required; %s is not used with it.", names.baseURL, names.model, names.otherModel)} + } + mode := getenv("AUTH_MODE") + if mode == "" { + if names.explicitAuthMode { + return settings{}, &configError{fmt.Sprintf("%s is set, so AUTH_MODE must be set explicitly to bearer or api_key.", names.baseURL)} + } + mode = "bearer" + } + loaded := settings{profile: profile, baseURL: baseURL, model: model, apiVersion: getenv("ANTHROPIC_API_VERSION")} + + switch mode { + case "bearer": + loaded.auth = authSettings{ + mode: mode, + credential: orDefault(getenv("AZURE_TOKEN_CREDENTIALS"), defaultCredential), + tenantID: getenv("AZURE_TENANT_ID"), + clientID: getenv("AZURE_CLIENT_ID"), + scope: orDefault(getenv("TOKEN_SCOPE"), defaultTokenScope), + } + case "api_key": + apiKey := getenv(names.apiKey) + if apiKey == "" { + return settings{}, &configError{fmt.Sprintf("AUTH_MODE=api_key with %s requires %s; %s is not used with it.", names.baseURL, names.apiKey, names.otherKey)} + } + loaded.auth = authSettings{mode: mode, apiKey: apiKey, keyHeader: orDefault(getenv("API_KEY_HEADER"), "Authorization")} + default: + return settings{}, &configError{"AUTH_MODE must be bearer or api_key."} + } + return loaded, nil +} + +func orDefault(value, fallback string) string { + if value == "" { + return fallback + } + return value +} diff --git a/samples/java/README.md b/samples/java/README.md new file mode 100644 index 0000000..32e7f5e --- /dev/null +++ b/samples/java/README.md @@ -0,0 +1,165 @@ +# Java sample: standard Anthropic SDK with explicit authentication + +One command-line app that makes a Messages call, or a streaming call with `--stream`, using the **standard** +`AnthropicClient` from the official [`com.anthropic:anthropic-java`](https://central.sonatype.com/artifact/com.anthropic/anthropic-java) +SDK (3.3.0). Authentication comes from the official +[`com.azure:azure-identity`](https://central.sonatype.com/artifact/com.azure/azure-identity) library (1.18.7) or +from an API key. There is no `anthropic-java-foundry` artifact, client subclass, alternate Messages API or custom +retry loop. + +| File (under `src/main/java/sample/anthropic`) | Role | +|---|---| +| `ClientFactory.java` | Generic helper. Builds the standard client with one explicit credential. Knows no identity library and reads no environment or system property. Copy this one file (it needs only the Anthropic SDK). | +| `CredentialSelector.java` | The only code that uses Azure Identity: selects one credential class and adapts it to the helper's `Supplier`. | +| `SampleSettings.java`, `SampleRunner.java`, `Main.java` | Environment parsing, the Messages/streaming calls, output and exit codes. | + +Tests live in `src/test/java/sample/anthropic` and run offline. + +## Run + +Requires JDK 17 or later and Maven 3.9 or later. For the default bearer mode sign in first (`az login`, or `azd auth +login` with `AZURE_TOKEN_CREDENTIALS=AzureDeveloperCliCredential`) in the intended tenant and subscription. + +```powershell +# The `azd up` outputs as they are (the legacy profile; bearer authentication by default) ... +$env:CLAUDE_BASE_URL = "https://.services.ai.azure.com/anthropic" +$env:CLAUDE_DEPLOYMENT_NAME = "" +# ... or the canonical profile, which must name its authentication mode: +# $env:ANTHROPIC_BASE_URL = "https://.services.ai.azure.com/anthropic" +# $env:ANTHROPIC_MODEL = "" +# $env:AUTH_MODE = "bearer" +cd samples/java +mvn -q exec:java "-Dexec.args=Say hello in one sentence." +mvn -q exec:java "-Dexec.args=--stream Say hello in one sentence." +``` + +Output is the response text followed by `usage: input_tokens=N output_tokens=M`. With `--stream` the text is printed as it +arrives. A response without non-blank text (for example thinking blocks only), a stream that ends before +`message_stop`, and every transport, credential or HTTP error exit non-zero and print the typed cause and HTTP status, +never a token or key. Exit codes: `0` success, `1` request failure, `2` configuration or usage error. Each call uses +`max_tokens` 1024 and a 120 second per-call timeout. The timeout is this sample's own policy, set explicitly in +`SampleRunner`; `ClientFactory` keeps the SDK's timeout unless the caller sets `timeout(...)`. The SDK's default retries +are unchanged. + +`mvn exec:java` reports every non-zero exit as `1`. For the exact codes run the class directly: + +```powershell +mvn -q dependency:build-classpath "-Dmdep.outputFile=target/classpath.txt" +java -cp "target/classes;$(Get-Content target/classpath.txt -Raw)" sample.anthropic.Main --stream "Say hello" # use ':' on Linux/macOS +``` + +## Configuration + +Read by the sample entrypoint only (never by `ClientFactory`). Real keys and IDs belong in the environment or a secret +store, not in tracked files. + +**The endpoint variable selects one profile, and the profile decides which model and key variables are read.** The two +families are never mixed, so an endpoint, deployment name or key left in the environment for another tool cannot be +paired with the wrong partner or silently receive an identity token. + +| | Canonical profile | Legacy profile (`azd` outputs) | +|---|---|---| +| Selected by | `ANTHROPIC_BASE_URL` is set (it wins when both URLs are set) | only `CLAUDE_BASE_URL` is set | +| Model or deployment | `ANTHROPIC_MODEL` (required) | `CLAUDE_DEPLOYMENT_NAME` (required) | +| Key in `AUTH_MODE=api_key` | `ANTHROPIC_API_KEY` | `CLAUDE_API_KEY` | +| `AUTH_MODE` | must be set: `bearer` or `api_key` | `bearer` unless set to `api_key` | + +The other family's variables are ignored, never a fallback. A missing model, key or (canonical) `AUTH_MODE` is a +configuration error, exit `2`, that names the variable. + +Both profiles also read: + +| Variable | Meaning | Default | +|---|---|---| +| `AZURE_TOKEN_CREDENTIALS` | One credential class: `AzureCliCredential`, `AzureDeveloperCliCredential` or `ManagedIdentityCredential`. Nothing falls back to another credential. | `AzureCliCredential` | +| `AZURE_TENANT_ID` | Tenant for the CLI credentials. | credential default | +| `AZURE_CLIENT_ID` | Client ID of a user-assigned managed identity. | system-assigned | +| `TOKEN_SCOPE` | Scope requested from the credential. | `https://ai.azure.com/.default` | +| `API_KEY_HEADER` | `Authorization` sends `Bearer ` (the SDK's own key semantics); any other name, such as `x-api-key`, sends the raw key. | `Authorization` | +| `ANTHROPIC_API_VERSION` | `anthropic-version` header. Unset keeps the SDK default. | unset | + +The base URL must be `https` (plain `http` only for loopback test servers) and the model or deployment name is sent +verbatim. `AzureCliCredential` and `AzureDeveloperCliCredential` are built with a 60 second `processTimeout`, so a slow +CLI start is not reported as a failure; `ManagedIdentityCredential` has no such option. +## Use the helper in your own code + +```java +AnthropicClient client = ClientFactory.create(ClientFactory.Options.builder() + .baseUrl("https://.services.ai.azure.com/anthropic") + // Exactly one credential: a per-attempt bearer supplier ... + .tokenSupplier(() -> credential + .getTokenSync(new TokenRequestContext().addScopes("https://ai.azure.com/.default")) + .getToken()) + // ... or .apiKey(key).apiKeyHeader("x-api-key") (default header: Authorization). + // Optional: .tokenExecutor(executor) decides where the supplier runs for client.async() calls. + .build()); +try { + Message message = client.messages().create(MessageCreateParams.builder() /* standard SDK call */ .build()); +} finally { + client.close(); +} +``` + +`ClientFactory.create` returns the unmodified SDK client; everything else is the SDK's own API. What it adds: + +- **One explicit credential.** It never calls `fromEnv()` and never sets the SDK's `apiKey` or `authToken`, so + `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_PROFILE` and the matching system properties are not used. + One public SDK `Interceptor`, run on every attempt (retries included): + - refuses any request that is not for the configured origin (credentials are bound to it); + - removes every credential header (`Authorization`, `x-api-key`, `api-key`), then sets only the chosen one, using + `replaceHeaders` because the SDK applies credentials above interceptors; + - leaves other headers, such as `anthropic-beta`, untouched. +- **Origin and redirects.** `https` only (loopback `http` for tests), no user info/query/fragment in the base URL. + Redirect following is switched off per request, and any 301/302/303/307/308 response is refused. +- **Plain supplier.** The `Supplier` is invoked before every attempt, including SDK retries. The helper adds no + cache, retry or token logic; supplier errors surface with their own type and are not retried. +- **Blocking and asynchronous calls.** The interceptor decorates the SDK's public `HttpClient` (`execute`, + `executeAsync`, `close`), so `client.messages()` and `client.async().messages()`, streaming included, behave as on a + stock client with the same origin, header and redirect policy. Blocking calls run the supplier on the calling thread. + Asynchronous calls run it on `tokenExecutor(...)` (default: the JDK's asynchronous pool), so neither the caller nor + the SDK's callback threads wait for it; give a slow supplier, such as a CLI credential, a dedicated executor. +- **Ownership.** The caller owns the credential and closes it; closing the client releases only its HTTP resources. + +The SDK's public `Backend` interface could carry the same logic, but it is a larger surface (base URL, request +preparation, authorization, close) than this one interceptor, and `authToken(String)` takes a fixed value, so +renewal needs a per-request hook either way. + +Token cost: the supplier runs per request. `ManagedIdentityCredential` caches tokens inside Azure Identity, but a CLI +credential can start a subprocess on each call, so the per-request cost depends on the credential. This sample reuses +one credential instance and adds no cache of its own. + +### Dependency alignment + +`anthropic-java` is built against Jackson 2.19 and `azure-core` against 2.18. Left to Maven's nearest-wins rule the +two mix and the SDK fails at runtime with `NoSuchMethodError: JsonProperty.isRequired()`, so `pom.xml` imports the +`jackson-bom` at the Anthropic SDK's version. Keep an equivalent constraint in any project that combines the two +libraries. + +## Test (offline) + +```powershell +cd samples/java +mvn test +``` + +The tests use the real SDK (blocking, asynchronous and streaming calls) against a loopback HTTP server, with hostile canary values in `ANTHROPIC_API_KEY`, +`ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_BASE_URL`, `ANTHROPIC_PROFILE`, `ANTHROPIC_CUSTOM_HEADERS`, the +`anthropic.apiKey`/`anthropic.authToken`/`anthropic.baseUrl` system properties and the federation variables +(installed by `pom.xml` for the test JVM). Entrypoint tests also leave the other profile's URL, model and key in the +environment as canaries and assert that none of them is used or sent. Fake `az`/`azd` scripts stand in for the CLIs. +They need no Azure account, login or model quota. + +## Known limits + +- Interrupting a thread that is already waiting on the socket does not stop the call; it ends at the per-call timeout. + Interrupting during a retry back-off does stop it, and closing a `StreamResponse` stops a stream. The sample's + 120 second per-call timeout (its own policy, see above) bounds each HTTP call, including a whole streamed response, + not the retries. +- Cancelling the future that the interceptor returns cancels what it controls: a request that has not been sent, and the + in-flight SDK future. Whether cancelling a future returned by `client.async()` reaches the interceptor is up to the SDK, + and a token fetch that has already started is never interrupted. +- Azure Identity logs through SLF4J. With no SLF4J binding on the classpath SLF4J prints a one-time "no-operation + logger" notice on stderr; add a binding (for example `slf4j-simple`) to see Azure logs. +- `AzureCliCredential` and `AzureDeveloperCliCredential` need their CLI on `PATH`; use `ManagedIdentityCredential` in + hosted environments. +- Only the Messages and streaming calls are demonstrated. Other SDK APIs go through the same client and interceptor. \ No newline at end of file diff --git a/samples/java/pom.xml b/samples/java/pom.xml new file mode 100644 index 0000000..1da92c0 --- /dev/null +++ b/samples/java/pom.xml @@ -0,0 +1,102 @@ + + + 4.0.0 + + sample.anthropic + anthropic-standard-sdk-sample + 1.0.0 + jar + Standard Anthropic SDK sample + Messages and streaming calls with the standard Anthropic Java client and explicit authentication. + + + 17 + UTF-8 + 3.3.0 + 1.18.7 + 5.14.4 + + 2.19.4 + sample.anthropic.Main + + + + + + com.fasterxml.jackson + jackson-bom + ${jackson.version} + pom + import + + + + + + + com.anthropic + anthropic-java + ${anthropic.version} + + + com.azure + azure-identity + ${azure.identity.version} + + + org.junit.jupiter + junit-jupiter + ${junit.version} + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.14.1 + + + + -Xlint:all,-auxiliaryclass + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.6.1 + + + + canary-ambient-api-key + canary-ambient-auth-token + https://canary-ambient-base.invalid + canary-ambient-profile + canary-ambient-identity-token + x-api-key: canary-ambient-custom-x-api-key api-key: canary-ambient-custom-api-key + + ${project.build.directory}${file.separator}fake-cli${path.separator}${env.PATH} + + + canary-ambient-property-api-key + canary-ambient-property-auth-token + https://canary-ambient-property-base.invalid + + + + + org.codehaus.mojo + exec-maven-plugin + 3.6.4 + + ${exec.mainClass} + + + + + \ No newline at end of file diff --git a/samples/java/src/main/java/sample/anthropic/ClientFactory.java b/samples/java/src/main/java/sample/anthropic/ClientFactory.java new file mode 100644 index 0000000..b48520e --- /dev/null +++ b/samples/java/src/main/java/sample/anthropic/ClientFactory.java @@ -0,0 +1,462 @@ +package sample.anthropic; + +import com.anthropic.client.AnthropicClient; +import com.anthropic.client.okhttp.AnthropicOkHttpClient; +import com.anthropic.core.RequestOptions; +import com.anthropic.core.http.HttpClient; +import com.anthropic.core.http.HttpRequest; +import com.anthropic.core.http.HttpResponse; +import com.anthropic.core.http.Interceptor; +import java.net.URI; +import java.net.URISyntaxException; +import java.time.Duration; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import java.util.regex.Pattern; + +/** + * Builds the standard {@link AnthropicClient} with one explicitly chosen credential. It adds no client + * subclass and no Messages API of its own; calls, streaming, status errors and retries stay with the SDK. + * + *

The factory neither reads environment variables or system properties nor knows any identity library. + * It never calls {@code fromEnv()} or sets the SDK's {@code apiKey}/{@code authToken}, so nothing ambient is + * discovered, and it registers one public SDK {@link Interceptor}. On every attempt (retries included) that + * interceptor refuses a request that is not for the configured origin, removes every credential header + * ({@code Authorization}, {@code x-api-key}, {@code api-key}), sets the chosen one, disables redirect + * following and refuses redirect responses. Other headers, such as {@code anthropic-beta}, are left alone. + * + *

The interceptor decorates the SDK's {@link HttpClient}, so it covers both execution modes. Blocking calls + * run the token supplier on the calling thread. {@code client.async()} calls run it on the + * {@link Options.Builder#tokenExecutor token executor}, so neither the caller nor the SDK's callback threads wait + * for it. Cancelling the future the interceptor returns cancels the request it has not sent yet or the in-flight + * SDK future; a token fetch that is already running is not interrupted. + */ +public final class ClientFactory { + + /** The header used for an API key when none is chosen: {@code Authorization: Bearer}. */ + public static final String DEFAULT_API_KEY_HEADER = "Authorization"; + + private static final List CREDENTIAL_HEADER_NAMES = List.of("Authorization", "x-api-key", "api-key"); + private static final Pattern HEADER_NAME = Pattern.compile("[!#$%&'*+\\-.^_`|~0-9A-Za-z]+"); + private static final Pattern IPV4_LOOPBACK = Pattern.compile("127(\\.\\d{1,3}){3}"); + + private ClientFactory() {} + + /** Settings for {@link #create}. Configure exactly one of the token supplier and the API key. */ + public static final class Options { + private final String baseUrl; + private final Supplier tokenSupplier; + private final String apiKey; + private final String apiKeyHeader; + private final String apiVersion; + private final Duration timeout; + private final Integer maxRetries; + private final Executor tokenExecutor; + + private Options(Builder builder) { + this.baseUrl = builder.baseUrl; + this.tokenSupplier = builder.tokenSupplier; + this.apiKey = builder.apiKey; + this.apiKeyHeader = builder.apiKeyHeader; + this.apiVersion = builder.apiVersion; + this.timeout = builder.timeout; + this.maxRetries = builder.maxRetries; + this.tokenExecutor = builder.tokenExecutor; + } + + public static Builder builder() { + return new Builder(); + } + + /** Builder for {@link Options}. */ + public static final class Builder { + private String baseUrl; + private Supplier tokenSupplier; + private String apiKey; + private String apiKeyHeader = DEFAULT_API_KEY_HEADER; + private String apiVersion; + private Duration timeout; + private Integer maxRetries; + private Executor tokenExecutor; + + private Builder() {} + + /** + * Absolute service endpoint, for example {@code https://api.anthropic.com}. Must be https, except + * that plain http is accepted for loopback test servers. The credential is bound to this origin. + */ + public Builder baseUrl(String baseUrl) { + this.baseUrl = baseUrl; + return this; + } + + /** + * Per-attempt bearer token, sent as {@code Authorization: Bearer}. Called before every attempt, + * including SDK retries, and never cached by the factory: expiry, refresh and caching belong to the + * supplier. The caller owns the supplier and whatever it wraps; closing the client does not close them. + * Blocking calls run it on the calling thread; {@code client.async()} calls run it on + * {@link #tokenExecutor}. + */ + public Builder tokenSupplier(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; + return this; + } + + /** + * Where the {@link #tokenSupplier} runs for {@code client.async()} calls, so a supplier that blocks (a + * CLI credential starts a subprocess) never blocks the caller or the SDK's callback threads. When not + * set the JDK's default asynchronous pool is used. Ignored with an API key; blocking calls never use it. + */ + public Builder tokenExecutor(Executor tokenExecutor) { + this.tokenExecutor = tokenExecutor; + return this; + } + + /** Static key, placed in {@link #apiKeyHeader}. */ + public Builder apiKey(String apiKey) { + this.apiKey = apiKey; + return this; + } + + /** + * Header that carries the API key. {@code Authorization} (the default) sends {@code Bearer }; + * any other name, such as {@code x-api-key}, sends the raw key. + */ + public Builder apiKeyHeader(String apiKeyHeader) { + this.apiKeyHeader = apiKeyHeader; + return this; + } + + /** Value for {@code anthropic-version}. When null the SDK default is left untouched. */ + public Builder apiVersion(String apiVersion) { + this.apiVersion = apiVersion; + return this; + } + + /** + * Maximum time for one HTTP call, not including SDK retries. When not set the SDK default is kept; + * the factory never picks a timeout of its own. + */ + public Builder timeout(Duration timeout) { + this.timeout = timeout; + return this; + } + + /** SDK retry count. When not set the SDK default is kept. */ + public Builder maxRetries(int maxRetries) { + this.maxRetries = maxRetries; + return this; + } + + public Options build() { + return new Options(this); + } + } + } + + /** + * Creates the client. The caller closes it. + * + * @throws IllegalArgumentException if the options are missing, ambiguous or unsafe + */ + public static AnthropicClient create(Options options) { + if (options == null) { + throw new IllegalArgumentException("options must not be null"); + } + + URI baseUri = parseBaseUrl(options.baseUrl); + + if ((options.tokenSupplier == null) == (options.apiKey == null)) { + throw new IllegalArgumentException("Configure exactly one credential: set either tokenSupplier or apiKey."); + } + if (options.apiKey != null && !isCredentialValue(options.apiKey)) { + throw new IllegalArgumentException("apiKey is empty or contains whitespace or control characters."); + } + if (options.apiKeyHeader == null || !HEADER_NAME.matcher(options.apiKeyHeader).matches()) { + throw new IllegalArgumentException("apiKeyHeader is not a valid HTTP header name."); + } + if (options.apiVersion != null && !isCredentialValue(options.apiVersion)) { + throw new IllegalArgumentException("apiVersion is empty or contains whitespace or control characters."); + } + if (options.timeout != null && (options.timeout.isZero() || options.timeout.isNegative())) { + throw new IllegalArgumentException("timeout must be positive."); + } + if (options.maxRetries != null && options.maxRetries < 0) { + throw new IllegalArgumentException("maxRetries must not be negative."); + } + + AnthropicOkHttpClient.Builder builder = AnthropicOkHttpClient.builder() + .baseUrl(baseUri.toString()) + .addInterceptor(interceptor(baseUri, options)); + if (options.timeout != null) { + builder.timeout(options.timeout); + } + if (options.maxRetries != null) { + builder.maxRetries(options.maxRetries); + } + + return builder.build(); + } + + /** The interceptor {@link #create} installs; package-private so tests can drive it with a fake HttpClient. */ + static Interceptor interceptor(URI baseUri, Options options) { + return new RequestAuthorizer(originOf(baseUri), options.tokenSupplier, options.apiKey, options.apiKeyHeader, + options.apiVersion, options.tokenExecutor); + } + + private static URI parseBaseUrl(String baseUrl) { + URI uri; + try { + uri = new URI(baseUrl == null ? "" : baseUrl); + } catch (URISyntaxException e) { + throw new IllegalArgumentException("baseUrl must be an absolute URL."); + } + + String scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase(Locale.ROOT); + if (!uri.isAbsolute() || uri.getHost() == null) { + throw new IllegalArgumentException("baseUrl must be an absolute URL."); + } + boolean https = scheme.equals("https"); + boolean loopbackHttp = scheme.equals("http") && isLoopbackHost(uri.getHost()); + if (!https && !loopbackHttp) { + throw new IllegalArgumentException("baseUrl must use https; plain http is accepted only for loopback test servers."); + } + if (uri.getRawUserInfo() != null || uri.getRawQuery() != null || uri.getRawFragment() != null) { + throw new IllegalArgumentException("baseUrl must not contain user info, a query or a fragment."); + } + + return uri; + } + + private static boolean isLoopbackHost(String host) { + return host.equalsIgnoreCase("localhost") + || IPV4_LOOPBACK.matcher(host).matches() + || host.equals("[::1]"); + } + + private static String originOf(URI uri) { + String scheme = uri.getScheme().toLowerCase(Locale.ROOT); + int port = uri.getPort() >= 0 ? uri.getPort() : (scheme.equals("https") ? 443 : 80); + return scheme + "://" + uri.getHost().toLowerCase(Locale.ROOT) + ":" + port; + } + + private static boolean isCredentialValue(String value) { + if (value.isEmpty()) { + return false; + } + for (int i = 0; i < value.length(); i++) { + char c = value.charAt(i); + if (c <= ' ' || c >= '\u007f') { + return false; + } + } + return true; + } + + private static boolean isRedirect(int status) { + return status == 301 || status == 302 || status == 303 || status == 307 || status == 308; + } + + private static final class RequestAuthorizer implements Interceptor { + private final String boundOrigin; + private final Supplier tokenSupplier; + private final String apiKey; + private final String apiKeyHeader; + private final String apiVersion; + private final Executor tokenExecutor; + + RequestAuthorizer( + String boundOrigin, + Supplier tokenSupplier, + String apiKey, + String apiKeyHeader, + String apiVersion, + Executor tokenExecutor) { + this.boundOrigin = boundOrigin; + this.tokenSupplier = tokenSupplier; + this.apiKey = apiKey; + this.apiKeyHeader = apiKeyHeader; + this.apiVersion = apiVersion; + this.tokenExecutor = tokenExecutor; + } + + @Override + public HttpClient intercept(HttpClient next) { + return new HttpClient() { + @Override + public HttpResponse execute(HttpRequest request, RequestOptions requestOptions) { + return RequestAuthorizer.this.execute(next, request, requestOptions); + } + + @Override + public CompletableFuture executeAsync(HttpRequest request, RequestOptions requestOptions) { + return RequestAuthorizer.this.executeAsync(next, request, requestOptions); + } + + @Override + public void close() { + next.close(); + } + }; + } + + HttpResponse execute(HttpClient next, HttpRequest request, RequestOptions requestOptions) { + // Checked before the supplier runs so a request for another origin never costs a token. + ensureBoundOrigin(request.baseUrl()); + HttpRequest authorized = authorize(request, tokenSupplier == null ? null : readToken()); + + HttpResponse response = next.execute(authorized, withoutRedirects(requestOptions)); + IllegalStateException redirect = closeIfRedirect(response); + if (redirect != null) { + throw redirect; + } + return response; + } + + CompletableFuture executeAsync(HttpClient next, HttpRequest request, RequestOptions requestOptions) { + CompletableFuture credentialed; + try { + ensureBoundOrigin(request.baseUrl()); + credentialed = tokenSupplier == null + ? CompletableFuture.completedFuture(authorize(request, null)) + : supplyToken().thenApply(token -> authorize(request, token)); + } catch (RuntimeException e) { + return CompletableFuture.failedFuture(e); + } + + CompletableFuture result = new CompletableFuture<>(); + AtomicReference> inFlight = new AtomicReference<>(); + credentialed.whenComplete((authorized, failure) -> { + if (failure != null) { + result.completeExceptionally(unwrapped(failure)); + } else if (!result.isDone()) { + send(next, authorized, requestOptions, result, inFlight); + } + }); + result.whenComplete((response, failure) -> { + if (result.isCancelled()) { + credentialed.cancel(true); + CompletableFuture sent = inFlight.get(); + if (sent != null) { + sent.cancel(true); + } + } + }); + return result; + } + + private void send( + HttpClient next, + HttpRequest authorized, + RequestOptions requestOptions, + CompletableFuture result, + AtomicReference> inFlight) { + CompletableFuture sent; + try { + sent = next.executeAsync(authorized, withoutRedirects(requestOptions)); + } catch (RuntimeException e) { + result.completeExceptionally(e); + return; + } + + inFlight.set(sent); + sent.whenComplete((response, failure) -> { + if (failure != null) { + result.completeExceptionally(unwrapped(failure)); + return; + } + IllegalStateException redirect = closeIfRedirect(response); + if (redirect != null) { + result.completeExceptionally(redirect); + } else if (!result.complete(response)) { + response.close(); + } + }); + if (result.isCancelled()) { + sent.cancel(true); + } + } + + private CompletableFuture supplyToken() { + return tokenExecutor == null + ? CompletableFuture.supplyAsync(this::readToken) + : CompletableFuture.supplyAsync(this::readToken, tokenExecutor); + } + + private String readToken() { + String token = tokenSupplier.get(); + if (token == null || !isCredentialValue(token)) { + throw new IllegalStateException( + "The token supplier returned an empty token or one with whitespace or control characters."); + } + return token; + } + + private HttpRequest authorize(HttpRequest request, String token) { + String headerName; + String headerValue; + if (tokenSupplier != null) { + headerName = "Authorization"; + headerValue = "Bearer " + token; + } else { + headerName = apiKeyHeader; + headerValue = apiKeyHeader.equalsIgnoreCase("Authorization") ? "Bearer " + apiKey : apiKey; + } + + HttpRequest.Builder authorized = request.toBuilder(); + for (String name : CREDENTIAL_HEADER_NAMES) { + authorized.removeHeaders(name); + } + // Credentials are set above this interceptor by the SDK, so replace rather than append. + authorized.replaceHeaders(headerName, headerValue); + if (apiVersion != null) { + authorized.replaceHeaders("anthropic-version", apiVersion); + } + return authorized.build(); + } + + private static RequestOptions withoutRedirects(RequestOptions requestOptions) { + return requestOptions.toBuilder().followRedirects(false).build(); + } + + /** Closes a redirect response and returns the failure to raise for it; null for any other response. */ + private IllegalStateException closeIfRedirect(HttpResponse response) { + int status = response.statusCode(); + if (!isRedirect(status)) { + return null; + } + response.close(); + return new IllegalStateException("Refused an HTTP " + status + " redirect: credentials are bound to " + + boundOrigin + " and redirects are not followed."); + } + + /** Strips the future wrappers so a failure surfaces with its own type, as in the blocking path. */ + private static Throwable unwrapped(Throwable failure) { + Throwable cause = failure; + while ((cause instanceof CompletionException || cause instanceof ExecutionException) + && cause.getCause() != null) { + cause = cause.getCause(); + } + return cause; + } + + private void ensureBoundOrigin(String requestBaseUrl) { + String origin; + try { + origin = originOf(new URI(requestBaseUrl)); + } catch (URISyntaxException | RuntimeException e) { + origin = ""; + } + if (!origin.equals(boundOrigin)) { + throw new IllegalStateException( + "Refused a request outside " + boundOrigin + "; credentials are bound to that origin."); + } + } + } +} \ No newline at end of file diff --git a/samples/java/src/main/java/sample/anthropic/CredentialSelector.java b/samples/java/src/main/java/sample/anthropic/CredentialSelector.java new file mode 100644 index 0000000..a80f4a7 --- /dev/null +++ b/samples/java/src/main/java/sample/anthropic/CredentialSelector.java @@ -0,0 +1,65 @@ +package sample.anthropic; + +import com.azure.core.credential.AccessToken; +import com.azure.core.credential.TokenCredential; +import com.azure.core.credential.TokenRequestContext; +import com.azure.identity.AzureCliCredentialBuilder; +import com.azure.identity.AzureDeveloperCliCredentialBuilder; +import com.azure.identity.ManagedIdentityCredentialBuilder; +import java.time.Duration; +import java.util.function.Supplier; + +/** + * The only place that knows Azure Identity: it selects exactly one explicit credential class and adapts it to + * the generic token supplier. Nothing here falls back to another credential, and the caller owns (and closes) + * the credential. + */ +final class CredentialSelector { + /** How long a CLI credential waits for its CLI process to return a token. */ + static final Duration CLI_PROCESS_TIMEOUT = Duration.ofSeconds(60); + + private CredentialSelector() {} + + static TokenCredential create(SampleSettings settings) { + switch (settings.credentialName()) { + case "AzureCliCredential": { + AzureCliCredentialBuilder builder = new AzureCliCredentialBuilder().processTimeout(CLI_PROCESS_TIMEOUT); + if (settings.tenantId() != null) { + builder.tenantId(settings.tenantId()); + } + return builder.build(); + } + case "AzureDeveloperCliCredential": { + AzureDeveloperCliCredentialBuilder builder = + new AzureDeveloperCliCredentialBuilder().processTimeout(CLI_PROCESS_TIMEOUT); + if (settings.tenantId() != null) { + builder.tenantId(settings.tenantId()); + } + return builder.build(); + } + case "ManagedIdentityCredential": { + ManagedIdentityCredentialBuilder builder = new ManagedIdentityCredentialBuilder(); + if (settings.clientId() != null) { + builder.clientId(settings.clientId()); + } + return builder.build(); + } + default: + throw new SampleSettings.ConfigurationException("AZURE_TOKEN_CREDENTIALS must be one of: " + + String.join(", ", SampleSettings.CREDENTIAL_NAMES) + "."); + } + } + + /** + * Asks the credential for a token on every call. Caching and renewal stay with the credential; some CLI + * credentials start a subprocess per call. + */ + static Supplier tokenSupplier(TokenCredential credential, String scope, SecretRedactor redactor) { + TokenRequestContext context = new TokenRequestContext().addScopes(scope); + return () -> { + AccessToken token = credential.getTokenSync(context); + redactor.add(token.getToken()); + return token.getToken(); + }; + } +} \ No newline at end of file diff --git a/samples/java/src/main/java/sample/anthropic/Main.java b/samples/java/src/main/java/sample/anthropic/Main.java new file mode 100644 index 0000000..d49592e --- /dev/null +++ b/samples/java/src/main/java/sample/anthropic/Main.java @@ -0,0 +1,10 @@ +package sample.anthropic; + +/** Entrypoint: {@code mvn -q exec:java -Dexec.args="[--stream] [prompt...]"}. */ +public final class Main { + private Main() {} + + public static void main(String[] args) { + System.exit(SampleRunner.run(args, System::getenv, System.out, System.err, CredentialSelector::create)); + } +} \ No newline at end of file diff --git a/samples/java/src/main/java/sample/anthropic/SampleRunner.java b/samples/java/src/main/java/sample/anthropic/SampleRunner.java new file mode 100644 index 0000000..97ebdfa --- /dev/null +++ b/samples/java/src/main/java/sample/anthropic/SampleRunner.java @@ -0,0 +1,248 @@ +package sample.anthropic; + +import com.anthropic.client.AnthropicClient; +import com.anthropic.core.http.StreamResponse; +import com.anthropic.errors.AnthropicServiceException; +import com.anthropic.models.messages.ContentBlock; +import com.anthropic.models.messages.Message; +import com.anthropic.models.messages.MessageCreateParams; +import com.anthropic.models.messages.RawContentBlockDelta; +import com.anthropic.models.messages.RawMessageStreamEvent; +import com.azure.core.credential.TokenCredential; +import java.io.PrintStream; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.function.Function; +import java.util.function.Supplier; +import java.util.regex.Pattern; + +/** One Messages call, or one streaming call with {@code --stream}, plus output and exit codes. */ +public final class SampleRunner { + public static final int EXIT_OK = 0; + public static final int EXIT_FAILURE = 1; + public static final int EXIT_USAGE = 2; + + private static final long MAX_TOKENS = 1024; + + /** Application policy of this sample, set explicitly on the client; ClientFactory has no timeout default of its own. */ + static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(120); + + private static final String DEFAULT_PROMPT = "Say hello in one short sentence."; + private static final String USAGE = "usage: Main [--stream] [prompt...]"; + private static final Pattern WHITESPACE = Pattern.compile("\\s+"); + + private SampleRunner() {} + + /** Creates the one credential the sample uses; tests substitute a fake. */ + @FunctionalInterface + interface CredentialFactory { + TokenCredential create(SampleSettings settings); + } + + /** Raised when a successful HTTP response cannot count as a result (for example, no text). */ + static final class UnusableResponseException extends RuntimeException { + private static final long serialVersionUID = 1L; + + UnusableResponseException(String message) { + super(message); + } + } + + static int run( + String[] args, + Function environment, + PrintStream out, + PrintStream err, + CredentialFactory credentialFactory) { + boolean stream = false; + boolean optionsEnded = false; + List promptWords = new ArrayList<>(); + for (String arg : args) { + if (!optionsEnded && arg.equals("--")) { + optionsEnded = true; + } else if (!optionsEnded && arg.equals("--stream")) { + stream = true; + } else if (!optionsEnded && (arg.equals("-h") || arg.equals("--help"))) { + out.println(USAGE); + return EXIT_OK; + } else if (!optionsEnded && arg.startsWith("--")) { + err.println("error: unknown option " + arg); + err.println(USAGE); + return EXIT_USAGE; + } else { + promptWords.add(arg); + } + } + String prompt = promptWords.isEmpty() ? DEFAULT_PROMPT : String.join(" ", promptWords); + + SampleSettings settings; + try { + settings = SampleSettings.fromEnvironment(environment); + } catch (SampleSettings.ConfigurationException e) { + err.println("error: " + e.getMessage()); + return EXIT_USAGE; + } + + SecretRedactor redactor = new SecretRedactor(); + redactor.add(settings.apiKey()); + TokenCredential credential = null; + try { + ClientFactory.Options.Builder options = ClientFactory.Options.builder() + .baseUrl(settings.baseUrl()) + .apiVersion(settings.apiVersion()) + .timeout(REQUEST_TIMEOUT); + if (settings.authMode() == SampleSettings.AuthMode.BEARER) { + credential = credentialFactory.create(settings); + Supplier tokens = CredentialSelector.tokenSupplier(credential, settings.tokenScope(), redactor); + options.tokenSupplier(tokens); + } else { + options.apiKey(settings.apiKey()).apiKeyHeader(settings.apiKeyHeader()); + } + + AnthropicClient client; + try { + client = ClientFactory.create(options.build()); + } catch (IllegalArgumentException e) { + err.println("error: " + redactor.redact(String.valueOf(e.getMessage()))); + return EXIT_USAGE; + } + + // The SDK client is deliberately not AutoCloseable, so release it explicitly. + try { + MessageCreateParams params = MessageCreateParams.builder() + .model(settings.model()) + .maxTokens(MAX_TOKENS) + .addUserMessage(prompt) + .build(); + if (stream) { + writeStream(client, params, out); + } else { + writeMessage(client, params, out); + } + } finally { + client.close(); + } + return EXIT_OK; + } catch (Exception e) { + if (e instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } + err.println("error: " + describe(e, redactor)); + return EXIT_FAILURE; + } finally { + // The factory does not own the credential, so the caller that created it releases it. + closeQuietly(credential); + } + } + + private static void writeMessage(AnthropicClient client, MessageCreateParams params, PrintStream out) { + Message message = client.messages().create(params); + + StringBuilder text = new StringBuilder(); + List blockKinds = new ArrayList<>(); + for (ContentBlock block : message.content()) { + blockKinds.add(kindOf(block)); + block.text().ifPresent(textBlock -> text.append(textBlock.text())); + } + + if (text.toString().trim().isEmpty()) { + throw new UnusableResponseException( + "The response contained no text (content blocks: " + String.join(", ", blockKinds) + ")."); + } + + out.println(text); + out.println(formatUsage(message.usage().inputTokens(), message.usage().outputTokens())); + } + + private static void writeStream(AnthropicClient client, MessageCreateParams params, PrintStream out) { + long inputTokens = 0; + long outputTokens = 0; + boolean sawText = false; + boolean sawStop = false; + + try (StreamResponse stream = client.messages().createStreaming(params)) { + for (RawMessageStreamEvent event : stream) { + if (event.isMessageStart()) { + inputTokens = event.asMessageStart().message().usage().inputTokens(); + outputTokens = event.asMessageStart().message().usage().outputTokens(); + } else if (event.isContentBlockDelta()) { + RawContentBlockDelta delta = event.asContentBlockDelta().delta(); + if (delta.isText() && !delta.asText().text().isEmpty()) { + String piece = delta.asText().text(); + out.print(piece); + out.flush(); + sawText |= !piece.trim().isEmpty(); + } + } else if (event.isMessageDelta()) { + outputTokens = event.asMessageDelta().usage().outputTokens(); + } else if (event.isMessageStop()) { + sawStop = true; + } + } + } + + if (!sawText) { + throw new UnusableResponseException("The stream contained no text."); + } + if (!sawStop) { + throw new UnusableResponseException("The stream ended before message_stop."); + } + + out.println(); + out.println(formatUsage(inputTokens, outputTokens)); + } + + private static String kindOf(ContentBlock block) { + if (block.isText()) { + return "text"; + } else if (block.isThinking()) { + return "thinking"; + } else if (block.isRedactedThinking()) { + return "redacted_thinking"; + } else if (block.isToolUse()) { + return "tool_use"; + } + return "other"; + } + + private static String formatUsage(long inputTokens, long outputTokens) { + return "usage: input_tokens=" + inputTokens + " output_tokens=" + outputTokens; + } + + /** Typed root cause and HTTP status, never credentials. */ + static String describe(Throwable failure, SecretRedactor redactor) { + StringBuilder text = new StringBuilder(); + Throwable current = failure; + for (int depth = 0; current != null && depth < 4; depth++) { + if (depth > 0) { + text.append(" <- "); + } + text.append(current.getClass().getSimpleName()); + if (current instanceof AnthropicServiceException) { + text.append(" (HTTP ").append(((AnthropicServiceException) current).statusCode()).append(')'); + } + + String message = WHITESPACE.matcher(String.valueOf(current.getMessage())).replaceAll(" ").trim(); + if (message.length() > 300) { + message = message.substring(0, 300) + "..."; + } + if (!message.isEmpty() && !message.equals("null")) { + text.append(": ").append(message); + } + + current = current.getCause() == current ? null : current.getCause(); + } + return redactor.redact(text.toString()); + } + + private static void closeQuietly(Object resource) { + if (resource instanceof AutoCloseable) { + try { + ((AutoCloseable) resource).close(); + } catch (Exception ignored) { + // Nothing useful to report: the call has already succeeded or failed. + } + } + } +} \ No newline at end of file diff --git a/samples/java/src/main/java/sample/anthropic/SampleSettings.java b/samples/java/src/main/java/sample/anthropic/SampleSettings.java new file mode 100644 index 0000000..ef1cb15 --- /dev/null +++ b/samples/java/src/main/java/sample/anthropic/SampleSettings.java @@ -0,0 +1,141 @@ +package sample.anthropic; + +import java.util.List; +import java.util.Locale; +import java.util.function.Function; + +/** + * Environment-driven settings of this sample entrypoint. The reusable {@link ClientFactory} never reads them. + * + *

The endpoint variable selects one {@link Profile}, and the profile decides which model and key variables are + * read. URL, model and key are never coalesced across the two families, so an endpoint, deployment name or key left + * in the environment for another tool cannot be paired with the wrong partner or silently receive an identity token. + * + * @param apiVersion null keeps the SDK default {@code anthropic-version} + */ +record SampleSettings( + Profile profile, + String baseUrl, + String model, + AuthMode authMode, + String apiKey, + String apiKeyHeader, + String apiVersion, + String tokenScope, + String credentialName, + String tenantId, + String clientId) { + + enum AuthMode { + BEARER, + API_KEY + } + + /** Selected by {@code ANTHROPIC_BASE_URL} (canonical) or by {@code CLAUDE_BASE_URL} alone (legacy). */ + enum Profile { + CANONICAL, + LEGACY + } + + /** Raised for missing or invalid configuration; the sample exits with status 2. */ + static final class ConfigurationException extends RuntimeException { + private static final long serialVersionUID = 1L; + + ConfigurationException(String message) { + super(message); + } + } + + static final String DEFAULT_TOKEN_SCOPE = "https://ai.azure.com/.default"; + static final String DEFAULT_CREDENTIAL = "AzureCliCredential"; + static final List CREDENTIAL_NAMES = + List.of("AzureCliCredential", "AzureDeveloperCliCredential", "ManagedIdentityCredential"); + + static SampleSettings fromEnvironment(Function environment) { + Profile profile; + String urlVariable; + String modelVariable; + String keyVariable; + String otherModelVariable; + String otherKeyVariable; + String baseUrl = value(environment, "ANTHROPIC_BASE_URL"); + if (baseUrl != null) { + profile = Profile.CANONICAL; + urlVariable = "ANTHROPIC_BASE_URL"; + modelVariable = "ANTHROPIC_MODEL"; + keyVariable = "ANTHROPIC_API_KEY"; + otherModelVariable = "CLAUDE_DEPLOYMENT_NAME"; + otherKeyVariable = "CLAUDE_API_KEY"; + } else { + baseUrl = value(environment, "CLAUDE_BASE_URL"); + if (baseUrl == null) { + throw new ConfigurationException("Set ANTHROPIC_BASE_URL (or CLAUDE_BASE_URL for the legacy profile)."); + } + profile = Profile.LEGACY; + urlVariable = "CLAUDE_BASE_URL"; + modelVariable = "CLAUDE_DEPLOYMENT_NAME"; + keyVariable = "CLAUDE_API_KEY"; + otherModelVariable = "ANTHROPIC_MODEL"; + otherKeyVariable = "ANTHROPIC_API_KEY"; + } + + String model = value(environment, modelVariable); + if (model == null) { + throw new ConfigurationException(urlVariable + " selects the " + profile.name().toLowerCase(Locale.ROOT) + + " profile, so " + modelVariable + " is required; " + otherModelVariable + " is not used with it."); + } + + String modeText = value(environment, "AUTH_MODE"); + AuthMode mode; + if (modeText == null) { + if (profile == Profile.CANONICAL) { + throw new ConfigurationException( + "ANTHROPIC_BASE_URL selects the canonical profile, so AUTH_MODE must be set to 'bearer' or 'api_key'; " + + "this stops an endpoint left in the environment from silently receiving an identity token."); + } + mode = AuthMode.BEARER; + } else if (modeText.equalsIgnoreCase("bearer")) { + mode = AuthMode.BEARER; + } else if (modeText.equalsIgnoreCase("api_key")) { + mode = AuthMode.API_KEY; + } else { + throw new ConfigurationException("AUTH_MODE must be 'bearer' or 'api_key'."); + } + + String apiKey = null; + String credentialName = value(environment, "AZURE_TOKEN_CREDENTIALS"); + if (credentialName == null) { + credentialName = DEFAULT_CREDENTIAL; + } + if (mode == AuthMode.API_KEY) { + apiKey = value(environment, keyVariable); + if (apiKey == null) { + throw new ConfigurationException("AUTH_MODE=api_key with " + urlVariable + " needs " + keyVariable + "; " + + otherKeyVariable + " is not used with it."); + } + } else if (!CREDENTIAL_NAMES.contains(credentialName)) { + throw new ConfigurationException( + "AZURE_TOKEN_CREDENTIALS must be one of: " + String.join(", ", CREDENTIAL_NAMES) + "."); + } + + String apiKeyHeader = value(environment, "API_KEY_HEADER"); + String tokenScope = value(environment, "TOKEN_SCOPE"); + return new SampleSettings( + profile, + baseUrl, + model, + mode, + apiKey, + apiKeyHeader != null ? apiKeyHeader : ClientFactory.DEFAULT_API_KEY_HEADER, + value(environment, "ANTHROPIC_API_VERSION"), + tokenScope != null ? tokenScope : DEFAULT_TOKEN_SCOPE, + credentialName, + value(environment, "AZURE_TENANT_ID"), + value(environment, "AZURE_CLIENT_ID")); + } + + private static String value(Function environment, String name) { + String value = environment.apply(name); + return value != null && !value.trim().isEmpty() ? value.trim() : null; + } +} \ No newline at end of file diff --git a/samples/java/src/main/java/sample/anthropic/SecretRedactor.java b/samples/java/src/main/java/sample/anthropic/SecretRedactor.java new file mode 100644 index 0000000..06f1a6e --- /dev/null +++ b/samples/java/src/main/java/sample/anthropic/SecretRedactor.java @@ -0,0 +1,26 @@ +package sample.anthropic; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; + +/** Removes known secrets and bearer values from text before it is printed. */ +final class SecretRedactor { + private static final Pattern BEARER_VALUE = Pattern.compile("Bearer\\s+[A-Za-z0-9._~+/=-]+", Pattern.CASE_INSENSITIVE); + + private final List secrets = new ArrayList<>(); + + synchronized void add(String secret) { + if (secret != null && !secret.isEmpty() && !secrets.contains(secret)) { + secrets.add(secret); + } + } + + synchronized String redact(String text) { + String result = BEARER_VALUE.matcher(text).replaceAll("Bearer [redacted]"); + for (String secret : secrets) { + result = result.replace(secret, "[redacted]"); + } + return result; + } +} \ No newline at end of file diff --git a/samples/java/src/test/java/sample/anthropic/ClientFactoryTest.java b/samples/java/src/test/java/sample/anthropic/ClientFactoryTest.java new file mode 100644 index 0000000..db9424d --- /dev/null +++ b/samples/java/src/test/java/sample/anthropic/ClientFactoryTest.java @@ -0,0 +1,952 @@ +package sample.anthropic; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.anthropic.client.AnthropicClient; +import com.anthropic.client.okhttp.AnthropicOkHttpClient; +import com.anthropic.core.RequestOptions; +import com.anthropic.core.http.AsyncStreamResponse; +import com.anthropic.core.http.Headers; +import com.anthropic.core.http.HttpClient; +import com.anthropic.core.http.HttpMethod; +import com.anthropic.core.http.HttpRequest; +import com.anthropic.core.http.HttpResponse; +import com.anthropic.core.http.StreamResponse; +import com.anthropic.errors.AnthropicIoException; +import com.anthropic.errors.AnthropicServiceException; +import com.anthropic.errors.PermissionDeniedException; +import com.anthropic.errors.UnauthorizedException; +import com.anthropic.models.messages.Message; +import com.anthropic.models.messages.MessageCreateParams; +import com.anthropic.models.messages.RawMessageStreamEvent; +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; +import java.time.Duration; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Executor; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * Drives the real Anthropic SDK client built by {@link ClientFactory} against a real HTTP server on the + * loopback interface. No test touches the network beyond loopback. + */ +class ClientFactoryTest { + + private static String textOf(Message message) { + StringBuilder text = new StringBuilder(); + message.content().forEach(block -> block.text().ifPresent(textBlock -> text.append(textBlock.text()))); + return text.toString(); + } + + @ParameterizedTest + @ValueSource(strings = {"", "/anthropic"}) + void bearerUsesMessagesPathModelAndRotatingAuthorization(String path) throws Exception { + try (RecordingServer server = new RecordingServer()) { + RotatingTokens tokens = new RotatingTokens(); + AnthropicClient client = TestClients.bearer(server, tokens.supplier(), path, null, 0, null); + + Message first = client.messages().create(TestClients.params("my-custom-deployment")); + client.messages().create(TestClients.params()); + client.close(); + + assertEquals("OK", textOf(first)); + List requests = server.requests(); + assertEquals(2, requests.size()); + assertEquals(path + "/v1/messages", requests.get(0).path()); + assertEquals("Bearer rotating-token-1", requests.get(0).header("Authorization")); + assertEquals("Bearer rotating-token-2", requests.get(1).header("Authorization")); + assertFalse(requests.get(0).has("x-api-key")); + assertFalse(requests.get(0).has("api-key")); + assertEquals(TestClients.sdkDefaultHeader("X-Stainless-Timeout"), requests.get(0).header("X-Stainless-Timeout")); + assertTrue(requests.get(0).body().contains("\"model\":\"my-custom-deployment\""), requests.get(0).body()); + assertTrue(requests.get(0).body().contains("\"max_tokens\":1024"), requests.get(0).body()); + assertFalse(requests.get(0).body().contains("\"stream\"")); + assertEquals(2, tokens.calls()); + } + } + + @ParameterizedTest + @CsvSource({ + "x-api-key,synthetic-resource-key", + "api-key,synthetic-resource-key", + "X-Custom-Key,synthetic-resource-key", + "Authorization,Bearer synthetic-resource-key" + }) + void apiKeyPlacesTheKeyInTheChosenHeaderOnly(String header, String expectedValue) throws Exception { + try (RecordingServer server = new RecordingServer()) { + AnthropicClient client = TestClients.apiKey(server, "synthetic-resource-key", header, 0); + client.messages().create(TestClients.params()); + client.close(); + + Recorded request = server.single(); + assertEquals(expectedValue, request.header(header)); + for (String closedName : List.of("Authorization", "x-api-key", "api-key")) { + if (!closedName.equalsIgnoreCase(header)) { + assertFalse(request.has(closedName), closedName + " must not be sent"); + } + } + } + } + + @Test + void aChosenHeaderAlreadyOnTheRequestIsReplacedNotAppended() throws Exception { + try (RecordingServer server = new RecordingServer()) { + AnthropicClient client = TestClients.apiKey(server, "synthetic-resource-key", "X-Custom-Key", 0); + MessageCreateParams params = MessageCreateParams.builder() + .model(TestClients.MODEL) + .maxTokens(1024L) + .addUserMessage("Hello") + .putAdditionalHeader("X-Custom-Key", AmbientEnvironment.EXTRA_API_KEY) + .build(); + client.messages().create(params); + client.close(); + + assertEquals("synthetic-resource-key", server.single().header("X-Custom-Key")); + server.single().assertNoCanaryEgress(); + } + } + + @Test + void apiKeyDefaultHeaderIsAuthorizationBearer() throws Exception { + try (RecordingServer server = new RecordingServer()) { + AnthropicClient client = ClientFactory.create( + ClientFactory.Options.builder().baseUrl(server.baseUrl()).apiKey("synthetic-native-key").build()); + client.messages().create(TestClients.params()); + client.close(); + + assertEquals("Bearer synthetic-native-key", server.single().header("Authorization")); + assertFalse(server.single().has("x-api-key")); + } + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void ambientNativeCredentialsNeverReachTheWire(boolean bearer) throws Exception { + AmbientEnvironment.assertInstalled(); + try (RecordingServer server = new RecordingServer()) { + AnthropicClient client = bearer + ? TestClients.bearer(server, new RotatingTokens().supplier()) + : TestClients.apiKey(server, "synthetic-resource-key", "x-api-key", 0); + client.messages().create(TestClients.params()); + client.close(); + + Recorded request = server.single(); + request.assertNoCanaryEgress(); + assertEquals("127.0.0.1", request.header("Host").split(":")[0]); + } + } + + @Test + void perRequestHeadersKeepBetasAndLoseCredentials() throws Exception { + try (RecordingServer server = new RecordingServer()) { + AnthropicClient client = TestClients.bearer(server, new RotatingTokens().supplier()); + client.messages().create(TestClients.params()); + MessageCreateParams extras = MessageCreateParams.builder() + .model(TestClients.MODEL) + .maxTokens(1024L) + .addUserMessage("Hello") + .putAdditionalHeader("anthropic-beta", "files-api-2025-04-14") + .putAdditionalHeader("Authorization", "Bearer " + AmbientEnvironment.EXTRA_AUTHORIZATION) + .putAdditionalHeader("x-api-key", AmbientEnvironment.EXTRA_API_KEY) + .putAdditionalHeader("X-Request-Source", "sample") + .build(); + client.messages().create(extras); + client.close(); + + List requests = server.requests(); + assertFalse(requests.get(0).has("anthropic-beta")); + assertEquals("files-api-2025-04-14", requests.get(1).header("anthropic-beta")); + assertEquals("sample", requests.get(1).header("X-Request-Source")); + assertFalse(requests.get(1).has("x-api-key")); + assertEquals("Bearer rotating-token-2", requests.get(1).header("Authorization")); + for (Recorded request : requests) { + assertFalse(request.everything().contains("oauth-2025-04-20")); + request.assertNoCanaryEgress(); + } + } + } + + @Test + void apiVersionNullKeepsTheSdkDefaultAndAValueReplacesIt() throws Exception { + try (RecordingServer server = new RecordingServer()) { + AnthropicClient plain = AnthropicOkHttpClient.builder().baseUrl(server.baseUrl()).apiKey("baseline-key").build(); + plain.messages().create(TestClients.params()); + plain.close(); + String sdkDefault = server.requests().get(0).header("anthropic-version"); + assertNotNull(sdkDefault); + + AnthropicClient keepsDefault = TestClients.bearer(server, new RotatingTokens().supplier(), "", null, 0, null); + keepsDefault.messages().create(TestClients.params()); + keepsDefault.close(); + AnthropicClient replaces = TestClients.bearer(server, new RotatingTokens().supplier(), "", "2023-06-01", 0, null); + replaces.messages().create(TestClients.params()); + replaces.close(); + + assertEquals(sdkDefault, server.requests().get(1).header("anthropic-version")); + assertEquals("2023-06-01", server.requests().get(2).header("anthropic-version")); + assertNotEquals("2023-06-01", sdkDefault); + } + } + + @Test + void streamingUsesTheSameStandardClientAndPerAttemptCredential() throws Exception { + try (RecordingServer server = new RecordingServer()) { + server.enqueue((exchange, request) -> Responses.stream(exchange, "Hel", "lo")); + RotatingTokens tokens = new RotatingTokens(); + AnthropicClient client = TestClients.bearer(server, tokens.supplier()); + + StringBuilder text = new StringBuilder(); + try (StreamResponse stream = client.messages().createStreaming(TestClients.params())) { + for (RawMessageStreamEvent event : stream) { + if (event.isContentBlockDelta() && event.asContentBlockDelta().delta().isText()) { + text.append(event.asContentBlockDelta().delta().asText().text()); + } + } + } + client.close(); + + assertEquals("Hello", text.toString()); + Recorded request = server.single(); + assertTrue(request.body().contains("\"stream\":true"), request.body()); + assertEquals("Bearer rotating-token-1", request.header("Authorization")); + assertFalse(request.has("anthropic-beta")); + assertEquals("/v1/messages", request.path()); + } + } + + @Test + void retryRequestsAFreshTokenForEveryAttempt() throws Exception { + try (RecordingServer server = new RecordingServer()) { + server.enqueue((exchange, request) -> { + exchange.getResponseHeaders().add("Retry-After-Ms", "1"); + Responses.error(exchange, 500, "api_error", "try again"); + }); + RotatingTokens tokens = new RotatingTokens(); + AnthropicClient client = TestClients.bearer(server, tokens.supplier(), "", null, null, null); + + Message message = client.messages().create(TestClients.params()); + client.close(); + + assertEquals("OK", textOf(message)); + List requests = server.requests(); + assertEquals(2, requests.size()); + assertEquals("Bearer rotating-token-1", requests.get(0).header("Authorization")); + assertEquals("Bearer rotating-token-2", requests.get(1).header("Authorization")); + assertEquals("0", requests.get(0).header("x-stainless-retry-count")); + assertEquals("1", requests.get(1).header("x-stainless-retry-count")); + assertEquals(2, tokens.calls()); + } + } + + @ParameterizedTest + @CsvSource({"401,authentication_error", "403,permission_error"}) + void authFailuresSurfaceTypedStatusWithoutHiddenRetries(int status, String errorType) throws Exception { + try (RecordingServer server = new RecordingServer()) { + server.enqueue((exchange, request) -> Responses.error(exchange, status, errorType, "rejected")); + RotatingTokens tokens = new RotatingTokens(); + AnthropicClient client = TestClients.bearer(server, tokens.supplier(), "", null, null, null); + + AnthropicServiceException failure = assertThrows( + AnthropicServiceException.class, () -> client.messages().create(TestClients.params())); + client.close(); + + assertEquals(status, failure.statusCode()); + Class expected = + status == 401 ? UnauthorizedException.class : PermissionDeniedException.class; + assertInstanceOf(expected, failure); + assertEquals(1, server.requests().size()); + assertEquals(1, tokens.calls()); + assertFalse(String.valueOf(failure.getMessage()).contains("rotating-token")); + } + } + + @Test + void supplierFailurePropagatesItsTypeWithoutRetriesOrRequests() throws Exception { + try (RecordingServer server = new RecordingServer()) { + AtomicInteger calls = new AtomicInteger(); + Supplier failing = () -> { + calls.incrementAndGet(); + throw new UnsupportedOperationException("synthetic supplier failure"); + }; + AnthropicClient client = TestClients.bearer(server, failing, "", null, null, null); + + UnsupportedOperationException failure = assertThrows( + UnsupportedOperationException.class, () -> client.messages().create(TestClients.params())); + client.close(); + + assertEquals("synthetic supplier failure", failure.getMessage()); + assertEquals(1, calls.get()); + assertTrue(server.requests().isEmpty()); + } + } + + @ParameterizedTest + @ValueSource(strings = {"", "has space", "line\r\nbreak", "tab\there"}) + void malformedTokensAreRejectedBeforeAnyRequest(String token) throws Exception { + try (RecordingServer server = new RecordingServer()) { + AnthropicClient client = TestClients.bearer(server, () -> token, "", null, null, null); + + IllegalStateException failure = assertThrows( + IllegalStateException.class, () -> client.messages().create(TestClients.params())); + client.close(); + + assertTrue(server.requests().isEmpty()); + assertFalse(failure.getMessage().contains("break")); + } + } + + @ParameterizedTest + @ValueSource(ints = {301, 302, 303, 307, 308}) + void redirectsAreRefusedWithoutFollowingOrRetrying(int status) throws Exception { + try (RecordingServer attacker = new RecordingServer(); RecordingServer origin = new RecordingServer()) { + origin.enqueue((exchange, request) -> Responses.redirect(exchange, status, attacker.baseUrl() + "/steal")); + AnthropicClient client = TestClients.apiKey(origin, "synthetic-resource-key", "x-api-key", null); + + IllegalStateException failure = assertThrows( + IllegalStateException.class, () -> client.messages().create(TestClients.params())); + client.close(); + + assertTrue(failure.getMessage().toLowerCase().contains("redirect"), failure.getMessage()); + assertFalse(failure.getMessage().contains(attacker.baseUrl())); + assertEquals(1, origin.requests().size()); + assertTrue(attacker.requests().isEmpty()); + } + } + + @Test + void originBindingRefusesRequestsForAnotherOriginBeforeAskingForATokenOrSending() throws Exception { + try (RecordingServer server = new RecordingServer()) { + RotatingTokens tokens = new RotatingTokens(); + AnthropicClient client = TestClients.bearer(server, tokens.supplier(), "", null, null, null); + AnthropicClient retargeted = client.withOptions(options -> options.baseUrl("https://attacker.example")); + + IllegalStateException failure = assertThrows( + IllegalStateException.class, () -> retargeted.messages().create(TestClients.params())); + client.close(); + + assertTrue(failure.getMessage().contains("bound"), failure.getMessage()); + assertTrue(server.requests().isEmpty()); + assertEquals(0, tokens.calls()); + } + } + + @Test + void timeoutKeepsTheSdkDefaultUntilTheCallerSetsOne() throws Exception { + try (RecordingServer server = new RecordingServer()) { + AnthropicClient keepsDefault = TestClients.bearer(server, new RotatingTokens().supplier(), "", null, 0, null); + keepsDefault.messages().create(TestClients.params()); + keepsDefault.close(); + AnthropicClient overrides = + TestClients.bearer(server, new RotatingTokens().supplier(), "", null, 0, Duration.ofSeconds(45)); + overrides.messages().create(TestClients.params()); + overrides.close(); + + String sdkDefault = TestClients.sdkDefaultHeader("X-Stainless-Timeout"); + assertEquals(sdkDefault, server.requests().get(0).header("X-Stainless-Timeout")); + assertEquals("45", server.requests().get(1).header("X-Stainless-Timeout")); + assertNotEquals("45", sdkDefault); + } + } + + @Test + void asyncMessagesUseTheStandardClientAndAFreshBearerToken() throws Exception { + try (RecordingServer server = new RecordingServer()) { + RotatingTokens tokens = new RotatingTokens(); + AnthropicClient client = TestClients.bearer(server, tokens.supplier()); + + Message message = client.async().messages() + .create(TestClients.params("my-custom-deployment")) + .get(10, TimeUnit.SECONDS); + client.close(); + + assertEquals("OK", textOf(message)); + Recorded request = server.single(); + assertEquals("/v1/messages", request.path()); + assertEquals("Bearer rotating-token-1", request.header("Authorization")); + assertFalse(request.has("x-api-key")); + assertFalse(request.has("api-key")); + assertFalse(request.has("anthropic-beta")); + assertTrue(request.body().contains("\"model\":\"my-custom-deployment\""), request.body()); + assertEquals(1, tokens.calls()); + request.assertNoCanaryEgress(); + } + } + + @ParameterizedTest + @CsvSource({"x-api-key,synthetic-resource-key", "Authorization,Bearer synthetic-resource-key"}) + void asyncApiKeyIsPlacedInTheChosenHeaderOnly(String header, String expectedValue) throws Exception { + AmbientEnvironment.assertInstalled(); + try (RecordingServer server = new RecordingServer()) { + AnthropicClient client = TestClients.apiKey(server, "synthetic-resource-key", header, 0); + + client.async().messages().create(TestClients.params()).get(10, TimeUnit.SECONDS); + client.close(); + + Recorded request = server.single(); + assertEquals(expectedValue, request.header(header)); + for (String closedName : List.of("Authorization", "x-api-key", "api-key")) { + assertEquals(closedName.equalsIgnoreCase(header), request.has(closedName), closedName); + } + request.assertNoCanaryEgress(); + } + } + + @Test + void asyncPerRequestHeadersKeepBetasAndLoseCredentials() throws Exception { + try (RecordingServer server = new RecordingServer()) { + AnthropicClient client = TestClients.bearer(server, new RotatingTokens().supplier()); + MessageCreateParams extras = MessageCreateParams.builder() + .model(TestClients.MODEL) + .maxTokens(1024L) + .addUserMessage("Hello") + .putAdditionalHeader("anthropic-beta", "files-api-2025-04-14") + .putAdditionalHeader("Authorization", "Bearer " + AmbientEnvironment.EXTRA_AUTHORIZATION) + .putAdditionalHeader("x-api-key", AmbientEnvironment.EXTRA_API_KEY) + .putAdditionalHeader("X-Request-Source", "sample") + .build(); + + client.async().messages().create(extras).get(10, TimeUnit.SECONDS); + client.close(); + + Recorded request = server.single(); + assertEquals("files-api-2025-04-14", request.header("anthropic-beta")); + assertEquals("sample", request.header("X-Request-Source")); + assertFalse(request.has("x-api-key")); + assertEquals("Bearer rotating-token-1", request.header("Authorization")); + assertFalse(request.everything().contains("oauth-2025-04-20")); + request.assertNoCanaryEgress(); + } + } + + @Test + void asyncStreamingUsesTheSameStandardClientAndAFreshTokenPerAttempt() throws Exception { + try (RecordingServer server = new RecordingServer()) { + server.enqueue((exchange, request) -> Responses.stream(exchange, "Hel", "lo")); + RotatingTokens tokens = new RotatingTokens(); + AnthropicClient client = TestClients.bearer(server, tokens.supplier()); + + StringBuilder text = new StringBuilder(); + AsyncStreamResponse stream = + client.async().messages().createStreaming(TestClients.params()); + stream.subscribe(event -> { + if (event.isContentBlockDelta() && event.asContentBlockDelta().delta().isText()) { + text.append(event.asContentBlockDelta().delta().asText().text()); + } + }); + stream.onCompleteFuture().get(10, TimeUnit.SECONDS); + client.close(); + + assertEquals("Hello", text.toString()); + Recorded request = server.single(); + assertTrue(request.body().contains("\"stream\":true"), request.body()); + assertEquals("Bearer rotating-token-1", request.header("Authorization")); + assertFalse(request.has("anthropic-beta")); + assertEquals(1, tokens.calls()); + } + } + + @Test + void asyncRetryRequestsAFreshTokenForEveryAttempt() throws Exception { + try (RecordingServer server = new RecordingServer()) { + server.enqueue((exchange, request) -> { + exchange.getResponseHeaders().add("Retry-After-Ms", "1"); + Responses.error(exchange, 500, "api_error", "try again"); + }); + RotatingTokens tokens = new RotatingTokens(); + AnthropicClient client = TestClients.bearer(server, tokens.supplier(), "", null, null, null); + + Message message = client.async().messages().create(TestClients.params()).get(10, TimeUnit.SECONDS); + client.close(); + + assertEquals("OK", textOf(message)); + List requests = server.requests(); + assertEquals(2, requests.size()); + assertEquals("Bearer rotating-token-1", requests.get(0).header("Authorization")); + assertEquals("Bearer rotating-token-2", requests.get(1).header("Authorization")); + assertEquals("0", requests.get(0).header("x-stainless-retry-count")); + assertEquals("1", requests.get(1).header("x-stainless-retry-count")); + assertEquals(2, tokens.calls()); + } + } + + @ParameterizedTest + @CsvSource({"401,authentication_error", "403,permission_error"}) + void asyncAuthFailuresSurfaceTypedStatusWithoutHiddenRetries(int status, String errorType) throws Exception { + try (RecordingServer server = new RecordingServer()) { + server.enqueue((exchange, request) -> Responses.error(exchange, status, errorType, "rejected")); + RotatingTokens tokens = new RotatingTokens(); + AnthropicClient client = TestClients.bearer(server, tokens.supplier(), "", null, null, null); + + ExecutionException failure = assertThrows( + ExecutionException.class, + () -> client.async().messages().create(TestClients.params()).get(10, TimeUnit.SECONDS)); + client.close(); + + Class expected = + status == 401 ? UnauthorizedException.class : PermissionDeniedException.class; + assertInstanceOf(expected, failure.getCause()); + assertEquals(status, ((AnthropicServiceException) failure.getCause()).statusCode()); + assertEquals(1, server.requests().size()); + assertEquals(1, tokens.calls()); + } + } + + @Test + void asyncSupplierFailurePropagatesItsTypeWithoutRetriesOrRequests() throws Exception { + try (RecordingServer server = new RecordingServer()) { + AtomicInteger calls = new AtomicInteger(); + Supplier failing = () -> { + calls.incrementAndGet(); + throw new UnsupportedOperationException("synthetic supplier failure"); + }; + AnthropicClient client = TestClients.bearer(server, failing, "", null, null, null); + + ExecutionException failure = assertThrows( + ExecutionException.class, + () -> client.async().messages().create(TestClients.params()).get(10, TimeUnit.SECONDS)); + client.close(); + + assertInstanceOf(UnsupportedOperationException.class, failure.getCause()); + assertEquals("synthetic supplier failure", failure.getCause().getMessage()); + assertEquals(1, calls.get()); + assertTrue(server.requests().isEmpty()); + } + } + + @ParameterizedTest + @ValueSource(strings = {"", "has space", "line\r\nbreak", "tab\there"}) + void asyncMalformedTokensAreRejectedBeforeAnyRequest(String token) throws Exception { + try (RecordingServer server = new RecordingServer()) { + AnthropicClient client = TestClients.bearer(server, () -> token, "", null, null, null); + + ExecutionException failure = assertThrows( + ExecutionException.class, + () -> client.async().messages().create(TestClients.params()).get(10, TimeUnit.SECONDS)); + client.close(); + + assertInstanceOf(IllegalStateException.class, failure.getCause()); + assertTrue(server.requests().isEmpty()); + assertFalse(failure.getCause().getMessage().contains("break")); + } + } + + @ParameterizedTest + @ValueSource(ints = {301, 302, 303, 307, 308}) + void asyncRedirectsAreRefusedWithoutFollowingOrRetrying(int status) throws Exception { + try (RecordingServer elsewhere = new RecordingServer(); RecordingServer origin = new RecordingServer()) { + origin.enqueue((exchange, request) -> Responses.redirect(exchange, status, elsewhere.baseUrl() + "/other")); + AnthropicClient client = TestClients.apiKey(origin, "synthetic-resource-key", "x-api-key", null); + + ExecutionException failure = assertThrows( + ExecutionException.class, + () -> client.async().messages().create(TestClients.params()).get(10, TimeUnit.SECONDS)); + client.close(); + + assertInstanceOf(IllegalStateException.class, failure.getCause()); + assertTrue(failure.getCause().getMessage().toLowerCase().contains("redirect"), failure.getCause().getMessage()); + assertFalse(failure.getCause().getMessage().contains(elsewhere.baseUrl())); + assertEquals(1, origin.requests().size()); + assertTrue(elsewhere.requests().isEmpty()); + } + } + + @Test + void asyncOriginBindingRefusesAnotherOriginBeforeAskingForATokenOrSending() throws Exception { + try (RecordingServer server = new RecordingServer()) { + RotatingTokens tokens = new RotatingTokens(); + AnthropicClient client = TestClients.bearer(server, tokens.supplier(), "", null, null, null); + AnthropicClient retargeted = client.withOptions(options -> options.baseUrl("https://other.example")); + + ExecutionException failure = assertThrows( + ExecutionException.class, + () -> retargeted.async().messages().create(TestClients.params()).get(10, TimeUnit.SECONDS)); + client.close(); + + assertInstanceOf(IllegalStateException.class, failure.getCause()); + assertTrue(failure.getCause().getMessage().contains("bound"), failure.getCause().getMessage()); + assertTrue(server.requests().isEmpty()); + assertEquals(0, tokens.calls()); + } + } + + @Test + void asyncTokenFetchRunsOffTheCallerThreadSoTheCallerIsNotBlocked() throws Exception { + try (RecordingServer server = new RecordingServer()) { + CountDownLatch release = new CountDownLatch(1); + AtomicReference supplierThread = new AtomicReference<>(); + Supplier slow = () -> { + supplierThread.set(Thread.currentThread()); + try { + release.await(30, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return "slow-token"; + }; + AnthropicClient client = TestClients.bearer(server, slow, "", null, null, null); + + CompletableFuture pending = client.async().messages().create(TestClients.params()); + + assertFalse(pending.isDone()); + assertTrue(server.requests().isEmpty()); + release.countDown(); + Message message = pending.get(10, TimeUnit.SECONDS); + client.close(); + + assertEquals("OK", textOf(message)); + assertNotSame(Thread.currentThread(), supplierThread.get()); + assertEquals("Bearer slow-token", server.single().header("Authorization")); + } + } + + @Test + void asyncTokenFetchUsesTheConfiguredExecutorAndBlockingCallsNeverDo() throws Exception { + ExecutorService executor = Executors.newSingleThreadExecutor(task -> new Thread(task, "token-executor-test")); + try (RecordingServer server = new RecordingServer()) { + AtomicReference supplierThread = new AtomicReference<>(); + Supplier supplier = () -> { + supplierThread.set(Thread.currentThread()); + return "executor-token"; + }; + AnthropicClient client = ClientFactory.create(ClientFactory.Options.builder() + .baseUrl(server.baseUrl()) + .tokenSupplier(supplier) + .tokenExecutor(executor) + .build()); + + client.async().messages().create(TestClients.params()).get(10, TimeUnit.SECONDS); + assertEquals("token-executor-test", supplierThread.get().getName()); + assertEquals("Bearer executor-token", server.requests().get(0).header("Authorization")); + + client.messages().create(TestClients.params()); + assertSame(Thread.currentThread(), supplierThread.get()); + client.close(); + } finally { + executor.shutdownNow(); + } + } + + @Test + void cancellingBeforeTheTokenArrivesSendsNothing() throws Exception { + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + CountDownLatch started = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + FakeHttpClient next = new FakeHttpClient(); + HttpClient decorated = decorate(next, () -> { + started.countDown(); + try { + release.await(30, TimeUnit.SECONDS); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + return "late-token"; + }, executor); + + CompletableFuture call = decorated.executeAsync(messagesRequest(), RequestOptions.none()); + assertTrue(started.await(10, TimeUnit.SECONDS)); + call.cancel(true); + release.countDown(); + executor.submit(() -> { }).get(10, TimeUnit.SECONDS); // runs only after the token task has finished + + assertTrue(call.isCancelled()); + assertTrue(next.sent.isEmpty()); + } finally { + executor.shutdownNow(); + } + } + + @Test + void cancellingAfterTheRequestWasSentCancelsTheInFlightCall() { + FakeHttpClient next = new FakeHttpClient(); + HttpClient decorated = decorate(next, () -> "token", Runnable::run); + + CompletableFuture call = decorated.executeAsync(messagesRequest(), RequestOptions.none()); + assertEquals(1, next.sent.size()); + call.cancel(true); + + assertTrue(next.inFlight.isCancelled()); + } + + @Test + void anInFlightFailureSurfacesWithItsOwnType() { + FakeHttpClient next = new FakeHttpClient(); + HttpClient decorated = decorate(next, () -> "token", Runnable::run); + CompletableFuture call = decorated.executeAsync(messagesRequest(), RequestOptions.none()); + IOException failure = new IOException("synthetic transport failure"); + + next.inFlight.completeExceptionally(failure); + + ExecutionException thrown = assertThrows(ExecutionException.class, () -> call.get(10, TimeUnit.SECONDS)); + assertSame(failure, thrown.getCause()); + } + + @Test + void aRedirectResponseIsClosedAndRefusedWhileOtherResponsesPassThrough() throws Exception { + FakeHttpClient redirecting = new FakeHttpClient(); + FakeResponse redirect = new FakeResponse(307); + CompletableFuture refused = + decorate(redirecting, () -> "token", Runnable::run).executeAsync(messagesRequest(), RequestOptions.none()); + redirecting.inFlight.complete(redirect); + + ExecutionException thrown = assertThrows(ExecutionException.class, () -> refused.get(10, TimeUnit.SECONDS)); + assertInstanceOf(IllegalStateException.class, thrown.getCause()); + assertTrue(redirect.closed); + + FakeHttpClient answering = new FakeHttpClient(); + FakeResponse ok = new FakeResponse(200); + CompletableFuture accepted = + decorate(answering, () -> "token", Runnable::run).executeAsync(messagesRequest(), RequestOptions.none()); + answering.inFlight.complete(ok); + + assertSame(ok, accepted.get(10, TimeUnit.SECONDS)); + assertFalse(ok.closed); + } + + @Test + void closeDelegatesToTheWrappedClient() { + FakeHttpClient next = new FakeHttpClient(); + + decorate(next, () -> "token", Runnable::run).close(); + + assertTrue(next.closed); + } + + private static HttpClient decorate(HttpClient next, Supplier tokens, Executor executor) { + String baseUrl = "http://127.0.0.1:9"; + ClientFactory.Options options = ClientFactory.Options.builder() + .baseUrl(baseUrl) + .tokenSupplier(tokens) + .tokenExecutor(executor) + .build(); + return ClientFactory.interceptor(URI.create(baseUrl), options).intercept(next); + } + + private static HttpRequest messagesRequest() { + return HttpRequest.builder() + .method(HttpMethod.POST) + .baseUrl("http://127.0.0.1:9") + .addPathSegments("v1", "messages") + .build(); + } + + /** An SDK HttpClient whose asynchronous call stays pending until the test completes it. */ + private static final class FakeHttpClient implements HttpClient { + final CompletableFuture inFlight = new CompletableFuture<>(); + final List sent = new CopyOnWriteArrayList<>(); + volatile boolean closed; + + @Override + public HttpResponse execute(HttpRequest request, RequestOptions requestOptions) { + throw new UnsupportedOperationException("only the asynchronous path is used"); + } + + @Override + public CompletableFuture executeAsync(HttpRequest request, RequestOptions requestOptions) { + sent.add(request); + return inFlight; + } + + @Override + public void close() { + closed = true; + } + } + + private static final class FakeResponse implements HttpResponse { + private final int status; + volatile boolean closed; + + FakeResponse(int status) { + this.status = status; + } + + @Override + public int statusCode() { + return status; + } + + @Override + public Headers headers() { + return Headers.builder().build(); + } + + @Override + public InputStream body() { + return InputStream.nullInputStream(); + } + + @Override + public void close() { + closed = true; + } + } + + @Test + void timeoutIsAppliedPerCallAndRetriedBySdk() throws Exception { + CountDownLatch release = new CountDownLatch(1); + try (RecordingServer server = new RecordingServer()) { + RecordingServer.Responder stall = (exchange, request) -> release.await(30, TimeUnit.SECONDS); + server.enqueue(stall); + server.enqueue(stall); + AnthropicClient client = TestClients.bearer( + server, new RotatingTokens().supplier(), "", null, 1, Duration.ofMillis(300)); + + AnthropicIoException failure = assertThrows( + AnthropicIoException.class, () -> client.messages().create(TestClients.params())); + release.countDown(); + client.close(); + + assertNotNull(failure); + assertEquals(2, server.requests().size()); + } finally { + release.countDown(); + } + } + + @Test + void retryBackoffRemainsInterruptible() throws Exception { + try (RecordingServer server = new RecordingServer()) { + server.enqueue((exchange, request) -> { + exchange.getResponseHeaders().add("Retry-After-Ms", "60000"); + Responses.error(exchange, 503, "overloaded_error", "busy"); + }); + AnthropicClient client = TestClients.bearer(server, new RotatingTokens().supplier(), "", null, null, null); + AtomicReference outcome = new AtomicReference<>(); + Thread caller = new Thread(() -> { + try { + client.messages().create(TestClients.params()); + } catch (Throwable t) { + outcome.set(t); + } + }); + + caller.start(); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10); + while (server.requests().isEmpty() && System.nanoTime() < deadline) { + Thread.sleep(10); + } + Thread.sleep(200); + caller.interrupt(); + caller.join(TimeUnit.SECONDS.toMillis(10)); + client.close(); + + assertFalse(caller.isAlive(), "the interrupted call must return"); + assertInstanceOf(InterruptedException.class, outcome.get()); + assertEquals(1, server.requests().size()); + } + } + + @Test + void closingAStreamStopsItWithoutRetrying() throws Exception { + CountDownLatch release = new CountDownLatch(1); + try (RecordingServer server = new RecordingServer()) { + server.enqueue((exchange, request) -> { + exchange.getResponseHeaders().add("Content-Type", "text/event-stream"); + exchange.sendResponseHeaders(200, 0); + exchange.getResponseBody().write(Responses.messageStartEvent().getBytes(java.nio.charset.StandardCharsets.UTF_8)); + exchange.getResponseBody().flush(); + release.await(30, TimeUnit.SECONDS); + }); + AnthropicClient client = TestClients.bearer(server, new RotatingTokens().supplier(), "", null, null, null); + + long start = System.nanoTime(); + try (StreamResponse stream = client.messages().createStreaming(TestClients.params())) { + Iterator events = stream.iterator(); + assertTrue(events.next().isMessageStart()); + } + long elapsedMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); + release.countDown(); + client.close(); + + assertTrue(elapsedMillis < 10_000, "closing the stream must not wait for the server"); + assertEquals(1, server.requests().size()); + } finally { + release.countDown(); + } + } + + @ParameterizedTest + @ValueSource(strings = { + "", "not a url", "/relative/path", "http://example.com", "ftp://example.com", + "https://user:pass@example.com", "https://example.com/path?query=1", "https://example.com/path#fragment" + }) + void createRejectsUnsafeBaseUrls(String baseUrl) { + assertThrows(IllegalArgumentException.class, () -> ClientFactory.create( + ClientFactory.Options.builder().baseUrl(baseUrl).apiKey("synthetic-key").build())); + } + + @ParameterizedTest + @ValueSource(strings = {"http://127.0.0.1:5000", "http://localhost:5000", "http://[::1]:5000", "https://example.com"}) + void createAcceptsHttpsAndLoopbackHttp(String baseUrl) { + AnthropicClient client = ClientFactory.create( + ClientFactory.Options.builder().baseUrl(baseUrl).apiKey("synthetic-key").build()); + assertNotNull(client); + client.close(); + } + + @Test + void createRequiresExactlyOneCredential() { + assertThrows(IllegalArgumentException.class, () -> ClientFactory.create( + ClientFactory.Options.builder().baseUrl("https://example.com").build())); + assertThrows(IllegalArgumentException.class, () -> ClientFactory.create( + ClientFactory.Options.builder() + .baseUrl("https://example.com") + .apiKey("synthetic-key") + .tokenSupplier(() -> "token") + .build())); + assertThrows(IllegalArgumentException.class, () -> ClientFactory.create(null)); + } + + @ParameterizedTest + @CsvSource(value = { + "'api-key-with-space ',x-api-key,,", "synthetic-key,'bad header',,", "synthetic-key,'bad:header',,", + "synthetic-key,'',,", "synthetic-key,x-api-key,'bad version',", "synthetic-key,x-api-key,'',", + "synthetic-key,x-api-key,,-1" + }) + void createRejectsMalformedOptions(String apiKey, String header, String apiVersion, Integer maxRetries) { + ClientFactory.Options.Builder options = ClientFactory.Options.builder() + .baseUrl("https://example.com") + .apiKey(apiKey) + .apiKeyHeader(header) + .apiVersion(apiVersion); + if (maxRetries != null) { + options.maxRetries(maxRetries); + } + assertThrows(IllegalArgumentException.class, () -> ClientFactory.create(options.build())); + } + + @ParameterizedTest + @ValueSource(longs = {0, -5}) + void createRejectsNonPositiveTimeouts(long seconds) { + assertThrows(IllegalArgumentException.class, () -> ClientFactory.create( + ClientFactory.Options.builder() + .baseUrl("https://example.com") + .apiKey("synthetic-key") + .timeout(Duration.ofSeconds(seconds)) + .build())); + } +} \ No newline at end of file diff --git a/samples/java/src/test/java/sample/anthropic/CredentialSelectorTest.java b/samples/java/src/test/java/sample/anthropic/CredentialSelectorTest.java new file mode 100644 index 0000000..5b490d6 --- /dev/null +++ b/samples/java/src/test/java/sample/anthropic/CredentialSelectorTest.java @@ -0,0 +1,139 @@ +package sample.anthropic; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.azure.core.credential.TokenCredential; +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.function.Supplier; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * Credential wiring through the real Azure Identity classes. Fake CLIs (found through the PATH that surefire + * sets) stand in for the cloud, so no account, login or network is involved. + */ +class CredentialSelectorTest { + private static final String TENANT_ID = "00000000-0000-0000-0000-00000000aaaa"; + private static final Path FAKE_CLI_DIRECTORY = Path.of("target", "fake-cli").toAbsolutePath(); + + private static SampleSettings settings(String credentialName, String tenantId, String clientId) { + return new SampleSettings( + SampleSettings.Profile.CANONICAL, + "https://example.com", + TestClients.MODEL, + SampleSettings.AuthMode.BEARER, + null, + ClientFactory.DEFAULT_API_KEY_HEADER, + null, + SampleSettings.DEFAULT_TOKEN_SCOPE, + credentialName, + tenantId, + clientId); + } + + @ParameterizedTest + @CsvSource({ + "AzureCliCredential,com.azure.identity.AzureCliCredential", + "AzureDeveloperCliCredential,com.azure.identity.AzureDeveloperCliCredential", + "ManagedIdentityCredential,com.azure.identity.ManagedIdentityCredential" + }) + void createSelectsExactlyTheNamedCredentialClass(String name, Class expected) { + TokenCredential credential = CredentialSelector.create(settings(name, null, null)); + + assertEquals(expected, credential.getClass()); + } + + @ParameterizedTest + @ValueSource(strings = {"DefaultAzureCredential", "EnvironmentCredential", ""}) + void createRejectsAnyOtherCredentialName(String name) { + assertThrows(SampleSettings.ConfigurationException.class, + () -> CredentialSelector.create(settings(name, null, null))); + } + + @ParameterizedTest + @ValueSource(strings = {"AzureCliCredential", "AzureDeveloperCliCredential"}) + void cliCredentialsAreConstructedWithASixtySecondProcessTimeout(String name) throws ReflectiveOperationException { + TokenCredential credential = CredentialSelector.create(settings(name, TENANT_ID, null)); + + // The credential keeps the timeout it was built with in the options of its identity client. + Field field = credential.getClass().getDeclaredField("identityClient"); + field.setAccessible(true); + Object client = field.get(credential); + Method getOptions = client.getClass().getMethod("getIdentityClientOptions"); + getOptions.setAccessible(true); + Object options = getOptions.invoke(client); + Method getTimeout = options.getClass().getMethod("getCredentialProcessTimeout"); + getTimeout.setAccessible(true); + + assertEquals(Duration.ofSeconds(60), getTimeout.invoke(options)); + assertEquals(CredentialSelector.CLI_PROCESS_TIMEOUT, getTimeout.invoke(options)); + } + + @Test + void azureCliCredentialReceivesTheScopeAndTenantFromConfiguration() throws IOException { + Path arguments = installFakeCli( + "az", + "{\"accessToken\":\"fake-cli-token\",\"expiresOn\":\"2099-01-01 00:00:00.000000\"," + + "\"expires_on\":4070908800,\"tokenType\":\"Bearer\"}"); + Supplier supplier = CredentialSelector.tokenSupplier( + CredentialSelector.create(settings("AzureCliCredential", TENANT_ID, null)), + SampleSettings.DEFAULT_TOKEN_SCOPE, + new SecretRedactor()); + + assertEquals("fake-cli-token", supplier.get()); + + String recorded = Files.readString(arguments); + assertTrue(recorded.contains("get-access-token"), recorded); + assertTrue(recorded.contains("https://ai.azure.com"), recorded); + assertTrue(recorded.contains("--tenant " + TENANT_ID), recorded); + } + + @Test + void azureDeveloperCliCredentialReceivesTheScopeAndTenantFromConfiguration() throws IOException { + Path arguments = installFakeCli("azd", "{\"token\":\"fake-azd-token\",\"expiresOn\":\"2099-01-01T00:00:00Z\"}"); + Supplier supplier = CredentialSelector.tokenSupplier( + CredentialSelector.create(settings("AzureDeveloperCliCredential", TENANT_ID, null)), + SampleSettings.DEFAULT_TOKEN_SCOPE, + new SecretRedactor()); + + assertEquals("fake-azd-token", supplier.get()); + + String recorded = Files.readString(arguments); + assertTrue(recorded.contains("--scope " + SampleSettings.DEFAULT_TOKEN_SCOPE), recorded); + assertTrue(recorded.contains("--tenant-id " + TENANT_ID), recorded); + } + + /** Writes a fake CLI into the directory surefire put first on PATH; it records its arguments. */ + private static Path installFakeCli(String name, String outputJson) throws IOException { + Files.createDirectories(FAKE_CLI_DIRECTORY); + Path arguments = FAKE_CLI_DIRECTORY.resolve(name + ".arguments"); + Files.deleteIfExists(arguments); + + if (System.getProperty("os.name").toLowerCase().contains("win")) { + Files.writeString( + FAKE_CLI_DIRECTORY.resolve(name + ".cmd"), + "@echo off\r\necho %* >> \"" + arguments + "\"\r\necho " + outputJson + "\r\n", + StandardCharsets.UTF_8); + } else { + Path script = FAKE_CLI_DIRECTORY.resolve(name); + Files.writeString( + script, + "#!/bin/sh\necho \"$@\" >> '" + arguments + "'\necho '" + outputJson + "'\n", + StandardCharsets.UTF_8); + if (!script.toFile().setExecutable(true)) { + throw new IOException("Could not make the fake CLI executable: " + script); + } + } + return arguments; + } +} \ No newline at end of file diff --git a/samples/java/src/test/java/sample/anthropic/HelperBoundaryTest.java b/samples/java/src/test/java/sample/anthropic/HelperBoundaryTest.java new file mode 100644 index 0000000..a2f075d --- /dev/null +++ b/samples/java/src/test/java/sample/anthropic/HelperBoundaryTest.java @@ -0,0 +1,27 @@ +package sample.anthropic; + +import static org.junit.jupiter.api.Assertions.assertFalse; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import org.junit.jupiter.api.Test; + +/** The generic helper stays generic: no identity library, no environment, no SDK credential slots. */ +class HelperBoundaryTest { + + @Test + void clientFactoryKnowsNoIdentityLibraryAndReadsNoConfiguration() throws IOException { + String source = Files.readString(Path.of("src/main/java/sample/anthropic/ClientFactory.java")) + .replaceAll("(?s)/\\*.*?\\*/", "") + .replaceAll("//[^\\n]*", ""); + + List forbidden = List.of( + "com.azure", "Azure", "Foundry", "System.getenv", "System.getProperty", "fromEnv", ".apiKey(", ".authToken(", + "configurationProvider", "backend("); + for (String fragment : forbidden) { + assertFalse(source.contains(fragment), "ClientFactory must not use: " + fragment); + } + } +} \ No newline at end of file diff --git a/samples/java/src/test/java/sample/anthropic/SampleRunnerTest.java b/samples/java/src/test/java/sample/anthropic/SampleRunnerTest.java new file mode 100644 index 0000000..79725db --- /dev/null +++ b/samples/java/src/test/java/sample/anthropic/SampleRunnerTest.java @@ -0,0 +1,450 @@ +package sample.anthropic; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.azure.core.credential.AccessToken; +import com.azure.core.credential.TokenCredential; +import com.azure.core.credential.TokenRequestContext; +import com.azure.identity.CredentialUnavailableException; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; +import reactor.core.publisher.Mono; + +/** The sample entrypoint end to end: environment, credential wiring, real SDK, output, exit codes. */ +class SampleRunnerTest { + + private record RunResult(int exitCode, String output, String error) {} + + private static final class FakeCredential implements TokenCredential, AutoCloseable { + private final AtomicInteger calls = new AtomicInteger(); + final List> scopes = new ArrayList<>(); + RuntimeException failure; + boolean closed; + + @Override + public Mono getToken(TokenRequestContext context) { + return Mono.fromSupplier(() -> token(context)); + } + + @Override + public AccessToken getTokenSync(TokenRequestContext context) { + return token(context); + } + + private AccessToken token(TokenRequestContext context) { + scopes.add(List.copyOf(context.getScopes())); + if (failure != null) { + throw failure; + } + return new AccessToken("fake-credential-token-" + calls.incrementAndGet(), OffsetDateTime.now().plusHours(1)); + } + + @Override + public void close() { + closed = true; + } + } + + private static Function env(String spec) { + Map values = new HashMap<>(); + for (String pair : spec.split(";")) { + if (!pair.isEmpty()) { + int separator = pair.indexOf('='); + values.put(pair.substring(0, separator), pair.substring(separator + 1)); + } + } + return values::get; + } + + private static RunResult run(String[] args, String environment, FakeCredential credential) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + ByteArrayOutputStream error = new ByteArrayOutputStream(); + int exitCode = SampleRunner.run( + args, + env(environment), + new PrintStream(output, true, StandardCharsets.UTF_8), + new PrintStream(error, true, StandardCharsets.UTF_8), + settings -> credential); + return new RunResult( + exitCode, + output.toString(StandardCharsets.UTF_8).replace("\r\n", "\n"), + error.toString(StandardCharsets.UTF_8).replace("\r\n", "\n")); + } + + // ANTHROPIC_BASE_URL selects the canonical profile; CLAUDE_BASE_URL alone selects the legacy one. + private static String canonicalEnv(RecordingServer server) { + return "ANTHROPIC_BASE_URL=" + server.baseUrl() + ";ANTHROPIC_MODEL=claude-sonnet-5-5"; + } + + private static String bearerEnv(RecordingServer server) { + return canonicalEnv(server) + ";AUTH_MODE=bearer"; + } + + private static String keyEnv(RecordingServer server) { + return canonicalEnv(server) + ";AUTH_MODE=api_key"; + } + + private static String legacyEnv(RecordingServer server) { + return "CLAUDE_BASE_URL=" + server.baseUrl() + ";CLAUDE_DEPLOYMENT_NAME=legacy-deployment"; + } + + // The other family's values, with canaries that must never be used or sent. + private static final String LEGACY_CANARIES = "CLAUDE_BASE_URL=https://legacy-canary.invalid;" + + "CLAUDE_DEPLOYMENT_NAME=legacy-model-canary;CLAUDE_API_KEY=legacy-key-canary"; + + private static final String NATIVE_CANARIES = "ANTHROPIC_MODEL=native-model-canary;ANTHROPIC_API_KEY=native-key-canary"; + + private static final List FAMILY_CANARIES = List.of( + "legacy-canary.invalid", "legacy-model-canary", "legacy-key-canary", "native-model-canary", "native-key-canary"); + + private static void assertNoFamilyCanaries(Recorded request) { + String everything = request.everything().toLowerCase(); + for (String canary : FAMILY_CANARIES) { + assertFalse(everything.contains(canary), "family canary reached the wire: " + canary); + } + } + + @Test + void legacyProfileDefaultsToBearerUsesItsOwnNamesAndPrintsTextThenUsage() throws Exception { + try (RecordingServer server = new RecordingServer()) { + FakeCredential credential = new FakeCredential(); + + RunResult result = run( + new String[0], + "CLAUDE_BASE_URL=" + server.baseUrl() + ";CLAUDE_DEPLOYMENT_NAME=my-deployment", + credential); + + assertEquals(0, result.exitCode()); + assertEquals("OK\nusage: input_tokens=11 output_tokens=5\n", result.output()); + assertEquals("", result.error()); + Recorded request = server.single(); + assertEquals("/v1/messages", request.path()); + assertEquals("Bearer fake-credential-token-1", request.header("Authorization")); + assertEquals(TestClients.sdkDefaultApiVersion(), request.header("anthropic-version")); + assertEquals("120", request.header("X-Stainless-Timeout")); + assertTrue(request.body().contains("\"model\":\"my-deployment\""), request.body()); + assertTrue(request.body().contains("\"max_tokens\":1024"), request.body()); + assertEquals(List.of(List.of("https://ai.azure.com/.default")), credential.scopes); + request.assertNoCanaryEgress(); + } + } + + @Test + void canonicalProfileWinsOverLegacyAndHonorsScopeAndVersionOverrides() throws Exception { + try (RecordingServer server = new RecordingServer()) { + FakeCredential credential = new FakeCredential(); + String environment = "ANTHROPIC_BASE_URL=" + server.baseUrl() + ";CLAUDE_BASE_URL=https://legacy.example/anthropic;" + + "ANTHROPIC_MODEL=preferred-model;CLAUDE_DEPLOYMENT_NAME=legacy-model;" + + "TOKEN_SCOPE=api://custom/.default;ANTHROPIC_API_VERSION=2023-06-01;AUTH_MODE=BEARER"; + + RunResult result = run(new String[0], environment, credential); + + assertEquals(0, result.exitCode(), result.error()); + Recorded request = server.single(); + assertTrue(request.body().contains("\"model\":\"preferred-model\""), request.body()); + assertEquals("2023-06-01", request.header("anthropic-version")); + assertNotEquals("2023-06-01", TestClients.sdkDefaultApiVersion()); + assertEquals(List.of(List.of("api://custom/.default")), credential.scopes); + } + } + + @Test + void canonicalProfileIgnoresEveryLegacyValue() throws Exception { + try (RecordingServer server = new RecordingServer()) { + FakeCredential credential = new FakeCredential(); + + RunResult result = + run(new String[0], keyEnv(server) + ";ANTHROPIC_API_KEY=canonical-key;" + LEGACY_CANARIES, credential); + + assertEquals(0, result.exitCode(), result.error()); + Recorded request = server.single(); + assertTrue(request.body().contains("\"model\":\"claude-sonnet-5-5\""), request.body()); + assertEquals("Bearer canonical-key", request.header("Authorization")); + assertNoFamilyCanaries(request); + assertTrue(credential.scopes.isEmpty()); + } + } + + @Test + void legacyProfileIgnoresEveryAmbientNativeValue() throws Exception { + try (RecordingServer server = new RecordingServer()) { + RunResult result = run( + new String[0], + legacyEnv(server) + ";AUTH_MODE=api_key;CLAUDE_API_KEY=legacy-key;" + NATIVE_CANARIES, + new FakeCredential()); + + assertEquals(0, result.exitCode(), result.error()); + Recorded request = server.single(); + assertTrue(request.body().contains("\"model\":\"legacy-deployment\""), request.body()); + assertEquals("Bearer legacy-key", request.header("Authorization")); + assertNoFamilyCanaries(request); + } + } + + @Test + void legacyBearerDefaultNeverUsesAnAmbientNativeKey() throws Exception { + try (RecordingServer server = new RecordingServer()) { + FakeCredential credential = new FakeCredential(); + + RunResult result = run(new String[0], legacyEnv(server) + ";" + NATIVE_CANARIES, credential); + + assertEquals(0, result.exitCode(), result.error()); + Recorded request = server.single(); + assertEquals("Bearer fake-credential-token-1", request.header("Authorization")); + assertTrue(request.body().contains("\"model\":\"legacy-deployment\""), request.body()); + assertNoFamilyCanaries(request); + assertEquals(1, credential.scopes.size()); + } + } + + @Test + void canonicalBearerWhenExplicitIgnoresBothKeyFamilies() throws Exception { + try (RecordingServer server = new RecordingServer()) { + FakeCredential credential = new FakeCredential(); + + RunResult result = run( + new String[0], + bearerEnv(server) + ";ANTHROPIC_API_KEY=native-key-canary;CLAUDE_API_KEY=legacy-key-canary", + credential); + + assertEquals(0, result.exitCode(), result.error()); + Recorded request = server.single(); + assertEquals("Bearer fake-credential-token-1", request.header("Authorization")); + assertNoFamilyCanaries(request); + assertFalse(request.has("x-api-key")); + } + } + + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "canonical|;ANTHROPIC_API_KEY=canonical-key|Authorization|Bearer canonical-key", + "legacy|;CLAUDE_API_KEY=legacy-key|Authorization|Bearer legacy-key", + "canonical|;ANTHROPIC_API_KEY=canonical-key;API_KEY_HEADER=x-api-key|x-api-key|canonical-key", + "canonical|;ANTHROPIC_API_KEY=canonical-key;API_KEY_HEADER=api-key|api-key|canonical-key", + "legacy|;CLAUDE_API_KEY=legacy-key;API_KEY_HEADER=x-api-key|x-api-key|legacy-key" + }) + void apiKeyModePlacesTheKeyInTheConfiguredHeaderWithoutAskingForAToken( + String profile, String extra, String header, String expected) throws Exception { + try (RecordingServer server = new RecordingServer()) { + FakeCredential credential = new FakeCredential(); + String base = profile.equals("legacy") ? legacyEnv(server) + ";AUTH_MODE=api_key" : keyEnv(server); + + RunResult result = run(new String[0], base + extra, credential); + + assertEquals(0, result.exitCode(), result.error()); + Recorded request = server.single(); + assertEquals(expected, request.header(header)); + for (String closedName : List.of("Authorization", "x-api-key", "api-key")) { + assertEquals(closedName.equalsIgnoreCase(header), request.has(closedName), closedName); + } + assertEquals(TestClients.sdkDefaultApiVersion(), request.header("anthropic-version")); + assertTrue(credential.scopes.isEmpty()); + request.assertNoCanaryEgress(); + } + } + + @Test + void streamPrintsTextAsItArrivesThenUsage() throws Exception { + try (RecordingServer server = new RecordingServer()) { + server.enqueue((exchange, request) -> Responses.stream(exchange, "Hel", "lo")); + + RunResult result = run(new String[] {"--stream", "Say", "hi"}, bearerEnv(server), new FakeCredential()); + + assertEquals(0, result.exitCode(), result.error()); + assertEquals("Hello\nusage: input_tokens=11 output_tokens=7\n", result.output()); + assertEquals("", result.error()); + assertTrue(server.single().body().contains("\"stream\":true")); + assertTrue(server.single().body().contains("Say hi")); + } + } + + @Test + void promptWordsAreJoinedAndAfterDoubleDashOptionsAreLiteral() throws Exception { + try (RecordingServer server = new RecordingServer()) { + RunResult result = run(new String[] {"--", "--stream", "is", "text"}, bearerEnv(server), new FakeCredential()); + + assertEquals(0, result.exitCode(), result.error()); + assertFalse(server.single().body().contains("\"stream\"")); + assertTrue(server.single().body().contains("--stream is text"), server.single().body()); + } + } + + @Test + void thinkingOnlyResponseIsAFailureNotASuccess() throws Exception { + try (RecordingServer server = new RecordingServer()) { + server.enqueue((exchange, request) -> Responses.thinkingOnly(exchange)); + + RunResult result = run(new String[0], bearerEnv(server), new FakeCredential()); + + assertEquals(SampleRunner.EXIT_FAILURE, result.exitCode()); + assertEquals("", result.output()); + assertTrue(result.error().contains("UnusableResponseException"), result.error()); + assertTrue(result.error().contains("no text"), result.error()); + assertTrue(result.error().contains("thinking"), result.error()); + } + } + + @ParameterizedTest + @ValueSource(strings = {"", " \\n "}) + void emptyOrBlankTextIsAFailure(String text) throws Exception { + try (RecordingServer server = new RecordingServer()) { + server.enqueue((exchange, request) -> Responses.message(exchange, text.replace("\\n", "\n"), 11, 5)); + + RunResult result = run(new String[0], bearerEnv(server), new FakeCredential()); + + assertEquals(SampleRunner.EXIT_FAILURE, result.exitCode()); + assertEquals("", result.output()); + assertTrue(result.error().contains("UnusableResponseException"), result.error()); + } + } + + @Test + void streamWithoutTextOrWithoutMessageStopIsAFailure() throws Exception { + try (RecordingServer silent = new RecordingServer(); RecordingServer truncated = new RecordingServer()) { + silent.enqueue((exchange, request) -> Responses.stream(exchange, "")); + truncated.enqueue((exchange, request) -> Responses.truncatedStream(exchange, "partial")); + + RunResult noText = run(new String[] {"--stream"}, bearerEnv(silent), new FakeCredential()); + RunResult cutOff = run(new String[] {"--stream"}, bearerEnv(truncated), new FakeCredential()); + + assertEquals(SampleRunner.EXIT_FAILURE, noText.exitCode()); + assertTrue(noText.error().contains("no text"), noText.error()); + assertEquals(SampleRunner.EXIT_FAILURE, cutOff.exitCode()); + assertTrue(cutOff.error().contains("before message_stop"), cutOff.error()); + assertFalse(cutOff.output().contains("usage:")); + } + } + + @ParameterizedTest + @CsvSource({"401,UnauthorizedException (HTTP 401)", "403,PermissionDeniedException (HTTP 403)"}) + void authRejectionShowsTypedStatusAndNeverTheToken(int status, String expected) throws Exception { + try (RecordingServer server = new RecordingServer()) { + server.enqueue((exchange, request) -> Responses.error( + exchange, status, "authentication_error", "denied for Bearer fake-credential-token-1 and fake-credential-token-1")); + + RunResult result = run(new String[0], bearerEnv(server), new FakeCredential()); + + assertEquals(SampleRunner.EXIT_FAILURE, result.exitCode()); + assertEquals("", result.output()); + assertTrue(result.error().contains(expected), result.error()); + assertTrue(result.error().contains("[redacted]"), result.error()); + assertFalse(result.error().contains("fake-credential-token"), result.error()); + } + } + + @Test + void apiKeyIsRedactedFromServerErrors() throws Exception { + try (RecordingServer server = new RecordingServer()) { + server.enqueue((exchange, request) -> + Responses.error(exchange, 401, "authentication_error", "bad key super-secret-key-value")); + + RunResult result = run(new String[0], keyEnv(server) + ";ANTHROPIC_API_KEY=super-secret-key-value", new FakeCredential()); + + assertEquals(SampleRunner.EXIT_FAILURE, result.exitCode()); + assertTrue(result.error().contains("[redacted]"), result.error()); + assertFalse(result.error().contains("super-secret-key-value"), result.error()); + } + } + + @Test + void credentialFailureShowsItsTypeAndSendsNothing() throws Exception { + try (RecordingServer server = new RecordingServer()) { + FakeCredential credential = new FakeCredential(); + credential.failure = new CredentialUnavailableException("synthetic CLI is not signed in"); + + RunResult result = run(new String[0], bearerEnv(server), credential); + + assertEquals(SampleRunner.EXIT_FAILURE, result.exitCode()); + assertTrue( + result.error().contains("CredentialUnavailableException: synthetic CLI is not signed in"), result.error()); + assertTrue(server.requests().isEmpty()); + } + } + + @Test + void theCallerClosesTheCredentialOnSuccessAndOnFailure() throws Exception { + try (RecordingServer server = new RecordingServer(); RecordingServer rejecting = new RecordingServer()) { + FakeCredential succeeded = new FakeCredential(); + FakeCredential failed = new FakeCredential(); + rejecting.enqueue((exchange, request) -> Responses.error(exchange, 403, "permission_error", "no")); + + run(new String[0], bearerEnv(server), succeeded); + run(new String[0], bearerEnv(rejecting), failed); + + assertTrue(succeeded.closed); + assertTrue(failed.closed); + } + } + + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + "ANTHROPIC_MODEL=m|ANTHROPIC_BASE_URL", + "ANTHROPIC_BASE_URL=https://x.example;AUTH_MODE=bearer|ANTHROPIC_MODEL", + "ANTHROPIC_BASE_URL=https://x.example;ANTHROPIC_MODEL=m;AUTH_MODE=oauth|AUTH_MODE", + "ANTHROPIC_BASE_URL=https://x.example;ANTHROPIC_MODEL=m;AUTH_MODE=api_key|ANTHROPIC_API_KEY", + "ANTHROPIC_BASE_URL=https://x.example;ANTHROPIC_MODEL=m;AUTH_MODE=bearer;AZURE_TOKEN_CREDENTIALS=DefaultAzureCredential|AZURE_TOKEN_CREDENTIALS", + "ANTHROPIC_BASE_URL=http://example.com;ANTHROPIC_MODEL=m;AUTH_MODE=api_key;ANTHROPIC_API_KEY=k|https" + }) + void invalidConfigurationExitsWithUsageStatus(String environment, String expected) { + FakeCredential credential = new FakeCredential(); + + RunResult result = run(new String[0], environment, credential); + + assertEquals(SampleRunner.EXIT_USAGE, result.exitCode()); + assertEquals("", result.output()); + assertTrue(result.error().contains(expected), result.error()); + } + + @ParameterizedTest + @CsvSource(delimiter = '|', value = { + // The canonical URL needs the canonical model and key: the legacy names are never a fallback. + "ANTHROPIC_BASE_URL={URL};CLAUDE_DEPLOYMENT_NAME=legacy-model;AUTH_MODE=bearer|ANTHROPIC_MODEL", + "ANTHROPIC_BASE_URL={URL};ANTHROPIC_MODEL=m;AUTH_MODE=api_key;CLAUDE_API_KEY=legacy-key|ANTHROPIC_API_KEY", + // The canonical profile never defaults to an identity token, even when legacy values are also present. + "ANTHROPIC_BASE_URL={URL};ANTHROPIC_MODEL=m;ANTHROPIC_API_KEY=native-key;CLAUDE_API_KEY=legacy-key|AUTH_MODE", + "ANTHROPIC_BASE_URL={URL};ANTHROPIC_MODEL=m;CLAUDE_BASE_URL={URL};CLAUDE_DEPLOYMENT_NAME=legacy-deployment|AUTH_MODE", + // A legacy-only URL needs the legacy model and key: ambient native names are never a fallback. + "CLAUDE_BASE_URL={URL};ANTHROPIC_MODEL=native-model|CLAUDE_DEPLOYMENT_NAME", + "CLAUDE_BASE_URL={URL};CLAUDE_DEPLOYMENT_NAME=legacy-deployment;AUTH_MODE=api_key;ANTHROPIC_API_KEY=native-key|CLAUDE_API_KEY" + }) + void profilesAreNeverMixedAndTheErrorNamesTheMissingVariable(String environment, String expected) throws Exception { + try (RecordingServer server = new RecordingServer()) { + FakeCredential credential = new FakeCredential(); + + RunResult result = run(new String[0], environment.replace("{URL}", server.baseUrl()), credential); + + assertEquals(SampleRunner.EXIT_USAGE, result.exitCode()); + assertEquals("", result.output()); + assertTrue(result.error().contains(expected), result.error()); + assertTrue(server.requests().isEmpty()); + assertTrue(credential.scopes.isEmpty()); + assertFalse(credential.closed, "no credential may be created for an invalid configuration"); + } + } + + @Test + void helpAndUnknownOptions() { + RunResult help = run(new String[] {"--help"}, "", new FakeCredential()); + RunResult unknown = run(new String[] {"--verbose"}, "ANTHROPIC_BASE_URL=https://x.example;ANTHROPIC_MODEL=m", new FakeCredential()); + + assertEquals(SampleRunner.EXIT_OK, help.exitCode()); + assertTrue(help.output().contains("usage:")); + assertEquals(SampleRunner.EXIT_USAGE, unknown.exitCode()); + assertTrue(unknown.error().contains("unknown option --verbose"), unknown.error()); + } +} \ No newline at end of file diff --git a/samples/java/src/test/java/sample/anthropic/TestSupport.java b/samples/java/src/test/java/sample/anthropic/TestSupport.java new file mode 100644 index 0000000..afd33bb --- /dev/null +++ b/samples/java/src/test/java/sample/anthropic/TestSupport.java @@ -0,0 +1,332 @@ +package sample.anthropic; + +import com.anthropic.client.AnthropicClient; +import com.anthropic.client.okhttp.AnthropicOkHttpClient; +import com.anthropic.models.messages.MessageCreateParams; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import java.io.IOException; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.Queue; +import java.util.TreeMap; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; + +/** The hostile ambient configuration that surefire installs for the whole test JVM (see pom.xml). */ +final class AmbientEnvironment { + static final String API_KEY = "canary-ambient-api-key"; + static final String AUTH_TOKEN = "canary-ambient-auth-token"; + static final String BASE_HOST = "canary-ambient-base.invalid"; + static final String PROFILE = "canary-ambient-profile"; + static final String IDENTITY_TOKEN = "canary-ambient-identity-token"; + static final String CUSTOM_API_KEY = "canary-ambient-custom-x-api-key"; + static final String CUSTOM_API_KEY_ALTERNATE = "canary-ambient-custom-api-key"; + static final String PROPERTY_API_KEY = "canary-ambient-property-api-key"; + static final String PROPERTY_AUTH_TOKEN = "canary-ambient-property-auth-token"; + static final String PROPERTY_BASE_HOST = "canary-ambient-property-base.invalid"; + static final String EXTRA_AUTHORIZATION = "canary-extra-authorization"; + static final String EXTRA_API_KEY = "canary-extra-key"; + + static final List ALL_CANARIES = List.of( + API_KEY, AUTH_TOKEN, BASE_HOST, PROFILE, IDENTITY_TOKEN, CUSTOM_API_KEY, CUSTOM_API_KEY_ALTERNATE, + PROPERTY_API_KEY, PROPERTY_AUTH_TOKEN, PROPERTY_BASE_HOST, EXTRA_AUTHORIZATION, EXTRA_API_KEY); + + private AmbientEnvironment() {} + + /** Fails unless the canaries are really present, so a missing surefire setup cannot make tests vacuous. */ + static void assertInstalled() { + check(API_KEY, System.getenv("ANTHROPIC_API_KEY")); + check(AUTH_TOKEN, System.getenv("ANTHROPIC_AUTH_TOKEN")); + check(PROPERTY_API_KEY, System.getProperty("anthropic.apiKey")); + check(PROPERTY_AUTH_TOKEN, System.getProperty("anthropic.authToken")); + } + + private static void check(String expected, String actual) { + if (!expected.equals(actual)) { + throw new AssertionError("Ambient canary missing; run the tests through Maven (surefire sets them)."); + } + } +} + +/** One request as the server saw it. */ +record Recorded(String method, String path, Map> headers, String body) { + boolean has(String name) { + return headers.containsKey(name); + } + + String header(String name) { + List values = headers.get(name); + return values == null ? null : String.join(", ", values); + } + + String everything() { + StringBuilder text = new StringBuilder(method).append(' ').append(path).append('\n'); + headers.forEach((name, values) -> text.append(name).append(": ").append(String.join(", ", values)).append('\n')); + return text.append(body).toString(); + } + + void assertNoCanaryEgress() { + String everything = everything(); + for (String canary : AmbientEnvironment.ALL_CANARIES) { + if (everything.toLowerCase().contains(canary)) { + throw new AssertionError("Canary reached the wire: " + canary); + } + } + } +} + +/** A real HTTP server on the loopback interface that records every request the SDK sends. */ +final class RecordingServer implements AutoCloseable { + @FunctionalInterface + interface Responder { + void respond(HttpExchange exchange, Recorded request) throws Exception; + } + + private final HttpServer server; + private final ExecutorService executor = Executors.newCachedThreadPool(); + private final List requests = new CopyOnWriteArrayList<>(); + private final Queue responders = new ConcurrentLinkedQueue<>(); + + RecordingServer() throws IOException { + server = HttpServer.create(new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 0), 0); + server.createContext("/", this::handle); + server.setExecutor(executor); + server.start(); + } + + String baseUrl() { + return "http://127.0.0.1:" + server.getAddress().getPort(); + } + + List requests() { + return List.copyOf(requests); + } + + Recorded single() { + List all = requests(); + if (all.size() != 1) { + throw new AssertionError("Expected exactly one request but saw " + all.size()); + } + return all.get(0); + } + + void enqueue(Responder responder) { + responders.add(responder); + } + + @Override + public void close() { + server.stop(0); + executor.shutdownNow(); + } + + private void handle(HttpExchange exchange) throws IOException { + byte[] body = exchange.getRequestBody().readAllBytes(); + Map> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); + exchange.getRequestHeaders().forEach((name, values) -> headers.put(name, List.copyOf(values))); + Recorded recorded = new Recorded( + exchange.getRequestMethod(), + exchange.getRequestURI().toString(), + headers, + new String(body, StandardCharsets.UTF_8)); + requests.add(recorded); + + Responder responder = responders.poll(); + try { + if (responder == null) { + Responses.message(exchange, "OK", 11, 5); + } else { + responder.respond(exchange, recorded); + } + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new IOException(e); + } finally { + exchange.close(); + } + } +} + +/** Canned service responses. */ +final class Responses { + private Responses() {} + + static String messageJson(String textJson, long inputTokens, long outputTokens) { + return "{\"id\":\"msg_test\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"test-model\"," + + "\"content\":[{\"type\":\"text\",\"text\":" + textJson + "}]," + + "\"stop_reason\":\"end_turn\",\"stop_sequence\":null," + + "\"usage\":{\"input_tokens\":" + inputTokens + ",\"output_tokens\":" + outputTokens + "}}"; + } + + static void message(HttpExchange exchange, String text, long inputTokens, long outputTokens) throws IOException { + json(exchange, 200, messageJson(quote(text), inputTokens, outputTokens)); + } + + static void thinkingOnly(HttpExchange exchange) throws IOException { + json(exchange, 200, "{\"id\":\"msg_test\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"test-model\"," + + "\"content\":[{\"type\":\"thinking\",\"thinking\":\"pondering\",\"signature\":\"sig\"}]," + + "\"stop_reason\":\"max_tokens\",\"stop_sequence\":null," + + "\"usage\":{\"input_tokens\":11,\"output_tokens\":1024}}"); + } + + static void error(HttpExchange exchange, int status, String type, String message) throws IOException { + json(exchange, status, "{\"type\":\"error\",\"error\":{\"type\":\"" + type + "\",\"message\":\"" + message + "\"}}"); + } + + static void redirect(HttpExchange exchange, int status, String location) throws IOException { + exchange.getResponseHeaders().add("Location", location); + exchange.sendResponseHeaders(status, -1); + } + + static void json(HttpExchange exchange, int status, String body) throws IOException { + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(status, bytes.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(bytes); + } + } + + /** A server-sent-event stream with one text delta per argument. */ + static void stream(HttpExchange exchange, String... textDeltas) throws IOException { + streamEvents(exchange, true, textDeltas); + } + + /** Like {@link #stream} but the connection ends before message_stop. */ + static void truncatedStream(HttpExchange exchange, String... textDeltas) throws IOException { + streamEvents(exchange, false, textDeltas); + } + + static String messageStartEvent() { + return event("message_start", "{\"type\":\"message_start\",\"message\":{\"id\":\"msg_stream\",\"type\":\"message\"," + + "\"role\":\"assistant\",\"model\":\"test-model\",\"content\":[],\"stop_reason\":null," + + "\"stop_sequence\":null,\"usage\":{\"input_tokens\":11,\"output_tokens\":1}}}"); + } + + private static void streamEvents(HttpExchange exchange, boolean includeStop, String[] textDeltas) throws IOException { + StringBuilder sse = new StringBuilder(messageStartEvent()); + sse.append(event("content_block_start", + "{\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}")); + for (String delta : textDeltas) { + sse.append(event("content_block_delta", "{\"type\":\"content_block_delta\",\"index\":0," + + "\"delta\":{\"type\":\"text_delta\",\"text\":" + quote(delta) + "}}")); + } + sse.append(event("content_block_stop", "{\"type\":\"content_block_stop\",\"index\":0}")); + sse.append(event("message_delta", "{\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"," + + "\"stop_sequence\":null},\"usage\":{\"output_tokens\":7}}")); + if (includeStop) { + sse.append(event("message_stop", "{\"type\":\"message_stop\"}")); + } + + byte[] bytes = sse.toString().getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "text/event-stream"); + exchange.sendResponseHeaders(200, bytes.length); + try (OutputStream out = exchange.getResponseBody()) { + out.write(bytes); + } + } + + static String event(String name, String data) { + return "event: " + name + "\ndata: " + data + "\n\n"; + } + + static String quote(String text) { + StringBuilder quoted = new StringBuilder("\""); + for (char c : text.toCharArray()) { + switch (c) { + case '"' -> quoted.append("\\\""); + case '\\' -> quoted.append("\\\\"); + case '\n' -> quoted.append("\\n"); + case '\r' -> quoted.append("\\r"); + case '\t' -> quoted.append("\\t"); + default -> quoted.append(c); + } + } + return quoted.append('"').toString(); + } +} + +/** A token supplier that hands out a different token per call, like a renewing credential. */ +final class RotatingTokens { + private final AtomicInteger calls = new AtomicInteger(); + + int calls() { + return calls.get(); + } + + Supplier supplier() { + return () -> "rotating-token-" + calls.incrementAndGet(); + } +} + +final class TestClients { + static final String MODEL = "claude-sonnet-5-5"; + + private TestClients() {} + + static AnthropicClient bearer(RecordingServer server, Supplier tokens) { + return bearer(server, tokens, "", null, 0, null); + } + + /** Pass null for {@code maxRetries} or {@code timeout} to keep the factory/SDK defaults. */ + static AnthropicClient bearer( + RecordingServer server, Supplier tokens, String path, String apiVersion, Integer maxRetries, + Duration timeout) { + ClientFactory.Options.Builder options = ClientFactory.Options.builder() + .baseUrl(server.baseUrl() + path) + .tokenSupplier(tokens) + .apiVersion(apiVersion); + if (maxRetries != null) { + options.maxRetries(maxRetries); + } + if (timeout != null) { + options.timeout(timeout); + } + return ClientFactory.create(options.build()); + } + + static AnthropicClient apiKey(RecordingServer server, String key, String header, Integer maxRetries) { + ClientFactory.Options.Builder options = ClientFactory.Options.builder() + .baseUrl(server.baseUrl()) + .apiKey(key) + .apiKeyHeader(header); + if (maxRetries != null) { + options.maxRetries(maxRetries); + } + return ClientFactory.create(options.build()); + } + + /** The {@code anthropic-version} an unconfigured standard SDK client sends. */ + static String sdkDefaultApiVersion() throws Exception { + return sdkDefaultHeader("anthropic-version"); + } + + /** A header an unconfigured standard SDK client sends for {@link #params()}. */ + static String sdkDefaultHeader(String name) throws Exception { + try (RecordingServer baseline = new RecordingServer()) { + AnthropicClient plain = AnthropicOkHttpClient.builder().baseUrl(baseline.baseUrl()).apiKey("baseline-key").build(); + plain.messages().create(params()); + plain.close(); + return baseline.single().header(name); + } + } + + static MessageCreateParams params() { + return params(MODEL); + } + + static MessageCreateParams params(String model) { + return MessageCreateParams.builder().model(model).maxTokens(1024L).addUserMessage("Hello").build(); + } +} \ No newline at end of file diff --git a/samples/php/README.md b/samples/php/README.md new file mode 100644 index 0000000..2070fcd --- /dev/null +++ b/samples/php/README.md @@ -0,0 +1,161 @@ +# Claude on Microsoft Foundry: PHP + +Calls a Claude deployment through the **standard** Anthropic PHP SDK client (`Anthropic\Client`, `anthropic-ai/sdk` `~1.3.0`). It does not use the SDK's `Anthropic\Foundry` namespace and does not subclass the client: the endpoint, the model (deployment) name and the credential are plain configuration. + +| File | Purpose | +|---|---| +| `main.php` | Entry point: one Messages call, printed whole or streamed (`--stream`). | +| `src/Sample.php` | Reads the environment, builds the client, prints the text and usage. | +| `src/ClientFactory.php` | The generic helper. `ClientFactory::createClient()` returns the standard client with exactly one explicit credential. It reads no environment variables and imports no cloud-provider code. | +| `src/CliTokenProvider.php` | Token provider for local development: a command-line fallback that runs `az account get-access-token`. | +| `tests/` | Offline tests: no cloud, no credentials. | + +## Prerequisites + +- PHP 8.1 or later (the SDK's floor) and [Composer](https://getcomposer.org/) 2. +- A CA bundle that PHP's cURL can use. PHP for Windows has none configured, so set one up once (see [TLS certificates](#tls-certificates)); Linux and macOS builds normally use the system store without any setting. +- For `AUTH_MODE=bearer` (the legacy profile's default), the [Azure CLI](https://learn.microsoft.com/cli/azure/) signed in to the tenant that owns the deployment (`az login`). +- A deployment of a Claude model in Microsoft Foundry, and its endpoint URL. + +## Install + +```sh +cd samples/php +composer install +``` + +`composer.json` requires `anthropic-ai/sdk` and `guzzlehttp/guzzle`. The SDK needs a PSR-18 HTTP client; Guzzle is the one the SDK itself recommends. + +## TLS certificates + +The default transport is Guzzle on PHP's cURL extension. It verifies the endpoint's certificate against the CA bundle named by `curl.cainfo` in `php.ini`, and PHP's OpenSSL functions use `openssl.cafile`. PHP for Windows leaves both empty, so the first call can fail with `cURL error 60: SSL certificate problem: unable to get local issuer certificate`. Never switch verification off; give PHP a CA bundle you trust instead: + +1. Get a bundle. The Mozilla bundle that the curl project publishes as `cacert.pem` ([curl.se/docs/caextract.html](https://curl.se/docs/caextract.html)) is the usual choice: check it against the SHA-256 checksum published next to it, and keep it outside this repository. Behind a proxy that inspects TLS, use your organization's bundle instead; it has to contain the proxy's root certificate. +2. Point both settings at it, in the `php.ini` that `php --ini` reports as loaded: + + ```ini + curl.cainfo = "\cacert.pem" + openssl.cafile = "\cacert.pem" + ``` + + or for a single run, without editing `php.ini`: + + ```powershell + php -d "curl.cainfo=\cacert.pem" -d "openssl.cafile=\cacert.pem" main.php + ``` + +Nothing in this sample touches TLS verification: it is Guzzle's default (on), or whatever the PSR-18 client you pass to `ClientFactory::createClient()` does. + +## Configure + +The endpoint, model and key come from one of two profiles that **never borrow from each other**, so a secret can never be paired with the endpoint of the other family: + +| | Canonical profile | Legacy profile | +|---|---|---| +| Selected when | `ANTHROPIC_BASE_URL` is set (it wins when both URLs are set) | only `CLAUDE_BASE_URL` is set | +| Endpoint | `ANTHROPIC_BASE_URL` | `CLAUDE_BASE_URL` | +| Model or deployment | `ANTHROPIC_MODEL` (required) | `CLAUDE_DEPLOYMENT_NAME` (required) | +| Key for `AUTH_MODE=api_key` | `ANTHROPIC_API_KEY` only | `CLAUDE_API_KEY` only | +| `AUTH_MODE` when unset | **error**: set `AUTH_MODE=api_key` or `AUTH_MODE=bearer` explicitly | `bearer` | + +A missing model, key or (canonical profile) `AUTH_MODE` is an error that names what it needs; the sample never falls back to the other profile's value. Because the canonical profile has no default mode, an ambient native `ANTHROPIC_BASE_URL` and `ANTHROPIC_MODEL` can neither silently receive an Azure token nor silently pick up a native key: you choose `api_key` (uses `ANTHROPIC_API_KEY`) or `bearer` (uses an Azure CLI token) on purpose. An ambient `ANTHROPIC_API_KEY` is ignored when `CLAUDE_BASE_URL` selects the legacy profile. + +These settings are shared by both profiles: + +| Variable | Default | Purpose | +|---|---|---| +| `AUTH_MODE` | legacy: `bearer`; canonical: none, must be set | `bearer`: a Microsoft Entra ID token from the Azure CLI. `api_key`: a static key. | +| `API_KEY_HEADER` | `Authorization` | Header that carries the key. `Authorization` sends `Bearer `, the current SDK's native behavior; any other name (for example `x-api-key`) sends the raw key. | +| `ANTHROPIC_API_VERSION` | unset | Unset keeps the SDK's default `anthropic-version`. Set it to override (for example `2023-06-01`). | +| `TOKEN_SCOPE` | `https://ai.azure.com/.default` | Scope requested from the Azure CLI. | +| `AZURE_TENANT_ID` | unset | Adds `--tenant` to the Azure CLI call. | +| `AZURE_TOKEN_CREDENTIALS` | unset | Credential selector shared with the other language samples. Only `AzureCliCredential` (also the default) is implemented here: any other value (`ManagedIdentityCredential`, `AzureDeveloperCliCredential`, `DefaultAzureCredential`, a typo) is rejected with an error instead of being ignored or answered with the CLI. Ignored in `api_key` mode. For managed identity, workload identity, `azd` or any other credential, pass your own token provider. | + +The endpoint must be HTTPS; plain HTTP is accepted for loopback hosts. To load the values that `azd env get-values > .env.local` wrote at the repository root (legacy `CLAUDE_*` names): + +```powershell +# PowerShell, from samples/php +Get-Content ..\..\.env.local | ForEach-Object { if ($_ -match '^\s*([A-Za-z_][A-Za-z0-9_]*)=(.*)$') { Set-Item "env:$($Matches[1])" $Matches[2].Trim('"') } } +``` + +```sh +# bash +set -a; . ../../.env.local; set +a +``` + +## Run + +```sh +php main.php # one Messages call +php main.php --stream # the same request, streamed as it is generated +``` + +Both modes print only the text, then the token usage (the sample waits up to 120 seconds per request): + +```text + + +[usage] input= output= +``` + +Thinking blocks are not printed. A response without any text fails with a message and a non-zero exit status instead of reporting success; so do API errors, credential failures and bad configuration (exit status 1; an unknown argument exits with 2). A failure prints `Error: ...` and then one ` caused by: ...` line per underlying error (for example the transport error behind an `APIConnectionException`), with credentials and token-like strings replaced by `[redacted]`. + +## Authentication + +**`AUTH_MODE=bearer` is a local-development fallback** (the legacy profile's default; the canonical profile needs it set explicitly). The sample runs `az account get-access-token --scope --output json` (adding `--tenant ` when set) for every token request and sends the returned `accessToken` as `Authorization: Bearer`. The Azure CLI owns token caching and renewal; the sample keeps no cache. The price is one CLI process per HTTP attempt, which takes seconds on a typical machine. + +- The command is a fixed argument list, never shell text. Every argument must match `[A-Za-z0-9._:/-]+`, so quotes, spaces and shell or `cmd.exe` metacharacters are rejected before anything starts. +- On Windows the CLI is usually a batch file (`az.cmd` or `az.bat`). The sample finds it on `PATH` (honoring `PATHEXT`, absolute entries only) and starts it as `cmd.exe /d /c az.cmd ...` from its own directory with that fixed argument list. +- Each CLI process has a finite allowance of 60 seconds (a cold start under load can exceed the 10 seconds some identity libraries allow). When it runs out, the process, and on Windows its children, is stopped and the sample fails with a timeout error. It never falls back to another credential. +- A non-zero exit status, output that is not a JSON object, or a missing or empty `accessToken` raises a clear error. The error never contains the CLI's output, and the token is never printed, logged or written to a file. + +**For production, pass your own token provider.** `ClientFactory::createClient()` accepts any `callable(): string` that returns the current token, for example one backed by your identity library (managed identity, workload identity, and so on). No officially supported Microsoft Azure Identity library for PHP was identified when this sample was written, and the sample neither depends on nor endorses a third-party one. Because the provider runs on every HTTP attempt, it should be cheap or cache internally. + +**`AUTH_MODE=api_key`** sends a static key in the header named by `API_KEY_HEADER`. Use it for development and testing. + +## What the helper guarantees + +`ClientFactory::createClient()` returns a plain `Anthropic\Client` and uses only public SDK features (a request middleware and a PSR-18 transport option): + +- **Exactly one credential.** The SDK is given a public, non-secret placeholder token, solely to stop it from discovering `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_PROFILE`, workload identity variables or profiles on disk. A middleware that runs on every HTTP attempt (retries and redirect hops included) removes `Authorization`, `x-api-key` and `api-key`, whatever put them there (including `ANTHROPIC_CUSTOM_HEADERS` and per-request headers), and applies the selected credential. The placeholder never reaches the wire. All other headers, including `anthropic-beta` values you pass, are preserved. +- **No OAuth beta.** A plain bearer token is sent without `anthropic-beta: oauth-2025-04-20`. +- **One origin.** The base URL must be HTTPS (loopback may use HTTP) and may not carry credentials, a query or a fragment. A redirect to a different scheme, host or port is refused before any credential is produced. +- **SDK defaults kept.** The factory adds no retry, refresh or cache of its own, and sets no retry count or timeout unless you pass `maxRetries:` or `timeout:`. The SDK's retries (2) and its documented 600 second request timeout apply; because the PHP SDK leaves timeouts to the PSR-18 client, the default Guzzle transport is created with that value and does not follow redirects. `anthropic-version` is the SDK's default unless you pass `apiVersion:`. +- **The sample's own policy.** `Sample` passes `timeout: 120` (`Sample::REQUEST_TIMEOUT_SECONDS`) so a stuck request ends after two minutes. That is an application choice made visibly in `src/Sample.php`, not something the factory does for you. + +```php +use ClaudeSample\ClientFactory; + +$client = ClientFactory::createClient( + baseUrl: 'https://.services.ai.azure.com/anthropic', + tokenProvider: static fn (): string => $identity->currentAccessToken(), +); +$message = $client->messages->create( + maxTokens: 1024, + messages: [['role' => 'user', 'content' => 'Hello']], + model: '', +); +``` + +## Tests + +```sh +composer test +# which runs: php -d zend.assertions=1 -d assert.exception=1 tests/run.php +``` + +The suite uses PHP's built-in `assert()` (the runner refuses to start with assertions off, which would pass silently) and needs no framework. It runs offline: + +- a recording PSR-18 transport checks the request the SDK builds: the Foundry-style and native paths and the model, a rotating bearer token, a resource key in `x-api-key` and the native `Authorization` key, the API version, no OAuth beta, canaries for `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_PROFILE`, `ANTHROPIC_BASE_URL` and `ANTHROPIC_CUSTOM_HEADERS` (with a control showing the SDK defaults would send them), streaming, HTTP error statuses, retries that fetch a fresh token, and redirects; +- the token provider (`CliTokenProvider`) is tested with a fake process runner and with a fixture `az` (a `.cmd` on Windows, a shell script elsewhere) that is really launched; +- the entry point is tested end to end, including mixed-family canaries (decoy `ANTHROPIC_*` and `CLAUDE_*` values must never be paired with the other profile's endpoint, model or key) and the 120 second policy; the error output (the cause chain behind a connection failure, credential redaction, the certificate hint) is tested with synthetic failures and with a real refused connection; a few tests talk to PHP's built-in web server on a loopback port through the default Guzzle transport (credential headers on a real socket, redirects, streaming and the timeout). Nothing leaves your machine. + +## Troubleshooting + +- `Run "composer install" in this directory first.`: install the dependencies. +- `ANTHROPIC_BASE_URL selects the ANTHROPIC_* settings and requires an explicit AUTH_MODE ...`: the canonical profile has no default mode; set `AUTH_MODE=api_key` (and `ANTHROPIC_API_KEY`) or `AUTH_MODE=bearer`. +- `Azure CLI exited with code N ...`: run `az login`, and `az account get-access-token --scope https://ai.azure.com/.default --output none` to see the CLI's own message. +- `Error: APIConnectionException: Anthropic API Connection Error`: the `caused by:` line under it names the real problem. `cURL error 60` or `SSL certificate problem` (also `cURL error 77`) means PHP has no usable CA bundle, and the sample adds a `Hint:` line: see [TLS certificates](#tls-certificates). `cURL error 6`, `7` and `28` are a host that does not resolve, a refused connection and a timeout: check the endpoint URL and the network. +- A connection failure can take tens of seconds to be reported: the SDK retries it twice, and in `bearer` mode every attempt asks the Azure CLI for a token again. +- `Azure CLI did not finish within its 60 second allowance ...`: run `az account get-access-token --output none` by hand to see why; the first run after an install or reboot is the slowest. +- A 401 or 403 from the service is reported as is (`AuthenticationException`, `PermissionDeniedException`); the sample never retries it with another credential. diff --git a/samples/php/composer.json b/samples/php/composer.json new file mode 100644 index 0000000..fab850e --- /dev/null +++ b/samples/php/composer.json @@ -0,0 +1,25 @@ +{ + "name": "azure-samples/claude-php-sample", + "description": "Claude on Microsoft Foundry through the standard Anthropic PHP SDK client", + "type": "project", + "license": "MIT", + "require": { + "php": ">=8.1", + "anthropic-ai/sdk": "~1.3.0", + "guzzlehttp/guzzle": "^7.9" + }, + "autoload": { + "psr-4": { + "ClaudeSample\\": "src/" + } + }, + "config": { + "allow-plugins": { + "php-http/discovery": false + }, + "sort-packages": true + }, + "scripts": { + "test": "php -d zend.assertions=1 -d assert.exception=1 tests/run.php" + } +} diff --git a/samples/php/composer.lock b/samples/php/composer.lock new file mode 100644 index 0000000..57623e7 --- /dev/null +++ b/samples/php/composer.lock @@ -0,0 +1,1159 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "7ec5aa92be6e8102fb207b5e10715bfd", + "packages": [ + { + "name": "anthropic-ai/sdk", + "version": "v1.3.0", + "source": { + "type": "git", + "url": "https://github.com/anthropics/anthropic-sdk-php.git", + "reference": "3f558cd8a929695c6d0798ed53c9d986884dec7f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/anthropics/anthropic-sdk-php/zipball/3f558cd8a929695c6d0798ed53c9d986884dec7f", + "reference": "3f558cd8a929695c6d0798ed53c9d986884dec7f", + "shasum": "" + }, + "require": { + "open-telemetry/api": "^1.0", + "php": "^8.1", + "php-http/discovery": "^1", + "psr/http-client": "^1", + "psr/http-client-implementation": "^1", + "psr/http-factory-implementation": "^1", + "psr/http-message": "^1|^2", + "standard-webhooks/standard-webhooks": "^1" + }, + "require-dev": { + "aws/aws-sdk-php": "^3.368", + "friendsofphp/php-cs-fixer": "^3", + "google/auth": "^1.49", + "guzzlehttp/guzzle": "^7", + "mcp/sdk": "^0.7.1", + "nyholm/psr7": "^1", + "open-telemetry/sdk": "^1.0", + "pestphp/pest": "^3", + "php-http/mock-client": "^1", + "phpstan/extension-installer": "^1", + "phpstan/phpstan": "2.2.13", + "phpstan/phpstan-phpunit": "^2", + "phpunit/phpunit": "^11", + "symfony/http-client": "^7" + }, + "suggest": { + "aws/aws-sdk-php": "Allows using the AWS Bedrock, AWS gateway, and Bedrock Mantle SDKs", + "google/auth": "Allows using the Google Vertex and Google Cloud gateway SDKs", + "mcp/sdk": "Required to use the BetaMcp helpers for integrating MCP servers with the Anthropic SDK" + }, + "type": "library", + "autoload": { + "files": [ + "src/Version.php" + ], + "psr-4": { + "Anthropic\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "description": "Anthropic PHP SDK", + "support": { + "issues": "https://github.com/anthropics/anthropic-sdk-php/issues", + "source": "https://github.com/anthropics/anthropic-sdk-php/tree/v1.3.0" + }, + "time": "2026-10-23T23:14:10+00:00" + }, + { + "name": "guzzlehttp/guzzle", + "version": "7.16.1", + "source": { + "type": "git", + "url": "https://github.com/guzzle/guzzle.git", + "reference": "81755d989b3007ca7f88a069857553cd08e7dc2e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/guzzle/zipball/81755d989b3007ca7f88a069857553cd08e7dc2e", + "reference": "81755d989b3007ca7f88a069857553cd08e7dc2e", + "shasum": "" + }, + "require": { + "ext-json": "*", + "guzzlehttp/promises": "^2.6", + "guzzlehttp/psr7": "^2.13.2", + "php": "^7.2.5 || ^8.0", + "psr/http-client": "^1.0", + "symfony/deprecation-contracts": "^2.5 || ^3.0", + "symfony/polyfill-php80": "^1.25" + }, + "provide": { + "psr/http-client-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "ext-curl": "*", + "guzzle/client-integration-tests": "3.0.3", + "guzzlehttp/test-server": "^0.7", + "php-http/message-factory": "^1.1", + "phpunit/phpunit": "^8.5.52 || ^9.6.34", + "psr/log": "^1.1 || ^2.0 || ^3.0" + }, + "suggest": { + "ext-curl": "Required for CURL handler support", + "ext-intl": "Required for Internationalized Domain Name (IDN) support", + "psr/log": "Required for using the Log middleware" + }, + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "autoload": { + "files": [ + "src/functions_include.php" + ], + "psr-4": { + "GuzzleHttp\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Jeremy Lindblom", + "email": "jeremeamia@gmail.com", + "homepage": "https://github.com/jeremeamia" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle is a PHP HTTP client library", + "keywords": [ + "client", + "curl", + "framework", + "http", + "http client", + "psr-18", + "psr-7", + "rest", + "web service" + ], + "support": { + "issues": "https://github.com/guzzle/guzzle/issues", + "source": "https://github.com/guzzle/guzzle/tree/7.16.1" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/guzzle", + "type": "tidelift" + } + ], + "time": "2026-10-25T21:35:21+00:00" + }, + { + "name": "guzzlehttp/promises", + "version": "2.6.0", + "source": { + "type": "git", + "url": "https://github.com/guzzle/promises.git", + "reference": "3d88c829bd5f13d13847b39067dbf09a60af2154" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/promises/zipball/3d88c829bd5f13d13847b39067dbf09a60af2154", + "reference": "3d88c829bd5f13d13847b39067dbf09a60af2154", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0", + "symfony/deprecation-contracts": "^2.5 || ^3.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "phpunit/phpunit": "^8.5.52 || ^9.6.34" + }, + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Promise\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + } + ], + "description": "Guzzle promises library", + "keywords": [ + "promise" + ], + "support": { + "issues": "https://github.com/guzzle/promises/issues", + "source": "https://github.com/guzzle/promises/tree/2.6.0" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/promises", + "type": "tidelift" + } + ], + "time": "2026-10-18T12:46:59+00:00" + }, + { + "name": "guzzlehttp/psr7", + "version": "2.13.2", + "source": { + "type": "git", + "url": "https://github.com/guzzle/psr7.git", + "reference": "adee536f95101929f262b8c59e8a61472f347d58" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/guzzle/psr7/zipball/adee536f95101929f262b8c59e8a61472f347d58", + "reference": "adee536f95101929f262b8c59e8a61472f347d58", + "shasum": "" + }, + "require": { + "php": "^7.2.5 || ^8.0", + "psr/http-factory": "^1.0", + "psr/http-message": "^1.1 || ^2.0", + "ralouphie/getallheaders": "^3.0", + "symfony/deprecation-contracts": "^2.5 || ^3.0", + "symfony/polyfill-php80": "^1.25" + }, + "provide": { + "psr/http-factory-implementation": "1.0", + "psr/http-message-implementation": "1.0" + }, + "require-dev": { + "bamarni/composer-bin-plugin": "^1.8.2", + "http-interop/http-factory-tests": "1.1.0", + "jshttp/mime-db": "1.54.0.1", + "phpunit/phpunit": "^8.5.52 || ^9.6.34" + }, + "suggest": { + "laminas/laminas-httphandlerrunner": "Emit PSR-7 responses" + }, + "type": "library", + "extra": { + "bamarni-bin": { + "bin-links": true, + "forward-command": false + } + }, + "autoload": { + "psr-4": { + "GuzzleHttp\\Psr7\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Graham Campbell", + "email": "hello@gjcampbell.co.uk", + "homepage": "https://github.com/GrahamCampbell" + }, + { + "name": "Michael Dowling", + "email": "mtdowling@gmail.com", + "homepage": "https://github.com/mtdowling" + }, + { + "name": "George Mponos", + "email": "gmponos@gmail.com", + "homepage": "https://github.com/gmponos" + }, + { + "name": "Tobias Nyholm", + "email": "tobias.nyholm@gmail.com", + "homepage": "https://github.com/Nyholm" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://github.com/sagikazarmark" + }, + { + "name": "Tobias Schultze", + "email": "webmaster@tubo-world.de", + "homepage": "https://github.com/Tobion" + }, + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com", + "homepage": "https://sagikazarmark.hu" + } + ], + "description": "PSR-7 message implementation that also provides common utility methods", + "keywords": [ + "http", + "message", + "psr-7", + "request", + "response", + "stream", + "uri", + "url" + ], + "support": { + "issues": "https://github.com/guzzle/psr7/issues", + "source": "https://github.com/guzzle/psr7/tree/2.13.2" + }, + "funding": [ + { + "url": "https://github.com/GrahamCampbell", + "type": "github" + }, + { + "url": "https://github.com/Nyholm", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/guzzlehttp/psr7", + "type": "tidelift" + } + ], + "time": "2026-10-17T23:49:46+00:00" + }, + { + "name": "open-telemetry/api", + "version": "1.10.1", + "source": { + "type": "git", + "url": "https://github.com/opentelemetry-php/api.git", + "reference": "b2bc26bf8bd6b2b6447b3626b2a1b5733873aa0b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/opentelemetry-php/api/zipball/b2bc26bf8bd6b2b6447b3626b2a1b5733873aa0b", + "reference": "b2bc26bf8bd6b2b6447b3626b2a1b5733873aa0b", + "shasum": "" + }, + "require": { + "open-telemetry/context": "^1.4", + "php": "^8.1", + "psr/log": "^1.1|^2.0|^3.0", + "symfony/polyfill-php82": "^1.26" + }, + "conflict": { + "open-telemetry/sdk": "<=1.11" + }, + "type": "library", + "extra": { + "spi": { + "OpenTelemetry\\API\\Instrumentation\\AutoInstrumentation\\HookManagerInterface": [ + "OpenTelemetry\\API\\Instrumentation\\AutoInstrumentation\\ExtensionHookManager" + ] + }, + "branch-alias": { + "dev-main": "1.8.x-dev" + } + }, + "autoload": { + "files": [ + "Trace/functions.php" + ], + "psr-4": { + "OpenTelemetry\\API\\": "." + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "opentelemetry-php contributors", + "homepage": "https://github.com/open-telemetry/opentelemetry-php/graphs/contributors" + } + ], + "description": "API for OpenTelemetry PHP.", + "keywords": [ + "Metrics", + "api", + "apm", + "logging", + "opentelemetry", + "otel", + "tracing" + ], + "support": { + "chat": "https://app.slack.com/client/T08PSQ7BQ/C01NFPCV44V", + "docs": "https://opentelemetry.io/docs/languages/php", + "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", + "source": "https://github.com/open-telemetry/opentelemetry-php" + }, + "time": "2026-09-16T01:59:09+00:00" + }, + { + "name": "open-telemetry/context", + "version": "1.5.0", + "source": { + "type": "git", + "url": "https://github.com/opentelemetry-php/context.git", + "reference": "3c414b246e0dabb7d6145404e6a5e4536ca18d07" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/opentelemetry-php/context/zipball/3c414b246e0dabb7d6145404e6a5e4536ca18d07", + "reference": "3c414b246e0dabb7d6145404e6a5e4536ca18d07", + "shasum": "" + }, + "require": { + "php": "^8.1", + "symfony/polyfill-php82": "^1.26" + }, + "suggest": { + "ext-ffi": "To allow context switching in Fibers" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-main": "1.0.x-dev" + } + }, + "autoload": { + "files": [ + "fiber/initialize_fiber_handler.php" + ], + "psr-4": { + "OpenTelemetry\\Context\\": "." + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "Apache-2.0" + ], + "authors": [ + { + "name": "opentelemetry-php contributors", + "homepage": "https://github.com/open-telemetry/opentelemetry-php/graphs/contributors" + } + ], + "description": "Context implementation for OpenTelemetry PHP.", + "keywords": [ + "Context", + "opentelemetry", + "otel" + ], + "support": { + "chat": "https://app.slack.com/client/T08PSQ7BQ/C01NFPCV44V", + "docs": "https://opentelemetry.io/docs/languages/php", + "issues": "https://github.com/open-telemetry/opentelemetry-php/issues", + "source": "https://github.com/open-telemetry/opentelemetry-php" + }, + "time": "2025-10-19T06:44:33+00:00" + }, + { + "name": "php-http/discovery", + "version": "1.20.0", + "source": { + "type": "git", + "url": "https://github.com/php-http/discovery.git", + "reference": "82fe4c73ef3363caed49ff8dd1539ba06044910d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-http/discovery/zipball/82fe4c73ef3363caed49ff8dd1539ba06044910d", + "reference": "82fe4c73ef3363caed49ff8dd1539ba06044910d", + "shasum": "" + }, + "require": { + "composer-plugin-api": "^1.0|^2.0", + "php": "^7.1 || ^8.0" + }, + "conflict": { + "nyholm/psr7": "<1.0", + "zendframework/zend-diactoros": "*" + }, + "provide": { + "php-http/async-client-implementation": "*", + "php-http/client-implementation": "*", + "psr/http-client-implementation": "*", + "psr/http-factory-implementation": "*", + "psr/http-message-implementation": "*" + }, + "require-dev": { + "composer/composer": "^1.0.2|^2.0", + "graham-campbell/phpspec-skip-example-extension": "^5.0", + "php-http/httplug": "^1.0 || ^2.0", + "php-http/message-factory": "^1.0", + "phpspec/phpspec": "^5.1 || ^6.1 || ^7.3", + "sebastian/comparator": "^3.0.5 || ^4.0.8", + "symfony/phpunit-bridge": "^6.4.4 || ^7.0.1" + }, + "type": "composer-plugin", + "extra": { + "class": "Http\\Discovery\\Composer\\Plugin", + "plugin-optional": true + }, + "autoload": { + "psr-4": { + "Http\\Discovery\\": "src/" + }, + "exclude-from-classmap": [ + "src/Composer/Plugin.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Márk Sági-Kazár", + "email": "mark.sagikazar@gmail.com" + } + ], + "description": "Finds and installs PSR-7, PSR-17, PSR-18 and HTTPlug implementations", + "homepage": "http://php-http.org", + "keywords": [ + "adapter", + "client", + "discovery", + "factory", + "http", + "message", + "psr17", + "psr7" + ], + "support": { + "issues": "https://github.com/php-http/discovery/issues", + "source": "https://github.com/php-http/discovery/tree/1.20.0" + }, + "time": "2024-10-02T11:20:13+00:00" + }, + { + "name": "psr/http-client", + "version": "1.0.3", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-client.git", + "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-client/zipball/bb5906edc1c324c9a05aa0873d40117941e5fa90", + "reference": "bb5906edc1c324c9a05aa0873d40117941e5fa90", + "shasum": "" + }, + "require": { + "php": "^7.0 || ^8.0", + "psr/http-message": "^1.0 || ^2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Client\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP clients", + "homepage": "https://github.com/php-fig/http-client", + "keywords": [ + "http", + "http-client", + "psr", + "psr-18" + ], + "support": { + "source": "https://github.com/php-fig/http-client" + }, + "time": "2023-09-23T14:17:50+00:00" + }, + { + "name": "psr/http-factory", + "version": "1.1.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-factory.git", + "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-factory/zipball/2b4765fddfe3b508ac62f829e852b1501d3f6e8a", + "reference": "2b4765fddfe3b508ac62f829e852b1501d3f6e8a", + "shasum": "" + }, + "require": { + "php": ">=7.1", + "psr/http-message": "^1.0 || ^2.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "PSR-17: Common interfaces for PSR-7 HTTP message factories", + "keywords": [ + "factory", + "http", + "message", + "psr", + "psr-17", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-factory" + }, + "time": "2024-04-15T12:06:14+00:00" + }, + { + "name": "psr/http-message", + "version": "2.0", + "source": { + "type": "git", + "url": "https://github.com/php-fig/http-message.git", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/http-message/zipball/402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "reference": "402d35bcb92c70c026d1a6a9883f06b2ead23d71", + "shasum": "" + }, + "require": { + "php": "^7.2 || ^8.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.0.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Http\\Message\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for HTTP messages", + "homepage": "https://github.com/php-fig/http-message", + "keywords": [ + "http", + "http-message", + "psr", + "psr-7", + "request", + "response" + ], + "support": { + "source": "https://github.com/php-fig/http-message/tree/2.0" + }, + "time": "2023-04-04T09:54:51+00:00" + }, + { + "name": "psr/log", + "version": "3.0.2", + "source": { + "type": "git", + "url": "https://github.com/php-fig/log.git", + "reference": "f16e1d5863e37f8d8c2a01719f5b34baa2b714d3" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/php-fig/log/zipball/f16e1d5863e37f8d8c2a01719f5b34baa2b714d3", + "reference": "f16e1d5863e37f8d8c2a01719f5b34baa2b714d3", + "shasum": "" + }, + "require": { + "php": ">=8.0.0" + }, + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "3.x-dev" + } + }, + "autoload": { + "psr-4": { + "Psr\\Log\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "PHP-FIG", + "homepage": "https://www.php-fig.org/" + } + ], + "description": "Common interface for logging libraries", + "homepage": "https://github.com/php-fig/log", + "keywords": [ + "log", + "psr", + "psr-3" + ], + "support": { + "source": "https://github.com/php-fig/log/tree/3.0.2" + }, + "time": "2024-09-11T13:17:53+00:00" + }, + { + "name": "ralouphie/getallheaders", + "version": "3.0.3", + "source": { + "type": "git", + "url": "https://github.com/ralouphie/getallheaders.git", + "reference": "120b605dfeb996808c31b6477290a714d356e822" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/ralouphie/getallheaders/zipball/120b605dfeb996808c31b6477290a714d356e822", + "reference": "120b605dfeb996808c31b6477290a714d356e822", + "shasum": "" + }, + "require": { + "php": ">=5.6" + }, + "require-dev": { + "php-coveralls/php-coveralls": "^2.1", + "phpunit/phpunit": "^5 || ^6.5" + }, + "type": "library", + "autoload": { + "files": [ + "src/getallheaders.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ralph Khattar", + "email": "ralph.khattar@gmail.com" + } + ], + "description": "A polyfill for getallheaders.", + "support": { + "issues": "https://github.com/ralouphie/getallheaders/issues", + "source": "https://github.com/ralouphie/getallheaders/tree/develop" + }, + "time": "2019-03-08T08:55:37+00:00" + }, + { + "name": "standard-webhooks/standard-webhooks", + "version": "v1.0.2", + "source": { + "type": "git", + "url": "https://github.com/standard-webhooks/standard-webhooks.git", + "reference": "a1773d7ffc577d730e2bf4d4bd740a82a42aa904" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/standard-webhooks/standard-webhooks/zipball/a1773d7ffc577d730e2bf4d4bd740a82a42aa904", + "reference": "a1773d7ffc577d730e2bf4d4bd740a82a42aa904", + "shasum": "" + }, + "require": { + "php": "^8.0" + }, + "require-dev": { + "phpunit/phpunit": "^9.0 || ^10.0" + }, + "type": "library", + "autoload": { + "psr-4": { + "StandardWebhooks\\": "libraries/php/src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Standard Webhooks - Open source tools and guidelines for sending webhooks easily, securely, and reliably", + "homepage": "https://www.standardwebhooks.com", + "keywords": [ + "hmac", + "signature", + "standard-webhooks", + "verification", + "webhooks" + ], + "support": { + "issues": "https://github.com/standard-webhooks/standard-webhooks/issues", + "source": "https://github.com/standard-webhooks/standard-webhooks/tree/v1.0.2" + }, + "time": "2026-02-18T19:02:27+00:00" + }, + { + "name": "symfony/deprecation-contracts", + "version": "v3.7.1", + "source": { + "type": "git", + "url": "https://github.com/symfony/deprecation-contracts.git", + "reference": "f3202fa1b5097b0af062dc978b32ecf63404e31d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/deprecation-contracts/zipball/f3202fa1b5097b0af062dc978b32ecf63404e31d", + "reference": "f3202fa1b5097b0af062dc978b32ecf63404e31d", + "shasum": "" + }, + "require": { + "php": ">=8.1" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/contracts", + "name": "symfony/contracts" + }, + "branch-alias": { + "dev-main": "3.7-dev" + } + }, + "autoload": { + "files": [ + "function.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "A generic function and convention to trigger deprecation notices", + "homepage": "https://symfony.com", + "support": { + "source": "https://github.com/symfony/deprecation-contracts/tree/v3.7.1" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-06-05T06:23:12+00:00" + }, + { + "name": "symfony/polyfill-php80", + "version": "v1.43.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php80.git", + "reference": "9c6a5d6b01ca51d486c813e9a9c0ed55f208bb74" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php80/zipball/9c6a5d6b01ca51d486c813e9a9c0ed55f208bb74", + "reference": "9c6a5d6b01ca51d486c813e9a9c0ed55f208bb74", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php80\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Ion Bazan", + "email": "ion.bazan@gmail.com" + }, + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php80/tree/v1.43.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-09-25T15:50:05+00:00" + }, + { + "name": "symfony/polyfill-php82", + "version": "v1.43.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-php82.git", + "reference": "843bbe8b2a7934307b749751eede0f111f5d1cfc" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-php82/zipball/843bbe8b2a7934307b749751eede0f111f5d1cfc", + "reference": "843bbe8b2a7934307b749751eede0f111f5d1cfc", + "shasum": "" + }, + "require": { + "php": ">=7.2" + }, + "type": "library", + "extra": { + "thanks": { + "url": "https://github.com/symfony/polyfill", + "name": "symfony/polyfill" + } + }, + "autoload": { + "files": [ + "bootstrap.php" + ], + "psr-4": { + "Symfony\\Polyfill\\Php82\\": "" + }, + "classmap": [ + "Resources/stubs" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Nicolas Grekas", + "email": "p@tchwork.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill backporting some PHP 8.2+ features to lower PHP versions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "polyfill", + "portable", + "shim" + ], + "support": { + "source": "https://github.com/symfony/polyfill-php82/tree/v1.43.0" + }, + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://github.com/nicolas-grekas", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ], + "time": "2026-09-25T15:50:05+00:00" + } + ], + "packages-dev": [], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": {}, + "prefer-stable": false, + "prefer-lowest": false, + "platform": { + "php": ">=8.1" + }, + "platform-dev": {}, + "plugin-api-version": "2.9.0" +} diff --git a/samples/php/main.php b/samples/php/main.php new file mode 100644 index 0000000..7bd1ff1 --- /dev/null +++ b/samples/php/main.php @@ -0,0 +1,13 @@ +#!/usr/bin/env php + --output json`. The CLI owns token caching + * and renewal, so the price is one CLI process per request and this class keeps no cache of its own. Production code + * should give ClientFactory a token provider backed by its own identity library instead. + * + * The command is a fixed argument list, never shell text. Every argument is checked against a short allowlist, which also + * keeps cmd.exe metacharacters out when the CLI is a Windows batch file (az.cmd / az.bat). + * + * Each CLI process gets a finite allowance (60 seconds: a cold start under load can exceed 10). When it runs out the + * process (and, on Windows, its children) is stopped and the call fails; there is no fallback to another credential. + */ +final class CliTokenProvider +{ + public const TIMEOUT_SECONDS = 60.0; + + /** Letters, digits and . _ : / - only: no quotes, spaces, or shell and cmd.exe metacharacters. */ + private const SAFE_ARGUMENT = '/^[A-Za-z0-9._:\/-]+$/D'; + + private const TENANT = '/^[A-Za-z0-9.-]+$/D'; + + private const VISIBLE_ASCII = '/^[\x21-\x7E]+$/D'; + + private function __construct() {} + + /** + * @param (callable(list): array{int, string})|null $run Replaces the process launch. Receives the arguments after `az` and returns [exit code, stdout]. + * @param float|null $timeout Seconds each CLI process may take; null means TIMEOUT_SECONDS + * + * @return \Closure(): string + */ + public static function provider(string $scope, ?string $tenantId = null, ?callable $run = null, ?float $timeout = null): \Closure + { + $arguments = ['account', 'get-access-token', '--scope', self::safe($scope, 'The token scope'), '--output', 'json']; + if ($tenantId !== null && '' !== $tenantId) { + if (1 !== preg_match(self::TENANT, $tenantId)) { + throw new \InvalidArgumentException('The tenant ID may only contain letters, digits, "." and "-".'); + } + array_push($arguments, '--tenant', $tenantId); + } + $run ??= static fn (array $arguments): array => self::run($arguments, null, $timeout); + + return static function () use ($arguments, $run, $scope): string { + [$exitCode, $stdout] = $run($arguments); + if (0 !== $exitCode) { + throw new \RuntimeException(sprintf('Azure CLI exited with code %d while requesting a token for scope %s. Run "az login" and retry, or supply your own token provider.', $exitCode, $scope)); + } + try { + $payload = json_decode($stdout, true, 16, JSON_THROW_ON_ERROR); + } catch (\JsonException) { + $payload = null; + } + if (!is_array($payload) || ([] !== $payload && array_is_list($payload))) { + throw new \RuntimeException('Azure CLI returned output that is not a JSON object.'); + } + $token = $payload['accessToken'] ?? null; + if (!is_string($token) || 1 !== preg_match(self::VISIBLE_ASCII, $token)) { + throw new \RuntimeException('Azure CLI response has no usable accessToken.'); + } + + return $token; + }; + } + + /** + * Starts the Azure CLI found on $searchPath (default: PATH) and returns [exit code, stdout]. stderr is discarded. + * A CLI that is still running after $timeout seconds (default TIMEOUT_SECONDS) is stopped and the call throws. + * + * @param list $arguments + * + * @return array{int, string} + */ + public static function run(array $arguments, ?string $searchPath = null, ?float $timeout = null): array + { + $timeout ??= self::TIMEOUT_SECONDS; + foreach ($arguments as $argument) { + self::safe($argument, 'Azure CLI arguments'); + } + $windows = 'Windows' === PHP_OS_FAMILY; + $executable = self::locate($searchPath ?? (string) getenv('PATH'), null, $windows); + if ($executable === null) { + throw new \RuntimeException('Azure CLI ("az") was not found on PATH. Install it and run "az login", or supply your own token provider.'); + } + [$command, $directory] = self::command($executable, $arguments, $windows, $windows ? self::commandInterpreter() : null); + // Windows pipes cannot be read against a deadline; a socket pair can. + $descriptors = [0 => ['pipe', 'r'], 1 => $windows ? ['socket'] : ['pipe', 'w'], 2 => ['file', $windows ? 'NUL' : '/dev/null', 'w']]; + $process = @proc_open($command, $descriptors, $pipes, $directory, null, ['bypass_shell' => true]); + if (!is_resource($process)) { + throw new \RuntimeException('Azure CLI could not be started.'); + } + fclose($pipes[0]); + + $deadline = microtime(true) + $timeout; + $stdout = ''; + while (true) { + $remaining = $deadline - microtime(true); + if ($remaining <= 0) { + self::stop($process, $windows); + fclose($pipes[1]); + proc_close($process); + throw new \RuntimeException(sprintf('Azure CLI did not finish within its %s second allowance and was stopped; try "az account get-access-token --output none" by hand, or supply your own token provider.', rtrim(rtrim(number_format($timeout, 1, '.', ''), '0'), '.'))); + } + $stdout .= self::available($pipes[1], min(0.2, $remaining)); + $status = proc_get_status($process); + if (!$status['running']) { + // The exit code is only reported by the first status call after the process ended. + $exitCode = $status['exitcode'] < 0 ? 1 : $status['exitcode']; + break; + } + if (feof($pipes[1])) { + usleep(10_000); + } + } + $stdout .= self::available($pipes[1], 0.05, true); + fclose($pipes[1]); + proc_close($process); + + return [$exitCode, $stdout]; + } + + /** + * Finds `az` in the absolute directories of $searchPath. On Windows it honors PATHEXT, limited to .com, .exe, .bat and .cmd. + */ + public static function locate(string $searchPath, ?string $pathExt = null, ?bool $windows = null): ?string + { + $windows ??= 'Windows' === PHP_OS_FAMILY; + $names = ['az']; + if ($windows) { + $extensions = array_values(array_filter( + array_map('strtolower', explode(';', $pathExt ?? (string) getenv('PATHEXT'))), + static fn (string $extension): bool => in_array($extension, ['.com', '.exe', '.bat', '.cmd'], true), + )); + $names = array_map(static fn (string $extension): string => 'az'.$extension, $extensions ?: ['.com', '.exe', '.bat', '.cmd']); + } + foreach (explode($windows ? ';' : ':', $searchPath) as $directory) { + $directory = trim($directory, " \t\""); + $absolute = $windows ? 1 === preg_match('/^(?:[A-Za-z]:[\\\\\/]|\\\\\\\\)/', $directory) : str_starts_with($directory, '/'); + if (!$absolute) { + continue; + } + foreach ($names as $name) { + $candidate = rtrim($directory, '\\/').DIRECTORY_SEPARATOR.$name; + if (is_file($candidate) && ($windows || is_executable($candidate))) { + return $candidate; + } + } + } + + return null; + } + + /** + * Builds the argument list and working directory for one launch. + * + * A Windows batch file can only run under cmd.exe. It is started by bare file name from its own directory, so a + * path with spaces or parentheses needs no quoting; /d skips AutoRun commands. Arguments are allowlisted by run(). + * + * @param list $arguments + * + * @return array{list, string|null} [argv, working directory] + */ + public static function command(string $executable, array $arguments, bool $windows, ?string $interpreter = null): array + { + if ($windows && 1 === preg_match('/\.(?:bat|cmd)$/i', $executable)) { + return [[$interpreter ?? self::commandInterpreter(), '/d', '/c', basename($executable), ...$arguments], dirname($executable)]; + } + + return [[$executable, ...$arguments], null]; + } + + /** What $stream can deliver within $wait seconds; with $all, everything that is already there. */ + private static function available($stream, float $wait, bool $all = false): string + { + $data = ''; + do { + $read = [$stream]; + $write = $except = null; + if (!@stream_select($read, $write, $except, 0, (int) ($wait * 1_000_000)) || [] === $read) { + break; + } + $chunk = fread($stream, 8192); + if (!is_string($chunk) || '' === $chunk) { + break; + } + $data .= $chunk; + } while ($all); + + return $data; + } + + /** Stops the CLI; on Windows also its children (az.cmd runs the CLI as a child of cmd.exe). */ + private static function stop($process, bool $windows): void + { + $pid = (int) (proc_get_status($process)['pid'] ?? 0); + if ($windows && $pid > 0) { + $taskkill = rtrim((string) (getenv('SystemRoot') ?: 'C:\\Windows'), '\\/').'\\System32\\taskkill.exe'; + $killer = @proc_open([$taskkill, '/F', '/T', '/PID', (string) $pid], [0 => ['file', 'NUL', 'r'], 1 => ['file', 'NUL', 'w'], 2 => ['file', 'NUL', 'w']], $ignored, null, null, ['bypass_shell' => true]); + if (is_resource($killer)) { + proc_close($killer); + } + } + proc_terminate($process, 9); + } + + private static function commandInterpreter(): string + { + $configured = (string) getenv('ComSpec'); + if (0 === strcasecmp(basename($configured), 'cmd.exe') && is_file($configured)) { + return $configured; + } + + return rtrim((string) (getenv('SystemRoot') ?: 'C:\\Windows'), '\\/').'\\System32\\cmd.exe'; + } + + private static function safe(string $value, string $what): string + { + if (1 !== preg_match(self::SAFE_ARGUMENT, $value)) { + throw new \InvalidArgumentException(sprintf('%s may only contain letters, digits and the characters . _ : / -', $what)); + } + + return $value; + } +} diff --git a/samples/php/src/ClientFactory.php b/samples/php/src/ClientFactory.php new file mode 100644 index 0000000..12fcf02 --- /dev/null +++ b/samples/php/src/ClientFactory.php @@ -0,0 +1,161 @@ +`; any other name sends the raw key. + * @param string|null $apiVersion `anthropic-version` to send on every request; null keeps the SDK default + * @param ClientInterface|null $httpClient PSR-18 transport. It must enforce its own timeout and must not follow redirects; defaults to Guzzle. + * @param float|null $timeout Seconds, for the default transport only (the SDK leaves timeouts to the PSR-18 client); null keeps the SDK's documented 600 seconds + * @param int|null $maxRetries null keeps the SDK default + */ + public static function createClient( + string $baseUrl, + ?callable $tokenProvider = null, + ?string $apiKey = null, + string $keyHeader = 'Authorization', + ?string $apiVersion = null, + ?ClientInterface $httpClient = null, + ?float $timeout = null, + ?int $maxRetries = null, + ): Client { + $origin = self::originOf($baseUrl); + if (($tokenProvider === null) === ($apiKey === null)) { + throw new \InvalidArgumentException('Provide exactly one of tokenProvider or apiKey.'); + } + if (1 !== preg_match(self::HEADER_NAME, $keyHeader)) { + throw new \InvalidArgumentException('keyHeader must be a valid HTTP header name.'); + } + if ($apiKey !== null && 1 !== preg_match(self::VISIBLE_ASCII, $apiKey)) { + throw new \InvalidArgumentException('apiKey must be a non-empty string without whitespace or control characters.'); + } + if ($apiVersion !== null && 1 !== preg_match(self::VISIBLE_ASCII, $apiVersion)) { + throw new \InvalidArgumentException('apiVersion must be a non-empty string without whitespace or control characters.'); + } + + $header = $tokenProvider !== null ? 'Authorization' : $keyHeader; + $authorize = static function (RequestInterface $request, \Closure $next) use ($origin, $tokenProvider, $apiKey, $header, $apiVersion): ResponseInterface { + self::assertOrigin($request->getUri(), $origin); + $secret = $tokenProvider !== null ? self::acquireToken($tokenProvider) : (string) $apiKey; + foreach ([...self::CREDENTIAL_HEADERS, $header] as $name) { + $request = $request->withoutHeader($name); + } + $request = $request->withHeader($header, 0 === strcasecmp($header, 'Authorization') ? 'Bearer '.$secret : $secret); + if ($apiVersion !== null) { + $request = $request->withHeader('anthropic-version', $apiVersion); + } + + return $next($request); + }; + + $requestOptions = [ + 'transporter' => $httpClient ?? self::defaultHttpClient($timeout), + 'middleware' => [$authorize], + ]; + if ($maxRetries !== null) { + $requestOptions['maxRetries'] = $maxRetries; + } + + return new Client( + authToken: self::SUPPRESSION_PLACEHOLDER, + baseUrl: $baseUrl, + requestOptions: $requestOptions, + ); + } + + /** The transport used when none is passed: Guzzle with a request timeout (default: the SDK's) and without redirect following. */ + public static function defaultHttpClient(?float $timeout = null): ClientInterface + { + $timeout ??= self::SDK_DEFAULT_TIMEOUT; + if (!class_exists(GuzzleClient::class)) { + throw new \LogicException('Pass an $httpClient (PSR-18) with a request timeout and without redirect following, or install guzzlehttp/guzzle.'); + } + + return new GuzzleClient([ + 'timeout' => $timeout, + 'connect_timeout' => $timeout, + 'allow_redirects' => false, + 'http_errors' => false, + ]); + } + + /** @return array{string, string, int} scheme, host, port */ + private static function originOf(string $baseUrl): array + { + $parts = parse_url($baseUrl); + $scheme = strtolower((string) ($parts['scheme'] ?? '')); + $host = strtolower((string) ($parts['host'] ?? '')); + $secure = 'https' === $scheme || ('http' === $scheme && in_array($host, self::LOOPBACK_HOSTS, true)); + if (false === $parts || '' === $host || !$secure || isset($parts['user']) || isset($parts['pass']) || isset($parts['query']) || isset($parts['fragment'])) { + throw new \InvalidArgumentException('baseUrl must be an HTTPS URL without credentials, query, or fragment.'); + } + + return [$scheme, $host, $parts['port'] ?? ('https' === $scheme ? 443 : 80)]; + } + + /** @param array{string, string, int} $origin */ + private static function assertOrigin(UriInterface $uri, array $origin): void + { + $scheme = strtolower($uri->getScheme()); + $port = $uri->getPort() ?? ('https' === $scheme ? 443 : 80); + if ([$scheme, strtolower($uri->getHost()), $port] !== $origin || '' !== $uri->getUserInfo()) { + throw new \RuntimeException('Refusing to send credentials to a different origin.'); + } + } + + private static function acquireToken(callable $tokenProvider): string + { + try { + $token = $tokenProvider(); + } catch (ClientExceptionInterface $e) { + // A PSR-18 exception would be retried and rewrapped by the SDK as a connection failure. + throw new \RuntimeException('The token provider failed.', 0, $e); + } + if (!is_string($token) || 1 !== preg_match(self::VISIBLE_ASCII, $token)) { + throw new \RuntimeException('The token provider must return a non-empty string without whitespace or control characters.'); + } + + return $token; + } +} diff --git a/samples/php/src/Sample.php b/samples/php/src/Sample.php new file mode 100644 index 0000000..17ca078 --- /dev/null +++ b/samples/php/src/Sample.php @@ -0,0 +1,311 @@ + -d openssl.cafile=) at a trusted CA bundle; see \"TLS certificates\" in the README.\n"; + + private function __construct() {} + + /** + * @param list $arguments command-line arguments after the script name + * @param array $env + * @param resource $stdout + * @param resource $stderr + * @param ClientInterface|null $httpClient PSR-18 transport override (tests) + * @param (callable(list): array{int, string})|null $runCli Azure CLI process override (tests) + */ + public static function run(array $arguments, array $env, $stdout, $stderr, ?ClientInterface $httpClient = null, ?callable $runCli = null): int + { + $stream = false; + foreach ($arguments as $argument) { + if ('--stream' === $argument) { + $stream = true; + } elseif ('-h' === $argument || '--help' === $argument) { + fwrite($stdout, self::USAGE); + + return 0; + } else { + fwrite($stderr, sprintf("Unknown argument: %s\n%s", $argument, self::USAGE)); + + return 2; + } + } + + $issued = new \ArrayObject(); + try { + [$client, $model] = self::configure($env, $httpClient, $runCli, $issued); + if ($stream) { + self::stream($client, $model, $stdout); + } else { + self::message($client, $model, $stdout); + } + } catch (\Throwable $error) { + $configured = array_filter(array_map(static fn (string $name): mixed => $env[$name] ?? null, self::KEY_VARIABLES), 'is_string'); + fwrite($stderr, self::describeError($error, [...$configured, ...$issued->getArrayCopy()])); + + return 1; + } + + return 0; + } + + /** + * The text printed for a failure: the error, then each underlying cause. The transport error behind a connection + * failure (a rejected server certificate, a refused connection) is visible only there. Credentials and token-like + * strings are replaced by [redacted], and every message is cut to one line of bounded length. + * + * @param list $secrets exact values to remove from every message + */ + public static function describeError(\Throwable $error, array $secrets = []): string + { + $own = $error instanceof \InvalidArgumentException || $error instanceof \RuntimeException; + $entries = [self::redact(($own ? '' : self::shortName($error).': ').$error->getMessage(), $secrets)]; + $cause = $error->getPrevious(); + for ($depth = 0; $cause !== null && $depth < self::MAX_CAUSES; ++$depth, $cause = $cause->getPrevious()) { + $entry = self::redact(self::shortName($cause).': '.$cause->getMessage(), $secrets); + if ($entry !== end($entries)) { + $entries[] = $entry; + } + } + if ($cause !== null) { + $entries[] = '(further causes are not shown)'; + } + + $tls = 1 === preg_match(self::TLS_FAILURE, implode("\n", $entries)); + $text = 'Error: '.array_shift($entries)."\n"; + foreach ($entries as $entry) { + $text .= ' caused by: '.$entry."\n"; + } + + return $tls ? $text.self::TLS_HINT : $text; + } + + /** + * Builds the client and returns it with the model name. + * + * ANTHROPIC_BASE_URL selects the canonical profile: ANTHROPIC_MODEL and, for an API key, ANTHROPIC_API_KEY. AUTH_MODE + * must be set explicitly (api_key or bearer), so an ambient native endpoint and key can never silently receive an + * Azure token, nor an ambient Azure setup a native key. Otherwise CLAUDE_BASE_URL selects the legacy profile: + * CLAUDE_DEPLOYMENT_NAME and CLAUDE_API_KEY, with AUTH_MODE defaulting to bearer. A profile never falls back to the + * other one's model or key, so a secret can never be paired with the endpoint of the other family. + * + * @param array $env + * @param (callable(list): array{int, string})|null $runCli + * @param \ArrayObject|null $issued receives every bearer token the provider returns, so error output can remove it + * + * @return array{Client, string} + */ + public static function configure(array $env, ?ClientInterface $httpClient = null, ?callable $runCli = null, ?\ArrayObject $issued = null): array + { + $canonical = self::setting($env, 'ANTHROPIC_BASE_URL') !== null; + if ($canonical) { + [$baseUrl, $model, $keyName, $defaultMode] = [self::setting($env, 'ANTHROPIC_BASE_URL'), self::setting($env, 'ANTHROPIC_MODEL'), 'ANTHROPIC_API_KEY', null]; + $missingModel = 'ANTHROPIC_BASE_URL selects the ANTHROPIC_* settings: also set ANTHROPIC_MODEL (CLAUDE_DEPLOYMENT_NAME is not used with it).'; + $missingKey = 'Set ANTHROPIC_API_KEY (CLAUDE_API_KEY is not used with ANTHROPIC_BASE_URL).'; + } else { + [$baseUrl, $model, $keyName, $defaultMode] = [self::setting($env, 'CLAUDE_BASE_URL'), self::setting($env, 'CLAUDE_DEPLOYMENT_NAME'), 'CLAUDE_API_KEY', 'bearer']; + $missingModel = 'CLAUDE_BASE_URL selects the CLAUDE_* settings: also set CLAUDE_DEPLOYMENT_NAME (ANTHROPIC_MODEL is not used with it).'; + $missingKey = 'Set CLAUDE_API_KEY (ANTHROPIC_API_KEY is not used with CLAUDE_BASE_URL).'; + } + if ($baseUrl === null) { + throw new \InvalidArgumentException('Set CLAUDE_BASE_URL and CLAUDE_DEPLOYMENT_NAME, or ANTHROPIC_BASE_URL and ANTHROPIC_MODEL. The two sets are never mixed.'); + } + if ($model === null) { + throw new \InvalidArgumentException($missingModel); + } + + $mode = self::setting($env, 'AUTH_MODE') ?? $defaultMode; + if ($mode === null) { + throw new \InvalidArgumentException('ANTHROPIC_BASE_URL selects the ANTHROPIC_* settings and requires an explicit AUTH_MODE: set AUTH_MODE=api_key (uses ANTHROPIC_API_KEY) or AUTH_MODE=bearer (uses an Azure CLI token).'); + } + $tokenProvider = null; + $apiKey = null; + if ('bearer' === $mode) { + // The selector is shared with the other language samples. Only the Azure CLI is built in here, so any other + // explicit choice is refused rather than silently answered with the CLI. + $selector = self::setting($env, 'AZURE_TOKEN_CREDENTIALS'); + if ($selector !== null && 'AzureCliCredential' !== $selector) { + throw new \InvalidArgumentException(sprintf( + 'AZURE_TOKEN_CREDENTIALS=%s is not supported: the Azure CLI (AzureCliCredential) is this sample\'s only built-in token source. Unset it, or pass your own token provider to ClientFactory for other credentials.', + 1 === preg_match('/^[A-Za-z0-9_.-]{1,64}$/D', $selector) ? $selector : '(unprintable or too long)', + )); + } + $tokenProvider = CliTokenProvider::provider( + self::setting($env, 'TOKEN_SCOPE') ?? self::DEFAULT_TOKEN_SCOPE, + self::setting($env, 'AZURE_TENANT_ID'), + $runCli, + ); + if ($issued !== null) { + $provider = $tokenProvider; + $tokenProvider = static function () use ($provider, $issued): string { + $token = $provider(); + $issued[] = $token; + + return $token; + }; + } + } elseif ('api_key' === $mode) { + $apiKey = self::setting($env, $keyName) ?? throw new \InvalidArgumentException($missingKey); + } else { + throw new \InvalidArgumentException('AUTH_MODE must be bearer or api_key.'); + } + + $client = ClientFactory::createClient( + baseUrl: $baseUrl, + tokenProvider: $tokenProvider, + apiKey: $apiKey, + keyHeader: self::setting($env, 'API_KEY_HEADER') ?? 'Authorization', + apiVersion: self::setting($env, 'ANTHROPIC_API_VERSION'), + httpClient: $httpClient, + timeout: self::REQUEST_TIMEOUT_SECONDS, + ); + + return [$client, $model]; + } + + /** @param resource $stdout */ + private static function message(Client $client, string $model, $stdout): void + { + $message = $client->messages->create( + maxTokens: self::MAX_TOKENS, + messages: [['role' => 'user', 'content' => self::PROMPT]], + model: $model, + ); + + $printed = false; + foreach ($message->content as $block) { + if ($block instanceof TextBlock && '' !== trim($block->text)) { + fwrite($stdout, $block->text."\n"); + $printed = true; + } + } + if (!$printed) { + throw new \RuntimeException(self::noText($message->stopReason)); + } + fwrite($stdout, sprintf("\n[usage] input=%d output=%d\n", $message->usage->inputTokens, $message->usage->outputTokens)); + } + + /** @param resource $stdout */ + private static function stream(Client $client, string $model, $stdout): void + { + $events = $client->messages->createStream( + maxTokens: self::MAX_TOKENS, + messages: [['role' => 'user', 'content' => self::PROMPT]], + model: $model, + ); + + $printed = false; + $input = 0; + $output = 0; + $stopReason = null; + foreach ($events as $event) { + if ($event instanceof RawMessageStartEvent) { + $input = $event->message->usage->inputTokens; + $output = $event->message->usage->outputTokens; + } elseif ($event instanceof RawContentBlockDeltaEvent && $event->delta instanceof TextDelta) { + fwrite($stdout, $event->delta->text); + fflush($stdout); + $printed = $printed || '' !== trim($event->delta->text); + } elseif ($event instanceof RawMessageDeltaEvent) { + $input = $event->usage->inputTokens ?? $input; + $output = $event->usage->outputTokens; + $stopReason = $event->delta->stopReason; + } + } + if (!$printed) { + throw new \RuntimeException(self::noText($stopReason)); + } + fwrite($stdout, sprintf("\n\n[usage] input=%d output=%d\n", $input, $output)); + } + + private static function shortName(\Throwable $error): string + { + return (new \ReflectionClass($error))->getShortName(); + } + + /** @param list $secrets */ + private static function redact(string $text, array $secrets): string + { + foreach ($secrets as $secret) { + if (strlen($secret) >= self::MIN_SECRET_LENGTH) { + $text = str_replace($secret, '[redacted]', $text); + } + } + $patterns = [ + '~(?<=://)[^/@\s]*@~' => '[redacted]@', + '~(\bhttps?://[^\s?#]*)[?#]\S*~i' => '$1?[redacted]', + '~\b(authorization|proxy-authorization|x-api-key|api-key|cookie)(["\']?\s*[:=]\s*["\']?)(?:(?:bearer|basic)\s+)?[^\s"\',;]+~i' => '$1$2[redacted]', + '~\b(bearer|basic)\s+[A-Za-z0-9._\~+/=-]{6,}~i' => '$1 [redacted]', + '~\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}(?:\.[A-Za-z0-9_-]*)?~' => '[redacted]', + '~\bsk-ant-[A-Za-z0-9_-]+~' => '[redacted]', + '~[\x00-\x1F\x7F]+~' => ' ', + ]; + $text = preg_replace(array_keys($patterns), array_values($patterns), $text); + if ($text === null) { + return '(message hidden: it could not be checked for credentials)'; + } + $text = trim($text); + + return strlen($text) > self::MAX_MESSAGE_LENGTH ? substr($text, 0, self::MAX_MESSAGE_LENGTH).'...' : $text; + } + + private static function noText(?string $stopReason): string + { + return sprintf('No text response (stop_reason=%s). Increase max_tokens if the response exhausted its budget.', $stopReason ?? 'none'); + } + + /** @param array $env the first of $names that is set and not empty */ + private static function setting(array $env, string ...$names): ?string + { + foreach ($names as $name) { + if (isset($env[$name]) && '' !== $env[$name]) { + return $env[$name]; + } + } + + return null; + } +} diff --git a/samples/php/tests/CliTokenProviderTest.php b/samples/php/tests/CliTokenProviderTest.php new file mode 100644 index 0000000..fcaff62 --- /dev/null +++ b/samples/php/tests/CliTokenProviderTest.php @@ -0,0 +1,166 @@ +): array{int, string} */ +function cli_returning(int $exitCode, string $stdout, array &$calls = []): \Closure +{ + return static function (array $arguments) use ($exitCode, $stdout, &$calls): array { + $calls[] = $arguments; + + return [$exitCode, $stdout]; + }; +} + +function failure_message(\Closure $provider): string +{ + try { + $provider(); + } catch (\RuntimeException $error) { + return $error->getMessage(); + } + throw new \AssertionError('the provider succeeded'); +} + +test('CLI token provider asks for the scope with a fixed argument list, once per token request', function (): void { + $calls = []; + $provider = CliTokenProvider::provider('https://ai.azure.com/.default', null, static function (array $arguments) use (&$calls): array { + $calls[] = $arguments; + + return [0, json_encode(['accessToken' => 'cli-token-'.count($calls), 'expiresOn' => '2099-01-01 00:00:00.000000', 'tokenType' => 'Bearer'])]; + }); + same([], $calls, 'nothing runs at creation'); + same('cli-token-1', $provider(), 'first token'); + same('cli-token-2', $provider(), 'second token: this class keeps no cache of its own'); + same([TOKEN_ARGUMENTS, TOKEN_ARGUMENTS], $calls, 'arguments'); +}); + +test('CLI token provider adds --tenant only when a tenant is configured', function (): void { + $calls = []; + CliTokenProvider::provider('https://ai.azure.com/.default', 'tenant-1.example', cli_returning(0, '{"accessToken":"t"}', $calls))(); + CliTokenProvider::provider('https://ai.azure.com/.default', '', cli_returning(0, '{"accessToken":"t"}', $calls))(); + same([[...TOKEN_ARGUMENTS, '--tenant', 'tenant-1.example'], TOKEN_ARGUMENTS], $calls, 'arguments'); +}); + +test('CLI arguments are allowlisted, so nothing is interpreted by a shell or cmd.exe', function (): void { + $unsafe = ['', 'a b', 'a&b', 'a|b', 'a^b', 'a%PATH%', 'a"b', "a'b", 'a;b', 'a`b', 'a$b', 'a(b)', 'a static fn () => CliTokenProvider::provider($value), + 'tenant' => static fn () => CliTokenProvider::provider('https://ai.azure.com/.default', $value ?: 'x y'), + 'run' => static fn () => CliTokenProvider::run(['account', $value]), + ] as $where => $attempt) { + try { + $attempt(); + } catch (\InvalidArgumentException) { + continue; + } + throw new \AssertionError(sprintf('%s accepted %s', $where, json_encode($value))); + } + } +}); + +test('CLI failure, malformed output and empty tokens raise exact errors without echoing the payload', function (): void { + $scope = 'https://ai.azure.com/.default'; + $leak = 'raw-payload-secret-value'; + $cases = [ + 'non-zero exit' => [7, '{"accessToken":"'.$leak.'"}', sprintf('Azure CLI exited with code 7 while requesting a token for scope %s. Run "az login" and retry, or supply your own token provider.', $scope)], + 'not JSON' => [0, 'ERROR '.$leak, 'Azure CLI returned output that is not a JSON object.'], + 'JSON scalar' => [0, '"'.$leak.'"', 'Azure CLI returned output that is not a JSON object.'], + 'no accessToken' => [0, '{"refreshToken":"'.$leak.'"}', 'Azure CLI response has no usable accessToken.'], + 'empty accessToken' => [0, '{"accessToken":"","refreshToken":"'.$leak.'"}', 'Azure CLI response has no usable accessToken.'], + 'null accessToken' => [0, '{"accessToken":null,"x":"'.$leak.'"}', 'Azure CLI response has no usable accessToken.'], + 'numeric accessToken' => [0, '{"accessToken":12345,"x":"'.$leak.'"}', 'Azure CLI response has no usable accessToken.'], + 'spaced accessToken' => [0, '{"accessToken":"two words","x":"'.$leak.'"}', 'Azure CLI response has no usable accessToken.'], + 'multi-line accessToken' => [0, '{"accessToken":"line\nbreak","x":"'.$leak.'"}', 'Azure CLI response has no usable accessToken.'], + ]; + foreach ($cases as $label => [$exitCode, $stdout, $expected]) { + $message = failure_message(CliTokenProvider::provider($scope, null, cli_returning($exitCode, $stdout))); + same($expected, $message, $label); + assert(!str_contains($message, $leak), "$label echoed the CLI payload"); + } +}); + +test('a CLI that does not finish within its allowance is stopped and reported, never replaced by a fallback', function (): void { + if ('Windows' !== PHP_OS_FAMILY) { + chmod(FAKE_AZ_DIRECTORY.'/az', 0755); + } + same(60.0, CliTokenProvider::TIMEOUT_SECONDS, 'the default allowance is finite and generous'); + $started = microtime(true); + $provider = CliTokenProvider::provider('https://ai.azure.com/.default', null, static fn (array $arguments): array => CliTokenProvider::run($arguments, FAKE_AZ_DIRECTORY, 1.0)); + $message = with_env(['FAKE_AZ_MODE' => 'slow'], static fn (): string => failure_message($provider)); + same('Azure CLI did not finish within its 1 second allowance and was stopped; try "az account get-access-token --output none" by hand, or supply your own token provider.', $message, 'message'); + assert(microtime(true) - $started < 4.5, 'the CLI must be stopped at its allowance, not left to finish (the fixture takes about 7 seconds)'); + assert(!str_contains($message, 'too-late-token'), 'no output of the CLI in the error'); +}); + +test('a missing Azure CLI is reported with an actionable message', function (): void { + try { + CliTokenProvider::run(['version'], __DIR__.DIRECTORY_SEPARATOR.'no-such-directory'); + } catch (\RuntimeException $error) { + same('Azure CLI ("az") was not found on PATH. Install it and run "az login", or supply your own token provider.', $error->getMessage(), 'message'); + + return; + } + throw new \AssertionError('a missing CLI was not reported'); +}); + +test('command(): a Windows batch file runs under cmd.exe from its own directory, anything else runs directly', function (): void { + $arguments = ['account', 'get-access-token']; + same( + [['C:/Windows/System32/cmd.exe', '/d', '/c', 'az.cmd', ...$arguments], 'C:/Program Files (x86)/Azure CLI/wbin'], + CliTokenProvider::command('C:/Program Files (x86)/Azure CLI/wbin/az.cmd', $arguments, true, 'C:/Windows/System32/cmd.exe'), + 'az.cmd on Windows', + ); + same( + [['C:/Windows/System32/cmd.exe', '/d', '/c', 'az.BAT', ...$arguments], 'C:/tools'], + CliTokenProvider::command('C:/tools/az.BAT', $arguments, true, 'C:/Windows/System32/cmd.exe'), + 'az.BAT on Windows', + ); + same([['C:/tools/az.exe', ...$arguments], null], CliTokenProvider::command('C:/tools/az.exe', $arguments, true, 'C:/Windows/System32/cmd.exe'), 'az.exe on Windows'); + same([['/usr/bin/az', ...$arguments], null], CliTokenProvider::command('/usr/bin/az', $arguments, false), 'az on Unix'); + same([['/opt/tools/az.cmd', ...$arguments], null], CliTokenProvider::command('/opt/tools/az.cmd', $arguments, false), 'a file named az.cmd on Unix is not special'); +}); + +test('locate(): searches only absolute PATH entries and honors PATHEXT on Windows', function (): void { + $directory = FAKE_AZ_DIRECTORY; + if ('Windows' === PHP_OS_FAMILY) { + same($directory.'\\az.cmd', CliTokenProvider::locate($directory, '.COM;.EXE;.BAT;.CMD', true), 'found through PATHEXT'); + same($directory.'\\az.cmd', CliTokenProvider::locate('relative-dir;'.$directory, null, true), 'relative PATH entries are skipped; default extensions'); + same(null, CliTokenProvider::locate('relative-dir;'.__DIR__.'\\nowhere', '.EXE', true), 'absent'); + same(null, CliTokenProvider::locate($directory, '.EXE;.COM', true), 'extensions missing from PATHEXT are not tried'); + } else { + chmod($directory.'/az', 0755); + same($directory.'/az', CliTokenProvider::locate('relative-dir:'.$directory, null, false), 'found on PATH'); + same(null, CliTokenProvider::locate('relative-dir', null, false), 'relative PATH entries are skipped'); + } +}); + +test('real process launch: the fixture CLI receives exactly the fixed arguments and its exit status is returned', function (): void { + if ('Windows' !== PHP_OS_FAMILY) { + chmod(FAKE_AZ_DIRECTORY.'/az', 0755); + } + $run = static fn (array $arguments): array => CliTokenProvider::run($arguments, FAKE_AZ_DIRECTORY); + + [$exitCode, $stdout] = with_env(['FAKE_AZ_MODE' => 'args'], static fn (): array => $run([...TOKEN_ARGUMENTS, '--tenant', 'tenant-1.example'])); + same(0, $exitCode, 'exit code'); + same( + 'account get-access-token --scope https://ai.azure.com/.default --output json --tenant tenant-1.example', + json_decode($stdout, true, flags: JSON_THROW_ON_ERROR)['accessToken'], + 'arguments as the CLI saw them', + ); + + $token = with_env(['FAKE_AZ_MODE' => 'ok'], static fn (): string => CliTokenProvider::provider('https://ai.azure.com/.default', null, $run)()); + same('fixture-cli-token', $token, 'token through the provider'); + + same(3, with_env(['FAKE_AZ_MODE' => 'fail'], static fn (): int => $run(TOKEN_ARGUMENTS)[0]), 'failing CLI exit code'); + $message = with_env(['FAKE_AZ_MODE' => 'empty'], static fn (): string => failure_message(CliTokenProvider::provider('https://ai.azure.com/.default', null, $run))); + same('Azure CLI response has no usable accessToken.', $message, 'empty token through a real launch'); +}); diff --git a/samples/php/tests/ClientFactoryTest.php b/samples/php/tests/ClientFactoryTest.php new file mode 100644 index 0000000..2ebf7d2 --- /dev/null +++ b/samples/php/tests/ClientFactoryTest.php @@ -0,0 +1,331 @@ + $options named createClient() arguments that replace the defaults */ +function make(Recorder $recorder, array $options = []): Client +{ + return ClientFactory::createClient(...[ + 'baseUrl' => BASE_URL, + 'tokenProvider' => static fn (): string => 'selected-token', + 'httpClient' => $recorder, + 'maxRetries' => 0, + ...$options, + ]); +} + +/** @param array $requestOptions */ +function send(Client $client, array $requestOptions = []): Message +{ + return $client->messages->create( + maxTokens: 32, + messages: [['role' => 'user', 'content' => 'Hello']], + model: MODEL, + requestOptions: [] === $requestOptions ? null : $requestOptions, + ); +} + +function authorization_of(RequestInterface $request): string +{ + return headers_of($request)['authorization'] ?? '(none)'; +} + +test('returns the standard SDK client and resolves the token per request, not at creation', function (): void { + $calls = 0; + $recorder = new Recorder(); + $client = make($recorder, ['tokenProvider' => static function () use (&$calls): string { + return ['first-token', 'second-token'][$calls++]; + }]); + same(Client::class, get_class($client), 'client class'); + same(0, $calls, 'provider calls at creation'); + same('OK', send($client)->content[0]->text, 'response text'); + send($client); + same(2, $calls, 'provider calls'); + same(['Bearer first-token', 'Bearer second-token'], array_map(authorization_of(...), $recorder->requests), 'authorization per request'); + foreach ($recorder->requests as $request) { + $headers = headers_of($request); + assert(!isset($headers['anthropic-beta']), 'a generic bearer must not carry the OAuth beta'); + assert(!isset($headers['x-api-key']) && !isset($headers['api-key']), 'only one credential header'); + assert(!str_contains(wire_of($request), 'provided-by-request-hook'), 'the suppression placeholder stays off the wire'); + } +}); + +test('sends the model and the native or Foundry-style path', function (): void { + $cases = ['https://api.anthropic.com' => '/v1/messages', BASE_URL => '/anthropic/v1/messages']; + foreach ($cases as $base => $path) { + $recorder = new Recorder(); + send(make($recorder, ['baseUrl' => $base])); + same($base.'/v1/messages', (string) $recorder->requests[0]->getUri(), "URL for $base"); + same($path, $recorder->requests[0]->getUri()->getPath(), "path for $base"); + $body = json_decode((string) $recorder->requests[0]->getBody(), true, flags: JSON_THROW_ON_ERROR); + same(MODEL, $body['model'], 'model'); + same(32, $body['max_tokens'], 'max_tokens'); + } +}); + +test('ambient credentials, profile, base URL and custom headers cannot reach the wire', function (): void { + $ambient = [ + 'ANTHROPIC_API_KEY' => 'ambient-key-canary', + 'ANTHROPIC_AUTH_TOKEN' => 'ambient-token-canary', + 'ANTHROPIC_PROFILE' => 'nonexistent-profile-canary', + 'ANTHROPIC_BASE_URL' => 'https://wrong.example', + 'ANTHROPIC_CUSTOM_HEADERS' => "Authorization: custom-canary\nx-api-key: key-canary\napi-key: alias-canary", + 'ANTHROPIC_FOUNDRY_RESOURCE' => 'unchanged-cli-resource', + ]; + with_env($ambient, static function (): void { + $recorder = new Recorder(); + send(make($recorder), ['extraHeaders' => [ + 'Authorization' => 'request-canary', + 'x-api-key' => 'request-key-canary', + 'anthropic-beta' => 'a-requested-beta', + ]]); + $request = $recorder->requests[0]; + $headers = headers_of($request); + same('Bearer selected-token', $headers['authorization'], 'authorization'); + assert(!isset($headers['x-api-key']) && !isset($headers['api-key']), 'no other credential header'); + same('a-requested-beta', $headers['anthropic-beta'], 'the requested beta is preserved and nothing is added'); + same(BASE_URL.'/v1/messages', (string) $request->getUri(), 'the explicit base URL wins over ANTHROPIC_BASE_URL'); + assert(!str_contains(wire_of($request), 'canary'), 'no ambient or per-request canary on the wire'); + same('unchanged-cli-resource', getenv('ANTHROPIC_FOUNDRY_RESOURCE'), 'the factory does not touch the environment'); + }); +}); + +test('control: the same ambient values do reach the wire from an unconfigured SDK client', function (): void { + with_env([ + 'ANTHROPIC_API_KEY' => 'ambient-key-canary', + 'ANTHROPIC_CUSTOM_HEADERS' => "x-api-key: header-canary\napi-key: alias-canary", + ], static function (): void { + $recorder = new Recorder(); + send(new Client(baseUrl: BASE_URL, requestOptions: ['transporter' => $recorder, 'maxRetries' => 0])); + $wire = wire_of($recorder->requests[0]); + foreach (['ambient-key-canary', 'header-canary', 'alias-canary'] as $canary) { + assert(str_contains($wire, $canary), "the SDK defaults leak $canary, so the canary test is meaningful"); + } + }); + with_env(['ANTHROPIC_PROFILE' => 'nonexistent-profile-canary'], static function (): void { + try { + new Client(baseUrl: BASE_URL, requestOptions: ['transporter' => new Recorder()]); + } catch (AnthropicException) { + ClientFactory::createClient(baseUrl: BASE_URL, apiKey: 'selected-key', httpClient: new Recorder()); + + return; + } + throw new \AssertionError('the SDK did not look for the profile named by ANTHROPIC_PROFILE'); + }); +}); + +test('API key header is configuration: Authorization by default, any other header name verbatim', function (): void { + $cases = [ + [BASE_URL, null, 'authorization', 'Bearer selected-key'], + ['https://api.anthropic.com', 'Authorization', 'authorization', 'Bearer selected-key'], + [BASE_URL, 'x-api-key', 'x-api-key', 'selected-key'], + [BASE_URL, 'api-key', 'api-key', 'selected-key'], + ]; + foreach ($cases as [$base, $header, $name, $expected]) { + $recorder = new Recorder(); + $options = ['baseUrl' => $base, 'tokenProvider' => null, 'apiKey' => 'selected-key']; + send(make($recorder, null === $header ? $options : $options + ['keyHeader' => $header])); + $headers = headers_of($recorder->requests[0]); + same($expected, $headers[$name] ?? null, "$name for ".($header ?? 'the default header')); + foreach (['authorization', 'x-api-key', 'api-key'] as $other) { + assert($other === $name || !isset($headers[$other]), "$other must be absent"); + } + assert(!isset($headers['anthropic-beta']), 'no OAuth beta'); + assert(!str_contains(wire_of($recorder->requests[0]), 'provided-by-request-hook'), 'placeholder stays off the wire'); + } +}); + +test('anthropic-version is the SDK default unless configured', function (): void { + $recorder = new Recorder(); + send(make($recorder)); + same(Client::ANTHROPIC_API_VERSION, headers_of($recorder->requests[0])['anthropic-version'], 'default version'); + + $recorder = new Recorder(); + send(make($recorder, ['apiVersion' => '2023-06-01']), ['extraHeaders' => ['anthropic-version' => 'request-version']]); + same('2023-06-01', headers_of($recorder->requests[0])['anthropic-version'], 'configured version'); +}); + +test('invalid configuration fails before any network use', function (): void { + $invalid = [ + 'neither credential' => ['tokenProvider' => null], + 'both credentials' => ['apiKey' => 'key'], + 'plain HTTP' => ['baseUrl' => 'http://insecure.example'], + 'credentials in the URL' => ['baseUrl' => 'https://user:secret@example.com'], + 'query in the URL' => ['baseUrl' => BASE_URL.'?x=1'], + 'fragment in the URL' => ['baseUrl' => BASE_URL.'#x'], + 'unsupported scheme' => ['baseUrl' => 'ftp://example.com'], + 'no host' => ['baseUrl' => 'https://'], + 'empty URL' => ['baseUrl' => ''], + 'empty key' => ['tokenProvider' => null, 'apiKey' => ''], + 'multi-line key' => ['tokenProvider' => null, 'apiKey' => "key\nvalue"], + 'spaced key' => ['tokenProvider' => null, 'apiKey' => 'key value'], + 'bad header name' => ['tokenProvider' => null, 'apiKey' => 'key', 'keyHeader' => "bad\nheader"], + 'empty header name' => ['tokenProvider' => null, 'apiKey' => 'key', 'keyHeader' => ''], + 'bad version' => ['apiVersion' => "2023\n06"], + ]; + foreach ($invalid as $label => $options) { + $recorder = new Recorder(); + try { + make($recorder, $options); + } catch (\InvalidArgumentException) { + same(0, count($recorder->requests), "$label sent a request"); + + continue; + } + throw new \AssertionError("$label was accepted"); + } + foreach (['http://127.0.0.1:8080', 'http://localhost', 'http://[::1]:8080', 'https://example.com:8443/anthropic'] as $accepted) { + make(new Recorder(), ['baseUrl' => $accepted]); + } +}); + +test('a same-origin redirect is followed and re-authorized', function (): void { + $issued = 0; + $recorder = new Recorder(static fn (RequestInterface $request, int $call): Response => 1 === $call + ? new Response(307, ['Location' => '/anthropic/v1/messages-moved']) + : json_response(message_body())); + send(make($recorder, ['tokenProvider' => static function () use (&$issued): string { + return 'token-'.(++$issued); + }])); + same(['Bearer token-1', 'Bearer token-2'], array_map(authorization_of(...), $recorder->requests), 'authorization per hop'); + same('/anthropic/v1/messages-moved', $recorder->requests[1]->getUri()->getPath(), 'redirect target'); +}); + +test('a cross-origin redirect is refused before any credential is produced or sent', function (): void { + $targets = [ + 'https://untrusted.example/v1/messages', + 'http://example.services.ai.azure.com/anthropic/v1/messages', + 'https://example.services.ai.azure.com:8443/anthropic/v1/messages', + ]; + foreach ($targets as $target) { + $issued = 0; + $recorder = new Recorder(static fn (): Response => new Response(302, ['Location' => $target])); + $client = make($recorder, ['tokenProvider' => static function () use (&$issued): string { + return 'token-'.(++$issued); + }]); + try { + send($client); + } catch (\RuntimeException $error) { + same('Refusing to send credentials to a different origin.', $error->getMessage(), 'message'); + same(1, count($recorder->requests), "only the original origin is contacted for $target"); + same(1, $issued, "no token is produced for the refused hop to $target"); + + continue; + } + throw new \AssertionError("redirect to $target was followed"); + } +}); + +test('a provider failure surfaces unchanged and no request is sent', function (): void { + $failure = new \RuntimeException('credential unavailable'); + $recorder = new Recorder(); + $client = make($recorder, ['tokenProvider' => static function () use ($failure): string { + throw $failure; + }]); + try { + send($client); + } catch (\RuntimeException $caught) { + same($failure, $caught, 'exception'); + same(0, count($recorder->requests), 'requests'); + + return; + } + throw new \AssertionError('the provider failure was swallowed'); +}); + +test('a token that is empty, multi-line or not a string is rejected without being echoed', function (): void { + foreach (['', "line\nbreak", 'has space', 42, null] as $bad) { + $recorder = new Recorder(); + $client = make($recorder, ['tokenProvider' => static fn () => $bad]); + try { + send($client); + } catch (\RuntimeException $error) { + same('The token provider must return a non-empty string without whitespace or control characters.', $error->getMessage(), 'message'); + same(0, count($recorder->requests), 'requests'); + + continue; + } + throw new \AssertionError('an invalid token was sent'); + } +}); + +test('HTTP error statuses surface as SDK exceptions that do not contain the credential', function (): void { + $expected = [ + 401 => AuthenticationException::class, + 403 => PermissionDeniedException::class, + 429 => RateLimitException::class, + 500 => InternalServerException::class, + ]; + foreach ($expected as $status => $class) { + $recorder = new Recorder(static fn (): Response => json_response( + ['type' => 'error', 'error' => ['type' => 'api_error', 'message' => 'test failure']], + $status, + )); + try { + send(make($recorder)); + } catch (APIStatusException $error) { + same($class, get_class($error), "exception class for $status"); + same($status, $error->status, 'status'); + assert(!str_contains($error->getMessage(), 'selected-token'), 'the credential must not appear in the error'); + + continue; + } + throw new \AssertionError("status $status was reported as success"); + } +}); + +test('an SDK retry acquires a fresh token', function (): void { + $issued = 0; + $recorder = new Recorder(static fn (RequestInterface $request, int $call): Response => 1 === $call + ? json_response(['type' => 'error', 'error' => ['type' => 'api_error', 'message' => 'try again']], 500, ['retry-after-ms' => '1']) + : json_response(message_body())); + send(make($recorder, ['maxRetries' => 1, 'tokenProvider' => static function () use (&$issued): string { + return 'token-'.(++$issued); + }])); + same(['Bearer token-1', 'Bearer token-2'], array_map(authorization_of(...), $recorder->requests), 'authorization per attempt'); +}); + +test('streaming goes through the same credential hook', function (): void { + $recorder = new Recorder(static fn (): Response => sse_response(['Hel', 'lo'])); + $text = ''; + $events = make($recorder)->messages->createStream(maxTokens: 32, messages: [['role' => 'user', 'content' => 'Hello']], model: MODEL); + foreach ($events as $event) { + if ($event instanceof RawContentBlockDeltaEvent && $event->delta instanceof TextDelta) { + $text .= $event->delta->text; + } + } + same('Hello', $text, 'streamed text'); + $headers = headers_of($recorder->requests[0]); + same('Bearer selected-token', $headers['authorization'], 'authorization'); + assert(str_contains($headers['accept'], 'text/event-stream'), 'a streaming request'); + assert(!isset($headers['anthropic-beta']), 'no OAuth beta'); +}); + +test('the default transport keeps the SDK timeout unless one is given, and does not follow redirects', function (): void { + foreach ([[null, 600.0], [30.0, 30.0]] as [$requested, $expected]) { + $http = null === $requested ? ClientFactory::defaultHttpClient() : ClientFactory::defaultHttpClient($requested); + assert($http instanceof GuzzleClient, 'the default transport is Guzzle'); + $config = (new \ReflectionProperty(GuzzleClient::class, 'config'))->getValue($http); + same($expected, $config['timeout'], 'timeout'); + same($expected, $config['connect_timeout'], 'connect timeout'); + same(false, $config['allow_redirects'], 'allow_redirects'); + same(false, $config['http_errors'], 'http_errors'); + } +}); diff --git a/samples/php/tests/EndToEndTest.php b/samples/php/tests/EndToEndTest.php new file mode 100644 index 0000000..decb128 --- /dev/null +++ b/samples/php/tests/EndToEndTest.php @@ -0,0 +1,173 @@ + ['pipe', 'r'], 1 => ['file', $null, 'w'], 2 => ['file', $null, 'w']], + $pipes, + ); + if (!is_resource($process)) { + throw new \RuntimeException('The test web server could not be started.'); + } + self::$process = $process; + register_shutdown_function(static function () use ($process, $pipes): void { + proc_terminate($process); + fclose($pipes[0]); + proc_close($process); + }); + + for ($attempt = 0; $attempt < 100; ++$attempt) { + $connection = @fsockopen('127.0.0.1', self::$port, $errno, $error, 0.2); + if (false !== $connection) { + fclose($connection); + + return; + } + usleep(100_000); + } + throw new \RuntimeException('The test web server did not become ready.'); + } +} + +/** @return array the request headers the server received */ +function echoed(Message $message): array +{ + return json_decode($message->content[0]->text, true, flags: JSON_THROW_ON_ERROR); +} + +function loopback(string $path, array $options = []): Client +{ + return ClientFactory::createClient(...[ + 'baseUrl' => 'http://127.0.0.1:'.TestServer::port().$path, + 'tokenProvider' => static fn (): string => 'e2e-token', + 'maxRetries' => 0, + ...$options, + ]); +} + +test('end to end: the server receives one bearer credential, no OAuth beta, and no ambient canary', function (): void { + $ambient = [ + 'ANTHROPIC_API_KEY' => 'ambient-key-canary', 'ANTHROPIC_AUTH_TOKEN' => 'ambient-token-canary', + 'ANTHROPIC_CUSTOM_HEADERS' => "x-api-key: header-canary\napi-key: alias-canary", + ]; + $headers = with_env($ambient, static fn (): array => echoed(send(loopback('/echo')))); + same('Bearer e2e-token', $headers['authorization'], 'authorization'); + assert(!isset($headers['x-api-key']) && !isset($headers['api-key']), 'only one credential header'); + assert(!isset($headers['anthropic-beta']), 'no OAuth beta'); + assert(!str_contains(json_encode($headers), 'canary') && !str_contains(json_encode($headers), 'provided-by-request-hook'), 'no canary or placeholder'); + same(Client::ANTHROPIC_API_VERSION, $headers['anthropic-version'], 'default API version'); + assert(str_starts_with($headers['host'], '127.0.0.1:'), 'host header'); +}); + +test('end to end: an API key travels in the selected header only', function (): void { + $headers = echoed(send(loopback('/echo', ['tokenProvider' => null, 'apiKey' => 'e2e-key', 'keyHeader' => 'x-api-key', 'apiVersion' => '2023-06-01']))); + same('e2e-key', $headers['x-api-key'], 'x-api-key'); + assert(!isset($headers['authorization']) && !isset($headers['api-key']), 'only one credential header'); + same('2023-06-01', $headers['anthropic-version'], 'explicit version'); +}); + +test('end to end: streaming over the default transport carries the same credential', function (): void { + $text = ''; + $events = loopback('/stream')->messages->createStream(maxTokens: 32, messages: [['role' => 'user', 'content' => 'Hello']], model: MODEL); + foreach ($events as $event) { + if ($event instanceof RawContentBlockDeltaEvent && $event->delta instanceof TextDelta) { + $text .= $event->delta->text; + } + } + $headers = json_decode($text, true, flags: JSON_THROW_ON_ERROR); + same('Bearer e2e-token', $headers['authorization'], 'authorization'); + assert(str_contains($headers['accept'], 'text/event-stream'), 'a streaming request'); +}); + +test('end to end: the default transport does not follow redirects; same-origin hops are re-authorized by the SDK', function (): void { + $issued = 0; + $provider = static function () use (&$issued): string { + return 'e2e-token-'.(++$issued); + }; + $headers = echoed(send(loopback('/redirect-same', ['tokenProvider' => $provider]))); + same('Bearer e2e-token-2', $headers['authorization'], 'the redirected hop carries a fresh token'); + same(2, $issued, 'tokens issued'); +}); + +test('end to end: a cross-origin redirect is refused and the second origin is never contacted', function (): void { + $issued = 0; + $provider = static function () use (&$issued): string { + return 'e2e-token-'.(++$issued); + }; + try { + send(loopback('/redirect-cross', ['tokenProvider' => $provider])); + } catch (\RuntimeException $error) { + same('Refusing to send credentials to a different origin.', $error->getMessage(), 'message'); + same(1, $issued, 'no token for the refused hop'); + + return; + } + throw new \AssertionError('the cross-origin redirect was followed'); +}); + +test('end to end: the transport timeout is enforced', function (): void { + $started = microtime(true); + try { + send(loopback('/slow', ['timeout' => 1.0])); + } catch (APIConnectionException) { + assert(microtime(true) - $started < 2.9, 'the request must end at the 1 second timeout, not when the server answers'); + + return; + } + throw new \AssertionError('a slow server did not time out'); +}); + +test('end to end: a refused connection shows the real transport error as its cause, without the credential', function (): void { + $probe = stream_socket_server('tcp://127.0.0.1:0'); + $port = (int) substr((string) strrchr((string) stream_socket_get_name($probe, false), ':'), 1); + fclose($probe); + + $client = ClientFactory::createClient(baseUrl: "http://127.0.0.1:$port", apiKey: 'e2e-key-canary-value', maxRetries: 0); + try { + send($client); + } catch (APIConnectionException $error) { + $text = Sample::describeError($error, ['e2e-key-canary-value']); + assert(str_starts_with($text, "Error: APIConnectionException: Anthropic API Connection Error\n caused by: ConnectException: cURL error 7"), "the cURL error is shown: $text"); + assert(!str_contains($text, 'canary') && !str_contains($text, 'Hint:'), 'no credential and no certificate hint'); + + return; + } + throw new \AssertionError('a refused connection did not fail'); +}); diff --git a/samples/php/tests/SampleTest.php b/samples/php/tests/SampleTest.php new file mode 100644 index 0000000..8bfab28 --- /dev/null +++ b/samples/php/tests/SampleTest.php @@ -0,0 +1,447 @@ + BASE_URL, 'CLAUDE_DEPLOYMENT_NAME' => MODEL]; +const CANONICAL_ENV = ['ANTHROPIC_BASE_URL' => BASE_URL, 'ANTHROPIC_MODEL' => MODEL]; +const NO_ENDPOINT = 'Error: Set CLAUDE_BASE_URL and CLAUDE_DEPLOYMENT_NAME, or ANTHROPIC_BASE_URL and ANTHROPIC_MODEL. The two sets are never mixed.'; +const LEGACY_NEEDS_MODEL = 'Error: CLAUDE_BASE_URL selects the CLAUDE_* settings: also set CLAUDE_DEPLOYMENT_NAME (ANTHROPIC_MODEL is not used with it).'; +const CANONICAL_NEEDS_MODEL = 'Error: ANTHROPIC_BASE_URL selects the ANTHROPIC_* settings: also set ANTHROPIC_MODEL (CLAUDE_DEPLOYMENT_NAME is not used with it).'; +const LEGACY_NEEDS_KEY = 'Error: Set CLAUDE_API_KEY (ANTHROPIC_API_KEY is not used with CLAUDE_BASE_URL).'; +const CANONICAL_NEEDS_KEY = 'Error: Set ANTHROPIC_API_KEY (CLAUDE_API_KEY is not used with ANTHROPIC_BASE_URL).'; +const CANONICAL_NEEDS_MODE = 'Error: ANTHROPIC_BASE_URL selects the ANTHROPIC_* settings and requires an explicit AUTH_MODE: set AUTH_MODE=api_key (uses ANTHROPIC_API_KEY) or AUTH_MODE=bearer (uses an Azure CLI token).'; + +/** + * @param list $arguments + * @param array $env + * + * @return array{int, string, string} exit code, stdout, stderr + */ +function run_sample(array $arguments, array $env, ?Recorder $recorder = null, ?\Closure $cli = null): array +{ + $stdout = fopen('php://memory', 'w+'); + $stderr = fopen('php://memory', 'w+'); + $code = Sample::run($arguments, $env, $stdout, $stderr, $recorder, $cli ?? static fn (): array => [0, '{"accessToken":"entra-test-token"}']); + rewind($stdout); + rewind($stderr); + + return [$code, (string) stream_get_contents($stdout), (string) stream_get_contents($stderr)]; +} + +/** @return array a response that holds a thinking block ahead of the text */ +function thinking_then_text(): array +{ + $body = message_body('OK'); + array_unshift($body['content'], ['type' => 'thinking', 'thinking' => 'not for display', 'signature' => 'sample']); + + return $body; +} + +/** @return array the configuration of the Guzzle transport behind a client */ +function transport_config(Client $client): array +{ + $options = (new \ReflectionProperty(BaseClient::class, 'options'))->getValue($client); + + return (new \ReflectionProperty(GuzzleClient::class, 'config'))->getValue($options->transporter); +} + +test('the one-shot sample prints the text and usage, never the thinking, and sends one bearer request', function (): void { + $recorder = new Recorder(static fn (): Response => json_response(thinking_then_text())); + [$code, $stdout, $stderr] = with_env([], static fn (): array => run_sample([], SAMPLE_ENV, $recorder)); + same(0, $code, "exit code (stderr: $stderr)"); + same("OK\n\n[usage] input=1 output=2\n", $stdout, 'stdout'); + same('', $stderr, 'stderr'); + same(1, count($recorder->requests), 'requests'); + $request = $recorder->requests[0]; + $headers = headers_of($request); + same('/anthropic/v1/messages', $request->getUri()->getPath(), 'path'); + same('Bearer entra-test-token', $headers['authorization'], 'authorization'); + same(Client::ANTHROPIC_API_VERSION, $headers['anthropic-version'], 'the SDK default API version'); + assert(!isset($headers['anthropic-beta']) && !isset($headers['x-api-key']) && !isset($headers['api-key']), 'bearer only, no OAuth beta'); + $body = json_decode((string) $request->getBody(), true, flags: JSON_THROW_ON_ERROR); + same(MODEL, $body['model'], 'model'); + same(1024, $body['max_tokens'], 'max_tokens'); + same(Sample::PROMPT, $body['messages'][0]['content'], 'prompt'); +}); + +test('--stream prints the text as it arrives, then usage', function (): void { + $recorder = new Recorder(static fn (): Response => sse_response(['Seattle has ', 'the Space Needle.'], 11, 13)); + [$code, $stdout, $stderr] = with_env([], static fn (): array => run_sample(['--stream'], SAMPLE_ENV, $recorder)); + same(0, $code, "exit code (stderr: $stderr)"); + same("Seattle has the Space Needle.\n\n[usage] input=11 output=13\n", $stdout, 'stdout'); + $headers = headers_of($recorder->requests[0]); + same('Bearer entra-test-token', $headers['authorization'], 'authorization'); + assert(str_contains($headers['accept'], 'text/event-stream'), 'a streaming request'); + assert(!isset($headers['anthropic-beta']), 'no OAuth beta'); +}); + +test('API key mode: Authorization by default, API_KEY_HEADER and ANTHROPIC_API_VERSION are optional overrides', function (): void { + $legacy = SAMPLE_ENV + ['AUTH_MODE' => 'api_key', 'CLAUDE_API_KEY' => 'sample-key']; + $canonical = CANONICAL_ENV + ['AUTH_MODE' => 'api_key', 'ANTHROPIC_API_KEY' => 'sample-key']; + $cases = [ + ['legacy: default header', $legacy, 'authorization', 'Bearer sample-key', Client::ANTHROPIC_API_VERSION], + ['legacy: resource key header', $legacy + ['API_KEY_HEADER' => 'x-api-key'], 'x-api-key', 'sample-key', Client::ANTHROPIC_API_VERSION], + ['legacy: explicit version', $legacy + ['ANTHROPIC_API_VERSION' => '2023-06-01'], 'authorization', 'Bearer sample-key', '2023-06-01'], + ['canonical: explicit api_key', $canonical, 'authorization', 'Bearer sample-key', Client::ANTHROPIC_API_VERSION], + ['canonical: explicit api_key, resource key header', $canonical + ['API_KEY_HEADER' => 'x-api-key'], 'x-api-key', 'sample-key', Client::ANTHROPIC_API_VERSION], + ]; + foreach ($cases as [$label, $env, $header, $expected, $version]) { + $recorder = new Recorder(); + $cliCalls = 0; + [$code, , $stderr] = with_env([], static function () use ($env, $recorder, &$cliCalls): array { + return run_sample([], $env, $recorder, static function () use (&$cliCalls): array { + ++$cliCalls; + + return [1, '']; + }); + }); + same(0, $code, "$label exit code (stderr: $stderr)"); + $headers = headers_of($recorder->requests[0]); + same($expected, $headers[$header] ?? null, "$label header"); + same($version, $headers['anthropic-version'], "$label version"); + same(0, $cliCalls, "$label must not start the Azure CLI"); + foreach (['authorization', 'x-api-key', 'api-key'] as $other) { + assert($other === $header || !isset($headers[$other]), "$label: $other must be absent"); + } + } +}); + +test('canonical profile (ANTHROPIC_BASE_URL): AUTH_MODE is explicit, and only ANTHROPIC_* values are used', function (): void { + $recorder = new Recorder(); + $seen = []; + $env = [ + 'ANTHROPIC_BASE_URL' => 'https://other.services.ai.azure.com/anthropic', 'ANTHROPIC_MODEL' => 'preferred-model', + 'AUTH_MODE' => 'bearer', 'TOKEN_SCOPE' => 'api://example/.default', 'AZURE_TENANT_ID' => 'tenant-1.example', + 'CLAUDE_BASE_URL' => 'https://legacy-canary.example/anthropic', 'CLAUDE_DEPLOYMENT_NAME' => 'legacy-model-canary', 'CLAUDE_API_KEY' => 'legacy-key-canary', + ]; + [$code, , $stderr] = with_env([], static function () use ($env, $recorder, &$seen): array { + return run_sample([], $env, $recorder, static function (array $arguments) use (&$seen): array { + $seen = $arguments; + + return [0, '{"accessToken":"entra-test-token"}']; + }); + }); + same(0, $code, "exit code (stderr: $stderr)"); + same('other.services.ai.azure.com', $recorder->requests[0]->getUri()->getHost(), 'host'); + same('preferred-model', json_decode((string) $recorder->requests[0]->getBody(), true, flags: JSON_THROW_ON_ERROR)['model'], 'model'); + same('Bearer entra-test-token', headers_of($recorder->requests[0])['authorization'], 'authorization'); + same(['account', 'get-access-token', '--scope', 'api://example/.default', '--output', 'json', '--tenant', 'tenant-1.example'], $seen, 'CLI arguments'); + assert(!str_contains(wire_of($recorder->requests[0]), 'canary'), 'no legacy value on the wire'); +}); + +test('mixed families: neither profile ever borrows a model or key from the other', function (): void { + $ambientAnthropic = ['ANTHROPIC_API_KEY' => 'ambient-anthropic-key-canary', 'ANTHROPIC_MODEL' => 'ambient-model-canary', 'ANTHROPIC_AUTH_TOKEN' => 'ambient-token-canary']; + $legacyDecoys = ['CLAUDE_BASE_URL' => 'https://legacy-canary.example/anthropic', 'CLAUDE_DEPLOYMENT_NAME' => 'legacy-model-canary', 'CLAUDE_API_KEY' => 'legacy-key-canary']; + + $success = [ + 'legacy profile with ambient ANTHROPIC_* values' => [ + SAMPLE_ENV + ['AUTH_MODE' => 'api_key', 'CLAUDE_API_KEY' => 'legacy-selected-key'] + $ambientAnthropic, + 'Bearer legacy-selected-key', MODEL, + ], + 'canonical profile with every legacy decoy present' => [ + CANONICAL_ENV + ['AUTH_MODE' => 'api_key', 'ANTHROPIC_API_KEY' => 'canonical-selected-key'] + $legacyDecoys, + 'Bearer canonical-selected-key', MODEL, + ], + 'both URLs set: the explicit canonical profile wins' => [ + ['ANTHROPIC_BASE_URL' => BASE_URL, 'ANTHROPIC_MODEL' => 'canonical-model', 'AUTH_MODE' => 'api_key', 'ANTHROPIC_API_KEY' => 'canonical-selected-key'] + $legacyDecoys, + 'Bearer canonical-selected-key', 'canonical-model', + ], + ]; + foreach ($success as $label => [$env, $authorization, $model]) { + $recorder = new Recorder(); + [$code, , $stderr] = with_env([], static fn (): array => run_sample([], $env, $recorder)); + same(0, $code, "$label: exit code (stderr: $stderr)"); + same($authorization, headers_of($recorder->requests[0])['authorization'], "$label: authorization"); + same($model, json_decode((string) $recorder->requests[0]->getBody(), true, flags: JSON_THROW_ON_ERROR)['model'], "$label: model"); + same('example.services.ai.azure.com', $recorder->requests[0]->getUri()->getHost(), "$label: host"); + assert(!str_contains(wire_of($recorder->requests[0]), 'canary'), "$label: a decoy reached the wire"); + } + + $refused = [ + 'ambient native endpoint and model never get an Azure token' => [CANONICAL_ENV + ['AZURE_TENANT_ID' => 'tenant-1.example'], CANONICAL_NEEDS_MODE], + 'canonical api_key never falls back to CLAUDE_API_KEY' => [CANONICAL_ENV + ['AUTH_MODE' => 'api_key', 'CLAUDE_API_KEY' => 'legacy-key-canary'], CANONICAL_NEEDS_KEY], + 'canonical model never falls back to CLAUDE_DEPLOYMENT_NAME' => [['ANTHROPIC_BASE_URL' => BASE_URL, 'ANTHROPIC_API_KEY' => 'k'] + $legacyDecoys, CANONICAL_NEEDS_MODEL], + 'legacy api_key never falls back to ANTHROPIC_API_KEY' => [SAMPLE_ENV + ['AUTH_MODE' => 'api_key', 'ANTHROPIC_API_KEY' => 'ambient-anthropic-key-canary'], LEGACY_NEEDS_KEY], + 'legacy model never falls back to ANTHROPIC_MODEL' => [['CLAUDE_BASE_URL' => BASE_URL] + $ambientAnthropic, LEGACY_NEEDS_MODEL], + ]; + foreach ($refused as $label => [$env, $expected]) { + $recorder = new Recorder(); + $cliCalls = 0; + [$code, $stdout, $stderr] = with_env([], static function () use ($env, $recorder, &$cliCalls): array { + return run_sample([], $env, $recorder, static function () use (&$cliCalls): array { + ++$cliCalls; + + return [0, '{"accessToken":"entra-test-token"}']; + }); + }); + same(1, $code, "$label: exit code"); + same($expected."\n", $stderr, "$label: stderr"); + same('', $stdout, "$label: stdout"); + same(0, count($recorder->requests), "$label: requests"); + same(0, $cliCalls, "$label: the Azure CLI must not start"); + } +}); + +test('missing-mode canary: the canonical profile without AUTH_MODE sends neither the native key nor an Azure token', function (): void { + $ambient = [ + 'ANTHROPIC_API_KEY' => 'ambient-anthropic-key-canary', 'AZURE_TENANT_ID' => 'tenant-1.example', 'TOKEN_SCOPE' => 'api://example/.default', + 'CLAUDE_BASE_URL' => 'https://legacy-canary.example/anthropic', 'CLAUDE_DEPLOYMENT_NAME' => 'legacy-model-canary', 'CLAUDE_API_KEY' => 'legacy-key-canary', + ]; + foreach ([CANONICAL_ENV + $ambient, CANONICAL_ENV + ['AUTH_MODE' => ''] + $ambient] as $env) { + $recorder = new Recorder(); + $cliCalls = 0; + [$code, $stdout, $stderr] = with_env($ambient, static function () use ($env, $recorder, &$cliCalls): array { + return run_sample([], $env, $recorder, static function () use (&$cliCalls): array { + ++$cliCalls; + + return [0, '{"accessToken":"entra-test-token"}']; + }); + }); + same(1, $code, 'exit code'); + same(CANONICAL_NEEDS_MODE."\n", $stderr, 'stderr'); + same('', $stdout, 'stdout'); + same(0, count($recorder->requests), 'no request, so no native key and no Azure token left the process'); + same(0, $cliCalls, 'the Azure CLI must not start'); + assert(!str_contains($stderr.$stdout, 'canary'), 'the error must not echo any ambient value'); + } +}); + +test('configuration errors exit 1 with a clear message and make no request', function (): void { + $cases = [ + 'no endpoint at all' => [[], NO_ENDPOINT], + 'a legacy model alone is not an endpoint' => [['CLAUDE_DEPLOYMENT_NAME' => MODEL], NO_ENDPOINT], + 'a canonical model alone is not an endpoint' => [['ANTHROPIC_MODEL' => MODEL], NO_ENDPOINT], + 'legacy endpoint without its model' => [['CLAUDE_BASE_URL' => BASE_URL], LEGACY_NEEDS_MODEL], + 'canonical endpoint without its model' => [['ANTHROPIC_BASE_URL' => BASE_URL], CANONICAL_NEEDS_MODEL], + 'unknown mode' => [SAMPLE_ENV + ['AUTH_MODE' => 'oauth'], 'Error: AUTH_MODE must be bearer or api_key.'], + 'legacy key mode without a key' => [SAMPLE_ENV + ['AUTH_MODE' => 'api_key'], LEGACY_NEEDS_KEY], + 'canonical endpoint without AUTH_MODE' => [CANONICAL_ENV, CANONICAL_NEEDS_MODE], + 'canonical api_key without a key' => [CANONICAL_ENV + ['AUTH_MODE' => 'api_key'], CANONICAL_NEEDS_KEY], + 'plain HTTP endpoint' => [['CLAUDE_BASE_URL' => 'http://insecure.example', 'CLAUDE_DEPLOYMENT_NAME' => MODEL], 'Error: baseUrl must be an HTTPS URL without credentials, query, or fragment.'], + 'unsafe scope' => [SAMPLE_ENV + ['TOKEN_SCOPE' => 'x&y'], 'Error: The token scope may only contain letters, digits and the characters . _ : / -'], + ]; + foreach ($cases as $label => [$env, $expected]) { + $recorder = new Recorder(); + [$code, $stdout, $stderr] = with_env([], static fn (): array => run_sample([], $env, $recorder)); + same(1, $code, "$label exit code"); + same($expected."\n", $stderr, "$label stderr"); + same('', $stdout, "$label stdout"); + same(0, count($recorder->requests), "$label requests"); + } +}); + +test('AZURE_TOKEN_CREDENTIALS: AzureCliCredential is accepted, any other explicit choice is refused, and key mode ignores it', function (): void { + foreach ([null, 'AzureCliCredential'] as $selector) { + $recorder = new Recorder(); + $cliCalls = 0; + $env = SAMPLE_ENV + (null === $selector ? [] : ['AZURE_TOKEN_CREDENTIALS' => $selector]); + [$code, , $stderr] = with_env([], static function () use ($env, $recorder, &$cliCalls): array { + return run_sample([], $env, $recorder, static function () use (&$cliCalls): array { + ++$cliCalls; + + return [0, '{"accessToken":"entra-test-token"}']; + }); + }); + same(0, $code, 'accepted selector '.var_export($selector, true)." (stderr: $stderr)"); + same(1, $cliCalls, 'the Azure CLI supplies the token'); + } + + $message = static fn (string $shown): string => "Error: AZURE_TOKEN_CREDENTIALS=$shown is not supported: the Azure CLI (AzureCliCredential) is this sample's only built-in token source. Unset it, or pass your own token provider to ClientFactory for other credentials.\n"; + $refused = [ + 'ManagedIdentityCredential' => 'ManagedIdentityCredential', 'AzureDeveloperCliCredential' => 'AzureDeveloperCliCredential', + 'DefaultAzureCredential' => 'DefaultAzureCredential', 'WorkloadIdentityCredential' => 'WorkloadIdentityCredential', + 'azureclicredential' => 'azureclicredential', "Azure\nCliCredential" => '(unprintable or too long)', + ]; + foreach ($refused as $selector => $shown) { + $recorder = new Recorder(); + $cliCalls = 0; + $env = SAMPLE_ENV + ['AZURE_TOKEN_CREDENTIALS' => (string) $selector]; + [$code, $stdout, $stderr] = with_env([], static function () use ($env, $recorder, &$cliCalls): array { + return run_sample([], $env, $recorder, static function () use (&$cliCalls): array { + ++$cliCalls; + + return [0, '{"accessToken":"entra-test-token"}']; + }); + }); + same(1, $code, "$shown: exit code"); + same($message($shown), $stderr, "$shown: stderr"); + same('', $stdout, "$shown: stdout"); + same(0, $cliCalls, "$shown: the Azure CLI must not start"); + same(0, count($recorder->requests), "$shown: requests"); + } + + $recorder = new Recorder(); + [$code, , $stderr] = with_env([], static fn (): array => run_sample([], SAMPLE_ENV + ['AUTH_MODE' => 'api_key', 'CLAUDE_API_KEY' => 'sample-key', 'AZURE_TOKEN_CREDENTIALS' => 'ManagedIdentityCredential'], $recorder)); + same(0, $code, "key mode ignores the selector (stderr: $stderr)"); +}); + +test('the sample sets its own 120 second timeout; the factory itself keeps the SDK default', function (): void { + same(120.0, Sample::REQUEST_TIMEOUT_SECONDS, 'policy constant'); + [$client] = with_env([], static fn (): array => Sample::configure(SAMPLE_ENV, null, static fn (): array => [0, '{"accessToken":"entra-test-token"}'])); + same(120.0, transport_config($client)['timeout'], 'timeout of the sample client'); + same(false, transport_config($client)['allow_redirects'], 'redirects are not followed'); + same(600.0, transport_config(ClientFactory::createClient(baseUrl: BASE_URL, apiKey: 'sample-key'))['timeout'], 'timeout of a factory client'); +}); + +test('a response without text (thinking only) is an error, not a silent success', function (): void { + $thinkingOnly = message_body(); + $thinkingOnly['content'] = [['type' => 'thinking', 'thinking' => 'not for display', 'signature' => 'sample']]; + $recorder = new Recorder(static fn (): Response => json_response($thinkingOnly)); + [$code, $stdout, $stderr] = with_env([], static fn (): array => run_sample([], SAMPLE_ENV, $recorder)); + same(1, $code, 'exit code'); + same('', $stdout, 'stdout'); + same("Error: No text response (stop_reason=end_turn). Increase max_tokens if the response exhausted its budget.\n", $stderr, 'stderr'); + + $events = [ + ['message_start', ['type' => 'message_start', 'message' => ['id' => 'm', 'type' => 'message', 'role' => 'assistant', 'model' => MODEL, 'content' => [], 'stop_reason' => null, 'stop_sequence' => null, 'usage' => ['input_tokens' => 1, 'output_tokens' => 1]]]], + ['content_block_start', ['type' => 'content_block_start', 'index' => 0, 'content_block' => ['type' => 'thinking', 'thinking' => '', 'signature' => '']]], + ['content_block_delta', ['type' => 'content_block_delta', 'index' => 0, 'delta' => ['type' => 'thinking_delta', 'thinking' => 'hidden']]], + ['content_block_stop', ['type' => 'content_block_stop', 'index' => 0]], + ['message_delta', ['type' => 'message_delta', 'delta' => ['stop_reason' => 'max_tokens', 'stop_sequence' => null], 'usage' => ['output_tokens' => 9]]], + ['message_stop', ['type' => 'message_stop']], + ]; + $body = ''; + foreach ($events as [$type, $payload]) { + $body .= "event: $type\ndata: ".json_encode($payload)."\n\n"; + } + $recorder = new Recorder(static fn (): Response => new Response(200, ['Content-Type' => 'text/event-stream'], $body)); + [$code, $stdout, $stderr] = with_env([], static fn (): array => run_sample(['--stream'], SAMPLE_ENV, $recorder)); + same(1, $code, 'stream exit code'); + same('', $stdout, 'stream stdout'); + same("Error: No text response (stop_reason=max_tokens). Increase max_tokens if the response exhausted its budget.\n", $stderr, 'stream stderr'); +}); + +test('real API and credential failures exit 1 and never print the token', function (): void { + $recorder = new Recorder(static fn (): Response => json_response(['type' => 'error', 'error' => ['type' => 'authentication_error', 'message' => 'invalid credential']], 401)); + [$code, $stdout, $stderr] = with_env([], static fn (): array => run_sample([], SAMPLE_ENV, $recorder)); + same(1, $code, 'exit code'); + same('', $stdout, 'stdout'); + assert(str_starts_with($stderr, 'Error: AuthenticationException: '), 'the SDK exception is named'); + assert(str_contains($stderr, '401') && str_contains($stderr, 'invalid credential'), 'the service error is reported'); + assert(!str_contains($stderr, 'entra-test-token'), 'the token must not be printed'); + + $recorder = new Recorder(static fn (): Response => json_response(['type' => 'error', 'error' => ['type' => 'api_error', 'message' => 'overloaded']], 500)); + [$code, , $stderr] = with_env([], static fn (): array => run_sample(['--stream'], SAMPLE_ENV, $recorder)); + same(1, $code, 'stream exit code'); + assert(str_starts_with($stderr, 'Error: InternalServerException: '), 'the streaming error is reported too'); + + $recorder = new Recorder(); + [$code, $stdout, $stderr] = with_env([], static fn (): array => run_sample([], SAMPLE_ENV, $recorder, static fn (): array => [1, '{"accessToken":"never-printed-token"}'])); + same(1, $code, 'CLI failure exit code'); + same('', $stdout, 'CLI failure stdout'); + same("Error: Azure CLI exited with code 1 while requesting a token for scope https://ai.azure.com/.default. Run \"az login\" and retry, or supply your own token provider.\n", $stderr, 'CLI failure stderr'); + same(0, count($recorder->requests), 'no request without a token'); +}); + +test('a connection failure shows its cause, so a certificate problem is visible and comes with a hint', function (): void { + $request = new Request('POST', BASE_URL.'/v1/messages'); + $curl = 'cURL error 60: SSL certificate problem: unable to get local issuer certificate (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) for '.BASE_URL.'/v1/messages'; + $lines = explode("\n", rtrim(Sample::describeError(new APIConnectionException($request, new ConnectException($curl, $request))), "\n")); + same(3, count($lines), 'the error, its cause and the hint'); + same('Error: APIConnectionException: Anthropic API Connection Error', $lines[0], 'top-level line'); + same(" caused by: ConnectException: $curl", $lines[1], 'the transport error'); + assert(str_starts_with($lines[2], 'Hint: ') && str_contains($lines[2], 'curl.cainfo') && str_contains($lines[2], 'openssl.cafile') && str_contains($lines[2], 'README'), 'the hint names both settings and the README'); + assert(!str_contains(strtolower($lines[2]), 'disable'), 'the hint never suggests switching verification off'); + + $refused = new ConnectException('cURL error 7: Failed to connect to localhost port 8 after 2 ms: Could not connect to server (see https://curl.haxx.se/libcurl/c/libcurl-errors.html)', $request); + $text = Sample::describeError(new APIConnectionException($request, $refused)); + assert(str_contains($text, ' caused by: ConnectException: cURL error 7: Failed to connect to localhost port 8 after 2 ms'), 'other causes are shown unchanged'); + assert(!str_contains($text, 'Hint:') && !str_contains($text, '[redacted]'), 'no hint and no redaction for an ordinary failure'); + assert(str_contains(Sample::describeError(new \RuntimeException('failed', 0, new ConnectException('cURL error 77: error setting certificate file: nowhere.pem', $request))), 'Hint: '), 'an unusable CA file gets the hint too'); +}); + +test('error output never contains credentials: exact values, headers, bearer tokens, JWTs, URL userinfo and queries are redacted', function (): void { + $jwt = 'eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJzYW1wbGUifQ.c2lnbmF0dXJlLXNhbXBsZQ'; + $cases = [ + 'Authorization: Bearer opaque-bearer-canary' => ['opaque-bearer-canary'], + 'sent x-api-key: header-key-canary' => ['header-key-canary'], + 'sent api-key=alias-key-canary' => ['alias-key-canary'], + 'Proxy-Authorization: Basic cHJveHktY2FuYXJ5' => ['cHJveHktY2FuYXJ5'], + 'Cookie: session=cookie-canary; theme=dark' => ['cookie-canary'], + 'a loose Bearer loose-bearer-canary here' => ['loose-bearer-canary'], + "token $jwt in the middle" => [$jwt, 'eyJzdWIi'], + 'key sk-ant-api03-key-canary-123456 rejected' => ['key-canary-123456'], + 'https://user-canary:pass-canary@example.test/a?sig=query-canary#frag-canary' => ['user-canary', 'pass-canary', 'query-canary', 'frag-canary'], + 'the configured exact-secret-canary and the issued issued-token-canary' => ['exact-secret-canary', 'issued-token-canary'], + ]; + $request = new Request('POST', BASE_URL.'/v1/messages'); + foreach ($cases as $message => $forbidden) { + $text = Sample::describeError(new APIConnectionException($request, new ConnectException($message, $request)), ['exact-secret-canary', 'issued-token-canary']); + foreach ($forbidden as $value) { + assert(!str_contains($text, $value), "'$value' leaked from: $message"); + } + assert(str_contains($text, '[redacted]'), "nothing was redacted in: $message"); + } + same("Error: Authorization: [redacted]\n", Sample::describeError(new \RuntimeException('Authorization: Bearer top-level-canary')), 'the top-level message is redacted too'); + same("Error: the key is k\n", Sample::describeError(new \RuntimeException('the key is k'), ['k']), 'values shorter than eight characters are not replaced everywhere'); +}); + +test('error output is bounded: one line per message, a thousand characters at most, five causes at most, no repeats', function (): void { + $error = null; + for ($depth = 8; $depth >= 1; --$depth) { + $error = new \LogicException("cause $depth", 0, $error); + } + $lines = explode("\n", rtrim(Sample::describeError(new \LogicException('top', 0, $error)), "\n")); + same(7, count($lines), 'the error, five causes and the omission note'); + same('Error: LogicException: top', $lines[0], 'top-level line'); + same(' caused by: LogicException: cause 5', $lines[5], 'the fifth cause is the last one shown'); + same(' caused by: (further causes are not shown)', $lines[6], 'omission note'); + + same("Error: LogicException: first Error: injected third\n", Sample::describeError(new \LogicException("first\nError: injected\r\nthird")), 'a message cannot add lines'); + $long = Sample::describeError(new \LogicException(str_repeat('x', 5000))); + same(strlen('Error: ') + 1000 + strlen("...\n"), strlen($long), 'a long message is cut to a thousand characters'); + same("Error: LogicException: same\n", Sample::describeError(new \LogicException('same', 0, new \LogicException('same'))), 'a cause that repeats its parent is not shown again'); +}); + +test('a failed connection exits 1, shows its cause without any credential, and the SDK still retries it', function (): void { + $request = new Request('POST', BASE_URL.'/v1/messages'); + $recorder = new Recorder(static fn (): Response => throw new ConnectException('cURL error 60: SSL certificate problem: unable to get local issuer certificate for '.BASE_URL.'/v1/messages (token entra-test-token)', $request)); + [$code, $stdout, $stderr] = with_env([], static fn (): array => run_sample([], SAMPLE_ENV, $recorder)); + same(1, $code, 'exit code'); + same('', $stdout, 'stdout'); + assert(str_starts_with($stderr, "Error: APIConnectionException: Anthropic API Connection Error\n caused by: ConnectException: cURL error 60: SSL certificate problem"), "the cause is shown: $stderr"); + assert(str_contains($stderr, '(token [redacted])') && !str_contains($stderr, 'entra-test-token'), 'the token the provider issued is removed'); + assert(str_contains($stderr, "\nHint: "), 'a certificate failure carries the hint'); + same(3, count($recorder->requests), 'the first attempt and the SDK default of two retries'); + + $recorder = new Recorder(static fn (): Response => throw new ConnectException('cURL error 7: refused, key=sample-key-canary-value', $request)); + $env = ['AUTH_MODE' => 'api_key', 'CLAUDE_API_KEY' => 'sample-key-canary-value'] + SAMPLE_ENV; + [$code, , $stderr] = with_env([], static fn (): array => run_sample(['--stream'], $env, $recorder)); + same(1, $code, 'stream exit code'); + assert(str_contains($stderr, 'caused by: ConnectException: cURL error 7: refused, key=[redacted]') && !str_contains($stderr, 'canary'), 'the configured key is removed'); + assert(!str_contains($stderr, 'Hint:'), 'no certificate hint for a refused connection'); +}); + +test('unknown arguments are a usage error; --help prints usage', function (): void { + [$code, , $stderr] = run_sample(['--bogus'], SAMPLE_ENV); + same(2, $code, 'exit code'); + same("Unknown argument: --bogus\nUsage: php main.php [--stream]\n", $stderr, 'stderr'); + [$code, $stdout] = run_sample(['--help'], []); + same(0, $code, 'help exit code'); + same("Usage: php main.php [--stream]\n", $stdout, 'help output'); +}); + +test('ambient ANTHROPIC_* credentials in the process environment never reach the sample request', function (): void { + $ambient = [ + 'ANTHROPIC_API_KEY' => 'ambient-key-canary', 'ANTHROPIC_AUTH_TOKEN' => 'ambient-token-canary', + 'ANTHROPIC_PROFILE' => 'nonexistent-profile-canary', 'ANTHROPIC_CUSTOM_HEADERS' => "x-api-key: header-canary\napi-key: alias-canary", + ]; + foreach ([[], ['AUTH_MODE' => 'api_key', 'CLAUDE_API_KEY' => 'sample-key']] as $mode) { + $recorder = new Recorder(); + [$code, , $stderr] = with_env($ambient, static fn (): array => run_sample([], $mode + SAMPLE_ENV, $recorder)); + same(0, $code, "exit code (stderr: $stderr)"); + assert(!str_contains(wire_of($recorder->requests[0]), 'canary'), 'a canary reached the wire'); + } +}); diff --git a/samples/php/tests/fixtures/fake-az/az b/samples/php/tests/fixtures/fake-az/az new file mode 100644 index 0000000..3ca0251 --- /dev/null +++ b/samples/php/tests/fixtures/fake-az/az @@ -0,0 +1,9 @@ +#!/bin/sh +# Test double for the Azure CLI. It contacts nothing and prints synthetic data; FAKE_AZ_MODE selects the behavior. +case "${FAKE_AZ_MODE:-ok}" in + fail) exit 3 ;; + slow) sleep 7; printf '%s\n' '{"accessToken":"too-late-token"}' ;; + empty) printf '%s\n' '{"accessToken":""}' ;; + args) printf '{"accessToken":"%s"}\n' "$*" ;; + *) printf '%s\n' '{"accessToken":"fixture-cli-token","tokenType":"Bearer"}' ;; +esac diff --git a/samples/php/tests/fixtures/fake-az/az.cmd b/samples/php/tests/fixtures/fake-az/az.cmd new file mode 100644 index 0000000..24017f0 --- /dev/null +++ b/samples/php/tests/fixtures/fake-az/az.cmd @@ -0,0 +1,22 @@ +@echo off +rem Test double for the Azure CLI. It contacts nothing and prints synthetic data; FAKE_AZ_MODE selects the behavior. +if "%FAKE_AZ_MODE%"=="fail" exit /b 3 +if "%FAKE_AZ_MODE%"=="slow" goto slow +if "%FAKE_AZ_MODE%"=="empty" goto empty +if "%FAKE_AZ_MODE%"=="args" goto args +echo {"accessToken":"fixture-cli-token","tokenType":"Bearer"} +exit /b 0 +:slow +rem ping waits about a second per count; unlike the timeout command it needs no console. +ping -n 8 127.0.0.1 >nul +echo {"accessToken":"too-late-token"} +exit /b 0 +:empty +echo {"accessToken":""} +exit /b 0 +:args +rem PHP quotes every argument it hands to cmd.exe; drop the quotes so the output stays valid JSON. +set ARGS=%* +set ARGS=%ARGS:"=% +echo {"accessToken":"%ARGS%"} +exit /b 0 diff --git a/samples/php/tests/run.php b/samples/php/tests/run.php new file mode 100644 index 0000000..36c1085 --- /dev/null +++ b/samples/php/tests/run.php @@ -0,0 +1,17 @@ + $value) { + $received[strtolower($name)] = $value; +} +$text = json_encode($received, JSON_THROW_ON_ERROR); + +if (str_starts_with($path, '/stream/')) { + header('Content-Type: text/event-stream'); + $events = [ + ['message_start', ['type' => 'message_start', 'message' => ['id' => 'msg_e2e', 'type' => 'message', 'role' => 'assistant', 'model' => 'm', 'content' => [], 'stop_reason' => null, 'stop_sequence' => null, 'usage' => ['input_tokens' => 3, 'output_tokens' => 1]]]], + ['content_block_start', ['type' => 'content_block_start', 'index' => 0, 'content_block' => ['type' => 'text', 'text' => '']]], + ['content_block_delta', ['type' => 'content_block_delta', 'index' => 0, 'delta' => ['type' => 'text_delta', 'text' => $text]]], + ['content_block_stop', ['type' => 'content_block_stop', 'index' => 0]], + ['message_delta', ['type' => 'message_delta', 'delta' => ['stop_reason' => 'end_turn', 'stop_sequence' => null], 'usage' => ['output_tokens' => 4]]], + ['message_stop', ['type' => 'message_stop']], + ]; + foreach ($events as [$type, $payload]) { + echo "event: $type\ndata: ".json_encode($payload, JSON_THROW_ON_ERROR)."\n\n"; + } + + return; +} + +header('Content-Type: application/json'); +echo json_encode([ + 'id' => 'msg_e2e', 'type' => 'message', 'role' => 'assistant', 'model' => 'm', + 'content' => [['type' => 'text', 'text' => $text]], + 'stop_reason' => 'end_turn', 'stop_sequence' => null, + 'usage' => ['input_tokens' => 1, 'output_tokens' => 2], +], JSON_THROW_ON_ERROR); diff --git a/samples/php/tests/support.php b/samples/php/tests/support.php new file mode 100644 index 0000000..72e918c --- /dev/null +++ b/samples/php/tests/support.php @@ -0,0 +1,178 @@ + */ + private static array $tests = []; + + public static function add(string $name, \Closure $body): void + { + self::$tests[] = [$name, $body]; + } + + public static function run(): int + { + $failed = 0; + foreach (self::$tests as [$name, $body]) { + try { + $body(); + echo "PASS $name\n"; + } catch (\Throwable $error) { + ++$failed; + echo "FAIL $name\n ".get_class($error).': '.$error->getMessage()."\n"; + } + } + printf("\n%d tests, %d failed\n", count(self::$tests), $failed); + + return 0 === $failed && [] !== self::$tests ? 0 : 1; + } +} + +function test(string $name, \Closure $body): void +{ + Suite::add($name, $body); +} + +function same(mixed $expected, mixed $actual, string $what): void +{ + if ($expected !== $actual) { + throw new \AssertionError(sprintf('%s: expected %s, got %s', $what, var_export($expected, true), var_export($actual, true))); + } +} + +/** Records every request and answers through $responder(request, call number). */ +final class Recorder implements ClientInterface +{ + /** @var list */ + public array $requests = []; + + /** @var \Closure(RequestInterface, int): ResponseInterface */ + private \Closure $responder; + + public function __construct(?\Closure $responder = null) + { + $this->responder = $responder ?? static fn (): ResponseInterface => json_response(message_body()); + } + + public function sendRequest(RequestInterface $request): ResponseInterface + { + $this->requests[] = $request; + + return ($this->responder)($request, count($this->requests)); + } +} + +/** @return array */ +function message_body(string $text = 'OK'): array +{ + return [ + 'id' => 'msg_test', 'type' => 'message', 'role' => 'assistant', 'model' => MODEL, + 'content' => [['type' => 'text', 'text' => $text]], + 'stop_reason' => 'end_turn', 'stop_sequence' => null, + 'usage' => ['input_tokens' => 1, 'output_tokens' => 2], + ]; +} + +/** + * @param array $body + * @param array $headers + */ +function json_response(array $body, int $status = 200, array $headers = []): Response +{ + return new Response($status, ['Content-Type' => 'application/json', ...$headers], json_encode($body, JSON_THROW_ON_ERROR)); +} + +/** @param list $chunks */ +function sse_response(array $chunks, int $input = 5, int $output = 7): Response +{ + $events = [ + ['message_start', ['type' => 'message_start', 'message' => [ + 'id' => 'msg_stream', 'type' => 'message', 'role' => 'assistant', 'model' => MODEL, 'content' => [], + 'stop_reason' => null, 'stop_sequence' => null, 'usage' => ['input_tokens' => $input, 'output_tokens' => 1], + ]]], + ['content_block_start', ['type' => 'content_block_start', 'index' => 0, 'content_block' => ['type' => 'text', 'text' => '']]], + ]; + foreach ($chunks as $chunk) { + $events[] = ['content_block_delta', ['type' => 'content_block_delta', 'index' => 0, 'delta' => ['type' => 'text_delta', 'text' => $chunk]]]; + } + $events[] = ['content_block_stop', ['type' => 'content_block_stop', 'index' => 0]]; + $events[] = ['message_delta', ['type' => 'message_delta', 'delta' => ['stop_reason' => 'end_turn', 'stop_sequence' => null], 'usage' => ['output_tokens' => $output]]]; + $events[] = ['message_stop', ['type' => 'message_stop']]; + + $body = ''; + foreach ($events as [$type, $payload]) { + $body .= "event: $type\ndata: ".json_encode($payload, JSON_THROW_ON_ERROR)."\n\n"; + } + + return new Response(200, ['Content-Type' => 'text/event-stream'], $body); +} + +/** @return array lower-cased header name => joined values */ +function headers_of(RequestInterface $request): array +{ + $headers = []; + foreach ($request->getHeaders() as $name => $values) { + $headers[strtolower((string) $name)] = implode(', ', $values); + } + + return $headers; +} + +/** Everything a request shows on the wire, for canary searches. */ +function wire_of(RequestInterface $request): string +{ + return json_encode([headers_of($request), (string) $request->getUri(), (string) $request->getBody()], JSON_THROW_ON_ERROR); +} + +/** + * Runs $body with exactly the ANTHROPIC_*, CLAUDE_*, AZURE_*, AUTH_MODE, API_KEY_HEADER, TOKEN_SCOPE and FAKE_AZ_* + * variables in $set, and restores the previous values afterwards. The SDK reads both $_ENV and getenv(). + * + * @param array $set + */ +function with_env(array $set, \Closure $body): mixed +{ + $managed = '/^(?:ANTHROPIC_|CLAUDE_|AZURE_|FAKE_AZ_|AUTH_MODE$|API_KEY_HEADER$|TOKEN_SCOPE$)/'; + $names = array_unique([...array_keys($set), ...array_keys(getenv()), ...array_keys($_ENV)]); + $names = array_values(array_filter(array_map('strval', $names), static fn (string $name): bool => 1 === preg_match($managed, $name) || array_key_exists($name, $set))); + + $saved = []; + foreach ($names as $name) { + $saved[$name] = [getenv($name), array_key_exists($name, $_ENV), $_ENV[$name] ?? null]; + putenv($name); + unset($_ENV[$name]); + } + $set += ['ANTHROPIC_CONFIG_DIR' => __DIR__.DIRECTORY_SEPARATOR.'no-profile-here']; + foreach ($set as $name => $value) { + putenv("$name=$value"); + $_ENV[$name] = $value; + } + try { + return $body(); + } finally { + foreach (array_unique([...array_keys($set), ...$names]) as $name) { + putenv((string) $name); + unset($_ENV[$name]); + } + foreach ($saved as $name => [$value, $hadEnv, $envValue]) { + if (false !== $value) { + putenv("$name=$value"); + } + if ($hadEnv) { + $_ENV[$name] = $envValue; + } + } + } +} diff --git a/samples/ruby/Gemfile b/samples/ruby/Gemfile new file mode 100644 index 0000000..957e392 --- /dev/null +++ b/samples/ruby/Gemfile @@ -0,0 +1,12 @@ +# frozen_string_literal: true + +source "https://rubygems.org" + +# No `ruby` directive on purpose: the anthropic gem already requires Ruby 3.2 or later, and a directive would write the +# exact Ruby patch release into Gemfile.lock (a RUBY VERSION line) and rewrite it on every other Ruby. +gem "anthropic", "~> 2.3.0" + +group :test do + # 5.x: Minitest 6 needs the prism gem, which compiles a native extension on Rubies that do not bundle it. + gem "minitest", "~> 5.25" +end diff --git a/samples/ruby/Gemfile.lock b/samples/ruby/Gemfile.lock new file mode 100644 index 0000000..19b76c1 --- /dev/null +++ b/samples/ruby/Gemfile.lock @@ -0,0 +1,23 @@ +GEM + remote: https://rubygems.org/ + specs: + anthropic (2.3.0) + base64 (~> 0.1) + connection_pool (>= 2, < 4) + opentelemetry-api (>= 1.2.4, < 2) + standardwebhooks (~> 1.0) + base64 (0.3.0) + connection_pool (3.0.2) + logger (1.7.0) + minitest (5.27.0) + opentelemetry-api (1.8.0) + logger + standardwebhooks (1.0.1) + +PLATFORMS + ruby + x64-mingw-ucrt + +DEPENDENCIES + anthropic (~> 2.3.0) + minitest (~> 5.25) diff --git a/samples/ruby/README.md b/samples/ruby/README.md new file mode 100644 index 0000000..98f6bd1 --- /dev/null +++ b/samples/ruby/README.md @@ -0,0 +1,141 @@ +# Claude on Microsoft Foundry: Ruby + +Calls a Claude deployment through the **standard** Anthropic Ruby SDK client (`Anthropic::Client`, the `anthropic` gem `~> 2.3.0`). It has no Foundry-specific client or subclass: the endpoint, the model (deployment) name and the credential are plain configuration. + +| File | Purpose | +|---|---| +| `main.rb` | Entry point: one Messages call, printed whole or streamed (`--stream`). | +| `lib/claude_sample/sample.rb` | Reads the environment, builds the client, prints the text and usage. | +| `lib/claude_sample/client_factory.rb` | The generic helper. `ClaudeSample::ClientFactory.create_client` returns the standard client with exactly one explicit credential. It reads no environment variables and imports no cloud-provider code. | +| `lib/claude_sample/cli_token_provider.rb` | Token provider for local development: a command-line fallback that runs `az account get-access-token`. | +| `Gemfile`, `Gemfile.lock` | `anthropic ~> 2.3.0`, plus Minitest 5.x in the `test` group. The lock is portable (see Install). | +| `test/` | Offline Minitest tests: no cloud, no credentials. | + +## Prerequisites + +- Ruby 3.2 or later (the SDK's floor) and Bundler. +- For `AUTH_MODE=bearer` (the legacy profile's default), the [Azure CLI](https://learn.microsoft.com/cli/azure/) signed in to the tenant that owns the deployment (`az login`). +- A deployment of a Claude model in Microsoft Foundry, and its endpoint URL. + +## Install + +```sh +cd samples/ruby +bundle install +``` + +The Gemfile has one runtime dependency, `anthropic`: the SDK uses Ruby's bundled `net/http`, so no other HTTP library is needed. Minitest 5.x sits in the `test` group; it is 5.x because Minitest 6 depends on the `prism` gem, a native extension that needs a compiler on Rubies that do not ship it. + +`Gemfile.lock` is checked in and meant to work unchanged on every supported Ruby (3.2 to 4.0) and platform. It was generated on the oldest supported Ruby, so its versions install on all of them; every gem in it is pure Ruby, so it lists the `ruby` platform plus `x64-mingw-ucrt` (RubyInstaller on Windows), and it has no `RUBY VERSION` or `BUNDLED WITH` section, so a different Ruby patch release does not rewrite it and Bundler does not download an older Bundler to match it. `bundle install` leaves it as it is; `BUNDLE_FROZEN=true bundle install` fails on any drift. + +## Configure + +The endpoint, model and key come from one of two profiles that **never borrow from each other**, so a secret can never be paired with the endpoint of the other family: + +| | Canonical profile | Legacy profile | +|---|---|---| +| Selected when | `ANTHROPIC_BASE_URL` is set (it wins when both URLs are set) | only `CLAUDE_BASE_URL` is set | +| Endpoint | `ANTHROPIC_BASE_URL` | `CLAUDE_BASE_URL` | +| Model or deployment | `ANTHROPIC_MODEL` (required) | `CLAUDE_DEPLOYMENT_NAME` (required) | +| Key for `AUTH_MODE=api_key` | `ANTHROPIC_API_KEY` only | `CLAUDE_API_KEY` only | +| `AUTH_MODE` when unset | **error**: set `AUTH_MODE=api_key` or `AUTH_MODE=bearer` explicitly | `bearer` | + +A missing model, key or (canonical profile) `AUTH_MODE` is an error that names what it needs; the sample never falls back to the other profile's value. Because the canonical profile has no default mode, an ambient native `ANTHROPIC_BASE_URL` and `ANTHROPIC_MODEL` can neither silently receive an Azure token nor silently pick up a native key: you choose `api_key` (uses `ANTHROPIC_API_KEY`) or `bearer` (uses an Azure CLI token) on purpose. An ambient `ANTHROPIC_API_KEY` is ignored when `CLAUDE_BASE_URL` selects the legacy profile. + +These settings are shared by both profiles: + +| Variable | Default | Purpose | +|---|---|---| +| `AUTH_MODE` | legacy: `bearer`; canonical: none, must be set | `bearer`: a Microsoft Entra ID token from the Azure CLI. `api_key`: a static key. | +| `API_KEY_HEADER` | `Authorization` | Header that carries the key. `Authorization` sends `Bearer `, the current SDK's native behavior; any other name (for example `x-api-key`) sends the raw key. | +| `ANTHROPIC_API_VERSION` | unset | Unset keeps the SDK's default `anthropic-version`. Set it to override (for example `2023-06-01`). | +| `TOKEN_SCOPE` | `https://ai.azure.com/.default` | Scope requested from the Azure CLI. | +| `AZURE_TENANT_ID` | unset | Adds `--tenant` to the Azure CLI call. | +| `AZURE_TOKEN_CREDENTIALS` | unset | Credential selector shared with the other language samples. Only `AzureCliCredential` (also the default) is implemented here: any other value (`ManagedIdentityCredential`, `AzureDeveloperCliCredential`, `DefaultAzureCredential`, a typo) is rejected with an error instead of being ignored or answered with the CLI. Ignored in `api_key` mode. For managed identity, workload identity, `azd` or any other credential, pass your own token provider. | + +The endpoint must be HTTPS; plain HTTP is accepted for loopback hosts. To load the values that `azd env get-values > .env.local` wrote at the repository root (legacy `CLAUDE_*` names): + +```powershell +# PowerShell, from samples/ruby +Get-Content ..\..\.env.local | ForEach-Object { if ($_ -match '^\s*([A-Za-z_][A-Za-z0-9_]*)=(.*)$') { Set-Item "env:$($Matches[1])" $Matches[2].Trim('"') } } +``` + +```sh +# bash +set -a; . ../../.env.local; set +a +``` + +## Run + +```sh +bundle exec ruby main.rb # one Messages call +bundle exec ruby main.rb --stream # the same request, streamed as it is generated +``` + +`ruby main.rb` works too: `main.rb` loads `bundler/setup` itself. Both modes print only the text, then the token usage (the sample waits up to 120 seconds per request): + +```text + + +[usage] input= output= +``` + +Thinking blocks are not printed. A response without any text fails with a message and a non-zero exit status instead of reporting success; so do API errors, credential failures and bad configuration (exit status 1; an unknown argument exits with 2). + +## Authentication + +**`AUTH_MODE=bearer` is a local-development fallback** (the legacy profile's default; the canonical profile needs it set explicitly). The sample runs `az account get-access-token --scope --output json` (adding `--tenant ` when set) for every token request and sends the returned `accessToken` as `Authorization: Bearer`. The Azure CLI owns token caching and renewal; the sample keeps no cache. The price is one CLI process per HTTP attempt, which takes seconds on a typical machine. + +- The command is a fixed argument list, never shell text. Every argument must match `[A-Za-z0-9._:/-]+`, so quotes, spaces and shell or `cmd.exe` metacharacters are rejected before anything starts. +- On Windows the CLI is usually a batch file (`az.cmd` or `az.bat`). The sample finds it on `PATH` (honoring `PATHEXT`, absolute entries only) and starts it as `cmd.exe /d /c az.cmd ...` from its own directory with that fixed argument list. +- Each CLI process has a finite allowance of 60 seconds (a cold start under load can exceed the 10 seconds some identity libraries allow). When it runs out, the process, and on Windows its children, is stopped and the sample fails with a timeout error. It never falls back to another credential. +- A non-zero exit status, output that is not a JSON object, or a missing or empty `accessToken` raises a clear error. The error never contains the CLI's output, and the token is never printed, logged or written to a file. + +**For production, pass your own token provider.** `create_client` accepts any callable that returns the current token as a string, for example one backed by your identity library (managed identity, workload identity, and so on). No officially supported Microsoft Azure Identity library for Ruby was identified when this sample was written, and the sample neither depends on nor endorses a third-party one. Because the provider runs on every HTTP attempt, it should be cheap or cache internally. + +**`AUTH_MODE=api_key`** sends a static key in the header named by `API_KEY_HEADER`. Use it for development and testing. + +## What the helper guarantees + +`ClientFactory.create_client` returns a plain `Anthropic::Client` and uses only public SDK features (the `middleware:` option): + +- **Exactly one credential.** The SDK is given a public, non-secret placeholder token, solely to stop it from discovering `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_PROFILE`, federation variables or profiles on disk. A middleware that runs on every HTTP attempt (retries and redirect hops included) removes `authorization`, `x-api-key` and `api-key`, whatever put them there (including `ANTHROPIC_CUSTOM_HEADERS` and per-request `extra_headers`), and applies the selected credential. The placeholder never reaches the wire. All other headers, including `anthropic-beta` values you pass, are preserved. +- **No OAuth beta.** A plain bearer token is sent without `anthropic-beta: oauth-2025-04-20`. +- **One origin.** The base URL must be HTTPS (loopback may use HTTP) and may not carry credentials, a query or a fragment. A redirect to a different scheme, host or port is refused before any credential is produced. +- **SDK defaults kept.** The factory adds no retry, refresh or cache of its own, and sets no retry count or timeout unless you pass `max_retries:` or `timeout:`. The SDK's retries (2) and its 600 second request timeout apply. `anthropic-version` is the SDK's default unless you pass `api_version:`. +- **The sample's own policy.** `Sample` passes `timeout: 120.0` (`ClaudeSample::Sample::REQUEST_TIMEOUT_SECONDS`) so a stuck request ends after two minutes. That is an application choice made visibly in `lib/claude_sample/sample.rb`, not something the factory does for you. + +```ruby +require_relative "lib/claude_sample/client_factory" + +client = ClaudeSample::ClientFactory.create_client( + base_url: "https://.services.ai.azure.com/anthropic", + token_provider: -> { identity.current_access_token } +) +message = client.messages.create( + max_tokens: 1024, messages: [{role: "user", content: "Hello"}], model: "" +) +``` + +## Tests + +```sh +bundle install +bundle exec ruby test/run.rb # ruby test/run.rb works as well +``` + +The tests use Minitest 5.x from the Gemfile's `test` group (installed by `bundle install`, with no load-path tricks). They run offline. A real HTTP server on a loopback port stands in for the endpoint, so the SDK's own `Net::HTTP` transport produces the bytes under test: + +- the request the SDK sends: the Foundry-style and native paths and the model, a rotating bearer token, a resource key in `x-api-key` and the native `Authorization` key, the API version, no OAuth beta, canaries for `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_PROFILE`, `ANTHROPIC_BASE_URL` and `ANTHROPIC_CUSTOM_HEADERS` (with a control showing the SDK defaults would send them), streaming, HTTP error statuses, retries that fetch a fresh token, redirects, and the transport timeout; +- the token provider (`CliTokenProvider`), with a fake process runner and with a fixture `az` (a `.cmd` on Windows, a shell script elsewhere) that is really launched; +- the entry point, including mixed-family canaries (decoy `ANTHROPIC_*` and `CLAUDE_*` values must never be paired with the other profile's endpoint, model or key) and the 120 second policy. + +Nothing leaves your machine. + +## Troubleshooting + +- `Azure CLI exited with code N ...`: run `az login`, and `az account get-access-token --scope https://ai.azure.com/.default --output none` to see the CLI's own message. +- `Could not find gem 'anthropic'` (or `minitest`): run `bundle install` in this directory. +- `ANTHROPIC_BASE_URL selects the ANTHROPIC_* settings and requires an explicit AUTH_MODE ...`: the canonical profile has no default mode; set `AUTH_MODE=api_key` (and `ANTHROPIC_API_KEY`) or `AUTH_MODE=bearer`. +- `Azure CLI did not finish within its 60 second allowance ...`: run `az account get-access-token --output none` by hand to see why; the first run after an install or reboot is the slowest. +- A 401 or 403 from the service is reported as is (`AuthenticationError`, `PermissionDeniedError`); the sample never retries it with another credential. diff --git a/samples/ruby/lib/claude_sample/cli_token_provider.rb b/samples/ruby/lib/claude_sample/cli_token_provider.rb new file mode 100644 index 0000000..90301c2 --- /dev/null +++ b/samples/ruby/lib/claude_sample/cli_token_provider.rb @@ -0,0 +1,162 @@ +# frozen_string_literal: true + +require "json" +require "open3" + +module ClaudeSample + # A token provider for local development that asks a command-line tool for the current token. The one built-in + # tool is the Azure CLI, used as a documented fallback; production code passes its own provider to ClientFactory. + # + # Every token request starts `az account get-access-token --scope --output json`. The CLI owns token caching + # and renewal, so the price is one CLI process per request and this module keeps no cache of its own. Production code + # should give ClientFactory a token provider backed by its own identity library instead. + # + # The command is a fixed argument list, never shell text. Every argument is checked against a short allowlist, which + # also keeps cmd.exe metacharacters out when the CLI is a Windows batch file (az.cmd / az.bat). + # + # Each CLI process gets a finite allowance (60 seconds: a cold start under load can exceed 10). When it runs out the + # process (and, on Windows, its children) is stopped and the call fails; there is no fallback to another credential. + module CliTokenProvider + TIMEOUT_SECONDS = 60.0 + # Letters, digits and . _ : / - only: no quotes, spaces, or shell and cmd.exe metacharacters. + SAFE_ARGUMENT = %r{\A[A-Za-z0-9._:/-]+\z} + TENANT = /\A[A-Za-z0-9.-]+\z/ + VISIBLE_ASCII = /\A[\x21-\x7E]+\z/ + EXTENSIONS = %w[.com .exe .bat .cmd].freeze + + class << self + # @param run [#call, nil] replaces the process launch: receives the arguments after `az`, returns [exit status, stdout] + # @param timeout [Float, nil] seconds each CLI process may take; nil means TIMEOUT_SECONDS + # @return [Proc] returns an access token string; every call starts the CLI + def provider(scope, tenant_id = nil, run: nil, timeout: nil) + arguments = ["account", "get-access-token", "--scope", safe!(scope, "The token scope"), "--output", "json"] + unless tenant_id.nil? || tenant_id.empty? + raise ArgumentError, 'The tenant ID may only contain letters, digits, "." and "-".' unless TENANT.match?(tenant_id) + + arguments.push("--tenant", tenant_id) + end + run ||= ->(args) { self.run(args, nil, timeout: timeout) } + + lambda do + exit_status, stdout = run.call(arguments) + unless exit_status.zero? + raise "Azure CLI exited with code #{exit_status} while requesting a token for scope #{scope}. " \ + 'Run "az login" and retry, or supply your own token provider.' + end + + payload = begin + JSON.parse(stdout) + rescue JSON::ParserError + nil + end + raise "Azure CLI returned output that is not a JSON object." unless payload.is_a?(Hash) + + token = payload["accessToken"] + raise "Azure CLI response has no usable accessToken." unless token.is_a?(String) && VISIBLE_ASCII.match?(token) + + token + end + end + + # Starts the Azure CLI found on search_path (default: PATH) and returns [exit status, stdout]. stderr is discarded. + # A CLI that is still running after timeout seconds (default TIMEOUT_SECONDS) is stopped and the call raises. + # + # @param arguments [Array] + # @return [Array(Integer, String)] + def run(arguments, search_path = nil, timeout: nil) + timeout ||= TIMEOUT_SECONDS + arguments.each { |argument| safe!(argument, "Azure CLI arguments") } + windows = Gem.win_platform? + executable = locate(search_path || ENV.fetch("PATH", ""), windows: windows) + raise 'Azure CLI ("az") was not found on PATH. Install it and run "az login", or supply your own token provider.' if executable.nil? + + argv, directory = command(executable, arguments, windows: windows) + options = {} + options[:chdir] = directory if directory + Open3.popen3(*argv, **options) do |stdin, stdout, stderr, waiter| + stdin.close + discard = Thread.new { stderr.read } # drained and dropped, so the CLI never blocks on it + output = +"" + reader = Thread.new do + loop { output << stdout.readpartial(16_384) } + rescue EOFError, IOError + nil + end + unless waiter.join(timeout) + stop(waiter.pid, windows) + reader.kill + discard.kill + raise "Azure CLI did not finish within its #{timeout.round(1).to_s.delete_suffix(".0")} second allowance and was stopped; " \ + 'try "az account get-access-token --output none" by hand, or supply your own token provider.' + end + reader.join(1) # whatever the finished process left in the pipe + reader.kill + discard.kill + [waiter.value.exitstatus || 1, output.force_encoding(Encoding::UTF_8)] + end + rescue SystemCallError + raise "Azure CLI could not be started." + end + + # Finds `az` in the absolute directories of search_path. On Windows it honors PATHEXT, limited to .com, .exe, .bat and .cmd. + def locate(search_path, pathext: nil, windows: Gem.win_platform?) + names = ["az"] + if windows + extensions = (pathext || ENV.fetch("PATHEXT", "")).split(";").map(&:downcase).select { |extension| EXTENSIONS.include?(extension) } + names = (extensions.empty? ? EXTENSIONS : extensions).map { |extension| "az#{extension}" } + end + search_path.split(windows ? ";" : ":").each do |directory| + directory = directory.strip.delete('"') + absolute = windows ? directory.match?(%r{\A(?:[A-Za-z]:[\\/]|\\\\)}) : directory.start_with?("/") + next unless absolute + + names.each do |name| + candidate = File.join(directory, name) + return candidate if File.file?(candidate) && (windows || File.executable?(candidate)) + end + end + nil + end + + # Builds the argument list and working directory for one launch. + # + # A Windows batch file can only run under cmd.exe. It is started by bare file name from its own directory, so a + # path with spaces or parentheses needs no quoting; /d skips AutoRun commands. Arguments are allowlisted by run. + # + # @return [Array(Array, String, nil)] argv and working directory + def command(executable, arguments, windows:, interpreter: nil) + if windows && executable.match?(/\.(?:bat|cmd)\z/i) + return [[interpreter || command_interpreter, "/d", "/c", File.basename(executable), *arguments], File.dirname(executable)] + end + + [[executable, *arguments], nil] + end + + private + + # Stops the CLI; on Windows also its children (az.cmd runs the CLI as a child of cmd.exe). + def stop(pid, windows) + if windows + taskkill = File.join(ENV.fetch("SystemRoot", "C:\\Windows"), "System32", "taskkill.exe") + system(taskkill, "/F", "/T", "/PID", pid.to_s, out: File::NULL, err: File::NULL) + end + Process.kill("KILL", pid) + rescue SystemCallError + nil + end + + def command_interpreter + configured = ENV.fetch("ComSpec", "") + return configured if File.basename(configured).casecmp?("cmd.exe") && File.file?(configured) + + File.join(ENV.fetch("SystemRoot", "C:\\Windows"), "System32", "cmd.exe") + end + + def safe!(value, what) + return value if value.is_a?(String) && SAFE_ARGUMENT.match?(value) + + raise ArgumentError, "#{what} may only contain letters, digits and the characters . _ : / -" + end + end + end +end diff --git a/samples/ruby/lib/claude_sample/client_factory.rb b/samples/ruby/lib/claude_sample/client_factory.rb new file mode 100644 index 0000000..7eb3c98 --- /dev/null +++ b/samples/ruby/lib/claude_sample/client_factory.rb @@ -0,0 +1,97 @@ +# frozen_string_literal: true + +require "anthropic" +require "uri" + +module ClaudeSample + # Creates the standard Anthropic::Client for any Anthropic-compatible endpoint with exactly one explicit credential. + # + # The factory reads no environment variables and imports no cloud-provider code. Left alone, the SDK would look for + # ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, ANTHROPIC_PROFILE, workload identity variables and profiles on disk, so it + # is handed a public, non-secret placeholder that only switches that discovery off. A public request middleware then + # runs on every HTTP attempt (retries and redirect hops included), removes every credential header, and applies the + # selected credential. The placeholder never leaves the process. + module ClientFactory + # Credential-bearing headers. All of them are removed before the selected credential is applied. + CREDENTIAL_HEADERS = %w[authorization x-api-key api-key].freeze + + # Public, non-secret value that only stops the SDK from discovering credentials. + SUPPRESSION_PLACEHOLDER = "provided-by-request-hook" + + LOOPBACK_HOSTS = %w[localhost 127.0.0.1 [::1]].freeze + + VISIBLE_ASCII = /\A[\x21-\x7E]+\z/ + HEADER_NAME = /\A[!\#$%&'*+\-.^_`|~0-9A-Za-z]+\z/ + + BASE_URL_ERROR = "base_url must be an HTTPS URL without credentials, query, or fragment." + SECRET_ERROR = "must be a non-empty string without whitespace or control characters." + + class << self + # @param base_url [String] HTTPS endpoint (plain HTTP only for loopback hosts) without credentials, query or fragment + # @param token_provider [#call, nil] returns a bearer token. It runs once per HTTP attempt, so it should be cheap or cache. + # @param api_key [String, nil] a static key; exclusive with token_provider + # @param key_header [String] header that carries api_key. "Authorization" sends "Bearer "; any other name sends the raw key. + # @param api_version [String, nil] anthropic-version to send on every request; nil keeps the SDK default + # @param timeout [Float, nil] seconds per attempt, enforced by the SDK; nil keeps the SDK default + # @param max_retries [Integer, nil] nil keeps the SDK default + # @return [Anthropic::Client] + def create_client(base_url:, token_provider: nil, api_key: nil, key_header: "Authorization", api_version: nil, + timeout: nil, max_retries: nil) + origin = origin_of(base_url) + raise ArgumentError, "Provide exactly one of token_provider or api_key." if token_provider.nil? == api_key.nil? + raise ArgumentError, "token_provider must respond to #call." unless token_provider.nil? || token_provider.respond_to?(:call) + raise ArgumentError, "key_header must be a valid HTTP header name." unless HEADER_NAME.match?(key_header.to_s) + raise ArgumentError, "api_key #{SECRET_ERROR}" unless api_key.nil? || visible_ascii?(api_key) + raise ArgumentError, "api_version #{SECRET_ERROR}" unless api_version.nil? || visible_ascii?(api_version) + + header = token_provider ? "authorization" : key_header.downcase + authorize = lambda do |request, nxt| + assert_origin!(request.url, origin) + secret = token_provider ? acquire_token(token_provider) : api_key + headers = request.headers.reject { |name, _| CREDENTIAL_HEADERS.include?(name.downcase) || name.downcase == header } + headers[header] = header == "authorization" ? "Bearer #{secret}" : secret + headers["anthropic-version"] = api_version if api_version + nxt.call(request.with(headers: headers.freeze)) + end + + options = {auth_token: SUPPRESSION_PLACEHOLDER, base_url: base_url, middleware: [authorize]} + options[:timeout] = Float(timeout) unless timeout.nil? + options[:max_retries] = max_retries unless max_retries.nil? + Anthropic::Client.new(**options) + end + + private + + def visible_ascii?(value) + value.is_a?(String) && VISIBLE_ASCII.match?(value) + end + + # @return [Array(String, String, Integer)] scheme, host, port + def origin_of(base_url) + uri = begin + URI.parse(base_url.to_s) + rescue URI::InvalidURIError + raise ArgumentError, BASE_URL_ERROR + end + host = uri.host.to_s.downcase + secure = uri.scheme == "https" || (uri.scheme == "http" && LOOPBACK_HOSTS.include?(host)) + raise ArgumentError, BASE_URL_ERROR if host.empty? || !secure || uri.userinfo || uri.query || uri.fragment + + [uri.scheme, host, uri.port] + end + + def assert_origin!(url, origin) + return if [url.scheme, url.host.to_s.downcase, url.port] == origin && url.userinfo.nil? + + raise "Refusing to send credentials to a different origin." + end + + def acquire_token(token_provider) + token = token_provider.call + return token if visible_ascii?(token) + + raise "The token provider must return a non-empty string without whitespace or control characters." + end + end + end +end diff --git a/samples/ruby/lib/claude_sample/sample.rb b/samples/ruby/lib/claude_sample/sample.rb new file mode 100644 index 0000000..ba4333e --- /dev/null +++ b/samples/ruby/lib/claude_sample/sample.rb @@ -0,0 +1,180 @@ +# frozen_string_literal: true + +require_relative "cli_token_provider" +require_relative "client_factory" + +module ClaudeSample + # The command-line sample: one Messages call, printed whole or streamed (--stream). + # + # All configuration comes from the environment passed to run, in one of two profiles that never borrow from each other: + # ANTHROPIC_BASE_URL selects the canonical profile (ANTHROPIC_MODEL, ANTHROPIC_API_KEY; AUTH_MODE must be set + # explicitly), otherwise CLAUDE_BASE_URL selects the legacy one (CLAUDE_DEPLOYMENT_NAME, CLAUDE_API_KEY; AUTH_MODE + # defaults to bearer). The bearer credential is an Azure CLI token, a local-development fallback. + module Sample + PROMPT = "What are 3 things to visit in Seattle?" + MAX_TOKENS = 1024 + DEFAULT_TOKEN_SCOPE = "https://ai.azure.com/.default" + + # Application policy of this sample, passed to the factory explicitly: the factory itself keeps the SDK default. + REQUEST_TIMEOUT_SECONDS = 120.0 + USAGE = "Usage: ruby main.rb [--stream]\n" + + class << self + # @param argv [Array] command-line arguments + # @param env [Hash{String=>String}] + # @param run_cli [#call, nil] Azure CLI process override (tests) + # @return [Integer] the exit status + def run(argv, env, stdout, stderr, run_cli: nil) + stream = false + argv.each do |argument| + case argument + when "--stream" + stream = true + when "-h", "--help" + stdout.write(USAGE) + return 0 + else + stderr.write("Unknown argument: #{argument}\n#{USAGE}") + return 2 + end + end + + begin + client, model = configure(env, run_cli) + stream ? stream_message(client, model, stdout) : message(client, model, stdout) + 0 + rescue StandardError => e + stderr.write("Error: #{describe(e)}\n") + 1 + end + end + + # Builds the client and returns it with the model name. + # + # ANTHROPIC_BASE_URL selects the canonical profile: ANTHROPIC_MODEL and, for an API key, ANTHROPIC_API_KEY. AUTH_MODE + # must be set explicitly (api_key or bearer), so an ambient native endpoint and key can never silently receive an + # Azure token, nor an ambient Azure setup a native key. Otherwise CLAUDE_BASE_URL selects the legacy profile: + # CLAUDE_DEPLOYMENT_NAME and CLAUDE_API_KEY, with AUTH_MODE defaulting to bearer. A profile never falls back to the + # other one's model or key, so a secret can never be paired with the endpoint of the other family. + # + # @return [Array(Anthropic::Client, String)] + def configure(env, run_cli = nil) + if setting(env, "ANTHROPIC_BASE_URL") + base_url = setting(env, "ANTHROPIC_BASE_URL") + model = setting(env, "ANTHROPIC_MODEL") + key_name = "ANTHROPIC_API_KEY" + default_mode = nil + missing_model = "ANTHROPIC_BASE_URL selects the ANTHROPIC_* settings: also set ANTHROPIC_MODEL (CLAUDE_DEPLOYMENT_NAME is not used with it)." + missing_key = "Set ANTHROPIC_API_KEY (CLAUDE_API_KEY is not used with ANTHROPIC_BASE_URL)." + else + base_url = setting(env, "CLAUDE_BASE_URL") + model = setting(env, "CLAUDE_DEPLOYMENT_NAME") + key_name = "CLAUDE_API_KEY" + default_mode = "bearer" + missing_model = "CLAUDE_BASE_URL selects the CLAUDE_* settings: also set CLAUDE_DEPLOYMENT_NAME (ANTHROPIC_MODEL is not used with it)." + missing_key = "Set CLAUDE_API_KEY (ANTHROPIC_API_KEY is not used with CLAUDE_BASE_URL)." + end + if base_url.nil? + raise ArgumentError, "Set CLAUDE_BASE_URL and CLAUDE_DEPLOYMENT_NAME, or ANTHROPIC_BASE_URL and ANTHROPIC_MODEL. The two sets are never mixed." + end + raise ArgumentError, missing_model if model.nil? + + mode = setting(env, "AUTH_MODE") || default_mode + if mode.nil? + raise ArgumentError, "ANTHROPIC_BASE_URL selects the ANTHROPIC_* settings and requires an explicit AUTH_MODE: " \ + "set AUTH_MODE=api_key (uses ANTHROPIC_API_KEY) or AUTH_MODE=bearer (uses an Azure CLI token)." + end + + token_provider = nil + api_key = nil + case mode + when "bearer" + # The selector is shared with the other language samples. Only the Azure CLI is built in here, so any other + # explicit choice is refused rather than silently answered with the CLI. + selector = setting(env, "AZURE_TOKEN_CREDENTIALS") + if selector && selector != "AzureCliCredential" + shown = selector.match?(/\A[A-Za-z0-9_.-]{1,64}\z/) ? selector : "(unprintable or too long)" + raise ArgumentError, "AZURE_TOKEN_CREDENTIALS=#{shown} is not supported: the Azure CLI (AzureCliCredential) is this sample's " \ + "only built-in token source. Unset it, or pass your own token provider to ClientFactory for other credentials." + end + token_provider = CliTokenProvider.provider( + setting(env, "TOKEN_SCOPE") || DEFAULT_TOKEN_SCOPE, setting(env, "AZURE_TENANT_ID"), run: run_cli + ) + when "api_key" + api_key = setting(env, key_name) || raise(ArgumentError, missing_key) + else + raise ArgumentError, "AUTH_MODE must be bearer or api_key." + end + + client = ClientFactory.create_client( + base_url: base_url, + token_provider: token_provider, + api_key: api_key, + key_header: setting(env, "API_KEY_HEADER") || "Authorization", + api_version: setting(env, "ANTHROPIC_API_VERSION"), + timeout: REQUEST_TIMEOUT_SECONDS + ) + [client, model] + end + + private + + def message(client, model, stdout) + message = client.messages.create( + max_tokens: MAX_TOKENS, messages: [{role: "user", content: PROMPT}], model: model + ) + texts = message.content.filter_map { |block| block.text if block.type == :text && !block.text.strip.empty? } + raise no_text(message.stop_reason) if texts.empty? + + texts.each { |text| stdout.write("#{text}\n") } + stdout.write("\n[usage] input=#{message.usage.input_tokens} output=#{message.usage.output_tokens}\n") + end + + def stream_message(client, model, stdout) + events = client.messages.stream( + max_tokens: MAX_TOKENS, messages: [{role: "user", content: PROMPT}], model: model + ) + printed = false + input = 0 + output = 0 + stop_reason = nil + events.each do |event| + case event.type + when :message_start + input = event.message.usage.input_tokens + output = event.message.usage.output_tokens + when :text + stdout.write(event.text) + stdout.flush + printed ||= !event.text.strip.empty? + when :message_delta + input = event.usage.input_tokens || input + output = event.usage.output_tokens + stop_reason = event.delta.stop_reason + end + end + raise no_text(stop_reason) unless printed + + stdout.write("\n\n[usage] input=#{input} output=#{output}\n") + end + + def no_text(stop_reason) + "No text response (stop_reason=#{stop_reason || "none"}). Increase max_tokens if the response exhausted its budget." + end + + def describe(error) + own = error.instance_of?(ArgumentError) || error.instance_of?(RuntimeError) + own ? error.message : "#{error.class.name.split("::").last}: #{error.message}" + end + + # The first of names that is set and not empty. + def setting(env, *names) + names.each do |name| + value = env[name] + return value unless value.nil? || value.empty? + end + nil + end + end + end +end diff --git a/samples/ruby/main.rb b/samples/ruby/main.rb new file mode 100644 index 0000000..079508c --- /dev/null +++ b/samples/ruby/main.rb @@ -0,0 +1,7 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +require "bundler/setup" +require_relative "lib/claude_sample/sample" + +exit(ClaudeSample::Sample.run(ARGV, ENV.to_h, $stdout, $stderr)) diff --git a/samples/ruby/test/cli_token_provider_test.rb b/samples/ruby/test/cli_token_provider_test.rb new file mode 100644 index 0000000..b6f348f --- /dev/null +++ b/samples/ruby/test/cli_token_provider_test.rb @@ -0,0 +1,126 @@ +# frozen_string_literal: true + +require_relative "test_helper" + +class CliTokenProviderTest < Minitest::Test + include EnvHelper + + FAKE_AZ = File.expand_path("fixtures/fake-az", __dir__) + SCOPE = "https://ai.azure.com/.default" + TOKEN_ARGUMENTS = ["account", "get-access-token", "--scope", SCOPE, "--output", "json"].freeze + CLI = ClaudeSample::CliTokenProvider + + def failure_message(provider) + assert_raises(RuntimeError) { provider.call }.message + end + + def test_asks_for_the_scope_with_a_fixed_argument_list_once_per_token_request + calls = [] + provider = CLI.provider(SCOPE, run: lambda { |arguments| + calls << arguments + [0, JSON.generate("accessToken" => "cli-token-#{calls.length}", "expiresOn" => "2099-01-01 00:00:00.000000", "tokenType" => "Bearer")] + }) + assert_empty calls, "nothing runs at creation" + assert_equal "cli-token-1", provider.call + assert_equal "cli-token-2", provider.call, "this module keeps no cache of its own" + assert_equal [TOKEN_ARGUMENTS, TOKEN_ARGUMENTS], calls + end + + def test_adds_tenant_only_when_a_tenant_is_configured + calls = [] + run = lambda { |arguments| + calls << arguments + [0, '{"accessToken":"t"}'] + } + CLI.provider(SCOPE, "tenant-1.example", run: run).call + CLI.provider(SCOPE, "", run: run).call + CLI.provider(SCOPE, nil, run: run).call + assert_equal [[*TOKEN_ARGUMENTS, "--tenant", "tenant-1.example"], TOKEN_ARGUMENTS, TOKEN_ARGUMENTS], calls + end + + def test_arguments_are_allowlisted_so_nothing_is_interpreted_by_a_shell_or_cmd_exe + ["", "a b", "a&b", "a|b", "a^b", "a%PATH%", 'a"b', "a'b", "a;b", "a`b", "a$b", "a(b)", "a [7, %({"accessToken":"#{leak}"}), + %(Azure CLI exited with code 7 while requesting a token for scope #{SCOPE}. Run "az login" and retry, or supply your own token provider.)], + "not JSON" => [0, "ERROR #{leak}", "Azure CLI returned output that is not a JSON object."], + "JSON scalar" => [0, %("#{leak}"), "Azure CLI returned output that is not a JSON object."], + "JSON list" => [0, %(["#{leak}"]), "Azure CLI returned output that is not a JSON object."], + "no accessToken" => [0, %({"refreshToken":"#{leak}"}), "Azure CLI response has no usable accessToken."], + "empty accessToken" => [0, %({"accessToken":"","refreshToken":"#{leak}"}), "Azure CLI response has no usable accessToken."], + "null accessToken" => [0, %({"accessToken":null,"x":"#{leak}"}), "Azure CLI response has no usable accessToken."], + "numeric accessToken" => [0, %({"accessToken":12345,"x":"#{leak}"}), "Azure CLI response has no usable accessToken."], + "spaced accessToken" => [0, %({"accessToken":"two words","x":"#{leak}"}), "Azure CLI response has no usable accessToken."], + "multi-line accessToken" => [0, %({"accessToken":"line\\nbreak","x":"#{leak}"}), "Azure CLI response has no usable accessToken."] + } + cases.each do |label, (exit_status, stdout, expected)| + message = failure_message(CLI.provider(SCOPE, run: ->(_arguments) { [exit_status, stdout] })) + assert_equal expected, message, label + refute_includes message, leak, "#{label} echoed the CLI payload" + end + end + + def test_a_cli_that_does_not_finish_within_its_allowance_is_stopped_and_reported_never_replaced_by_a_fallback + File.chmod(0o755, File.join(FAKE_AZ, "az")) unless Gem.win_platform? + assert_equal 60.0, CLI::TIMEOUT_SECONDS, "the default allowance is finite and generous" + started = Process.clock_gettime(Process::CLOCK_MONOTONIC) + provider = CLI.provider(SCOPE, run: ->(arguments) { CLI.run(arguments, FAKE_AZ, timeout: 1.0) }) + message = with_env("FAKE_AZ_MODE" => "slow") { failure_message(provider) } + assert_equal 'Azure CLI did not finish within its 1 second allowance and was stopped; try "az account get-access-token --output none" ' \ + "by hand, or supply your own token provider.", message + assert_operator Process.clock_gettime(Process::CLOCK_MONOTONIC) - started, :<, 4.5, "the CLI must be stopped at its allowance (the fixture takes about 7 seconds)" + refute_includes message, "too-late-token" + end + + def test_a_missing_azure_cli_is_reported_with_an_actionable_message + error = assert_raises(RuntimeError) { CLI.run(["version"], File.expand_path("no-such-directory", __dir__)) } + assert_equal 'Azure CLI ("az") was not found on PATH. Install it and run "az login", or supply your own token provider.', error.message + end + + def test_command_a_windows_batch_file_runs_under_cmd_exe_from_its_own_directory_anything_else_runs_directly + arguments = %w[account get-access-token] + cmd = "C:/Windows/System32/cmd.exe" + assert_equal [[cmd, "/d", "/c", "az.cmd", *arguments], "C:/Program Files (x86)/Azure CLI/wbin"], + CLI.command("C:/Program Files (x86)/Azure CLI/wbin/az.cmd", arguments, windows: true, interpreter: cmd) + assert_equal [[cmd, "/d", "/c", "az.BAT", *arguments], "C:/tools"], CLI.command("C:/tools/az.BAT", arguments, windows: true, interpreter: cmd) + assert_equal [["C:/tools/az.exe", *arguments], nil], CLI.command("C:/tools/az.exe", arguments, windows: true, interpreter: cmd) + assert_equal [["/usr/bin/az", *arguments], nil], CLI.command("/usr/bin/az", arguments, windows: false) + assert_equal [["/opt/tools/az.cmd", *arguments], nil], CLI.command("/opt/tools/az.cmd", arguments, windows: false) + end + + def test_locate_searches_only_absolute_path_entries_and_honors_pathext_on_windows + if Gem.win_platform? + assert_equal "#{FAKE_AZ}/az.cmd", CLI.locate(FAKE_AZ, pathext: ".COM;.EXE;.BAT;.CMD", windows: true) + assert_equal "#{FAKE_AZ}/az.cmd", CLI.locate("relative-dir;#{FAKE_AZ}", pathext: "", windows: true), "relative entries are skipped; default extensions" + assert_nil CLI.locate("relative-dir;#{File.expand_path("nowhere", __dir__)}", pathext: ".EXE", windows: true) + assert_nil CLI.locate(FAKE_AZ, pathext: ".EXE;.COM", windows: true), "extensions missing from PATHEXT are not tried" + else + File.chmod(0o755, File.join(FAKE_AZ, "az")) + assert_equal "#{FAKE_AZ}/az", CLI.locate("relative-dir:#{FAKE_AZ}", windows: false) + assert_nil CLI.locate("relative-dir", windows: false), "relative entries are skipped" + end + end + + def test_real_process_launch_the_fixture_cli_receives_exactly_the_fixed_arguments_and_its_status_is_returned + File.chmod(0o755, File.join(FAKE_AZ, "az")) unless Gem.win_platform? + run = ->(arguments) { CLI.run(arguments, FAKE_AZ) } + + exit_status, stdout = with_env("FAKE_AZ_MODE" => "args") { run.call([*TOKEN_ARGUMENTS, "--tenant", "tenant-1.example"]) } + assert_equal 0, exit_status + assert_equal "account get-access-token --scope #{SCOPE} --output json --tenant tenant-1.example", JSON.parse(stdout)["accessToken"] + + assert_equal "fixture-cli-token", with_env("FAKE_AZ_MODE" => "ok") { CLI.provider(SCOPE, run: run).call } + assert_equal 3, with_env("FAKE_AZ_MODE" => "fail") { run.call(TOKEN_ARGUMENTS).first } + message = with_env("FAKE_AZ_MODE" => "empty") { failure_message(CLI.provider(SCOPE, run: run)) } + assert_equal "Azure CLI response has no usable accessToken.", message + end +end diff --git a/samples/ruby/test/client_factory_test.rb b/samples/ruby/test/client_factory_test.rb new file mode 100644 index 0000000..2c39af0 --- /dev/null +++ b/samples/ruby/test/client_factory_test.rb @@ -0,0 +1,258 @@ +# frozen_string_literal: true + +require_relative "test_helper" + +class ClientFactoryTest < Minitest::Test + include EnvHelper + + PARAMS = {max_tokens: 32, messages: [{role: "user", content: "Hello"}], model: MODEL}.freeze + + def setup + @server = LoopbackServer.new + @base_url = @server.base_url + end + + def teardown + @server.close + end + + def create(**options) + ClaudeSample::ClientFactory.create_client( + **{base_url: @base_url, token_provider: -> { "selected-token" }, max_retries: 0}.merge(options) + ) + end + + def requests = @server.requests + + def test_returns_the_standard_client_and_resolves_the_token_per_request_not_at_creation + calls = 0 + tokens = %w[first-token second-token] + client = create(token_provider: -> { tokens.fetch((calls += 1) - 1) }) + assert_instance_of Anthropic::Client, client + assert_equal 0, calls + assert_equal "OK", client.messages.create(**PARAMS).content.first.text + client.messages.create(**PARAMS) + assert_equal 2, calls + assert_equal ["Bearer first-token", "Bearer second-token"], requests.map { |request| request.header("authorization") } + requests.each do |request| + assert_nil request.header("anthropic-beta"), "a generic bearer must not carry the OAuth beta" + assert_nil request.header("x-api-key") + assert_nil request.header("api-key") + refute_includes request.wire, "provided-by-request-hook", "the suppression placeholder stays off the wire" + end + end + + def test_sends_the_model_and_the_native_or_foundry_style_path + {"" => "/v1/messages", "/anthropic" => "/anthropic/v1/messages"}.each do |prefix, path| + requests.clear + create(base_url: @server.base_url(prefix)).messages.create(**PARAMS) + assert_equal path, requests.first.path + assert_equal MODEL, requests.first.json["model"] + assert_equal 32, requests.first.json["max_tokens"] + end + end + + def test_ambient_credentials_profile_base_url_and_custom_headers_cannot_reach_the_wire + ambient = { + "ANTHROPIC_API_KEY" => "ambient-key-canary", + "ANTHROPIC_AUTH_TOKEN" => "ambient-token-canary", + "ANTHROPIC_PROFILE" => "nonexistent-profile-canary", + "ANTHROPIC_BASE_URL" => "https://wrong.example", + "ANTHROPIC_CUSTOM_HEADERS" => "Authorization: custom-canary\nx-api-key: key-canary\napi-key: alias-canary", + "ANTHROPIC_FOUNDRY_RESOURCE" => "unchanged-cli-resource" + } + with_env(ambient) do + create.messages.create( + **PARAMS, + request_options: {extra_headers: {"Authorization" => "request-canary", "x-api-key" => "request-key-canary", + "anthropic-beta" => "a-requested-beta"}} + ) + request = requests.first + assert_equal "Bearer selected-token", request.header("authorization") + assert_nil request.header("x-api-key") + assert_nil request.header("api-key") + assert_equal "a-requested-beta", request.header("anthropic-beta"), "the requested beta is preserved and nothing is added" + assert_equal "/anthropic/v1/messages", request.path, "the explicit base URL wins over ANTHROPIC_BASE_URL" + refute_includes request.wire, "canary" + assert_equal "unchanged-cli-resource", ENV.fetch("ANTHROPIC_FOUNDRY_RESOURCE"), "the factory does not touch the environment" + end + end + + def test_control_the_same_ambient_values_do_reach_the_wire_from_an_unconfigured_sdk_client + with_env("ANTHROPIC_API_KEY" => "ambient-key-canary", "ANTHROPIC_CUSTOM_HEADERS" => "x-api-key: header-canary\napi-key: alias-canary") do + capture_io { Anthropic::Client.new(base_url: @base_url, max_retries: 0).messages.create(**PARAMS) } + %w[ambient-key-canary header-canary alias-canary].each do |canary| + assert_includes requests.first.wire, canary, "the SDK defaults leak #{canary}, so the canary test is meaningful" + end + end + with_env("ANTHROPIC_PROFILE" => "nonexistent-profile-canary") do + assert_raises(Anthropic::Errors::Error, "the SDK looks for the profile named by ANTHROPIC_PROFILE") do + Anthropic::Client.new(base_url: @base_url) + end + create(api_key: "selected-key", token_provider: nil) + end + end + + def test_api_key_header_is_configuration_authorization_by_default_any_other_name_verbatim + [ + [nil, "authorization", "Bearer selected-key"], + ["Authorization", "authorization", "Bearer selected-key"], + ["x-api-key", "x-api-key", "selected-key"], + ["api-key", "api-key", "selected-key"] + ].each do |header, name, expected| + requests.clear + options = {token_provider: nil, api_key: "selected-key"} + options[:key_header] = header if header + create(**options).messages.create(**PARAMS) + request = requests.first + assert_equal expected, request.header(name), "#{name} for #{header.inspect}" + (%w[authorization x-api-key api-key] - [name]).each { |other| assert_nil request.header(other), "#{other} must be absent" } + assert_nil request.header("anthropic-beta") + refute_includes request.wire, "provided-by-request-hook" + end + end + + def test_anthropic_version_is_the_sdk_default_unless_configured + create.messages.create(**PARAMS) + assert_equal "2026-10-21", requests.last.header("anthropic-version"), "the SDK default version" + create(api_version: "2023-06-01").messages.create( + **PARAMS, request_options: {extra_headers: {"anthropic-version" => "request-version"}} + ) + assert_equal "2023-06-01", requests.last.header("anthropic-version"), "the configured version" + end + + def test_invalid_configuration_fails_before_any_network_use + invalid = { + "neither credential" => {token_provider: nil}, + "both credentials" => {api_key: "key"}, + "plain HTTP" => {base_url: "http://insecure.example"}, + "credentials in the URL" => {base_url: "https://user:secret@example.com"}, + "query in the URL" => {base_url: "https://example.com/anthropic?x=1"}, + "fragment in the URL" => {base_url: "https://example.com/anthropic#x"}, + "unsupported scheme" => {base_url: "ftp://example.com"}, + "no host" => {base_url: "https://"}, + "empty URL" => {base_url: ""}, + "not callable" => {token_provider: "token"}, + "empty key" => {token_provider: nil, api_key: ""}, + "multi-line key" => {token_provider: nil, api_key: "key\nvalue"}, + "spaced key" => {token_provider: nil, api_key: "key value"}, + "non-string key" => {token_provider: nil, api_key: 12_345}, + "bad header name" => {token_provider: nil, api_key: "key", key_header: "bad\nheader"}, + "empty header name" => {token_provider: nil, api_key: "key", key_header: ""}, + "bad version" => {api_version: "2023\n06"} + } + invalid.each do |label, options| + assert_raises(ArgumentError, label) { create(**options) } + end + assert_empty requests + ["http://127.0.0.1:8080", "http://localhost", "http://[::1]:8080", "https://example.com:8443/anthropic"].each do |accepted| + create(base_url: accepted) + end + end + + def test_the_factory_keeps_the_sdk_defaults_for_timeout_and_retries_unless_given + client = ClaudeSample::ClientFactory.create_client(base_url: @base_url, token_provider: -> { "token" }) + assert_equal Anthropic::Client::DEFAULT_TIMEOUT_IN_SECONDS, client.timeout + assert_equal 600.0, client.timeout + assert_equal Anthropic::Client::DEFAULT_MAX_RETRIES, client.max_retries + assert_equal 30.0, create(timeout: 30).timeout + assert_equal 5, create(max_retries: 5).max_retries + end + + def test_a_same_origin_redirect_is_followed_and_re_authorized + @server.close + @server = LoopbackServer.new do |request, count| + count == 1 ? [307, {"location" => "/anthropic/v1/messages-moved"}, ""] : LoopbackServer.json_response(message_body) + end + issued = 0 + create(base_url: @server.base_url, token_provider: -> { "token-#{issued += 1}" }).messages.create(**PARAMS) + assert_equal ["Bearer token-1", "Bearer token-2"], requests.map { |request| request.header("authorization") } + assert_equal "/anthropic/v1/messages-moved", requests.last.path + end + + def test_a_cross_origin_redirect_is_refused_before_any_credential_is_produced_or_sent + @server.close + [ + ->(port) { "http://localhost:#{port}/anthropic/v1/messages" }, + ->(port) { "https://127.0.0.1:#{port}/anthropic/v1/messages" }, + ->(_port) { "http://127.0.0.1:1/anthropic/v1/messages" } + ].each do |target| + port = nil + @server = LoopbackServer.new { |_request, _count| [302, {"location" => target.call(port)}, ""] } + port = @server.port + issued = 0 + error = assert_raises(RuntimeError) do + create(base_url: @server.base_url, token_provider: -> { "token-#{issued += 1}" }).messages.create(**PARAMS) + end + assert_equal "Refusing to send credentials to a different origin.", error.message + assert_equal 1, requests.length, "only the original origin is contacted" + assert_equal 1, issued, "no token is produced for the refused hop" + @server.close + end + @server = LoopbackServer.new + end + + def test_a_provider_failure_surfaces_unchanged_and_no_request_is_sent + failure = RuntimeError.new("credential unavailable") + error = assert_raises(RuntimeError) { create(token_provider: -> { raise failure }).messages.create(**PARAMS) } + assert_same failure, error + assert_empty requests + end + + def test_a_token_that_is_empty_multi_line_or_not_a_string_is_rejected_without_being_echoed + ["", "line\nbreak", "has space", 42, nil].each do |bad| + error = assert_raises(RuntimeError) { create(token_provider: -> { bad }).messages.create(**PARAMS) } + assert_equal "The token provider must return a non-empty string without whitespace or control characters.", error.message + end + assert_empty requests + end + + def test_http_error_statuses_surface_as_sdk_errors_that_do_not_contain_the_credential + { + 401 => Anthropic::Errors::AuthenticationError, 403 => Anthropic::Errors::PermissionDeniedError, + 429 => Anthropic::Errors::RateLimitError, 500 => Anthropic::Errors::InternalServerError + }.each do |status, error_class| + @server.close + @server = LoopbackServer.new { |_request, _count| LoopbackServer.json_response(error_body("api_error", "test failure"), status) } + error = assert_raises(error_class) { create(base_url: @server.base_url).messages.create(**PARAMS) } + assert_equal status, error.status + refute_includes error.message, "selected-token" + end + end + + def test_an_sdk_retry_acquires_a_fresh_token + @server.close + @server = LoopbackServer.new do |_request, count| + if count == 1 + LoopbackServer.json_response(error_body("api_error", "try again"), 500, "retry-after-ms" => "1") + else + LoopbackServer.json_response(message_body) + end + end + issued = 0 + create(base_url: @server.base_url, max_retries: 1, token_provider: -> { "token-#{issued += 1}" }).messages.create(**PARAMS) + assert_equal ["Bearer token-1", "Bearer token-2"], requests.map { |request| request.header("authorization") } + end + + def test_streaming_goes_through_the_same_credential_hook + @server.close + @server = LoopbackServer.new { |_request, _count| [200, {"content-type" => "text/event-stream"}, sse_body(%w[Hel lo])] } + stream = create(base_url: @server.base_url).messages.stream(**PARAMS) + assert_equal "Hello", stream.text.to_a.join + request = requests.first + assert_equal "Bearer selected-token", request.header("authorization") + assert_includes request.header("accept"), "text/event-stream" + assert_nil request.header("anthropic-beta") + end + + def test_the_transport_timeout_is_enforced + @server.close + @server = LoopbackServer.new do |_request, _count| + sleep 3 + LoopbackServer.json_response(message_body) + end + started = Process.clock_gettime(Process::CLOCK_MONOTONIC) + assert_raises(Anthropic::Errors::APITimeoutError) { create(base_url: @server.base_url, timeout: 1.0).messages.create(**PARAMS) } + assert_operator Process.clock_gettime(Process::CLOCK_MONOTONIC) - started, :<, 2.9, "the request must end at the 1 second timeout" + end +end diff --git a/samples/ruby/test/fixtures/fake-az/az b/samples/ruby/test/fixtures/fake-az/az new file mode 100644 index 0000000..3ca0251 --- /dev/null +++ b/samples/ruby/test/fixtures/fake-az/az @@ -0,0 +1,9 @@ +#!/bin/sh +# Test double for the Azure CLI. It contacts nothing and prints synthetic data; FAKE_AZ_MODE selects the behavior. +case "${FAKE_AZ_MODE:-ok}" in + fail) exit 3 ;; + slow) sleep 7; printf '%s\n' '{"accessToken":"too-late-token"}' ;; + empty) printf '%s\n' '{"accessToken":""}' ;; + args) printf '{"accessToken":"%s"}\n' "$*" ;; + *) printf '%s\n' '{"accessToken":"fixture-cli-token","tokenType":"Bearer"}' ;; +esac diff --git a/samples/ruby/test/fixtures/fake-az/az.cmd b/samples/ruby/test/fixtures/fake-az/az.cmd new file mode 100644 index 0000000..5e380e8 --- /dev/null +++ b/samples/ruby/test/fixtures/fake-az/az.cmd @@ -0,0 +1,22 @@ +@echo off +rem Test double for the Azure CLI. It contacts nothing and prints synthetic data; FAKE_AZ_MODE selects the behavior. +if "%FAKE_AZ_MODE%"=="fail" exit /b 3 +if "%FAKE_AZ_MODE%"=="slow" goto slow +if "%FAKE_AZ_MODE%"=="empty" goto empty +if "%FAKE_AZ_MODE%"=="args" goto args +echo {"accessToken":"fixture-cli-token","tokenType":"Bearer"} +exit /b 0 +:slow +rem ping waits about a second per count; unlike the timeout command it needs no console. +ping -n 8 127.0.0.1 >nul +echo {"accessToken":"too-late-token"} +exit /b 0 +:empty +echo {"accessToken":""} +exit /b 0 +:args +rem Some launchers quote every argument; drop the quotes so the output stays valid JSON. +set ARGS=%* +set ARGS=%ARGS:"=% +echo {"accessToken":"%ARGS%"} +exit /b 0 diff --git a/samples/ruby/test/run.rb b/samples/ruby/test/run.rb new file mode 100644 index 0000000..6c2ac72 --- /dev/null +++ b/samples/ruby/test/run.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +# Runs every test file in one Minitest process: `bundle exec ruby test/run.rb`. A plain `ruby test/run.rb` works as well, +# because test_helper.rb loads bundler/setup. +Dir[File.join(__dir__, "*_test.rb")].sort.each { |file| require file } diff --git a/samples/ruby/test/sample_test.rb b/samples/ruby/test/sample_test.rb new file mode 100644 index 0000000..a8d2547 --- /dev/null +++ b/samples/ruby/test/sample_test.rb @@ -0,0 +1,323 @@ +# frozen_string_literal: true + +require "stringio" +require_relative "test_helper" + +class SampleTest < Minitest::Test + include EnvHelper + + CLI_OK = ->(_arguments) { [0, '{"accessToken":"entra-test-token"}'] } + NO_ENDPOINT = "Error: Set CLAUDE_BASE_URL and CLAUDE_DEPLOYMENT_NAME, or ANTHROPIC_BASE_URL and ANTHROPIC_MODEL. The two sets are never mixed.\n" + LEGACY_NEEDS_MODEL = "Error: CLAUDE_BASE_URL selects the CLAUDE_* settings: also set CLAUDE_DEPLOYMENT_NAME (ANTHROPIC_MODEL is not used with it).\n" + CANONICAL_NEEDS_MODEL = "Error: ANTHROPIC_BASE_URL selects the ANTHROPIC_* settings: also set ANTHROPIC_MODEL (CLAUDE_DEPLOYMENT_NAME is not used with it).\n" + LEGACY_NEEDS_KEY = "Error: Set CLAUDE_API_KEY (ANTHROPIC_API_KEY is not used with CLAUDE_BASE_URL).\n" + CANONICAL_NEEDS_KEY = "Error: Set ANTHROPIC_API_KEY (CLAUDE_API_KEY is not used with ANTHROPIC_BASE_URL).\n" + CANONICAL_NEEDS_MODE = "Error: ANTHROPIC_BASE_URL selects the ANTHROPIC_* settings and requires an explicit AUTH_MODE: " \ + "set AUTH_MODE=api_key (uses ANTHROPIC_API_KEY) or AUTH_MODE=bearer (uses an Azure CLI token).\n" + + def teardown + @server&.close + end + + def serve(&responder) + @server&.close + @server = LoopbackServer.new(&responder) + end + + # The legacy (CLAUDE_*) settings. + def sample_env(extra = {}) + {"CLAUDE_BASE_URL" => @server.base_url, "CLAUDE_DEPLOYMENT_NAME" => MODEL}.merge(extra) + end + + # The canonical (ANTHROPIC_*) settings. + def canonical_env(extra = {}) + {"ANTHROPIC_BASE_URL" => @server.base_url, "ANTHROPIC_MODEL" => MODEL}.merge(extra) + end + + # @return [Array(Integer, String, String)] exit status, stdout, stderr + def run_sample(argv, env, cli: CLI_OK, ambient: {}) + stdout = StringIO.new + stderr = StringIO.new + status = with_env(ambient) { ClaudeSample::Sample.run(argv, env, stdout, stderr, run_cli: cli) } + [status, stdout.string, stderr.string] + end + + def counting_cli + calls = [] + [calls, lambda { |arguments| + calls << arguments + [0, '{"accessToken":"entra-test-token"}'] + }] + end + + def thinking_then_text + body = message_body("OK") + body["content"].unshift({"type" => "thinking", "thinking" => "not for display", "signature" => "sample"}) + body + end + + def test_the_one_shot_sample_prints_the_text_and_usage_never_the_thinking_and_sends_one_bearer_request + serve { |_request, _count| LoopbackServer.json_response(thinking_then_text) } + status, stdout, stderr = run_sample([], sample_env) + assert_equal 0, status, stderr + assert_equal "OK\n\n[usage] input=1 output=2\n", stdout + assert_equal "", stderr + assert_equal 1, @server.requests.length + request = @server.requests.first + assert_equal "/anthropic/v1/messages", request.path + assert_equal "Bearer entra-test-token", request.header("authorization") + assert_equal "2026-10-21", request.header("anthropic-version"), "the SDK default API version" + %w[anthropic-beta x-api-key api-key].each { |name| assert_nil request.header(name), "#{name} must be absent" } + assert_equal MODEL, request.json["model"] + assert_equal 1024, request.json["max_tokens"] + assert_equal ClaudeSample::Sample::PROMPT, request.json["messages"].first["content"] + end + + def test_stream_prints_the_text_as_it_arrives_then_usage + serve { |_request, _count| [200, {"content-type" => "text/event-stream"}, sse_body(["Seattle has ", "the Space Needle."], input: 11, output: 13)] } + status, stdout, stderr = run_sample(["--stream"], sample_env) + assert_equal 0, status, stderr + assert_equal "Seattle has the Space Needle.\n\n[usage] input=11 output=13\n", stdout + request = @server.requests.first + assert_equal "Bearer entra-test-token", request.header("authorization") + assert_includes request.header("accept"), "text/event-stream" + assert_nil request.header("anthropic-beta") + end + + def test_api_key_mode_authorization_by_default_api_key_header_and_anthropic_api_version_are_optional_overrides + serve + legacy = {"AUTH_MODE" => "api_key", "CLAUDE_API_KEY" => "sample-key"} + canonical = {"AUTH_MODE" => "api_key", "ANTHROPIC_API_KEY" => "sample-key"} + [ + ["legacy: default header", sample_env(legacy), "authorization", "Bearer sample-key", "2026-10-21"], + ["legacy: resource key header", sample_env(legacy.merge("API_KEY_HEADER" => "x-api-key")), "x-api-key", "sample-key", "2026-10-21"], + ["legacy: explicit version", sample_env(legacy.merge("ANTHROPIC_API_VERSION" => "2023-06-01")), "authorization", "Bearer sample-key", "2023-06-01"], + ["canonical: explicit api_key", canonical_env(canonical), "authorization", "Bearer sample-key", "2026-10-21"], + ["canonical: explicit api_key, resource key header", canonical_env(canonical.merge("API_KEY_HEADER" => "x-api-key")), "x-api-key", "sample-key", "2026-10-21"] + ].each do |label, env, header, expected, version| + cli_calls, cli = counting_cli + status, _stdout, stderr = run_sample([], env, cli: cli) + assert_equal 0, status, "#{label}: #{stderr}" + request = @server.requests.last + assert_equal expected, request.header(header), "#{label} header" + assert_equal version, request.header("anthropic-version"), "#{label} version" + assert_empty cli_calls, "#{label} must not start the Azure CLI" + (%w[authorization x-api-key api-key] - [header]).each { |other| assert_nil request.header(other), "#{label}: #{other} must be absent" } + end + end + + def test_canonical_profile_auth_mode_is_explicit_and_only_anthropic_values_are_used + serve + calls, cli = counting_cli + env = canonical_env( + "ANTHROPIC_BASE_URL" => @server.base_url("/canonical"), "ANTHROPIC_MODEL" => "preferred-model", + "AUTH_MODE" => "bearer", "TOKEN_SCOPE" => "api://example/.default", "AZURE_TENANT_ID" => "tenant-1.example", + "CLAUDE_BASE_URL" => @server.base_url("/legacy-canary"), "CLAUDE_DEPLOYMENT_NAME" => "legacy-model-canary", "CLAUDE_API_KEY" => "legacy-key-canary" + ) + status, _stdout, stderr = run_sample([], env, cli: cli) + assert_equal 0, status, stderr + request = @server.requests.first + assert_equal "/canonical/v1/messages", request.path + assert_equal "preferred-model", request.json["model"] + assert_equal "Bearer entra-test-token", request.header("authorization") + assert_equal [%w[account get-access-token --scope api://example/.default --output json --tenant tenant-1.example]], calls + refute_includes request.wire, "canary" + end + + def test_mixed_families_neither_profile_ever_borrows_a_model_or_key_from_the_other + serve + ambient_anthropic = {"ANTHROPIC_API_KEY" => "ambient-anthropic-key-canary", "ANTHROPIC_MODEL" => "ambient-model-canary", + "ANTHROPIC_AUTH_TOKEN" => "ambient-token-canary"} + legacy_decoys = {"CLAUDE_BASE_URL" => @server.base_url("/legacy-canary"), "CLAUDE_DEPLOYMENT_NAME" => "legacy-model-canary", + "CLAUDE_API_KEY" => "legacy-key-canary"} + { + "legacy profile with ambient ANTHROPIC_* values" => + [sample_env({"AUTH_MODE" => "api_key", "CLAUDE_API_KEY" => "legacy-selected-key"}.merge(ambient_anthropic)), "Bearer legacy-selected-key", MODEL, "/anthropic/v1/messages"], + "canonical profile with every legacy decoy present" => + [canonical_env({"ANTHROPIC_BASE_URL" => @server.base_url("/canonical"), "AUTH_MODE" => "api_key", "ANTHROPIC_API_KEY" => "canonical-selected-key"}.merge(legacy_decoys)), + "Bearer canonical-selected-key", MODEL, "/canonical/v1/messages"], + "both URLs set: the explicit canonical profile wins" => + [{"ANTHROPIC_BASE_URL" => @server.base_url("/canonical"), "ANTHROPIC_MODEL" => "canonical-model", "AUTH_MODE" => "api_key", "ANTHROPIC_API_KEY" => "canonical-selected-key"}.merge(legacy_decoys), + "Bearer canonical-selected-key", "canonical-model", "/canonical/v1/messages"] + }.each do |label, (env, authorization, model, path)| + status, _stdout, stderr = run_sample([], env) + assert_equal 0, status, "#{label}: #{stderr}" + request = @server.requests.last + assert_equal authorization, request.header("authorization"), "#{label}: authorization" + assert_equal model, request.json["model"], "#{label}: model" + assert_equal path, request.path, "#{label}: path" + refute_includes request.wire, "canary", "#{label}: a decoy reached the wire" + end + sent = @server.requests.length + + { + "ambient native endpoint and model never get an Azure token" => [canonical_env("AZURE_TENANT_ID" => "tenant-1.example"), CANONICAL_NEEDS_MODE], + "canonical api_key never falls back to CLAUDE_API_KEY" => [canonical_env("AUTH_MODE" => "api_key", "CLAUDE_API_KEY" => "legacy-key-canary"), CANONICAL_NEEDS_KEY], + "canonical model never falls back to CLAUDE_DEPLOYMENT_NAME" => + [{"ANTHROPIC_BASE_URL" => @server.base_url, "ANTHROPIC_API_KEY" => "k"}.merge(legacy_decoys), CANONICAL_NEEDS_MODEL], + "legacy api_key never falls back to ANTHROPIC_API_KEY" => + [sample_env("AUTH_MODE" => "api_key", "ANTHROPIC_API_KEY" => "ambient-anthropic-key-canary"), LEGACY_NEEDS_KEY], + "legacy model never falls back to ANTHROPIC_MODEL" => [{"CLAUDE_BASE_URL" => @server.base_url}.merge(ambient_anthropic), LEGACY_NEEDS_MODEL] + }.each do |label, (env, expected)| + cli_calls, cli = counting_cli + status, stdout, stderr = run_sample([], env, cli: cli) + assert_equal 1, status, "#{label}: exit status" + assert_equal expected, stderr, "#{label}: stderr" + assert_equal "", stdout, "#{label}: stdout" + assert_empty cli_calls, "#{label}: the Azure CLI must not start" + end + assert_equal sent, @server.requests.length, "a refused configuration sends no request" + end + + def test_missing_mode_canary_the_canonical_profile_without_auth_mode_sends_neither_the_native_key_nor_an_azure_token + serve + ambient = { + "ANTHROPIC_API_KEY" => "ambient-anthropic-key-canary", "AZURE_TENANT_ID" => "tenant-1.example", "TOKEN_SCOPE" => "api://example/.default", + "CLAUDE_BASE_URL" => @server.base_url("/legacy-canary"), "CLAUDE_DEPLOYMENT_NAME" => "legacy-model-canary", "CLAUDE_API_KEY" => "legacy-key-canary" + } + [canonical_env(ambient), canonical_env({"AUTH_MODE" => ""}.merge(ambient))].each do |env| + cli_calls, cli = counting_cli + status, stdout, stderr = run_sample([], env, cli: cli, ambient: ambient) + assert_equal 1, status, "exit status" + assert_equal CANONICAL_NEEDS_MODE, stderr, "stderr" + assert_equal "", stdout, "stdout" + assert_empty cli_calls, "the Azure CLI must not start" + refute_includes stderr + stdout, "canary", "the error must not echo any ambient value" + end + assert_empty @server.requests, "no request, so no native key and no Azure token left the process" + end + + def test_configuration_errors_exit_1_with_a_clear_message_and_make_no_request + serve + { + "no endpoint at all" => [{}, NO_ENDPOINT], + "a legacy model alone is not an endpoint" => [{"CLAUDE_DEPLOYMENT_NAME" => MODEL}, NO_ENDPOINT], + "a canonical model alone is not an endpoint" => [{"ANTHROPIC_MODEL" => MODEL}, NO_ENDPOINT], + "legacy endpoint without its model" => [{"CLAUDE_BASE_URL" => @server.base_url}, LEGACY_NEEDS_MODEL], + "canonical endpoint without its model" => [{"ANTHROPIC_BASE_URL" => @server.base_url}, CANONICAL_NEEDS_MODEL], + "unknown mode" => [sample_env("AUTH_MODE" => "oauth"), "Error: AUTH_MODE must be bearer or api_key.\n"], + "legacy key mode without a key" => [sample_env("AUTH_MODE" => "api_key"), LEGACY_NEEDS_KEY], + "canonical endpoint without AUTH_MODE" => [canonical_env, CANONICAL_NEEDS_MODE], + "canonical api_key without a key" => [canonical_env("AUTH_MODE" => "api_key"), CANONICAL_NEEDS_KEY], + "plain HTTP endpoint" => [{"CLAUDE_BASE_URL" => "http://insecure.example", "CLAUDE_DEPLOYMENT_NAME" => MODEL}, + "Error: base_url must be an HTTPS URL without credentials, query, or fragment.\n"], + "unsafe scope" => [sample_env("TOKEN_SCOPE" => "x&y"), "Error: The token scope may only contain letters, digits and the characters . _ : / -\n"] + }.each do |label, (env, expected)| + status, stdout, stderr = run_sample([], env) + assert_equal 1, status, label + assert_equal expected, stderr, label + assert_equal "", stdout, label + end + assert_empty @server.requests + end + + def test_azure_token_credentials_azure_cli_credential_is_accepted_any_other_explicit_choice_is_refused_and_key_mode_ignores_it + serve + [nil, "AzureCliCredential"].each do |selector| + calls, cli = counting_cli + status, _stdout, stderr = run_sample([], sample_env(selector ? {"AZURE_TOKEN_CREDENTIALS" => selector} : {}), cli: cli) + assert_equal 0, status, "accepted selector #{selector.inspect}: #{stderr}" + assert_equal 1, calls.length, "the Azure CLI supplies the token" + end + + { + "ManagedIdentityCredential" => "ManagedIdentityCredential", "AzureDeveloperCliCredential" => "AzureDeveloperCliCredential", + "DefaultAzureCredential" => "DefaultAzureCredential", "WorkloadIdentityCredential" => "WorkloadIdentityCredential", + "azureclicredential" => "azureclicredential", "Azure\nCliCredential" => "(unprintable or too long)" + }.each do |selector, shown| + calls, cli = counting_cli + requests_before = @server.requests.length + status, stdout, stderr = run_sample([], sample_env("AZURE_TOKEN_CREDENTIALS" => selector), cli: cli) + assert_equal 1, status, "#{shown}: exit status" + assert_equal "Error: AZURE_TOKEN_CREDENTIALS=#{shown} is not supported: the Azure CLI (AzureCliCredential) is this sample's only built-in token " \ + "source. Unset it, or pass your own token provider to ClientFactory for other credentials.\n", stderr, "#{shown}: stderr" + assert_equal "", stdout + assert_empty calls, "#{shown}: the Azure CLI must not start" + assert_equal requests_before, @server.requests.length, "#{shown}: no request" + end + + status, _stdout, stderr = run_sample([], sample_env("AUTH_MODE" => "api_key", "CLAUDE_API_KEY" => "sample-key", "AZURE_TOKEN_CREDENTIALS" => "ManagedIdentityCredential")) + assert_equal 0, status, "key mode ignores the selector: #{stderr}" + end + + def test_the_sample_sets_its_own_120_second_timeout_and_the_factory_itself_keeps_the_sdk_default + serve + assert_equal 120.0, ClaudeSample::Sample::REQUEST_TIMEOUT_SECONDS + client, = with_env { ClaudeSample::Sample.configure(sample_env, CLI_OK) } + assert_equal 120.0, client.timeout + assert_equal Anthropic::Client::DEFAULT_MAX_RETRIES, client.max_retries, "the SDK retries are kept" + assert_equal 600.0, ClaudeSample::ClientFactory.create_client(base_url: @server.base_url, api_key: "sample-key").timeout + end + + def test_a_response_without_text_thinking_only_is_an_error_not_a_silent_success + thinking_only = message_body + thinking_only["content"] = [{"type" => "thinking", "thinking" => "not for display", "signature" => "sample"}] + serve { |_request, _count| LoopbackServer.json_response(thinking_only) } + status, stdout, stderr = run_sample([], sample_env) + assert_equal 1, status + assert_equal "", stdout + assert_equal "Error: No text response (stop_reason=end_turn). Increase max_tokens if the response exhausted its budget.\n", stderr + + events = [ + ["message_start", {"type" => "message_start", "message" => {"id" => "m", "type" => "message", "role" => "assistant", "model" => MODEL, "content" => [], + "stop_reason" => nil, "stop_sequence" => nil, "usage" => {"input_tokens" => 1, "output_tokens" => 1}}}], + ["content_block_start", {"type" => "content_block_start", "index" => 0, "content_block" => {"type" => "thinking", "thinking" => "", "signature" => ""}}], + ["content_block_delta", {"type" => "content_block_delta", "index" => 0, "delta" => {"type" => "thinking_delta", "thinking" => "hidden"}}], + ["content_block_stop", {"type" => "content_block_stop", "index" => 0}], + ["message_delta", {"type" => "message_delta", "delta" => {"stop_reason" => "max_tokens", "stop_sequence" => nil}, "usage" => {"output_tokens" => 9}}], + ["message_stop", {"type" => "message_stop"}] + ] + body = events.map { |type, payload| "event: #{type}\ndata: #{JSON.generate(payload)}\n\n" }.join + serve { |_request, _count| [200, {"content-type" => "text/event-stream"}, body] } + status, stdout, stderr = run_sample(["--stream"], sample_env) + assert_equal 1, status + assert_equal "", stdout + assert_equal "Error: No text response (stop_reason=max_tokens). Increase max_tokens if the response exhausted its budget.\n", stderr + end + + def test_real_api_and_credential_failures_exit_1_and_never_print_the_token + serve { |_request, _count| LoopbackServer.json_response(error_body("authentication_error", "invalid credential"), 401) } + status, stdout, stderr = run_sample([], sample_env) + assert_equal 1, status + assert_equal "", stdout + assert stderr.start_with?("Error: AuthenticationError: "), "the SDK error is named: #{stderr}" + assert_includes stderr, "invalid credential" + refute_includes stderr, "entra-test-token" + + serve { |_request, _count| LoopbackServer.json_response(error_body("api_error", "overloaded"), 500, "x-should-retry" => "false") } + status, _stdout, stderr = run_sample(["--stream"], sample_env) + assert_equal 1, status + assert stderr.start_with?("Error: InternalServerError: "), "the streaming error is reported too: #{stderr}" + + serve + status, stdout, stderr = run_sample([], sample_env, cli: ->(_arguments) { [1, '{"accessToken":"never-printed-token"}'] }) + assert_equal 1, status + assert_equal "", stdout + assert_equal %(Error: Azure CLI exited with code 1 while requesting a token for scope https://ai.azure.com/.default. ) + + %(Run "az login" and retry, or supply your own token provider.\n), stderr + assert_empty @server.requests, "no request without a token" + end + + def test_unknown_arguments_are_a_usage_error_help_prints_usage + serve + status, _stdout, stderr = run_sample(["--bogus"], sample_env) + assert_equal 2, status + assert_equal "Unknown argument: --bogus\nUsage: ruby main.rb [--stream]\n", stderr + status, stdout, = run_sample(["--help"], {}) + assert_equal 0, status + assert_equal "Usage: ruby main.rb [--stream]\n", stdout + end + + def test_ambient_anthropic_credentials_in_the_process_environment_never_reach_the_sample_request + serve + ambient = { + "ANTHROPIC_API_KEY" => "ambient-key-canary", "ANTHROPIC_AUTH_TOKEN" => "ambient-token-canary", + "ANTHROPIC_PROFILE" => "nonexistent-profile-canary", "ANTHROPIC_CUSTOM_HEADERS" => "x-api-key: header-canary\napi-key: alias-canary" + } + [{}, {"AUTH_MODE" => "api_key", "CLAUDE_API_KEY" => "sample-key"}].each do |mode| + status, _stdout, stderr = run_sample([], sample_env(mode), ambient: ambient) + assert_equal 0, status, stderr + refute_includes @server.requests.last.wire, "canary" + end + end +end diff --git a/samples/ruby/test/test_helper.rb b/samples/ruby/test/test_helper.rb new file mode 100644 index 0000000..0e1a33a --- /dev/null +++ b/samples/ruby/test/test_helper.rb @@ -0,0 +1,141 @@ +# frozen_string_literal: true + +# Every gem, Minitest included, comes from the Gemfile (`bundle install`), wherever Bundler put it. +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) +require "bundler/setup" +require "minitest/autorun" +require "json" +require "socket" + +$LOAD_PATH.unshift(File.expand_path("../lib", __dir__)) +require "claude_sample/sample" + +MODEL = "sample-deployment" + +def message_body(text = "OK") + { + "id" => "msg_test", "type" => "message", "role" => "assistant", "model" => MODEL, + "content" => [{"type" => "text", "text" => text}], + "stop_reason" => "end_turn", "stop_sequence" => nil, + "usage" => {"input_tokens" => 1, "output_tokens" => 2} + } +end + +def error_body(type, message) + {"type" => "error", "error" => {"type" => type, "message" => message}} +end + +# A Server-Sent Events body: one text block streamed as the given chunks. +def sse_body(chunks, input: 5, output: 7) + events = [ + ["message_start", {"type" => "message_start", "message" => { + "id" => "msg_stream", "type" => "message", "role" => "assistant", "model" => MODEL, "content" => [], + "stop_reason" => nil, "stop_sequence" => nil, "usage" => {"input_tokens" => input, "output_tokens" => 1} + }}], + ["content_block_start", {"type" => "content_block_start", "index" => 0, "content_block" => {"type" => "text", "text" => ""}}] + ] + chunks.each do |chunk| + events << ["content_block_delta", {"type" => "content_block_delta", "index" => 0, "delta" => {"type" => "text_delta", "text" => chunk}}] + end + events << ["content_block_stop", {"type" => "content_block_stop", "index" => 0}] + events << ["message_delta", {"type" => "message_delta", "delta" => {"stop_reason" => "end_turn", "stop_sequence" => nil}, + "usage" => {"output_tokens" => output}}] + events << ["message_stop", {"type" => "message_stop"}] + events.map { |type, payload| "event: #{type}\ndata: #{JSON.generate(payload)}\n\n" }.join +end + +# A real HTTP server on a loopback port: the SDK's own Net::HTTP transport talks to it, so the tests see the bytes the +# SDK actually sends. The responder returns [status, headers, body] for each request. +class LoopbackServer + Request = Struct.new(:verb, :path, :headers, :body) do + # Header values by lower-case name; a header sent twice has two values. + def header(name) = headers[name.downcase]&.join(", ") + + def json = JSON.parse(body) + + # Everything the request shows on the wire, for canary searches. + def wire = JSON.generate([verb, path, headers, body]) + end + + REASONS = {200 => "OK", 302 => "Found", 307 => "Temporary Redirect"}.freeze + + attr_reader :requests, :port + + def self.json_response(body, status = 200, headers = {}) + [status, {"content-type" => "application/json"}.merge(headers), JSON.generate(body)] + end + + def initialize(&responder) + @responder = responder || ->(_request, _count) { LoopbackServer.json_response(message_body) } + @requests = [] + @server = TCPServer.new("127.0.0.1", 0) + @port = @server.addr[1] + @thread = Thread.new { serve } + end + + def base_url(path = "/anthropic") = "http://127.0.0.1:#{port}#{path}" + + def close + @server.close + @thread.join(5) + end + + private + + def serve + loop { handle(@server.accept) } + rescue IOError, Errno::EBADF + nil + end + + def handle(socket) + verb, path, = socket.gets.to_s.split(" ") + return if verb.nil? + + headers = {} + while (line = socket.gets) && line != "\r\n" + name, value = line.chomp.split(":", 2) + (headers[name.downcase] ||= []) << value.to_s.strip + end + request = Request.new(verb, path, headers, read_body(socket, headers)) + @requests << request + status, response_headers, body = @responder.call(request, @requests.length) + head = +"HTTP/1.1 #{status} #{REASONS.fetch(status, "Status")}\r\n" + response_headers.each { |name, value| head << "#{name}: #{value}\r\n" } + socket.write("#{head}content-length: #{body.bytesize}\r\nconnection: close\r\n\r\n#{body}") + rescue Errno::ECONNRESET, Errno::EPIPE + nil + ensure + socket.close + end + + def read_body(socket, headers) + if headers["transfer-encoding"]&.join&.include?("chunked") + body = +"" + while (size = socket.gets.to_s.to_i(16)).positive? + body << socket.read(size) + socket.gets + end + socket.gets + body + else + socket.read(headers.fetch("content-length", ["0"]).first.to_i).to_s + end + end +end + +module EnvHelper + MANAGED = /\A(?:ANTHROPIC_|CLAUDE_|AZURE_|FAKE_AZ_|AUTH_MODE\z|API_KEY_HEADER\z|TOKEN_SCOPE\z)/ + + # Runs the block with exactly the ANTHROPIC_*, CLAUDE_*, AZURE_*, AUTH_MODE, API_KEY_HEADER, TOKEN_SCOPE and + # FAKE_AZ_* variables in set, and restores the previous environment afterwards. + def with_env(set = {}) + saved = ENV.to_h + ENV.keys.grep(MANAGED).each { |name| ENV.delete(name) } + ENV["ANTHROPIC_CONFIG_DIR"] = File.expand_path("no-profile-here", __dir__) + set.each { |name, value| ENV[name] = value } + yield + ensure + ENV.replace(saved) + end +end diff --git a/samples/typescript/.gitignore b/samples/typescript/.gitignore new file mode 100644 index 0000000..44e4a2b --- /dev/null +++ b/samples/typescript/.gitignore @@ -0,0 +1,3 @@ +node_modules/ +dist/ +*.tsbuildinfo \ No newline at end of file diff --git a/samples/typescript/README.md b/samples/typescript/README.md new file mode 100644 index 0000000..d39d494 --- /dev/null +++ b/samples/typescript/README.md @@ -0,0 +1,146 @@ +# TypeScript sample: standard Anthropic SDK with explicit authentication + +Calls a Claude model with the stock `@anthropic-ai/sdk` client. The credential is chosen explicitly and +resolved again for every HTTP attempt: a Microsoft Entra ID bearer token (default) or an API key. There is +no SDK subclass and no provider-specific SDK package; `createClient` returns a plain `Anthropic` client, so +`messages.create`, `messages.stream`, retries and cancellation work as documented by the SDK. + +| File | Purpose | +| --- | --- | +| `src/client_auth.ts` | Generic helper: `createClient(...)` builds the client (no Azure code, no environment access). | +| `src/token_provider.ts` | Selects one Azure Identity credential and wraps it with `getBearerTokenProvider`. | +| `src/sample_client.ts` | Reads the environment and builds the client for the sample. | +| `src/main.ts` | Command-line entrypoint. | +| `test/` | Offline tests: the real SDK against loopback mock servers, run with Node's built-in test runner. | + +## Requirements + +Node.js 24 or later. The `.ts` files run directly with Node's built-in type stripping, so there is no build +step. Tested with Node.js 24.22 and 26.13, `@anthropic-ai/sdk` 1.1.0 and `@azure/identity` 4.14.0. The SDK source +this sample relies on (the client's credential and header handling, `middleware`, the error classes and the stream +helper) is unchanged in SDK 1.3.0, but 1.3.0 itself has not been tested. + +## Run + +```powershell +cd samples\typescript +npm ci + +$env:ANTHROPIC_BASE_URL = "https://.services.ai.azure.com/anthropic" # or https://api.anthropic.com +$env:ANTHROPIC_MODEL = "" +$env:AUTH_MODE = "bearer" # required with ANTHROPIC_BASE_URL: bearer or api_key +az login # the default credential is the Azure CLI + +npm start # prints the reply text and token usage +npm start -- --stream # streams the reply text as it arrives +npm start -- "Your prompt" # any other prompt +``` + +```bash +cd samples/typescript && npm ci +export ANTHROPIC_BASE_URL="https://.services.ai.azure.com/anthropic" +export ANTHROPIC_MODEL="" +export AUTH_MODE=bearer +npm start +``` + +The starter kit's legacy variables work too: `CLAUDE_BASE_URL` and `CLAUDE_DEPLOYMENT_NAME` (see Configuration). + +To reuse the starter kit's `.env.local`, let Node read it: `node --env-file=../../.env.local src/main.ts`. +Variables already set in the shell take precedence. + +The command exits 0 only when the reply contains text. A reply with only thinking, an empty reply, a +configuration problem or any request error exits nonzero. Errors report the HTTP status and error type, never +the credential, the endpoint, the model name or the response body. + +## Configuration + +The sample reads one of two variable families and never mixes them, so a URL, a model and a key from different +families cannot be combined: an ambient `ANTHROPIC_BASE_URL` for the native API cannot receive an Azure token, and +an ambient first-party `ANTHROPIC_API_KEY` cannot be sent to another endpoint. + +| | Canonical profile | Legacy profile (starter kit) | +| --- | --- | --- | +| Selected by | `ANTHROPIC_BASE_URL`; it wins when both base URLs are set | `CLAUDE_BASE_URL`, when `ANTHROPIC_BASE_URL` is unset | +| Model | `ANTHROPIC_MODEL`, required | `CLAUDE_DEPLOYMENT_NAME`, required | +| `AUTH_MODE` | must be set explicitly: `bearer` or `api_key` | `bearer` when unset, or `api_key` | +| Key for `api_key` | `ANTHROPIC_API_KEY` only | `CLAUDE_API_KEY` only | + +A missing model or key is an error that names the variable the selected profile needs; the other family's +variables are never a fallback. + +These settings apply to both profiles: + +| Variable | Default | Meaning | +| --- | --- | --- | +| `AZURE_TOKEN_CREDENTIALS` | `AzureCliCredential` | `AzureCliCredential`, `AzureDeveloperCliCredential` or `ManagedIdentityCredential`. Exactly one is used; there is no fallback chain. | +| `AZURE_TENANT_ID` | unset | Tenant for the two CLI credentials. | +| `AZURE_CLIENT_ID` | unset | Client ID of a user-assigned managed identity. | +| `TOKEN_SCOPE` | `https://ai.azure.com/.default` | Scope requested for the bearer token. | +| `API_KEY_HEADER` | `Authorization` | `Authorization` sends `Bearer `, the SDK's own scheme. `x-api-key` (or another header name) sends the raw key. | +| `ANTHROPIC_API_VERSION` | unset | Sets `anthropic-version`. When unset the SDK's own value is used. | + +The base URL must be HTTPS; plain HTTP is accepted for loopback hosts. +## What `createClient` guarantees + +```ts +import { createClient } from './src/client_auth.ts'; + +const client = createClient({ baseURL, tokenProvider: () => getToken() }); // Authorization: Bearer +const keyed = createClient({ baseURL, apiKey, keyHeader: 'x-api-key' }); // or a static key +``` + +- **One explicit credential.** `tokenProvider` is called for every HTTP attempt, including each SDK retry, so a + renewed token is picked up. A static `apiKey` goes in `keyHeader` (`Authorization` by default). +- **No ambient credentials.** The SDK is given a non-secret placeholder key, so it never reads + `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, `ANTHROPIC_PROFILE` or a profile on disk. A public `middleware` + then replaces every credential header (`authorization`, `x-api-key`, `api-key` and the selected header) before + each attempt, so credentials from `ANTHROPIC_CUSTOM_HEADERS`, default headers or per-request headers cannot + reach the wire. The placeholder is never sent. Other headers, including `anthropic-beta`, are untouched. +- **No OAuth beta.** The SDK's `credentials` provider path, which adds `anthropic-beta: oauth-2025-04-20` and its + own token cache, is not used (`client.credentials` is `null`). The helper has no cache and no retry of its own. +- **Bound to one origin.** The HTTPS base URL (loopback HTTP for local mocks) fixes the origin. A request to + another origin, for example through `withOptions({ baseURL })` or an absolute URL, fails with `ClientAuthError` + before anything is sent. Redirects are never followed (`redirect: 'manual'`): the SDK reports the 3xx status + as an error and the redirect target is never contacted. +- **SDK behaviour is preserved.** The helper leaves the SDK's retry and timeout defaults alone (`maxRetries` and + `timeoutMs` are applied only when you pass them). `AbortSignal` cancellation (also while a token is being + acquired), status errors (`AuthenticationError`, `PermissionDeniedError`, ...) and streaming are the SDK's. +- **The 120 second limit is the sample's policy, not the helper's.** `src/main.ts` ends the whole call, including + retries and streaming, after 120 seconds (`TOTAL_TIMEOUT_MS`, applied with `AbortSignal.timeout`) and sends + `max_tokens` 1024. + +Keep in mind: + +- Middleware you add after this helper runs closer to the network and can still add headers, and + `withOptions({ middleware })` would replace the helper's. Do not add credentials there. +- The SDK treats an error whose message or cause mentions a timeout as a request timeout and retries it, so a + credential provider that fails with such a message is retried and can surface as `APIConnectionTimeoutError`. +- The SDK's debug logging (`ANTHROPIC_LOG=debug`) redacts a fixed list of header names (`authorization`, + `x-api-key`, `api-key`, ...). With any other `keyHeader`, keep debug logging off. + +## Tokens and caching + +`getBearerTokenProvider` from `@azure/identity` is built on the `@azure/core-rest-pipeline` token cycler: it keeps +the token it received and requests a new one shortly before the credential's reported expiry (two minutes by +default), so the provider is cheap to call for every attempt. That caching comes from the helper, not from the +credential classes; for example `AzureCliCredential` runs `az account get-access-token` each time it is asked. +The tests check this behaviour with a fake credential. `createCredential` passes `AZURE_TENANT_ID` only to the +two CLI credentials and `AZURE_CLIENT_ID` only to `ManagedIdentityCredential`. The two CLI credentials also get a +60 second process timeout (`processTimeoutInMs`). `@azure/identity` sets none by default and aborting the request +does not stop a running `az` or `azd` process, so the timeout is what ends a hung one, and 60 seconds leaves room +for a slow cold start under load. + +## Tests + +```powershell +npm run build # tsc: type-checks src/ and emits plain JavaScript to dist/ (node dist/main.js runs it) +npm test # type-checks src/ and test/, then runs node --test; no network, no credentials +npm run typecheck # tsc --noEmit (strict, erasable syntax only); npm test runs it first +``` + +The tests cover native and `/anthropic` paths, a fresh token for every request and retry, ambient credential and +header canaries (with a control proving the canaries are live), the selected key header and API version, no +OAuth beta, user header and beta pass-through, streaming, 401/403/429/500 statuses, cancellation and timeouts, +cross-origin and redirect safety, variable-family pairing (mixed `ANTHROPIC_*` and `CLAUDE_*` canaries), +credential selection and the command-line exit codes. \ No newline at end of file diff --git a/samples/typescript/package-lock.json b/samples/typescript/package-lock.json new file mode 100644 index 0000000..e8341be --- /dev/null +++ b/samples/typescript/package-lock.json @@ -0,0 +1,1057 @@ +{ + "name": "anthropic-explicit-auth-sample", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "anthropic-explicit-auth-sample", + "version": "0.0.0", + "dependencies": { + "@anthropic-ai/sdk": "1.1.0", + "@azure/identity": "4.14.0" + }, + "devDependencies": { + "@types/node": "26.6.5", + "typescript": "7.0.2" + }, + "engines": { + "node": ">=24" + } + }, + "node_modules/@anthropic-ai/sdk": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-1.1.0.tgz", + "integrity": "sha512-Op/fKMsfVwFCfObc87leLOFlORE0RjOvLzRzPCWWLI7Ww6bobpKR6YmYC8ZYgulRh+m2a/3/61VUXoWHFtCXIw==", + "license": "Apache-2.0", + "dependencies": { + "@opentelemetry/api": "^1.4.1", + "json-schema-to-ts": "^3.1.1", + "standardwebhooks": "^1.0.0" + }, + "bin": { + "anthropic-ai-sdk": "bin/cli" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } + } + }, + "node_modules/@azure/abort-controller": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-2.2.0.tgz", + "integrity": "sha1-k+DoKwGGLn6jtbaZWHGdPz/SyKw=", + "license": "MIT", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@azure/core-auth": { + "version": "1.11.0", + "resolved": "https://registry.npmjs.org/@azure/core-auth/-/core-auth-1.11.0.tgz", + "integrity": "sha1-Ha7/32LRqHHSK4ZfnzFkpj6h9XU=", + "license": "MIT", + "dependencies": { + "@azure/abort-controller": "^2.1.2", + "@azure/core-util": "^1.13.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@azure/core-client": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@azure/core-client/-/core-client-1.11.1.tgz", + "integrity": "sha1-2ZCHiohXdQerETGTW0c0sppjfVg=", + "license": "MIT", + "dependencies": { + "@azure/abort-controller": "^2.1.2", + "@azure/core-auth": "^1.10.0", + "@azure/core-rest-pipeline": "^1.22.0", + "@azure/core-tracing": "^1.3.0", + "@azure/core-util": "^1.13.0", + "@azure/logger": "^1.3.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@azure/core-process": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@azure/core-process/-/core-process-1.0.0.tgz", + "integrity": "sha1-w68cFyI9ZTjhs2ln3clM2uUyy4M=", + "license": "MIT", + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@azure/core-rest-pipeline": { + "version": "1.25.0", + "resolved": "https://registry.npmjs.org/@azure/core-rest-pipeline/-/core-rest-pipeline-1.25.0.tgz", + "integrity": "sha1-kupJEu27H3OV9IKaMAYxF0qoLwg=", + "license": "MIT", + "dependencies": { + "@azure/abort-controller": "^2.1.2", + "@azure/core-auth": "^1.10.0", + "@azure/core-tracing": "^1.3.0", + "@azure/core-util": "^1.13.0", + "@azure/logger": "^1.3.0", + "@typespec/ts-http-runtime": "^0.3.4", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@azure/core-tracing": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@azure/core-tracing/-/core-tracing-1.4.0.tgz", + "integrity": "sha1-1lenAOJNJW0ZXmKKeV22qMxHXqs=", + "license": "MIT", + "dependencies": { + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@azure/core-util": { + "version": "1.14.0", + "resolved": "https://registry.npmjs.org/@azure/core-util/-/core-util-1.14.0.tgz", + "integrity": "sha1-fOn+V5WPEy3UIlc4VuWkXHIyuwQ=", + "license": "MIT", + "dependencies": { + "@azure/abort-controller": "^2.1.2", + "@typespec/ts-http-runtime": "^0.3.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@azure/identity": { + "version": "4.14.0", + "resolved": "https://registry.npmjs.org/@azure/identity/-/identity-4.14.0.tgz", + "integrity": "sha512-8utCLdTZn14CiAe0HW4JbtzUMsc0mdDwnjUvStFMrR4IxQP8S2eL9zVAdplpfORVJGYmidZElpeXRYjJQ4UyUw==", + "license": "MIT", + "dependencies": { + "@azure/abort-controller": "^2.0.0", + "@azure/core-auth": "^1.9.0", + "@azure/core-client": "^1.9.2", + "@azure/core-process": "^1.0.0", + "@azure/core-rest-pipeline": "^1.17.0", + "@azure/core-tracing": "^1.0.0", + "@azure/core-util": "^1.11.0", + "@azure/logger": "^1.0.0", + "@azure/msal-browser": "^5.5.0", + "@azure/msal-node": "^6.0.0", + "open": "^11.0.0", + "tslib": "^2.2.0" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@azure/logger": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@azure/logger/-/logger-1.4.0.tgz", + "integrity": "sha1-PVpif+WaJ27OdIenndkq1cUIwzk=", + "license": "MIT", + "dependencies": { + "@typespec/ts-http-runtime": "^0.3.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/@azure/msal-browser": { + "version": "5.27.0", + "resolved": "https://registry.npmjs.org/@azure/msal-browser/-/msal-browser-5.27.0.tgz", + "integrity": "sha512-i2CKKyuCuOZEBZJiAoFK/viYZAP6CRaqqlkeHl3ViteDHOUE/tkI/Slq1cdGnwhkIB+k1OE0g00QGl9O0gAFNQ==", + "license": "MIT", + "dependencies": { + "@azure/msal-common": "16.15.0" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/@azure/msal-common": { + "version": "16.15.0", + "resolved": "https://registry.npmjs.org/@azure/msal-common/-/msal-common-16.15.0.tgz", + "integrity": "sha512-lwdLb1B9Q5nEhPLVIKe78XH5wFMN15fCiDkY7ylPDSWZuWcD93G3jpJajrKhO3CQld8SLKz0sHiOi24mxdvtsg==", + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/@azure/msal-node": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/@azure/msal-node/-/msal-node-6.0.1.tgz", + "integrity": "sha1-SLnVpHLxa0A706MklCJ+z8VMr9Q=", + "license": "MIT", + "dependencies": { + "@azure/msal-common": "16.14.1", + "jsonwebtoken": "^9.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@azure/msal-node/node_modules/@azure/msal-common": { + "version": "16.14.1", + "resolved": "https://registry.npmjs.org/@azure/msal-common/-/msal-common-16.14.1.tgz", + "integrity": "sha1-LJh/MdqFjlROcrb6qYb+zbPeIPg=", + "license": "MIT", + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/@babel/runtime": { + "version": "7.29.10", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.10.tgz", + "integrity": "sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@opentelemetry/api": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.10.0.tgz", + "integrity": "sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/@stablelib/base64": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz", + "integrity": "sha1-vfwcbTpi16O3u8ZbbM4btFYWQb4=", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "26.6.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz", + "integrity": "sha512-uMzsv9stDdofIZBx4UGh4Z9ZgXnGC9seRDscilBcTHAeOFk67MZg/k9bWVfO+bk4qZmG+l52hRnLwUiH2LnJTg==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha1-zcfOgdYPHgkDSWDd+x+4gNendrY=", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha1-pV/fz6WN9Y0n2yI3zealweNacjU=", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha1-ONHJFygAqR1we+xk0qNwoBZjTbQ=", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha1-8f+IEAMLNdK1vg22otxlBGDqlPo=", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha1-PYawPzU8WxupUWLrbONVM7/ClL0=", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha1-rZS0HhruKk3MaimMe2fEM0X94y4=", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha1-2TNNltbaxv+F2pyGVYiUjek56R8=", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha1-KWWu5PyHM2ATnYk9qv5jl6KROK0=", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha1-Goh6MRvtOoM/gL/Uqe03wnGTbPA=", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha1-i2PJsvRFs5PrTkPsIdoiXa3jV30=", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha1-tuijXCibPql6kqQdRhqu7Q07NuE=", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha1-Lvlmk75IYfbReWVCflsAnLvtGj4=", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha1-cyacsLq6UK6gygYERaa4jlg/HOI=", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha1-OjZJ+X+vohC05uN5jBXgZgXIqQE=", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha1-R+xZSRpAxHDSgH3E0rglUo/Zeas=", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha1-eWvo2gvZidij+5bygB44qDZbS68=", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha1-03/ipynrlCwHbEVO5/GBX699Vg8=", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha1-q6jTRkw1ZacER4m6upaRa9SrLIg=", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha1-ud5QoXGWOD9iYgtfnQovNK07YNc=", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha1-zzt7DWzlY12spMjgHBic3N5H7Dw=", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typespec/ts-http-runtime": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@typespec/ts-http-runtime/-/ts-http-runtime-0.3.9.tgz", + "integrity": "sha1-MyhVu9cpqzbgd5st/CTtySDRJGE=", + "license": "MIT", + "dependencies": { + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.0", + "tslib": "^2.6.2" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha1-48121MVI7oldPD/Y3B9sW5Ay56g=", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk=", + "license": "BSD-3-Clause" + }, + "node_modules/bundle-name": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/bundle-name/-/bundle-name-4.1.1.tgz", + "integrity": "sha512-DdH81/zPLVS11EUgWq3tEu/xn+EzljlMYooDNdzWEnFha3R3NBMpMV1UqYIpjYHV/SgpFKMIX1Oh7o06SjM/oA==", + "license": "MIT", + "dependencies": { + "run-applescript": "^7.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha1-xq5DLZvZZiWC/OCHCbA4xY6ePWo=", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/default-browser": { + "version": "5.5.1", + "resolved": "https://registry.npmjs.org/default-browser/-/default-browser-5.5.1.tgz", + "integrity": "sha1-F5Cv/FJoD7sR4XyrJ1LWmqKjfSw=", + "license": "MIT", + "dependencies": { + "bundle-name": "^4.1.0", + "default-browser-id": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/default-browser-id": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/default-browser-id/-/default-browser-id-5.0.1.tgz", + "integrity": "sha1-96fMuPUQS/jg9xujscz6Xq/bIeg=", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/define-lazy-prop": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-3.0.0.tgz", + "integrity": "sha1-27Ga37dG1/xtc0oGty9KANAhJV8=", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha1-rg8PothQRe8UqBfao86azQSJ5b8=", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, + "node_modules/fast-sha256": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz", + "integrity": "sha1-eRa6IFTuslWYJgjMzQ9mYMebeuY=", + "license": "Unlicense" + }, + "node_modules/http-proxy-agent": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", + "integrity": "sha1-mosfJGhmwChQlIZYX2K48sGMJw4=", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha1-2o3+rH2hMLBcK6S1nJts1mYRprk=", + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/is-docker": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-3.0.0.tgz", + "integrity": "sha1-kAk6oxBid9inelkQ265xdH4VogA=", + "license": "MIT", + "bin": { + "is-docker": "cli.js" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-in-ssh": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-in-ssh/-/is-in-ssh-1.0.0.tgz", + "integrity": "sha1-jrc8HKu6d3SNOJWI7uoTKmMFdiI=", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-inside-container": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-inside-container/-/is-inside-container-1.0.0.tgz", + "integrity": "sha1-6B+6aZZi6zHb2vJnZqYdSBRxfqQ=", + "license": "MIT", + "dependencies": { + "is-docker": "^3.0.0" + }, + "bin": { + "is-inside-container": "cli.js" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-wsl": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-3.1.1.tgz", + "integrity": "sha1-MniXsmgyo+sRfabCdJLQTKEyWU8=", + "license": "MIT", + "dependencies": { + "is-inside-container": "^1.0.0" + }, + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/json-schema-to-ts": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz", + "integrity": "sha1-gfOsr1o0c2SS9vX1GHDvns4cqFM=", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.18.3", + "ts-algebra": "^2.0.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/jsonwebtoken": { + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz", + "integrity": "sha1-bNV6sB6bCsB8uEfVPTybbuMfeuI=", + "license": "MIT", + "dependencies": { + "jws": "^4.0.1", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1", + "semver": "^7.5.4" + }, + "engines": { + "node": ">=12", + "npm": ">=6" + } + }, + "node_modules/jwa": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", + "integrity": "sha1-v4F20a0M1y4PP1gzhZWhPhELyAQ=", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz", + "integrity": "sha1-B+3Bvo+sIOZ3soPs4mFJi9OPBpA=", + "license": "MIT", + "dependencies": { + "jwa": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/lodash.includes": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", + "integrity": "sha1-YLuYqHy5I8aMoeUTJUgzFISfVT8=", + "license": "MIT" + }, + "node_modules/lodash.isboolean": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", + "integrity": "sha1-bC4XHbKiV82WgC/UOwGyDV9YcPY=", + "license": "MIT" + }, + "node_modules/lodash.isinteger": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", + "integrity": "sha1-YZwK89A/iwTDH1iChAt3sRzWg0M=", + "license": "MIT" + }, + "node_modules/lodash.isnumber": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", + "integrity": "sha1-POdoEMWSjQM1IwGsKHMX8RwLH/w=", + "license": "MIT" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", + "integrity": "sha1-fFJqUtibRcRcxpC4gWO+BJf1UMs=", + "license": "MIT" + }, + "node_modules/lodash.isstring": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", + "integrity": "sha1-1SfftUVuynzJu5XV2ur4i6VKVFE=", + "license": "MIT" + }, + "node_modules/lodash.once": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", + "integrity": "sha1-DdOXEhPHxW34gJd9UEyI+0cal6w=", + "license": "MIT" + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha1-V0yBOM4dK1hh8LRFedut1gxmFbI=", + "license": "MIT" + }, + "node_modules/open": { + "version": "11.0.4", + "resolved": "https://registry.npmjs.org/open/-/open-11.0.4.tgz", + "integrity": "sha512-++Zlftm0kVLPmzC06t6epuWmcRMDbI4z5P3NNX979WA/k23+NtSOynEGzsVfZwguKw2mi5umVgnBlJQMwRz4Pg==", + "license": "MIT", + "dependencies": { + "default-browser": "^5.5.1", + "define-lazy-prop": "^3.0.0", + "is-in-ssh": "^1.0.0", + "is-inside-container": "^1.0.0", + "powershell-utils": "^0.2.1", + "wsl-utils": "^1.0.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/powershell-utils": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/powershell-utils/-/powershell-utils-0.2.1.tgz", + "integrity": "sha1-CFMBb1s8EtUrlXHI/oBZZ32d2+I=", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/run-applescript": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/run-applescript/-/run-applescript-7.1.0.tgz", + "integrity": "sha1-Lp5UxGZOwxBsW1Yw4knT1llcSRE=", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha1-Hq+fqb2x/dTsdfWPnNtOa3gn7sY=", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha1-ObZGA33VDBT7RR5+TKxY7YuGP2k=", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/standardwebhooks": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.1.1.tgz", + "integrity": "sha1-JbmPorvk7a17QneBNckjVj49Xi8=", + "license": "MIT", + "dependencies": { + "@stablelib/base64": "^1.0.0", + "fast-sha256": "^1.3.0" + } + }, + "node_modules/ts-algebra": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz", + "integrity": "sha1-Tj4JU4ePJlGPzn9rsRUGSmU4i3o=", + "license": "MIT" + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha1-YS7+TtI11Wfoq6Xypfq3AoCt6D8=", + "license": "0BSD" + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha1-nsdz15VKjBgsF8xbvVdaoovFFYI=", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha1-4kDZfItdheU0fOc9JYZceQbB7J8=", + "dev": true, + "license": "MIT" + }, + "node_modules/wsl-utils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/wsl-utils/-/wsl-utils-1.0.1.tgz", + "integrity": "sha512-c16PKLIRxBYpR3jSWsdS7SFp0COm5SOQdiFjY818dYFHJbMGuLBszpF07LBWmOS1uzrHa9VGdynsEgoeKy0oOQ==", + "license": "MIT", + "dependencies": { + "is-wsl": "^3.1.0", + "powershell-utils": "^0.2.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + } + } +} diff --git a/samples/typescript/package.json b/samples/typescript/package.json new file mode 100644 index 0000000..abbe8c8 --- /dev/null +++ b/samples/typescript/package.json @@ -0,0 +1,25 @@ +{ + "name": "anthropic-explicit-auth-sample", + "version": "0.0.0", + "private": true, + "description": "Standard Anthropic TypeScript SDK sample with explicit, renewable authentication.", + "type": "module", + "engines": { + "node": ">=24" + }, + "scripts": { + "build": "tsc -p tsconfig.build.json", + "start": "node src/main.ts", + "typecheck": "tsc --noEmit", + "pretest": "npm run typecheck", + "test": "node --test --test-timeout=60000 \"test/*.test.ts\"" + }, + "dependencies": { + "@anthropic-ai/sdk": "1.1.0", + "@azure/identity": "4.14.0" + }, + "devDependencies": { + "@types/node": "26.6.5", + "typescript": "7.0.2" + } +} \ No newline at end of file diff --git a/samples/typescript/src/client_auth.ts b/samples/typescript/src/client_auth.ts new file mode 100644 index 0000000..05963aa --- /dev/null +++ b/samples/typescript/src/client_auth.ts @@ -0,0 +1,163 @@ +/** + * Builds a stock `Anthropic` client whose credential is chosen explicitly and + * resolved for every HTTP attempt. + * + * The helper only uses public SDK options: an explicit non-secret placeholder + * `apiKey` (so the SDK never looks at ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, + * ANTHROPIC_PROFILE or a profile on disk) and one `middleware`. The middleware + * runs for each attempt, including SDK retries, and: + * - refuses any request whose origin differs from the configured base URL; + * - replaces every credential-bearing header (SDK, ambient and per-request) + * with the single selected credential; + * - forces `redirect: "manual"`, so a redirect is never followed and the SDK + * reports the redirect status as an error. + * It does not use the SDK's `credentials` provider path, so no OAuth beta + * header is added and no SDK token cache or 401 refresh is involved. + */ +import Anthropic, { AnthropicError, type ClientOptions, type Middleware } from '@anthropic-ai/sdk'; + +/** Returns the credential for one HTTP attempt; it is called again for each retry. */ +export type CredentialProvider = () => string | Promise; + +export interface CreateClientOptions { + /** Messages API base URL. HTTPS only; plain HTTP is accepted for loopback hosts. */ + baseURL: string; + /** Bearer-token callback, sent as `Authorization: Bearer `. Pass this or `apiKey`. */ + tokenProvider?: CredentialProvider; + /** Static API key. Pass this or `tokenProvider`. */ + apiKey?: string; + /** Header that carries `apiKey`: `Authorization` (sent as `Bearer `) or a raw-key header such as `x-api-key`. */ + keyHeader?: string; + /** Overrides the SDK's `anthropic-version` header; the SDK default applies when omitted. */ + apiVersion?: string; + /** SDK retry count; the SDK default applies when omitted. */ + maxRetries?: number; + /** SDK timeout for one HTTP attempt, in milliseconds; the SDK default applies when omitted. */ + timeoutMs?: number; + /** Alternate `fetch`, for tests or a custom transport. */ + fetch?: ClientOptions['fetch']; +} + +/** Raised before a request is sent when the credential cannot be applied safely. */ +export class ClientAuthError extends AnthropicError { + override name = 'ClientAuthError'; +} + +/** Sent to the SDK in place of a credential; the middleware always replaces it, so it never reaches the network. */ +export const PLACEHOLDER_CREDENTIAL = 'provided-by-request-middleware'; + +const CREDENTIAL_HEADERS = ['authorization', 'x-api-key', 'api-key']; +const HEADER_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; +const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']); + +export function createClient(options: CreateClientOptions): Anthropic { + const url = parseBaseURL(options.baseURL); + const { tokenProvider, apiKey } = options; + if ((tokenProvider === undefined) === (apiKey === undefined)) { + throw new TypeError('Provide exactly one of tokenProvider or apiKey.'); + } + if (tokenProvider !== undefined && typeof tokenProvider !== 'function') { + throw new TypeError('tokenProvider must be a function.'); + } + if (apiKey !== undefined && !isSecret(apiKey)) { + throw new TypeError('apiKey must be a nonempty, single-line string.'); + } + const keyHeader = options.keyHeader ?? 'Authorization'; + if (!HEADER_NAME.test(keyHeader)) { + throw new TypeError('keyHeader must be a valid HTTP header name.'); + } + if (options.apiVersion !== undefined && !/^[\x21-\x7e]+$/.test(options.apiVersion)) { + throw new TypeError('apiVersion must be a nonempty string of printable ASCII characters.'); + } + if (options.timeoutMs !== undefined && (!Number.isInteger(options.timeoutMs) || options.timeoutMs <= 0)) { + throw new TypeError('timeoutMs must be a positive integer.'); + } + + const source: CredentialProvider = tokenProvider ?? (() => apiKey as string); + const header = tokenProvider !== undefined ? 'Authorization' : keyHeader; + const bearer = header.toLowerCase() === 'authorization'; + const origin = url.origin; + + const authorize: Middleware = async (request, next) => { + if (!sameOrigin(request.url, origin)) { + throw new ClientAuthError('Refusing to send credentials to a different origin.'); + } + const value = await acquire(source, request.signal); + const headers = new Headers(request.headers); + for (const name of CREDENTIAL_HEADERS) headers.delete(name); + headers.delete(header); + try { + headers.set(header, bearer ? `Bearer ${value}` : value); + } catch { + // The runtime's own error text can echo the rejected value, so it is not kept. + throw new ClientAuthError('The credential is not a valid HTTP header value.'); + } + return next({ ...request, headers, redirect: 'manual' }); + }; + + const sdkOptions: ClientOptions = { + baseURL: options.baseURL, + apiKey: PLACEHOLDER_CREDENTIAL, + webhookKey: null, + middleware: [authorize], + }; + if (options.maxRetries !== undefined) sdkOptions.maxRetries = options.maxRetries; + if (options.timeoutMs !== undefined) sdkOptions.timeout = options.timeoutMs; + if (options.apiVersion !== undefined) sdkOptions.defaultHeaders = { 'anthropic-version': options.apiVersion }; + if (options.fetch !== undefined) sdkOptions.fetch = options.fetch; + return new Anthropic(sdkOptions); +} + +function parseBaseURL(baseURL: string): URL { + const invalid = () => new TypeError('baseURL must be an HTTPS URL without credentials, query, or fragment.'); + let url: URL; + try { + url = new URL(baseURL); + } catch { + throw invalid(); + } + const secure = url.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname)); + if (!secure || !url.hostname || url.username || url.password || url.search || url.hash) throw invalid(); + return url; +} + +function sameOrigin(requestURL: string, origin: string): boolean { + try { + return new URL(requestURL).origin === origin; + } catch { + return false; + } +} + +function isSecret(value: unknown): value is string { + return typeof value === 'string' && value.trim() !== '' && !/[\r\n]/.test(value); +} + +async function acquire(source: CredentialProvider, signal: AbortSignal | null | undefined): Promise { + let value: unknown; + try { + value = await untilAborted(Promise.resolve().then(source), signal); + } catch (error) { + // An abort is rethrown as is so the SDK reports it as a cancellation. + if (signal?.aborted) throw error; + throw new ClientAuthError('The credential provider failed.', { cause: error }); + } + if (!isSecret(value)) { + throw new ClientAuthError('The credential provider must return a nonempty, single-line string.'); + } + return value; +} + +function untilAborted(promise: Promise, signal: AbortSignal | null | undefined): Promise { + if (!signal) return promise; + const reason = () => signal.reason ?? new DOMException('This operation was aborted', 'AbortError'); + if (signal.aborted) { + promise.catch(() => {}); + return Promise.reject(reason()); + } + return new Promise((resolve, reject) => { + const abort = () => reject(reason()); + signal.addEventListener('abort', abort, { once: true }); + promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', abort)); + }); +} \ No newline at end of file diff --git a/samples/typescript/src/config_error.ts b/samples/typescript/src/config_error.ts new file mode 100644 index 0000000..a6e9b56 --- /dev/null +++ b/samples/typescript/src/config_error.ts @@ -0,0 +1,4 @@ +/** A problem with the sample's environment configuration; the message names only variables, never values. */ +export class ConfigError extends Error { + override name = 'ConfigError'; +} \ No newline at end of file diff --git a/samples/typescript/src/main.ts b/samples/typescript/src/main.ts new file mode 100644 index 0000000..6972c4c --- /dev/null +++ b/samples/typescript/src/main.ts @@ -0,0 +1,154 @@ +/** + * Calls a Claude model through the standard Anthropic SDK. + * + * node src/main.ts print the reply text and token usage + * node src/main.ts --stream stream the reply text as it arrives + * node src/main.ts "your prompt" use your own prompt + * + * Exits 0 only when the reply has text; thinking-only or empty replies and every + * error exit nonzero. Errors report the HTTP status and error type but never the + * credential, endpoint, model name or response body. + */ +import { parseArgs } from 'node:util'; + +import type Anthropic from '@anthropic-ai/sdk'; +import { APIConnectionError, APIConnectionTimeoutError, APIError, APIUserAbortError } from '@anthropic-ai/sdk'; + +import { ClientAuthError } from './client_auth.ts'; +import { ConfigError } from './config_error.ts'; +import { configuredClient, loadSettings, type ClientOverrides, type Environment } from './sample_client.ts'; + +const DEFAULT_PROMPT = 'What are 3 things to visit in Seattle?'; +const MAX_TOKENS = 1024; +// Application policy of this sample, not a helper default: the whole call, including SDK retries and +// streaming, ends after 120 seconds. The SDK's own per-attempt timeout and retry defaults are untouched. +const TOTAL_TIMEOUT_MS = 120_000; +const USAGE = 'Usage: node src/main.ts [--stream] [prompt...]'; + +export interface Output { + write(text: string): unknown; +} + +export interface RunIO { + stdout: Output; + stderr: Output; +} + +export interface RunOptions extends ClientOverrides { + /** Deadline for the whole call, including SDK retries and streaming. */ + totalTimeoutMs?: number; +} + +interface MessageRequest { + model: string; + max_tokens: number; + messages: Array<{ role: 'user'; content: string }>; +} + +export async function run(argv: readonly string[], env: Environment, io: RunIO, options: RunOptions = {}): Promise { + let command: { stream: boolean; help: boolean; prompt: string }; + try { + command = parseCommandLine(argv); + } catch { + io.stderr.write(`${USAGE}\n`); + return 2; + } + if (command.help) { + io.stdout.write(`${USAGE}\n`); + return 0; + } + + const totalTimeoutMs = options.totalTimeoutMs ?? TOTAL_TIMEOUT_MS; + const signal = AbortSignal.timeout(totalTimeoutMs); + try { + const settings = loadSettings(env); + const client = configuredClient(settings, options); + const request: MessageRequest = { + model: settings.model, + max_tokens: MAX_TOKENS, + messages: [{ role: 'user', content: command.prompt }], + }; + return command.stream ? await streamReply(client, request, signal, io) : await printReply(client, request, signal, io); + } catch (error) { + io.stderr.write(`${describeError(error, signal, totalTimeoutMs)}\n`); + return 1; + } +} + +function parseCommandLine(argv: readonly string[]): { stream: boolean; help: boolean; prompt: string } { + const { values, positionals } = parseArgs({ + args: [...argv], + options: { stream: { type: 'boolean' }, help: { type: 'boolean', short: 'h' } }, + allowPositionals: true, + }); + return { + stream: values.stream === true, + help: values.help === true, + prompt: positionals.join(' ').trim() || DEFAULT_PROMPT, + }; +} + +async function printReply(client: Anthropic, request: MessageRequest, signal: AbortSignal, io: RunIO): Promise { + const message = await client.messages.create(request, { signal }); + let hasText = false; + for (const block of message.content) { + if (block.type === 'text' && block.text.trim()) { + io.stdout.write(`${block.text}\n`); + hasText = true; + } + } + if (!hasText) return noText(message.stop_reason, io); + io.stdout.write(`\n[usage] input=${message.usage.input_tokens} output=${message.usage.output_tokens}\n`); + return 0; +} + +async function streamReply(client: Anthropic, request: MessageRequest, signal: AbortSignal, io: RunIO): Promise { + const stream = client.messages.stream(request, { signal }); + let hasText = false; + stream.on('text', (delta) => { + if (delta.trim()) hasText = true; + io.stdout.write(delta); + }); + const message = await stream.finalMessage(); + io.stdout.write('\n'); + return hasText ? 0 : noText(message.stop_reason, io); +} + +function noText(stopReason: string | null, io: RunIO): number { + io.stderr.write(`No text response (stop_reason=${stopReason}). Increase max_tokens if the response exhausted its budget.\n`); + return 1; +} + +const HTTP_HINTS: Array<[(status: number) => boolean, string]> = [ + [(status) => status >= 300 && status < 400, 'The endpoint answered with a redirect, which is never followed.'], + [(status) => status === 401, 'The credential was rejected. Check AUTH_MODE, the token scope or the API key.'], + [(status) => status === 403, 'The caller is not permitted to use this resource. Check its role assignment or key.'], + [(status) => status === 404, 'The endpoint path or model name was not found. Check the base URL and model settings.'], + [(status) => status === 429, 'The request was rate limited. Retry later.'], + [(status) => status >= 500, 'The service reported an error. Retry later.'], +]; + +function describeError(error: unknown, signal: AbortSignal, totalTimeoutMs: number): string { + if (error instanceof ConfigError) return error.message; + if (error instanceof ClientAuthError) { + const cause = error.cause instanceof Error ? ` Cause: ${error.cause.name}.` : ''; + const hint = cause ? ' Sign in with the Azure CLI or select another AZURE_TOKEN_CREDENTIALS.' : ''; + return `${error.message}${cause}${hint}`; + } + if (error instanceof APIUserAbortError) { + return signal.aborted ? `Request timed out after ${totalTimeoutMs / 1000} seconds.` : 'Request was cancelled.'; + } + if (error instanceof APIConnectionTimeoutError) return 'Request timed out.'; + if (error instanceof APIConnectionError) return 'Could not connect to the endpoint.'; + if (error instanceof APIError) { + const type = (error.error as { error?: { type?: unknown } } | undefined)?.error?.type; + const label = typeof type === 'string' && /^[a-z_]{1,64}$/.test(type) ? ` (${type})` : ''; + const hint = HTTP_HINTS.find(([matches]) => matches(error.status ?? 0))?.[1]; + return `Request failed with HTTP ${error.status}${label}.${hint ? ` ${hint}` : ''}`; + } + return `Unexpected error (${error instanceof Error ? error.name : typeof error}).`; +} + +if (import.meta.main) { + process.exitCode = await run(process.argv.slice(2), process.env, process); +} \ No newline at end of file diff --git a/samples/typescript/src/sample_client.ts b/samples/typescript/src/sample_client.ts new file mode 100644 index 0000000..79d2af3 --- /dev/null +++ b/samples/typescript/src/sample_client.ts @@ -0,0 +1,132 @@ +/** Environment configuration shared by the sample entrypoint. */ +import type Anthropic from '@anthropic-ai/sdk'; + +import { createClient, type CreateClientOptions, type CredentialProvider } from './client_auth.ts'; +import { ConfigError } from './config_error.ts'; +import { createCredential, createTokenProvider } from './token_provider.ts'; + +export type Environment = Readonly>; + +export const DEFAULT_TOKEN_SCOPE = 'https://ai.azure.com/.default'; + +/** `anthropic` is the canonical ANTHROPIC_* family, `claude` the legacy CLAUDE_* family. */ +export type Profile = 'anthropic' | 'claude'; + +export type SampleAuth = + | { mode: 'bearer'; credential: string; tenantId: string | undefined; clientId: string | undefined; scope: string } + | { mode: 'api_key'; apiKey: string; keyHeader: string }; + +export interface SampleSettings { + profile: Profile; + baseURL: string; + model: string; + /** Sent as `anthropic-version` only when ANTHROPIC_API_VERSION is set; otherwise the SDK default applies. */ + apiVersion: string | undefined; + auth: SampleAuth; +} + +export interface ClientOverrides { + /** Replaces the Microsoft Entra ID token provider. */ + tokenProvider?: CredentialProvider; + fetch?: CreateClientOptions['fetch']; + maxRetries?: number; + timeoutMs?: number; +} + +interface ProfileVariables { + baseURL: string; + model: string; + apiKey: string; + /** The other family's variables, named in errors only; they are never read for this profile. */ + otherModel: string; + otherKey: string; + /** The canonical profile never defaults to a token: an ambient URL must not silently receive one. */ + explicitAuthMode: boolean; +} + +const PROFILES: Record = { + anthropic: { + baseURL: 'ANTHROPIC_BASE_URL', + model: 'ANTHROPIC_MODEL', + apiKey: 'ANTHROPIC_API_KEY', + otherModel: 'CLAUDE_DEPLOYMENT_NAME', + otherKey: 'CLAUDE_API_KEY', + explicitAuthMode: true, + }, + claude: { + baseURL: 'CLAUDE_BASE_URL', + model: 'CLAUDE_DEPLOYMENT_NAME', + apiKey: 'CLAUDE_API_KEY', + otherModel: 'ANTHROPIC_MODEL', + otherKey: 'ANTHROPIC_API_KEY', + explicitAuthMode: false, + }, +}; + +/** + * ANTHROPIC_BASE_URL selects the canonical profile, otherwise CLAUDE_BASE_URL selects the legacy one. + * The URL, model and key all come from the selected family, so a value from one family is never + * combined with another family's endpoint. + */ +export function loadSettings(env: Environment): SampleSettings { + const canonicalURL = env['ANTHROPIC_BASE_URL']; + const legacyURL = env['CLAUDE_BASE_URL']; + const profile: Profile | undefined = canonicalURL ? 'anthropic' : legacyURL ? 'claude' : undefined; + const baseURL = canonicalURL || legacyURL; + if (profile === undefined || !baseURL) { + throw new ConfigError('Set ANTHROPIC_BASE_URL, ANTHROPIC_MODEL and AUTH_MODE, or the legacy CLAUDE_BASE_URL and CLAUDE_DEPLOYMENT_NAME.'); + } + const names = PROFILES[profile]; + + const model = env[names.model]; + if (!model) { + throw new ConfigError(`${names.baseURL} is set, so ${names.model} is required; ${names.otherModel} is not used with it.`); + } + const requestedMode = env['AUTH_MODE']; + if (!requestedMode && names.explicitAuthMode) { + throw new ConfigError(`${names.baseURL} is set, so AUTH_MODE must be set explicitly to bearer or api_key.`); + } + const mode = requestedMode || 'bearer'; + const apiVersion = env['ANTHROPIC_API_VERSION'] || undefined; + + if (mode === 'bearer') { + return { + profile, + baseURL, + model, + apiVersion, + auth: { + mode, + credential: env['AZURE_TOKEN_CREDENTIALS'] || 'AzureCliCredential', + tenantId: env['AZURE_TENANT_ID'] || undefined, + clientId: env['AZURE_CLIENT_ID'] || undefined, + scope: env['TOKEN_SCOPE'] || DEFAULT_TOKEN_SCOPE, + }, + }; + } + if (mode === 'api_key') { + const apiKey = env[names.apiKey]; + if (!apiKey) { + throw new ConfigError(`AUTH_MODE=api_key with ${names.baseURL} requires ${names.apiKey}; ${names.otherKey} is not used with it.`); + } + return { profile, baseURL, model, apiVersion, auth: { mode, apiKey, keyHeader: env['API_KEY_HEADER'] || 'Authorization' } }; + } + throw new ConfigError('AUTH_MODE must be bearer or api_key.'); +} + +export function configuredClient(settings: SampleSettings, overrides: ClientOverrides = {}): Anthropic { + const shared: Omit = {}; + if (settings.apiVersion !== undefined) shared.apiVersion = settings.apiVersion; + if (overrides.fetch !== undefined) shared.fetch = overrides.fetch; + if (overrides.maxRetries !== undefined) shared.maxRetries = overrides.maxRetries; + if (overrides.timeoutMs !== undefined) shared.timeoutMs = overrides.timeoutMs; + + const { auth } = settings; + if (auth.mode === 'api_key') { + return createClient({ ...shared, baseURL: settings.baseURL, apiKey: auth.apiKey, keyHeader: auth.keyHeader }); + } + const tokenProvider = + overrides.tokenProvider ?? + createTokenProvider(createCredential(auth.credential, { tenantId: auth.tenantId, clientId: auth.clientId }), auth.scope); + return createClient({ ...shared, baseURL: settings.baseURL, tokenProvider }); +} \ No newline at end of file diff --git a/samples/typescript/src/token_provider.ts b/samples/typescript/src/token_provider.ts new file mode 100644 index 0000000..c990814 --- /dev/null +++ b/samples/typescript/src/token_provider.ts @@ -0,0 +1,71 @@ +/** Explicit Microsoft Entra ID credential selection and bearer-token acquisition. */ +import { + AzureCliCredential, + AzureDeveloperCliCredential, + ManagedIdentityCredential, + getBearerTokenProvider, + type TokenCredential, +} from '@azure/identity'; + +import { ConfigError } from './config_error.ts'; + +export const CREDENTIAL_CHOICES = ['AzureCliCredential', 'AzureDeveloperCliCredential', 'ManagedIdentityCredential'] as const; + +/** Both CLI credentials start a process for each token request; this leaves room for a cold start under load. */ +export const CLI_PROCESS_TIMEOUT_MS = 60_000; + +export interface CliCredentialOptions { + tenantId?: string; + processTimeoutInMs?: number; +} + +export interface CredentialConstructors { + AzureCliCredential: new (options?: CliCredentialOptions) => TokenCredential; + AzureDeveloperCliCredential: new (options?: CliCredentialOptions) => TokenCredential; + ManagedIdentityCredential: new (options?: { clientId?: string }) => TokenCredential; +} + +export interface CredentialIds { + tenantId?: string | undefined; + clientId?: string | undefined; +} + +const AZURE_IDENTITY_CREDENTIALS: CredentialConstructors = { + AzureCliCredential, + AzureDeveloperCliCredential, + ManagedIdentityCredential, +}; + +const cliOptions = (tenantId: string | undefined): CliCredentialOptions => + tenantId ? { tenantId, processTimeoutInMs: CLI_PROCESS_TIMEOUT_MS } : { processTimeoutInMs: CLI_PROCESS_TIMEOUT_MS }; + +/** + * Builds exactly the credential named by AZURE_TOKEN_CREDENTIALS, with no fallback chain. + * The tenant applies to the two CLI credentials, which also get a process timeout, and the + * client ID to the managed identity. + */ +export function createCredential( + source: string, + ids: CredentialIds = {}, + constructors: CredentialConstructors = AZURE_IDENTITY_CREDENTIALS, +): TokenCredential { + switch (source) { + case 'AzureCliCredential': + return new constructors.AzureCliCredential(cliOptions(ids.tenantId)); + case 'AzureDeveloperCliCredential': + return new constructors.AzureDeveloperCliCredential(cliOptions(ids.tenantId)); + case 'ManagedIdentityCredential': + return new constructors.ManagedIdentityCredential(ids.clientId ? { clientId: ids.clientId } : {}); + default: + throw new ConfigError(`AZURE_TOKEN_CREDENTIALS must be ${CREDENTIAL_CHOICES.join(', ')}.`); + } +} + +/** + * The official helper: its callback keeps the token it received and asks the credential + * for a new one shortly before it expires (it is built on the @azure/core-rest-pipeline + * token cycler), so a long-running caller does not run the credential on every request. + */ +export function createTokenProvider(credential: TokenCredential, scope: string): () => Promise { + return getBearerTokenProvider(credential, scope); +} \ No newline at end of file diff --git a/samples/typescript/test/client_auth.test.ts b/samples/typescript/test/client_auth.test.ts new file mode 100644 index 0000000..9739b66 --- /dev/null +++ b/samples/typescript/test/client_auth.test.ts @@ -0,0 +1,493 @@ +import assert from 'node:assert/strict'; +import { describe, it } from 'node:test'; +import { inspect } from 'node:util'; + +import Anthropic, { + APIConnectionTimeoutError, + APIError, + APIUserAbortError, + AuthenticationError, + InternalServerError, + PermissionDeniedError, + RateLimitError, +} from '@anthropic-ai/sdk'; + +import { ClientAuthError, createClient } from '../src/client_auth.ts'; +import { + MESSAGE, + PARAMS, + assertCleanRequests, + hang, + headerText, + nth, + respondWith, + respondWithError, + respondWithStream, + sendJSON, + useCleanEnvironment, + useServers, +} from './helpers.ts'; + +const serve = useServers(); +useCleanEnvironment(); + +const AMBIENT_CANARIES = { + ANTHROPIC_API_KEY: 'ambient-key-canary', + ANTHROPIC_AUTH_TOKEN: 'ambient-token-canary', + ANTHROPIC_PROFILE: 'nonexistent-canary-profile', + ANTHROPIC_BASE_URL: 'https://wrong.example', + ANTHROPIC_CUSTOM_HEADERS: + 'Authorization: Bearer custom-canary\nx-api-key: key-canary\napi-key: alias-canary\nx-note: kept-header', +}; + +describe('credentials', () => { + it('returns the stock SDK client and resolves a fresh token for every request', async () => { + const server = await serve(respondWith()); + let calls = 0; + const client = createClient({ baseURL: server.origin, tokenProvider: () => `token-${++calls}`, maxRetries: 0 }); + + assert.equal(Object.getPrototypeOf(client), Anthropic.prototype); + assert.equal(client.credentials, null, 'the SDK credential-provider path must not be used'); + assert.equal(calls, 0, 'the provider is not called until a request is made'); + + await client.messages.create(PARAMS); + await client.messages.create(PARAMS); + + assert.deepEqual( + server.requests.map((request) => request.headers.authorization), + ['Bearer token-1', 'Bearer token-2'], + ); + const request = nth(server.requests, 0); + assert.equal(request.url, '/v1/messages'); + assert.equal(JSON.parse(request.body).model, 'claude-test'); + assert.equal(request.headers['anthropic-beta'], undefined); + assertCleanRequests(server.requests); + }); + + it('keeps the base URL path and sends the model unchanged', async () => { + const server = await serve(respondWith()); + for (const suffix of ['/anthropic', '/anthropic/']) { + const client = createClient({ baseURL: server.origin + suffix, tokenProvider: () => 'token', maxRetries: 0 }); + await client.messages.create({ ...PARAMS, model: 'my-deployment' }); + } + assert.deepEqual(server.requests.map((request) => request.url), ['/anthropic/v1/messages', '/anthropic/v1/messages']); + assert.ok(server.requests.every((request) => JSON.parse(request.body).model === 'my-deployment')); + }); + + it('ignores ambient credentials, profiles, base URL and credential headers, and per-request overrides', async () => { + Object.assign(process.env, AMBIENT_CANARIES); + const server = await serve(respondWith()); + + // Control: a plain SDK client under the same environment does send the ambient credentials and headers. + await new Anthropic({ baseURL: server.origin, maxRetries: 0 }).messages.create(PARAMS); + const control = headerText(nth(server.requests, 0)); + assert.ok(control.includes('ambient-key-canary') || control.includes('key-canary'), 'the canaries must be live'); + server.requests.length = 0; + + const client = createClient({ baseURL: server.origin, tokenProvider: () => 'selected-token', maxRetries: 0 }); + delete process.env['ANTHROPIC_CUSTOM_HEADERS']; + + await client.messages.create(PARAMS, { + headers: { + Authorization: 'Bearer request-canary', + 'x-api-key': 'request-key-canary', + 'anthropic-beta': 'a-requested-beta', + 'x-request-note': 'request-header', + }, + }); + + const request = nth(server.requests, 0); + assert.equal(request.headers.authorization, 'Bearer selected-token'); + assert.equal(request.headers['x-api-key'], undefined); + assert.equal(request.headers['api-key'], undefined); + assert.equal(request.headers['anthropic-beta'], 'a-requested-beta'); + assert.equal(request.headers['x-request-note'], 'request-header'); + assert.equal(request.headers['x-note'], 'kept-header', 'non-credential headers are not touched'); + assert.ok(!headerText(request).includes('canary')); + assertCleanRequests(server.requests); + }); + + it('keeps ambient credentials out of key-header requests too', async () => { + Object.assign(process.env, AMBIENT_CANARIES); + const server = await serve(respondWith()); + const client = createClient({ baseURL: server.origin, apiKey: 'selected-key', keyHeader: 'x-api-key', maxRetries: 0 }); + + await client.messages.create(PARAMS, { headers: { Authorization: 'Bearer request-canary' } }); + + const request = nth(server.requests, 0); + assert.equal(request.headers['x-api-key'], 'selected-key'); + assert.equal(request.headers.authorization, undefined); + assert.equal(request.headers['api-key'], undefined); + assert.ok(!headerText(request).includes('canary')); + assertCleanRequests(server.requests); + }); + + it('sends a static key in the configured header', async () => { + const server = await serve(respondWith()); + const cases = [ + [undefined, 'authorization', 'Bearer selected-key'], + ['Authorization', 'authorization', 'Bearer selected-key'], + ['x-api-key', 'x-api-key', 'selected-key'], + ['api-key', 'api-key', 'selected-key'], + ] as const; + for (const [keyHeader, header, expected] of cases) { + const before = server.requests.length; + const client = createClient({ + baseURL: server.origin, + apiKey: 'selected-key', + ...(keyHeader === undefined ? {} : { keyHeader }), + maxRetries: 0, + }); + await client.messages.create(PARAMS); + const request = nth(server.requests, before); + assert.equal(request.headers[header], expected, `header ${header}`); + for (const other of ['authorization', 'x-api-key', 'api-key']) { + if (other !== header) assert.equal(request.headers[other], undefined, `${other} must be absent for ${header}`); + } + } + assertCleanRequests(server.requests); + }); + + it('applies a configured API version and otherwise preserves the SDK default', async () => { + const server = await serve(respondWith()); + const stock = new Anthropic({ apiKey: 'stock-key', baseURL: server.origin, maxRetries: 0 }); + await stock.messages.create(PARAMS); + const sdkDefault = nth(server.requests, 0).headers['anthropic-version']; + assert.ok(sdkDefault); + + await createClient({ baseURL: server.origin, apiKey: 'key', maxRetries: 0 }).messages.create(PARAMS); + await createClient({ baseURL: server.origin, apiKey: 'key', apiVersion: '2023-06-01', maxRetries: 0 }).messages.create(PARAMS); + + assert.equal(nth(server.requests, 1).headers['anthropic-version'], sdkDefault); + assert.equal(nth(server.requests, 2).headers['anthropic-version'], '2023-06-01'); + }); + + it('preserves user headers and beta headers, and never adds the OAuth beta', async () => { + const server = await serve(respondWith()); + const client = createClient({ baseURL: server.origin, tokenProvider: () => 'token', maxRetries: 0 }) + .withOptions({ defaultHeaders: { 'x-team': 'platform' } }); + + await client.beta.messages.create({ ...PARAMS, betas: ['files-api-2025-04-14'] }); + await client.messages.create(PARAMS, { headers: { 'anthropic-beta': 'prompt-caching-2024-07-31' } }); + + const [native, custom] = server.requests; + assert.equal(nth(server.requests, 0).headers['x-team'], 'platform'); + assert.match(String(native?.headers['anthropic-beta']), /files-api-2025-04-14/); + assert.equal(custom?.headers['anthropic-beta'], 'prompt-caching-2024-07-31'); + assert.equal(native?.headers.authorization, 'Bearer token'); + assertCleanRequests(server.requests); + }); + + it('reacquires the credential for every SDK retry', async () => { + const server = await serve((request, response) => + server.requests.length < 3 + ? sendJSON(response, 500, { type: 'error', error: { type: 'api_error', message: 'try again' } }, { 'retry-after-ms': '1' }) + : sendJSON(response, 200, MESSAGE), + ); + let calls = 0; + const client = createClient({ baseURL: server.origin, tokenProvider: () => `token-${++calls}` }); + + await client.messages.create(PARAMS); + + assert.deepEqual( + server.requests.map((request) => request.headers.authorization), + ['Bearer token-1', 'Bearer token-2', 'Bearer token-3'], + ); + assert.deepEqual(server.requests.map((request) => request.headers['x-stainless-retry-count']), ['0', '1', '2']); + }); + + it('accepts a provider that returns a promise', async () => { + const server = await serve(respondWith()); + const client = createClient({ baseURL: server.origin, tokenProvider: async () => 'async-token', maxRetries: 0 }); + await client.messages.create(PARAMS); + assert.equal(nth(server.requests, 0).headers.authorization, 'Bearer async-token'); + }); +}); + +describe('configuration', () => { + it('rejects invalid configuration before any request', () => { + const base = { baseURL: 'https://example.services.ai.azure.com/anthropic' }; + const invalid: Array<[string, Parameters[0]]> = [ + ['no credential', base], + ['two credentials', { ...base, apiKey: 'key', tokenProvider: () => 'token' }], + ['plain HTTP', { baseURL: 'http://insecure.example', apiKey: 'key' }], + ['HTTP on a lookalike host', { baseURL: 'http://localhost.example', apiKey: 'key' }], + ['embedded credentials', { baseURL: 'https://user:secret@example.com', apiKey: 'key' }], + ['query string', { baseURL: 'https://example.com/anthropic?x=1', apiKey: 'key' }], + ['fragment', { baseURL: 'https://example.com/anthropic#x', apiKey: 'key' }], + ['not a URL', { baseURL: 'not a url', apiKey: 'key' }], + ['empty key', { ...base, apiKey: '' }], + ['blank key', { ...base, apiKey: ' ' }], + ['multi-line key', { ...base, apiKey: 'key\nx-injected: 1' }], + ['bad header name', { ...base, apiKey: 'key', keyHeader: 'bad header' }], + ['bad API version', { ...base, apiKey: 'key', apiVersion: 'bad\nversion' }], + ['zero timeout', { ...base, apiKey: 'key', timeoutMs: 0 }], + ['provider that is not a function', { ...base, tokenProvider: 'token' as unknown as () => string }], + ]; + for (const [name, options] of invalid) { + assert.throws(() => createClient(options), TypeError, name); + } + }); + + it('accepts HTTPS and loopback HTTP base URLs', () => { + for (const baseURL of ['https://example.com', 'https://example.com:8443/anthropic', 'http://localhost:1', 'http://127.0.0.1:1', 'http://[::1]:1']) { + assert.doesNotThrow(() => createClient({ baseURL, apiKey: 'key' }), baseURL); + } + }); + + it('preserves the SDK retry and timeout defaults unless they are set', () => { + const stock = new Anthropic({ apiKey: 'key' }); + const client = createClient({ baseURL: 'https://example.com', apiKey: 'key' }); + assert.equal(client.maxRetries, stock.maxRetries); + assert.equal(client.timeout, stock.timeout); + const custom = createClient({ baseURL: 'https://example.com', apiKey: 'key', maxRetries: 5, timeoutMs: 5_000 }); + assert.equal(custom.maxRetries, 5); + assert.equal(custom.timeout, 5_000); + }); + + it('passes manual redirect handling to fetch even when a request asks to follow', async () => { + const calls: Array<{ url: string; init: RequestInit }> = []; + const client = createClient({ + baseURL: 'https://example.com/anthropic', + tokenProvider: () => 'token', + maxRetries: 0, + fetch: async (url, init) => { + calls.push({ url: String(url), init: init ?? {} }); + return Response.json(MESSAGE); + }, + }); + + await client.messages.create(PARAMS, { fetchOptions: { redirect: 'follow' } }); + + const call = calls[0]; + assert.equal(call?.url, 'https://example.com/anthropic/v1/messages'); + assert.equal(call?.init.redirect, 'manual'); + assert.equal(new Headers(call?.init.headers).get('authorization'), 'Bearer token'); + }); +}); + +describe('origin and redirects', () => { + it('does not follow redirects and never contacts the redirect target', async () => { + const other = await serve(respondWith()); + const origin = await serve((_request, response) => { + response.writeHead(307, { location: `${other.origin}/v1/messages` }); + response.end(); + }); + const clients = [ + createClient({ baseURL: origin.origin, tokenProvider: () => 'selected-token' }), + createClient({ baseURL: origin.origin, apiKey: 'selected-key', keyHeader: 'x-api-key' }), + ]; + + for (const client of clients) { + await assert.rejects(client.messages.create(PARAMS), (error) => error instanceof APIError && error.status === 307); + } + + assert.equal(origin.requests.length, 2, 'a redirect is final, so the SDK does not retry it'); + assert.equal(other.requests.length, 0, 'no credential may reach the redirect target'); + }); + + it('does not follow a same-origin redirect either', async () => { + const server = await serve((request, response) => { + response.writeHead(308, { location: '/elsewhere' }); + response.end(); + }); + const client = createClient({ baseURL: server.origin, tokenProvider: () => 'token' }); + await assert.rejects(client.messages.create(PARAMS), (error) => error instanceof APIError && error.status === 308); + assert.equal(server.requests.length, 1); + }); + + it('refuses to send credentials to a different origin from a copied client or an absolute URL', async () => { + const other = await serve(respondWith()); + const origin = await serve(respondWith()); + const client = createClient({ baseURL: origin.origin, tokenProvider: () => 'selected-token', maxRetries: 0 }); + + await assert.rejects(client.withOptions({ baseURL: other.origin }).messages.create(PARAMS), ClientAuthError); + await assert.rejects(client.post(`${other.origin}/v1/messages`, { body: PARAMS }), ClientAuthError); + + assert.equal(other.requests.length, 0); + assert.equal(origin.requests.length, 0); + }); +}); + +describe('failures', () => { + it('reports a provider failure with its cause and sends no request, without retrying', async () => { + const server = await serve(respondWith()); + let calls = 0; + const failure = new Error('credential unavailable'); + const client = createClient({ + baseURL: server.origin, + tokenProvider: () => { + calls += 1; + throw failure; + }, + }); + + await assert.rejects(client.messages.create(PARAMS), (error) => { + assert.ok(error instanceof ClientAuthError); + assert.equal(error.cause, failure); + return true; + }); + + assert.equal(calls, 1); + assert.equal(server.requests.length, 0); + }); + + it('rejects credentials that are not a nonempty single line', async () => { + const server = await serve(respondWith()); + for (const value of ['', ' ', 'a\nb', 'a\r\nb', 42 as unknown as string, undefined as unknown as string]) { + const client = createClient({ baseURL: server.origin, tokenProvider: () => value, maxRetries: 0 }); + await assert.rejects(client.messages.create(PARAMS), ClientAuthError, JSON.stringify(value)); + } + assert.equal(server.requests.length, 0); + }); + + it('rejects credentials that cannot be an HTTP header value without echoing them', async () => { + const server = await serve(respondWith()); + const client = createClient({ baseURL: server.origin, tokenProvider: () => 'token-\u2603', maxRetries: 0 }); + await assert.rejects(client.messages.create(PARAMS), (error) => { + assert.ok(error instanceof ClientAuthError); + assert.ok(!String(error.message).includes('token-')); + assert.equal(error.cause, undefined); + return true; + }); + assert.equal(server.requests.length, 0); + }); + + it('preserves HTTP statuses and the SDK error classes', async () => { + const cases = [ + [401, AuthenticationError], + [403, PermissionDeniedError], + [429, RateLimitError], + [500, InternalServerError], + ] as const; + for (const [status, errorClass] of cases) { + const server = await serve(respondWithError(status)); + const client = createClient({ baseURL: server.origin, tokenProvider: () => 'token', maxRetries: 0 }); + await assert.rejects(client.messages.create(PARAMS), (error) => { + assert.ok(error instanceof errorClass, `status ${status}`); + assert.equal((error as APIError).status, status); + return true; + }); + } + }); + + it('does not retry authentication or permission failures', async () => { + for (const status of [401, 403]) { + const server = await serve(respondWithError(status)); + const client = createClient({ baseURL: server.origin, tokenProvider: () => 'token' }); + await assert.rejects(client.messages.create(PARAMS), (error) => error instanceof APIError && error.status === status); + assert.equal(server.requests.length, 1, `status ${status}`); + } + }); + + it('times out an attempt that never answers', async () => { + const server = await serve(hang); + const client = createClient({ baseURL: server.origin, tokenProvider: () => 'token', maxRetries: 0, timeoutMs: 50 }); + await assert.rejects(client.messages.create(PARAMS), APIConnectionTimeoutError); + assert.equal(server.requests.length, 1); + }); +}); + +describe('streaming and cancellation', () => { + it('streams text through the standard SDK helper', async () => { + const server = await serve(respondWithStream([['thinking', 'not for display'], ['text', 'OK']])); + const client = createClient({ baseURL: server.origin, tokenProvider: () => 'stream-token', maxRetries: 0 }); + + const stream = client.messages.stream(PARAMS); + let text = ''; + stream.on('text', (delta) => { + text += delta; + }); + const message = await stream.finalMessage(); + + assert.equal(text, 'OK'); + assert.equal(message.stop_reason, 'end_turn'); + const request = nth(server.requests, 0); + assert.equal(request.headers.authorization, 'Bearer stream-token'); + assert.equal(JSON.parse(request.body).stream, true); + assertCleanRequests(server.requests); + }); + + it('cancels while the credential is being acquired', async () => { + const server = await serve(respondWith()); + const controller = new AbortController(); + let started!: () => void; + const providerStarted = new Promise((resolve) => { + started = resolve; + }); + const client = createClient({ + baseURL: server.origin, + tokenProvider: () => { + started(); + return new Promise(() => {}); + }, + maxRetries: 0, + }); + + const call = client.messages.create(PARAMS, { signal: controller.signal }); + await providerStarted; + controller.abort(); + + await assert.rejects(call, APIUserAbortError); + assert.equal(server.requests.length, 0); + }); + + it('cancels a request that is in flight', async () => { + const server = await serve(hang); + const controller = new AbortController(); + const client = createClient({ baseURL: server.origin, tokenProvider: () => 'token', maxRetries: 0 }); + + const call = client.messages.create(PARAMS, { signal: controller.signal }); + while (server.requests.length === 0) await new Promise((resolve) => setTimeout(resolve, 5)); + controller.abort(); + + await assert.rejects(call, APIUserAbortError); + }); + + it('honours a signal that is already aborted and a total deadline', async () => { + const server = await serve(hang); + let calls = 0; + const client = createClient({ + baseURL: server.origin, + tokenProvider: () => `token-${++calls}`, + maxRetries: 0, + }); + + await assert.rejects(client.messages.create(PARAMS, { signal: AbortSignal.abort() }), APIUserAbortError); + assert.equal(calls, 0); + + await assert.rejects(client.messages.create(PARAMS, { signal: AbortSignal.timeout(100) }), APIUserAbortError); + assert.equal(server.requests.length, 1); + }); +}); + +describe('logging', () => { + it('keeps the credential out of SDK debug logs for the credential headers', async () => { + const server = await serve(respondWith()); + const lines: string[] = []; + const record = (...args: unknown[]) => { + lines.push(inspect(args, { depth: 8 })); + }; + const logger = { debug: record, info: record, warn: record, error: record }; + const variants = [ + { tokenProvider: () => 'logged-token-value' }, + { apiKey: 'logged-key-value' }, + { apiKey: 'logged-x-api-key-value', keyHeader: 'x-api-key' }, + ]; + + for (const variant of variants) { + const client = createClient({ baseURL: server.origin, ...variant, maxRetries: 0 }).withOptions({ + logger, + logLevel: 'debug', + }); + await client.messages.create(PARAMS); + } + + const logged = lines.join('\n'); + assert.match(logged, /sending request/, 'the SDK logged the request headers'); + assert.match(logged, /\*\*\*/, 'and redacted the credential headers'); + for (const secret of ['logged-token-value', 'logged-key-value', 'logged-x-api-key-value']) { + assert.ok(!logged.includes(secret), `${secret} leaked into the SDK log`); + } + }); +}); \ No newline at end of file diff --git a/samples/typescript/test/helpers.ts b/samples/typescript/test/helpers.ts new file mode 100644 index 0000000..c63a6f5 --- /dev/null +++ b/samples/typescript/test/helpers.ts @@ -0,0 +1,159 @@ +import assert from 'node:assert/strict'; +import { createServer, type IncomingHttpHeaders, type ServerResponse } from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { afterEach, beforeEach } from 'node:test'; + +export interface RecordedRequest { + method: string; + url: string; + headers: IncomingHttpHeaders; + body: string; +} + +export type Handler = (request: RecordedRequest, response: ServerResponse) => void | Promise; + +export interface TestServer { + origin: string; + requests: RecordedRequest[]; + close(): Promise; +} + +/** Starts a loopback HTTP server that records every request before running the handler. */ +export async function startServer(handler: Handler): Promise { + const requests: RecordedRequest[] = []; + const server = createServer((request, response) => { + const chunks: Buffer[] = []; + request.on('data', (chunk: Buffer) => chunks.push(chunk)); + request.on('end', () => { + const recorded: RecordedRequest = { + method: request.method ?? '', + url: request.url ?? '', + headers: request.headers, + body: Buffer.concat(chunks).toString('utf8'), + }; + requests.push(recorded); + Promise.resolve(handler(recorded, response)).catch(() => response.destroy()); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const { port } = server.address() as AddressInfo; + return { + origin: `http://127.0.0.1:${port}`, + requests, + close: () => + new Promise((resolve) => { + server.close(() => resolve()); + server.closeAllConnections(); + }), + }; +} + +/** Registers servers started in a test so they are closed afterwards. */ +export function useServers(): (handler: Handler) => Promise { + const started: TestServer[] = []; + afterEach(async () => { + await Promise.all(started.splice(0).map((server) => server.close())); + }); + return async (handler) => { + const server = await startServer(handler); + started.push(server); + return server; + }; +} + +export const MESSAGE = { + id: 'msg_test', + type: 'message', + role: 'assistant', + model: 'claude-test', + content: [{ type: 'text', text: 'OK' }], + stop_reason: 'end_turn', + stop_sequence: null, + usage: { input_tokens: 1, output_tokens: 2 }, +}; + +export const THINKING_BLOCK = { type: 'thinking', thinking: 'not for display', signature: 'sample' }; + +export const PARAMS = { + model: 'claude-test', + max_tokens: 32, + messages: [{ role: 'user' as const, content: 'Hello' }], +}; + +export function sendJSON(response: ServerResponse, status: number, body: unknown, headers: Record = {}): void { + response.writeHead(status, { 'content-type': 'application/json', ...headers }); + response.end(JSON.stringify(body)); +} + +export function respondWith(message: unknown = MESSAGE): Handler { + return (_request, response) => sendJSON(response, 200, message); +} + +export function respondWithError(status: number, headers: Record = {}): Handler { + return (_request, response) => + sendJSON(response, status, { type: 'error', error: { type: 'api_error', message: 'test failure' } }, headers); +} + +/** Never answers; the connection is closed when the test server is. */ +export const hang: Handler = () => {}; + +/** Builds a Messages API event stream whose content blocks are the given `[type, text]` pairs. */ +export function eventStream(blocks: ReadonlyArray): string { + const events: Array<[string, Record]> = [ + ['message_start', { message: { ...MESSAGE, content: [], stop_reason: null, usage: { input_tokens: 1, output_tokens: 0 } } }], + ]; + blocks.forEach(([kind, text], index) => { + events.push(['content_block_start', { index, content_block: kind === 'text' ? { type: 'text', text: '' } : { type: 'thinking', thinking: '', signature: '' } }]); + events.push(['content_block_delta', { index, delta: kind === 'text' ? { type: 'text_delta', text } : { type: 'thinking_delta', thinking: text } }]); + events.push(['content_block_stop', { index }]); + }); + events.push(['message_delta', { delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: { output_tokens: 2 } }]); + events.push(['message_stop', {}]); + return events.map(([name, data]) => `event: ${name}\ndata: ${JSON.stringify({ type: name, ...data })}\n\n`).join(''); +} + +export function respondWithStream(blocks: ReadonlyArray): Handler { + return (_request, response) => { + response.writeHead(200, { 'content-type': 'text/event-stream' }); + response.end(eventStream(blocks)); + }; +} + +const AMBIENT_PREFIXES = ['ANTHROPIC_', 'CLAUDE_', 'AZURE_']; +const AMBIENT_NAMES = ['AUTH_MODE', 'API_KEY_HEADER', 'TOKEN_SCOPE']; + +/** Gives each test an environment without any variable the SDK or the sample reads, and restores it afterwards. */ +export function useCleanEnvironment(): void { + let saved: NodeJS.ProcessEnv = {}; + beforeEach(() => { + saved = { ...process.env }; + for (const name of Object.keys(process.env)) { + if (AMBIENT_NAMES.includes(name) || AMBIENT_PREFIXES.some((prefix) => name.startsWith(prefix))) { + delete process.env[name]; + } + } + }); + afterEach(() => { + for (const name of Object.keys(process.env)) delete process.env[name]; + Object.assign(process.env, saved); + }); +} + +export function nth(requests: readonly RecordedRequest[], index: number): RecordedRequest { + const request = requests[index]; + assert.ok(request, `expected a request at index ${index}, saw ${requests.length}`); + return request; +} + +export function headerText(request: RecordedRequest): string { + return JSON.stringify(request.headers); +} + +/** Every request must be free of the placeholder credential and of the SDK's OAuth beta. */ +export function assertCleanRequests(requests: readonly RecordedRequest[]): void { + for (const request of requests) { + const text = headerText(request); + assert.ok(!text.includes('provided-by-request-middleware'), 'the placeholder credential must never be sent'); + assert.ok(!text.includes('oauth-2025-04-20'), 'the OAuth beta must not be added'); + } +} \ No newline at end of file diff --git a/samples/typescript/test/sample.test.ts b/samples/typescript/test/sample.test.ts new file mode 100644 index 0000000..b764d41 --- /dev/null +++ b/samples/typescript/test/sample.test.ts @@ -0,0 +1,647 @@ +import assert from 'node:assert/strict'; +import { execFile } from 'node:child_process'; +import { describe, it } from 'node:test'; +import { fileURLToPath } from 'node:url'; +import { promisify } from 'node:util'; + +import type { AccessToken, TokenCredential } from '@azure/identity'; +import { AzureCliCredential, AzureDeveloperCliCredential, ManagedIdentityCredential } from '@azure/identity'; + +import { ConfigError } from '../src/config_error.ts'; +import { run, type RunIO, type RunOptions } from '../src/main.ts'; +import { DEFAULT_TOKEN_SCOPE, loadSettings, type Environment } from '../src/sample_client.ts'; +import { + CLI_PROCESS_TIMEOUT_MS, + CREDENTIAL_CHOICES, + createCredential, + createTokenProvider, + type CredentialConstructors, +} from '../src/token_provider.ts'; +import { + MESSAGE, + THINKING_BLOCK, + hang, + startServer, + nth, + respondWith, + respondWithError, + respondWithStream, + sendJSON, + useCleanEnvironment, + useServers, +} from './helpers.ts'; + +const serve = useServers(); +useCleanEnvironment(); + +const CANONICAL = { ANTHROPIC_BASE_URL: 'https://example.services.ai.azure.com/anthropic', ANTHROPIC_MODEL: 'sample-deployment' }; +const LEGACY = { CLAUDE_BASE_URL: 'https://legacy.example', CLAUDE_DEPLOYMENT_NAME: 'legacy-deployment' }; + +describe('loadSettings', () => { + it('selects the canonical profile and requires an explicit AUTH_MODE, so an ambient URL never gets a token by default', () => { + assert.throws(() => loadSettings(CANONICAL), { + name: 'ConfigError', + message: 'ANTHROPIC_BASE_URL is set, so AUTH_MODE must be set explicitly to bearer or api_key.', + }); + assert.deepEqual(loadSettings({ ...CANONICAL, AUTH_MODE: 'bearer' }), { + profile: 'anthropic', + baseURL: CANONICAL.ANTHROPIC_BASE_URL, + model: 'sample-deployment', + apiVersion: undefined, + auth: { + mode: 'bearer', + credential: 'AzureCliCredential', + tenantId: undefined, + clientId: undefined, + scope: DEFAULT_TOKEN_SCOPE, + }, + }); + assert.equal(DEFAULT_TOKEN_SCOPE, 'https://ai.azure.com/.default'); + }); + + it('selects the legacy profile when only CLAUDE_BASE_URL is set, and that profile defaults to bearer', () => { + const settings = loadSettings(LEGACY); + assert.equal(settings.profile, 'claude'); + assert.equal(settings.baseURL, 'https://legacy.example'); + assert.equal(settings.model, 'legacy-deployment'); + assert.equal(settings.auth.mode, 'bearer'); + assert.equal(settings.apiVersion, undefined); + }); + + it('lets a complete canonical profile override the legacy one entirely', () => { + const settings = loadSettings({ + ...LEGACY, + ...CANONICAL, + AUTH_MODE: 'api_key', + ANTHROPIC_API_KEY: 'native-key', + CLAUDE_API_KEY: 'legacy-key', + }); + assert.deepEqual(settings, { + profile: 'anthropic', + baseURL: CANONICAL.ANTHROPIC_BASE_URL, + model: 'sample-deployment', + apiVersion: undefined, + auth: { mode: 'api_key', apiKey: 'native-key', keyHeader: 'Authorization' }, + }); + }); + + it('reads the bearer settings', () => { + const { auth } = loadSettings({ + ...CANONICAL, + AUTH_MODE: 'bearer', + AZURE_TOKEN_CREDENTIALS: 'ManagedIdentityCredential', + AZURE_TENANT_ID: 'example-tenant', + AZURE_CLIENT_ID: 'example-client', + TOKEN_SCOPE: 'https://example.test/.default', + }); + assert.deepEqual(auth, { + mode: 'bearer', + credential: 'ManagedIdentityCredential', + tenantId: 'example-tenant', + clientId: 'example-client', + scope: 'https://example.test/.default', + }); + }); + + it('defaults the API key header to Authorization and reads the key of the selected family only', () => { + assert.deepEqual(loadSettings({ ...LEGACY, AUTH_MODE: 'api_key', CLAUDE_API_KEY: 'legacy-key' }).auth, { + mode: 'api_key', + apiKey: 'legacy-key', + keyHeader: 'Authorization', + }); + const configured = loadSettings({ + ...CANONICAL, + AUTH_MODE: 'api_key', + ANTHROPIC_API_KEY: 'native-key', + API_KEY_HEADER: 'x-api-key', + ANTHROPIC_API_VERSION: '2023-06-01', + }); + assert.deepEqual(configured.auth, { mode: 'api_key', apiKey: 'native-key', keyHeader: 'x-api-key' }); + assert.equal(configured.apiVersion, '2023-06-01'); + }); + + it('never combines a URL with the model or key of the other family', () => { + const url = 'https://example.test'; + const cases: Array<[string, Environment, RegExp]> = [ + [ + 'canonical URL, legacy model', + { ANTHROPIC_BASE_URL: url, AUTH_MODE: 'bearer', CLAUDE_DEPLOYMENT_NAME: 'legacy-deployment' }, + /^ANTHROPIC_BASE_URL is set, so ANTHROPIC_MODEL is required; CLAUDE_DEPLOYMENT_NAME is not used with it\.$/, + ], + [ + 'canonical URL, legacy key', + { ANTHROPIC_BASE_URL: url, ANTHROPIC_MODEL: 'native-model', AUTH_MODE: 'api_key', CLAUDE_API_KEY: 'legacy-key-canary' }, + /^AUTH_MODE=api_key with ANTHROPIC_BASE_URL requires ANTHROPIC_API_KEY; CLAUDE_API_KEY is not used with it\.$/, + ], + [ + 'legacy URL, canonical model', + { CLAUDE_BASE_URL: url, AUTH_MODE: 'bearer', ANTHROPIC_MODEL: 'native-model' }, + /^CLAUDE_BASE_URL is set, so CLAUDE_DEPLOYMENT_NAME is required; ANTHROPIC_MODEL is not used with it\.$/, + ], + [ + 'legacy URL, canonical key', + { ...LEGACY, AUTH_MODE: 'api_key', ANTHROPIC_API_KEY: 'native-key-canary' }, + /^AUTH_MODE=api_key with CLAUDE_BASE_URL requires CLAUDE_API_KEY; ANTHROPIC_API_KEY is not used with it\.$/, + ], + ]; + for (const [name, env, message] of cases) { + assert.throws(() => loadSettings(env), { name: 'ConfigError', message }, name); + } + }); + + it('reports missing or invalid configuration without echoing values', () => { + assert.throws(() => loadSettings({}), { + name: 'ConfigError', + message: 'Set ANTHROPIC_BASE_URL, ANTHROPIC_MODEL and AUTH_MODE, or the legacy CLAUDE_BASE_URL and CLAUDE_DEPLOYMENT_NAME.', + }); + assert.throws(() => loadSettings({ ANTHROPIC_MODEL: 'native-model', CLAUDE_DEPLOYMENT_NAME: 'legacy' }), ConfigError); + for (const family of [CANONICAL, LEGACY]) { + assert.throws(() => loadSettings({ ...family, AUTH_MODE: 'basic' }), { message: 'AUTH_MODE must be bearer or api_key.' }); + } + }); +}); +describe('credential selection', () => { + function recordingConstructors() { + const calls: Array<{ name: string; options: unknown }> = []; + const make = (name: string) => + class implements TokenCredential { + constructor(options?: unknown) { + calls.push({ name, options }); + } + async getToken(): Promise { + return null; + } + }; + const constructors: CredentialConstructors = { + AzureCliCredential: make('AzureCliCredential'), + AzureDeveloperCliCredential: make('AzureDeveloperCliCredential'), + ManagedIdentityCredential: make('ManagedIdentityCredential'), + }; + return { calls, constructors }; + } + + it('builds exactly the named credential and passes each identity to the credential that uses it', () => { + const ids = { tenantId: 'example-tenant', clientId: 'example-client' }; + const { calls, constructors } = recordingConstructors(); + + createCredential('AzureCliCredential', ids, constructors); + createCredential('AzureDeveloperCliCredential', ids, constructors); + createCredential('ManagedIdentityCredential', ids, constructors); + createCredential('AzureCliCredential', {}, constructors); + createCredential('ManagedIdentityCredential', {}, constructors); + + assert.deepEqual(calls, [ + { name: 'AzureCliCredential', options: { tenantId: 'example-tenant', processTimeoutInMs: 60_000 } }, + { name: 'AzureDeveloperCliCredential', options: { tenantId: 'example-tenant', processTimeoutInMs: 60_000 } }, + { name: 'ManagedIdentityCredential', options: { clientId: 'example-client' } }, + { name: 'AzureCliCredential', options: { processTimeoutInMs: 60_000 } }, + { name: 'ManagedIdentityCredential', options: {} }, + ]); + assert.equal(CLI_PROCESS_TIMEOUT_MS, 60_000); + }); + + it('has no fallback: other names fail and name the setting', () => { + const { calls, constructors } = recordingConstructors(); + for (const source of ['DefaultAzureCredential', 'typo', 'azureclicredential', '']) { + assert.throws(() => createCredential(source, {}, constructors), { name: 'ConfigError', message: /AZURE_TOKEN_CREDENTIALS/ }, source); + } + assert.deepEqual(calls, []); + assert.deepEqual([...CREDENTIAL_CHOICES], ['AzureCliCredential', 'AzureDeveloperCliCredential', 'ManagedIdentityCredential']); + }); + + it('constructs the real Azure Identity credentials without contacting anything', () => { + assert.ok(createCredential('AzureCliCredential', { tenantId: 'example-tenant' }) instanceof AzureCliCredential); + assert.ok(createCredential('AzureDeveloperCliCredential') instanceof AzureDeveloperCliCredential); + assert.ok(createCredential('ManagedIdentityCredential', { clientId: 'example-client' }) instanceof ManagedIdentityCredential); + }); + + it('gives the real CLI credentials the process timeout', () => { + // The pinned @azure/identity keeps processTimeoutInMs in a private `timeout` field of each CLI credential. + const timeoutOf = (credential: unknown) => (credential as { timeout?: number }).timeout; + assert.equal(timeoutOf(createCredential('AzureCliCredential')), 60_000); + assert.equal(timeoutOf(createCredential('AzureDeveloperCliCredential', { tenantId: 'example-tenant' })), 60_000); + }); +}); + +describe('token provider', () => { + function fakeCredential(expiresInMs: number[]) { + const requests: Array = []; + const credential: TokenCredential = { + async getToken(scopes) { + requests.push(scopes); + const index = requests.length; + return { token: `token-${index}`, expiresOnTimestamp: Date.now() + (expiresInMs[index - 1] ?? 3_600_000) }; + }, + }; + return { credential, requests }; + } + + it('is lazy, requests the scope, and reuses the token until it nears expiry', async () => { + const { credential, requests } = fakeCredential([3_600_000]); + const provider = createTokenProvider(credential, DEFAULT_TOKEN_SCOPE); + assert.equal(requests.length, 0); + + assert.equal(await provider(), 'token-1'); + assert.equal(await provider(), 'token-1'); + + assert.equal(requests.length, 1); + assert.deepEqual(requests[0], [DEFAULT_TOKEN_SCOPE]); + }); + + it('asks the credential for a new token before the current one expires', async () => { + const { credential, requests } = fakeCredential([30_000, 3_600_000]); + const provider = createTokenProvider(credential, DEFAULT_TOKEN_SCOPE); + + assert.equal(await provider(), 'token-1'); + assert.equal(await provider(), 'token-1', 'the still-valid token is returned while the refresh runs'); + await new Promise((resolve) => setImmediate(resolve)); + assert.equal(await provider(), 'token-2'); + assert.equal(requests.length, 2); + }); +}); + +const execFileAsync = promisify(execFile); +const MAIN = fileURLToPath(new URL('../src/main.ts', import.meta.url)); + +async function runProcess(args: string[], env: Record) { + try { + const { stdout, stderr } = await execFileAsync(process.execPath, [MAIN, ...args], { + env: { ...process.env, ...env }, + timeout: 30_000, + }); + return { code: 0, stdout, stderr }; + } catch (error) { + const failure = error as { code?: unknown; stdout?: string; stderr?: string }; + return { code: typeof failure.code === 'number' ? failure.code : -1, stdout: failure.stdout ?? '', stderr: failure.stderr ?? '' }; + } +} + +function capture() { + let out = ''; + let err = ''; + const io: RunIO = { + stdout: { write: (text) => (out += text) }, + stderr: { write: (text) => (err += text) }, + }; + return { io, stdout: () => out, stderr: () => err }; +} + +const PROMPT = 'What are 3 things to visit in Seattle?'; +const TEXT_MESSAGE = { ...MESSAGE, content: [THINKING_BLOCK, { type: 'text', text: 'OK' }] }; +const THINKING_ONLY = { ...MESSAGE, content: [THINKING_BLOCK], stop_reason: 'max_tokens' }; + +async function sampleEnvironment(server: { origin: string }, extra: Environment = {}): Promise { + return { + ANTHROPIC_BASE_URL: `${server.origin}/anthropic`, + ANTHROPIC_MODEL: 'sample-deployment', + AUTH_MODE: 'api_key', + ANTHROPIC_API_KEY: 'sample-key', + ...extra, + }; +} + +describe('main', () => { + it('prints the reply text and usage, not the thinking, using the SDK defaults', async () => { + const server = await serve(respondWith(TEXT_MESSAGE)); + const output = capture(); + + assert.equal(await run([], await sampleEnvironment(server), output.io), 0); + + assert.equal(output.stdout(), 'OK\n\n[usage] input=1 output=2\n'); + assert.equal(output.stderr(), ''); + const request = nth(server.requests, 0); + assert.equal(request.url, '/anthropic/v1/messages'); + assert.equal(request.headers.authorization, 'Bearer sample-key'); + assert.equal(request.headers['x-api-key'], undefined); + assert.equal(request.headers['anthropic-beta'], undefined); + assert.match(String(request.headers['anthropic-version']), /^\d{4}-\d{2}-\d{2}$/); + assert.deepEqual(JSON.parse(request.body), { + model: 'sample-deployment', + max_tokens: 1024, + messages: [{ role: 'user', content: PROMPT }], + }); + }); + + it('honours API_KEY_HEADER and ANTHROPIC_API_VERSION', async () => { + const server = await serve(respondWith(TEXT_MESSAGE)); + const env = await sampleEnvironment(server, { API_KEY_HEADER: 'x-api-key', ANTHROPIC_API_VERSION: '2023-06-01' }); + + assert.equal(await run([], env, capture().io), 0); + + const request = nth(server.requests, 0); + assert.equal(request.headers['x-api-key'], 'sample-key'); + assert.equal(request.headers.authorization, undefined); + assert.equal(request.headers['anthropic-version'], '2023-06-01'); + }); + + it('reads the legacy variable names', async () => { + const server = await serve(respondWith(TEXT_MESSAGE)); + const env = { + CLAUDE_BASE_URL: server.origin, + CLAUDE_DEPLOYMENT_NAME: 'legacy-deployment', + AUTH_MODE: 'api_key', + CLAUDE_API_KEY: 'legacy-key', + }; + + assert.equal(await run([], env, capture().io), 0); + + const request = nth(server.requests, 0); + assert.equal(request.url, '/v1/messages'); + assert.equal(request.headers.authorization, 'Bearer legacy-key'); + assert.equal(JSON.parse(request.body).model, 'legacy-deployment'); + }); + + it('authenticates with a bearer token for every attempt and never uses ambient credentials', async () => { + Object.assign(process.env, { + ANTHROPIC_API_KEY: 'ambient-key-canary', + ANTHROPIC_AUTH_TOKEN: 'ambient-token-canary', + ANTHROPIC_PROFILE: 'nonexistent-canary-profile', + ANTHROPIC_CUSTOM_HEADERS: 'x-api-key: header-canary', + }); + const server = await serve((_request, response) => + server.requests.length < 2 + ? sendJSON(response, 500, { type: 'error', error: { type: 'api_error', message: 'again' } }, { 'retry-after-ms': '1' }) + : sendJSON(response, 200, TEXT_MESSAGE), + ); + let calls = 0; + const env = { ANTHROPIC_BASE_URL: server.origin, ANTHROPIC_MODEL: 'sample-deployment', AUTH_MODE: 'bearer' }; + + assert.equal(await run([], env, capture().io, { tokenProvider: () => `entra-test-token-${++calls}` }), 0); + + assert.deepEqual( + server.requests.map((request) => request.headers.authorization), + ['Bearer entra-test-token-1', 'Bearer entra-test-token-2'], + ); + for (const request of server.requests) { + assert.equal(request.headers['x-api-key'], undefined); + assert.equal(request.headers['anthropic-beta'], undefined); + assert.ok(!JSON.stringify(request.headers).includes('canary')); + } + }); + + it('streams only the text and uses a custom prompt', async () => { + const server = await serve(respondWithStream([['thinking', 'not for display'], ['text', 'Hello'], ['text', ' there']])); + const output = capture(); + + assert.equal(await run(['--stream', 'Say', 'hi'], await sampleEnvironment(server), output.io), 0); + + assert.equal(output.stdout(), 'Hello there\n'); + const body = JSON.parse(nth(server.requests, 0).body); + assert.equal(body.stream, true); + assert.equal(body.max_tokens, 1024); + assert.deepEqual(body.messages, [{ role: 'user', content: 'Say hi' }]); + }); + + it('exits nonzero when the reply has no text', async () => { + const empty = { ...MESSAGE, content: [], stop_reason: 'end_turn' }; + const blank = { ...MESSAGE, content: [{ type: 'text', text: ' \n' }] }; + for (const [name, message] of [['thinking only', THINKING_ONLY], ['empty', empty], ['blank text', blank]] as const) { + const server = await serve(respondWith(message)); + const output = capture(); + assert.equal(await run([], await sampleEnvironment(server), output.io), 1, name); + assert.match(output.stderr(), /No text response \(stop_reason=/, name); + assert.ok(!output.stdout().includes('not for display'), name); + assert.ok(!output.stdout().includes('[usage]'), name); + } + const server = await serve(respondWith(THINKING_ONLY)); + const output = capture(); + await run([], await sampleEnvironment(server), output.io); + assert.match(output.stderr(), /max_tokens/); + }); + + it('exits nonzero when a stream has no text', async () => { + const server = await serve(respondWithStream([['thinking', 'not for display']])); + const output = capture(); + + assert.equal(await run(['--stream'], await sampleEnvironment(server), output.io), 1); + + assert.match(output.stderr(), /No text response/); + assert.ok(!output.stdout().includes('not for display')); + }); + + it('reports HTTP failures without echoing the credential, endpoint, model or response body', async () => { + for (const stream of [false, true]) { + for (const status of [401, 403, 404, 429, 500]) { + const server = await serve(respondWithError(status)); + const output = capture(); + const code = await run(stream ? ['--stream'] : [], await sampleEnvironment(server), output.io, { maxRetries: 0 }); + + assert.equal(code, 1); + assert.match(output.stderr(), new RegExp(`HTTP ${status} \\(api_error\\)`)); + for (const secret of ['sample-key', server.origin, new URL(server.origin).host, 'sample-deployment', 'test failure']) { + assert.ok(!output.stderr().includes(secret), `${secret} leaked for ${status}`); + } + assert.equal(output.stdout(), '', 'no reply text on failure'); + } + } + }); + + it('reports a redirect as an error and does not follow it', async () => { + const other = await serve(respondWith(TEXT_MESSAGE)); + const server = await serve((_request, response) => { + response.writeHead(307, { location: `${other.origin}/v1/messages` }); + response.end(); + }); + const output = capture(); + + assert.equal(await run([], await sampleEnvironment(server), output.io), 1); + + assert.match(output.stderr(), /HTTP 307/); + assert.equal(other.requests.length, 0); + }); + + it('reports a credential failure without the provider message', async () => { + const server = await serve(respondWith(TEXT_MESSAGE)); + const output = capture(); + const env = { ANTHROPIC_BASE_URL: server.origin, ANTHROPIC_MODEL: 'sample-deployment', AUTH_MODE: 'bearer' }; + const failing: RunOptions = { + tokenProvider: () => { + throw new Error('tenant details that must not be printed'); + }, + }; + + assert.equal(await run([], env, output.io, failing), 1); + + assert.match(output.stderr(), /credential provider failed/); + assert.match(output.stderr(), /Cause: Error/); + assert.ok(!output.stderr().includes('tenant details')); + assert.equal(server.requests.length, 0); + }); + + it('reports an unreachable endpoint without naming it', async () => { + const closed = await startServer(respondWith()); + const env = await sampleEnvironment(closed); + await closed.close(); + const output = capture(); + + assert.equal(await run([], env, output.io, { maxRetries: 0 }), 1); + + assert.equal(output.stderr(), 'Could not connect to the endpoint.\n'); + }); + + it('reports a credential failure the same way while streaming', async () => { + const server = await serve(respondWith(TEXT_MESSAGE)); + const output = capture(); + const env = { ANTHROPIC_BASE_URL: server.origin, ANTHROPIC_MODEL: 'sample-deployment', AUTH_MODE: 'bearer' }; + const failing: RunOptions = { + tokenProvider: () => { + throw new Error('tenant details that must not be printed'); + }, + }; + + assert.equal(await run(['--stream'], env, output.io, failing), 1); + + assert.match(output.stderr(), /credential provider failed/); + assert.ok(!output.stderr().includes('tenant details')); + assert.equal(server.requests.length, 0); + }); + + it('exits nonzero on a missing configuration without contacting anything', async () => { + const output = capture(); + assert.equal(await run([], {}, output.io), 1); + assert.match(output.stderr(), /^Set ANTHROPIC_BASE_URL, ANTHROPIC_MODEL and AUTH_MODE, or the legacy CLAUDE_BASE_URL and CLAUDE_DEPLOYMENT_NAME\.\n$/); + assert.equal(output.stdout(), ''); + }); + + it('bounds the whole call with a total deadline', async () => { + const server = await serve(hang); + const output = capture(); + + assert.equal(await run([], await sampleEnvironment(server), output.io, { totalTimeoutMs: 100 }), 1); + + assert.match(output.stderr(), /timed out after 0\.1 seconds/); + assert.ok(!output.stderr().includes(server.origin)); + }); + + it('prints usage for --help and exits 2 for unknown options', async () => { + const help = capture(); + assert.equal(await run(['--help'], {}, help.io), 0); + assert.match(help.stdout(), /Usage: node src\/main\.ts/); + + const unknown = capture(); + assert.equal(await run(['--nope'], {}, unknown.io), 2); + assert.match(unknown.stderr(), /Usage: node src\/main\.ts/); + }); + + it('runs as a command: exit codes and output of the real entrypoint', async () => { + const ok = await serve(respondWith(TEXT_MESSAGE)); + const streamed = await serve(respondWithStream([['text', 'Hello']])); + const denied = await serve(respondWithError(401)); + const env = (server: { origin: string }) => ({ + ANTHROPIC_BASE_URL: server.origin, + ANTHROPIC_MODEL: 'sample-deployment', + AUTH_MODE: 'api_key', + ANTHROPIC_API_KEY: 'sample-key', + }); + + const plain = await runProcess([], env(ok)); + assert.deepEqual(plain, { code: 0, stdout: 'OK\n\n[usage] input=1 output=2\n', stderr: '' }); + + const stream = await runProcess(['--stream'], env(streamed)); + assert.deepEqual(stream, { code: 0, stdout: 'Hello\n', stderr: '' }); + + const failure = await runProcess([], env(denied)); + assert.equal(failure.code, 1); + assert.equal(failure.stdout, ''); + assert.match(failure.stderr, /HTTP 401/); + assert.ok(!failure.stderr.includes('sample-key')); + + assert.equal((await runProcess([], {})).code, 1); + assert.equal((await runProcess(['--bogus'], {})).code, 2); + }); + + it('never sends a credential from one variable family to the endpoint of the other', async () => { + const native = await serve(respondWith(TEXT_MESSAGE)); + const legacy = await serve(respondWith(TEXT_MESSAGE)); + const cases: Array<[string, Environment, RegExp]> = [ + [ + 'canonical URL, legacy model and key', + { ANTHROPIC_BASE_URL: native.origin, AUTH_MODE: 'api_key', CLAUDE_DEPLOYMENT_NAME: 'legacy-model', CLAUDE_API_KEY: 'legacy-key-canary' }, + /ANTHROPIC_MODEL is required/, + ], + [ + 'canonical URL and model, legacy key', + { ANTHROPIC_BASE_URL: native.origin, ANTHROPIC_MODEL: 'native-model', AUTH_MODE: 'api_key', CLAUDE_API_KEY: 'legacy-key-canary' }, + /requires ANTHROPIC_API_KEY/, + ], + [ + 'legacy URL and model, canonical key', + { CLAUDE_BASE_URL: legacy.origin, CLAUDE_DEPLOYMENT_NAME: 'legacy-model', AUTH_MODE: 'api_key', ANTHROPIC_API_KEY: 'native-key-canary' }, + /requires CLAUDE_API_KEY/, + ], + [ + 'legacy URL, canonical model and key', + { CLAUDE_BASE_URL: legacy.origin, ANTHROPIC_MODEL: 'native-model', AUTH_MODE: 'api_key', ANTHROPIC_API_KEY: 'native-key-canary' }, + /CLAUDE_DEPLOYMENT_NAME is required/, + ], + ]; + + for (const [name, env, expected] of cases) { + const output = capture(); + assert.equal(await run([], env, output.io), 1, name); + assert.match(output.stderr(), expected, name); + assert.ok(!output.stderr().includes('canary'), name); + } + + assert.equal(native.requests.length + legacy.requests.length, 0, 'nothing may be sent'); + }); + + it('uses only the selected family when both are complete', async () => { + const native = await serve(respondWith(TEXT_MESSAGE)); + const legacy = await serve(respondWith(TEXT_MESSAGE)); + const both = { + ANTHROPIC_BASE_URL: `${native.origin}/anthropic`, + ANTHROPIC_MODEL: 'native-model', + ANTHROPIC_API_KEY: 'native-key', + CLAUDE_BASE_URL: legacy.origin, + CLAUDE_DEPLOYMENT_NAME: 'legacy-model', + CLAUDE_API_KEY: 'legacy-key', + AUTH_MODE: 'api_key', + }; + + assert.equal(await run([], both, capture().io), 0); + const { ANTHROPIC_BASE_URL: _url, ANTHROPIC_MODEL: _model, ...legacyOnly } = both; + assert.equal(await run([], legacyOnly, capture().io), 0, 'an ambient ANTHROPIC_API_KEY must not matter'); + + const request = nth(native.requests, 0); + assert.equal(request.url, '/anthropic/v1/messages'); + assert.equal(request.headers.authorization, 'Bearer native-key'); + assert.equal(JSON.parse(request.body).model, 'native-model'); + const fallback = nth(legacy.requests, 0); + assert.equal(fallback.headers.authorization, 'Bearer legacy-key'); + assert.equal(JSON.parse(fallback.body).model, 'legacy-model'); + assert.equal(native.requests.length, 1); + assert.equal(legacy.requests.length, 1); + for (const sent of [request, fallback]) assert.ok(!JSON.stringify(sent.headers).includes('canary')); + }); + + it('gives a token to a canonical URL only when bearer is chosen explicitly', async () => { + const server = await serve(respondWith(TEXT_MESSAGE)); + let calls = 0; + const options: RunOptions = { tokenProvider: () => `entra-test-token-${++calls}` }; + const canonical = { ANTHROPIC_BASE_URL: server.origin, ANTHROPIC_MODEL: 'sample-deployment' }; + + const implicit = capture(); + assert.equal(await run([], canonical, implicit.io, options), 1); + assert.match(implicit.stderr(), /AUTH_MODE must be set explicitly/); + assert.equal(calls, 0, 'no token may be acquired'); + assert.equal(server.requests.length, 0, 'nothing may be sent'); + + assert.equal(await run([], { ...canonical, AUTH_MODE: 'bearer' }, capture().io, options), 0); + assert.equal(nth(server.requests, 0).headers.authorization, 'Bearer entra-test-token-1'); + + const legacy = { CLAUDE_BASE_URL: server.origin, CLAUDE_DEPLOYMENT_NAME: 'legacy-deployment' }; + assert.equal(await run([], legacy, capture().io, options), 0, 'the legacy profile keeps bearer as its default'); + assert.equal(nth(server.requests, 1).headers.authorization, 'Bearer entra-test-token-2'); + }); + + it('does not modify the process environment', async () => { + const server = await serve(respondWith(TEXT_MESSAGE)); + process.env['ANTHROPIC_FOUNDRY_RESOURCE'] = 'unchanged-resource'; + const before = JSON.stringify(process.env); + + await run([], await sampleEnvironment(server), capture().io); + + assert.equal(JSON.stringify(process.env), before); + }); +}); \ No newline at end of file diff --git a/samples/typescript/tsconfig.build.json b/samples/typescript/tsconfig.build.json new file mode 100644 index 0000000..4750d67 --- /dev/null +++ b/samples/typescript/tsconfig.build.json @@ -0,0 +1,11 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "noEmit": false, + "allowImportingTsExtensions": false, + "rewriteRelativeImportExtensions": true, + "rootDir": "src", + "outDir": "dist" + }, + "include": ["src/**/*.ts"] +} \ No newline at end of file diff --git a/samples/typescript/tsconfig.json b/samples/typescript/tsconfig.json new file mode 100644 index 0000000..2730f63 --- /dev/null +++ b/samples/typescript/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "es2023", + "lib": ["es2023"], + "module": "nodenext", + "moduleResolution": "nodenext", + "types": ["node"], + "noEmit": true, + "strict": true, + "noUncheckedIndexedAccess": true, + "noImplicitOverride": true, + "noFallthroughCasesInSwitch": true, + "verbatimModuleSyntax": true, + "erasableSyntaxOnly": true, + "allowImportingTsExtensions": true, + "isolatedModules": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true + }, + "include": ["src/**/*.ts", "test/**/*.ts"] +} \ No newline at end of file diff --git a/skills/claude-on-foundry/SKILL.md b/skills/claude-on-foundry/SKILL.md index 2d62090..2d7fc82 100644 --- a/skills/claude-on-foundry/SKILL.md +++ b/skills/claude-on-foundry/SKILL.md @@ -131,10 +131,10 @@ Match the customer's exact error string to a row. Verify the diagnostic command |---|---|---|---| | `404 Not Found` on first SDK call | `base_url` is missing the `/anthropic` suffix. | Print the `base_url` the script is using. | Append `/anthropic` so it's `https://.services.ai.azure.com/anthropic`. | | `401 Unauthorized` on first call | Token scope wrong, or no `az login`. | `az account get-access-token --resource https://ai.azure.com/.default --query expiresOn` | `az login` (add `--tenant ` if Foundry is in a different tenant). Scope must be `https://ai.azure.com/.default`. | -| `401 Unauthorized` after ~1 hour of running | Captured static `auth_token` expired. | Check whether the client uses a static token. | Use `AnthropicFoundry(azure_ad_token_provider=...)`, as in all Entra ID samples. Azure Identity caches and refreshes before expiry. Requires `anthropic>=2.1.0`. | +| `401 Unauthorized` after ~1 hour of running | Captured static token expired. | Check whether the client receives a renewable-token callback. | Use [`src/client_auth.py`](../../src/client_auth.py) with [`src/token_provider.py`](../../src/token_provider.py). The standard client asks the cached Azure Identity provider for the current token on every attempt. | | `AttributeError: 'ThinkingBlock' object has no attribute 'text'` | Claude 5.5 returned a non-text block. | Inspect the block's `type`. | Only print `block.text` when `block.type == "text"`. | -| `base_url and resource are mutually exclusive` | A sourced Claude Code activator set `ANTHROPIC_FOUNDRY_RESOURCE` while the SDK also received an explicit URL. | Check both settings without publishing their values. | Use the shared [`src/claude_auth.py`](../../src/claude_auth.py) client factory; it clears the resource alias only inside the Python process. | -| SDK token uses the wrong tenant with `azd` | `DefaultAzureCredential` does not forward `AZURE_TENANT_ID` to CLI credentials automatically. | Compare the deployment tenant to the CLI login tenant without publishing either ID. | Set `AZURE_TENANT_ID` in process env or gitignored `.env.local`; the shared [`src/claude_auth.py`](../../src/claude_auth.py) provider forwards it with each token request. | +| `base_url and resource are mutually exclusive` | Legacy platform-specific SDK construction consumes the Claude Code resource alias. | Check client imports without publishing configuration values. | Use the standard SDK through [`src/client_auth.py`](../../src/client_auth.py); it does not consume or mutate `ANTHROPIC_FOUNDRY_RESOURCE`. | +| SDK token uses the wrong tenant with `azd` | The credential/token request targets a different tenant. | Compare the deployment tenant to the CLI login tenant without publishing either ID. | Select `AzureDeveloperCliCredential` explicitly after azd login, set `AZURE_TENANT_ID` in process env or gitignored `.env.local`, and use [`src/token_provider.py`](../../src/token_provider.py). | | `401 PermissionDenied: Principal does not have access to API/Operation` — intermittently, passes seconds later | Data-plane RBAC propagation lag right after a role grant. | `az role assignment list --assignee --scope -o table` | Wait 1-3 minutes and retry. Do NOT suggest disabling retries. | | `403 Forbidden` consistently | Caller has no data-plane role on the Foundry account. | Same `az role assignment list` query. | Grant `Cognitive Services User` (minimum), `Foundry User`, or `Azure AI Developer`. See the one-liner in [README → Granting data-plane roles after `azd up`](../../README.md#granting-data-plane-roles-after-azd-up). | | `claude -p` says: `The model claude--... is not available on your foundry deployment` | User-global `~/.claude/settings.json` pins a family this workspace didn't deploy, overriding the workspace pin. | `cat .claude/settings.json` and `cat ~/.claude/settings.json`. | Re-run `pwsh -File scripts/configure-claude-code.ps1`, OR pass `--model ` explicitly, OR (with user OK) edit the user-global file to remove the `"model"` line. | @@ -178,7 +178,8 @@ claude # interactive REPL; try /status and /mode | **Switch variants (Bicep ↔ Terraform)** | They produce equivalent infra but with different `azd` env state. Create a new env in the other folder: `cd infra-terraform && azd env new && ...`. | | **Refresh Claude Code wiring** | `pwsh -File scripts/configure-claude-code.ps1` (or the `.sh` variant). Idempotent — runs without re-deploying. | | **Wire up the Claude Code VS Code extension** | `azd env set CLAUDE_WRITE_VSCODE_SETTINGS 1` (then re-run `azd provision` or the configure script). Opt-in because the activator + `.claude/settings.json` are enough for the CLI and SDK; only the [Anthropic Claude Code VS Code extension](https://marketplace.visualstudio.com/items?itemName=anthropic.claude-code) needs `claudeCode.*` keys in workspace settings. | -| **Convert to long-running auth** | Use `AnthropicFoundry(azure_ad_token_provider=provider)` with Azure Identity's cached bearer-token provider. See [`src/hello_claude_token_refresh.py`](../../src/hello_claude_token_refresh.py) and [`src/claude_auth.py`](../../src/claude_auth.py). Requires `anthropic>=2.1.0`; all Entra ID samples already use this pattern. | +| **Convert to long-running auth** | Pass a cached bearer-token callback to the standard client factory. See [`src/hello_claude_token_refresh.py`](../../src/hello_claude_token_refresh.py) and [`src/token_provider.py`](../../src/token_provider.py). | +| **Use another SDK language or native Anthropic endpoint** | Follow [`samples/README.md`](../../samples/README.md). Change endpoint/model/authentication configuration, not the client type. PHP/Ruby use a callback with an explicitly documented Azure CLI local fallback, not an official Azure Identity SDK. | --- diff --git a/src/chat_stream.py b/src/chat_stream.py index 65b6a49..a0fdbe1 100644 --- a/src/chat_stream.py +++ b/src/chat_stream.py @@ -6,14 +6,12 @@ from __future__ import annotations -import os import sys -from anthropic import AnthropicFoundry +from anthropic import Anthropic from anthropic.types import MessageParam -from dotenv import load_dotenv -from claude_auth import create_foundry_client +from sample_client import configured_client SYSTEM_PROMPT = ( @@ -21,26 +19,8 @@ ) -def build_client() -> tuple[AnthropicFoundry, str]: - load_dotenv(".env.local", override=False) - load_dotenv(".env", override=False) - - base_url = os.environ.get("CLAUDE_BASE_URL") - deployment = os.environ.get("CLAUDE_DEPLOYMENT_NAME") - if not base_url or not deployment: - print( - "Set CLAUDE_BASE_URL and CLAUDE_DEPLOYMENT_NAME (see .env.sample).", - file=sys.stderr, - ) - sys.exit(1) - - return create_foundry_client(base_url), deployment - - -def main() -> None: - client, deployment = build_client() +def _chat(client: Anthropic, deployment: str) -> None: history: list[MessageParam] = [] - print(f"Connected to {deployment}. Type 'exit' to quit.\n") while True: try: @@ -54,7 +34,6 @@ def main() -> None: return history.append({"role": "user", "content": user}) - print("claude> ", end="", flush=True) assistant_text = "" with client.messages.stream( @@ -66,7 +45,8 @@ def main() -> None: for text in stream.text_stream: assistant_text += text print(text, end="", flush=True) - print("\n") + print() + print() if not assistant_text.strip(): raise RuntimeError( "No text response. Increase max_tokens if the response exhausted its budget." @@ -74,5 +54,15 @@ def main() -> None: history.append({"role": "assistant", "content": assistant_text}) +def main() -> int: + try: + with configured_client() as (client, deployment): + _chat(client, deployment) + except ValueError as error: + print(str(error), file=sys.stderr) + return 1 + return 0 + + if __name__ == "__main__": - main() + raise SystemExit(main()) diff --git a/src/claude_auth.py b/src/claude_auth.py deleted file mode 100644 index 6560a60..0000000 --- a/src/claude_auth.py +++ /dev/null @@ -1,44 +0,0 @@ -"""Cached, tenant-aware Entra ID token provider for the Foundry SDK client.""" - -from __future__ import annotations - -import os -from collections.abc import Callable -from typing import Any - -from anthropic import AnthropicFoundry -from azure.core.credentials import AccessToken -from azure.identity import DefaultAzureCredential, get_bearer_token_provider - - -class _TenantCredential: - def __init__(self, credential: DefaultAzureCredential, tenant_id: str) -> None: - self._credential = credential - self._tenant_id = tenant_id - - def get_token(self, *scopes: str, **kwargs: Any) -> AccessToken: - # DefaultAzureCredential does not pass AZURE_TENANT_ID to its CLI legs. - kwargs["tenant_id"] = self._tenant_id - return self._credential.get_token(*scopes, **kwargs) - - -def entra_token_provider() -> Callable[[], str]: - credential = DefaultAzureCredential() - tenant_id = os.environ.get("AZURE_TENANT_ID") - if tenant_id: - return get_bearer_token_provider( - _TenantCredential(credential, tenant_id), "https://ai.azure.com/.default" - ) - return get_bearer_token_provider(credential, "https://ai.azure.com/.default") - - -def create_foundry_client( - base_url: str, *, api_key: str | None = None -) -> AnthropicFoundry: - # The explicit SDK URL wins over the CLI resource alias in this process. - os.environ.pop("ANTHROPIC_FOUNDRY_RESOURCE", None) - if api_key is not None: - return AnthropicFoundry(base_url=base_url, api_key=api_key) - return AnthropicFoundry( - base_url=base_url, azure_ad_token_provider=entra_token_provider() - ) diff --git a/src/client_auth.py b/src/client_auth.py new file mode 100644 index 0000000..1aafd36 --- /dev/null +++ b/src/client_auth.py @@ -0,0 +1,136 @@ +"""Construct standard SDK clients with explicit, renewable authentication.""" + +from __future__ import annotations + +from collections.abc import Awaitable, Callable +import re +from urllib.parse import urlsplit + +from anthropic import Anthropic, AsyncAnthropic, DefaultAsyncHttpxClient, DefaultHttpxClient +import httpx2 as httpx + + +_CREDENTIAL_HEADERS = ("authorization", "x-api-key", "api-key") +_HEADER_NAME = re.compile(r"[!#$%&'*+\-.^_`|~0-9A-Za-z]+\Z") + + +def _validate( + base_url: str, + token_provider: object, + api_key: str | None, + key_header: str, +) -> tuple[str, str, int]: + url = urlsplit(base_url) + if ( + not url.hostname + or url.username + or url.password + or url.query + or url.fragment + or ( + url.scheme != "https" + and not ( + url.scheme == "http" + and url.hostname in ("localhost", "127.0.0.1", "::1") + ) + ) + ): + raise ValueError("base_url must be an HTTPS URL without credentials, query, or fragment.") + if (token_provider is None) == (api_key is None): + raise ValueError("Provide exactly one of token_provider or api_key.") + if token_provider is not None and not callable(token_provider): + raise TypeError("token_provider must be callable.") + if not _HEADER_NAME.fullmatch(key_header): + raise ValueError("key_header must be a valid HTTP header name.") + if api_key is not None: + _validate_secret(api_key) + return url.scheme, url.hostname, url.port or (443 if url.scheme == "https" else 80) + + +def _validate_secret(value: str) -> None: + if not isinstance(value, str) or not value.strip() or "\r" in value or "\n" in value: + raise ValueError("The credential provider must return a nonempty, single-line string.") + + +def _authorize( + request: httpx.Request, + origin: tuple[str, str, int], + value: str, + header: str, +) -> None: + request_origin = ( + request.url.scheme, + request.url.host, + request.url.port or (443 if request.url.scheme == "https" else 80), + ) + if request_origin != origin: + raise ValueError("Refusing to send credentials to a different origin.") + _validate_secret(value) + for name in (*_CREDENTIAL_HEADERS, header): + request.headers.pop(name, None) + request.headers[header] = f"Bearer {value}" if header.lower() == "authorization" else value + + +def create_client( + *, + base_url: str, + token_provider: Callable[[], str] | None = None, + api_key: str | None = None, + key_header: str = "Authorization", + api_version: str | None = None, + transport: httpx.BaseTransport | None = None, + max_retries: int = 2, +) -> Anthropic: + origin = _validate(base_url, token_provider, api_key, key_header) + + def authorize(request: httpx.Request) -> None: + value = token_provider() if token_provider is not None else api_key + if value is None: + raise ValueError("A credential is required.") + _authorize(request, origin, value, "Authorization" if token_provider is not None else key_header) + + http_client = DefaultHttpxClient( + transport=transport, + follow_redirects=False, + event_hooks={"request": [authorize]}, + ) + # Explicit credentials suppress SDK discovery; the public hook sets the real header. + return Anthropic( + base_url=base_url, + auth_token="provided-by-request-hook", + default_headers={"anthropic-version": api_version} if api_version else None, + http_client=http_client, + max_retries=max_retries, + ) + + +def create_async_client( + *, + base_url: str, + token_provider: Callable[[], Awaitable[str]] | None = None, + api_key: str | None = None, + key_header: str = "Authorization", + api_version: str | None = None, + transport: httpx.AsyncBaseTransport | None = None, + max_retries: int = 2, +) -> AsyncAnthropic: + origin = _validate(base_url, token_provider, api_key, key_header) + + async def authorize(request: httpx.Request) -> None: + value = await token_provider() if token_provider is not None else api_key + if value is None: + raise ValueError("A credential is required.") + _authorize(request, origin, value, "Authorization" if token_provider is not None else key_header) + + http_client = DefaultAsyncHttpxClient( + transport=transport, + follow_redirects=False, + event_hooks={"request": [authorize]}, + ) + return AsyncAnthropic( + base_url=base_url, + auth_token="provided-by-request-hook", + default_headers={"anthropic-version": api_version} if api_version else None, + http_client=http_client, + max_retries=max_retries, + ) diff --git a/src/hello_claude.py b/src/hello_claude.py index 223818f..7f8abb1 100644 --- a/src/hello_claude.py +++ b/src/hello_claude.py @@ -4,46 +4,33 @@ CLAUDE_BASE_URL e.g. https://.services.ai.azure.com/anthropic CLAUDE_DEPLOYMENT_NAME the Foundry deployment name (NOT the model id) -Auth: Microsoft Entra ID via DefaultAzureCredential. Run `az login` or -`azd auth login` first. Tokens are cached and refreshed before expiry. +Auth: Microsoft Entra ID via an explicitly selected credential. Run `az login` +first, or select AzureDeveloperCliCredential after `azd auth login`. +Tokens are cached and refreshed before expiry. Set AZURE_TENANT_ID when the deployment lives in a non-default tenant. """ from __future__ import annotations -import os import sys -from dotenv import load_dotenv - -from claude_auth import create_foundry_client +from sample_client import configured_client def main() -> int: - # Load .env.local first (developer overrides), then .env - load_dotenv(".env.local", override=False) - load_dotenv(".env", override=False) - - base_url = os.environ.get("CLAUDE_BASE_URL") - deployment = os.environ.get("CLAUDE_DEPLOYMENT_NAME") - - if not base_url or not deployment: - print( - "Set CLAUDE_BASE_URL and CLAUDE_DEPLOYMENT_NAME (see .env.sample).", - file=sys.stderr, - ) + try: + with configured_client() as (client, deployment): + message = client.messages.create( + model=deployment, + max_tokens=1024, + messages=[ + {"role": "user", "content": "What are 3 things to visit in Seattle?"} + ], + ) + except ValueError as error: + print(str(error), file=sys.stderr) return 1 - client = create_foundry_client(base_url) - - message = client.messages.create( - model=deployment, - max_tokens=1024, - messages=[ - {"role": "user", "content": "What are 3 things to visit in Seattle?"} - ], - ) - has_text = False for block in message.content: if block.type == "text" and block.text.strip(): diff --git a/src/hello_claude_apikey.py b/src/hello_claude_apikey.py index b900b7e..de75655 100644 --- a/src/hello_claude_apikey.py +++ b/src/hello_claude_apikey.py @@ -4,41 +4,28 @@ (e.g. `Cognitive Services User`) for Entra ID auth. For production, prefer the Entra ID flow in src/hello_claude.py. -AnthropicFoundry sends the Foundry API-key headers. The generic Anthropic -client's API-key authentication changed in SDK 2.x and is not interchangeable. +The standard client uses an explicitly configured API-key header. +API_KEY_HEADER defaults to the current native SDK's bearer-key semantics. """ from __future__ import annotations -import os import sys -from dotenv import load_dotenv - -from claude_auth import create_foundry_client +from sample_client import configured_client def main() -> int: - load_dotenv(".env.local", override=False) - load_dotenv(".env", override=False) - - base_url = os.environ.get("CLAUDE_BASE_URL") - deployment = os.environ.get("CLAUDE_DEPLOYMENT_NAME") - api_key = os.environ.get("CLAUDE_API_KEY") - - if not (base_url and deployment and api_key): - print( - "Set CLAUDE_BASE_URL, CLAUDE_DEPLOYMENT_NAME, CLAUDE_API_KEY.", - file=sys.stderr, - ) + try: + with configured_client(auth_mode="api_key") as (client, deployment): + msg = client.messages.create( + model=deployment, + max_tokens=1024, + messages=[{"role": "user", "content": "What are 3 things to visit in Seattle?"}], + ) + except ValueError as error: + print(str(error), file=sys.stderr) return 1 - - client = create_foundry_client(base_url, api_key=api_key) - msg = client.messages.create( - model=deployment, - max_tokens=512, - messages=[{"role": "user", "content": "What are 3 things to visit in Seattle?"}], - ) has_text = False for block in msg.content: if block.type == "text" and block.text.strip(): diff --git a/src/hello_claude_token_refresh.py b/src/hello_claude_token_refresh.py index 8e3f4c1..4c76564 100644 --- a/src/hello_claude_token_refresh.py +++ b/src/hello_claude_token_refresh.py @@ -1,38 +1,29 @@ """Long-running Claude-on-Foundry sample with automatic Entra ID token refresh. Use this pattern for services, daemons, long-running batch jobs, and -notebooks. AnthropicFoundry invokes an Azure Identity token provider on +notebooks. A request hook invokes a cached token provider on each request. The provider caches the token and refreshes it before expiry. The one-shot and streaming samples use the same authentication path. """ from __future__ import annotations -import os import sys -from dotenv import load_dotenv - -from claude_auth import create_foundry_client +from sample_client import configured_client def main() -> int: - load_dotenv(".env.local", override=False) - load_dotenv(".env", override=False) - - base_url = os.environ.get("CLAUDE_BASE_URL") - deployment = os.environ.get("CLAUDE_DEPLOYMENT_NAME") - if not base_url or not deployment: - print("Set CLAUDE_BASE_URL and CLAUDE_DEPLOYMENT_NAME.", file=sys.stderr) + try: + with configured_client() as (client, deployment): + msg = client.messages.create( + model=deployment, + max_tokens=1024, + messages=[{"role": "user", "content": "What are 3 things to visit in Seattle?"}], + ) + except ValueError as error: + print(str(error), file=sys.stderr) return 1 - - client = create_foundry_client(base_url) - - msg = client.messages.create( - model=deployment, - max_tokens=512, - messages=[{"role": "user", "content": "What are 3 things to visit in Seattle?"}], - ) has_text = False for block in msg.content: if block.type == "text" and block.text.strip(): diff --git a/src/sample_client.py b/src/sample_client.py new file mode 100644 index 0000000..542f781 --- /dev/null +++ b/src/sample_client.py @@ -0,0 +1,66 @@ +"""Environment configuration shared by the Python sample entrypoints.""" + +from __future__ import annotations + +from collections.abc import Generator +from contextlib import ExitStack, contextmanager +import os + +from anthropic import Anthropic +from dotenv import load_dotenv + +from client_auth import create_client +from token_provider import cached_token_provider, create_credential + + +@contextmanager +def configured_client( + *, auth_mode: str | None = None +) -> Generator[tuple[Anthropic, str], None, None]: + process_endpoint = bool(os.environ.get("ANTHROPIC_BASE_URL")) + process_auth_mode = os.environ.get("AUTH_MODE") + load_dotenv(".env.local", override=False) + load_dotenv(".env", override=False) + canonical = bool(os.environ.get("ANTHROPIC_BASE_URL")) + base_url = os.environ.get("ANTHROPIC_BASE_URL" if canonical else "CLAUDE_BASE_URL") + model = os.environ.get("ANTHROPIC_MODEL" if canonical else "CLAUDE_DEPLOYMENT_NAME") + if not base_url or not model: + raise ValueError("Set CLAUDE_BASE_URL and CLAUDE_DEPLOYMENT_NAME (or ANTHROPIC_BASE_URL and ANTHROPIC_MODEL).") + if process_endpoint and process_auth_mode is None: + raise ValueError("Set AUTH_MODE in the process environment with ANTHROPIC_BASE_URL.") + mode = auth_mode or os.environ.get("AUTH_MODE") + if canonical and mode is None: + raise ValueError("Set AUTH_MODE explicitly when using ANTHROPIC_BASE_URL.") + if mode is None: + mode = "bearer" + with ExitStack() as resources: + provider = None + key = None + if mode == "bearer": + tenant = os.environ.get("AZURE_TENANT_ID") + credential = resources.enter_context(create_credential( + os.environ.get("AZURE_TOKEN_CREDENTIALS", "AzureCliCredential"), + tenant_id=tenant, + client_id=os.environ.get("AZURE_CLIENT_ID"), + )) + provider = cached_token_provider( + credential, os.environ.get("TOKEN_SCOPE", "https://ai.azure.com/.default"), + tenant_id=tenant, + ) + elif mode == "api_key": + key_name = "ANTHROPIC_API_KEY" if canonical else "CLAUDE_API_KEY" + key = os.environ.get(key_name) + if not key: + raise ValueError(f"Set {key_name} for the selected endpoint profile.") + else: + raise ValueError("AUTH_MODE must be bearer or api_key.") + client = resources.enter_context(create_client( + base_url=base_url, + token_provider=provider, + api_key=key, + key_header=os.environ.get("API_KEY_HEADER", "Authorization"), + api_version=os.environ.get("ANTHROPIC_API_VERSION"), + )) + if provider is not None: + provider() + yield client, model diff --git a/src/token_provider.py b/src/token_provider.py new file mode 100644 index 0000000..f173e3e --- /dev/null +++ b/src/token_provider.py @@ -0,0 +1,50 @@ +"""Credential selection and cached, tenant-aware bearer-token acquisition.""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import Any + +from azure.core.credentials import AccessToken, TokenCredential +from azure.identity import ( + AzureCliCredential, + AzureDeveloperCliCredential, + ManagedIdentityCredential, + get_bearer_token_provider, +) + + +def create_credential( + source: str, *, tenant_id: str | None = None, client_id: str | None = None +) -> AzureCliCredential | AzureDeveloperCliCredential | ManagedIdentityCredential: + if source == "AzureCliCredential": + return AzureCliCredential(tenant_id=tenant_id or "", process_timeout=60) + if source == "AzureDeveloperCliCredential": + return AzureDeveloperCliCredential(tenant_id=tenant_id or "", process_timeout=60) + if source == "ManagedIdentityCredential": + return ManagedIdentityCredential(client_id=client_id) + raise ValueError( + "AZURE_TOKEN_CREDENTIALS must name AzureCliCredential, " + "AzureDeveloperCliCredential, or ManagedIdentityCredential." + ) + + +class _TenantCredential: + def __init__(self, credential: TokenCredential, tenant_id: str) -> None: + self._credential = credential + self._tenant_id = tenant_id + + def get_token(self, *scopes: str, **kwargs: Any) -> AccessToken: + # Forward the selected tenant through the token-provider policy. + kwargs["tenant_id"] = self._tenant_id + return self._credential.get_token(*scopes, **kwargs) + + +def cached_token_provider( + credential: TokenCredential, scope: str, *, tenant_id: str | None = None +) -> Callable[[], str]: + if tenant_id: + return get_bearer_token_provider( + _TenantCredential(credential, tenant_id), scope + ) + return get_bearer_token_provider(credential, scope) diff --git a/tests/test_client_auth.py b/tests/test_client_auth.py new file mode 100644 index 0000000..fc5bc34 --- /dev/null +++ b/tests/test_client_auth.py @@ -0,0 +1,210 @@ +from __future__ import annotations + +import asyncio +import os +from pathlib import Path +import sys +import unittest +from unittest.mock import Mock, patch + +from anthropic import APIConnectionError, APIStatusError, Anthropic, AsyncAnthropic, DEFAULT_TIMEOUT +import httpx2 as httpx + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) +from client_auth import create_async_client, create_client + +MESSAGE = { + "id": "msg_test", "type": "message", "role": "assistant", "model": "claude-test", + "content": [{"type": "text", "text": "OK"}], "stop_reason": "end_turn", + "stop_sequence": None, "usage": {"input_tokens": 1, "output_tokens": 1}, +} +PARAMS = {"model": "claude-test", "max_tokens": 32, "messages": [{"role": "user", "content": "Hello"}]} +BASE_URL = "https://example.services.ai.azure.com/anthropic" + + +class ClientAuthTests(unittest.TestCase): + def setUp(self) -> None: + self.environment = patch.dict(os.environ, {}, clear=True) + self.environment.start() + self.addCleanup(self.environment.stop) + self.requests: list[httpx.Request] = [] + + def respond(self, request: httpx.Request) -> httpx.Response: + self.requests.append(request) + return httpx.Response(200, json=MESSAGE) + + def test_returns_standard_client_and_resolves_token_for_each_request(self) -> None: + provider = Mock(side_effect=["first-token", "second-token"]) + with create_client(base_url=BASE_URL, token_provider=provider, + transport=httpx.MockTransport(self.respond), max_retries=0) as client: + self.assertIs(type(client), Anthropic) + provider.assert_not_called() + client.messages.create(**PARAMS) + client.messages.create(**PARAMS) + self.assertEqual([r.headers["authorization"] for r in self.requests], + ["Bearer first-token", "Bearer second-token"]) + self.assertEqual(str(self.requests[0].url), BASE_URL + "/v1/messages") + self.assertTrue(all("anthropic-beta" not in request.headers for request in self.requests)) + + def test_sdk_timeout_defaults_are_preserved(self) -> None: + with create_client(base_url=BASE_URL, token_provider=lambda: "test-token", + transport=httpx.MockTransport(self.respond)) as client: + self.assertEqual(client.timeout, DEFAULT_TIMEOUT) + + def test_callable_truthiness_does_not_change_the_authentication_scheme(self) -> None: + class Provider: + def __bool__(self) -> bool: + return False + def __call__(self) -> str: + return "selected-token" + with create_client(base_url=BASE_URL, token_provider=Provider(), key_header="x-api-key", + transport=httpx.MockTransport(self.respond), max_retries=0) as client: + client.messages.create(**PARAMS) + self.assertEqual(self.requests[0].headers["authorization"], "Bearer selected-token") + self.assertNotIn("x-api-key", self.requests[0].headers) + + def test_ambient_and_per_request_credentials_cannot_override_the_provider(self) -> None: + with ( + patch.dict(os.environ, { + "ANTHROPIC_API_KEY": "ambient-key-canary", + "ANTHROPIC_AUTH_TOKEN": "ambient-token-canary", + "ANTHROPIC_PROFILE": "nonexistent-canary", + "ANTHROPIC_BASE_URL": "https://wrong.example", + "ANTHROPIC_CUSTOM_HEADERS": "Authorization: custom-canary\nx-api-key: key-canary\napi-key: alias-canary", + "ANTHROPIC_FOUNDRY_RESOURCE": "unchanged-cli-resource", + }), + create_client(base_url=BASE_URL, token_provider=lambda: "selected-token", + transport=httpx.MockTransport(self.respond), max_retries=0) as client, + ): + client.messages.create(**PARAMS, extra_headers={ + "Authorization": "request-canary", "x-api-key": "request-key-canary", + "anthropic-beta": "a-requested-beta", + }) + self.assertEqual(os.environ["ANTHROPIC_FOUNDRY_RESOURCE"], "unchanged-cli-resource") + request = self.requests[0] + self.assertEqual(request.headers["authorization"], "Bearer selected-token") + self.assertNotIn("x-api-key", request.headers) + self.assertNotIn("api-key", request.headers) + self.assertEqual(request.headers["anthropic-beta"], "a-requested-beta") + self.assertNotIn("canary", str(request.headers)) + + def test_api_key_header_and_api_version_are_configuration(self) -> None: + for base_url, header in (("https://api.anthropic.com", "Authorization"), (BASE_URL, "x-api-key")): + with self.subTest(header=header): + with create_client(base_url=base_url, api_key="selected-key", key_header=header, + api_version="2023-06-01", transport=httpx.MockTransport(self.respond), + max_retries=0) as client: + client.messages.create(**PARAMS) + request = self.requests[-1] + self.assertEqual(request.headers[header], + "Bearer selected-key" if header == "Authorization" else "selected-key") + self.assertEqual(request.headers["anthropic-version"], "2023-06-01") + self.assertNotIn("provided-by-request-hook", str(request.headers)) + if header == "x-api-key": + self.assertNotIn("authorization", request.headers) + + def test_invalid_configuration_fails_before_network(self) -> None: + invalid = [ + {"base_url": BASE_URL}, + {"base_url": BASE_URL, "api_key": "key", "token_provider": lambda: "token"}, + {"base_url": "http://insecure.example", "api_key": "key"}, + {"base_url": "https://user:pass@example.com", "api_key": "key"}, + {"base_url": BASE_URL, "api_key": ""}, + {"base_url": BASE_URL, "api_key": "key", "key_header": "bad\nheader"}, + ] + for options in invalid: + with self.subTest(options={key: value for key, value in options.items() if key != "api_key"}): + with self.assertRaises(ValueError): + create_client(**options) + + def test_redirect_is_not_followed(self) -> None: + def redirect(request: httpx.Request) -> httpx.Response: + self.requests.append(request) + return httpx.Response(307, headers={"location": "https://untrusted.example/v1/messages"}) + with create_client(base_url=BASE_URL, token_provider=lambda: "selected-token", + transport=httpx.MockTransport(redirect), max_retries=0) as client: + with self.assertRaises(APIStatusError) as error: + client.messages.create(**PARAMS) + self.assertEqual(error.exception.status_code, 307) + self.assertEqual(len(self.requests), 1) + + def test_copied_client_cannot_retarget_the_credentials(self) -> None: + with create_client(base_url=BASE_URL, token_provider=lambda: "selected-token", + transport=httpx.MockTransport(self.respond), max_retries=0) as client: + with self.assertRaises(APIConnectionError) as error: + client.with_options(base_url="https://untrusted.example").messages.create(**PARAMS) + self.assertIsInstance(error.exception.__cause__, ValueError) + self.assertEqual(self.requests, []) + + def test_provider_failure_has_a_visible_cause_and_no_request(self) -> None: + def fail() -> str: + raise RuntimeError("credential unavailable") + with create_client(base_url=BASE_URL, token_provider=fail, + transport=httpx.MockTransport(self.respond), max_retries=0) as client: + with self.assertRaises(APIConnectionError) as error: + client.messages.create(**PARAMS) + self.assertIsInstance(error.exception.__cause__, RuntimeError) + self.assertEqual(self.requests, []) + + def test_http_status_is_preserved(self) -> None: + for status in (401, 403, 429, 500): + with self.subTest(status=status): + with create_client(base_url=BASE_URL, token_provider=lambda: "selected-token", + transport=httpx.MockTransport(lambda request: httpx.Response(status, + json={"type": "error", "error": {"type": "api_error", "message": "test failure"}})), + max_retries=0) as client: + with self.assertRaises(APIStatusError) as error: + client.messages.create(**PARAMS) + self.assertEqual(error.exception.status_code, status) + + def test_sdk_retry_acquires_the_current_token(self) -> None: + def respond(request: httpx.Request) -> httpx.Response: + self.requests.append(request) + return httpx.Response(500 if len(self.requests) == 1 else 200, json=MESSAGE) + provider = Mock(side_effect=["first-token", "second-token"]) + with create_client(base_url=BASE_URL, token_provider=provider, + transport=httpx.MockTransport(respond), max_retries=1) as client: + client.messages.create(**PARAMS) + self.assertEqual([r.headers["authorization"] for r in self.requests], + ["Bearer first-token", "Bearer second-token"]) + + +class AsyncClientAuthTests(unittest.IsolatedAsyncioTestCase): + async def test_async_provider_and_standard_client(self) -> None: + requests: list[httpx.Request] = [] + calls = 0 + async def token() -> str: + nonlocal calls + calls += 1 + return f"token-{calls}" + def respond(request: httpx.Request) -> httpx.Response: + requests.append(request) + return httpx.Response(200, json=MESSAGE) + with patch.dict(os.environ, {}, clear=True): + async with create_async_client(base_url=BASE_URL, token_provider=token, + transport=httpx.MockTransport(respond), max_retries=0) as client: + self.assertIs(type(client), AsyncAnthropic) + await client.messages.create(**PARAMS) + await client.messages.create(**PARAMS) + self.assertEqual([r.headers["authorization"] for r in requests], ["Bearer token-1", "Bearer token-2"]) + self.assertTrue(all("anthropic-beta" not in request.headers for request in requests)) + + async def test_cancellation_reaches_async_provider(self) -> None: + started = asyncio.Event() + async def token() -> str: + started.set() + await asyncio.Event().wait() + return "unreachable" + with patch.dict(os.environ, {}, clear=True): + async with create_async_client(base_url=BASE_URL, token_provider=token, + transport=httpx.MockTransport(lambda request: httpx.Response(200, json=MESSAGE)), + max_retries=0) as client: + task = asyncio.create_task(client.messages.create(**PARAMS)) + await asyncio.wait_for(started.wait(), timeout=5) + task.cancel() + with self.assertRaises(asyncio.CancelledError): + await task + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_samples.py b/tests/test_samples.py index 586dc3b..f7ca148 100644 --- a/tests/test_samples.py +++ b/tests/test_samples.py @@ -13,12 +13,13 @@ from unittest.mock import Mock, patch import httpx2 as httpx -from anthropic import AnthropicFoundry from azure.core.credentials import AccessToken sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) -import claude_auth +import client_auth +import sample_client +import token_provider import chat_stream @@ -26,16 +27,9 @@ DEPLOYMENT = "sample-opus-deployment" THINKING_BLOCK = {"type": "thinking", "thinking": "not for display", "signature": "sample"} MESSAGE = { - "id": "msg_sample", - "type": "message", - "role": "assistant", - "model": DEPLOYMENT, - "content": [ - THINKING_BLOCK, - {"type": "text", "text": "OK"}, - ], - "stop_reason": "end_turn", - "stop_sequence": None, + "id": "msg_sample", "type": "message", "role": "assistant", "model": DEPLOYMENT, + "content": [THINKING_BLOCK, {"type": "text", "text": "OK"}], + "stop_reason": "end_turn", "stop_sequence": None, "usage": {"input_tokens": 1, "output_tokens": 2}, } @@ -48,213 +42,263 @@ def test_provider_is_lazy_cached_and_refreshes_before_expiry(self) -> None: AccessToken("first-test-token", int(now + 3600)), AccessToken("refreshed-test-token", int(now + 7200)), ] - with ( - patch.dict(os.environ, {}, clear=True), - patch.object(claude_auth, "DefaultAzureCredential", return_value=credential), - ): - provider = claude_auth.entra_token_provider() - credential.get_token.assert_not_called() - self.assertEqual(provider(), "first-test-token") - self.assertEqual(provider(), "first-test-token") - self.assertEqual(credential.get_token.call_count, 1) - # Stay before expiry while allowing Azure Core's refresh jitter. - with patch("time.time", return_value=now + 3590): - self.assertEqual(provider(), "refreshed-test-token") - self.assertEqual(credential.get_token.call_count, 2) - self.assertEqual( - credential.get_token.call_args.args, ("https://ai.azure.com/.default",) - ) - self.assertNotIn("tenant_id", credential.get_token.call_args.kwargs) + provider = token_provider.cached_token_provider( + credential, "https://ai.azure.com/.default" + ) + credential.get_token.assert_not_called() + self.assertEqual(provider(), "first-test-token") + self.assertEqual(provider(), "first-test-token") + self.assertEqual(credential.get_token.call_count, 1) + with patch("time.time", return_value=now + 3590): + self.assertEqual(provider(), "refreshed-test-token") + self.assertEqual(credential.get_token.call_count, 2) + self.assertEqual( + credential.get_token.call_args.args, ("https://ai.azure.com/.default",) + ) + self.assertNotIn("tenant_id", credential.get_token.call_args.kwargs) def test_explicit_tenant_reaches_the_credential(self) -> None: credential = Mock(spec=["get_token"]) credential.get_token.return_value = AccessToken( "tenant-test-token", int(time.time() + 3600) ) - with ( - patch.dict(os.environ, {"AZURE_TENANT_ID": "example-tenant"}, clear=True), - patch.object(claude_auth, "DefaultAzureCredential", return_value=credential), - ): - provider = claude_auth.entra_token_provider() - self.assertEqual(provider(), "tenant-test-token") - self.assertEqual( - credential.get_token.call_args.kwargs["tenant_id"], "example-tenant" + provider = token_provider.cached_token_provider( + credential, "https://ai.azure.com/.default", tenant_id="example-tenant" ) + self.assertEqual(provider(), "tenant-test-token") + self.assertEqual(credential.get_token.call_args.kwargs["tenant_id"], "example-tenant") + + def test_credential_selection_has_no_silent_fallback(self) -> None: + with patch.object(token_provider, "AzureCliCredential") as cli: + token_provider.create_credential("AzureCliCredential", tenant_id="example-tenant") + cli.assert_called_once_with(tenant_id="example-tenant", process_timeout=60) + with patch.object(token_provider, "AzureDeveloperCliCredential") as azd: + token_provider.create_credential("AzureDeveloperCliCredential", tenant_id="example-tenant") + azd.assert_called_once_with(tenant_id="example-tenant", process_timeout=60) + with patch.object(token_provider, "ManagedIdentityCredential") as identity: + token_provider.create_credential("ManagedIdentityCredential", client_id="example-client") + identity.assert_called_once_with(client_id="example-client") + with self.assertRaisesRegex(ValueError, "AZURE_TOKEN_CREDENTIALS"): + token_provider.create_credential("typo") + + def test_selected_credential_constructors_work_without_patches(self) -> None: + for source in ("AzureCliCredential", "AzureDeveloperCliCredential", "ManagedIdentityCredential"): + with self.subTest(source=source), patch.dict(os.environ, {"AZURE_TOKEN_CREDENTIALS": source}, clear=True): + with token_provider.create_credential(source) as credential: + self.assertIsInstance(credential, getattr(token_provider, source)) + with self.assertRaisesRegex(ValueError, "AZURE_TOKEN_CREDENTIALS"): + token_provider.create_credential("DefaultAzureCredential") class SampleTests(unittest.TestCase): - def _client(self, requests: list[httpx.Request], **kwargs) -> AnthropicFoundry: + def _transport(self, requests: list[httpx.Request]) -> httpx.MockTransport: def respond(request: httpx.Request) -> httpx.Response: requests.append(request) return httpx.Response(200, json=MESSAGE) + return httpx.MockTransport(respond) - return AnthropicFoundry( - **kwargs, - http_client=httpx.Client(transport=httpx.MockTransport(respond)), - max_retries=0, + def _environment(self): + return patch.dict(os.environ, { + "CLAUDE_BASE_URL": BASE_URL, + "CLAUDE_DEPLOYMENT_NAME": DEPLOYMENT, + "CLAUDE_API_KEY": "sample-test-key", + "ANTHROPIC_FOUNDRY_RESOURCE": "sample-cli-resource", + }, clear=True) + + def _client_factory(self, requests: list[httpx.Request]): + return patch.object( + sample_client, "create_client", + side_effect=lambda **kwargs: client_auth.create_client( + **kwargs, transport=self._transport(requests), max_retries=0 + ), ) def test_entra_samples_handle_thinking_without_oauth_beta_headers(self) -> None: for name in ("hello_claude", "hello_claude_token_refresh"): with self.subTest(sample=name): - module = importlib.import_module(name) requests: list[httpx.Request] = [] output = io.StringIO() with ( - patch.dict( - os.environ, - { - "CLAUDE_BASE_URL": BASE_URL, - "CLAUDE_DEPLOYMENT_NAME": DEPLOYMENT, - "ANTHROPIC_FOUNDRY_RESOURCE": "sample-cli-resource", - }, - clear=True, - ), - patch.object(module, "load_dotenv"), - patch.object( - claude_auth, "entra_token_provider", - return_value=lambda: "entra-test-token" - ), - patch.object( - claude_auth, - "AnthropicFoundry", - side_effect=lambda **kwargs: self._client(requests, **kwargs), - ), + self._environment(), + patch.object(sample_client, "load_dotenv"), + patch.object(sample_client, "create_credential") as credential, + patch.object(sample_client, "cached_token_provider", return_value=lambda: "entra-test-token"), + self._client_factory(requests), contextlib.redirect_stdout(output), ): - self.assertEqual(module.main(), 0) + self.assertEqual(importlib.import_module(name).main(), 0) + self.assertEqual(os.environ["ANTHROPIC_FOUNDRY_RESOURCE"], "sample-cli-resource") + credential.return_value.__exit__.assert_called_once() self.assertIn("OK", output.getvalue()) self.assertIn("[usage] input=1 output=2", output.getvalue()) self.assertNotIn("not for display", output.getvalue()) self.assertEqual(len(requests), 1) - request = requests[0] - self.assertEqual(request.url.path, "/anthropic/v1/messages") - self.assertEqual(request.headers["authorization"], "Bearer entra-test-token") - self.assertNotIn("anthropic-beta", request.headers) - self.assertNotIn("x-api-key", request.headers) - self.assertEqual(json.loads(request.content)["model"], DEPLOYMENT) - - def test_api_key_sample_uses_foundry_headers_and_handles_thinking(self) -> None: - module = importlib.import_module("hello_claude_apikey") + self.assertEqual(requests[0].url.path, "/anthropic/v1/messages") + self.assertEqual(requests[0].headers["authorization"], "Bearer entra-test-token") + self.assertNotIn("anthropic-beta", requests[0].headers) + self.assertNotIn("x-api-key", requests[0].headers) + self.assertEqual(json.loads(requests[0].content)["model"], DEPLOYMENT) + + def test_api_key_sample_uses_configured_header_and_handles_thinking(self) -> None: requests: list[httpx.Request] = [] output = io.StringIO() with ( - patch.dict( - os.environ, - { - "CLAUDE_BASE_URL": BASE_URL, - "CLAUDE_DEPLOYMENT_NAME": DEPLOYMENT, - "CLAUDE_API_KEY": "sample-test-key", - "ANTHROPIC_FOUNDRY_RESOURCE": "sample-cli-resource", - }, - clear=True, - ), - patch.object(module, "load_dotenv"), - patch.object( - claude_auth, - "AnthropicFoundry", - side_effect=lambda **kwargs: self._client(requests, **kwargs), - ), + self._environment(), + patch.object(sample_client, "load_dotenv"), + self._client_factory(requests), contextlib.redirect_stdout(output), ): - self.assertEqual(module.main(), 0) + self.assertEqual(importlib.import_module("hello_claude_apikey").main(), 0) self.assertIn("OK", output.getvalue()) self.assertNotIn("not for display", output.getvalue()) - self.assertEqual(requests[0].headers["x-api-key"], "sample-test-key") - self.assertEqual(requests[0].headers["api-key"], "sample-test-key") - self.assertNotIn("authorization", requests[0].headers) + self.assertEqual(requests[0].headers["authorization"], "Bearer sample-test-key") + self.assertNotIn("x-api-key", requests[0].headers) - def test_streaming_client_uses_explicit_url_after_cli_activation(self) -> None: + def test_canonical_configuration_can_target_the_native_endpoint(self) -> None: requests: list[httpx.Request] = [] with ( - patch.dict( - os.environ, - { - "CLAUDE_BASE_URL": BASE_URL, - "CLAUDE_DEPLOYMENT_NAME": DEPLOYMENT, - "ANTHROPIC_FOUNDRY_RESOURCE": "sample-cli-resource", - }, - clear=True, - ), - patch.object(chat_stream, "load_dotenv"), - patch.object( - claude_auth, "entra_token_provider", return_value=lambda: "entra-test-token" - ), - patch.object( - claude_auth, - "AnthropicFoundry", - side_effect=lambda **kwargs: self._client(requests, **kwargs), - ), + self._environment(), + patch.dict(os.environ, { + "AUTH_MODE": "api_key", + "ANTHROPIC_BASE_URL": "https://api.anthropic.com", + "ANTHROPIC_MODEL": "claude-sonnet-5-5", + "ANTHROPIC_API_KEY": "native-test-key", + "API_KEY_HEADER": "Authorization", + "ANTHROPIC_API_VERSION": "2026-10-21", + }), + patch.object(sample_client, "load_dotenv"), + self._client_factory(requests), + contextlib.redirect_stdout(io.StringIO()), ): - client, deployment = chat_stream.build_client() - with client: - client.messages.create( - model=deployment, max_tokens=16, - messages=[{"role": "user", "content": "Hi"}], - ) - self.assertEqual(str(requests[0].url), BASE_URL + "/v1/messages") + self.assertEqual(importlib.import_module("hello_claude").main(), 0) + self.assertEqual(str(requests[0].url), "https://api.anthropic.com/v1/messages") + self.assertEqual(requests[0].headers["authorization"], "Bearer native-test-key") + self.assertEqual(requests[0].headers["anthropic-version"], "2026-10-21") def test_samples_report_missing_configuration(self) -> None: - for name in ("hello_claude", "hello_claude_token_refresh", "hello_claude_apikey"): + for name in ("hello_claude", "hello_claude_token_refresh", "hello_claude_apikey", "chat_stream"): with self.subTest(sample=name): - module = importlib.import_module(name) error = io.StringIO() with ( patch.dict(os.environ, {}, clear=True), - patch.object(module, "load_dotenv"), + patch.object(sample_client, "load_dotenv"), contextlib.redirect_stderr(error), ): - self.assertEqual(module.main(), 1) - expected = ( - "Set CLAUDE_BASE_URL, CLAUDE_DEPLOYMENT_NAME" - if name == "hello_claude_apikey" - else "Set CLAUDE_BASE_URL and CLAUDE_DEPLOYMENT_NAME" - ) - self.assertIn(expected, error.getvalue()) + self.assertEqual(importlib.import_module(name).main(), 1) + self.assertIn("Set CLAUDE_BASE_URL and CLAUDE_DEPLOYMENT_NAME", error.getvalue()) + + def test_legacy_endpoint_never_uses_an_ambient_native_key(self) -> None: + requests: list[httpx.Request] = [] + with ( + self._environment(), + patch.dict(os.environ, {"AUTH_MODE": "api_key", "ANTHROPIC_API_KEY": "native-canary"}), + patch.object(sample_client, "load_dotenv"), + self._client_factory(requests), + contextlib.redirect_stdout(io.StringIO()), + ): + self.assertEqual(importlib.import_module("hello_claude").main(), 0) + self.assertEqual(requests[0].headers["authorization"], "Bearer sample-test-key") + self.assertNotIn("native-canary", str(requests[0].headers)) + + def test_canonical_endpoint_never_falls_back_to_a_legacy_key(self) -> None: + with ( + self._environment(), + patch.dict(os.environ, { + "AUTH_MODE": "api_key", + "ANTHROPIC_BASE_URL": "https://api.anthropic.com", + "ANTHROPIC_MODEL": "claude-test", + }), + patch.object(sample_client, "load_dotenv"), + self.assertRaisesRegex(ValueError, "ANTHROPIC_API_KEY"), + ): + with sample_client.configured_client(): + self.fail("A key from a different profile must not be used.") + + def test_ambient_canonical_endpoint_requires_explicit_authentication(self) -> None: + with ( + self._environment(), + patch.dict(os.environ, { + "ANTHROPIC_BASE_URL": "https://api.anthropic.com", + "ANTHROPIC_MODEL": "claude-test", + }), + patch.object(sample_client, "load_dotenv"), + patch.object(sample_client, "create_credential") as credential, + self.assertRaisesRegex(ValueError, "AUTH_MODE"), + ): + with sample_client.configured_client(): + self.fail("An ambient endpoint must not receive the default bearer token.") + credential.assert_not_called() + + def test_dotenv_mode_cannot_authorize_an_ambient_process_endpoint(self) -> None: + def load_mode(*args, **kwargs) -> None: + os.environ["AUTH_MODE"] = "bearer" + with ( + self._environment(), + patch.dict(os.environ, { + "ANTHROPIC_BASE_URL": "https://api.anthropic.com", + "ANTHROPIC_MODEL": "claude-test", + }), + patch.object(sample_client, "load_dotenv", side_effect=load_mode), + patch.object(sample_client, "create_credential") as credential, + self.assertRaisesRegex(ValueError, "process environment"), + ): + with sample_client.configured_client(): + self.fail("A file default must not authorize an ambient process endpoint.") + credential.assert_not_called() + + def test_empty_canonical_endpoint_does_not_select_that_profile(self) -> None: + requests: list[httpx.Request] = [] + with ( + self._environment(), + patch.dict(os.environ, {"AUTH_MODE": "api_key", "ANTHROPIC_BASE_URL": ""}), + patch.object(sample_client, "load_dotenv"), + self._client_factory(requests), + contextlib.redirect_stdout(io.StringIO()), + ): + self.assertEqual(importlib.import_module("hello_claude").main(), 0) + self.assertEqual(str(requests[0].url), BASE_URL + "/v1/messages") + self.assertEqual(requests[0].headers["authorization"], "Bearer sample-test-key") + + def test_endpoint_is_validated_before_the_provider_is_warmed(self) -> None: + provider = Mock(return_value="test-token") + with ( + self._environment(), + patch.dict(os.environ, {"CLAUDE_BASE_URL": "http://insecure.example"}), + patch.object(sample_client, "load_dotenv"), + patch.object(sample_client, "create_credential"), + patch.object(sample_client, "cached_token_provider", return_value=provider), + self.assertRaisesRegex(ValueError, "HTTPS"), + ): + with sample_client.configured_client(): + self.fail("An insecure endpoint must not be used.") + provider.assert_not_called() def test_samples_report_thinking_only_responses_instead_of_succeeding(self) -> None: for name in ("hello_claude", "hello_claude_token_refresh", "hello_claude_apikey"): with self.subTest(sample=name): - module = importlib.import_module(name) output, error = io.StringIO(), io.StringIO() requests: list[httpx.Request] = [] with ( - patch.dict( - os.environ, - { - "CLAUDE_BASE_URL": BASE_URL, - "CLAUDE_DEPLOYMENT_NAME": DEPLOYMENT, - "CLAUDE_API_KEY": "sample-test-key", - }, - clear=True, - ), - patch.object(module, "load_dotenv"), - patch.object( - claude_auth, "entra_token_provider", - return_value=lambda: "entra-test-token", - ), - patch.object( - claude_auth, "AnthropicFoundry", - side_effect=lambda **kwargs: self._client(requests, **kwargs), - ), - patch.dict(MESSAGE, { - "content": [THINKING_BLOCK], "stop_reason": "max_tokens", - }), + self._environment(), + patch.object(sample_client, "load_dotenv"), + patch.object(sample_client, "create_credential"), + patch.object(sample_client, "cached_token_provider", return_value=lambda: "entra-test-token"), + self._client_factory(requests), + patch.dict(MESSAGE, {"content": [THINKING_BLOCK], "stop_reason": "max_tokens"}), contextlib.redirect_stdout(output), contextlib.redirect_stderr(error), ): - self.assertEqual(module.main(), 1) + self.assertEqual(importlib.import_module(name).main(), 1) self.assertIn("No text response", error.getvalue()) self.assertIn("max_tokens", error.getvalue()) self.assertNotIn("not for display", output.getvalue()) def test_streaming_chat_reports_an_empty_text_stream(self) -> None: client = Mock() - client.messages.stream.return_value = contextlib.nullcontext( - SimpleNamespace(text_stream=iter(())) - ) + client.messages.stream.return_value = contextlib.nullcontext(SimpleNamespace(text_stream=iter(()))) with ( - patch.object(chat_stream, "build_client", return_value=(client, DEPLOYMENT)), + patch.object(chat_stream, "configured_client", + return_value=contextlib.nullcontext((client, DEPLOYMENT))), patch("builtins.input", return_value="Hi"), contextlib.redirect_stdout(io.StringIO()), self.assertRaisesRegex(RuntimeError, "No text response"), @@ -264,24 +308,13 @@ def test_streaming_chat_reports_an_empty_text_stream(self) -> None: def test_streaming_chat_ignores_thinking_and_sends_conversation(self) -> None: events = [ ("message_start", {"message": MESSAGE | {"content": [], "stop_reason": None}}), - ("content_block_start", { - "index": 0, "content_block": {"type": "thinking", "thinking": ""} - }), - ("content_block_delta", { - "index": 0, "delta": {"type": "thinking_delta", "thinking": "not for display"} - }), + ("content_block_start", {"index": 0, "content_block": {"type": "thinking", "thinking": ""}}), + ("content_block_delta", {"index": 0, "delta": {"type": "thinking_delta", "thinking": "not for display"}}), ("content_block_stop", {"index": 0}), - ("content_block_start", { - "index": 1, "content_block": {"type": "text", "text": ""} - }), - ("content_block_delta", { - "index": 1, "delta": {"type": "text_delta", "text": "OK"} - }), + ("content_block_start", {"index": 1, "content_block": {"type": "text", "text": ""}}), + ("content_block_delta", {"index": 1, "delta": {"type": "text_delta", "text": "OK"}}), ("content_block_stop", {"index": 1}), - ("message_delta", { - "delta": {"stop_reason": "end_turn", "stop_sequence": None}, - "usage": {"output_tokens": 2}, - }), + ("message_delta", {"delta": {"stop_reason": "end_turn", "stop_sequence": None}, "usage": {"output_tokens": 2}}), ("message_stop", {}), ] body = "".join( @@ -292,20 +325,17 @@ def test_streaming_chat_ignores_thinking_and_sends_conversation(self) -> None: def respond(request: httpx.Request) -> httpx.Response: requests.append(request) - return httpx.Response( - 200, headers={"content-type": "text/event-stream"}, text=body - ) + return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=body) output = io.StringIO() with ( patch.dict(os.environ, {}, clear=True), - AnthropicFoundry( - base_url=BASE_URL, - azure_ad_token_provider=lambda: "entra-test-token", - http_client=httpx.Client(transport=httpx.MockTransport(respond)), - max_retries=0, + client_auth.create_client( + base_url=BASE_URL, token_provider=lambda: "entra-test-token", + transport=httpx.MockTransport(respond), max_retries=0, ) as client, - patch.object(chat_stream, "build_client", return_value=(client, DEPLOYMENT)), + patch.object(chat_stream, "configured_client", + return_value=contextlib.nullcontext((client, DEPLOYMENT))), patch("builtins.input", side_effect=["Hi", "exit"]), contextlib.redirect_stdout(output), ):