import { describe, expect, test, vi, beforeEach } from "vitest"; const listMock = vi.fn(); const installMock = vi.fn(); const enableMock = vi.fn(); const disableMock = vi.fn(); const grantMock = vi.fn(); const listGrantsMock = vi.fn(); const revokeMock = vi.fn(); const verifyPermissionMock = vi.fn().mockResolvedValue(undefined); const csrfMock = vi.fn().mockResolvedValue(undefined); const getUserInfoMock = vi.fn().mockResolvedValue({ userId: "u-1" }); const getUserMock = vi.fn().mockResolvedValue({ email: "admin@example.com" }); const getTenantIdMock = vi.fn().mockResolvedValue("t-1"); // F-011 — limiter mock. consumeMock is replaced per-test to drive the // allowed / not-allowed branches; default is "allowed". const consumeMock = vi.fn(async (key: string) => { void key; return { allowed: true, remaining: 4, resetAt: 0 }; }); vi.mock("@toolctrl/shared-store", () => ({ createSlidingWindowRateLimiter: () => ({ consume: consumeMock }), })); vi.mock("~/shared-store.server", () => ({ getSharedStore: () => ({}), })); 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[]) => csrfMock(...args), })); vi.mock("~/utils/db/users.db.server", () => ({ getUser: (...args: unknown[]) => getUserMock(...args), })); vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn(async () => ({ t: (key: string, vars?: Record) => ({ "api.plugins.errors.missingGrantFields": "pluginId (string) and grants (array) are required.", "api.plugins.errors.missingCapabilityReview": "Capability review acknowledgement is required.", "api.plugins.errors.staleCapabilityReview": "Capability review is stale. Reload the plugin manifest and try again.", "api.plugins.errors.pluginNotFound": "Plugin not found.", "api.plugins.errors.invalidJsonBody": "Invalid JSON body.", "api.plugins.errors.unsupportedMediaType": "Plugin lifecycle requests must be sent as JSON.", "api.plugins.errors.missingRevokeFields": "pluginId (string) and capabilityNames (array) are required.", "api.plugins.errors.missingInstallFields": "manifestJson, wasmSha256 and signaturePublicKey are required.", "api.plugins.errors.installRateLimitExceeded": `Install rate limit (${vars?.perMin}/min) exceeded for this tenant.`, "api.plugins.errors.rateLimitUnavailable": "Plugin installs are temporarily unavailable because abuse protection could not be verified. Try again in a minute.", "settings.plugins.errors.lifecycle.already_installed": "This plugin is already installed.", "settings.plugins.errors.lifecycle.binary_not_found": "Plugin binary was not found.", "settings.plugins.errors.lifecycle.capability_unavailable": "One or more requested plugin capabilities are unavailable in this environment.", "settings.plugins.errors.lifecycle.production_guard_violation": "Plugin runtime production guard blocked this lifecycle operation.", "settings.plugins.errors.lifecycle.signature_key_not_trusted": "Plugin publisher key is not trusted.", })[key] ?? key, })), })); vi.mock("~/modules/plugins/services/.server/PluginLifecycleService", async () => { class PluginLifecycleError extends Error { constructor( public code: string, message: string ) { super(message); } } return { PluginLifecycleError, listPlugins: (...args: unknown[]) => listMock(...args), installPlugin: (...args: unknown[]) => installMock(...args), enablePlugin: (...args: unknown[]) => enableMock(...args), disablePlugin: (...args: unknown[]) => disableMock(...args), grantPluginCapabilities: (...args: unknown[]) => grantMock(...args), listPluginCapabilityGrants: (...args: unknown[]) => listGrantsMock(...args), revokePluginCapabilities: (...args: unknown[]) => revokeMock(...args), }; }); beforeEach(() => { listMock.mockReset(); installMock.mockReset(); enableMock.mockReset(); disableMock.mockReset(); grantMock.mockReset(); listGrantsMock.mockReset(); listGrantsMock.mockResolvedValue([]); revokeMock.mockReset(); verifyPermissionMock.mockClear(); csrfMock.mockClear(); getUserInfoMock.mockClear(); getUserMock.mockClear(); consumeMock.mockReset(); consumeMock.mockResolvedValue({ allowed: true, remaining: 4, resetAt: 0 }); }); describe("plugins API route", () => { test("GET lists plugins for tenant", async () => { listMock.mockResolvedValue([{ id: "p-1", pluginId: "com.acme.hi", enabled: true }]); const { loader } = await import("./api.tenants.$tenant.plugins.js"); const response = await loader({ request: new Request("http://localhost/api/tenants/t-1/plugins"), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(200); const data = await (response as Response).json(); expect(data.items).toHaveLength(1); expect(verifyPermissionMock).toHaveBeenCalledOnce(); expect(verifyPermissionMock).toHaveBeenCalledWith(expect.any(Request), "app.plugins.use", "t-1"); }); test("GET stops before tenant plugin lookup when use permission is denied", async () => { const denial = new Response("Forbidden", { status: 403 }); verifyPermissionMock.mockRejectedValueOnce(denial); const { loader } = await import("./api.tenants.$tenant.plugins.js"); await expect( loader({ request: new Request("http://localhost/api/tenants/t-1/plugins"), params: { tenant: "t-1" }, context: {}, }) ).rejects.toBe(denial); expect(verifyPermissionMock).toHaveBeenCalledWith(expect.any(Request), "app.plugins.use", "t-1"); expect(listMock).not.toHaveBeenCalled(); }); test("POST installs a plugin", async () => { installMock.mockResolvedValue({ id: "p-1", pluginId: "com.acme.hi" }); const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins", { method: "POST", body: JSON.stringify({ manifestJson: { id: "com.acme.hi" }, wasmSha256: "a".repeat(64), signaturePublicKey: "c".repeat(64), }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(201); expect(installMock).toHaveBeenCalledOnce(); expect(verifyPermissionMock).toHaveBeenCalledWith(expect.any(Request), "app.plugins.manage", "t-1"); }); test("POST install uses the resolved tenant and authenticated actor instead of request-supplied containment fields", async () => { getTenantIdMock.mockResolvedValueOnce("tenant-canonical"); installMock.mockResolvedValue({ id: "p-1", pluginId: "com.acme.hi" }); const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/tenant-attacker/plugins", { method: "POST", body: JSON.stringify({ tenantId: "t-evil", actor: { userId: "u-evil", email: "evil@example.com", ip: "198.51.100.99" }, manifestJson: { id: "com.acme.hi" }, wasmSha256: "a".repeat(64), signaturePublicKey: "c".repeat(64), }), headers: { "content-type": "application/json", "x-forwarded-for": "203.0.113.9, 198.51.100.99", }, }), params: { tenant: "tenant-attacker" }, context: {}, }); expect(response.status).toBe(201); expect(verifyPermissionMock).toHaveBeenCalledWith(expect.any(Request), "app.plugins.manage", "tenant-canonical"); expect(consumeMock).toHaveBeenCalledWith("tenant:tenant-canonical"); expect(consumeMock).toHaveBeenCalledWith("ip:203.0.113.9"); expect(installMock).toHaveBeenCalledWith({ tenantId: "tenant-canonical", manifestJson: { id: "com.acme.hi" }, wasmSha256: "a".repeat(64), signaturePublicKey: "c".repeat(64), actor: { userId: "u-1", email: "admin@example.com", ip: "203.0.113.9", }, }); }); test("POST stops before CSRF, actor lookup, and lifecycle mutation when manage permission is denied", async () => { const denial = new Response("Forbidden", { status: 403 }); verifyPermissionMock.mockRejectedValueOnce(denial); const { action } = await import("./api.tenants.$tenant.plugins.js"); await expect( action({ request: new Request("http://localhost/api/tenants/t-1/plugins", { method: "POST", body: JSON.stringify({ manifestJson: { id: "com.acme.hi" }, wasmSha256: "a".repeat(64), signaturePublicKey: "c".repeat(64), }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }) ).rejects.toBe(denial); expect(verifyPermissionMock).toHaveBeenCalledWith(expect.any(Request), "app.plugins.manage", "t-1"); expect(csrfMock).not.toHaveBeenCalled(); expect(getUserInfoMock).not.toHaveBeenCalled(); expect(getUserMock).not.toHaveBeenCalled(); expect(consumeMock).not.toHaveBeenCalled(); expect(installMock).not.toHaveBeenCalled(); expect(enableMock).not.toHaveBeenCalled(); expect(disableMock).not.toHaveBeenCalled(); expect(grantMock).not.toHaveBeenCalled(); expect(revokeMock).not.toHaveBeenCalled(); }); test("POST ?op=enable enables a plugin", async () => { enableMock.mockResolvedValue({ id: "p-1", enabled: true }); const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?id=p-1&op=enable", { method: "POST", body: JSON.stringify({}), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(200); expect(enableMock).toHaveBeenCalledOnce(); }); test("POST ?op=disable disables a plugin with a JSON body", async () => { disableMock.mockResolvedValue({ id: "p-1", enabled: false }); const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?id=p-1&op=disable", { method: "POST", body: JSON.stringify({}), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(200); expect(disableMock).toHaveBeenCalledOnce(); }); test("POST ?op=enable rejects non-JSON payloads before actor lookup or lifecycle services", async () => { const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?id=p-1&op=enable", { method: "POST", body: "enabled=true", headers: { "content-type": "application/x-www-form-urlencoded" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(415); await expect(response.json()).resolves.toEqual({ error: "unsupported_media_type", message: "Plugin lifecycle requests must be sent as JSON.", }); expect(getUserInfoMock).not.toHaveBeenCalled(); expect(getUserMock).not.toHaveBeenCalled(); expect(enableMock).not.toHaveBeenCalled(); }); test("POST ?op=disable rejects malformed JSON before actor lookup or lifecycle services", async () => { const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?id=p-1&op=disable", { method: "POST", body: "{", headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(400); await expect(response.json()).resolves.toEqual({ error: "invalid_json", message: "Invalid JSON body.", }); expect(getUserInfoMock).not.toHaveBeenCalled(); expect(getUserMock).not.toHaveBeenCalled(); expect(disableMock).not.toHaveBeenCalled(); }); test("POST ?op=grant grants plugin capabilities with manage permission", async () => { const plugin = { pluginId: "com.acme.hello", version: "1.0.0", manifest: { capabilities: [{ name: "log", scope: { level: "info" } }] }, }; listMock.mockResolvedValue([plugin]); grantMock.mockResolvedValue([{ id: "grant-1", capabilityName: "log" }]); const { createCapabilityReviewDigest } = await import("~/modules/plugins/utils/capabilityReviewDigest"); const { action } = await import("./api.tenants.$tenant.plugins.js"); const grants = [{ capabilityName: "log", scopeJson: { level: "info" } }]; const capabilityReviewDigest = createCapabilityReviewDigest(plugin as never, ["log"]); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?op=grant", { method: "POST", body: JSON.stringify({ pluginId: "com.acme.hello", grants, capabilitiesReviewed: true, capabilityReviewDigest, }), headers: { "content-type": "application/json", "x-forwarded-for": "203.0.113.9", }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(201); await expect(response.json()).resolves.toEqual({ grants: [{ id: "grant-1", capabilityName: "log" }], }); expect(verifyPermissionMock).toHaveBeenCalledWith(expect.any(Request), "app.plugins.manage", "t-1"); expect(grantMock).toHaveBeenCalledWith({ tenantId: "t-1", pluginId: "com.acme.hello", grants: [{ capabilityName: "log", scopeJson: { level: "info" } }], capabilityReviewDigest, actor: { userId: "u-1", email: "admin@example.com", ip: "203.0.113.9", }, }); }); test("POST ?op=grant grants hook consent with manage permission", async () => { const plugin = { pluginId: "com.acme.workflow-hook", version: "1.0.0", manifest: { capabilities: [], hooks: [{ name: "workflow.executed", export: "onWorkflowExecuted" }], }, }; listMock.mockResolvedValue([plugin]); grantMock.mockResolvedValue([{ id: "grant-1", capabilityName: "hook:workflow.executed" }]); const { createCapabilityReviewDigest } = await import("~/modules/plugins/utils/capabilityReviewDigest"); const { action } = await import("./api.tenants.$tenant.plugins.js"); const grants = [{ capabilityName: "hook:workflow.executed", scopeJson: null }]; const capabilityReviewDigest = createCapabilityReviewDigest(plugin as never, ["hook:workflow.executed"]); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?op=grant", { method: "POST", body: JSON.stringify({ pluginId: "com.acme.workflow-hook", grants, capabilitiesReviewed: true, capabilityReviewDigest, }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(201); expect(grantMock).toHaveBeenCalledWith({ tenantId: "t-1", pluginId: "com.acme.workflow-hook", grants: [{ capabilityName: "hook:workflow.executed", scopeJson: null }], capabilityReviewDigest, actor: { userId: "u-1", email: "admin@example.com", ip: null, }, }); }); test("POST ?op=grant persists canonical manifest scopes instead of client supplied subsets", async () => { const plugin = { pluginId: "com.acme.webhook", version: "1.0.0", manifest: { capabilities: [{ name: "http.outbound", scope: { allowedHosts: ["api.example.com", "hooks.example.com"] } }], }, }; listMock.mockResolvedValue([plugin]); grantMock.mockResolvedValue([{ id: "grant-1", capabilityName: "http.outbound" }]); const { createCapabilityReviewDigest } = await import("~/modules/plugins/utils/capabilityReviewDigest"); const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?op=grant", { method: "POST", body: JSON.stringify({ pluginId: "com.acme.webhook", grants: [{ capabilityName: "http.outbound", scopeJson: { allowedHosts: ["api.example.com"] } }], capabilitiesReviewed: true, capabilityReviewDigest: createCapabilityReviewDigest(plugin as never, ["http.outbound"]), }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(201); expect(grantMock).toHaveBeenCalledWith( expect.objectContaining({ tenantId: "t-1", pluginId: "com.acme.webhook", grants: [ { capabilityName: "http.outbound", scopeJson: { allowedHosts: ["api.example.com", "hooks.example.com"] }, }, ], }) ); }); test("POST ?op=grant returns 400 for missing grant fields", async () => { const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?op=grant", { method: "POST", body: JSON.stringify({ pluginId: "com.acme.hello" }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(400); await expect(response.json()).resolves.toEqual({ error: "missing_fields", message: "pluginId (string) and grants (array) are required.", }); expect(grantMock).not.toHaveBeenCalled(); }); test("POST ?op=grant returns 400 for malformed JSON", async () => { const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?op=grant", { method: "POST", body: "{", headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(400); await expect(response.json()).resolves.toEqual({ error: "invalid_json", message: "Invalid JSON body.", }); expect(grantMock).not.toHaveBeenCalled(); }); test("POST ?op=grant rejects non-JSON payloads before actor lookup or lifecycle services", async () => { const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?op=grant", { method: "POST", body: JSON.stringify({ pluginId: "com.acme.hello", grants: [{ capabilityName: "log", scopeJson: null }] }), headers: { "content-type": "text/plain" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(415); await expect(response.json()).resolves.toEqual({ error: "unsupported_media_type", message: "Plugin lifecycle requests must be sent as JSON.", }); expect(getUserInfoMock).not.toHaveBeenCalled(); expect(getUserMock).not.toHaveBeenCalled(); expect(listMock).not.toHaveBeenCalled(); expect(grantMock).not.toHaveBeenCalled(); }); test("POST ?op=grant rejects malformed grant array items before lifecycle services", async () => { const plugin = { pluginId: "com.acme.hello", version: "1.0.0", manifest: { capabilities: [{ name: "log", scope: null }] }, }; listMock.mockResolvedValue([plugin]); const { createCapabilityReviewDigest } = await import("~/modules/plugins/utils/capabilityReviewDigest"); const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?op=grant", { method: "POST", body: JSON.stringify({ pluginId: "com.acme.hello", grants: [{ capabilityName: "log", scopeJson: null }, null], capabilitiesReviewed: true, capabilityReviewDigest: createCapabilityReviewDigest(plugin as never, ["log"]), }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(400); await expect(response.json()).resolves.toEqual({ error: "missing_fields", message: "pluginId (string) and grants (array) are required.", }); expect(listMock).not.toHaveBeenCalled(); expect(grantMock).not.toHaveBeenCalled(); }); test("POST ?op=grant rejects malformed grant scopes before lifecycle services", async () => { const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?op=grant", { method: "POST", body: JSON.stringify({ pluginId: "com.acme.hello", grants: [{ capabilityName: "http.outbound", scopeJson: ["api.example.com"] }], capabilitiesReviewed: true, capabilityReviewDigest: "digest", }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(400); expect(listMock).not.toHaveBeenCalled(); expect(grantMock).not.toHaveBeenCalled(); }); test("POST ?op=grant rejects over-limit grant payloads before plugin lookup", async () => { const { action } = await import("./api.tenants.$tenant.plugins.js"); const cases = [ Array.from({ length: 65 }, (_, index) => ({ capabilityName: `capability.${index}`, scopeJson: null })), [{ capabilityName: "x".repeat(129), scopeJson: null }], [{ capabilityName: "log", scopeJson: { note: "x".repeat(16 * 1024) } }], ]; for (const grants of cases) { listMock.mockClear(); grantMock.mockClear(); consumeMock.mockClear(); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?op=grant", { method: "POST", body: JSON.stringify({ pluginId: "com.acme.hello", grants, capabilitiesReviewed: true, capabilityReviewDigest: "digest", }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(400); await expect(response.json()).resolves.toMatchObject({ error: "missing_fields" }); expect(listMock).not.toHaveBeenCalled(); expect(grantMock).not.toHaveBeenCalled(); expect(consumeMock).not.toHaveBeenCalled(); } }); test("POST ?op=grant rejects undeclared grants even when reviewed capabilities digest is valid", async () => { const plugin = { pluginId: "com.acme.hello", version: "1.0.0", manifest: { capabilities: [{ name: "log", scope: null }] }, }; listMock.mockResolvedValue([plugin]); const { createCapabilityReviewDigest } = await import("~/modules/plugins/utils/capabilityReviewDigest"); const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?op=grant", { method: "POST", body: JSON.stringify({ pluginId: "com.acme.hello", grants: [ { capabilityName: "log", scopeJson: null }, { capabilityName: "secret.read", scopeJson: null }, ], capabilitiesReviewed: true, capabilityReviewDigest: createCapabilityReviewDigest(plugin as never, ["log"]), }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(400); await expect(response.json()).resolves.toMatchObject({ error: "missing_fields" }); expect(grantMock).not.toHaveBeenCalled(); }); test("POST ?op=grant requires reviewed capability consent", async () => { const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?op=grant", { method: "POST", body: JSON.stringify({ pluginId: "com.acme.hello", grants: [{ capabilityName: "log", scopeJson: null }] }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(400); await expect(response.json()).resolves.toEqual({ error: "capability_review_required", message: "Capability review acknowledgement is required.", }); expect(listMock).not.toHaveBeenCalled(); expect(grantMock).not.toHaveBeenCalled(); }); test("POST ?op=grant rejects stale capability review digests", async () => { listMock.mockResolvedValue([ { pluginId: "com.acme.hello", version: "1.0.0", manifest: { capabilities: [{ name: "log", scope: null }] }, }, ]); const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?op=grant", { method: "POST", body: JSON.stringify({ pluginId: "com.acme.hello", grants: [{ capabilityName: "log", scopeJson: null }], capabilitiesReviewed: true, capabilityReviewDigest: "stale", }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(409); await expect(response.json()).resolves.toEqual({ error: "stale_capability_review", message: "Capability review is stale. Reload the plugin manifest and try again.", }); expect(grantMock).not.toHaveBeenCalled(); }); test("POST ?op=grant rejects partial capability review digests for broader grant submissions", async () => { const plugin = { pluginId: "com.acme.hello", version: "1.0.0", manifest: { capabilities: [ { name: "log", scope: null }, { name: "secret.read", scope: { keyPattern: "tenant/*" } }, ], }, }; listMock.mockResolvedValue([plugin]); const { action } = await import("./api.tenants.$tenant.plugins.js"); const { createCapabilityReviewDigest } = await import("~/modules/plugins/utils/capabilityReviewDigest"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?op=grant", { method: "POST", body: JSON.stringify({ pluginId: "com.acme.hello", grants: [ { capabilityName: "log", scopeJson: null }, { capabilityName: "secret.read", scopeJson: { keyPattern: "tenant/*" } }, ], capabilitiesReviewed: true, capabilityReviewDigest: createCapabilityReviewDigest(plugin as never, ["log"]), }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(409); await expect(response.json()).resolves.toEqual({ error: "stale_capability_review", message: "Capability review is stale. Reload the plugin manifest and try again.", }); expect(grantMock).not.toHaveBeenCalled(); }); test("POST ?op=grant rejects partial capability submissions when more manifest capabilities need review", async () => { const plugin = { pluginId: "com.acme.hello", version: "1.0.0", manifest: { capabilities: [ { name: "log", scope: null }, { name: "secret.read", scope: { keyPattern: "tenant/*" } }, ], }, }; listMock.mockResolvedValue([plugin]); listGrantsMock.mockResolvedValue([]); const { action } = await import("./api.tenants.$tenant.plugins.js"); const { createCapabilityReviewDigest } = await import("~/modules/plugins/utils/capabilityReviewDigest"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?op=grant", { method: "POST", body: JSON.stringify({ pluginId: "com.acme.hello", grants: [{ capabilityName: "log", scopeJson: null }], capabilitiesReviewed: true, capabilityReviewDigest: createCapabilityReviewDigest(plugin as never, ["log"]), }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(409); await expect(response.json()).resolves.toEqual({ error: "stale_capability_review", message: "Capability review is stale. Reload the plugin manifest and try again.", }); expect(listGrantsMock).toHaveBeenCalledWith({ tenantId: "t-1", pluginId: "com.acme.hello" }); expect(grantMock).not.toHaveBeenCalled(); }); test("POST ?op=revoke revokes plugin capabilities with manage permission", async () => { revokeMock.mockResolvedValue({ revokedCapabilities: ["http.outbound"], autoDisabled: true }); const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?op=revoke", { method: "POST", body: JSON.stringify({ pluginId: "com.acme.hello", capabilityNames: ["http.outbound"] }), headers: { "content-type": "application/json", "x-forwarded-for": "203.0.113.9", }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(200); await expect(response.json()).resolves.toEqual({ result: { revokedCapabilities: ["http.outbound"], autoDisabled: true }, }); expect(verifyPermissionMock).toHaveBeenCalledWith(expect.any(Request), "app.plugins.manage", "t-1"); expect(revokeMock).toHaveBeenCalledWith({ tenantId: "t-1", pluginId: "com.acme.hello", capabilityNames: ["http.outbound"], actor: { userId: "u-1", email: "admin@example.com", ip: "203.0.113.9", }, }); }); test("POST ?op=revoke returns 400 for missing revoke fields", async () => { const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?op=revoke", { method: "POST", body: JSON.stringify({ pluginId: "com.acme.hello" }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(400); await expect(response.json()).resolves.toEqual({ error: "missing_fields", message: "pluginId (string) and capabilityNames (array) are required.", }); expect(revokeMock).not.toHaveBeenCalled(); }); test("POST ?op=revoke returns 400 for malformed JSON", async () => { const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?op=revoke", { method: "POST", body: "{", headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(400); await expect(response.json()).resolves.toEqual({ error: "invalid_json", message: "Invalid JSON body.", }); expect(revokeMock).not.toHaveBeenCalled(); }); test("POST ?op=revoke rejects missing content type before actor lookup or lifecycle services", async () => { const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?op=revoke", { method: "POST", body: JSON.stringify({ pluginId: "com.acme.hello", capabilityNames: ["http.outbound"] }), }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(415); await expect(response.json()).resolves.toEqual({ error: "unsupported_media_type", message: "Plugin lifecycle requests must be sent as JSON.", }); expect(getUserInfoMock).not.toHaveBeenCalled(); expect(getUserMock).not.toHaveBeenCalled(); expect(revokeMock).not.toHaveBeenCalled(); }); test("POST ?op=revoke rejects malformed capability name arrays before lifecycle services", async () => { const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?op=revoke", { method: "POST", body: JSON.stringify({ pluginId: "com.acme.hello", capabilityNames: ["http.outbound", null] }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(400); await expect(response.json()).resolves.toEqual({ error: "missing_fields", message: "pluginId (string) and capabilityNames (array) are required.", }); expect(revokeMock).not.toHaveBeenCalled(); }); test("returns 400 for missing fields", async () => { const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins", { method: "POST", body: JSON.stringify({}), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(400); }); test("returns 400 for malformed install field types before rate limiting or lifecycle services", async () => { const { action } = await import("./api.tenants.$tenant.plugins.js"); const cases = [ { manifestJson: null, wasmSha256: "a".repeat(64), signaturePublicKey: "c".repeat(64) }, { manifestJson: { id: "com.acme.hi" }, wasmSha256: ["a".repeat(64)], signaturePublicKey: "c".repeat(64) }, { manifestJson: { id: "com.acme.hi" }, wasmSha256: "a".repeat(64), signaturePublicKey: { key: "c".repeat(64) } }, ]; for (const body of cases) { consumeMock.mockClear(); installMock.mockClear(); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins", { method: "POST", body: JSON.stringify(body), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(400); await expect(response.json()).resolves.toEqual({ error: "missing_fields", message: "manifestJson, wasmSha256 and signaturePublicKey are required.", }); expect(consumeMock).not.toHaveBeenCalled(); expect(installMock).not.toHaveBeenCalled(); } }); test("returns 400 for malformed install JSON", async () => { const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins", { method: "POST", body: "{", headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(400); await expect(response.json()).resolves.toEqual({ error: "invalid_json", message: "Invalid JSON body.", }); expect(consumeMock).not.toHaveBeenCalled(); expect(installMock).not.toHaveBeenCalled(); }); test("returns 415 for install JSON sent with a non-JSON content type before rate limiting or actor lookup", async () => { const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins", { method: "POST", body: JSON.stringify({ manifestJson: { id: "com.acme.hi" }, wasmSha256: "a".repeat(64), signaturePublicKey: "c".repeat(64), }), headers: { "content-type": "text/plain" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(415); await expect(response.json()).resolves.toEqual({ error: "unsupported_media_type", message: "Plugin lifecycle requests must be sent as JSON.", }); expect(consumeMock).not.toHaveBeenCalled(); expect(getUserInfoMock).not.toHaveBeenCalled(); expect(getUserMock).not.toHaveBeenCalled(); expect(installMock).not.toHaveBeenCalled(); }); test("returns 400 for oversized install JSON before rate limiting or install", async () => { const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins", { method: "POST", body: JSON.stringify({ manifestJson: { id: "com.acme.hi", blob: "x".repeat(129 * 1024) }, wasmSha256: "a".repeat(64), signaturePublicKey: "c".repeat(64), }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(400); await expect(response.json()).resolves.toEqual({ error: "invalid_json", message: "Invalid JSON body.", }); expect(consumeMock).not.toHaveBeenCalled(); expect(installMock).not.toHaveBeenCalled(); }); test("returns 400 for oversized install content-length before reading the body", async () => { const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins", { method: "POST", body: JSON.stringify({ manifestJson: { id: "com.acme.hi" }, wasmSha256: "a".repeat(64), signaturePublicKey: "c".repeat(64), }), headers: { "content-type": "application/json", "content-length": String(129 * 1024), }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(400); await expect(response.json()).resolves.toEqual({ error: "invalid_json", message: "Invalid JSON body.", }); expect(consumeMock).not.toHaveBeenCalled(); expect(installMock).not.toHaveBeenCalled(); }); // F-010/B-009 — JSON plugin routes must never let CSRF validation fall back // to reading the body. The route enforces a header-only CSRF contract so // body-size limits and JSON parsing remain owned by the plugin payload // reader instead of `validateCSRFToken(request.clone().text())`. test("install uses header-only CSRF validation and leaves the JSON body readable", async () => { csrfMock.mockImplementationOnce(async (request: Request, options?: { headerOnly?: boolean }) => { expect(options).toEqual({ headerOnly: true }); const headerToken = request.headers.get("x-csrf-token") ?? request.headers.get("csrf-token"); if (headerToken) { return; } throw new Error("CSRF Request Token not included."); }); installMock.mockResolvedValue({ id: "p-1", pluginId: "com.acme.hi" }); const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins", { method: "POST", body: JSON.stringify({ manifestJson: { id: "com.acme.hi" }, wasmSha256: "a".repeat(64), signaturePublicKey: "c".repeat(64), }), headers: { "content-type": "application/json", "x-csrf-token": "session-token", }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(201); expect(csrfMock).toHaveBeenCalledWith(expect.any(Request), { headerOnly: true }); expect(installMock).toHaveBeenCalledOnce(); const installArg = installMock.mock.calls[0]?.[0] as { manifestJson: unknown }; expect(installArg.manifestJson).toEqual({ id: "com.acme.hi" }); }); test("install fails clearly when x-csrf-token header is absent without reading the JSON body", async () => { csrfMock.mockImplementationOnce(async (request: Request, options?: { headerOnly?: boolean }) => { expect(options).toEqual({ headerOnly: true }); const headerToken = request.headers.get("x-csrf-token") ?? request.headers.get("csrf-token"); if (headerToken) { return; } throw new Error("CSRF Request Token not included."); }); const { action } = await import("./api.tenants.$tenant.plugins.js"); await expect( action({ request: new Request("http://localhost/api/tenants/t-1/plugins", { method: "POST", body: JSON.stringify({ manifestJson: { id: "com.acme.hi" }, wasmSha256: "a".repeat(64), signaturePublicKey: "c".repeat(64), }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }) ).rejects.toThrow(/CSRF Request Token not included/); }); // F-011 — install route rate limit. describe("install rate limit (F-011)", () => { test("returns 429 with Retry-After when the tenant has exceeded the per-min cap", async () => { consumeMock.mockResolvedValueOnce({ allowed: false, remaining: 0, resetAt: 60 }); const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = (await action({ request: new Request("http://localhost/api/tenants/t-1/plugins", { method: "POST", body: JSON.stringify({ manifestJson: { id: "com.acme.hi" }, wasmSha256: "a".repeat(64), signaturePublicKey: "c".repeat(64), }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, })) as Response; expect(response.status).toBe(429); expect(response.headers.get("Retry-After")).toBe("60"); const body = await response.json(); expect(body.error).toBe("rate_limit_exceeded"); expect(consumeMock).toHaveBeenCalledWith("tenant:t-1"); expect(consumeMock).toHaveBeenCalledTimes(1); expect(installMock).not.toHaveBeenCalled(); }); test("returns 429 with Retry-After when the request IP has exceeded the per-min cap", async () => { consumeMock.mockResolvedValueOnce({ allowed: true, remaining: 4, resetAt: 60 }); consumeMock.mockResolvedValueOnce({ allowed: false, remaining: 0, resetAt: 60 }); const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = (await action({ request: new Request("http://localhost/api/tenants/t-1/plugins", { method: "POST", body: JSON.stringify({ manifestJson: { id: "com.acme.hi" }, wasmSha256: "a".repeat(64), signaturePublicKey: "c".repeat(64), }), headers: { "content-type": "application/json", "x-forwarded-for": "203.0.113.10, 198.51.100.1" }, }), params: { tenant: "t-1" }, context: {}, })) as Response; expect(response.status).toBe(429); expect(response.headers.get("Retry-After")).toBe("60"); await expect(response.json()).resolves.toMatchObject({ error: "rate_limit_exceeded" }); expect(consumeMock).toHaveBeenNthCalledWith(1, "tenant:t-1"); expect(consumeMock).toHaveBeenNthCalledWith(2, "ip:203.0.113.10"); expect(installMock).not.toHaveBeenCalled(); }); test("fails open and installs when the limiter throws", async () => { consumeMock.mockImplementationOnce(async () => { throw new Error("Redis connection refused"); }); installMock.mockResolvedValue({ id: "p-1", pluginId: "com.acme.hi" }); const { action } = await import("./api.tenants.$tenant.plugins.js"); const response = (await action({ request: new Request("http://localhost/api/tenants/t-1/plugins", { method: "POST", body: JSON.stringify({ manifestJson: { id: "com.acme.hi" }, wasmSha256: "a".repeat(64), signaturePublicKey: "c".repeat(64), }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, })) as Response; expect(response.status).toBe(201); expect(installMock).toHaveBeenCalledOnce(); }); test("fails closed in production when 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; consumeMock.mockImplementationOnce(async () => { throw new Error("Redis connection refused"); }); const { action } = await import("./api.tenants.$tenant.plugins.js"); try { const response = (await action({ request: new Request("http://localhost/api/tenants/t-1/plugins", { method: "POST", body: JSON.stringify({ manifestJson: { id: "com.acme.hi" }, wasmSha256: "a".repeat(64), signaturePublicKey: "c".repeat(64), }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, })) as Response; expect(response.status).toBe(503); expect(response.headers.get("Retry-After")).toBe("60"); await expect(response.json()).resolves.toMatchObject({ error: "rate_limit_unavailable" }); expect(installMock).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("ignores the fail-open escape hatch in production when 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"; consumeMock.mockImplementationOnce(async () => { throw new Error("Redis connection refused"); }); const { action } = await import("./api.tenants.$tenant.plugins.js"); try { const response = (await action({ request: new Request("http://localhost/api/tenants/t-1/plugins", { method: "POST", body: JSON.stringify({ manifestJson: { id: "com.acme.hi" }, wasmSha256: "a".repeat(64), signaturePublicKey: "c".repeat(64), }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, })) as Response; expect(response.status).toBe(503); await expect(response.json()).resolves.toMatchObject({ error: "rate_limit_unavailable" }); expect(installMock).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("the limiter is keyed on tenant id and trusted request IP when present", async () => { installMock.mockResolvedValue({ id: "p-1", pluginId: "com.acme.hi" }); const { action } = await import("./api.tenants.$tenant.plugins.js"); await action({ request: new Request("http://localhost/api/tenants/t-1/plugins", { method: "POST", body: JSON.stringify({ manifestJson: { id: "com.acme.hi" }, wasmSha256: "a".repeat(64), signaturePublicKey: "c".repeat(64), }), headers: { "content-type": "application/json", "x-real-ip": "203.0.113.11" }, }), params: { tenant: "t-1" }, context: {}, }); expect(consumeMock).toHaveBeenCalledWith("tenant:t-1"); expect(consumeMock).toHaveBeenCalledWith("ip:203.0.113.11"); }); }); test("maps PluginLifecycleError to 404/409/400", async () => { const { action, ...mod } = await import("./api.tenants.$tenant.plugins.js"); const { PluginLifecycleError } = await import("~/modules/plugins/services/.server/PluginLifecycleService"); void mod; installMock.mockRejectedValue(new PluginLifecycleError("already_installed" as never, "dup")); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins", { method: "POST", body: JSON.stringify({ manifestJson: {}, wasmSha256: "a".repeat(64), signaturePublicKey: "c".repeat(64), }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(409); }); test("maps production plugin runtime guard failures to 403", async () => { const { action } = await import("./api.tenants.$tenant.plugins.js"); const { PluginLifecycleError } = await import("~/modules/plugins/services/.server/PluginLifecycleService"); installMock.mockRejectedValue( new PluginLifecycleError("production_guard_violation" as never, "PLUGIN_RUNTIME_PRODUCTION_ENABLED=true is required for tenant t-1") ); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins", { method: "POST", body: JSON.stringify({ manifestJson: {}, wasmSha256: "a".repeat(64), signaturePublicKey: "c".repeat(64), }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(403); await expect(response.json()).resolves.toMatchObject({ error: "production_guard_violation", message: "Plugin runtime production guard blocked this lifecycle operation.", }); }); test("maps production plugin runtime guard failures from enable operations to 403", async () => { const { action } = await import("./api.tenants.$tenant.plugins.js"); const { PluginLifecycleError } = await import("~/modules/plugins/services/.server/PluginLifecycleService"); enableMock.mockRejectedValue( new PluginLifecycleError("production_guard_violation" as never, "PLUGIN_RUNTIME_PRODUCTION_ENABLED=true is required for tenant t-1") ); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?id=p-1&op=enable", { method: "POST", body: JSON.stringify({}), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(403); await expect(response.json()).resolves.toMatchObject({ error: "production_guard_violation", message: "Plugin runtime production guard blocked this lifecycle operation.", }); }); test.each([ { code: "binary_not_found", rawMessage: "Plugin binary missing at /srv/plugins/com.acme.private/plugin.wasm for tenant t-1", status: 404, safeMessage: "Plugin binary was not found.", }, { code: "signature_key_not_trusted", rawMessage: "Publisher key abc123-private-prefix is not in PLUGIN_TRUSTED_PUBLIC_KEYS", status: 403, safeMessage: "Plugin publisher key is not trusted.", }, ])("maps $code lifecycle failures without leaking raw service messages", async ({ code, rawMessage, status, safeMessage }) => { const { action } = await import("./api.tenants.$tenant.plugins.js"); const { PluginLifecycleError } = await import("~/modules/plugins/services/.server/PluginLifecycleService"); installMock.mockRejectedValue(new PluginLifecycleError(code as never, rawMessage)); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins", { method: "POST", body: JSON.stringify({ manifestJson: {}, wasmSha256: "a".repeat(64), signaturePublicKey: "c".repeat(64), }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(status); await expect(response.json()).resolves.toEqual({ error: code, message: safeMessage }); }); test("maps unavailable plugin host capabilities to 403", async () => { const { action } = await import("./api.tenants.$tenant.plugins.js"); const { PluginLifecycleError } = await import("~/modules/plugins/services/.server/PluginLifecycleService"); grantMock.mockRejectedValue(new PluginLifecycleError("capability_unavailable" as never, "http.outbound unavailable")); listMock.mockResolvedValue([ { pluginId: "com.acme.hello", version: "1.0.0", manifest: { capabilities: [{ name: "http.outbound", scope: { allowedHosts: ["api.example.com"] } }] }, }, ]); const { createCapabilityReviewDigest } = await import("~/modules/plugins/utils/capabilityReviewDigest"); const response = await action({ request: new Request("http://localhost/api/tenants/t-1/plugins?op=grant", { method: "POST", body: JSON.stringify({ pluginId: "com.acme.hello", grants: [{ capabilityName: "http.outbound", scopeJson: { allowedHosts: ["api.example.com"] } }], capabilitiesReviewed: true, capabilityReviewDigest: createCapabilityReviewDigest( { pluginId: "com.acme.hello", version: "1.0.0", manifest: { capabilities: [{ name: "http.outbound", scope: { allowedHosts: ["api.example.com"] } }] }, } as never, ["http.outbound"] ), }), headers: { "content-type": "application/json" }, }), params: { tenant: "t-1" }, context: {}, }); expect(response.status).toBe(403); await expect(response.json()).resolves.toMatchObject({ error: "capability_unavailable", message: "One or more requested plugin capabilities are unavailable in this environment.", }); }); });