import { expect, test, type Locator, type Page } from "./utils/test"; import { expectNoCriticalA11yViolations } from "./utils/axe"; import { getTenantCredentials, loginAsTenantUser } from "./utils/auth"; import { compactMobileViewport, expectNoHorizontalOverflow, narrowMobileViewport } from "./utils/mobile"; import { escapeRegExp, skipIfUnavailable } from "./utils/navigation"; import { isE2eOperatorOptInEnabled, missingE2eInputs, skipOrFailWhenE2eFixtureMissing, skipOrFailWhenE2eInputsMissing, skipOrFailWhenE2eOptInMissing, skipWhenE2eOperatorOptInMissing, } from "./utils/readiness"; import { requireWorkflowOutboxDrainReadiness, waitForWorkflowExecutionTerminal } from "./utils/workflow"; /** * Plugin hook lifecycle mobile a11y — proves the seeded readiness plugin's * `workflow.executed` hook (export `onWorkflowExecuted`) records a * capability-use audit row after a manual workflow runs and the worker drains * the outbox, then exercises deactivate→re-enable lifecycle controls. * * Safe-by-default gating: * - Login + read-only assertions only need tenant credentials + the plugin * settings path (skips unless REQUIRE_E2E_READINESS=1). * - The hook-audit observation is OPERATOR-gated behind * E2E_REQUIRE_PLUGIN_HOOK_AUDIT=1 because it needs a running general worker, * plugin runtime, and outbox drain. It also reuses the workflow outbox-drain * readiness gate so it only runs when the worker is actually draining. * - Granting capabilities and toggling enable/disable are MUTATIONS, gated * additionally behind E2E_ALLOW_PLUGIN_LIFECYCLE_MUTATION=1. * * Mutating tests restore the seeded baseline (plugin ENABLED, `log` granted, * `audit` NOT granted) in a finally block so reruns stay idempotent. Note that * re-running the readiness seed also resets capability state; here we revoke * the `audit` grant explicitly through the revoke form to restore baseline. */ const credentials = getTenantCredentials(); const pluginSettingsPath = process.env.E2E_PLUGIN_SETTINGS_PATH; const workflowRunManualPath = process.env.E2E_WORKFLOW_RUN_MANUAL_PATH; // FIXTURE SEPARATION: these lifecycle/audit tests MUTATE the plugin they target // (grant audit, deactivate/re-enable). They must NOT touch the shared // `com.hivegrid.e2e-readiness` plugin, whose "enabled + audit-missing" seed // baseline the plugin-settings review/grant tests depend on and which is // UI-unrestorable once mutated (revoke auto-disables; the disabled+missing-cap // row hides its enable form). The seeded `com.hivegrid.e2e-lifecycle` plugin is // fully provisioned (all capabilities + hook consent granted), so granting audit // is a no-op and deactivate→re-enable never hits the review-before-enable gate — // the perfect dedicated fixture for these mutating tests. const lifecyclePluginId = "com.hivegrid.e2e-lifecycle"; const pluginHookAuditRequiredInputs = [ "E2E_TENANT_EMAIL", "E2E_TENANT_PASSWORD", "E2E_PLUGIN_SETTINGS_PATH", "E2E_WORKFLOW_RUN_MANUAL_PATH", ] as const; // Audit row outcome label (en/de) and the readiness plugin's hook-driven // capabilities. The seed grants `log`; consent grants `audit`. Either one // producing a success row after the hook fires proves the lifecycle. const auditSuccessOutcomePattern = /success|erfolgreich/i; const hookCapabilityPattern = /^(audit|log)$/u; /** * Operator gate for the hook-audit observation lane. Skips when the operator * opt-in is missing, and fails loudly when the opt-in is set but its required * fixture inputs are absent — mirroring requireWorkflowOutboxDrainReadiness so a * required readiness lane can never go green by silently skipping. */ function requirePluginHookAuditReadiness(env: NodeJS.ProcessEnv = process.env): void { if (!isE2eOperatorOptInEnabled("E2E_REQUIRE_PLUGIN_HOOK_AUDIT", env)) { skipWhenE2eOperatorOptInMissing( "E2E_REQUIRE_PLUGIN_HOOK_AUDIT", "plugin workflow.executed hook capability-use audit observation is operator-gated" ); return; } const missing = missingE2eInputs(pluginHookAuditRequiredInputs, env); if (missing.length > 0) { throw new Error(`E2E plugin hook-audit readiness opt-in missing ${missing.join(", ")} while E2E_REQUIRE_PLUGIN_HOOK_AUDIT=1.`); } // The hook only fires + drains when the worker/outbox path is running, so the // observation lane additionally requires the workflow outbox-drain readiness. requireWorkflowOutboxDrainReadiness(env); } function getPluginHookAuditPollTimeoutMs(env: NodeJS.ProcessEnv = process.env): number { const parsed = Number.parseInt(env.E2E_PLUGIN_HOOK_AUDIT_TIMEOUT_MS ?? "", 10); return Number.isFinite(parsed) && parsed > 0 ? parsed : 90_000; } function skipUnlessPluginLifecycleMutationAllowed(reason: string): void { skipOrFailWhenE2eOptInMissing("E2E_ALLOW_PLUGIN_LIFECYCLE_MUTATION", `skipping mutating plugin lifecycle ${reason}`); } test.describe("plugin hook lifecycle mobile a11y", () => { test.use({ viewport: narrowMobileViewport, isMobile: true, hasTouch: true }); test.beforeEach(() => { skipOrFailWhenE2eInputsMissing( ["E2E_TENANT_EMAIL", "E2E_TENANT_PASSWORD", "E2E_PLUGIN_SETTINGS_PATH"], "Plugin hook lifecycle mobile a11y inputs not configured" ); }); test("audit trail view for the readiness plugin stays readable on mobile without mutations", async ({ page }) => { await loginAsTenantUser(page, credentials!); const response = await page.goto(pluginSettingsPath!, { waitUntil: "domcontentloaded" }); await skipIfUnavailable(page, response, "Plugin hook lifecycle audit view path"); const pluginRow = await readinessPluginRow(page); const auditLink = pluginRow.locator('[data-ui-id="ui.plugins.audit.open"]').first(); if ((await auditLink.count()) === 0 || !(await auditLink.isVisible())) { skipOrFailWhenE2eFixtureMissing("Plugin readiness fixture has no audit trail link (audit-trails view permission missing)"); } // The audit page is read-only; assert no mutating request is issued while // navigating + inspecting it. const mutatingRequests: string[] = []; await page.route("**/*", async (route) => { const method = route.request().method(); // Observability beacons (Sentry/OTel) are not app mutations; the live // boiler target has them enabled, so exclude them from the guard. const isTelemetry = /sentry|otel|otlp/iu.test(route.request().url()); if (!isTelemetry && (method === "POST" || method === "PATCH" || method === "DELETE")) { mutatingRequests.push(`${method} ${route.request().url()}`); await route.abort(); return; } await route.continue(); }); await auditLink.click(); await expect(page).toHaveURL(/\/settings\/integrations\/plugins\/[^/?#]+\/audit(?:[?#].*)?$/u); // No data-ui-ids exist on the audit route; assert via real rendered text. await expect(page.getByRole("heading", { name: new RegExp(escapeRegExp(lifecyclePluginId), "u") }).first()).toBeVisible(); await expect(page.getByText(/plugin capability invocations|aufrufe von plugin-berechtigungen/i).first()).toBeVisible(); // Either a populated table (Timestamp/Outcome headers) or the empty-state copy. await expect( page .getByText(/timestamp|zeitstempel|outcome|ergebnis|no capability invocations|keine .*aufrufe/i) .first() ).toBeVisible(); expect(mutatingRequests, `Unexpected mutating requests on audit view: ${mutatingRequests.join(", ")}`).toEqual([]); await expectNoHorizontalOverflow(page); await expectNoCriticalA11yViolations(page); }); test("workflow.executed hook records a capability-use audit row after the worker drains", async ({ page }) => { requirePluginHookAuditReadiness(); skipUnlessPluginLifecycleMutationAllowed("workflow.executed hook capability-use observation"); await loginAsTenantUser(page, credentials!); const settingsResponse = await page.goto(pluginSettingsPath!, { waitUntil: "domcontentloaded" }); await skipIfUnavailable(page, settingsResponse, "Plugin hook lifecycle settings path"); const capabilityRestore = await snapshotCapabilityGrant(page, "audit"); try { // Grant `audit` so the hook can record an audit capability-use row. The // seed baseline leaves `audit` ungranted; we restore it in finally. await ensureCapabilityGranted(page, "audit"); const auditPath = await readinessAuditPath(page); // Trigger the seeded manual workflow run; this fires `workflow.executed`. const runResponse = await page.goto(workflowRunManualPath!, { waitUntil: "domcontentloaded" }); await skipIfUnavailable(page, runResponse, "Plugin hook lifecycle manual run path"); const runButton = page.locator('[data-ui-id="ui.workflows.run.manual.submit"], button.ui-workflows-run-manual-submit').first(); await expect(runButton).toBeVisible(); if (!(await runButton.isEnabled())) { skipOrFailWhenE2eFixtureMissing("Workflow manual run button is disabled; provide a live deterministic workflow path to drive the plugin hook"); } await runButton.click(); const executionResult = page.locator('[data-ui-id="ui.workflows.run.manual.executionResult"]').first(); await expect(executionResult).toBeVisible({ timeout: 15_000 }); const detailLink = executionResult.locator('[data-ui-id="ui.workflows.run.manual.viewExecutionFlow"]').first(); await expect(detailLink).toBeVisible(); const executionDetailsHref = await detailLink.getAttribute("href"); expect(executionDetailsHref).toMatch(/\/workflow-engine\/workflows\/[^/?#]+\/executions\?executionId=[^]+/u); // Wait for the worker to drain the outbox and the execution to terminate. await waitForWorkflowExecutionTerminal(page, executionDetailsHref!); // Poll the audit trail until a success capability-use row appears for the // readiness plugin's hook-driven `audit`/`log` capability. await expect .poll(async () => readinessPluginHasSuccessfulHookAuditRow(page, auditPath), { message: "readiness plugin workflow.executed hook recorded a success capability-use audit row", timeout: getPluginHookAuditPollTimeoutMs(), intervals: [1_000, 2_000, 5_000], }) .toBe(true); await expectNoHorizontalOverflow(page); await expectNoCriticalA11yViolations(page); } finally { await restoreCapabilityGrant(page, capabilityRestore); } }); test("deactivate then re-enable restores the readiness plugin lifecycle baseline", async ({ page }) => { skipUnlessPluginLifecycleMutationAllowed("deactivate/re-enable lifecycle flow"); await loginAsTenantUser(page, credentials!); const response = await page.goto(pluginSettingsPath!, { waitUntil: "domcontentloaded" }); await skipIfUnavailable(page, response, "Plugin hook lifecycle deactivate/re-enable path"); let pluginRow = await readinessPluginRow(page); // AK-UI-05: the lifecycle control is a ~/ui button carrying its op in // `data-op`, not a