fix(sdk): preserve proxy authentication alongside provider credentials (#3450)

## Description

The TypeScript SDK omits its proxy `apiKey` when an OpenAI or Anthropic
provider credential is present, causing token-protected remote proxies
to reject those requests with 401. Send `X-Headroom-Proxy-Token` from
shared `rawFetch()` while preserving provider authentication and the
existing bearer fallback. The server already supports this header via
#3422.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)

## Changes Made

- Add the dedicated proxy-token header in `sdk/typescript/src/client.ts`
whenever an SDK proxy key is configured; provider
`Authorization`/`x-api-key` headers and the bearer fallback are
untouched.
- Add eight regression cases covering both providers with explicit keys,
environment keys, proxy-only authentication, and provider-only
authentication.

## Testing

- [x] Unit tests pass (`pytest`) — N/A, TypeScript-only change; `npm
test` run instead
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
cd sdk/typescript
npm test
Test Files  18 passed | 5 skipped (23)
Tests       302 passed | 33 skipped (335)
npm run typecheck  # passed
npm run build      # passed
git diff --check   # passed
```

## Real Behavior Proof

- Environment: macOS, Node.js 26.5.1; locked SDK dependencies installed
with `npm ci`.
- Exact command / steps: `cd sdk/typescript && npm ci && npm test --
test/client-expanded.test.ts`, then `npm test`, `npm run typecheck`,
`npm run build`.
- Observed result: before the fix, six of the eight new cases failed
because `X-Headroom-Proxy-Token` was absent from the request headers.
After the fix all eight pass and still assert the expected provider
headers (`Authorization: Bearer <provider-key>` for OpenAI, `x-api-key`
for Anthropic, bearer fallback when no provider key is set). Tests drive
the real SDK clients and inspect requests at a mocked fetch boundary.
- Not tested: live provider calls, a deployed remote proxy, and the
Python test suite. The SDK suite reports 33 skipped tests.

## Runtime Rollout Safety

- Rollout-managed feature(s): None. The header is sent unconditionally
from `rawFetch()` when a proxy key is configured; no rollout flag or
channel gate is involved.
- Minimum rollout channel: N/A — not rollout-managed; the fix ships to
every channel with the next SDK release.
- Stable/default behavior changed: Yes. When an SDK proxy key is
configured, chat/message requests now also carry
`X-Headroom-Proxy-Token`. Provider auth headers and the existing bearer
fallback are unchanged, and no header is added when no proxy key is set.
- Kill switch / disable path: Do not configure a proxy key (`apiKey`
option / `HEADROOM_API_KEY`) — the header is only added when one exists.
Otherwise pin the previous SDK version.
- Unsafe override required: No.
- Qualification impact: None. Server-side support for the header landed
in #3422, and proxies that do not read it ignore the extra header.
- Rollback path: Revert this commit, or pin the preceding SDK release.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] My changes generate no new warnings
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)

## Additional Notes

Python-specific template checks (`pytest`, `ruff`, `mypy`) are not
applicable to this TypeScript-only change; the equivalent SDK commands
are recorded above. Documentation is unchanged — no new dependencies or
public configuration options are introduced.
This commit is contained in:
trs-80
2026-09-24 16:52:16 -05:00
committed by GitHub
parent e92cccca00
commit ca4b47a3fc
2 changed files with 42 additions and 1 deletions
+1
View File
@@ -510,6 +510,7 @@ export class HeadroomClient implements HeadroomClientInterface {
...options.headers,
};
if (this.apiKey) {
headers["X-Headroom-Proxy-Token"] = this.apiKey;
// Don't override provider auth headers
if (!headers["Authorization"] && !headers["x-api-key"]) {
headers["Authorization"] = `Bearer ${this.apiKey}`;
+41 -1
View File
@@ -2,7 +2,7 @@
* Tests for expanded HeadroomClient — chat.completions, messages, metrics, CCR, etc.
* Uses mocked proxy (no real server needed).
*/
import { describe, it, expect, vi, beforeEach } from "vitest";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { HeadroomClient } from "../src/client.js";
const mockFetch = vi.fn();
@@ -17,6 +17,46 @@ function jsonResponse(data: any, ok = true) {
};
}
describe("provider requests authenticate to the proxy separately", () => {
beforeEach(() => {
mockFetch.mockReset();
mockFetch.mockResolvedValue(jsonResponse({}));
for (const name of ["HEADROOM_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY"]) {
vi.stubEnv(name, "");
}
});
afterEach(() => vi.unstubAllEnvs());
it.each([
["openai", "explicit"], ["anthropic", "explicit"],
["openai", "environment"], ["anthropic", "environment"],
["openai", "proxy-only"], ["anthropic", "proxy-only"],
["openai", "provider-only"], ["anthropic", "provider-only"],
])("sends the correct credentials for %s (%s)", async (provider, source) => {
const hasProxy = source !== "provider-only";
const hasProvider = source !== "proxy-only";
const fromEnv = source === "environment";
if (fromEnv) {
vi.stubEnv("HEADROOM_API_KEY", "proxy-token");
vi.stubEnv(provider === "openai" ? "OPENAI_API_KEY" : "ANTHROPIC_API_KEY", "provider-key");
}
const client = new HeadroomClient({
baseUrl: "http://proxy:8787",
apiKey: hasProxy && !fromEnv ? "proxy-token" : undefined,
providerApiKey: hasProvider && !fromEnv ? "provider-key" : undefined,
});
const params = { model: "test-model", messages: [{ role: "user" as const, content: "hello" }] };
await (provider === "openai" ? client.chat.completions.create(params) : client.messages.create(params));
const headers = new Headers(mockFetch.mock.calls[0][1].headers);
expect(headers.get("X-Headroom-Proxy-Token")).toBe(hasProxy ? "proxy-token" : null);
expect(headers.get("Authorization")).toBe(
hasProvider ? (provider === "openai" ? "Bearer provider-key" : null) : "Bearer proxy-token",
);
expect(headers.get("x-api-key")).toBe(hasProvider && provider === "anthropic" ? "provider-key" : null);
});
});
describe("HeadroomClient constructor", () => {
it("accepts extended options", () => {
const client = new HeadroomClient({