fix(extensions): guard channel runtime fetches

This commit is contained in:
Peter Steinberger
2026-04-17 17:27:09 +01:00
parent c580933623
commit 41ef752dd8
4 changed files with 60 additions and 29 deletions

View File

@@ -8,6 +8,15 @@ function clearTestUndiciRuntimeDepsOverride(): void {
Reflect.deleteProperty(globalThis as object, TEST_UNDICI_RUNTIME_DEPS_KEY);
}
function stubRuntimeFetch(fetchImpl: typeof fetch): void {
(globalThis as Record<string, unknown>)[TEST_UNDICI_RUNTIME_DEPS_KEY] = {
Agent: function MockAgent() {},
EnvHttpProxyAgent: function MockEnvHttpProxyAgent() {},
ProxyAgent: function MockProxyAgent() {},
fetch: fetchImpl,
};
}
describe("performMatrixRequest", () => {
beforeEach(() => {
vi.unstubAllGlobals();
@@ -19,8 +28,7 @@ describe("performMatrixRequest", () => {
});
it("rejects oversized raw responses before buffering the whole body", async () => {
vi.stubGlobal(
"fetch",
stubRuntimeFetch(
vi.fn(
async () =>
new Response("too-big", {
@@ -55,8 +63,7 @@ describe("performMatrixRequest", () => {
controller.close();
},
});
vi.stubGlobal(
"fetch",
stubRuntimeFetch(
vi.fn(
async () =>
new Response(stream, {
@@ -87,8 +94,7 @@ describe("performMatrixRequest", () => {
controller.enqueue(new Uint8Array([1, 2, 3]));
},
});
vi.stubGlobal(
"fetch",
stubRuntimeFetch(
vi.fn(
async () =>
new Response(stream, {
@@ -135,12 +141,7 @@ describe("performMatrixRequest", () => {
},
});
});
(globalThis as Record<string, unknown>)[TEST_UNDICI_RUNTIME_DEPS_KEY] = {
Agent: function MockAgent() {},
EnvHttpProxyAgent: function MockEnvHttpProxyAgent() {},
ProxyAgent: function MockProxyAgent() {},
fetch: runtimeFetch,
};
stubRuntimeFetch(runtimeFetch);
const result = await performMatrixRequest({
homeserver: "http://127.0.0.1:8008",

View File

@@ -89,13 +89,6 @@ function buildBufferedResponse(params: {
return response;
}
function isMockedFetch(fetchImpl: typeof fetch | undefined): boolean {
if (typeof fetchImpl !== "function") {
return false;
}
return typeof (fetchImpl as typeof fetch & { mock?: unknown }).mock === "object";
}
async function fetchWithMatrixDispatcher(params: {
url: string;
init: MatrixDispatcherRequestInit;
@@ -104,10 +97,7 @@ async function fetchWithMatrixDispatcher(params: {
// fetches must stay fail-closed unless a retry path can preserve the
// validated pinned-address binding. Route dispatcher-attached requests
// through undici runtime fetch so the pinned dispatcher is preserved.
if (params.init.dispatcher && !isMockedFetch(globalThis.fetch)) {
return await fetchWithRuntimeDispatcher(params.url, params.init);
}
return await fetch(params.url, params.init);
return await fetchWithRuntimeDispatcher(params.url, params.init);
}
async function fetchWithMatrixGuardedRedirects(params: {