import "@testing-library/jest-dom"; import { fireEvent, render, screen } from "@testing-library/react"; import type { FormHTMLAttributes, ReactNode } from "react"; import { MemoryRouter, useActionData, useLoaderData } from "react-router"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { expectNoAxeViolations, runAxe } from "@toolctrl/ui-app/test-setup/axe"; import TenantPluginsRoute from "./plugins"; vi.mock("react-router", async () => { const actual = await vi.importActual("react-router"); return { ...actual, Form: ({ children, ...props }: { children: ReactNode } & FormHTMLAttributes) =>
{children}
, useActionData: vi.fn(), useLoaderData: vi.fn(), }; }); function interpolateTranslation(template: string, options?: Record) { return template.replace(/\{\{(\w+)\}\}/g, (_, key: string) => String(options?.[key] ?? `{{${key}}}`)); } vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string, options?: Record) => interpolateTranslation(translations[key] ?? String(options?.defaultValue ?? key), options), }), })); vi.mock("~/locale/format", () => ({ useLocaleFormatters: () => ({ date: (value: string) => `formatted:${value}`, }), })); vi.mock("~/utils/app/CanonicalUrlUtils", () => ({ appPath: ({ tenantSlug, path }: { tenantSlug: string; path: string }) => `/app/${tenantSlug}/${path}`, })); vi.mock("~/utils/data/useRootData", () => ({ useRootData: () => ({ csrf: "csrf-token" }), })); vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn(), })); vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ getUserPermission: vi.fn(), verifyUserHasPermission: vi.fn(), })); vi.mock("~/utils/services/.server/urlService", () => ({ getTenantIdFromUrl: vi.fn(), })); vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn(), validateCSRFToken: vi.fn(), })); vi.mock("~/utils/db/users.db.server", () => ({ getUser: vi.fn(), })); vi.mock("~/modules/plugins/services/.server/PluginLifecycleService", () => ({ PluginLifecycleError: class PluginLifecycleError extends Error { code: string; constructor(code: string, message: string) { super(message); this.code = code; } }, disablePlugin: vi.fn(), enablePlugin: vi.fn(), grantPluginCapabilities: vi.fn(), listPluginCapabilityGrants: vi.fn(), listPluginCapabilityGrantsForPlugins: vi.fn(), listPlugins: vi.fn(), revokePluginCapabilities: vi.fn(), })); const translations: Record = { "settings.plugins.title": "Plugins", "settings.plugins.description": "Installed plugins for acme", "settings.plugins.versionInstalled": "v{{version}} installed {{date}}", "settings.plugins.capabilities": "Capabilities", "settings.plugins.capabilityNames.http_outbound": "Outbound HTTP", "settings.plugins.capabilityNames.log": "Logging", "settings.plugins.capabilityNames.audit": "Audit logging", "settings.plugins.capabilityNames.secret_read": "Secret read", "settings.plugins.consent.allowedHosts": "Allowed hosts: {{hosts}}", "settings.plugins.consent.approve": "Approve capabilities", "settings.plugins.consent.approveAndEnable": "Approve and enable", "settings.plugins.consent.description": "Review and approve missing capability grants before enabling this plugin.", "settings.plugins.consent.granted": "Approved", "settings.plugins.consent.grantedAt": "Approved {{date}} for the scope shown above.", "settings.plugins.consent.hookLabel": "Hook: {{hook}}", "settings.plugins.consent.keyPattern": "Key pattern: {{pattern}}", "settings.plugins.consent.missing": "Approval required", "settings.plugins.consent.noScope": "No additional scope.", "settings.plugins.consent.none": "This plugin declares no capabilities.", "settings.plugins.consent.reviewCapabilities": "Review capabilities", "settings.plugins.consent.reviewDescription": "Version {{version}} is requesting these additional host capabilities.", "settings.plugins.consent.reviewFormLabel": "Capability review for {{pluginId}}", "settings.plugins.consent.reviewTitle": "Review {{pluginId}} capabilities", "settings.plugins.consent.reviewCapability": "I reviewed {{capability}}.", "settings.plugins.consent.reviewedCapabilities": "I reviewed the requested plugin capabilities.", "settings.plugins.consent.risk.low": "Low risk", "settings.plugins.consent.risk.medium": "Medium risk", "settings.plugins.consent.risk.high": "High risk", "settings.plugins.consent.risk.critical": "Critical risk", "settings.plugins.consent.available": "Available in this runtime", "settings.plugins.consent.unavailable": "Not available in this runtime", "settings.plugins.consent.unavailableDescription": "This host binding is not production-available yet. It cannot be approved until the operator enables a reviewed implementation.", "settings.plugins.consent.revoke": "Revoke approval", "settings.plugins.consent.revokeDisables": "Revoking approval disables this plugin.", "settings.plugins.consent.tablePrefix": "Table prefix: {{prefix}}", "shared.deny": "Deny", "settings.plugins.viewManifest": "View manifest", "settings.plugins.hideManifest": "Hide manifest", "settings.plugins.openSettings": "Open settings", "settings.plugins.viewAudit": "View audit", "shared.disable": "Disable", "shared.disabled": "Disabled", "shared.enable": "Enable", "shared.enabled": "Enabled", }; const pluginItem = { id: "pl-1", pluginId: "com.acme.outbound", version: "1.2.3", enabled: true, capabilities: [ { name: "http.outbound", scope: { allowedHosts: ["api.example.com"] }, granted: true, grantedAt: "2026-05-01T12:10:00.000Z", grantedScopeJson: { allowedHosts: ["api.example.com"] }, metadata: { risk: "high", productionAvailable: false }, }, ], missingCapabilities: [], capabilityReviewDigest: "review-digest", hasSettingsUi: true, manifestJson: JSON.stringify({ id: "com.acme.outbound", capabilities: [{ name: "http.outbound" }] }, null, 2), installedAt: "2026-05-01T12:00:00.000Z", }; function setLoaderData(canManage: boolean, item = pluginItem, canAudit = false) { vi.mocked(useLoaderData).mockReturnValue({ title: "Plugins", tenantSlug: "acme", canManage, canAudit, items: [item], }); vi.mocked(useActionData).mockReturnValue(undefined); } function renderPluginsRoute() { return render( ); } describe("tenant plugin settings UI", () => { beforeEach(() => { vi.clearAllMocks(); setLoaderData(false); }); it("hides mutation controls from read-only plugin users and exposes manifest state", async () => { renderPluginsRoute(); expect(screen.getByRole("heading", { name: "Plugins" })).toBeInTheDocument(); expect(screen.getByText("com.acme.outbound")).toBeInTheDocument(); expect(screen.getByText(/Outbound HTTP/u)).toBeInTheDocument(); expect(screen.getByText("Approved")).toBeInTheDocument(); expect(screen.getByText("Approved formatted:2026-05-01T12:10:00.000Z for the scope shown above.")).toBeInTheDocument(); expect(document.querySelector('[data-ui-id="ui.plugins.capability.grantMeta"]')).toBeInTheDocument(); expect(screen.queryByRole("button", { name: "Disable" })).not.toBeInTheDocument(); expect(screen.queryByRole("button", { name: "Enable" })).not.toBeInTheDocument(); expect(screen.queryByRole("button", { name: "Approve capabilities" })).not.toBeInTheDocument(); expect(screen.queryByRole("button", { name: "Revoke approval" })).not.toBeInTheDocument(); expect(document.querySelector('[data-ui-id="ui.plugins.list"]')).toBeInTheDocument(); expect(document.querySelector('[data-ui-id="ui.plugins.item"][data-plugin-row-id="pl-1"][data-plugin-id="com.acme.outbound"]')).toBeInTheDocument(); const settingsLink = screen.getByRole("link", { name: "Open settings" }); expect(settingsLink).toHaveAttribute("href", "/app/acme/settings/plugins/pl-1"); expect(settingsLink).toHaveAttribute("data-ui-id", "ui.plugins.settings.open"); expect(screen.queryByRole("link", { name: "View audit" })).not.toBeInTheDocument(); const manifestToggle = screen.getByRole("button", { name: "View manifest" }); expect(manifestToggle).toHaveAttribute("aria-expanded", "false"); expect(manifestToggle).toHaveAttribute("data-ui-id", "ui.plugins.manifest.toggle"); fireEvent.click(manifestToggle); expect(screen.getByRole("button", { name: "Hide manifest" })).toHaveAttribute("aria-expanded", "true"); expect(screen.getByText(/http\.outbound/u)).toBeInTheDocument(); expect(document.querySelector('[data-ui-id="ui.plugins.manifest.panel"]')).toBeInTheDocument(); }); it("shows the disable mutation control to plugin managers", () => { setLoaderData(true); renderPluginsRoute(); expect(screen.getByRole("button", { name: "Disable" })).toHaveAttribute("data-ui-id", "ui.plugins.lifecycle.button"); expect(document.querySelector('[data-ui-id="ui.plugins.lifecycle.form"]')).toBeInTheDocument(); expect(document.querySelector('input[name="id"]')).toHaveAttribute("value", "pl-1"); expect(document.querySelector('input[name="op"]')).toHaveAttribute("value", "disable"); expect(document.querySelector('input[name="csrf"]')).toHaveAttribute("value", "csrf-token"); }); it("shows plugin audit links only when the user has audit permission", () => { setLoaderData(false, pluginItem, true); renderPluginsRoute(); const auditLink = screen.getByRole("link", { name: "View audit" }); expect(auditLink).toHaveAttribute("href", "/app/acme/settings/plugins/pl-1/audit"); expect(auditLink).toHaveAttribute("data-ui-id", "ui.plugins.audit.open"); expect(screen.queryByRole("button", { name: "Disable" })).not.toBeInTheDocument(); }); it("shows revoke controls for granted capabilities to plugin managers", () => { setLoaderData(true); renderPluginsRoute(); expect(screen.getByRole("button", { name: "Revoke approval" })).toHaveAttribute("data-ui-id", "ui.plugins.capability.revoke.button"); expect(document.querySelector('[data-ui-id="ui.plugins.capability.revoke.form"]')).toBeInTheDocument(); expect(screen.getByText("Revoking approval disables this plugin.")).toBeInTheDocument(); expect(document.querySelector('input[name="pluginId"]')).toHaveAttribute("value", "com.acme.outbound"); expect(document.querySelector('input[name="capabilityNames[]"]')).toHaveAttribute("value", "http.outbound"); }); it("guides managers through capability review before enabling", () => { setLoaderData(true, { ...pluginItem, enabled: false, capabilities: [ { name: "log", scope: null, granted: false, grantedAt: null, grantedScopeJson: null, metadata: { risk: "low", productionAvailable: true }, }, ], missingCapabilities: ["log"], }); renderPluginsRoute(); expect(screen.getByText("Approval required")).toBeInTheDocument(); expect(screen.queryByRole("button", { name: "Enable" })).not.toBeInTheDocument(); const reviewToggle = screen.getByRole("button", { name: "Review capabilities" }); expect(reviewToggle).toHaveAttribute("aria-expanded", "false"); expect(reviewToggle).toHaveAttribute("data-ui-id", "ui.plugins.capabilityReview.toggle"); expect(screen.queryByRole("button", { name: "Approve and enable" })).not.toBeInTheDocument(); fireEvent.click(reviewToggle); expect(reviewToggle).toHaveAttribute("aria-expanded", "true"); expect(screen.getByRole("form", { name: "Capability review for com.acme.outbound" })).toHaveAttribute("data-ui-id", "ui.plugins.capabilityReview.form"); expect(screen.getByText("Review com.acme.outbound capabilities")).toBeInTheDocument(); expect(screen.getAllByText("No additional scope.")).toHaveLength(2); expect(screen.getByText("log")).toHaveAttribute("data-ui-id", "ui.plugins.capabilityReview.grantName"); expect(screen.getByText("Low risk")).toHaveAttribute("data-ui-id", "ui.plugins.capabilityReview.risk"); expect(screen.getByText("Available in this runtime")).toHaveAttribute("data-ui-id", "ui.plugins.capabilityReview.availability"); const approveButton = screen.getByRole("button", { name: "Approve and enable" }); expect(approveButton).toHaveAttribute("data-ui-id", "ui.plugins.capabilityReview.button"); expect(approveButton).toBeDisabled(); const reviewCheckbox = screen.getByLabelText("I reviewed Logging."); expect(reviewCheckbox).toHaveAttribute("data-ui-id", "ui.plugins.capabilityReview.checkbox"); fireEvent.click(reviewCheckbox); expect(approveButton).toBeEnabled(); expect(document.querySelector('input[name="op"]')).toHaveAttribute("value", "grantAndEnable"); expect(document.querySelector('input[name="capabilities[]"]')).toHaveAttribute("value", "log"); expect(document.querySelector('input[name="capabilitiesReviewed"]')).toHaveAttribute("value", "yes"); expect(document.querySelector('input[name="capabilityReviewDigest"]')).toHaveAttribute("value", "review-digest"); const denyButton = screen.getByRole("button", { name: "Deny" }); expect(denyButton).toHaveAttribute("data-ui-id", "ui.plugins.capabilityReview.deny"); fireEvent.click(denyButton); expect(screen.queryByRole("form", { name: "Capability review for com.acme.outbound" })).not.toBeInTheDocument(); fireEvent.click(screen.getByRole("button", { name: "Review capabilities" })); expect(screen.getByLabelText("I reviewed Logging.")).not.toBeChecked(); expect(screen.getByRole("button", { name: "Approve and enable" })).toBeDisabled(); expect(document.querySelector('input[name="capabilitiesReviewed"]')).toHaveAttribute("value", "no"); }); it("keeps approval disabled until every missing capability is reviewed", () => { setLoaderData(true, { ...pluginItem, enabled: false, capabilities: [ { name: "log", scope: null, granted: false, grantedAt: null, grantedScopeJson: null, metadata: { risk: "low", productionAvailable: true }, }, { name: "audit", scope: null, granted: false, grantedAt: null, grantedScopeJson: null, metadata: { risk: "medium", productionAvailable: true }, }, ], missingCapabilities: ["log", "audit"], }); renderPluginsRoute(); fireEvent.click(screen.getByRole("button", { name: "Review capabilities" })); const approveButton = screen.getByRole("button", { name: "Approve and enable" }); expect(approveButton).toBeDisabled(); fireEvent.click(screen.getByLabelText("I reviewed Logging.")); expect(approveButton).toBeDisabled(); expect(document.querySelector('input[name="capabilitiesReviewed"]')).toHaveAttribute("value", "no"); fireEvent.click(screen.getByLabelText("I reviewed Audit logging.")); expect(approveButton).toBeEnabled(); expect(document.querySelector('input[name="capabilitiesReviewed"]')).toHaveAttribute("value", "yes"); }); it("requires explicit review before enabling hook-only plugins", () => { setLoaderData(true, { ...pluginItem, pluginId: "com.acme.workflow-hook", enabled: false, capabilities: [ { name: "hook:workflow.executed", scope: null, granted: false, grantedAt: null, grantedScopeJson: null, metadata: { risk: "medium", productionAvailable: true }, }, ], missingCapabilities: ["hook:workflow.executed"], manifestJson: JSON.stringify({ id: "com.acme.workflow-hook", hooks: [{ name: "workflow.executed", export: "onWorkflowExecuted" }] }, null, 2), hasSettingsUi: false, }); renderPluginsRoute(); expect(screen.getByText("Hook: workflow.executed")).toBeInTheDocument(); expect(screen.getByText("Approval required")).toBeInTheDocument(); expect(screen.queryByRole("button", { name: "Enable" })).not.toBeInTheDocument(); fireEvent.click(screen.getByRole("button", { name: "Review capabilities" })); const approveButton = screen.getByRole("button", { name: "Approve and enable" }); expect(approveButton).toBeDisabled(); const reviewCheckbox = screen.getByLabelText("I reviewed Hook: workflow.executed."); expect(reviewCheckbox).toHaveAttribute("value", "hook:workflow.executed"); expect(screen.getByText("Medium risk")).toBeInTheDocument(); expect(screen.getByText("Available in this runtime")).toBeInTheDocument(); expect(screen.getAllByText("No additional scope.")).toHaveLength(2); fireEvent.click(reviewCheckbox); expect(approveButton).toBeEnabled(); expect(document.querySelector('input[name="op"]')).toHaveAttribute("value", "grantAndEnable"); expect(document.querySelector('input[name="capabilities[]"]')).toHaveAttribute("value", "hook:workflow.executed"); expect(document.querySelector('input[name="capabilitiesReviewed"]')).toHaveAttribute("value", "yes"); }); it("resets reviewed capability state when the review digest changes", () => { const itemWithMissingCapability = { ...pluginItem, enabled: false, capabilities: [ { name: "log", scope: null, granted: false, grantedAt: null, grantedScopeJson: null, metadata: { risk: "low", productionAvailable: true }, }, ], missingCapabilities: ["log"], }; setLoaderData(true, itemWithMissingCapability); const view = renderPluginsRoute(); fireEvent.click(screen.getByRole("button", { name: "Review capabilities" })); fireEvent.click(screen.getByLabelText("I reviewed Logging.")); expect(screen.getByRole("button", { name: "Approve and enable" })).toBeEnabled(); setLoaderData(true, { ...itemWithMissingCapability, capabilityReviewDigest: "changed-review-digest", capabilities: [ { name: "log", scope: null, granted: false, grantedAt: null, grantedScopeJson: null, metadata: { risk: "low", productionAvailable: true }, }, ], }); view.rerender( ); expect(screen.getByLabelText("I reviewed Logging.")).not.toBeChecked(); expect(screen.getByRole("button", { name: "Approve and enable" })).toBeDisabled(); expect(document.querySelector('input[name="capabilitiesReviewed"]')).toHaveAttribute("value", "no"); expect(document.querySelector('input[name="capabilityReviewDigest"]')).toHaveAttribute("value", "changed-review-digest"); expect(screen.getAllByText("No additional scope.")).toHaveLength(2); }); it("blocks approval for unavailable host bindings before submit", () => { setLoaderData(true, { ...pluginItem, enabled: false, capabilities: [ { name: "http.outbound", scope: { allowedHosts: ["api.example.com"] }, granted: false, grantedAt: null, grantedScopeJson: null, metadata: { risk: "high", productionAvailable: false }, }, ], missingCapabilities: ["http.outbound"], }); renderPluginsRoute(); fireEvent.click(screen.getByRole("button", { name: "Review capabilities" })); expect(screen.getByText("High risk")).toHaveAttribute("data-ui-id", "ui.plugins.capabilityReview.risk"); expect(screen.getByText("Not available in this runtime")).toHaveAttribute("data-ui-id", "ui.plugins.capabilityReview.availability"); expect(screen.getByText("This host binding is not production-available yet. It cannot be approved until the operator enables a reviewed implementation.")).toHaveAttribute( "data-ui-id", "ui.plugins.capabilityReview.unavailableReason" ); expect(screen.getByLabelText("I reviewed Outbound HTTP.")).toBeDisabled(); expect(screen.getByRole("button", { name: "Approve and enable" })).toBeDisabled(); expect(document.querySelector('input[name="capabilitiesReviewed"]')).toHaveAttribute("value", "no"); }); it("keeps capability-free plugins enable-able without consent controls", () => { setLoaderData(true, { ...pluginItem, enabled: false, capabilities: [], missingCapabilities: [], }); renderPluginsRoute(); expect(screen.getByText("This plugin declares no capabilities.")).toBeInTheDocument(); expect(screen.getByRole("button", { name: "Enable" })).toBeInTheDocument(); expect(screen.queryByRole("button", { name: "Approve and enable" })).not.toBeInTheDocument(); expect(screen.queryByRole("link", { name: "Open settings" })).not.toBeInTheDocument(); }); it("has no axe violations for the read-only plugin list", async () => { await expectNoAxeViolations( ); }); it("has no axe violations for plugin manager revoke controls", async () => { setLoaderData(true); await expectNoAxeViolations( ); }); it("has no axe violations for expanded capability review controls", async () => { setLoaderData(true, { ...pluginItem, enabled: false, capabilities: [ { name: "http.outbound", scope: { allowedHosts: ["api.example.com"] }, granted: false, grantedAt: null, grantedScopeJson: null, metadata: { risk: "high", productionAvailable: false }, }, ], missingCapabilities: ["http.outbound"], }); const { container } = renderPluginsRoute(); fireEvent.click(screen.getByRole("button", { name: "Review capabilities" })); expect(screen.getByRole("form", { name: "Capability review for com.acme.outbound" })).toBeInTheDocument(); expect((await runAxe(container)).violations).toEqual([]); }); });