Files
crank/apps/ui/tests/e2e/openapi-recovery.spec.js
bsodfather 54ce770682
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.

Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
  Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
  3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
  revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
  version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
  dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
  resources/list admission fix for bound template publications.

Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
  `just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
  a real MCP Inspector 2.12.0 client smoke.

Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
  runs only on main), story events run the changed packages, the full workspace suite
  stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
  release entry of the tag instead of dying with the runner workspace.

Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.

Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
2026-10-25 09:08:22 +00:00

350 lines
16 KiB
JavaScript

const fs = require('node:fs/promises');
const path = require('node:path');
const { test, expect } = require('@playwright/test');
const { getCurrentWorkspace, login, localized, uniqueName } = require('./helpers');
const controlDirectory = path.resolve(__dirname, '../../../../.tmp/ui-e2e');
async function dismissOnboardingIfOpen(page) {
await page.locator('#crank-onboarding-panel').waitFor({ state: 'attached' });
await page.locator('[data-testid="onboarding-dismiss"]').waitFor({ state: 'attached' });
await page.evaluate(() => document.querySelector('[data-testid="onboarding-dismiss"]').click());
await expect(page.locator('#crank-onboarding-panel')).toBeHidden();
}
function openApiDocument(operationId) {
return [
'openapi: 3.0.3',
`info: { title: '${operationId}', version: '1' }`,
'servers: [{ url: https://api.example.test }]',
'paths:',
` /${operationId}:`,
' get:',
` operationId: ${operationId}`,
' summary: Recovery test operation',
' responses:',
" '200': { description: OK }",
'',
].join('\n');
}
async function operationSnapshot(page, workspaceId) {
return page.evaluate(async (id) => {
const response = await window.CrankApi.listOperations(id);
if (!response || !Array.isArray(response.items)) throw new Error('Operations API returned no item list');
return response.items;
}, workspaceId);
}
// Deterministic stand-in for "replay after reload": hides the CSRF token and
// makes the session restore wait until the test releases it. Every attempt that
// reaches the wait is counted, so the test can prove a cancelled attempt never
// installs itself again and never sends its POST.
async function installSessionGate(page) {
await page.evaluate(() => {
const auth = window.CrankAuth;
const realToken = auth.getCsrfToken();
if (!realToken) throw new Error('the CSRF gate needs an authenticated session token');
const original = { getCsrfToken: auth.getCsrfToken, fetchSession: auth.fetchSession };
const gate = { realToken, waits: 0, released: false, resolvers: [] };
gate.release = () => {
gate.released = true;
gate.resolvers.splice(0).forEach((resolve) => resolve(auth.getCachedSession()));
};
gate.restore = () => {
gate.release();
auth.getCsrfToken = original.getCsrfToken;
auth.fetchSession = original.fetchSession;
};
window.__csrfGate = gate;
auth.getCsrfToken = () => (gate.released ? gate.realToken : '');
auth.fetchSession = () => {
gate.waits += 1;
return new Promise((resolve) => { gate.resolvers.push(resolve); });
};
});
}
async function requestAdminControl(command) {
const requestFile = path.join(controlDirectory, 'admin-control.request');
const ackFile = path.join(controlDirectory, 'admin-control.ack');
await fs.mkdir(controlDirectory, { recursive: true });
await fs.rm(ackFile, { force: true });
const temporaryFile = `${requestFile}.${process.pid}.${Date.now()}.tmp`;
await fs.writeFile(temporaryFile, `${command}\n`, { mode: 0o600 });
await fs.rename(temporaryFile, requestFile);
await expect.poll(async () => {
try {
return (await fs.readFile(ackFile, 'utf8')).trim();
} catch (_error) {
return '';
}
}, { timeout: 30_000, message: `Admin API did not acknowledge ${command}` }).toBe(command);
}
async function adminApiPid() {
return (await fs.readFile(path.join(controlDirectory, 'admin-api.pid'), 'utf8')).trim();
}
async function storageCounts(workspaceId) {
await requestAdminControl(`counts ${workspaceId}`);
return JSON.parse(await fs.readFile(path.join(controlDirectory, 'storage-counts.json'), 'utf8'));
}
async function openImport(page, operationId) {
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await page.locator('#openapi-import-file').setInputFiles({
name: `${operationId}.yaml`,
mimeType: 'application/yaml',
buffer: Buffer.from(openApiDocument(operationId)),
});
const previewResponse = page.waitForResponse((response) =>
response.request().method() === 'POST'
&& response.url().includes('/imports/openapi/preview'));
await page.locator('#openapi-import-preview').click();
const response = await previewResponse;
expect(response.ok()).toBe(true);
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
return response;
}
test('[P1] AC03 real invalid preview shows the exact canonical correlation headers', async ({ page }) => {
await login(page);
await dismissOnboardingIfOpen(page);
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await page.locator('#openapi-import-file').setInputFiles({
name: 'invalid-openapi.yaml',
mimeType: 'application/yaml',
buffer: Buffer.from('openapi: [\n'),
});
const rejectedPreview = page.waitForResponse((response) =>
response.request().method() === 'POST'
&& response.url().includes('/imports/openapi/preview'));
await page.locator('#openapi-import-preview').click();
const response = await rejectedPreview;
expect(response.status()).toBeGreaterThanOrEqual(400);
expect(response.status()).toBeLessThan(500);
const requestId = response.headers()['x-request-id'];
const traceId = response.headers()['x-trace-id'];
expect(requestId).toBeTruthy();
expect(traceId).toMatch(/^[a-f0-9]{32}$/i);
const status = page.locator('#openapi-import-status');
await expect(status).toBeFocused();
await expect(status).toHaveAttribute('role', 'status');
await expect(status).toHaveAttribute('aria-live', 'polite');
await expect(status).toHaveAttribute('aria-atomic', 'true');
await expect(status).toContainText(requestId);
await expect(status).toContainText(traceId);
await expect(status).toContainText('Request ID:');
await expect(status).toContainText('Trace ID:');
});
test('[P1] AC05 real preview and plan do not mutate Operations; reduced-motion Apply replay survives reload and API restart', async ({ page }) => {
// This journey includes bounded process stop/start and several database observations.
test.setTimeout(120_000);
await page.emulateMedia({ reducedMotion: 'reduce' });
await login(page);
await dismissOnboardingIfOpen(page);
expect(await page.evaluate(() => window.matchMedia('(prefers-reduced-motion: reduce)').matches)).toBe(true);
const workspace = await getCurrentWorkspace(page);
expect(workspace && workspace.id).toBeTruthy();
const initialOperations = await operationSnapshot(page, workspace.id);
const initialCounts = await storageCounts(workspace.id);
expect(initialCounts).toMatchObject({
sources: expect.any(Number),
operations: expect.any(Number),
versions: expect.any(Number),
});
const operationId = uniqueName('recovery_import').replace(/[^a-zA-Z0-9_]/g, '_');
const applyRequests = [];
const apiRequests = { preview: 0, createPlan: 0, apply: 0 };
page.on('request', (request) => {
if (request.method() !== 'POST') return;
const url = request.url();
if (url.includes('/imports/openapi/preview')) apiRequests.preview += 1;
if (/\/imports\/openapi\/[^/]+\/plans(?:\?|$)/.test(url)) apiRequests.createPlan += 1;
if (/\/imports\/openapi\/[^/]+\/apply(?:\?|$)/.test(url)) apiRequests.apply += 1;
});
await page.route('**/imports/openapi/*/apply', async (route) => {
applyRequests.push({
url: route.request().url(),
body: route.request().postData(),
});
if (applyRequests.length === 1) {
// Send the real request to Admin API, then lose only its browser response.
const response = await route.fetch();
expect(response.ok()).toBe(true);
await route.abort('connectionreset');
return;
}
await route.continue();
});
await openImport(page, operationId);
expect(await operationSnapshot(page, workspace.id)).toEqual(initialOperations);
expect(apiRequests.preview).toBe(1);
const afterPreviewCounts = await storageCounts(workspace.id);
expect(afterPreviewCounts).toEqual({
...initialCounts,
sources: initialCounts.sources + 1,
});
const dialogMotion = await page.locator('.openapi-import-dialog').evaluate((node) => getComputedStyle(node).transitionDuration);
expect(dialogMotion.split(',').every((duration) => Number.parseFloat(duration) === 0)).toBe(true);
await page.locator('#openapi-import-server-custom').fill('https://api.example.test');
await page.locator('#openapi-import-create').click();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
expect(await operationSnapshot(page, workspace.id)).toEqual(initialOperations);
expect(apiRequests.createPlan).toBe(1);
expect(await storageCounts(workspace.id)).toEqual(afterPreviewCounts);
await page.locator('#openapi-import-plan-apply').click();
await expect.poll(() => applyRequests.length).toBe(1);
expect(apiRequests.apply).toBe(1);
const applyStatus = page.locator('#openapi-import-status');
await expect(applyStatus).toBeFocused();
await expect(applyStatus).toHaveAttribute('role', 'status');
await expect(applyStatus).toHaveAttribute('aria-live', 'polite');
await expect(applyStatus).toHaveAttribute('aria-atomic', 'true');
await expect(applyStatus).toContainText(localized('Apply result is unknown', 'Результат применения неизвестен'));
await expect(page.locator('#openapi-import-retry')).toBeVisible();
const committedOperations = await operationSnapshot(page, workspace.id);
expect(committedOperations).toHaveLength(initialOperations.length + 1);
expect(committedOperations.some((operation) => operation.name === operationId
|| operation.operation_id === operationId)).toBe(true);
const committedCounts = await storageCounts(workspace.id);
expect(committedCounts).toEqual({
...afterPreviewCounts,
operations: afterPreviewCounts.operations + 1,
versions: afterPreviewCounts.versions + 1,
});
const pidBeforeRestart = await adminApiPid();
let adminMayBeStopped = true;
try {
await requestAdminControl('stop');
await requestAdminControl('start');
adminMayBeStopped = false;
} finally {
if (adminMayBeStopped) await requestAdminControl('start');
}
expect(await adminApiPid()).not.toBe(pidBeforeRestart);
expect(await storageCounts(workspace.id)).toEqual(committedCounts);
await page.reload();
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await expect(page.locator('#openapi-import-retry')).toBeVisible();
await expect(page.locator('#openapi-import-status')).toContainText(localized('Apply result is unknown', 'Результат применения неизвестен'));
const retryResponse = page.waitForResponse((response) =>
response.request().method() === 'POST'
&& response.url().includes('/imports/openapi/')
&& response.url().endsWith('/apply'));
await page.locator('#openapi-import-retry').click();
const response = await retryResponse;
expect(response.status()).toBe(200);
await expect(page.locator('#openapi-import-result')).toContainText(operationId);
await expect.poll(() => applyRequests.length).toBe(2);
expect(applyRequests[1].url).toBe(applyRequests[0].url);
expect(applyRequests[1].body).toBe(applyRequests[0].body);
expect(apiRequests).toEqual({ preview: 1, createPlan: 1, apply: 2 });
const finalOperations = await operationSnapshot(page, workspace.id);
expect(finalOperations).toHaveLength(initialOperations.length + 1);
expect(finalOperations.filter((operation) => operation.name === operationId
|| operation.operation_id === operationId)).toHaveLength(1);
expect(await storageCounts(workspace.id)).toEqual(committedCounts);
});
test('[P1] AC05 Apply waits for the CSRF session before the POST and a cancelled wait never replays', async ({ page }) => {
test.setTimeout(120_000);
await login(page);
await dismissOnboardingIfOpen(page);
const workspace = await getCurrentWorkspace(page);
expect(workspace && workspace.id).toBeTruthy();
const initialOperations = await operationSnapshot(page, workspace.id);
const applyRequests = [];
page.on('request', (request) => {
if (request.method() !== 'POST') return;
if (!/\/imports\/openapi\/[^/]+\/apply(?:\?|$)/.test(request.url())) return;
applyRequests.push({
url: request.url(),
body: request.postData(),
csrf: request.headers()['x-csrf-token'] || '',
});
});
const openPlanFor = async (operationId) => {
await openImport(page, operationId);
await page.locator('#openapi-import-server-custom').fill('https://api.example.test');
await page.locator('#openapi-import-create').click();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
};
const waitForApplyResponse = () => page.waitForResponse((response) =>
response.request().method() === 'POST'
&& response.url().includes('/imports/openapi/')
&& response.url().endsWith('/apply'));
const gateWaits = () => page.evaluate(() => window.__csrfGate.waits);
// A: the first Apply must hold the POST until the session (and its CSRF
// token) is restored, and a second click must not start a second attempt.
const operationA = uniqueName('csrf_gate_a').replace(/[^a-zA-Z0-9_]/g, '_');
await openPlanFor(operationA);
await installSessionGate(page);
await page.locator('#openapi-import-plan-apply').click();
await expect.poll(gateWaits).toBe(1);
// The attempt owns the existing cancel scheme before its async wait.
await expect(page.locator('#openapi-import-cancel')).toBeVisible();
await expect(page.locator('#openapi-import-plan-apply')).toBeDisabled();
expect(applyRequests).toHaveLength(0);
const appliedA = waitForApplyResponse();
await page.evaluate(() => window.__csrfGate.release());
expect((await appliedA).status()).toBe(200);
expect(applyRequests).toHaveLength(1);
expect(applyRequests[0].csrf).toBeTruthy();
await expect(page.locator('#openapi-import-result')).toContainText(operationA);
await page.evaluate(() => window.__csrfGate.restore());
// B: closing the modal while the session restore is still pending must not
// replay the cancelled attempt; the visible retry is the only POST and it
// keeps the same URL, body and idempotency key.
await page.evaluate(() => window.CrankOpenApiImport.close());
const operationB = uniqueName('csrf_gate_b').replace(/[^a-zA-Z0-9_]/g, '_');
await openPlanFor(operationB);
await installSessionGate(page);
await page.locator('#openapi-import-plan-apply').click();
await expect.poll(gateWaits).toBe(1);
await page.keyboard.press('Escape');
await expect(page.locator('#openapi-import-modal')).toBeHidden();
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await expect(page.locator('#openapi-import-retry')).toBeVisible();
const replay = await page.evaluate(() =>
JSON.parse(sessionStorage.getItem('crank_openapi_plan_apply_replay_v2')));
expect(replay && replay.idempotencyKey).toBeTruthy();
await page.locator('#openapi-import-retry').click();
await expect.poll(gateWaits).toBe(2);
expect(applyRequests).toHaveLength(1);
const appliedB = waitForApplyResponse();
await page.evaluate(() => window.__csrfGate.release());
expect((await appliedB).status()).toBe(200);
await page.evaluate(() => window.__csrfGate.restore());
expect(applyRequests).toHaveLength(2);
expect(applyRequests[1].csrf).toBeTruthy();
expect(applyRequests[1].body).toContain(replay.idempotencyKey);
expect(applyRequests[1].body).toContain(replay.planDigest);
await expect(page.locator('#openapi-import-result')).toContainText(operationB);
const finalOperations = await operationSnapshot(page, workspace.id);
expect(finalOperations).toHaveLength(initialOperations.length + 2);
for (const applied of [operationA, operationB]) {
expect(finalOperations.filter((operation) => operation.name === applied
|| operation.operation_id === applied)).toHaveLength(1);
}
});