451 lines
16 KiB
TypeScript
451 lines
16 KiB
TypeScript
import "@testing-library/jest-dom";
|
|
import { act, render, screen, waitFor } from "@testing-library/react";
|
|
import { MemoryRouter, useLoaderData } from "react-router";
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
|
|
import {
|
|
PLUGIN_SETTINGS_FRAME_CHANNEL_META_NAME,
|
|
PLUGIN_SETTINGS_FRAME_PROTOCOL_VERSION,
|
|
PLUGIN_SETTINGS_FRAME_SANDBOX,
|
|
} from "~/modules/plugins/components/PluginSettingsFrame";
|
|
|
|
import TenantPluginSettingsRoute from "./plugins.$id";
|
|
|
|
vi.mock("react-router", async () => {
|
|
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
|
return {
|
|
...actual,
|
|
useLoaderData: vi.fn(),
|
|
};
|
|
});
|
|
|
|
vi.mock("react-i18next", () => ({
|
|
useTranslation: () => ({
|
|
t: (key: string, options?: Record<string, unknown>) => {
|
|
if (key === "settings.plugins.audit.backToPlugins") return "Back to plugins";
|
|
if (key === "settings.plugins.settings.heading") return `Settings for ${String(options?.pluginId ?? "")}`;
|
|
if (key === "settings.plugins.settings.description") return "Manage this plugin's embedded settings.";
|
|
if (key === "settings.plugins.settings.frameTitle") return `Settings frame for ${String(options?.pluginId ?? "")}`;
|
|
if (key === "settings.plugins.settings.frameErrors.invalid_payload") return "The plugin settings request is invalid.";
|
|
if (key === "settings.plugins.settings.frameErrors.settings_unavailable") return "This setting is unavailable.";
|
|
if (key === "settings.plugins.settings.frameErrors.settings_update_failed") return "Plugin settings could not be saved.";
|
|
return key;
|
|
},
|
|
}),
|
|
}));
|
|
|
|
vi.mock("~/locale/i18next.server", () => ({
|
|
getTranslations: vi.fn(),
|
|
}));
|
|
vi.mock("~/utils/data/useRootData", () => ({
|
|
useRootData: () => ({ csrf: "csrf-token" }),
|
|
}));
|
|
|
|
vi.mock("~/modules/plugins/services/.server/PluginSettingsService", () => ({
|
|
PluginSettingsServiceError: class PluginSettingsServiceError extends Error {
|
|
constructor(
|
|
public readonly code: string,
|
|
message: string
|
|
) {
|
|
super(message);
|
|
}
|
|
},
|
|
loadPluginSettingsHtml: vi.fn(),
|
|
loadPluginSettingsPageData: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/utils/app/CanonicalUrlUtils", () => ({
|
|
appPath: ({ tenantSlug, path }: { tenantSlug: string; path: string }) => `/app/${tenantSlug}/${path}`,
|
|
}));
|
|
|
|
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
|
verifyUserHasPermission: vi.fn(),
|
|
}));
|
|
|
|
vi.mock("~/utils/services/.server/urlService", () => ({
|
|
getTenantIdFromUrl: vi.fn(),
|
|
}));
|
|
|
|
function renderSettingsRoute() {
|
|
return render(
|
|
<MemoryRouter>
|
|
<TenantPluginSettingsRoute />
|
|
</MemoryRouter>
|
|
);
|
|
}
|
|
|
|
function getFrameChannelId(frame: Element) {
|
|
const srcDoc = frame.getAttribute("srcdoc") ?? "";
|
|
const match = srcDoc.match(new RegExp(`name="${PLUGIN_SETTINGS_FRAME_CHANNEL_META_NAME}" content="([^"]+)"`, "u"));
|
|
if (!match?.[1]) throw new Error("plugin settings frame channel missing");
|
|
return match[1];
|
|
}
|
|
|
|
describe("tenant plugin settings route UI", () => {
|
|
afterEach(() => {
|
|
vi.unstubAllGlobals();
|
|
});
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
vi.mocked(useLoaderData).mockReturnValue({
|
|
title: "Plugin settings",
|
|
tenantSlug: "acme",
|
|
plugin: {
|
|
id: "pl-1",
|
|
pluginId: "com.acme.settings",
|
|
version: "1.0.0",
|
|
},
|
|
trustedHtml: "<main><h1>Settings</h1></main>",
|
|
settings: { theme: "dark" },
|
|
});
|
|
});
|
|
|
|
it("renders the sandboxed settings iframe with route-level navigation", () => {
|
|
renderSettingsRoute();
|
|
|
|
expect(screen.getByRole("link", { name: "Back to plugins" })).toHaveAttribute("href", "/app/acme/settings/plugins");
|
|
expect(screen.getByRole("heading", { name: "Settings for com.acme.settings" })).toBeInTheDocument();
|
|
expect(document.querySelector('[data-ui-id="ui.plugins.settings.page"]')).toBeInTheDocument();
|
|
|
|
const frame = screen.getByTitle("Settings frame for com.acme.settings");
|
|
expect(frame).toHaveAttribute("data-ui-id", "ui.plugins.settings.frame");
|
|
expect(frame).toHaveAttribute("data-plugin-id", "com.acme.settings");
|
|
expect(frame).toHaveAttribute("sandbox", PLUGIN_SETTINGS_FRAME_SANDBOX);
|
|
expect(frame).not.toHaveAttribute("src");
|
|
expect(frame).toHaveAttribute("srcdoc", expect.stringContaining('http-equiv="Content-Security-Policy"'));
|
|
expect(frame).toHaveAttribute("srcdoc", expect.stringContaining("script-src 'nonce-"));
|
|
expect(frame).not.toHaveAttribute("srcdoc", expect.stringContaining("script-src 'unsafe-inline'"));
|
|
expect(frame).toHaveAttribute("srcdoc", expect.stringContaining(`name="plugin-settings-protocol" content="${PLUGIN_SETTINGS_FRAME_PROTOCOL_VERSION}"`));
|
|
expect(frame).toHaveAttribute("srcdoc", expect.stringContaining('name="plugin-id" content="com.acme.settings"'));
|
|
expect(frame).toHaveAttribute("srcdoc", expect.stringContaining(`name="${PLUGIN_SETTINGS_FRAME_CHANNEL_META_NAME}"`));
|
|
});
|
|
|
|
it("serves loaded settings to the iframe and persists updates through the route action", async () => {
|
|
const fetchMock = vi.fn(
|
|
async () =>
|
|
new Response(JSON.stringify({ ok: true, key: "theme", value: "light", settings: { theme: "light" } }), {
|
|
status: 200,
|
|
headers: { "content-type": "application/json" },
|
|
})
|
|
);
|
|
vi.stubGlobal("fetch", fetchMock);
|
|
renderSettingsRoute();
|
|
|
|
const frame = screen.getByTitle("Settings frame for com.acme.settings") as HTMLIFrameElement;
|
|
const channelId = getFrameChannelId(frame);
|
|
const source = frame.contentWindow;
|
|
if (!source) throw new Error("iframe contentWindow missing");
|
|
const postMessage = vi.spyOn(source, "postMessage").mockImplementation(() => undefined);
|
|
|
|
act(() => {
|
|
window.dispatchEvent(
|
|
new MessageEvent("message", {
|
|
data: { type: "plugin.settings.get", version: 1, pluginId: "com.acme.settings", channelId, requestId: "get-1", key: "theme" },
|
|
origin: "null",
|
|
source,
|
|
})
|
|
);
|
|
});
|
|
await waitFor(() =>
|
|
expect(postMessage).toHaveBeenCalledWith(
|
|
{ type: "plugin.settings.result", version: 1, pluginId: "com.acme.settings", channelId, requestId: "get-1", ok: true, key: "theme", value: "dark" },
|
|
"*"
|
|
)
|
|
);
|
|
|
|
act(() => {
|
|
window.dispatchEvent(
|
|
new MessageEvent("message", {
|
|
data: { type: "plugin.settings.set", version: 1, pluginId: "com.acme.settings", channelId, requestId: "set-1", key: "theme", value: "light" },
|
|
origin: "null",
|
|
source,
|
|
})
|
|
);
|
|
});
|
|
await waitFor(() =>
|
|
expect(fetchMock).toHaveBeenCalledWith(".data", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json", "x-csrf-token": "csrf-token" },
|
|
body: JSON.stringify({ op: "setSetting", key: "theme", value: "light", csrf: "csrf-token" }),
|
|
})
|
|
);
|
|
await waitFor(() =>
|
|
expect(postMessage).toHaveBeenCalledWith(
|
|
{ type: "plugin.settings.result", version: 1, pluginId: "com.acme.settings", channelId, requestId: "set-1", ok: true, key: "theme", value: "light" },
|
|
"*"
|
|
)
|
|
);
|
|
});
|
|
|
|
it("keeps iframe settings unchanged when route-level persistence fails", async () => {
|
|
const fetchMock = vi.fn(
|
|
async () =>
|
|
new Response(JSON.stringify({ error: "rate_limited", message: "Too many plugin setting updates. Try again in a minute." }), {
|
|
status: 429,
|
|
headers: { "content-type": "application/json" },
|
|
})
|
|
);
|
|
vi.stubGlobal("fetch", fetchMock);
|
|
renderSettingsRoute();
|
|
|
|
const frame = screen.getByTitle("Settings frame for com.acme.settings") as HTMLIFrameElement;
|
|
const channelId = getFrameChannelId(frame);
|
|
const source = frame.contentWindow;
|
|
if (!source) throw new Error("iframe contentWindow missing");
|
|
const postMessage = vi.spyOn(source, "postMessage").mockImplementation(() => undefined);
|
|
|
|
act(() => {
|
|
window.dispatchEvent(
|
|
new MessageEvent("message", {
|
|
data: { type: "plugin.settings.set", version: 1, pluginId: "com.acme.settings", channelId, requestId: "set-fail", key: "theme", value: "light" },
|
|
origin: "null",
|
|
source,
|
|
})
|
|
);
|
|
});
|
|
|
|
await waitFor(() =>
|
|
expect(fetchMock).toHaveBeenCalledWith(".data", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json", "x-csrf-token": "csrf-token" },
|
|
body: JSON.stringify({ op: "setSetting", key: "theme", value: "light", csrf: "csrf-token" }),
|
|
})
|
|
);
|
|
await waitFor(() =>
|
|
expect(postMessage).toHaveBeenCalledWith(
|
|
{
|
|
type: "plugin.settings.result",
|
|
version: 1,
|
|
pluginId: "com.acme.settings",
|
|
channelId,
|
|
requestId: "set-fail",
|
|
ok: false,
|
|
error: "settings_update_failed",
|
|
message: "Plugin settings could not be saved.",
|
|
},
|
|
"*"
|
|
)
|
|
);
|
|
|
|
postMessage.mockClear();
|
|
act(() => {
|
|
window.dispatchEvent(
|
|
new MessageEvent("message", {
|
|
data: { type: "plugin.settings.get", version: 1, pluginId: "com.acme.settings", channelId, requestId: "get-after-fail", key: "theme" },
|
|
origin: "null",
|
|
source,
|
|
})
|
|
);
|
|
});
|
|
|
|
await waitFor(() =>
|
|
expect(postMessage).toHaveBeenCalledWith(
|
|
{
|
|
type: "plugin.settings.result",
|
|
version: 1,
|
|
pluginId: "com.acme.settings",
|
|
channelId,
|
|
requestId: "get-after-fail",
|
|
ok: true,
|
|
key: "theme",
|
|
value: "dark",
|
|
},
|
|
"*"
|
|
)
|
|
);
|
|
});
|
|
|
|
it("returns bounded iframe error copy when route-level persistence returns non-json", async () => {
|
|
const fetchMock = vi.fn(
|
|
async () =>
|
|
new Response("<!doctype html><title>Bad Gateway</title>", {
|
|
status: 502,
|
|
headers: { "content-type": "text/html" },
|
|
})
|
|
);
|
|
vi.stubGlobal("fetch", fetchMock);
|
|
renderSettingsRoute();
|
|
|
|
const frame = screen.getByTitle("Settings frame for com.acme.settings") as HTMLIFrameElement;
|
|
const channelId = getFrameChannelId(frame);
|
|
const source = frame.contentWindow;
|
|
if (!source) throw new Error("iframe contentWindow missing");
|
|
const postMessage = vi.spyOn(source, "postMessage").mockImplementation(() => undefined);
|
|
|
|
act(() => {
|
|
window.dispatchEvent(
|
|
new MessageEvent("message", {
|
|
data: { type: "plugin.settings.set", version: 1, pluginId: "com.acme.settings", channelId, requestId: "set-bad-gateway", key: "theme", value: "light" },
|
|
origin: "null",
|
|
source,
|
|
})
|
|
);
|
|
});
|
|
|
|
await waitFor(() =>
|
|
expect(postMessage).toHaveBeenCalledWith(
|
|
{
|
|
type: "plugin.settings.result",
|
|
version: 1,
|
|
pluginId: "com.acme.settings",
|
|
channelId,
|
|
requestId: "set-bad-gateway",
|
|
ok: false,
|
|
error: "settings_update_failed",
|
|
message: "Plugin settings could not be saved.",
|
|
},
|
|
"*"
|
|
)
|
|
);
|
|
expect(fetchMock).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
it("rejects forged iframe settings messages and reports frame violations without setting persistence", async () => {
|
|
const fetchMock = vi.fn();
|
|
vi.stubGlobal("fetch", fetchMock);
|
|
renderSettingsRoute();
|
|
|
|
const frame = screen.getByTitle("Settings frame for com.acme.settings") as HTMLIFrameElement;
|
|
const channelId = getFrameChannelId(frame);
|
|
const source = frame.contentWindow;
|
|
if (!source) throw new Error("iframe contentWindow missing");
|
|
const postMessage = vi.spyOn(source, "postMessage").mockImplementation(() => undefined);
|
|
|
|
act(() => {
|
|
window.dispatchEvent(
|
|
new MessageEvent("message", {
|
|
data: { type: "plugin.settings.set", version: 1, pluginId: "com.acme.settings", channelId, requestId: "wrong-origin", key: "theme", value: "light" },
|
|
origin: "https://evil.example",
|
|
source,
|
|
})
|
|
);
|
|
window.dispatchEvent(
|
|
new MessageEvent("message", {
|
|
data: { type: "plugin.settings.set", version: 1, pluginId: "com.acme.settings", channelId, requestId: "wrong-source", key: "theme", value: "light" },
|
|
origin: "null",
|
|
source: window,
|
|
})
|
|
);
|
|
window.dispatchEvent(
|
|
new MessageEvent("message", {
|
|
data: {
|
|
type: "plugin.settings.set",
|
|
version: 1,
|
|
pluginId: "com.acme.settings",
|
|
channelId: "stale-channel",
|
|
requestId: "wrong-channel",
|
|
key: "theme",
|
|
value: "light",
|
|
},
|
|
origin: "null",
|
|
source,
|
|
})
|
|
);
|
|
});
|
|
|
|
await waitFor(() =>
|
|
expect(postMessage).toHaveBeenCalledWith(
|
|
{
|
|
type: "plugin.settings.result",
|
|
version: 1,
|
|
pluginId: "com.acme.settings",
|
|
channelId,
|
|
requestId: "wrong-channel",
|
|
ok: false,
|
|
error: "invalid_payload",
|
|
message: "The plugin settings request is invalid.",
|
|
},
|
|
"*"
|
|
)
|
|
);
|
|
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(3));
|
|
expect(fetchMock.mock.calls.map(([, init]) => JSON.parse(String((init as RequestInit).body)).op)).toEqual([
|
|
"reportFrameViolation",
|
|
"reportFrameViolation",
|
|
"reportFrameViolation",
|
|
]);
|
|
expect(fetchMock.mock.calls.map(([, init]) => JSON.parse(String((init as RequestInit).body)).reason)).toEqual([
|
|
"wrong_origin",
|
|
"wrong_source",
|
|
"invalid_payload",
|
|
]);
|
|
expect(postMessage).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("deduplicates repeated iframe violation reports before they reach the route action", async () => {
|
|
const fetchMock = vi.fn();
|
|
vi.stubGlobal("fetch", fetchMock);
|
|
renderSettingsRoute();
|
|
|
|
const frame = screen.getByTitle("Settings frame for com.acme.settings") as HTMLIFrameElement;
|
|
const channelId = getFrameChannelId(frame);
|
|
const source = frame.contentWindow;
|
|
if (!source) throw new Error("iframe contentWindow missing");
|
|
|
|
act(() => {
|
|
for (let index = 0; index < 3; index += 1) {
|
|
window.dispatchEvent(
|
|
new MessageEvent("message", {
|
|
data: { type: "plugin.settings.set", version: 1, pluginId: "com.acme.settings", channelId, requestId: `wrong-origin-${index}`, key: "theme", value: "light" },
|
|
origin: "https://evil.example",
|
|
source,
|
|
})
|
|
);
|
|
}
|
|
});
|
|
|
|
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
|
|
expect(JSON.parse(String((fetchMock.mock.calls[0]?.[1] as RequestInit).body))).toEqual({
|
|
op: "reportFrameViolation",
|
|
reason: "wrong_origin",
|
|
csrf: "csrf-token",
|
|
});
|
|
});
|
|
|
|
it("rejects iframe settings messages for another plugin and reports the invalid payload without setting persistence", async () => {
|
|
const fetchMock = vi.fn();
|
|
vi.stubGlobal("fetch", fetchMock);
|
|
renderSettingsRoute();
|
|
|
|
const frame = screen.getByTitle("Settings frame for com.acme.settings") as HTMLIFrameElement;
|
|
const channelId = getFrameChannelId(frame);
|
|
const source = frame.contentWindow;
|
|
if (!source) throw new Error("iframe contentWindow missing");
|
|
const postMessage = vi.spyOn(source, "postMessage").mockImplementation(() => undefined);
|
|
|
|
act(() => {
|
|
window.dispatchEvent(
|
|
new MessageEvent("message", {
|
|
data: { type: "plugin.settings.set", version: 1, pluginId: "com.evil.settings", channelId, requestId: "wrong-plugin", key: "theme", value: "light" },
|
|
origin: "null",
|
|
source,
|
|
})
|
|
);
|
|
});
|
|
|
|
await waitFor(() =>
|
|
expect(postMessage).toHaveBeenCalledWith(
|
|
{
|
|
type: "plugin.settings.result",
|
|
version: 1,
|
|
pluginId: "com.acme.settings",
|
|
channelId,
|
|
requestId: "wrong-plugin",
|
|
ok: false,
|
|
error: "invalid_payload",
|
|
message: "The plugin settings request is invalid.",
|
|
},
|
|
"*"
|
|
)
|
|
);
|
|
await waitFor(() =>
|
|
expect(fetchMock).toHaveBeenCalledWith(".data", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json", "x-csrf-token": "csrf-token" },
|
|
body: JSON.stringify({ op: "reportFrameViolation", reason: "invalid_payload", csrf: "csrf-token" }),
|
|
})
|
|
);
|
|
});
|
|
});
|