[auth] OAuth protected-resource-metadata: fallback on 4xx not just 404 (#879)

Co-authored-by: adam jones <domdomegg+git@gmail.com>
This commit is contained in:
Paul Carleton 2025-08-19 15:43:09 +01:00 • committed by GitHub
commit 1f5950be01
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -465,7 +465,7 @@ describe("StreamableHTTPClientTransport", () => {
// Verify custom fetch was used
expect(customFetch).toHaveBeenCalled();
// Global fetch should never have been called
expect(global.fetch).not.toHaveBeenCalled();
});
@ -589,32 +589,32 @@ describe("StreamableHTTPClientTransport", () => {
await expect(transport.send(message)).rejects.toThrow(UnauthorizedError);
expect(mockAuthProvider.redirectToAuthorization.mock.calls).toHaveLength(1);
});
describe('Reconnection Logic', () => {
let transport: StreamableHTTPClientTransport;
// Use fake timers to control setTimeout and make the test instant.
beforeEach(() => jest.useFakeTimers());
afterEach(() => jest.useRealTimers());
it('should reconnect a GET-initiated notification stream that fails', async () => {
// ARRANGE
transport = new StreamableHTTPClientTransport(new URL("http://localhost:1234/mcp"), {
reconnectionOptions: {
initialReconnectionDelay: 10,
maxRetries: 1,
initialReconnectionDelay: 10,
maxRetries: 1,
maxReconnectionDelay: 1000, // Ensure it doesn't retry indefinitely
reconnectionDelayGrowFactor: 1 // No exponential backoff for simplicity
}
});
const errorSpy = jest.fn();
transport.onerror = errorSpy;
const failingStream = new ReadableStream({
start(controller) { controller.error(new Error("Network failure")); }
});
const fetchMock = global.fetch as jest.Mock;
// Mock the initial GET request, which will fail.
fetchMock.mockResolvedValueOnce({
@ -628,13 +628,13 @@ describe("StreamableHTTPClientTransport", () => {
headers: new Headers({ "content-type": "text/event-stream" }),
body: new ReadableStream(),
});
// ACT
await transport.start();
// Trigger the GET stream directly using the internal method for a clean test.
await transport["_startOrAuthSse"]({});
await jest.advanceTimersByTimeAsync(20); // Trigger reconnection timeout
// ASSERT
expect(errorSpy).toHaveBeenCalledWith(expect.objectContaining({
message: expect.stringContaining('SSE stream disconnected: Error: Network failure'),
@ -644,25 +644,25 @@ describe("StreamableHTTPClientTransport", () => {
expect(fetchMock.mock.calls[0][1]?.method).toBe('GET');
expect(fetchMock.mock.calls[1][1]?.method).toBe('GET');
});
it('should NOT reconnect a POST-initiated stream that fails', async () => {
// ARRANGE
transport = new StreamableHTTPClientTransport(new URL("http://localhost:1234/mcp"), {
reconnectionOptions: {
initialReconnectionDelay: 10,
maxRetries: 1,
reconnectionOptions: {
initialReconnectionDelay: 10,
maxRetries: 1,
maxReconnectionDelay: 1000, // Ensure it doesn't retry indefinitely
reconnectionDelayGrowFactor: 1 // No exponential backoff for simplicity
}
});
const errorSpy = jest.fn();
transport.onerror = errorSpy;
const failingStream = new ReadableStream({
start(controller) { controller.error(new Error("Network failure")); }
});
const fetchMock = global.fetch as jest.Mock;
// Mock the POST request. It returns a streaming content-type but a failing body.
fetchMock.mockResolvedValueOnce({
@ -670,7 +670,7 @@ describe("StreamableHTTPClientTransport", () => {
headers: new Headers({ "content-type": "text/event-stream" }),
body: failingStream,
});
// A dummy request message to trigger the `send` logic.
const requestMessage: JSONRPCRequest = {
jsonrpc: '2.0',
@ -678,13 +678,13 @@ describe("StreamableHTTPClientTransport", () => {
id: 'request-1',
params: {},
};
// ACT
await transport.start();
// Use the public `send` method to initiate a POST that gets a stream response.
await transport.send(requestMessage);
await jest.advanceTimersByTimeAsync(20); // Advance time to check for reconnections
// ASSERT
expect(errorSpy).toHaveBeenCalledWith(expect.objectContaining({
message: expect.stringContaining('SSE stream disconnected: Error: Network failure'),
@ -718,7 +718,9 @@ describe("StreamableHTTPClientTransport", () => {
(global.fetch as jest.Mock)
// Initial connection
.mockResolvedValueOnce(unauthedResponse)
// Resource discovery
// Resource discovery, path aware
.mockResolvedValueOnce(unauthedResponse)
// Resource discovery, root
.mockResolvedValueOnce(unauthedResponse)
// OAuth metadata discovery
.mockResolvedValueOnce({
@ -770,7 +772,9 @@ describe("StreamableHTTPClientTransport", () => {
(global.fetch as jest.Mock)
// Initial connection
.mockResolvedValueOnce(unauthedResponse)
// Resource discovery
// Resource discovery, path aware
.mockResolvedValueOnce(unauthedResponse)
// Resource discovery, root
.mockResolvedValueOnce(unauthedResponse)
// OAuth metadata discovery
.mockResolvedValueOnce({
@ -822,7 +826,9 @@ describe("StreamableHTTPClientTransport", () => {
(global.fetch as jest.Mock)
// Initial connection
.mockResolvedValueOnce(unauthedResponse)
// Resource discovery
// Resource discovery, path aware
.mockResolvedValueOnce(unauthedResponse)
// Resource discovery, root
.mockResolvedValueOnce(unauthedResponse)
// OAuth metadata discovery
.mockResolvedValueOnce({
@ -888,7 +894,7 @@ describe("StreamableHTTPClientTransport", () => {
ok: false,
status: 404
});
// Create transport instance
transport = new StreamableHTTPClientTransport(new URL("http://localhost:1234/mcp"), {
authProvider: mockAuthProvider,
@ -901,14 +907,14 @@ describe("StreamableHTTPClientTransport", () => {
// Verify custom fetch was used
expect(customFetch).toHaveBeenCalled();
// Verify specific OAuth endpoints were called with custom fetch
const customFetchCalls = customFetch.mock.calls;
const callUrls = customFetchCalls.map(([url]) => url.toString());
// Should have called resource metadata discovery
expect(callUrls.some(url => url.includes('/.well-known/oauth-protected-resource'))).toBe(true);
// Should have called OAuth authorization server metadata discovery
expect(callUrls.some(url => url.includes('/.well-known/oauth-authorization-server'))).toBe(true);
@ -966,19 +972,19 @@ describe("StreamableHTTPClientTransport", () => {
// Verify custom fetch was used
expect(customFetch).toHaveBeenCalled();
// Verify specific OAuth endpoints were called with custom fetch
const customFetchCalls = customFetch.mock.calls;
const callUrls = customFetchCalls.map(([url]) => url.toString());
// Should have called resource metadata discovery
expect(callUrls.some(url => url.includes('/.well-known/oauth-protected-resource'))).toBe(true);
// Should have called OAuth authorization server metadata discovery
expect(callUrls.some(url => url.includes('/.well-known/oauth-authorization-server'))).toBe(true);
// Should have called token endpoint for authorization code exchange
const tokenCalls = customFetchCalls.filter(([url, options]) =>
const tokenCalls = customFetchCalls.filter(([url, options]) =>
url.toString().includes('/token') && options?.method === "POST"
);
expect(tokenCalls.length).toBeGreaterThan(0);