670 lines
28 KiB
TypeScript
670 lines
28 KiB
TypeScript
import { beforeEach, describe, expect, test, vi } from "vitest";
|
|
|
|
const getTenantIdMock = vi.fn().mockResolvedValue("tenant-1");
|
|
const verifyPermissionMock = vi.fn().mockResolvedValue(undefined);
|
|
const loadPluginSettingsPageDataMock = vi.fn();
|
|
const setPluginUserSettingMock = vi.fn();
|
|
const reportPluginSettingsFrameViolationMock = vi.fn();
|
|
const getUserInfoMock = vi.fn();
|
|
const validateCSRFTokenMock = vi.fn();
|
|
const getUserMock = vi.fn();
|
|
const consumeRateLimitMock = vi.fn();
|
|
|
|
vi.mock("~/utils/services/.server/urlService", () => ({
|
|
getTenantIdFromUrl: (...args: unknown[]) => getTenantIdMock(...args),
|
|
}));
|
|
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
|
verifyUserHasPermission: (...args: unknown[]) => verifyPermissionMock(...args),
|
|
}));
|
|
vi.mock("~/utils/session.server", () => ({
|
|
getUserInfo: (...args: unknown[]) => getUserInfoMock(...args),
|
|
validateCSRFToken: (...args: unknown[]) => validateCSRFTokenMock(...args),
|
|
}));
|
|
vi.mock("~/utils/db/users.db.server", () => ({
|
|
getUser: (...args: unknown[]) => getUserMock(...args),
|
|
}));
|
|
vi.mock("~/shared-store.server", () => ({
|
|
getSharedStore: vi.fn(() => ({ kind: "test-store" })),
|
|
}));
|
|
vi.mock("@hivegrid/shared-store", () => ({
|
|
createSlidingWindowRateLimiter: vi.fn(() => ({
|
|
consume: (...args: unknown[]) => consumeRateLimitMock(...args),
|
|
})),
|
|
}));
|
|
vi.mock("~/locale/i18next.server", () => ({
|
|
getTranslations: vi.fn(async () => ({
|
|
t: (key: string, vars?: Record<string, unknown>) => (vars ? `${key}:${JSON.stringify(vars)}` : key),
|
|
})),
|
|
}));
|
|
vi.mock("~/modules/plugins/services/.server/PluginSettingsService", () => {
|
|
class PluginSettingsServiceError extends Error {
|
|
constructor(
|
|
public readonly code: string,
|
|
message: string
|
|
) {
|
|
super(message);
|
|
}
|
|
}
|
|
return {
|
|
PluginSettingsServiceError,
|
|
loadPluginSettingsPageData: (...args: unknown[]) => loadPluginSettingsPageDataMock(...args),
|
|
reportPluginSettingsFrameViolation: (...args: unknown[]) => reportPluginSettingsFrameViolationMock(...args),
|
|
setPluginUserSetting: (...args: unknown[]) => setPluginUserSettingMock(...args),
|
|
};
|
|
});
|
|
|
|
beforeEach(() => {
|
|
getTenantIdMock.mockClear();
|
|
verifyPermissionMock.mockReset();
|
|
verifyPermissionMock.mockResolvedValue(undefined);
|
|
loadPluginSettingsPageDataMock.mockReset();
|
|
setPluginUserSettingMock.mockReset();
|
|
reportPluginSettingsFrameViolationMock.mockReset();
|
|
reportPluginSettingsFrameViolationMock.mockResolvedValue(undefined);
|
|
getUserInfoMock.mockReset();
|
|
getUserInfoMock.mockResolvedValue({ userId: "user-1" });
|
|
validateCSRFTokenMock.mockReset();
|
|
validateCSRFTokenMock.mockResolvedValue(undefined);
|
|
getUserMock.mockReset();
|
|
getUserMock.mockResolvedValue({ email: "user@example.com" });
|
|
consumeRateLimitMock.mockReset();
|
|
consumeRateLimitMock.mockResolvedValue({ allowed: true });
|
|
});
|
|
|
|
describe("plugin settings route", () => {
|
|
test("headers add anti-framing policy while preserving server timing", async () => {
|
|
const { headers } = await import("./plugins.$id.js");
|
|
|
|
const responseHeaders = headers({
|
|
loaderHeaders: new Headers({ "Server-Timing": "plugin;dur=12" }),
|
|
parentHeaders: new Headers(),
|
|
actionHeaders: new Headers(),
|
|
errorHeaders: undefined,
|
|
});
|
|
|
|
expect(responseHeaders.get("Content-Security-Policy")).toBe(
|
|
"default-src 'self'; script-src 'self'; connect-src 'self'; img-src 'self' data: blob:; font-src 'self' data:; style-src 'self' 'unsafe-inline'; frame-src 'self'; child-src 'self'; worker-src 'none'; media-src 'none'; manifest-src 'none'; frame-ancestors 'self'; base-uri 'self'; object-src 'none'; form-action 'self'; navigate-to 'self'"
|
|
);
|
|
expect(responseHeaders.get("X-Frame-Options")).toBe("SAMEORIGIN");
|
|
expect(responseHeaders.get("Server-Timing")).toBe("plugin;dur=12");
|
|
});
|
|
|
|
test("headers deny powerful browser capabilities for embedded plugin settings", async () => {
|
|
const { headers } = await import("./plugins.$id.js");
|
|
|
|
const responseHeaders = headers({
|
|
loaderHeaders: new Headers(),
|
|
parentHeaders: new Headers(),
|
|
actionHeaders: new Headers(),
|
|
errorHeaders: undefined,
|
|
});
|
|
const policy = responseHeaders.get("Permissions-Policy") ?? "";
|
|
|
|
for (const directive of [
|
|
"camera=()",
|
|
"microphone=()",
|
|
"geolocation=()",
|
|
"clipboard-read=()",
|
|
"clipboard-write=()",
|
|
"display-capture=()",
|
|
"fullscreen=()",
|
|
"payment=()",
|
|
"storage-access=()",
|
|
"usb=()",
|
|
"web-share=()",
|
|
]) {
|
|
expect(policy).toContain(directive);
|
|
}
|
|
expect(policy).not.toContain("*");
|
|
expect(policy).not.toContain("self");
|
|
});
|
|
|
|
test("loader stops before settings lookup when use permission is denied", async () => {
|
|
const denial = new Response("Forbidden", { status: 403 });
|
|
verifyPermissionMock.mockRejectedValueOnce(denial);
|
|
const { loader } = await import("./plugins.$id.js");
|
|
|
|
await expect(
|
|
loader({
|
|
request: new Request("http://localhost/app/acme/settings/plugins/pl-1"),
|
|
params: { tenant: "acme", id: "pl-1" },
|
|
context: {},
|
|
})
|
|
).rejects.toBe(denial);
|
|
|
|
expect(verifyPermissionMock).toHaveBeenCalledWith(expect.any(Request), "app.plugins.use", "tenant-1");
|
|
expect(loadPluginSettingsPageDataMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("loader returns plugin frame HTML and per-user settings for tenant-scoped plugins", async () => {
|
|
loadPluginSettingsPageDataMock.mockResolvedValue({
|
|
plugin: { id: "pl-1", pluginId: "com.acme.settings", version: "1.0.0" },
|
|
entry: "ui/settings.html",
|
|
trustedHtml: "<main>Settings</main>",
|
|
settings: { theme: "dark" },
|
|
});
|
|
const { loader } = await import("./plugins.$id.js");
|
|
|
|
const response = await loader({
|
|
request: new Request("http://localhost/app/acme/settings/plugins/pl-1"),
|
|
params: { tenant: "acme", id: "pl-1" },
|
|
context: {},
|
|
});
|
|
|
|
await expect(response.json()).resolves.toMatchObject({
|
|
plugin: { id: "pl-1", pluginId: "com.acme.settings", version: "1.0.0" },
|
|
trustedHtml: "<main>Settings</main>",
|
|
settings: { theme: "dark" },
|
|
});
|
|
expect(loadPluginSettingsPageDataMock).toHaveBeenCalledWith({ tenantId: "tenant-1", pluginRowId: "pl-1", userId: "user-1" });
|
|
});
|
|
|
|
test("loader stops before settings lookup when no authenticated user is available", async () => {
|
|
getUserInfoMock.mockResolvedValueOnce({ userId: null });
|
|
const { loader } = await import("./plugins.$id.js");
|
|
|
|
await expect(
|
|
loader({
|
|
request: new Request("http://localhost/app/acme/settings/plugins/pl-1"),
|
|
params: { tenant: "acme", id: "pl-1" },
|
|
context: {},
|
|
})
|
|
).rejects.toMatchObject({ status: 401 });
|
|
|
|
expect(loadPluginSettingsPageDataMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("loader maps missing settings UI to 404", async () => {
|
|
const { PluginSettingsServiceError } = await import("~/modules/plugins/services/.server/PluginSettingsService");
|
|
loadPluginSettingsPageDataMock.mockRejectedValue(new PluginSettingsServiceError("settings_ui_unavailable", "no ui"));
|
|
const { loader } = await import("./plugins.$id.js");
|
|
|
|
await expect(
|
|
loader({
|
|
request: new Request("http://localhost/app/acme/settings/plugins/pl-1"),
|
|
params: { tenant: "acme", id: "pl-1" },
|
|
context: {},
|
|
})
|
|
).rejects.toMatchObject({ status: 404 });
|
|
});
|
|
|
|
test("loader maps unsafe and oversized settings UI errors to hardened statuses", async () => {
|
|
const { PluginSettingsServiceError } = await import("~/modules/plugins/services/.server/PluginSettingsService");
|
|
const { loader } = await import("./plugins.$id.js");
|
|
|
|
loadPluginSettingsPageDataMock.mockRejectedValueOnce(new PluginSettingsServiceError("settings_ui_entry_unsafe", "unsafe"));
|
|
await expect(
|
|
loader({
|
|
request: new Request("http://localhost/app/acme/settings/plugins/pl-1"),
|
|
params: { tenant: "acme", id: "pl-1" },
|
|
context: {},
|
|
})
|
|
).rejects.toMatchObject({ status: 400 });
|
|
|
|
loadPluginSettingsPageDataMock.mockRejectedValueOnce(new PluginSettingsServiceError("settings_ui_file_too_large", "too large"));
|
|
await expect(
|
|
loader({
|
|
request: new Request("http://localhost/app/acme/settings/plugins/pl-1"),
|
|
params: { tenant: "acme", id: "pl-1" },
|
|
context: {},
|
|
})
|
|
).rejects.toMatchObject({ status: 413 });
|
|
});
|
|
|
|
test("action stores one setting through the per-user settings service", async () => {
|
|
setPluginUserSettingMock.mockResolvedValue({ key: "theme", value: "light", settings: { theme: "light" } });
|
|
const { action } = await import("./plugins.$id.js");
|
|
const request = new Request("http://localhost/app/acme/settings/plugins/pl-1", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json", "x-forwarded-for": "203.0.113.5" },
|
|
body: JSON.stringify({ op: "setSetting", key: "theme", value: "light", csrf: "csrf-token" }),
|
|
});
|
|
|
|
const response = await action({
|
|
request,
|
|
params: { tenant: "acme", id: "pl-1" },
|
|
context: {},
|
|
});
|
|
|
|
await expect(response.json()).resolves.toEqual({ ok: true, key: "theme", value: "light", settings: { theme: "light" } });
|
|
expect(verifyPermissionMock).toHaveBeenCalledWith(request, "app.plugins.use", "tenant-1");
|
|
expect(validateCSRFTokenMock).toHaveBeenCalledWith(request, { headerOnly: true });
|
|
expect(setPluginUserSettingMock).toHaveBeenCalledWith({
|
|
tenantId: "tenant-1",
|
|
pluginRowId: "pl-1",
|
|
userId: "user-1",
|
|
key: "theme",
|
|
value: "light",
|
|
actor: { userId: "user-1", email: "user@example.com", ip: "203.0.113.5" },
|
|
});
|
|
});
|
|
|
|
test("action accepts json content types with charset parameters", async () => {
|
|
setPluginUserSettingMock.mockResolvedValue({ key: "theme", value: "light", settings: { theme: "light" } });
|
|
const { action } = await import("./plugins.$id.js");
|
|
const request = new Request("http://localhost/app/acme/settings/plugins/pl-1", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json; charset=utf-8" },
|
|
body: JSON.stringify({ op: "setSetting", key: "theme", value: "light", csrf: "csrf-token" }),
|
|
});
|
|
|
|
const response = await action({
|
|
request,
|
|
params: { tenant: "acme", id: "pl-1" },
|
|
context: {},
|
|
});
|
|
|
|
expect(response.status).toBe(200);
|
|
await expect(response.json()).resolves.toMatchObject({ ok: true, key: "theme" });
|
|
expect(consumeRateLimitMock).toHaveBeenCalledOnce();
|
|
expect(setPluginUserSettingMock).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
test("action reports plugin settings frame violations without persisting settings", async () => {
|
|
const { action } = await import("./plugins.$id.js");
|
|
const request = new Request("http://localhost/app/acme/settings/plugins/pl-1", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json", "x-forwarded-for": "203.0.113.7" },
|
|
body: JSON.stringify({ op: "reportFrameViolation", reason: "wrong_origin", csrf: "csrf-token" }),
|
|
});
|
|
|
|
const response = await action({
|
|
request,
|
|
params: { tenant: "acme", id: "pl-1" },
|
|
context: {},
|
|
});
|
|
|
|
expect(response.status).toBe(200);
|
|
await expect(response.json()).resolves.toEqual({ ok: true });
|
|
expect(verifyPermissionMock).toHaveBeenCalledWith(request, "app.plugins.use", "tenant-1");
|
|
expect(validateCSRFTokenMock).toHaveBeenCalledWith(request, { headerOnly: true });
|
|
expect(consumeRateLimitMock).toHaveBeenCalledWith("tenant:tenant-1:user:user-1:plugin:pl-1:reason:wrong_origin");
|
|
expect(reportPluginSettingsFrameViolationMock).toHaveBeenCalledWith({
|
|
tenantId: "tenant-1",
|
|
pluginRowId: "pl-1",
|
|
reason: "wrong_origin",
|
|
actor: { userId: "user-1", email: "user@example.com", ip: "203.0.113.7" },
|
|
});
|
|
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("action rejects invalid plugin settings frame violation reasons before rate limiting", async () => {
|
|
const { action } = await import("./plugins.$id.js");
|
|
|
|
const response = await action({
|
|
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify({ op: "reportFrameViolation", reason: "raw-payload", csrf: "csrf-token" }),
|
|
}),
|
|
params: { tenant: "acme", id: "pl-1" },
|
|
context: {},
|
|
});
|
|
|
|
expect(response.status).toBe(400);
|
|
await expect(response.json()).resolves.toEqual({
|
|
error: "invalid_frame_violation_reason",
|
|
message: "settings.plugins.settings.errors.invalid_frame_violation_reason",
|
|
});
|
|
expect(consumeRateLimitMock).not.toHaveBeenCalled();
|
|
expect(reportPluginSettingsFrameViolationMock).not.toHaveBeenCalled();
|
|
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("action rate limits plugin settings frame violation reports", async () => {
|
|
consumeRateLimitMock.mockResolvedValueOnce({ allowed: false });
|
|
const { action } = await import("./plugins.$id.js");
|
|
|
|
const response = await action({
|
|
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify({ op: "reportFrameViolation", reason: "wrong_source", csrf: "csrf-token" }),
|
|
}),
|
|
params: { tenant: "acme", id: "pl-1" },
|
|
context: {},
|
|
});
|
|
|
|
expect(response.status).toBe(429);
|
|
expect(response.headers.get("Retry-After")).toBe("60");
|
|
await expect(response.json()).resolves.toEqual({
|
|
error: "rate_limited",
|
|
message: 'settings.plugins.settings.errors.rate_limited:{"perMin":120}',
|
|
});
|
|
expect(reportPluginSettingsFrameViolationMock).not.toHaveBeenCalled();
|
|
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("action denies setting writes with use permission before CSRF and body parsing", async () => {
|
|
const denial = new Response("Forbidden", { status: 403 });
|
|
verifyPermissionMock.mockRejectedValueOnce(denial);
|
|
const { action } = await import("./plugins.$id.js");
|
|
|
|
await expect(
|
|
action({
|
|
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: "{",
|
|
}),
|
|
params: { tenant: "acme", id: "pl-1" },
|
|
context: {},
|
|
})
|
|
).rejects.toBe(denial);
|
|
|
|
expect(verifyPermissionMock).toHaveBeenCalledWith(expect.any(Request), "app.plugins.use", "tenant-1");
|
|
expect(validateCSRFTokenMock).not.toHaveBeenCalled();
|
|
expect(getUserInfoMock).not.toHaveBeenCalled();
|
|
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("action rejects non-json setting writes before parsing or rate limiting", async () => {
|
|
const { action } = await import("./plugins.$id.js");
|
|
|
|
const response = await action({
|
|
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
|
|
method: "POST",
|
|
headers: { "content-type": "text/plain" },
|
|
body: JSON.stringify({ op: "setSetting", key: "theme", value: "light", csrf: "csrf-token" }),
|
|
}),
|
|
params: { tenant: "acme", id: "pl-1" },
|
|
context: {},
|
|
});
|
|
|
|
expect(response.status).toBe(415);
|
|
await expect(response.json()).resolves.toEqual({
|
|
error: "unsupported_media_type",
|
|
message: "settings.plugins.settings.errors.unsupported_media_type",
|
|
});
|
|
expect(validateCSRFTokenMock).not.toHaveBeenCalled();
|
|
expect(consumeRateLimitMock).not.toHaveBeenCalled();
|
|
expect(getUserMock).not.toHaveBeenCalled();
|
|
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("action validates op and key before user lookup or setting writes", async () => {
|
|
const { action } = await import("./plugins.$id.js");
|
|
|
|
const response = await action({
|
|
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify({ op: "getSetting", key: "theme", csrf: "csrf-token" }),
|
|
}),
|
|
params: { tenant: "acme", id: "pl-1" },
|
|
context: {},
|
|
});
|
|
|
|
expect(response.status).toBe(400);
|
|
await expect(response.json()).resolves.toEqual({
|
|
error: "missing_fields",
|
|
message: "settings.plugins.settings.errors.missing_fields",
|
|
});
|
|
expect(validateCSRFTokenMock).toHaveBeenCalled();
|
|
expect(consumeRateLimitMock).not.toHaveBeenCalled();
|
|
expect(getUserMock).not.toHaveBeenCalled();
|
|
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("action validates setting key and value schema before rate limiting or persistence", async () => {
|
|
const { action } = await import("./plugins.$id.js");
|
|
const cases = [
|
|
{ key: "../theme", value: "dark", error: "settings_key_invalid" },
|
|
{ key: "__proto__", value: "polluted", error: "settings_key_invalid" },
|
|
{ key: "apiKey", value: "abc", error: "settings_key_secret_like" },
|
|
{ key: "authorization", value: "Bearer abc", error: "settings_key_secret_like" },
|
|
{ key: "clientSecret", value: "abc", error: "settings_key_secret_like" },
|
|
{ key: "theme", value: undefined, error: "settings_value_invalid" },
|
|
{ key: "appearance", value: { theme: { accessToken: "must-not-persist" } }, error: "settings_value_invalid" },
|
|
{ key: "appearance", value: { headers: { authorization: "Bearer must-not-persist" } }, error: "settings_value_invalid" },
|
|
{ key: "blob", value: "x".repeat(33 * 1024), error: "settings_value_too_large" },
|
|
];
|
|
|
|
for (const item of cases) {
|
|
const response = await action({
|
|
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify({ op: "setSetting", key: item.key, value: item.value, csrf: "csrf-token" }),
|
|
}),
|
|
params: { tenant: "acme", id: "pl-1" },
|
|
context: {},
|
|
});
|
|
|
|
expect(response.status, item.error).toBe(400);
|
|
await expect(response.json()).resolves.toEqual({
|
|
error: item.error,
|
|
message: `settings.plugins.settings.errors.${item.error}`,
|
|
});
|
|
}
|
|
|
|
expect(validateCSRFTokenMock).toHaveBeenCalledTimes(cases.length);
|
|
expect(consumeRateLimitMock).not.toHaveBeenCalled();
|
|
expect(getUserMock).not.toHaveBeenCalled();
|
|
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("action returns 400 for malformed settings JSON", async () => {
|
|
const { action } = await import("./plugins.$id.js");
|
|
|
|
const response = await action({
|
|
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: "{",
|
|
}),
|
|
params: { tenant: "acme", id: "pl-1" },
|
|
context: {},
|
|
});
|
|
|
|
expect(response.status).toBe(400);
|
|
await expect(response.json()).resolves.toEqual({
|
|
error: "invalid_json",
|
|
message: "settings.plugins.settings.errors.invalid_json",
|
|
});
|
|
expect(consumeRateLimitMock).not.toHaveBeenCalled();
|
|
expect(getUserMock).not.toHaveBeenCalled();
|
|
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("action rejects oversized settings JSON before parsing and rate limiting", async () => {
|
|
const { action } = await import("./plugins.$id.js");
|
|
|
|
const response = await action({
|
|
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json", "content-length": String(81 * 1024) },
|
|
body: JSON.stringify({ op: "setSetting", key: "blob", value: "x" }),
|
|
}),
|
|
params: { tenant: "acme", id: "pl-1" },
|
|
context: {},
|
|
});
|
|
|
|
expect(response.status).toBe(400);
|
|
await expect(response.json()).resolves.toEqual({
|
|
error: "invalid_json",
|
|
message: "settings.plugins.settings.errors.invalid_json",
|
|
});
|
|
expect(consumeRateLimitMock).not.toHaveBeenCalled();
|
|
expect(getUserMock).not.toHaveBeenCalled();
|
|
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("action rejects oversized settings JSON even when content-length is absent", async () => {
|
|
const { action } = await import("./plugins.$id.js");
|
|
const oversizedValue = "x".repeat(81 * 1024);
|
|
|
|
const response = await action({
|
|
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify({ op: "setSetting", key: "blob", value: oversizedValue }),
|
|
}),
|
|
params: { tenant: "acme", id: "pl-1" },
|
|
context: {},
|
|
});
|
|
|
|
expect(response.status).toBe(400);
|
|
await expect(response.json()).resolves.toEqual({
|
|
error: "invalid_json",
|
|
message: "settings.plugins.settings.errors.invalid_json",
|
|
});
|
|
expect(consumeRateLimitMock).not.toHaveBeenCalled();
|
|
expect(getUserMock).not.toHaveBeenCalled();
|
|
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("action rate limits per-user plugin setting writes before persistence", async () => {
|
|
consumeRateLimitMock.mockResolvedValueOnce({ allowed: false });
|
|
const { action } = await import("./plugins.$id.js");
|
|
|
|
const response = await action({
|
|
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify({ op: "setSetting", key: "theme", value: "light", csrf: "csrf-token" }),
|
|
}),
|
|
params: { tenant: "acme", id: "pl-1" },
|
|
context: {},
|
|
});
|
|
|
|
expect(response.status).toBe(429);
|
|
expect(response.headers.get("Retry-After")).toBe("60");
|
|
await expect(response.json()).resolves.toEqual({
|
|
error: "rate_limited",
|
|
message: 'settings.plugins.settings.errors.rate_limited:{"perMin":60}',
|
|
});
|
|
expect(getUserMock).not.toHaveBeenCalled();
|
|
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test("action fails open when plugin settings rate limit storage is unavailable", async () => {
|
|
consumeRateLimitMock.mockRejectedValueOnce(new Error("redis unavailable"));
|
|
setPluginUserSettingMock.mockResolvedValue({ key: "theme", value: "light", settings: { theme: "light" } });
|
|
const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
|
|
const { action } = await import("./plugins.$id.js");
|
|
|
|
const response = await action({
|
|
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify({ op: "setSetting", key: "theme", value: "light", csrf: "csrf-token" }),
|
|
}),
|
|
params: { tenant: "acme", id: "pl-1" },
|
|
context: {},
|
|
});
|
|
|
|
expect(response.status).toBe(200);
|
|
await expect(response.json()).resolves.toMatchObject({ ok: true, key: "theme" });
|
|
expect(setPluginUserSettingMock).toHaveBeenCalledOnce();
|
|
expect(warn).toHaveBeenCalledWith("[plugin-settings] rate-limit infra failure; allowing settings write:", "redis unavailable");
|
|
warn.mockRestore();
|
|
});
|
|
|
|
test("action fails closed in production when plugin settings rate limit storage is unavailable", async () => {
|
|
const originalNodeEnv = process.env.NODE_ENV;
|
|
const originalFailOpen = process.env.PLUGIN_RATE_LIMIT_FAIL_OPEN;
|
|
process.env.NODE_ENV = "production";
|
|
delete process.env.PLUGIN_RATE_LIMIT_FAIL_OPEN;
|
|
consumeRateLimitMock.mockRejectedValueOnce(new Error("redis unavailable"));
|
|
const { action } = await import("./plugins.$id.js");
|
|
|
|
try {
|
|
const response = await action({
|
|
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify({ op: "setSetting", key: "theme", value: "light", csrf: "csrf-token" }),
|
|
}),
|
|
params: { tenant: "acme", id: "pl-1" },
|
|
context: {},
|
|
});
|
|
|
|
expect(response.status).toBe(503);
|
|
expect(response.headers.get("Retry-After")).toBe("60");
|
|
await expect(response.json()).resolves.toEqual({
|
|
error: "rate_limit_unavailable",
|
|
message: "settings.plugins.settings.errors.rate_limit_unavailable",
|
|
});
|
|
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
|
|
} finally {
|
|
if (originalNodeEnv === undefined) delete process.env.NODE_ENV;
|
|
else process.env.NODE_ENV = originalNodeEnv;
|
|
if (originalFailOpen === undefined) delete process.env.PLUGIN_RATE_LIMIT_FAIL_OPEN;
|
|
else process.env.PLUGIN_RATE_LIMIT_FAIL_OPEN = originalFailOpen;
|
|
}
|
|
});
|
|
|
|
test("action ignores the fail-open escape hatch in production when plugin settings rate limit storage is unavailable", async () => {
|
|
const originalNodeEnv = process.env.NODE_ENV;
|
|
const originalFailOpen = process.env.PLUGIN_RATE_LIMIT_FAIL_OPEN;
|
|
process.env.NODE_ENV = "production";
|
|
process.env.PLUGIN_RATE_LIMIT_FAIL_OPEN = "true";
|
|
consumeRateLimitMock.mockRejectedValueOnce(new Error("redis unavailable"));
|
|
const { action } = await import("./plugins.$id.js");
|
|
|
|
try {
|
|
const response = await action({
|
|
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify({ op: "setSetting", key: "theme", value: "light", csrf: "csrf-token" }),
|
|
}),
|
|
params: { tenant: "acme", id: "pl-1" },
|
|
context: {},
|
|
});
|
|
|
|
expect(response.status).toBe(503);
|
|
await expect(response.json()).resolves.toEqual({
|
|
error: "rate_limit_unavailable",
|
|
message: "settings.plugins.settings.errors.rate_limit_unavailable",
|
|
});
|
|
expect(setPluginUserSettingMock).not.toHaveBeenCalled();
|
|
} finally {
|
|
if (originalNodeEnv === undefined) delete process.env.NODE_ENV;
|
|
else process.env.NODE_ENV = originalNodeEnv;
|
|
if (originalFailOpen === undefined) delete process.env.PLUGIN_RATE_LIMIT_FAIL_OPEN;
|
|
else process.env.PLUGIN_RATE_LIMIT_FAIL_OPEN = originalFailOpen;
|
|
}
|
|
});
|
|
|
|
test("action uses x-real-ip when x-forwarded-for is absent", async () => {
|
|
setPluginUserSettingMock.mockResolvedValue({ key: "theme", value: "light", settings: { theme: "light" } });
|
|
const { action } = await import("./plugins.$id.js");
|
|
|
|
await action({
|
|
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json", "x-real-ip": "198.51.100.9" },
|
|
body: JSON.stringify({ op: "setSetting", key: "theme", value: "light", csrf: "csrf-token" }),
|
|
}),
|
|
params: { tenant: "acme", id: "pl-1" },
|
|
context: {},
|
|
});
|
|
|
|
expect(setPluginUserSettingMock).toHaveBeenCalledWith(expect.objectContaining({ actor: expect.objectContaining({ ip: "198.51.100.9" }) }));
|
|
});
|
|
|
|
test("action maps service validation errors to localized JSON responses", async () => {
|
|
const { PluginSettingsServiceError } = await import("~/modules/plugins/services/.server/PluginSettingsService");
|
|
setPluginUserSettingMock.mockRejectedValue(new PluginSettingsServiceError("settings_value_invalid", "invalid value"));
|
|
const { action } = await import("./plugins.$id.js");
|
|
|
|
const response = await action({
|
|
request: new Request("http://localhost/app/acme/settings/plugins/pl-1", {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify({ op: "setSetting", key: "appearance", value: { theme: "dark" }, csrf: "csrf-token" }),
|
|
}),
|
|
params: { tenant: "acme", id: "pl-1" },
|
|
context: {},
|
|
});
|
|
|
|
expect(response.status).toBe(400);
|
|
await expect(response.json()).resolves.toEqual({
|
|
error: "settings_value_invalid",
|
|
message: "settings.plugins.settings.errors.settings_value_invalid",
|
|
});
|
|
});
|
|
});
|