From 5e62b7e1e5ca0606f89b466b2aeeca249fb3f870 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Thu, 24 Sep 2026 12:22:36 +0900 Subject: [PATCH] fix(auth): validate credential header values as control-free ByteStrings (R-3.4) The shared credential admission (V2 and V3) only rejected CR/LF. A token with NUL, a non-Latin-1 character or another control character passed, then Fetch rejected it after V3 had marked the attempt dispatched: a query burned its retry budget and a command ended MAYBE_APPLIED with NETWORK_FAILURE. The external session adapter also merged header names that differ only in case, silently keeping the last value. - admitCredentialHeaders: the value must match [\x20-\x7E\xA0-\xFF]+ (a ByteString without C0/C1 controls); the size limit is now the string length, which is the wire byte count for a ByteString. Failure stays CREDENTIAL_HEADER_VALUE_INVALID, i.e. AUTH_INTEGRATION_FAILURE before dispatch. - checkFinalInvariants: builds `new Headers(headers)` first; any value Fetch would reject fails as HEADER_VALUE_INVALID (new additive member of FinalInvariantFailure) with zero fetch calls. - validateCredentialPatch: rejects case-only duplicate header names. RED before fix: http-execution-v3-live-authority.test.ts "rejects a NUL / non-Latin-1 credential value before dispatch" (got TRANSPORT_FAILURE, fetch called), http-contract-bridge.test.ts "rejects a NUL/non-Latin-1/tab/DEL/C1 control value ..." and "fails before dispatch when Fetch would reject a header value", auth-session-adapter.test.ts "rejects credential headers that differ only in case instead of merging them". Pinned: "admits an ordinary bearer token", CR/LF rejection, existing "Bearer ok"/"Bearer token" integration paths. Gates: check:architecture, check:types:app, check:types:test, lint, test:component, test:integration, test:contract, test:platform, test:reference-feature pass. test:unit passes except removal-fixture.test.ts (needs generated artifacts/ release evidence absent in a fresh worktree; unrelated). Co-Authored-By: Claude Opus 5.5 --- src/adapters/auth/external-session-adapter.ts | 2 + src/adapters/http/http-contract-bridge.ts | 20 ++++- .../http-execution-v3-live-authority.test.ts | 44 +++++++++++ tests/unit/auth-session-adapter.test.ts | 22 ++++++ tests/unit/http-contract-bridge.test.ts | 76 ++++++++++++++++++- 5 files changed, 160 insertions(+), 4 deletions(-) diff --git a/src/adapters/auth/external-session-adapter.ts b/src/adapters/auth/external-session-adapter.ts index 92774f93..33eb531c 100644 --- a/src/adapters/auth/external-session-adapter.ts +++ b/src/adapters/auth/external-session-adapter.ts @@ -37,6 +37,8 @@ export function validateCredentialPatch(value: unknown): CredentialPatch { for (const [name, headerValue] of Object.entries(headers)) { const normalizedName = name.toLowerCase(); if ( + // Names that differ only in case would silently overwrite each other. + Object.hasOwn(projected, normalizedName) || !ALLOWED_CREDENTIAL_HEADERS.has(normalizedName) || typeof headerValue !== "string" || headerValue.length === 0 || diff --git a/src/adapters/http/http-contract-bridge.ts b/src/adapters/http/http-contract-bridge.ts index 4dd62335..1232cf86 100644 --- a/src/adapters/http/http-contract-bridge.ts +++ b/src/adapters/http/http-contract-bridge.ts @@ -50,6 +50,13 @@ export type CredentialAdmissionOutcome = const MAX_CREDENTIAL_HEADER_VALUE_BYTES = 8_192; +/** + * R-3.4. The one credential value rule for V2 and V3: a ByteString (every code + * unit one byte on the wire) with no C0/C1 control characters. Fetch rejects + * anything else only after the request counts as dispatched. + */ +const CREDENTIAL_HEADER_VALUE = /^[\x20-\x7E\xA0-\xFF]+$/; + /** * ยง7.7. Admits a credential patch against the resolved profile before any * header object is built. A rejection here guarantees `fetch()` is not called: @@ -82,9 +89,8 @@ export function admitCredentialHeaders( } if ( typeof value !== "string" || - value.length === 0 || - /[\r\n]/.test(value) || - encoder.encode(value).byteLength > MAX_CREDENTIAL_HEADER_VALUE_BYTES + !CREDENTIAL_HEADER_VALUE.test(value) || + value.length > MAX_CREDENTIAL_HEADER_VALUE_BYTES ) { return frozenAdmissionFailure("CREDENTIAL_HEADER_VALUE_INVALID"); } @@ -325,6 +331,7 @@ export type FinalInvariantFailure = | "CREDENTIAL_HEADER_NOT_ALLOWED" | "MISSING_REQUIRED_CREDENTIAL_HEADER" | "FORBIDDEN_HEADER" + | "HEADER_VALUE_INVALID" | "REQUEST_BODY_TOO_LARGE" | "DEADLINE_EXPIRED" | "SCOPE_FENCED"; @@ -383,6 +390,13 @@ export function checkFinalInvariants( return "MISSING_REQUIRED_CREDENTIAL_HEADER"; } } + // Fetch validates header values only once it is called; build them here so + // any value it would reject fails before dispatch, not as a network error. + try { + new Headers(input.headers); + } catch { + return "HEADER_VALUE_INVALID"; + } if ( input.request.bodyBytes && diff --git a/tests/integration/http-execution-v3-live-authority.test.ts b/tests/integration/http-execution-v3-live-authority.test.ts index 3471322a..685eadd6 100644 --- a/tests/integration/http-execution-v3-live-authority.test.ts +++ b/tests/integration/http-execution-v3-live-authority.test.ts @@ -281,6 +281,50 @@ describe("LIVE-01 credential integration failures are not user session failures" ); }); + /** + * R-3.4. Fetch rejects a header value that is not a control-free ByteString. + * Letting that reach `fetch()` reported an auth defect as a network failure + * after dispatch (MAYBE_APPLIED for a command). + */ + it.each([ + ["NUL", "Bearer abc\u0000def"], + ["non-Latin-1", "Bearer ํ•œ"], + ])( + "rejects a %s credential value before dispatch", + async (_label, value) => { + const fetcher = vi.fn( + async (_url: RequestInfo | URL, init?: RequestInit) => { + new Headers(init?.headers); + return jsonResponse([]); + }, + ); + const executor = createContractHttpExecutor({ + baseUrl: "https://api.example/", + maxRetryAttempts: 0, + authProfiles: TEST_PROFILES, + attachCredentials: () => + Object.freeze({ + kind: "READY" as const, + headers: Object.freeze({ authorization: value }), + }), + fetcher: fetcher as unknown as typeof fetch, + }); + + const outcome = await executor.execute( + bearerOperation(), + { limit: 1 }, + { routeId: ROUTE_ID, scope: scopeSnapshot() }, + ); + + expect(outcome).toMatchObject({ + kind: "AUTH_INTEGRATION_FAILURE", + reason: "CREDENTIAL_HEADER_VALUE_INVALID", + effect: "NOT_APPLICABLE", + }); + expect(fetcher).not.toHaveBeenCalled(); + }, + ); + it("still reports a real absent session as UNAUTHENTICATED", async () => { const fetcher = vi.fn(async () => jsonResponse([])); const executor = createContractHttpExecutor({ diff --git a/tests/unit/auth-session-adapter.test.ts b/tests/unit/auth-session-adapter.test.ts index 9832825d..bb600de7 100644 --- a/tests/unit/auth-session-adapter.test.ts +++ b/tests/unit/auth-session-adapter.test.ts @@ -68,6 +68,28 @@ describe("external AuthSessionPort adapter", () => { ).rejects.toThrow("forbidden credential patch"); }); + it("rejects credential headers that differ only in case instead of merging them", async () => { + const adapter = createExternalAuthSessionAdapter({ + readState: () => "authenticated", + subscribe: () => () => {}, + beginSignIn: async () => {}, + signOut: async () => {}, + attachCredential: async () => ({ + headers: { Authorization: "Bearer a", authorization: "Bearer b" }, + }), + recoverSession: async () => "restored", + notifyUnauthenticated: vi.fn(), + }); + + await expect( + adapter.credentialPatch({ + origin: "https://api.test", + method: "GET", + operationId: "GET_RESOURCE", + }), + ).rejects.toThrow("forbidden credential patch"); + }); + it("provides a safe anonymous adapter", async () => { const adapter = createAnonymousSessionAdapter(); expect(adapter.getState()).toBe("unauthenticated"); diff --git a/tests/unit/http-contract-bridge.test.ts b/tests/unit/http-contract-bridge.test.ts index 429008fd..218e7a67 100644 --- a/tests/unit/http-contract-bridge.test.ts +++ b/tests/unit/http-contract-bridge.test.ts @@ -1,8 +1,82 @@ import { describe, expect, it } from "vitest"; -import { projectRequest } from "../../src/adapters/http/http-contract-bridge.ts"; +import { + admitCredentialHeaders, + checkFinalInvariants, + projectRequest, +} from "../../src/adapters/http/http-contract-bridge.ts"; import { TEST_DETAIL_HTTP_CONTRACT } from "../helpers/external-contract-fixture.ts"; +const BEARER_PROFILE = Object.freeze({ + authProfileId: "TEST_BEARER", + transport: "BEARER_HEADER" as const, + credentials: "omit" as const, + allowedCredentialHeaders: Object.freeze(["authorization" as const]), + requiredCredentialHeaders: Object.freeze(["authorization" as const]), +}); + +describe("credential header admission", () => { + it.each([ + ["NUL", "Bearer abc\u0000def"], + ["non-Latin-1", "Bearer ํ•œ"], + ["tab", "Bearer abc\tdef"], + ["DEL", "Bearer abc\u007fdef"], + ["C1 control", "Bearer abc\u0085def"], + ["CR/LF", "Bearer abc\r\nX-Evil: 1"], + ])("rejects a %s value before any header object is built", (_label, value) => { + expect( + admitCredentialHeaders({ authorization: value }, BEARER_PROFILE), + ).toEqual({ ok: false, failure: "CREDENTIAL_HEADER_VALUE_INVALID" }); + }); + + it("admits an ordinary bearer token", () => { + const token = "Bearer eyJhbGciOi.J9-abc_DEF~+/="; + expect( + admitCredentialHeaders({ Authorization: token }, BEARER_PROFILE), + ).toEqual({ ok: true, headers: { authorization: token } }); + }); + + it("rejects names that differ only in case", () => { + expect( + admitCredentialHeaders( + { Authorization: "Bearer a", authorization: "Bearer b" }, + BEARER_PROFILE, + ).ok, + ).toBe(false); + }); +}); + +describe("final request invariants", () => { + it("fails before dispatch when Fetch would reject a header value", () => { + const request = Object.freeze({ + url: "https://api.test/base/x", + method: "POST", + bodyBytes: null, + }); + const init: RequestInit = { + method: "POST", + redirect: "error", + credentials: "omit", + }; + expect( + checkFinalInvariants({ + request, + expectedMethod: "POST", + baseUrl: "https://api.test/base/", + init, + headers: { + authorization: "Bearer ok", + "Idempotency-Key": "ํ‚ค", + }, + requestByteLimit: 0, + deadlineRemainingMs: 1_000, + scopeIsCurrent: true, + authProfile: BEARER_PROFILE, + }), + ).toBe("HEADER_VALUE_INVALID"); + }); +}); + describe("descriptor-driven path projection", () => { it.each([".", ".."])( "rejects the dot segment %j instead of letting URL resolution move the target",