fix: read the SDK's own discovery state instead of a marker of our own

Copilot review (#2287), two findings — and taken together they said the marker
was the wrong mechanism, so this removes it rather than patching it again:

- A transient failure in our CIMD preflight recorded no marker, so a *successful*
  SDK fallback discovery that advertised CIMD was still stored as `dcr`.
- `existing` and `existingKind` could describe different registrations, because
  `clientInformation()` answers preregistered-first while `clientRegistrationKind()`
  prefers the issuer's dynamic slot.

SDK v2 `auth()` persists the authorization-server metadata via
`saveDiscoveryState` *before* it reads or writes client information, and it takes
its URL-based-client-ID branch — rather than `registerClient` — exactly when that
metadata advertises `client_id_metadata_document_supported` and a
`clientMetadataUrl` is configured. So the branch is not inferred at all now: it is
read back from the state the SDK itself just wrote.

`resolveSdkRegistrationKind` becomes two cases. A save for an issuer that already
has a registration under this `client_id` is a back-stamp, answered by that
registration's recorded kind — so an existing DCR on the metadata URL stays
`dcr`. A save for an issuer with none is a new registration, answered by the
discovery state, guarded on the metadata describing that same issuer.

This drops `cimdClientMetadataUrl` and its storage accessors entirely, and
restores `ensureCimdClientRegistration` to a plain issuer-bound pre-registration.
Invalid-client recovery, second-issuer CIMD, second-issuer DCR minting the
metadata URL, and preflight failure are all consequences of the two cases rather
than separate mechanisms.

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 02:03:12 -04:00
commit 6273790077
4 changed files with 183 additions and 306 deletions

View file

@ -17,28 +17,6 @@ function createProvider(storage: OAuthStorage): BaseOAuthClientProvider {
});
}
/** Discovery that advertises CIMD support for the default AS location. */
function cimdDiscoveryFetch(): typeof fetch {
return async (input: RequestInfo | URL) => {
const url = String(input);
if (url.includes("/.well-known/oauth-protected-resource")) {
return new Response(JSON.stringify({ resource: SERVER_URL }));
}
if (url.includes("/.well-known/oauth-authorization-server")) {
return new Response(
JSON.stringify({
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,
}),
);
}
throw new Error(`unexpected fetch: ${url}`);
};
}
describe("ensureCimdClientRegistration", () => {
let storage: OAuthStorage;
@ -47,8 +25,6 @@ describe("ensureCimdClientRegistration", () => {
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 () => {}),
@ -97,12 +73,6 @@ 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 () => {
@ -133,13 +103,6 @@ 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 () => {
@ -246,60 +209,6 @@ describe("ensureCimdClientRegistration", () => {
).resolves.toBeUndefined();
expect(storage.saveClientInformation).not.toHaveBeenCalled();
// No marker is invented either — nothing was learned about the AS.
expect(storage.saveCimdClientMetadataUrl).not.toHaveBeenCalled();
});
// #2242 (Copilot): an AS advertising CIMD is not on its own evidence that the
// registration standing for it is a CIMD one. RFC 7591 §3.2 leaves a
// dynamically issued `client_id` opaque, so a real DCR may carry this very
// URL — marking it would relabel it.
it("withdraws the marker when an existing DCR happens to use the metadata URL as its client_id", async () => {
storage.getClientInformation = vi.fn(
async (_url: string, preregistered?: boolean) =>
preregistered ? undefined : { client_id: METADATA_URL },
);
storage.getClientRegistrationKind = vi.fn(
async (): Promise<"dcr"> => "dcr",
);
const fetchFn = cimdDiscoveryFetch();
await ensureCimdClientRegistration({
serverUrl: SERVER_URL,
provider: createProvider(storage),
fetchFn,
});
expect(storage.saveClientInformation).not.toHaveBeenCalled();
expect(storage.saveCimdClientMetadataUrl).toHaveBeenCalledWith(
SERVER_URL,
"http://127.0.0.1:9999",
undefined,
);
});
it("reaffirms the marker for an existing registration already recorded as cimd", async () => {
storage.getClientInformation = vi.fn(
async (_url: string, preregistered?: boolean) =>
preregistered ? undefined : { client_id: METADATA_URL },
);
storage.getClientRegistrationKind = vi.fn(
async (): Promise<"cimd"> => "cimd",
);
const fetchFn = cimdDiscoveryFetch();
await ensureCimdClientRegistration({
serverUrl: SERVER_URL,
provider: createProvider(storage),
fetchFn,
});
expect(storage.saveClientInformation).not.toHaveBeenCalled();
expect(storage.saveCimdClientMetadataUrl).toHaveBeenCalledWith(
SERVER_URL,
"http://127.0.0.1:9999",
METADATA_URL,
);
});
it("no-ops when client information is already stored for the discovered issuer", async () => {

View file

@ -61,8 +61,6 @@ 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,8 +221,6 @@ 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),
@ -643,16 +641,38 @@ describe("OAuthNavigation", () => {
const ISSUER = "https://as.example.com";
const METADATA_URL = "https://app.example.com/client-metadata.json";
/** Storage holding this AS's CIMD marker for METADATA_URL. */
/** Discovery state as SDK `auth()` persists it before saving client info. */
function seedDiscovery(
storage: OAuthStorage,
issuer: string,
cimd: boolean,
) {
vi.mocked(storage.getDiscoveryState).mockResolvedValue({
authorizationServerUrl: issuer,
authorizationServerMetadata: {
issuer,
authorization_endpoint: `${issuer}/authorize`,
token_endpoint: `${issuer}/token`,
response_types_supported: ["code"],
...(cimd && { client_id_metadata_document_supported: true }),
},
});
}
/** Storage whose issuer slot already holds a CIMD registration. */
function makeCimdStorage(): OAuthStorage {
const storage = makeStorage();
vi.mocked(storage.getCimdClientMetadataUrl).mockResolvedValue(
METADATA_URL,
vi.mocked(storage.getClientInformation).mockImplementation(
async (_url: string, preregistered?: boolean) =>
preregistered ? undefined : { client_id: METADATA_URL },
);
vi.mocked(storage.getClientRegistrationKind).mockResolvedValue(
"cimd",
);
return storage;
}
it("keeps cimd when CIMD is configured and this issuer carries the marker", async () => {
it("keeps cimd when back-stamping a registration recorded as cimd", async () => {
const storage = makeCimdStorage();
const provider = makeProvider(storage, vi.fn(), {
clientMetadataUrl: METADATA_URL,
@ -663,10 +683,6 @@ describe("OAuthNavigation", () => {
{ issuer: ISSUER },
);
expect(storage.getCimdClientMetadataUrl).toHaveBeenCalledWith(
SERVER,
ISSUER,
);
expect(storage.saveClientInformation).toHaveBeenCalledWith(
SERVER,
{ client_id: METADATA_URL },
@ -674,24 +690,50 @@ 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();
// RFC 7591 §3.2 leaves a dynamically issued `client_id` opaque, so an
// existing DCR may carry the configured metadata URL. Back-stamping it
// must not relabel it (Copilot).
it("keeps dcr when back-stamping a DCR that uses the metadata URL", async () => {
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");
// Even with an AS that does advertise CIMD.
seedDiscovery(storage, ISSUER, true);
const provider = makeProvider(storage, vi.fn(), {
clientMetadataUrl: METADATA_URL,
});
await provider.saveClientInformation(
{ client_id: METADATA_URL },
{ issuer: ISSUER },
);
expect(storage.saveClientInformation).toHaveBeenCalledWith(
SERVER,
{ client_id: METADATA_URL },
{ registrationKind: "dcr", issuer: ISSUER },
);
});
// Nothing stored for this issuer, so the SDK is creating the
// registration. It reaches its URL-based-client-ID branch exactly when
// the AS advertises CIMD — read back from the discovery state it
// persisted moments earlier.
it("records cimd for a new registration when the AS advertises CIMD", async () => {
const storage = makeStorage();
seedDiscovery(storage, ISSUER, true);
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 },
@ -699,8 +741,47 @@ describe("OAuthNavigation", () => {
);
});
it("records dcr for a new registration when the AS does not advertise CIMD", async () => {
const storage = makeStorage();
seedDiscovery(storage, ISSUER, false);
const provider = makeProvider(storage, vi.fn(), {
clientMetadataUrl: METADATA_URL,
});
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 the discovery state describes a different issuer", async () => {
const storage = makeStorage();
seedDiscovery(storage, "https://as-other.example.com", true);
const provider = makeProvider(storage, vi.fn(), {
clientMetadataUrl: METADATA_URL,
});
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 for a server-minted client_id while CIMD is configured", async () => {
const storage = makeCimdStorage();
seedDiscovery(storage, ISSUER, true);
const provider = makeProvider(storage, vi.fn(), {
clientMetadataUrl: METADATA_URL,
});
@ -710,8 +791,9 @@ describe("OAuthNavigation", () => {
{ issuer: ISSUER },
);
// The id is not the metadata URL, so the marker is never consulted.
expect(storage.getCimdClientMetadataUrl).not.toHaveBeenCalled();
// The id is not the metadata URL, so nothing is read at all.
expect(storage.getClientInformation).not.toHaveBeenCalled();
expect(storage.getDiscoveryState).not.toHaveBeenCalled();
expect(storage.saveClientInformation).toHaveBeenCalledWith(
SERVER,
{ client_id: "dcr-minted-id" },
@ -719,8 +801,9 @@ describe("OAuthNavigation", () => {
);
});
it("records dcr when CIMD is not configured, even if the marker is set", async () => {
it("records dcr when CIMD is not configured for this connection", async () => {
const storage = makeCimdStorage();
seedDiscovery(storage, ISSUER, true);
const provider = makeProvider(storage);
await provider.saveClientInformation(
@ -735,48 +818,6 @@ describe("OAuthNavigation", () => {
);
});
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,
});
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 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();
const provider = makeProvider(storage, vi.fn(), {
clientMetadataUrl: METADATA_URL,
});
await provider.saveClientInformation(
{ client_id: METADATA_URL },
{ issuer: ISSUER },
);
expect(storage.saveClientInformation).toHaveBeenCalledWith(
SERVER,
{ client_id: METADATA_URL },
{ registrationKind: "dcr", issuer: ISSUER },
);
});
// SEP-2352 keys registrations per authorization server, so a second AS
// behind one resource is a separate determination. Driven against a real
// `OAuthStorageBase` and the real `ensureCimdClientRegistration`, because
@ -859,6 +900,16 @@ describe("OAuthNavigation", () => {
provider,
fetchFn: discoveryFetch(ISSUER_B, true),
});
await storage.saveDiscoveryState(SERVER, {
authorizationServerUrl: ISSUER_B,
authorizationServerMetadata: {
issuer: ISSUER_B,
authorization_endpoint: `${ISSUER_B}/authorize`,
token_endpoint: `${ISSUER_B}/token`,
response_types_supported: ["code"],
client_id_metadata_document_supported: true,
},
});
await provider.saveClientInformation(
{ client_id: METADATA_URL },
{ issuer: ISSUER_B },
@ -882,6 +933,20 @@ describe("OAuthNavigation", () => {
provider,
fetchFn: discoveryFetch(ISSUER_B, false),
});
// Discovery state as SDK `auth()` persists it for issuer B — which
// is what tells the save apart from a CIMD one. Seeded explicitly so
// the assertion rests on B's advertised capabilities rather than on
// discovery state merely being absent.
await storage.saveDiscoveryState(SERVER, {
authorizationServerUrl: ISSUER_B,
authorizationServerMetadata: {
issuer: ISSUER_B,
authorization_endpoint: `${ISSUER_B}/authorize`,
token_endpoint: `${ISSUER_B}/token`,
response_types_supported: ["code"],
},
});
// ...and RFC 7591 §3.2 lets it mint an opaque id that happens to be
// the very URL issuer A uses as its CIMD client_id.
await provider.saveClientInformation(
@ -920,10 +985,6 @@ describe("OAuthNavigation", () => {
provider,
fetchFn: discoveryFetch(ISSUER, true),
});
expect(
await storage.getCimdClientMetadataUrl(SERVER, ISSUER),
).toBeUndefined();
// The SDK's issuer back-stamp of that same registration.
await provider.saveClientInformation(
{ client_id: METADATA_URL },
@ -935,33 +996,38 @@ describe("OAuthNavigation", () => {
).toBe("dcr");
});
// 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 () => {
// SDK v2 `auth()` answers `invalid_client` with
// `invalidateCredentials("client")` and an immediate retry. That clear
// removes the registration *and* its kind, so the retry takes the
// new-registration path and must be answered from the discovery state
// — which the clear does not touch (Copilot). Asserted against real
// storage, since the point is what `clearClientInformation` does.
it("keeps cimd through invalid-client recovery, which clears the credential", async () => {
const storage = makeRealStorage();
const provider = await bindIssuerA(storage);
expect(await storage.getCimdClientMetadataUrl(SERVER, ISSUER)).toBe(
METADATA_URL,
);
// Discovery state as SDK `auth()` persisted it for issuer A.
await storage.saveDiscoveryState(SERVER, {
authorizationServerUrl: ISSUER,
authorizationServerMetadata: {
issuer: ISSUER,
authorization_endpoint: `${ISSUER}/authorize`,
token_endpoint: `${ISSUER}/token`,
response_types_supported: ["code"],
client_id_metadata_document_supported: true,
},
});
await provider.invalidateCredentials("client");
// The credential and its kind are gone...
// The credential and its recorded kind are both 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.
// ...so the SDK's retry re-runs its URL-based client-ID branch.
await provider.saveClientInformation(
{ client_id: METADATA_URL },
{ issuer: ISSUER },

View file

@ -70,8 +70,6 @@ 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),
};