fix: record CIMD provenance as an issuer-keyed marker, not on the credential

Copilot review (#2287), three findings:

1. **invalid-client recovery lost the provenance.** SDK v2 `auth()` answers
   `invalid_client` / `unauthorized_client` with `invalidateCredentials("client")`
   and an immediate retry; our clear drops the registration *and* its kind, so
   the retry's URL-based client-ID save landed with nothing recorded and was
   stored as `dcr`. Provenance now lives in `cimdClientMetadataUrl`, an
   issuer-keyed marker on the issuer slot that records a property of the AS
   rather than a credential — `clearClientInformation` deliberately leaves it
   alone. `ensureCimdClientRegistration` writes it, and withdraws it when the AS
   stops advertising CIMD, on every connect.

2. **Discovery became a hard network dependency.** Moving the existing-client
   check after discovery meant a well-known outage could fail a reconnect the SDK
   would have served from its persisted discovery state. Reuse
   `provider.discoveryState()` first, and treat a discovery failure as "skip
   pre-registration" rather than an error — this helper is an optimization over
   what `auth()` does for itself.

3. **Dropped an unjustified double cast** in the test fetch helper; the async
   signature is directly assignable to `typeof fetch`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Lmj6X2epWpPE7ScdSKQmtA
Signed-off-by: cliffhall <cliff@futurescale.com>
This commit is contained in:
cliffhall 2026-09-07 01:34:03 -04:00
commit 4297ef8449
4 changed files with 299 additions and 108 deletions

View file

@ -24,6 +24,9 @@ describe("ensureCimdClientRegistration", () => {
storage = {
getClientInformation: vi.fn(async () => undefined),
saveClientInformation: vi.fn(async () => {}),
getDiscoveryState: vi.fn(async () => undefined),
getCimdClientMetadataUrl: vi.fn(async () => undefined),
saveCimdClientMetadataUrl: vi.fn(async () => {}),
getScope: vi.fn().mockResolvedValue(undefined),
getTokens: vi.fn(async () => undefined),
saveTokens: vi.fn(async () => {}),
@ -72,6 +75,12 @@ describe("ensureCimdClientRegistration", () => {
},
{ registrationKind: "cimd", issuer: "http://127.0.0.1:9999" },
);
// The provenance marker for this AS, which outlives the credential.
expect(storage.saveCimdClientMetadataUrl).toHaveBeenCalledWith(
SERVER_URL,
"http://127.0.0.1:9999",
METADATA_URL,
);
});
it("does not register when the AS metadata omits CIMD support", async () => {
@ -102,6 +111,13 @@ describe("ensureCimdClientRegistration", () => {
});
expect(storage.saveClientInformation).not.toHaveBeenCalled();
// The marker is actively withdrawn, not merely left unwritten, so an AS that
// stops advertising CIMD stops being treated as one.
expect(storage.saveCimdClientMetadataUrl).toHaveBeenCalledWith(
SERVER_URL,
"http://127.0.0.1:9999",
undefined,
);
});
it("discovers protected-resource metadata at the challenge-advertised URL (#2071)", async () => {
@ -161,6 +177,57 @@ describe("ensureCimdClientRegistration", () => {
);
});
// #2242 (Copilot): the existing-client check moved after discovery, so this
// helper must not turn a well-known outage into a failed reconnect. It reuses
// the discovery state SDK `auth()` persists, and treats a discovery failure as
// "skip pre-registration" rather than an error.
it("reuses persisted discovery state instead of re-fetching", async () => {
storage.getDiscoveryState = vi.fn(async () => ({
authorizationServerUrl: "http://127.0.0.1:9999",
authorizationServerMetadata: {
issuer: "http://127.0.0.1:9999",
authorization_endpoint: "http://127.0.0.1:9999/oauth/authorize",
token_endpoint: "http://127.0.0.1:9999/oauth/token",
response_types_supported: ["code"],
client_id_metadata_document_supported: true,
},
}));
const fetchFn = vi.fn(async () => {
throw new Error("discovery must not run when state is cached");
});
await ensureCimdClientRegistration({
serverUrl: SERVER_URL,
provider: createProvider(storage),
fetchFn,
});
expect(fetchFn).not.toHaveBeenCalled();
expect(storage.saveClientInformation).toHaveBeenCalledWith(
SERVER_URL,
{ client_id: METADATA_URL },
{ registrationKind: "cimd", issuer: "http://127.0.0.1:9999" },
);
});
it("skips pre-registration when discovery fails, rather than throwing", async () => {
const fetchFn = vi.fn(async () => {
throw new Error("well-known endpoint is down");
});
await expect(
ensureCimdClientRegistration({
serverUrl: SERVER_URL,
provider: createProvider(storage),
fetchFn,
}),
).resolves.toBeUndefined();
expect(storage.saveClientInformation).not.toHaveBeenCalled();
// No marker is invented either — nothing was learned about the AS.
expect(storage.saveCimdClientMetadataUrl).not.toHaveBeenCalled();
});
it("no-ops when client information is already stored for the discovered issuer", async () => {
// Dynamic slot only — a preregistered hit would short-circuit
// `clientInformation()` before it ever reaches the issuer-keyed read.

View file

@ -61,6 +61,8 @@ function createStorage(
getCodeVerifier: vi.fn(),
getDiscoveryState: vi.fn().mockResolvedValue(undefined),
saveDiscoveryState: vi.fn(),
getCimdClientMetadataUrl: vi.fn(async () => undefined),
saveCimdClientMetadataUrl: vi.fn(async () => undefined),
clearDiscoveryState: vi.fn(),
};
}

View file

@ -221,6 +221,8 @@ describe("OAuthNavigation", () => {
getScope: vi.fn().mockResolvedValue(undefined),
getClientInformation: vi.fn(async () => undefined),
getClientRegistrationKind: vi.fn(async () => undefined),
getCimdClientMetadataUrl: vi.fn(async () => undefined),
saveCimdClientMetadataUrl: vi.fn(async () => undefined),
saveClientInformation: vi.fn(async () => undefined),
savePreregisteredClientInformation: vi.fn(async () => undefined),
saveScope: vi.fn(async () => undefined),
@ -641,20 +643,16 @@ describe("OAuthNavigation", () => {
const ISSUER = "https://as.example.com";
const METADATA_URL = "https://app.example.com/client-metadata.json";
/** Storage already holding the CIMD pre-registration for METADATA_URL. */
/** Storage holding this AS's CIMD marker for METADATA_URL. */
function makeCimdStorage(): OAuthStorage {
const storage = makeStorage();
vi.mocked(storage.getClientInformation).mockImplementation(
async (_url: string, preregistered?: boolean) =>
preregistered ? undefined : { client_id: METADATA_URL },
);
vi.mocked(storage.getClientRegistrationKind).mockResolvedValue(
"cimd",
vi.mocked(storage.getCimdClientMetadataUrl).mockResolvedValue(
METADATA_URL,
);
return storage;
}
it("keeps cimd when CIMD is configured and the stored registration matches", async () => {
it("keeps cimd when CIMD is configured and this issuer carries the marker", async () => {
const storage = makeCimdStorage();
const provider = makeProvider(storage, vi.fn(), {
clientMetadataUrl: METADATA_URL,
@ -665,11 +663,8 @@ describe("OAuthNavigation", () => {
{ issuer: ISSUER },
);
// Reads the dynamic slot for this issuer, which falls back to the
// unkeyed slot the pre-registration wrote.
expect(storage.getClientInformation).toHaveBeenCalledWith(
expect(storage.getCimdClientMetadataUrl).toHaveBeenCalledWith(
SERVER,
false,
ISSUER,
);
expect(storage.saveClientInformation).toHaveBeenCalledWith(
@ -679,6 +674,31 @@ describe("OAuthNavigation", () => {
);
});
// SDK v2 `auth()` answers `invalid_client` / `unauthorized_client` with
// `invalidateCredentials("client")` and an immediate retry. That clears
// the stored registration *and* its kind, so provenance read off the
// credential would be gone by the time the retry's CIMD save lands
// (Copilot). The marker is not a credential and survives.
it("keeps cimd through invalid-client recovery, which clears the credential", async () => {
const storage = makeCimdStorage();
const provider = makeProvider(storage, vi.fn(), {
clientMetadataUrl: METADATA_URL,
});
await provider.invalidateCredentials("client");
await provider.saveClientInformation(
{ client_id: METADATA_URL },
{ issuer: ISSUER },
);
expect(storage.clearClientInformation).toHaveBeenCalledWith(SERVER);
expect(storage.saveClientInformation).toHaveBeenCalledWith(
SERVER,
{ client_id: METADATA_URL },
{ registrationKind: "cimd", issuer: ISSUER },
);
});
it("records dcr for a server-minted client_id while CIMD is configured", async () => {
const storage = makeCimdStorage();
const provider = makeProvider(storage, vi.fn(), {
@ -690,10 +710,8 @@ describe("OAuthNavigation", () => {
{ issuer: ISSUER },
);
// The id is not the metadata URL, so nothing is read and nothing is
// carried forward.
expect(storage.getClientInformation).not.toHaveBeenCalled();
expect(storage.getClientRegistrationKind).not.toHaveBeenCalled();
// The id is not the metadata URL, so the marker is never consulted.
expect(storage.getCimdClientMetadataUrl).not.toHaveBeenCalled();
expect(storage.saveClientInformation).toHaveBeenCalledWith(
SERVER,
{ client_id: "dcr-minted-id" },
@ -701,7 +719,7 @@ describe("OAuthNavigation", () => {
);
});
it("records dcr when CIMD is not configured, even if storage says cimd", async () => {
it("records dcr when CIMD is not configured, even if the marker is set", async () => {
const storage = makeCimdStorage();
const provider = makeProvider(storage);
@ -717,29 +735,11 @@ describe("OAuthNavigation", () => {
);
});
it("records dcr when the metadata URL differs from the configured one", async () => {
const storage = makeCimdStorage();
const provider = makeProvider(storage, vi.fn(), {
clientMetadataUrl: "https://other.example.com/client-metadata.json",
});
await provider.saveClientInformation(
{ client_id: METADATA_URL },
{ issuer: ISSUER },
);
expect(storage.saveClientInformation).toHaveBeenCalledWith(
SERVER,
{ client_id: METADATA_URL },
{ registrationKind: "dcr", issuer: ISSUER },
);
});
it("records dcr when no CIMD registration was ever stored", async () => {
// The AS returns the configured metadata URL from a real registration
// (RFC 7591 §3.2 leaves the id opaque). With nothing recorded as CIMD
// under that id, the save is still DCR.
it("records dcr when the marker names a different metadata URL", async () => {
const storage = makeStorage();
vi.mocked(storage.getCimdClientMetadataUrl).mockResolvedValue(
"https://other.example.com/client-metadata.json",
);
const provider = makeProvider(storage, vi.fn(), {
clientMetadataUrl: METADATA_URL,
});
@ -756,13 +756,11 @@ describe("OAuthNavigation", () => {
);
});
it("records dcr when the stored kind under that id is not cimd", async () => {
it("records dcr when this issuer carries no marker", async () => {
// The AS returns the configured metadata URL from a real registration
// (RFC 7591 §3.2 leaves the id opaque). With no marker for this AS,
// the save is still DCR.
const storage = makeStorage();
vi.mocked(storage.getClientInformation).mockImplementation(
async (_url: string, preregistered?: boolean) =>
preregistered ? undefined : { client_id: METADATA_URL },
);
vi.mocked(storage.getClientRegistrationKind).mockResolvedValue("dcr");
const provider = makeProvider(storage, vi.fn(), {
clientMetadataUrl: METADATA_URL,
});
@ -802,8 +800,8 @@ describe("OAuthNavigation", () => {
* has to name the AS, so that the RFC 8414 §3.3 issuer echo the SDK
* enforces resolves against the AS URL rather than the resource's.
*/
function discoveryFetch(issuer: string, cimd: boolean) {
return (async (input: RequestInfo | URL) => {
function discoveryFetch(issuer: string, cimd: boolean): typeof fetch {
return async (input: RequestInfo | URL) => {
const url = String(input);
if (url.includes("/.well-known/oauth-protected-resource")) {
return new Response(
@ -827,7 +825,7 @@ describe("OAuthNavigation", () => {
);
}
throw new Error(`unexpected fetch: ${url}`);
}) as unknown as typeof fetch;
};
}
/** Issuer A pre-registers via CIMD, then the SDK binds it. */
@ -900,6 +898,43 @@ describe("OAuthNavigation", () => {
).toBe("cimd");
});
// The provenance marker's whole reason for existing: SDK v2 `auth()`
// answers `invalid_client` with `invalidateCredentials("client")` and
// an immediate retry, and that clear removes the credential *and* its
// registration kind. Asserted against real storage, since the point is
// what `clearClientInformation` does and does not touch (Copilot).
it("keeps the CIMD marker through invalid-client credential invalidation", async () => {
const storage = makeRealStorage();
const provider = await bindIssuerA(storage);
expect(await storage.getCimdClientMetadataUrl(SERVER, ISSUER)).toBe(
METADATA_URL,
);
await provider.invalidateCredentials("client");
// The credential and its kind are gone...
expect(
await storage.getClientInformation(SERVER, false, ISSUER),
).toBeUndefined();
expect(
await storage.getClientRegistrationKind(SERVER, ISSUER),
).toBeUndefined();
// ...but the marker is not a credential, so it survives.
expect(await storage.getCimdClientMetadataUrl(SERVER, ISSUER)).toBe(
METADATA_URL,
);
// The SDK's retry re-runs its URL-based client-ID branch.
await provider.saveClientInformation(
{ client_id: METADATA_URL },
{ issuer: ISSUER },
);
expect(
await storage.getClientRegistrationKind(SERVER, ISSUER),
).toBe("cimd");
});
it("records dcr for a second issuer that mints its own client_id", async () => {
const storage = makeRealStorage();
const provider = await bindIssuerA(storage);

View file

@ -70,6 +70,8 @@ function createMockParams(
takeRevocationSnapshot: vi.fn().mockResolvedValue({ byIssuer: {} }),
getDiscoveryState: vi.fn().mockResolvedValue(undefined),
saveDiscoveryState: vi.fn().mockResolvedValue(undefined),
getCimdClientMetadataUrl: vi.fn(async () => undefined),
saveCimdClientMetadataUrl: vi.fn(async () => undefined),
clearDiscoveryState: vi.fn().mockResolvedValue(undefined),
};