Skip to content

Commit 2abde61

Browse files
committed
fix: validate clientMetadataUrl at construction time for fail-fast behavior
Move clientMetadataUrl validation to all SDK-controlled entry points (StreamableHTTP/SSE constructors, auth(), withOAuth factory) so invalid URLs are caught immediately rather than deep in the auth flow. Exports validateClientMetadataUrl() for consumers who implement OAuthClientProvider directly. Existing defense-in-depth validation in authInternal() is preserved. Closes modelcontextprotocol#1159
1 parent 108f2f3 commit 2abde61

8 files changed

Lines changed: 312 additions & 6 deletions

File tree

‎packages/client/src/client/auth.ts‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -404,6 +404,9 @@ export async function auth(
404404
fetchFn?: FetchLike;
405405
}
406406
): Promise<AuthResult> {
407+
// Validate clientMetadataUrl before any network calls
408+
validateClientMetadataUrl(provider.clientMetadataUrl);
409+
407410
try {
408411
return await authInternal(provider, options);
409412
} catch (error) {
@@ -614,6 +617,29 @@ async function authInternal(
614617
return 'REDIRECT';
615618
}
616619

620+
/**
621+
* Validates that the given `clientMetadataUrl` is a valid HTTPS URL with a non-root pathname.
622+
*
623+
* This function is a no-op when `url` is `undefined` or empty (providers that do not use
624+
* URL-based client IDs are unaffected). When the value is defined but invalid, it throws
625+
* an {@linkcode OAuthError} with code {@linkcode OAuthErrorCode.InvalidClientMetadata}.
626+
*
627+
* SDK transports and the `auth()` function call this automatically. Consumers who implement
628+
* {@linkcode OAuthClientProvider} directly can call this in their own constructors for
629+
* early validation.
630+
*
631+
* @param url - The `clientMetadataUrl` value to validate (from `OAuthClientProvider.clientMetadataUrl`)
632+
* @throws {OAuthError} When `url` is defined but is not a valid HTTPS URL with a non-root pathname
633+
*/
634+
export function validateClientMetadataUrl(url: string | undefined): void {
635+
if (url && !isHttpsUrl(url)) {
636+
throw new OAuthError(
637+
OAuthErrorCode.InvalidClientMetadata,
638+
`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${url}`
639+
);
640+
}
641+
}
642+
617643
/**
618644
* SEP-991: URL-based Client IDs
619645
* Validate that the `client_id` is a valid URL with `https` scheme

‎packages/client/src/client/middleware.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import type { FetchLike } from '@modelcontextprotocol/core';
22

33
import type { OAuthClientProvider } from './auth.js';
4-
import { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js';
4+
import { auth, extractWWWAuthenticateParams, UnauthorizedError, validateClientMetadataUrl } from './auth.js';
55

66
/**
77
* Middleware function that wraps and enhances fetch functionality.
@@ -36,8 +36,11 @@ export type Middleware = (next: FetchLike) => FetchLike;
3636
* @returns A fetch middleware function
3737
*/
3838
export const withOAuth =
39-
(provider: OAuthClientProvider, baseUrl?: string | URL): Middleware =>
40-
next => {
39+
(provider: OAuthClientProvider, baseUrl?: string | URL): Middleware => {
40+
// Validate clientMetadataUrl at factory creation time (fail-fast)
41+
validateClientMetadataUrl(provider.clientMetadataUrl);
42+
43+
return next => {
4144
return async (input, init) => {
4245
const makeRequest = async (): Promise<Response> => {
4346
const headers = new Headers(init?.headers);
@@ -95,6 +98,7 @@ export const withOAuth =
9598
return response;
9699
};
97100
};
101+
};
98102

99103
/**
100104
* Logger function type for HTTP requests

‎packages/client/src/client/sse.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import type { ErrorEvent, EventSourceInit } from 'eventsource';
44
import { EventSource } from 'eventsource';
55

66
import type { AuthResult, OAuthClientProvider } from './auth.js';
7-
import { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js';
7+
import { auth, extractWWWAuthenticateParams, UnauthorizedError, validateClientMetadataUrl } from './auth.js';
88

99
export class SseError extends Error {
1010
constructor(
@@ -81,6 +81,11 @@ export class SSEClientTransport implements Transport {
8181
onmessage?: (message: JSONRPCMessage) => void;
8282

8383
constructor(url: URL, opts?: SSEClientTransportOptions) {
84+
// Validate clientMetadataUrl at construction time (fail-fast)
85+
if (opts?.authProvider) {
86+
validateClientMetadataUrl(opts.authProvider.clientMetadataUrl);
87+
}
88+
8489
this._url = url;
8590
this._resourceMetadataUrl = undefined;
8691
this._scope = undefined;

‎packages/client/src/client/streamableHttp.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import {
1414
import { EventSourceParserStream } from 'eventsource-parser/stream';
1515

1616
import type { AuthResult, OAuthClientProvider } from './auth.js';
17-
import { auth, extractWWWAuthenticateParams, UnauthorizedError } from './auth.js';
17+
import { auth, extractWWWAuthenticateParams, UnauthorizedError, validateClientMetadataUrl } from './auth.js';
1818

1919
// Default reconnection options for StreamableHTTP connections
2020
const DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS: StreamableHTTPReconnectionOptions = {
@@ -147,6 +147,11 @@ export class StreamableHTTPClientTransport implements Transport {
147147
onmessage?: (message: JSONRPCMessage) => void;
148148

149149
constructor(url: URL, opts?: StreamableHTTPClientTransportOptions) {
150+
// Validate clientMetadataUrl at construction time (fail-fast)
151+
if (opts?.authProvider) {
152+
validateClientMetadataUrl(opts.authProvider.clientMetadataUrl);
153+
}
154+
150155
this._url = url;
151156
this._resourceMetadataUrl = undefined;
152157
this._scope = undefined;

‎packages/client/test/client/auth.test.ts‎

Lines changed: 103 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ import {
1717
refreshAuthorization,
1818
registerClient,
1919
selectClientAuthMethod,
20-
startAuthorization
20+
startAuthorization,
21+
validateClientMetadataUrl
2122
} from '../../src/client/auth.js';
2223
import { createPrivateKeyJwtAuth } from '../../src/client/authExtensions.js';
2324

@@ -1993,6 +1994,28 @@ describe('OAuth Authorization', () => {
19931994
vi.clearAllMocks();
19941995
});
19951996

1997+
it('throws OAuthError with InvalidClientMetadata before any network request when clientMetadataUrl is invalid', async () => {
1998+
const providerWithInvalidUrl: OAuthClientProvider = {
1999+
...mockProvider,
2000+
clientMetadataUrl: 'http://invalid.example.com/metadata'
2001+
};
2002+
2003+
await expect(
2004+
auth(providerWithInvalidUrl, {
2005+
serverUrl: 'https://server.example.com'
2006+
})
2007+
).rejects.toThrow(OAuthError);
2008+
2009+
await expect(
2010+
auth(providerWithInvalidUrl, {
2011+
serverUrl: 'https://server.example.com'
2012+
})
2013+
).rejects.toMatchObject({ code: OAuthErrorCode.InvalidClientMetadata });
2014+
2015+
// Verify no fetch was called
2016+
expect(mockFetch).not.toHaveBeenCalled();
2017+
});
2018+
19962019
it('performs client_credentials with private_key_jwt when provider has addClientAuthentication', async () => {
19972020
// Arrange: metadata discovery for PRM and AS
19982021
mockFetch.mockImplementation(url => {
@@ -3406,6 +3429,85 @@ describe('OAuth Authorization', () => {
34063429
});
34073430
});
34083431

3432+
describe('validateClientMetadataUrl', () => {
3433+
it('passes for valid HTTPS URL with path', () => {
3434+
expect(() => validateClientMetadataUrl('https://client.example.com/.well-known/oauth-client')).not.toThrow();
3435+
});
3436+
3437+
it('passes for valid HTTPS URL with multi-segment path', () => {
3438+
expect(() => validateClientMetadataUrl('https://example.com/clients/metadata.json')).not.toThrow();
3439+
});
3440+
3441+
it('throws OAuthError for HTTP URL', () => {
3442+
expect(() => validateClientMetadataUrl('http://client.example.com/.well-known/oauth-client')).toThrow(OAuthError);
3443+
try {
3444+
validateClientMetadataUrl('http://client.example.com/.well-known/oauth-client');
3445+
} catch (error) {
3446+
expect(error).toBeInstanceOf(OAuthError);
3447+
expect((error as OAuthError).code).toBe(OAuthErrorCode.InvalidClientMetadata);
3448+
expect((error as OAuthError).message).toContain('http://client.example.com/.well-known/oauth-client');
3449+
}
3450+
});
3451+
3452+
it('throws OAuthError for non-URL string', () => {
3453+
expect(() => validateClientMetadataUrl('not-a-url')).toThrow(OAuthError);
3454+
try {
3455+
validateClientMetadataUrl('not-a-url');
3456+
} catch (error) {
3457+
expect(error).toBeInstanceOf(OAuthError);
3458+
expect((error as OAuthError).code).toBe(OAuthErrorCode.InvalidClientMetadata);
3459+
expect((error as OAuthError).message).toContain('not-a-url');
3460+
}
3461+
});
3462+
3463+
it('passes silently for empty string', () => {
3464+
// Empty string is falsy, so it passes through without throwing
3465+
expect(() => validateClientMetadataUrl('')).not.toThrow();
3466+
});
3467+
3468+
it('throws OAuthError for root-path HTTPS URL with trailing slash', () => {
3469+
expect(() => validateClientMetadataUrl('https://client.example.com/')).toThrow(OAuthError);
3470+
try {
3471+
validateClientMetadataUrl('https://client.example.com/');
3472+
} catch (error) {
3473+
expect(error).toBeInstanceOf(OAuthError);
3474+
expect((error as OAuthError).code).toBe(OAuthErrorCode.InvalidClientMetadata);
3475+
expect((error as OAuthError).message).toContain('https://client.example.com/');
3476+
}
3477+
});
3478+
3479+
it('throws OAuthError for root-path HTTPS URL without trailing slash', () => {
3480+
expect(() => validateClientMetadataUrl('https://client.example.com')).toThrow(OAuthError);
3481+
try {
3482+
validateClientMetadataUrl('https://client.example.com');
3483+
} catch (error) {
3484+
expect(error).toBeInstanceOf(OAuthError);
3485+
expect((error as OAuthError).code).toBe(OAuthErrorCode.InvalidClientMetadata);
3486+
expect((error as OAuthError).message).toContain('https://client.example.com');
3487+
}
3488+
});
3489+
3490+
it('passes silently for undefined', () => {
3491+
expect(() => validateClientMetadataUrl(undefined)).not.toThrow();
3492+
});
3493+
3494+
it('passes silently when called with no arguments', () => {
3495+
// eslint-disable-next-line unicorn/no-useless-undefined
3496+
expect(() => validateClientMetadataUrl(undefined)).not.toThrow();
3497+
});
3498+
3499+
it('error message matches expected format', () => {
3500+
try {
3501+
validateClientMetadataUrl('http://example.com/path');
3502+
} catch (error) {
3503+
expect(error).toBeInstanceOf(OAuthError);
3504+
expect((error as OAuthError).message).toBe(
3505+
'clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: http://example.com/path'
3506+
);
3507+
}
3508+
});
3509+
});
3510+
34093511
describe('SEP-991: URL-based Client ID fallback logic', () => {
34103512
const validClientMetadata = {
34113513
redirect_uris: ['http://localhost:3000/callback'],

‎packages/client/test/client/middleware.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { FetchLike } from '@modelcontextprotocol/core';
2+
import { OAuthError, OAuthErrorCode } from '@modelcontextprotocol/core';
23
import type { Mocked, MockedFunction, MockInstance } from 'vitest';
34

45
import type { OAuthClientProvider } from '../../src/client/auth.js';
@@ -44,6 +45,37 @@ describe('withOAuth', () => {
4445
mockFetch = vi.fn();
4546
});
4647

48+
describe('clientMetadataUrl validation', () => {
49+
it('throws OAuthError at factory call when provider.clientMetadataUrl is an invalid HTTP URL', () => {
50+
const providerWithInvalidUrl: Mocked<OAuthClientProvider> = {
51+
...mockProvider,
52+
clientMetadataUrl: 'http://example.com/metadata'
53+
};
54+
55+
expect(() => withOAuth(providerWithInvalidUrl, 'https://server.example.com')).toThrow(OAuthError);
56+
try {
57+
withOAuth(providerWithInvalidUrl, 'https://server.example.com');
58+
} catch (error) {
59+
expect(error).toBeInstanceOf(OAuthError);
60+
expect((error as OAuthError).code).toBe(OAuthErrorCode.InvalidClientMetadata);
61+
expect((error as OAuthError).message).toContain('http://example.com/metadata');
62+
}
63+
});
64+
65+
it('succeeds when clientMetadataUrl is a valid HTTPS URL', () => {
66+
const providerWithValidUrl: Mocked<OAuthClientProvider> = {
67+
...mockProvider,
68+
clientMetadataUrl: 'https://client.example.com/.well-known/oauth-client'
69+
};
70+
71+
expect(() => withOAuth(providerWithValidUrl, 'https://server.example.com')).not.toThrow();
72+
});
73+
74+
it('succeeds when clientMetadataUrl is undefined', () => {
75+
expect(() => withOAuth(mockProvider, 'https://server.example.com')).not.toThrow();
76+
});
77+
});
78+
4779
it('should add Authorization header when tokens are available (with explicit baseUrl)', async () => {
4880
mockProvider.tokens.mockResolvedValue({
4981
access_token: 'test-token',

‎packages/client/test/client/sse.test.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,67 @@ import type { OAuthClientProvider } from '../../src/client/auth.js';
1111
import { UnauthorizedError } from '../../src/client/auth.js';
1212
import { SSEClientTransport } from '../../src/client/sse.js';
1313

14+
describe('SSEClientTransport clientMetadataUrl validation', () => {
15+
it('throws OAuthError when authProvider.clientMetadataUrl is an invalid HTTP URL', () => {
16+
const provider: OAuthClientProvider = {
17+
get redirectUrl() {
18+
return 'http://localhost/callback';
19+
},
20+
get clientMetadata() {
21+
return { redirect_uris: ['http://localhost/callback'] };
22+
},
23+
clientMetadataUrl: 'http://example.com/metadata',
24+
clientInformation: vi.fn(),
25+
tokens: vi.fn(),
26+
saveTokens: vi.fn(),
27+
redirectToAuthorization: vi.fn(),
28+
saveCodeVerifier: vi.fn(),
29+
codeVerifier: vi.fn()
30+
};
31+
32+
expect(() => new SSEClientTransport(new URL('https://server.example.com/sse'), { authProvider: provider })).toThrow(OAuthError);
33+
});
34+
35+
it('succeeds when clientMetadataUrl is a valid HTTPS URL', () => {
36+
const provider: OAuthClientProvider = {
37+
get redirectUrl() {
38+
return 'http://localhost/callback';
39+
},
40+
get clientMetadata() {
41+
return { redirect_uris: ['http://localhost/callback'] };
42+
},
43+
clientMetadataUrl: 'https://client.example.com/.well-known/oauth-client',
44+
clientInformation: vi.fn(),
45+
tokens: vi.fn(),
46+
saveTokens: vi.fn(),
47+
redirectToAuthorization: vi.fn(),
48+
saveCodeVerifier: vi.fn(),
49+
codeVerifier: vi.fn()
50+
};
51+
52+
expect(() => new SSEClientTransport(new URL('https://server.example.com/sse'), { authProvider: provider })).not.toThrow();
53+
});
54+
55+
it('succeeds when clientMetadataUrl is undefined', () => {
56+
const provider: OAuthClientProvider = {
57+
get redirectUrl() {
58+
return 'http://localhost/callback';
59+
},
60+
get clientMetadata() {
61+
return { redirect_uris: ['http://localhost/callback'] };
62+
},
63+
clientInformation: vi.fn(),
64+
tokens: vi.fn(),
65+
saveTokens: vi.fn(),
66+
redirectToAuthorization: vi.fn(),
67+
saveCodeVerifier: vi.fn(),
68+
codeVerifier: vi.fn()
69+
};
70+
71+
expect(() => new SSEClientTransport(new URL('https://server.example.com/sse'), { authProvider: provider })).not.toThrow();
72+
});
73+
});
74+
1475
/**
1576
* Parses HTTP Basic auth from a request's Authorization header.
1677
* Returns the decoded client_id and client_secret, or undefined if the header is absent or malformed.

0 commit comments

Comments
 (0)