fix(import): подтвердить обязательные гарантии второго эпика
CI / Rust Checks (pull_request) Successful in 24m43s
CI / UI Checks (pull_request) Successful in 6s
CI / Community Image Smoke (pull_request) Successful in 9m5s
CI / Frontend E2E (pull_request) Successful in 12m43s
CI / Deploy (pull_request) Skipped

This commit is contained in:
bsodfather committed 2026-10-10 13:25:05 +03:00
1 parent 31f6f00d3b
commit ad23cd9a46
33 files changed
+3328 -18

No files matched your search

+2
View File
@@ -2247,6 +2247,7 @@ Object.assign(TRANSLATIONS.en, {
'openapi.finding.missing_servers': 'No base URL was found in the document.',
'openapi.finding.multiple_servers': 'Several base URLs are available; choose one before creating drafts.',
'openapi.finding.unsupported_request_body': 'This request body needs review in the wizard.',
'openapi.finding.external_reference_disabled': 'External references are blocked by default. Check the reference at this source location. A server administrator must add trusted addresses to the server allowlist. For offline use, prepare a self-contained OpenAPI file with its referenced schemas included before uploading; this screen accepts one file and does not upload separate reference files.',
'openapi.finding.operation_name_renamed': 'The operation name was adjusted to keep it unique.',
'openapi.finding.operation_name_conflict': 'An operation with this name already exists.',
'openapi.finding.weak_tool_description': 'The tool description is too short.',
@@ -2449,6 +2450,7 @@ Object.assign(TRANSLATIONS.ru, {
'openapi.finding.missing_servers': 'В документе не найден base URL.',
'openapi.finding.multiple_servers': 'В документе несколько base URL; выберите один перед созданием черновиков.',
'openapi.finding.unsupported_request_body': 'Тело этого запроса нужно проверить в мастере.',
'openapi.finding.external_reference_disabled': 'Внешние ссылки по умолчанию запрещены. Проверьте ссылку по указанному пути. Администратор сервера может добавить доверенные адреса в список разрешённых адресов. Для работы без сети заранее подготовьте самодостаточный OpenAPI-файл, включив в него схемы из внешних ссылок; этот экран принимает один файл и не загружает отдельные файлы зависимостей.',
'openapi.finding.operation_name_renamed': 'Имя операции изменено, чтобы сохранить уникальность.',
'openapi.finding.operation_name_conflict': 'Операция с таким именем уже существует.',
'openapi.finding.weak_tool_description': 'Описание инструмента слишком короткое.',
+1
View File
@@ -724,6 +724,7 @@
multiple_servers: 'openapi.finding.multiple_servers',
unsupported_request_body: 'openapi.finding.unsupported_request_body',
unsupported_security_scheme: 'openapi.finding.unsupported_security_scheme',
external_reference_disabled: 'openapi.finding.external_reference_disabled',
unsupported_security_and_requirement: 'openapi.finding.unsupported_security_and_requirement',
auth_profile_required: 'openapi.error.auth_profile_required',
operation_name_renamed: 'openapi.finding.operation_name_renamed',
+63 -6
View File
@@ -101,6 +101,7 @@ trap cleanup EXIT
trap 'exit 130' INT TERM
cleanup
rm -f "$TMP_DIR/admin-control.request" "$TMP_DIR/admin-control.ack"
show_startup_log() {
local log_file="$1"
@@ -235,7 +236,8 @@ chmod 700 "$CRANK_STORAGE_ROOT"
(
cd "$ROOT_DIR/apps/ui"
exec node scripts/playwright-http-fixture.js >"$LOG_DIR/http-fixture.log" 2>&1
exec env CRANK_E2E_STREAM_FIXTURE_PORT="$STREAM_FIXTURE_PORT" \
node scripts/playwright-http-fixture.js >"$LOG_DIR/http-fixture.log" 2>&1
) &
echo $! > "$TMP_DIR/http-fixture.pid"
@@ -292,12 +294,27 @@ if ! (
exit 1
fi
# Launch the built executable directly so the test lifecycle controls the
# actual server PID, rather than a Cargo wrapper. This control exists only in
# the local Playwright harness and adds no application endpoint/configuration.
(
cd "$ROOT_DIR"
exec env -u CRANK_MCP_BIND -u CRANK_MCP_REFRESH_MS CRANK_DEMO_SEED=true \
cargo run -p admin-api --bin admin-api >>"$LOG_DIR/admin-api.log" 2>&1
) &
echo $! > "$TMP_DIR/admin-api.pid"
cargo build -p admin-api --bin admin-api --example e2e_storage_counts >>"$LOG_DIR/admin-api.log" 2>&1
)
ADMIN_BINARY="${CARGO_TARGET_DIR:-$ROOT_DIR/target}/debug/admin-api"
if [[ "$ADMIN_BINARY" != /* ]]; then
ADMIN_BINARY="$ROOT_DIR/$ADMIN_BINARY"
fi
STORAGE_COUNTS_BINARY="$(dirname "$ADMIN_BINARY")/examples/e2e_storage_counts"
start_admin() {
(
cd "$ROOT_DIR"
exec env -u CRANK_MCP_BIND -u CRANK_MCP_REFRESH_MS CRANK_DEMO_SEED=true \
"$ADMIN_BINARY" >>"$LOG_DIR/admin-api.log" 2>&1
) &
echo $! > "$TMP_DIR/admin-api.pid"
}
start_admin
wait_for_http \
"admin-api" \
@@ -322,7 +339,9 @@ wait_for_http \
(
cd "$ROOT_DIR/apps/ui"
exec node scripts/playwright-ui-server.js >"$LOG_DIR/ui-server.log" 2>&1
exec env CRANK_E2E_UI_PORT="$UI_PORT" CRANK_E2E_ADMIN_PORT="$ADMIN_PORT" \
CRANK_E2E_MCP_PORT="$MCP_PORT" \
node scripts/playwright-ui-server.js >"$LOG_DIR/ui-server.log" 2>&1
) &
echo $! > "$TMP_DIR/ui-server.pid"
@@ -335,5 +354,43 @@ wait_for_http \
echo "Crank UI e2e stack is ready on http://127.0.0.1:$UI_PORT"
while true; do
if [[ -f "$TMP_DIR/admin-control.request" ]]; then
command=""
read -r command < "$TMP_DIR/admin-control.request" || true
rm -f "$TMP_DIR/admin-control.request"
case "$command" in
stop)
if [[ -f "$TMP_DIR/admin-api.pid" ]]; then
admin_pid="$(cat "$TMP_DIR/admin-api.pid")"
kill "$admin_pid" 2>/dev/null || true
wait "$admin_pid" || true
rm -f "$TMP_DIR/admin-api.pid"
fi
;;
start)
if [[ ! -f "$TMP_DIR/admin-api.pid" ]] || \
! kill -0 "$(cat "$TMP_DIR/admin-api.pid")" 2>/dev/null; then
start_admin
fi
wait_for_http "restarted admin-api" "http://127.0.0.1:$ADMIN_PORT/health" \
"$TMP_DIR/admin-api.pid" "$LOG_DIR/admin-api.log" || exit 1
;;
counts\ *)
workspace="${command#counts }"
if [[ ! "$workspace" =~ ^[a-zA-Z0-9_-]{1,128}$ ]]; then
echo "Invalid local storage observation scope" >&2
exit 1
fi
"$STORAGE_COUNTS_BINARY" "$workspace" > "$TMP_DIR/storage-counts.json.tmp"
mv "$TMP_DIR/storage-counts.json.tmp" "$TMP_DIR/storage-counts.json"
;;
*)
echo "Unknown local Admin API test control command" >&2
exit 1
;;
esac
printf '%s\n' "$command" > "$TMP_DIR/admin-control.ack.tmp"
mv "$TMP_DIR/admin-control.ack.tmp" "$TMP_DIR/admin-control.ack"
fi
sleep 1
done
+2
View File
@@ -292,6 +292,8 @@ test('authentication recovery returns to an incomplete authoritative onboarding
});
await page.goto('/');
// Wait for the initial projection and its automatic panel opening before toggling.
await expect(page.getByTestId('onboarding-trigger')).toContainText(/3\s*\/\s*7/);
if (!await page.getByTestId('onboarding-checklist').isVisible()) {
await page.getByTestId('onboarding-trigger').click();
}
+59 -2
View File
@@ -61,7 +61,7 @@ function planResponse(prefix) {
};
}
async function preparePlanFlow(page, locale) {
async function preparePlanFlow(page, locale, reportFixture) {
const planCalls = [];
const applyCalls = [];
const prefix = uniqueName('plan_apply');
@@ -98,7 +98,7 @@ async function preparePlanFlow(page, locale) {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
body: JSON.stringify(reportFixture || {
plan_digest: 'a'.repeat(64),
counts: { selected: 1, excluded: 1, created: 0, versioned: 1 },
outcomes: [{ status: 'versioned' }],
@@ -196,6 +196,63 @@ test('[P1] AC-13 double-click sends one Apply with the stored reference, digest
expect(applyCalls[0].payload.idempotency_key.length).toBeGreaterThan(0);
});
for (const locale of ['en', 'ru']) {
test(`[P1] AC-2.13-13 renders every immutable Apply outcome in ${locale}`, async ({ page }) => {
const reportFixture = {
plan_digest: 'd'.repeat(64),
idempotency_key: 'apply-report-full-outcomes',
status: 'applied',
counts: { selected: 5, excluded: 0, created: 1, versioned: 1, renamed: 1, skipped: 1, rejected: 1 },
outcomes: [
{ key: 'GET /created', name: 'created_operation', status: 'created', version: 1 },
{ key: 'GET /versioned', name: 'versioned_operation', status: 'versioned', version: 2 },
{ key: 'GET /renamed', name: 'renamed_operation', status: 'renamed', version: 1 },
{ key: 'GET /skipped', name: 'skipped_operation', status: 'skipped', reason: 'not_selected' },
{
key: 'GET /rejected',
name: 'rejected_operation',
status: 'rejected',
reason: 'unsupported_schema',
message: 'raw-report-canary https://report-secret.example.test/internal',
},
],
};
const { releaseApplyResponse } = await preparePlanFlow(page, locale, reportFixture);
await page.locator('[data-testid="openapi-import-apply-confirmation"]').getByRole('button', {
name: localized('Apply import', 'Применить импорт'),
}).click();
releaseApplyResponse();
const report = page.locator('[data-testid="openapi-import-apply-result"]');
await expect(report).toBeVisible();
await expect(report.locator('.openapi-import-plan-summary')).toContainText(
localized('Applied: 3; skipped: 1; excluded: 0; rejected: 1.', 'Применено: 3; пропущено: 1; исключено: 0; отклонено: 1.'),
);
for (const outcome of reportFixture.outcomes) {
const row = report.locator(`[data-outcome="${outcome.status}"]`);
await expect(row).toHaveCount(1);
await expect(row).toContainText(outcome.name);
await expect(row).toContainText(outcome.key);
if (outcome.version) await expect(row).toContainText(`v${outcome.version}`);
if (outcome.reason) {
const reason = row.locator('.openapi-import-plan-reason');
await expect(reason).toBeVisible();
await expect(reason).toContainText(localized(
'This imported item needs review in the wizard.',
'Этот импортированный элемент нужно проверить в мастере.',
));
}
}
await expect(report.locator('[data-outcome="created"]')).toContainText(localized('Created', 'Создано'));
await expect(report.locator('[data-outcome="versioned"]')).toContainText(localized('New Draft Version', 'Новая версия черновика'));
await expect(report.locator('[data-outcome="renamed"]')).toContainText(localized('Created with confirmed name', 'Создано с подтверждённым именем'));
await expect(report.locator('[data-outcome="skipped"]')).toContainText(localized('Skipped', 'Пропущено'));
await expect(report.locator('[data-outcome="rejected"]')).toContainText(localized('Rejected', 'Отклонено'));
await expect(report).not.toContainText('raw-report-canary');
await expect(report).not.toContainText('https://report-secret.example.test/internal');
});
}
test('[P1] AC-13 submits the confirmed new_version decision for the exact existing operation', async ({ page }) => {
const prefix = uniqueName('plan_version');
const targetOperationId = 'op_exact_importplan_target';
@@ -188,6 +188,44 @@ test('[P1] AC-1 preview renders source locations and stable finding codes for ca
await expect(row.locator('[data-testid="openapi-import-conflict-location"]')).toContainText('/operationId');
});
for (const locale of ['en', 'ru']) {
test(`[P0] AC-2.8-02 external reference denial gives safe guidance and stays blocked in ${locale}`, async ({ page }) => {
const prefix = uniqueName('preview_external_denied');
const sourceCanary = 'private-reference-message-canary';
const urlCanary = 'https://private.example.test/internal/openapi.yaml';
const operations = [candidate(prefix, 'blocked', {
status: 'blocked',
findings: [{
code: 'external_reference_disabled',
severity: 'error',
message: sourceCanary + ' ' + urlCanary,
operation_key: 'GET /' + prefix + '-blocked',
source_location: { pointer: '/paths/~1' + prefix + '-blocked/get/schema/$ref' },
}],
})];
const response = previewResponse(prefix, operations);
await routeOperationsEmpty(page);
await page.route('**/api/admin/workspaces/*/imports/openapi/preview', async (route) => {
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(response) });
});
await openImportModal(page, locale);
await uploadAndPreview(page, prefix, [[prefix + '-blocked', prefix + '_blocked']]);
const row = page.locator('.openapi-import-operation').first();
const selection = row.locator('[data-openapi-operation]');
await expect(selection).toBeDisabled();
await expect(row.locator('[data-testid="openapi-import-operation-readiness"]')).toHaveAttribute('data-state', 'blocked');
await expect(page.locator('[data-testid="openapi-import-blockers"]')).toContainText('external_reference_disabled');
await row.locator('.openapi-import-findings summary').click();
const finding = row.locator('.openapi-import-finding');
await expect(finding).toContainText('external_reference_disabled');
await expect(finding).toContainText(locale === 'en' ? /server allowlist/i : /список разрешённых адресов/i);
await expect(finding).toContainText(locale === 'en' ? /offline/i : /работы без сети/i);
await expect(finding).not.toContainText(sourceCanary);
await expect(finding).not.toContainText(urlCanary);
});
}
// AC-4: duplicate/invalid/taken names must show a deterministic rename
// proposal and conflict type, and the snapshot must stay unchanged.
test('[P1] AC-4 preview shows conflict type and deterministic rename proposal without mutating the snapshot', async ({ page }) => {
+229
View File
@@ -0,0 +1,229 @@
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);
}
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);
});