Skip to content

Commit 12a4315

Browse files
authored
fix: reject unknown Anthropic model cursors and document auth changes (#551)
## Problem Unknown `after_id` and `before_id` values returned successful empty Anthropic model pages. Authentication docs missed the new native error-body migration details. The CI drift rule also required the old cursor behavior and rejected the corrected response. ## Why SDK callers need an error for an invalid cursor. Apps reading the old string `error.code` need to know that Anthropic omits it and Gemini/Vertex return numeric `401`. CI must check the new response while retaining its known missing-request-ID warning and the historical base comparison. ## Fix Reject unknown Anthropic cursors with HTTP 400, including with lifecycle filters. Keep valid paging and empty filtered pages working. Update README, changelog, provider docs, cursor tests and the drift grading rule. Header enforcement stays opt-in. The grading rule requires the exact status, error type, message and single known warning. It accepts the old empty-page policy only for cached base evidence. Regression tests mutate receipts, assertions and diffs to verify the gate still rejects mismatches. A saved actual CI receipt replay passes with 11 advisories and no blocks; this does not claim full response-body parity or fresh authenticated calls. Validation: format, lint, typecheck, all 428 test files (17,456 passed; 11 existing skips), build, package exports, all 14 unchanged API reports, and actionlint with ShellCheck passed. The earlier free-RAM test failure passed unchanged. Separate Node/Bun consumers passed 48 cursor checks each plus the original 38 each. Stacked above #542 using GitHub's native stack #552. The provider compatibility follow-up is #553, based on this PR. Merge only after required checks pass, in stack order.
2 parents da120be + 29afd48 commit 12a4315

13 files changed

Lines changed: 1329 additions & 57 deletions

File tree

‎.github/workflows/test-drift.yml‎

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -442,7 +442,7 @@ jobs:
442442
REPO: ${{ github.repository }}
443443
run: |
444444
PREV=$(gh run list --workflow="Drift Tests" --repo="${REPO}" --branch=main --limit=2 --json conclusion --jq '.[1].conclusion // "unknown"')
445-
echo "conclusion=$PREV" >> $GITHUB_OUTPUT
445+
echo "conclusion=$PREV" >> "$GITHUB_OUTPUT"
446446
447447
- name: Notify Slack
448448
env:
@@ -1070,7 +1070,8 @@ jobs:
10701070
("id" in diff && diff.id !== diff.path)) throw new Error("Unexpected native diff metadata");
10711071
return JSON.stringify([diff.severity, diff.issue, diff.path, diff.expected, diff.real, diff.mock]);
10721072
};
1073-
const classifyNative = (reportPath: string, observationPath: string, evidenceDir: string) => {
1073+
const classifyNative = (reportPath: string, observationPath: string, evidenceDir: string,
1074+
options: { allowLegacyCursorPolicy?: boolean } = {}) => {
10741075
const report = object(read(reportPath));
10751076
const artifact = object(read(observationPath));
10761077
if (typeof report.generatedAt !== "string" || report.generatedAt !== artifact.generatedAt || !Array.isArray(artifact.observations) || !Array.isArray(report.entries))
@@ -1177,17 +1178,39 @@ jobs:
11771178
"native provider Gemini auth local contracts", geminiLocal);
11781179
retain("Gemini native authentication", "inbound policy divergence", "src/response/errors.ts", ["renderError"], gemini, geminiLocal);
11791180
1180-
// The documented local catalog retains empty pages for both unknown cursor directions.
1181+
// Current cursors match native 400 errors. Only cached BASE receipts may
1182+
// retain the old exact empty-page policy from before this fix.
11811183
const emptyPage = { status: 200, body: { data: [], has_more: false, first_id: null, last_id: null } };
11821184
for (const direction of ["after", "before"]) {
11831185
const id = `anthropic-${direction}-unknown`;
11841186
const cursor = receipt(`vendor:${id}`, "anthropic-catalog");
11851187
anthropicError(cursor.expected, 400, "invalid_request_error", "Model with id aimock-nonexistent-model not found");
11861188
assertion(`${id} received status/body (evidence only)`, "passed", "native provider Anthropic catalog vendor observations");
1187-
assertion(`${id} comparison`, "failed", "native provider Anthropic catalog vendor observations");
1188-
localContract(`local:${id}`, "anthropic-catalog", `'${id}'`, "native provider catalog local contracts", emptyPage);
1189-
retain("Anthropic native catalog", `Native catalog comparison ${id}`, "src/response/catalog/anthropic-page.ts",
1190-
["anthropicPage", "renderAnthropicModels"], cursor, emptyPage);
1189+
const legacy = options.allowLegacyCursorPolicy === true && isDeepStrictEqual(cursor.actual, emptyPage);
1190+
const local = legacy ? emptyPage : { status: 400, body: { type: "error", error: {
1191+
type: "invalid_request_error", message: "Model with id aimock-nonexistent-model not found"
1192+
} } };
1193+
assertion(`${id} comparison`, legacy ? "failed" : "passed", "native provider Anthropic catalog vendor observations");
1194+
localContract(`local:${id}`, "anthropic-catalog", `'${id}'`, "native provider catalog local contracts", local);
1195+
if (!legacy) {
1196+
if (!isDeepStrictEqual(cursor.actual, local))
1197+
throw new Error(`Unexpected native cursor response: ${id}`);
1198+
// Catalog errors omit the vendor request_id. Bind that one known
1199+
// warning, including its full metadata; no other diff is allowed.
1200+
const expectedWarning = { severity: "warning", issue: "PROVIDER ADDED FIELD — in real API but not in SDK or mock",
1201+
path: "request_id", expected: "<absent>", real: "string", mock: "<absent>" };
1202+
const received = nativeResponseDiffs(cursor.expected, cursor.actual).map(normalizeDiff);
1203+
if (!isDeepStrictEqual(received, [normalizeDiff(expectedWarning)]))
1204+
throw new Error(`Unexpected native cursor differences: ${id}`);
1205+
// Passing comparisons do not emit report entries. An added entry
1206+
// would be unbound evidence, even if its warning looks familiar.
1207+
if (entries.some((entry) => entry.provider === "Anthropic native catalog" &&
1208+
entry.scenario === `Native catalog comparison ${id}`))
1209+
throw new Error(`Unexpected native cursor report entry: ${id}`);
1210+
} else {
1211+
retain("Anthropic native catalog", `Native catalog comparison ${id}`, "src/response/catalog/anthropic-page.ts",
1212+
["anthropicPage", "renderAnthropicModels"], cursor, local);
1213+
}
11911214
}
11921215
const policyKeys = new Set(validatedEntries.flatMap((entry) => (entry.diffs as unknown[]).map((value) =>
11931216
JSON.stringify([entry.provider, entry.scenario, String(object(value).id ?? object(value).path)]))));
@@ -1238,7 +1261,8 @@ jobs:
12381261
if (mode !== "delta") {
12391262
try {
12401263
const disposition = classifyNative(process.env.NATIVE_REPORT_PATH ?? "drift-report.json",
1241-
process.env.NATIVE_OBSERVATIONS_PATH ?? "drift-observations.json", process.env.NATIVE_EVIDENCE_DIR ?? "drift-evidence");
1264+
process.env.NATIVE_OBSERVATIONS_PATH ?? "drift-observations.json", process.env.NATIVE_EVIDENCE_DIR ?? "drift-evidence",
1265+
{ allowLegacyCursorPolicy: mode === "cache" });
12421266
const rawExit = Number(process.env.NATIVE_RAW_EXIT_CODE);
12431267
const effectiveExit = rawExit === 2 ? disposition.effectiveExit : rawExit;
12441268
console.log(JSON.stringify({ rawExit, effectiveExit, invocationId: disposition.invocationId, policy: "validated documented native policy differences" }));

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,13 @@
1212

1313
- Responses API (HTTP, SSE, WebSocket): optional `phase` response override (`commentary` | `final_answer`) on assistant message output items; validated on load (#531)
1414

15+
### Changed
16+
17+
- **Authentication error compatibility:** configured inbound auth no longer returns the string `error.code: "invalid_api_key"` on Anthropic Messages/count and Gemini/Vertex Google HTTP paths. Anthropic omits `error.code`; check HTTP 401 or `error.type: "authentication_error"`. Google returns numeric `error.code: 401`; check HTTP 401 or `error.status: "UNAUTHENTICATED"`. Update clients and tests that read the old field. Shared `/v1/models` and WebSocket rejections keep their existing bodies.
18+
1519
### Fixed
1620

21+
- Anthropic model lists reject unknown `after_id` and `before_id` cursors with 400 `invalid_request_error`, including when a lifecycle filter would return an empty page. Valid cursors and OpenAI-style lists keep their existing paging behavior.
1722
- Shared `/v1/models` paths select the Anthropic catalog when `anthropic-version` is present, or when `x-api-key` is present without `Authorization`. Non-Anthropic clients that use `x-api-key` alone also receive that catalog. Use `Authorization` without `anthropic-version` to retain the OpenAI format.
1823
- Configured inbound authentication returns native 401 bodies on Anthropic Messages/count and Gemini/Vertex Google HTTP paths. Anthropic adds a `request-id` response header. Shared model paths and WebSocket rejections retain their existing bodies. Anthropic's upstream diagnostic message and body `request_id` differ. The observed Gemini gateway 403 differs from aimock's intentional inbound 401.
1924

‎README.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,7 +258,9 @@ await createServer(fixtures, { auth: { apiKeys: ["test-key"] } });
258258
AIMOCK_API_KEYS=test-key,rotated-key npx @copilotkit/aimock --config aimock.json
259259
```
260260

261-
Use `Authorization: Bearer <key>`, `Authorization: Key <key>`, `x-api-key`, `x-goog-api-key`, `api-key`, or `xi-api-key`. Every supplied credential must resolve to one configured key; mismatches return `401` with an OpenAI-compatible authentication error. HTTP routes, control APIs, mounts, and WebSocket upgrades are protected. Genuine CORS preflights plus `GET /health`, `GET /ready`, and `GET /metrics` remain public. This is inbound test access control, distinct from `record.providerKeys`; when enabled, proxying strips test credentials and requires a configured static provider credential before egress.
261+
Use `Authorization: Bearer <key>`, `Authorization: Key <key>`, `x-api-key`, `x-goog-api-key`, `api-key`, or `xi-api-key`. Every supplied credential must resolve to one configured key; mismatches return `401`. HTTP routes, control APIs, mounts, and WebSocket upgrades are protected. Genuine CORS preflights plus `GET /health`, `GET /ready`, and `GET /metrics` remain public. This is inbound test access control, distinct from `record.providerKeys`; when enabled, proxying strips test credentials and requires a configured static provider credential before egress.
262+
263+
**Auth error compatibility:** Anthropic Messages/count now omit the old `error.code: "invalid_api_key"`; check HTTP 401 or `error.type: "authentication_error"`. Gemini/Vertex Google HTTP paths replace that string with numeric `error.code: 401`; check HTTP 401 or `error.status: "UNAUTHENTICATED"`. Shared `/v1/models`, other HTTP paths, and WebSocket rejections keep their existing OpenAI-shaped error bodies. See the [Anthropic](docs/claude-messages/index.html#authentication-errors) and [Gemini](docs/gemini/index.html#authentication-errors) examples before updating client assertions.
262264

263265
### aimock-owned upstream keys — `AIMOCK_PROVIDER_*_KEY`
264266

‎docs/claude-messages/index.html‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -120,12 +120,11 @@ <h2 id="model-catalog">Model Catalog</h2>
120120
page.
121121
</p>
122122
<p>
123-
Invalid limits and lifecycle values return 400 <code>invalid_request_error</code>. Unknown
124-
cursors return an empty page, with null first and last IDs. These error details and cursor
125-
results are local contracts. Authenticated upstream probes with unknown
126-
<code>after_id</code> and <code>before_id</code> returned 400
127-
<code>invalid_request_error</code>. aimock intentionally retains empty pages for those
128-
cursors.
123+
Invalid limits, lifecycle values, and unknown <code>after_id</code> or
124+
<code>before_id</code> cursors return 400 <code>invalid_request_error</code>. Unknown
125+
cursors return <code>Model with id &lt;id&gt; not found</code>, matching the status, error
126+
type, and message observed in authenticated upstream probes. aimock validates cursors
127+
before applying lifecycle filters, including filters that return an empty page.
129128
</p>
130129
<p>
131130
Each model has <code>type: "model"</code>, its ID as <code>display_name</code>,
@@ -184,6 +183,12 @@ <h2 id="authentication-errors">Authentication Errors</h2>
184183
<div class="code-block-header">Inbound rejection <span class="lang-tag">json</span></div>
185184
<pre><code>{"type":"error","error":{"type":"authentication_error","message":"Invalid API key"}}</code></pre>
186185
</div>
186+
<p>
187+
Compatibility change: these paths no longer return
188+
<code>error.code: "invalid_api_key"</code>. Check HTTP 401 or
189+
<code>error.type: "authentication_error"</code> instead. Update tests and clients that
190+
read the old field.
191+
</p>
187192
<p>
188193
Shared <code>/v1/models</code> paths retain their OpenAI-shaped authentication rejection,
189194
even with Anthropic headers. WebSocket authentication also retains its existing body.

‎docs/gemini/index.html‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,13 @@ <h2 id="authentication-errors">Authentication Errors</h2>
184184
<div class="code-block-header">Inbound rejection <span class="lang-tag">json</span></div>
185185
<pre><code>{"error":{"code":401,"message":"Invalid API key","status":"UNAUTHENTICATED"}}</code></pre>
186186
</div>
187+
<p>
188+
Compatibility change: Gemini and Vertex Google HTTP paths replace the string
189+
<code>error.code: "invalid_api_key"</code> with the numeric
190+
<code>error.code: 401</code> and <code>error.status: "UNAUTHENTICATED"</code>. Check HTTP
191+
401 or the status string instead of the old code. Update tests and clients that read that
192+
field.
193+
</p>
187194
<p>
188195
A live unauthenticated Gemini count probe returned 403 <code>PERMISSION_DENIED</code>
189196
for an unregistered caller. aimock intentionally retains 401

‎src/__tests__/drift/models.drift.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,12 +117,30 @@ const anthropicCatalogCases = [
117117
{
118118
id: "anthropic-after-unknown",
119119
query: "after_id=aimock-nonexistent-model",
120-
expected: { status: 200, body: emptyAnthropicPage },
120+
expected: {
121+
status: 400,
122+
body: {
123+
type: "error",
124+
error: {
125+
type: "invalid_request_error",
126+
message: "Model with id aimock-nonexistent-model not found",
127+
},
128+
},
129+
},
121130
},
122131
{
123132
id: "anthropic-before-unknown",
124133
query: "before_id=aimock-nonexistent-model",
125-
expected: { status: 200, body: emptyAnthropicPage },
134+
expected: {
135+
status: 400,
136+
body: {
137+
type: "error",
138+
error: {
139+
type: "invalid_request_error",
140+
message: "Model with id aimock-nonexistent-model not found",
141+
},
142+
},
143+
},
126144
},
127145
{
128146
id: "anthropic-lifecycle-invalid",

0 commit comments

Comments
 (0)