harden v2 custom widgets and workshop
This commit is contained in:
1 parent
e8a2c87c2d
commit
723b46926a
194 files changed
+44862
-1265
No files matched your search
@@ -45,4 +45,26 @@ describe("AI prompt", () => {
|
||||
expect(prompt.endsWith(CUSTOM_WIDGET_FINAL_OUTPUT_INSTRUCTION)).toBe(true);
|
||||
expect(prompt.length).toBeLessThanOrEqual(12_000);
|
||||
});
|
||||
|
||||
it("redacts embedded request credentials while retaining harmless request metadata", () => {
|
||||
const prompt = buildCustomWidgetAiPrompt(undefined, null, {
|
||||
requests: {
|
||||
status: {
|
||||
path: "/status?credential=Bearer-sk-secret-123456",
|
||||
headers: {
|
||||
"X-Auth": "Bearer sk-secret-123456",
|
||||
"X-Service": "Basic dXNlcjpwYXNz",
|
||||
"X-Feature-Key": "dashboard-layout",
|
||||
},
|
||||
},
|
||||
},
|
||||
template: "<Text>Bearer ghp_abcdefghijklmnopqrstuvwxyz123456</Text>",
|
||||
});
|
||||
|
||||
expect(prompt).not.toContain("sk-secret-123456");
|
||||
expect(prompt).not.toContain("dXNlcjpwYXNz");
|
||||
expect(prompt).not.toContain("ghp_abcdefghijklmnopqrstuvwxyz123456");
|
||||
expect(prompt).toContain('"X-Auth": "[REDACTED]"');
|
||||
expect(prompt).toContain('"X-Feature-Key": "dashboard-layout"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,186 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import type * as NetworkPolicy from "../server/network-policy";
|
||||
import type { CustomWidgetHttpRequest } from "../server/request-executor";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
lookup: vi.fn(),
|
||||
createPinnedAgent: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("node:dns/promises", () => ({ lookup: mocks.lookup }));
|
||||
vi.mock("../server/network-policy", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof NetworkPolicy>();
|
||||
return { ...actual, createPinnedAgent: mocks.createPinnedAgent };
|
||||
});
|
||||
|
||||
import { executeCustomWidgetRequest, MAX_REQUEST_DURATION_MS } from "../server/request-executor";
|
||||
import { resolveAndValidateHost } from "../server/network-policy";
|
||||
|
||||
const query = {
|
||||
baseUrl: "https://example.com",
|
||||
method: "GET",
|
||||
networkScope: "public",
|
||||
kind: "query",
|
||||
} satisfies CustomWidgetHttpRequest;
|
||||
|
||||
describe("custom widget request deadline", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
mocks.lookup.mockReset();
|
||||
mocks.createPinnedAgent.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("returns at the total deadline when DNS resolution stalls", async () => {
|
||||
mocks.lookup.mockReturnValue(new Promise(() => undefined));
|
||||
const assertion = expect(executeCustomWidgetRequest(query)).rejects.toMatchObject({
|
||||
code: "BAD_GATEWAY",
|
||||
reason: "timeout",
|
||||
});
|
||||
|
||||
await vi.advanceTimersByTimeAsync(MAX_REQUEST_DURATION_MS);
|
||||
|
||||
await assertion;
|
||||
expect(mocks.createPinnedAgent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("cancels an injected stalled resolver when its deadline aborts", async () => {
|
||||
const controller = new AbortController();
|
||||
const resolver = vi.fn(() => new Promise<never>(() => undefined));
|
||||
const assertion = expect(
|
||||
resolveAndValidateHost("example.com", "public", { signal: controller.signal, resolver }),
|
||||
).rejects.toMatchObject({ name: "AbortError" });
|
||||
|
||||
controller.abort();
|
||||
|
||||
await assertion;
|
||||
expect(resolver).toHaveBeenCalledWith("example.com");
|
||||
});
|
||||
|
||||
it("detaches stalled dispatcher cleanup after a bounded grace period", async () => {
|
||||
const close = vi.fn(() => new Promise<void>(() => undefined));
|
||||
const destroy = vi.fn(async () => undefined);
|
||||
mocks.createPinnedAgent.mockReturnValue({
|
||||
request: vi.fn(async () => ({
|
||||
statusCode: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
body: {
|
||||
arrayBuffer: vi.fn(async () => new TextEncoder().encode("{}").buffer),
|
||||
},
|
||||
})),
|
||||
close,
|
||||
destroy,
|
||||
});
|
||||
const logError = vi.fn();
|
||||
const request = executeCustomWidgetRequest({
|
||||
...query,
|
||||
baseUrl: "http://127.0.0.1",
|
||||
networkScope: "loopback",
|
||||
logError,
|
||||
});
|
||||
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
|
||||
await expect(request).resolves.toMatchObject({ ok: true, status: 200, data: {} });
|
||||
expect(close).toHaveBeenCalledOnce();
|
||||
expect(destroy).toHaveBeenCalledOnce();
|
||||
expect(logError).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
errorName: "DispatcherCloseTimeout",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not turn a completed action into a failure when dispatcher cleanup rejects", async () => {
|
||||
const closeFailure = Object.assign(new Error("cleanup failed"), { name: "DispatcherCloseError" });
|
||||
const close = vi.fn(async () => {
|
||||
throw closeFailure;
|
||||
});
|
||||
const destroy = vi.fn(async () => undefined);
|
||||
mocks.createPinnedAgent.mockReturnValue({
|
||||
request: vi.fn(async () => ({
|
||||
statusCode: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
body: {
|
||||
arrayBuffer: vi.fn(async () => new TextEncoder().encode('{"updated":true}').buffer),
|
||||
},
|
||||
})),
|
||||
close,
|
||||
destroy,
|
||||
});
|
||||
const logError = vi.fn();
|
||||
|
||||
await expect(
|
||||
executeCustomWidgetRequest({
|
||||
...query,
|
||||
baseUrl: "http://127.0.0.1",
|
||||
method: "POST",
|
||||
networkScope: "loopback",
|
||||
kind: "action",
|
||||
logError,
|
||||
}),
|
||||
).resolves.toMatchObject({ ok: true, status: 200, data: { updated: true } });
|
||||
expect(close).toHaveBeenCalledOnce();
|
||||
expect(destroy).toHaveBeenCalledOnce();
|
||||
expect(logError).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
errorName: "DispatcherCloseError",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("redacts apiKeyQuery credentials from transport errors and structured log events", async () => {
|
||||
const apiKey = "api-key-query-secret";
|
||||
const request = vi.fn(async ({ path }: { path: string }) => {
|
||||
const failure = new Error(`Transport failed for https://example.com${path}`);
|
||||
failure.name = `SocketError:${path}`;
|
||||
throw failure;
|
||||
});
|
||||
mocks.createPinnedAgent.mockReturnValue({
|
||||
request,
|
||||
close: vi.fn(async () => undefined),
|
||||
destroy: vi.fn(async () => undefined),
|
||||
});
|
||||
const logError = vi.fn();
|
||||
|
||||
const error = await executeCustomWidgetRequest({
|
||||
...query,
|
||||
baseUrl: "http://127.0.0.1",
|
||||
targetUrl: "http://127.0.0.1/status?view=summary",
|
||||
networkScope: "loopback",
|
||||
auth: {
|
||||
type: "apiKeyQuery",
|
||||
headerName: "access_token",
|
||||
secrets: [{ kind: "apiKey", value: apiKey }],
|
||||
},
|
||||
logError,
|
||||
}).then(
|
||||
() => undefined,
|
||||
(cause: unknown) => cause,
|
||||
);
|
||||
|
||||
expect(request).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
path: expect.stringContaining(`access_token=${apiKey}`),
|
||||
}),
|
||||
);
|
||||
expect(error).toMatchObject({
|
||||
code: "BAD_GATEWAY",
|
||||
message: "External request failed",
|
||||
});
|
||||
expect((error as Error).cause).toBeUndefined();
|
||||
expect(String(error)).not.toContain(apiKey);
|
||||
expect(String(error)).not.toContain("access_token");
|
||||
expect(logError).toHaveBeenCalledWith({
|
||||
origin: "http://127.0.0.1",
|
||||
method: "GET",
|
||||
errorName: "TransportError",
|
||||
});
|
||||
expect(JSON.stringify({ error, logCalls: logError.mock.calls })).not.toContain(apiKey);
|
||||
expect(JSON.stringify({ error, logCalls: logError.mock.calls })).not.toContain("access_token");
|
||||
});
|
||||
});
|
||||
@@ -23,6 +23,51 @@ describe("custom widget request limits", () => {
|
||||
await Promise.all(releases.slice(1).map((release) => release()));
|
||||
});
|
||||
|
||||
it("keeps anonymous client concurrency buckets independent", async () => {
|
||||
const limiter = new CustomWidgetRequestLimiter();
|
||||
const firstClient = { ...input, userId: undefined, anonymousId: "198.51.100.10" };
|
||||
const secondClient = { ...input, userId: undefined, anonymousId: "198.51.100.11" };
|
||||
const firstClientReleases = await Promise.all(Array.from({ length: 4 }, () => limiter.acquire(firstClient)));
|
||||
|
||||
await expect(limiter.acquire(firstClient)).rejects.toMatchObject({ code: "TOO_MANY_REQUESTS" });
|
||||
const releaseSecondClient = await limiter.acquire(secondClient);
|
||||
|
||||
await releaseSecondClient();
|
||||
await Promise.all(firstClientReleases.map((release) => release()));
|
||||
});
|
||||
|
||||
it("enforces an identity-independent per-definition rate bucket", async () => {
|
||||
const anonymousQuery = { ...input, category: "query" as const, userId: undefined };
|
||||
let increment = 0;
|
||||
const store: RequestLimitStore = {
|
||||
incrementRate: vi.fn(async () => {
|
||||
increment += 1;
|
||||
return {
|
||||
// Each acquisition increments its identity bucket first and its
|
||||
// definition bucket second. Simulate a fresh forged identity while
|
||||
// the shared definition bucket is already exhausted.
|
||||
count: increment === 4 ? 241 : 1,
|
||||
retryAfterMs: 456,
|
||||
};
|
||||
}),
|
||||
acquireConcurrency: vi.fn(async () => true),
|
||||
releaseConcurrency: vi.fn(async () => undefined),
|
||||
};
|
||||
const limiter = new CustomWidgetRequestLimiter({ store });
|
||||
const release = await limiter.acquire({ ...anonymousQuery, anonymousId: "198.51.100.10" });
|
||||
await release();
|
||||
|
||||
await expect(limiter.acquire({ ...anonymousQuery, anonymousId: "203.0.113.20" })).rejects.toMatchObject({
|
||||
code: "TOO_MANY_REQUESTS",
|
||||
retryAfterMs: 456,
|
||||
});
|
||||
|
||||
const incrementRate = vi.mocked(store.incrementRate);
|
||||
expect(incrementRate.mock.calls[0]?.[0]).not.toBe(incrementRate.mock.calls[2]?.[0]);
|
||||
expect(incrementRate.mock.calls[1]?.[0]).toBe(incrementRate.mock.calls[3]?.[0]);
|
||||
expect(store.acquireConcurrency).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("enforces category limits and exposes retry metadata", async () => {
|
||||
const store: RequestLimitStore = {
|
||||
incrementRate: vi.fn(async () => ({ count: 11, retryAfterMs: 321 })),
|
||||
|
||||
@@ -8,7 +8,14 @@ import { MantineProvider } from "@mantine/core";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ActionButton, CustomJsxRenderer, CustomWidgetRuntimeProvider, SubFetch, ToggleSwitch } from "../runtime";
|
||||
import {
|
||||
ActionButton,
|
||||
CustomJsxRenderer,
|
||||
CustomWidgetRuntimeProvider,
|
||||
RefreshButton,
|
||||
SubFetch,
|
||||
ToggleSwitch,
|
||||
} from "../runtime";
|
||||
import { createCustomJsxComponents } from "../jsx";
|
||||
import { MAX_REFRESH_INTERVAL_MS, MAX_REFRESH_INTERVAL_SECONDS, normalizeRefreshInterval } from "../runtime/sub-fetch";
|
||||
import type {
|
||||
@@ -78,6 +85,7 @@ async function render(
|
||||
port: CustomWidgetRuntimePort,
|
||||
capabilities: readonly CustomJsxRequestCapability[] = [],
|
||||
setQueryState?: (requestId: string, value: CustomWidgetPublishedQueryState | null) => void,
|
||||
canInvalidateQueries = true,
|
||||
) {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
await act(async () => {
|
||||
@@ -86,6 +94,7 @@ async function render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<CustomWidgetRuntimeProvider
|
||||
itemId="item-1"
|
||||
canInvalidateQueries={canInvalidateQueries}
|
||||
isEditMode={false}
|
||||
requestCapabilities={capabilities}
|
||||
port={port}
|
||||
@@ -107,6 +116,16 @@ async function settle() {
|
||||
}
|
||||
|
||||
describe("Custom Widget runtime ports", () => {
|
||||
it("disables shared-cache refresh for anonymous public-board viewers", async () => {
|
||||
const port = createPort();
|
||||
await render(<RefreshButton />, port, [], undefined, false);
|
||||
|
||||
const button = host.querySelector<HTMLButtonElement>('button[aria-label="Refresh"]');
|
||||
expect(button?.disabled).toBe(true);
|
||||
button?.click();
|
||||
expect(port.invalidate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("clamps refresh intervals below the browser timer overflow boundary", () => {
|
||||
expect(normalizeRefreshInterval(MAX_REFRESH_INTERVAL_SECONDS)).toBe(MAX_REFRESH_INTERVAL_MS);
|
||||
expect(normalizeRefreshInterval(MAX_REFRESH_INTERVAL_SECONDS + 1)).toBe(MAX_REFRESH_INTERVAL_MS);
|
||||
|
||||
@@ -25,12 +25,20 @@ describe("lean Custom Widget schema", () => {
|
||||
trigger: "manual",
|
||||
permission: "modify",
|
||||
});
|
||||
expect(customJsxRequestSchema.parse({ method: "DELETE", path: "/item" })).toMatchObject({
|
||||
expect(customJsxRequestSchema.parse({ kind: "action", method: "DELETE", path: "/item" })).toMatchObject({
|
||||
trigger: "manual",
|
||||
permission: "full",
|
||||
confirmation: { destructive: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects DELETE requests that could execute as automatic queries", () => {
|
||||
expect(customJsxRequestSchema.safeParse({ method: "DELETE", path: "/item" }).success).toBe(false);
|
||||
expect(
|
||||
customJsxRequestSchema.safeParse({ kind: "query", trigger: "manual", method: "DELETE", path: "/item" }).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("validates keyed sources, requests and options", () => {
|
||||
const result = customWidgetDefinitionSchema.parse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
@@ -93,6 +101,80 @@ describe("lean Custom Widget schema", () => {
|
||||
expect(customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, stateSchema: {} }).success).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"http://127.1",
|
||||
"http://2130706433",
|
||||
"http://0x7f000001",
|
||||
"http://0177.0.0.1",
|
||||
"http://1.2.3",
|
||||
"http://%31%32%37.0.0.1",
|
||||
"https://%65xample.com",
|
||||
"https://example%2ecom",
|
||||
"https://example.com\\@attacker.invalid",
|
||||
"https:\\\\example.com\\api",
|
||||
" https://example.com",
|
||||
"https://exa\tmple.com",
|
||||
"https://example.com\n",
|
||||
"https://example.com\u00a0",
|
||||
"https://@example.com",
|
||||
"https://:@example.com",
|
||||
"https://example。com",
|
||||
"https://127.0.0.1",
|
||||
"https://-example.com",
|
||||
"https://example-.com",
|
||||
"https://example..com",
|
||||
"https://example.com:00080",
|
||||
"https://example.com:0000000065535",
|
||||
"https://example.com:65536",
|
||||
"https://[fe80::1%25eth0]",
|
||||
"https://[::ffff:192.168.001.001]",
|
||||
])("rejects ambiguous persisted URL spelling %s for sources and icons", (url) => {
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
sources: {
|
||||
default: { ...CUSTOM_WIDGET_STARTER.sources.default, baseUrl: url },
|
||||
},
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, iconUrl: url }).success).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"https://example.com",
|
||||
"https://example.com.",
|
||||
"https://münich.example",
|
||||
"https://xn--mnich-kva.example",
|
||||
"http://192.168.1.1:0",
|
||||
"https://[2001:db8::1]:65535",
|
||||
"https://[::ffff:192.168.1.1]",
|
||||
])("accepts unambiguous HTTP URLs %s for sources and icons", (url) => {
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
sources: {
|
||||
default: { ...CUSTOM_WIDGET_STARTER.sources.default, baseUrl: url },
|
||||
},
|
||||
}).success,
|
||||
).toBe(true);
|
||||
expect(customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, iconUrl: url }).success).toBe(true);
|
||||
});
|
||||
|
||||
it("allows ordinary encoded icon paths and query values while rejecting oversized URLs", () => {
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
iconUrl: "https://example.com/icons/custom%20widget.svg?theme=dark#preview",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
iconUrl: `https://example.com/${"a".repeat(2048)}`,
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps auth secrets outside the document", () => {
|
||||
const definition = customWidgetDefinitionSchema.parse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
@@ -106,6 +188,71 @@ describe("lean Custom Widget schema", () => {
|
||||
).toEqual(["default:apiKey", "admin:username", "admin:password"]);
|
||||
});
|
||||
|
||||
it("rejects credentials embedded in request paths, headers, and JSX", () => {
|
||||
const requests = [
|
||||
{
|
||||
status: {
|
||||
path: "/api/status?credential=Bearer-sk-secret-123456",
|
||||
},
|
||||
},
|
||||
{
|
||||
status: {
|
||||
path: "/api/status",
|
||||
headers: { "X-Auth": "Bearer sk-secret-123456" },
|
||||
},
|
||||
},
|
||||
{
|
||||
status: {
|
||||
path: "/api/status",
|
||||
headers: { "X-Service": "Basic dXNlcjpwYXNz" },
|
||||
},
|
||||
},
|
||||
{
|
||||
status: {
|
||||
path: "/api/status",
|
||||
headers: { "X-Service": "ghp_abcdefghijklmnopqrstuvwxyz123456" },
|
||||
},
|
||||
},
|
||||
];
|
||||
for (const candidate of requests) {
|
||||
expect(customWidgetDefinitionSchema.safeParse({ ...CUSTOM_WIDGET_STARTER, requests: candidate }).success).toBe(
|
||||
false,
|
||||
);
|
||||
}
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
template: "<Text>Bearer sk-secret-123456</Text>",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("allows harmless key fields, auth modes, headers, and authentication guidance", () => {
|
||||
expect(
|
||||
customWidgetDefinitionSchema.safeParse({
|
||||
...CUSTOM_WIDGET_STARTER,
|
||||
sources: {
|
||||
default: {
|
||||
...CUSTOM_WIDGET_STARTER.sources.default,
|
||||
auth: { type: "apiKeyHeader", name: "X-Api-Key" },
|
||||
},
|
||||
},
|
||||
requests: {
|
||||
status: {
|
||||
path: "/api/status?key=status&auth=none",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"X-Api-Version": "2026-07",
|
||||
"X-Feature-Key": "dashboard-layout",
|
||||
},
|
||||
body: { authenticationMode: "none", key: "status", tokenCount: 3 },
|
||||
},
|
||||
},
|
||||
template: "<Stack><Text>Bearer authentication uses source credentials</Text></Stack>",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("requires installation confirmation for private and placeholder source URLs", () => {
|
||||
const sources = {
|
||||
default: { baseUrl: "https://pokeapi.co/api/v2", networkScope: "public" as const, auth: "none" as const },
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createServer } from "node:http";
|
||||
import { errors } from "undici";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import {
|
||||
@@ -6,11 +7,11 @@ import {
|
||||
assertSafeStaticHeaders,
|
||||
classifyAddress,
|
||||
executeCustomWidgetRequest,
|
||||
invalidateCustomWidgetResponseCache,
|
||||
resolveAndValidateHost,
|
||||
resolveSameOriginTarget,
|
||||
validateCustomWidgetUrl,
|
||||
} from "../server";
|
||||
import { isCustomWidgetRequestTimeoutError } from "../server/request-executor";
|
||||
|
||||
describe("custom widget network policy", () => {
|
||||
test.each([
|
||||
@@ -53,6 +54,121 @@ describe("custom widget network policy", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
["connect", new errors.ConnectTimeoutError()],
|
||||
["headers", new errors.HeadersTimeoutError()],
|
||||
["body", new errors.BodyTimeoutError()],
|
||||
["generic timeout name", Object.assign(new Error("timed out"), { name: "ProxyTimeoutError" })],
|
||||
])("recognizes %s timeout errors from the complete request lifecycle", (_label, error) => {
|
||||
expect(isCustomWidgetRequestTimeoutError(error)).toBe(true);
|
||||
});
|
||||
|
||||
test("recognizes an aborted request deadline as a timeout", () => {
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
expect(isCustomWidgetRequestTimeoutError(new errors.RequestAbortedError(), controller.signal)).toBe(true);
|
||||
expect(isCustomWidgetRequestTimeoutError(new Error("socket failed"))).toBe(false);
|
||||
});
|
||||
|
||||
test("normalizes response-body failures after headers arrive", async () => {
|
||||
const events: Array<{ errorName: string; reason?: "timeout" }> = [];
|
||||
const server = createServer((_request, response) => {
|
||||
response.writeHead(200, { "content-type": "application/json" });
|
||||
response.flushHeaders();
|
||||
response.write('{"status":');
|
||||
setImmediate(() => response.destroy());
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("Test server did not expose a TCP port");
|
||||
try {
|
||||
await expect(
|
||||
executeCustomWidgetRequest({
|
||||
baseUrl: `http://127.0.0.1:${address.port}`,
|
||||
method: "GET",
|
||||
networkScope: "loopback",
|
||||
kind: "query",
|
||||
logError: (event) => events.push(event),
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "BAD_GATEWAY" });
|
||||
expect(events).toHaveLength(1);
|
||||
expect(events[0]?.errorName).toBe("TransportError");
|
||||
} finally {
|
||||
await new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
|
||||
}
|
||||
});
|
||||
|
||||
test("normalizes failures while draining a redirect body", async () => {
|
||||
const server = createServer((_request, response) => {
|
||||
response.writeHead(302, { location: "/target" });
|
||||
response.flushHeaders();
|
||||
response.write("partial redirect body");
|
||||
setImmediate(() => response.destroy());
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("Test server did not expose a TCP port");
|
||||
try {
|
||||
await expect(
|
||||
executeCustomWidgetRequest({
|
||||
baseUrl: `http://127.0.0.1:${address.port}`,
|
||||
method: "GET",
|
||||
networkScope: "loopback",
|
||||
kind: "query",
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "BAD_GATEWAY" });
|
||||
} finally {
|
||||
await new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
|
||||
}
|
||||
});
|
||||
|
||||
test("maps Undici's response-size failure to the domain size limit", async () => {
|
||||
const server = createServer((_request, response) => {
|
||||
response.writeHead(200, { "content-type": "application/json" });
|
||||
response.end(`"${"x".repeat(1024 * 1024)}"`);
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("Test server did not expose a TCP port");
|
||||
try {
|
||||
await expect(
|
||||
executeCustomWidgetRequest({
|
||||
baseUrl: `http://127.0.0.1:${address.port}`,
|
||||
method: "GET",
|
||||
networkScope: "loopback",
|
||||
kind: "query",
|
||||
}),
|
||||
).rejects.toMatchObject({ code: "PAYLOAD_TOO_LARGE" });
|
||||
} finally {
|
||||
await new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
|
||||
}
|
||||
});
|
||||
|
||||
test("preserves domain errors raised while parsing the response body", async () => {
|
||||
const server = createServer((_request, response) => {
|
||||
response.writeHead(200, { "content-type": "application/json" });
|
||||
response.end("{invalid");
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("Test server did not expose a TCP port");
|
||||
try {
|
||||
await expect(
|
||||
executeCustomWidgetRequest({
|
||||
baseUrl: `http://127.0.0.1:${address.port}`,
|
||||
method: "GET",
|
||||
networkScope: "loopback",
|
||||
kind: "query",
|
||||
}),
|
||||
).rejects.toMatchObject({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Upstream returned invalid JSON",
|
||||
});
|
||||
} finally {
|
||||
await new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
|
||||
}
|
||||
});
|
||||
|
||||
test("preserves structured bodies for GET queries", async () => {
|
||||
const server = createServer((request, response) => {
|
||||
let body = "";
|
||||
@@ -164,36 +280,6 @@ describe("custom widget network policy", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("evicts declared response-cache prefixes after an action", async () => {
|
||||
let calls = 0;
|
||||
const server = createServer((_request, response) => {
|
||||
calls += 1;
|
||||
response.writeHead(200, { "content-type": "application/json" });
|
||||
response.end(JSON.stringify({ calls }));
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("Test server did not expose a TCP port");
|
||||
const cacheKey = "custom-jsx:item:status:params";
|
||||
const input = {
|
||||
baseUrl: `http://127.0.0.1:${address.port}`,
|
||||
method: "GET" as const,
|
||||
networkScope: "loopback" as const,
|
||||
kind: "query" as const,
|
||||
cacheKey,
|
||||
cacheTtlSeconds: 60,
|
||||
};
|
||||
try {
|
||||
await expect(executeCustomWidgetRequest(input)).resolves.toMatchObject({ data: { calls: 1 } });
|
||||
await expect(executeCustomWidgetRequest(input)).resolves.toMatchObject({ data: { calls: 1 } });
|
||||
invalidateCustomWidgetResponseCache(["custom-jsx:item:status:"]);
|
||||
await expect(executeCustomWidgetRequest(input)).resolves.toMatchObject({ data: { calls: 2 } });
|
||||
} finally {
|
||||
invalidateCustomWidgetResponseCache(["custom-jsx:item:status:"]);
|
||||
await new Promise<void>((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
|
||||
}
|
||||
});
|
||||
|
||||
test("allows only credential-free HTTP(S) URLs without fragments", () => {
|
||||
expect(validateCustomWidgetUrl("https://example.com/api").href).toBe("https://example.com/api");
|
||||
expect(() => validateCustomWidgetUrl("file:///etc/passwd")).toThrow("HTTP and HTTPS");
|
||||
|
||||
Reference in new issue
Block a user