const { test, expect } = require('@playwright/test'); const { browserJson, getCurrentWorkspace, login, localized, uniqueName } = require('./helpers'); const operationKey = 'get:/protected'; const profileId = 'auth_profile_safe_bearer'; const secretCanary = 'SECRET_CANARY_do_not_render_or_store'; function securityPreview() { return { job_id: 'job_security_mapping_atdd', expires_at: '2099-01-01T00:00:00Z', preview: { source: { servers: ['https://api.example.test'] }, findings: [], groups: [{ title: 'protected operations', operations: [{ key: operationKey, method: 'GET', path: '/protected', suggested_name: 'protected_operation', suggested_display_name: 'Protected operation', input_fields: 0, output_fields: 0, draft: { input_mapping: { rules: [] }, output_mapping: { rules: [] } }, findings: [{ code: 'unsupported_security_scheme', severity: 'warning', message: 'Unsupported scheme details are intentionally opaque', construct_id: 'security_scheme_unsupported', location: { path: '/paths/~1protected/get/security' }, operation_key: operationKey, }], security_requirements: { source: 'document', alternatives: [ { schemes: ['bearerAuth'], supported: true, findings: [] }, { schemes: [], supported: true, findings: [] }, { schemes: ['oauthAuth', 'apiKeyAuth'], supported: false, findings: ['unsupported_security_and_requirement'] }, ], }, }], }], }, security_profile_choices: [ { operation_key: operationKey, alternative_index: 0, schemes: ['bearerAuth'], profiles: [{ id: profileId, name: 'Production bearer', kind: 'bearer' }], }, ], }; } function protectedOperation(key, suggestedName, alternatives) { return { key, method: 'GET', path: '/' + key.split('/').pop(), suggested_name: suggestedName, suggested_display_name: suggestedName, input_fields: 0, output_fields: 0, draft: { input_mapping: { rules: [] }, output_mapping: { rules: [] } }, findings: [], security_requirements: { source: 'document', alternatives }, }; } function previewWith(operations, choices) { return { job_id: 'job_security_multi_atdd', expires_at: '2099-01-01T00:00:00Z', preview: { source: { servers: ['https://api.example.test'] }, findings: [], groups: [{ title: 'protected operations', operations }], }, security_profile_choices: choices, }; } async function dismissOnboardingIfOpen(page) { // Same harness hygiene as openapi-import-plan.spec.js and operations.spec.js: // the overlay intercepts pointer events on a fresh E2E stack. await page.locator('#crank-onboarding-panel').waitFor({ state: 'attached' }); await page.locator('[data-testid="onboarding-dismiss"]').waitFor({ state: 'attached' }); await page.evaluate(() => { const dismiss = document.querySelector('[data-testid="onboarding-dismiss"]'); if (dismiss) dismiss.click(); }); await expect(page.locator('#crank-onboarding-panel')).toBeHidden(); } async function openSecurityPreview(page, locale = 'en', previewPayload = securityPreview()) { // Register the preview boundary before navigation so the upload is deterministic. await page.route('**/imports/openapi/preview', async (route) => { await route.fulfill({ contentType: 'application/json', body: JSON.stringify(previewPayload), }); }); await login(page); await dismissOnboardingIfOpen(page); await page.evaluate((language) => window.setLang(language), locale); await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click(); await page.locator('#openapi-import-file').setInputFiles({ name: 'security-mapping.yaml', mimeType: 'application/yaml', buffer: Buffer.from('openapi: 3.0.3\ninfo: { title: Security mapping, version: "1" }\npaths: {}\n'), }); await page.locator('#openapi-import-preview').click(); await expect(page.locator('#openapi-import-preview-panel')).toBeVisible(); } function actionablePlan(decision) { return { plan_reference: 'plan_security_mapping_atdd', plan_digest: 'c'.repeat(64), expires_at: '2099-01-01T00:00:00Z', selection_mode: 'full', counts: { selected: 1, excluded: 0, actionable: 1, blocked: 0 }, candidates: [{ key: operationKey, name: 'protected_operation', state: 'actionable', action: decision.action, target_operation_id: null, confirmed_name: null, auth_profile_id: decision.auth_profile_id || null, security_alternative_index: decision.security_alternative_index, reason: null, }], }; } function containsCredentialField(value) { if (!value || typeof value !== 'object') return false; return Object.entries(value).some(([key, nested]) => /^(password|access_token|refresh_token|secret_value|credential_value|raw_credentials?)$/i.test(key) || containsCredentialField(nested)); } test('[P1] AC-1 sends the selected OR alternative and Auth Profile, then renders API authority', async ({ page }) => { // Given an OpenAPI preview with OR security choices and safe workspace profile metadata const planRequests = []; await page.route('**/imports/openapi/*/plans', async (route) => { const payload = route.request().postDataJSON(); planRequests.push(payload); await route.fulfill({ contentType: 'application/json', body: JSON.stringify(actionablePlan(payload.decisions[0])) }); }); await openSecurityPreview(page); // When an administrator selects a supported alternative and its compatible profile await page.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0'); await page.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId); await page.locator('#openapi-import-create').click(); // Then the existing plan API receives only the typed profile reference and alternative index await expect.poll(() => planRequests.length).toBe(1); expect(planRequests[0].decisions[0]).toMatchObject({ operation_key: operationKey, auth_profile_id: profileId, security_alternative_index: 0, }); await expect(page.getByTestId('openapi-security-status')).toHaveText(localized('Resolved', 'Разрешено')); expect(JSON.stringify(planRequests[0])).not.toContain(secretCanary); expect(containsCredentialField(planRequests[0])).toBe(false); }); test('[P1] AC-2 replaces a prior resolved plan with a blocker after profile revalidation fails', async ({ page }) => { // Given an API-confirmed resolved plan for a profile that becomes unavailable before revalidation const planRequests = []; await page.route('**/imports/openapi/*/plans', async (route) => { const payload = route.request().postDataJSON(); planRequests.push(payload); if (planRequests.length === 1) { await route.fulfill({ contentType: 'application/json', body: JSON.stringify(actionablePlan(payload.decisions[0])) }); return; } await route.fulfill({ status: 422, contentType: 'application/json', body: JSON.stringify({ error: { code: 'import_plan_auth_unavailable', message: secretCanary } }), }); }); await openSecurityPreview(page); await page.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0'); await page.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId); // When the API first confirms the selection and then rejects the stale profile await page.locator('#openapi-import-create').click(); await expect(page.locator('#openapi-import-plan-confirmation')).toBeVisible(); await expect(page.getByTestId('openapi-security-status')).toHaveText(localized('Resolved', 'Разрешено')); await page.locator('#openapi-import-plan-back').click(); await page.locator('#openapi-import-create').click(); // Then the old resolved value is replaced by the exact API-authoritative blocker state await expect.poll(() => planRequests.length).toBe(2); await expect(page.getByTestId('openapi-security-status')).toHaveText(localized('Blocked', 'Заблокировано')); await expect(page.locator('body')).not.toContainText(secretCanary); expect(planRequests[0].decisions[0]).toMatchObject({ auth_profile_id: profileId, security_alternative_index: 0 }); }); test('[P1] AC-3 shows safe security guidance in RU and EN without exposing error or secret canaries', async ({ page }) => { // Given safe profile metadata and an unsupported AND alternative in the preview let previewCalls = 0; await page.route('**/imports/openapi/preview', async (route) => { previewCalls += 1; await route.fulfill({ contentType: 'application/json', body: JSON.stringify(securityPreview()) }); }); await page.route('**/imports/openapi/*/plans', async (route) => { await route.fulfill({ status: 422, contentType: 'application/json', body: JSON.stringify({ error: { code: 'import_plan_security_alternative_required', message: secretCanary } }), }); }); await login(page); await dismissOnboardingIfOpen(page); await page.evaluate(() => window.setLang('ru')); await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click(); await page.locator('#openapi-import-file').setInputFiles({ name: 'security-mapping.yaml', mimeType: 'application/yaml', buffer: Buffer.from('openapi: 3.0.3\ninfo: { title: Security mapping, version: "1" }\npaths: {}\n'), }); await page.locator('#openapi-import-preview').click(); await expect(page.locator('#openapi-import-preview-panel')).toBeVisible(); // When the administrator inspects both locales, the unsupported AND alternative is visible but disabled // Native option elements are not visually visible inside a select; the safe // metadata must be present and selectable. await expect(page.getByLabel(localized('Auth Profile', 'Профиль авторизации')).locator('option[value="' + profileId + '"]')).toBeAttached(); await expect(page.getByLabel(localized('Security alternative', 'Вариант безопасности')).locator('option[value="2"]')).toHaveAttribute('disabled', ''); await page.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0'); await page.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId); await page.locator('#openapi-import-create').click(); await expect(page.getByTestId('openapi-security-status')).toHaveText(localized('Blocked', 'Заблокировано')); await expect(page.locator('body')).not.toContainText(secretCanary); await page.evaluate(() => window.setLang('en')); await expect(page.locator('#openapi-import-retry')).toBeVisible(); await page.locator('#openapi-import-retry').click(); await expect.poll(() => previewCalls).toBe(2); await expect(page.locator('#openapi-import-preview-panel')).toBeVisible(); // A fresh preview resets the selection, so the operation is required again, // never a leftover unresolved/resolved binding from the rejected plan. await expect(page.getByTestId('openapi-security-status')).toHaveText( localized('Authentication required', 'Требуется аутентификация'), ); await expect(page.locator('body')).not.toContainText(secretCanary); const exposed = await page.evaluate(() => ({ html: document.documentElement.innerText, local: JSON.stringify(localStorage), session: JSON.stringify(sessionStorage), })); expect(JSON.stringify(exposed)).not.toContain(secretCanary); }); /* ── Mandatory matrix branches (green phase) ─────────────────────────── */ test('[P1] anonymous alternative submits only the OR index, never an unrequested profile', async ({ page }) => { const planRequests = []; await page.route('**/imports/openapi/*/plans', async (route) => { const payload = route.request().postDataJSON(); planRequests.push(payload); const decision = payload.decisions[0]; await route.fulfill({ contentType: 'application/json', body: JSON.stringify(actionablePlan({ action: decision.action, auth_profile_id: decision.auth_profile_id || null, security_alternative_index: decision.security_alternative_index === undefined ? null : decision.security_alternative_index, })), }); }); await openSecurityPreview(page, 'en'); // The anonymous (empty-scheme) alternative is selectable; selecting it must // keep the profile unbound. const alternative = page.getByLabel(localized('Security alternative', 'Вариант безопасности')); await alternative.selectOption('1'); // The anonymous alternative must not offer any Auth Profile control. await expect(page.getByLabel(localized('Auth Profile', 'Профиль авторизации'))).toHaveCount(0); await page.locator('#openapi-import-create').click(); await expect.poll(() => planRequests.length).toBe(1); const decision = planRequests[0].decisions[0]; expect(decision).toMatchObject({ operation_key: operationKey, security_alternative_index: 1 }); expect(decision).not.toHaveProperty('auth_profile_id'); // A confirmed anonymous alternative is no-auth, never a resolved auth binding. await expect(page.locator('[data-openapi-security-op-status="' + operationKey + '"]')).toHaveText('No authentication'); await expect(page.getByTestId('openapi-security-status')).toHaveText(localized('No authentication', 'Без аутентификации')); expect(JSON.stringify(planRequests[0])).not.toContain(profileId); }); test('[P1] changing the alternative clears the profile and invalidates a prior plan', async ({ page }) => { const planRequests = []; await page.route('**/imports/openapi/*/plans', async (route) => { const payload = route.request().postDataJSON(); planRequests.push(payload); const decision = payload.decisions[0]; await route.fulfill({ contentType: 'application/json', body: JSON.stringify(actionablePlan({ action: decision.action, auth_profile_id: decision.auth_profile_id || null, security_alternative_index: decision.security_alternative_index === undefined ? null : decision.security_alternative_index, })), }); }); await openSecurityPreview(page, 'en'); const alternative = page.getByLabel(localized('Security alternative', 'Вариант безопасности')); const profile = page.getByLabel(localized('Auth Profile', 'Профиль авторизации')); await alternative.selectOption('0'); await profile.selectOption(profileId); // A confirmed plan exists for (alternative 0, profile). await page.locator('#openapi-import-create').click(); await expect(page.locator('#openapi-import-plan-confirmation')).toBeVisible(); await expect(page.getByTestId('openapi-security-status')).toHaveText('Resolved'); // Back to editing: the selection survives, the plan does not. await page.locator('#openapi-import-plan-back').click(); await expect(page.locator('#openapi-import-plan-confirmation')).toBeHidden(); await expect(page.getByTestId('openapi-security-status')).toHaveText('Unresolved'); // Switching the alternative drops the bound profile; the anonymous choice // hides the profile control entirely and the new plan carries only the index. await alternative.selectOption('1'); await expect(profile).toHaveCount(0); await page.locator('#openapi-import-create').click(); await expect.poll(() => planRequests.length).toBe(2); const decision = planRequests[1].decisions[0]; expect(decision).toMatchObject({ operation_key: operationKey, security_alternative_index: 1 }); expect(decision).not.toHaveProperty('auth_profile_id'); await expect(page.locator('[data-openapi-security-op-status="' + operationKey + '"]')).toHaveText('No authentication'); await expect(page.getByTestId('openapi-security-status')).toHaveText(localized('No authentication', 'Без аутентификации')); }); test('[P1] empty compatible-profile list keeps the selection safe and the API blocker authoritative', async ({ page }) => { const emptyPreview = securityPreview(); emptyPreview.security_profile_choices = []; const planRequests = []; await page.route('**/imports/openapi/*/plans', async (route) => { planRequests.push(route.request().postDataJSON()); // Actual public contract: a 200 plan whose candidate is blocked with the // safe reason the API owns, not a synthesized top-level error code. await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ plan_reference: 'plan_empty_profiles_atdd', plan_digest: 'f'.repeat(64), expires_at: '2099-01-01T00:00:00Z', selection_mode: 'full', counts: { selected: 1, excluded: 0, actionable: 0, blocked: 1 }, candidates: [{ key: operationKey, name: 'protected_operation', state: 'blocked', action: 'create', target_operation_id: null, confirmed_name: null, auth_profile_id: null, security_alternative_index: 0, reason: 'auth_profile_required', }], }), }); }); await openSecurityPreview(page, 'en', emptyPreview); // The empty compatible-profile list disables the profile control and shows // safe localized guidance instead of offering an arbitrary error payload. const alternative = page.getByLabel(localized('Security alternative', 'Вариант безопасности')); const profileSelect = page.getByLabel(localized('Auth Profile', 'Профиль авторизации')); await expect(profileSelect.locator('option')).toHaveCount(1); await alternative.selectOption('0'); await expect(profileSelect).toBeDisabled(); await expect(page.locator('.openapi-import-security-guidance')).toHaveText( 'No compatible Auth Profiles for the selected alternative. Choose another alternative or create a plan to revalidate.'); await page.locator('#openapi-import-create').click(); await expect.poll(() => planRequests.length).toBe(1); expect(planRequests[0].decisions[0]).toMatchObject({ operation_key: operationKey, security_alternative_index: 0, }); expect(planRequests[0].decisions[0]).not.toHaveProperty('auth_profile_id'); // The API candidate is authoritative: blocked, with safe translated guidance. await expect(page.locator('.openapi-import-security-op-status')).toHaveText('Blocked'); await expect(page.getByTestId('openapi-security-status')).toHaveText('Blocked'); await expect(page.locator('.openapi-import-plan-reason')).toHaveText( 'This operation requires an Auth Profile. Choose a compatible profile and create a new plan.'); await expect(page.locator('#openapi-import-plan-confirmation')).toBeVisible(); }); test('[P2] security controls keep accessible names, keyboard focus and a live status', async ({ page }) => { await openSecurityPreview(page, 'en'); const alternative = page.getByLabel(localized('Security alternative', 'Вариант безопасности')); const profile = page.getByLabel(localized('Auth Profile', 'Профиль авторизации')); await expect(alternative).toBeEditable(); await expect(profile).toBeEditable(); // Keyboard-only selection: focus the native select and change it with keys, // never programmatically. await alternative.focus(); expect(await alternative.evaluate((el) => el === document.activeElement)).toBe(true); await alternative.press('ArrowDown'); await expect(alternative).toHaveValue('0'); await profile.focus(); expect(await profile.evaluate((el) => el === document.activeElement)).toBe(true); await profile.press('ArrowDown'); await expect(profile).toHaveValue(profileId); const status = page.getByTestId('openapi-security-status'); await expect(status).toHaveAttribute('role', 'status'); await expect(status).toHaveAttribute('aria-live', 'polite'); const opStatus = page.locator('.openapi-import-security-op-status'); await expect(opStatus).toHaveAttribute('role', 'status'); await expect(opStatus).toHaveAttribute('aria-live', 'polite'); await page.locator('body').press('Escape'); await expect(page.locator('#openapi-import-modal')).toBeHidden(); }); test('[P1] a delayed preview response cannot restore state after the user cancelled', async ({ page }) => { let releasePreview; const previewReleased = new Promise((resolve) => { releasePreview = resolve; }); let previewFulfilled = false; await page.route('**/imports/openapi/preview', async (route) => { await previewReleased; await route.fulfill({ contentType: 'application/json', body: JSON.stringify(securityPreview()), }); previewFulfilled = true; }); await login(page); await dismissOnboardingIfOpen(page); await page.evaluate(() => window.setLang('en')); await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click(); await page.locator('#openapi-import-file').setInputFiles({ name: 'security-mapping.yaml', mimeType: 'application/yaml', buffer: Buffer.from('openapi: 3.0.3\ninfo: { title: Security mapping, version: "1" }\npaths: {}\n'), }); const previewRequest = page.waitForRequest((request) => request.method() === 'POST' && request.url().includes('/imports/openapi/preview')); await page.locator('#openapi-import-preview').click(); await previewRequest; await page.locator('#openapi-import-cancel').click(); // Release the stale response and wait for the handler to settle instead of a // fixed timeout, then prove it could not restore the panel. releasePreview(); await expect.poll(() => previewFulfilled).toBe(true); await expect(page.locator('#openapi-import-preview-panel')).toBeHidden(); await expect(page.locator('#openapi-import-cancel')).toBeHidden(); }); /* ── Per-operation authority and selection lifecycle ────────────────── */ test('[P1] offers only profiles compatible with the chosen OR alternative and hides them for anonymous', async ({ page }) => { const key = 'get:/multi'; await openSecurityPreview(page, 'en', previewWith([ protectedOperation(key, 'multi_operation', [ { schemes: ['bearerAuth'], supported: true, findings: [] }, { schemes: ['basicAuth'], supported: true, findings: [] }, { schemes: [], supported: true, findings: [] }, { schemes: ['oauthAuth'], supported: false, findings: ['unsupported_security_and_requirement'] }, ]), ], [ { operation_key: key, alternative_index: 0, schemes: ['bearerAuth'], profiles: [{ id: 'prof_bearer', name: 'Bearer profile', kind: 'bearer' }] }, { operation_key: key, alternative_index: 1, schemes: ['basicAuth'], profiles: [{ id: 'prof_basic', name: 'Basic profile', kind: 'basic' }] }, ])); const row = page.locator('.openapi-import-operation').filter({ hasText: 'multi_operation' }); const alternative = row.getByLabel(localized('Security alternative', 'Вариант безопасности')); const profile = row.getByLabel(localized('Auth Profile', 'Профиль авторизации')); // Profile-first selection may offer the safe union while no alternative is chosen. await expect(profile.locator('option[value="prof_bearer"]')).toBeAttached(); await expect(profile.locator('option[value="prof_basic"]')).toBeAttached(); await expect(alternative.locator('option[value="3"]')).toHaveAttribute('disabled', ''); await alternative.selectOption('0'); await expect(profile.locator('option[value="prof_bearer"]')).toBeAttached(); await expect(profile.locator('option[value="prof_basic"]')).toHaveCount(0); await alternative.selectOption('1'); await expect(profile.locator('option[value="prof_basic"]')).toBeAttached(); await expect(profile.locator('option[value="prof_bearer"]')).toHaveCount(0); // An anonymous alternative must offer no profile control at all. await alternative.selectOption('2'); await expect(row.locator('.openapi-import-security-controls select')).toHaveCount(1); await expect(row.getByLabel(localized('Auth Profile', 'Профиль авторизации'))).toHaveCount(0); }); test('[P1] reports per-operation resolved and blocked authority for a mixed plan', async ({ page }) => { const keyA = 'get:/alpha'; const keyB = 'get:/beta'; await page.route('**/imports/openapi/*/plans', async (route) => { await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ plan_reference: 'plan_multi_mixed_atdd', plan_digest: 'd'.repeat(64), expires_at: '2099-01-01T00:00:00Z', selection_mode: 'full', counts: { selected: 2, excluded: 0, actionable: 1, blocked: 1 }, candidates: [ { key: keyA, name: 'alpha_operation', state: 'actionable', action: 'create', auth_profile_id: 'prof_a', security_alternative_index: 0, reason: null }, { key: keyB, name: 'beta_operation', state: 'blocked', action: 'create', auth_profile_id: 'prof_b', security_alternative_index: 0, reason: 'auth_profile_required' }, ], }), }); }); await openSecurityPreview(page, 'en', previewWith([ protectedOperation(keyA, 'alpha_operation', [{ schemes: ['bearerAuth'], supported: true, findings: [] }]), protectedOperation(keyB, 'beta_operation', [{ schemes: ['bearerAuth'], supported: true, findings: [] }]), ], [ { operation_key: keyA, alternative_index: 0, schemes: ['bearerAuth'], profiles: [{ id: 'prof_a', name: 'A profile', kind: 'bearer' }] }, { operation_key: keyB, alternative_index: 0, schemes: ['bearerAuth'], profiles: [{ id: 'prof_b', name: 'B profile', kind: 'bearer' }] }, ])); // Before the plan both protected operations require an explicit binding. await expect(page.getByTestId('openapi-security-status')).toHaveText('Authentication required'); const rowA = page.locator('.openapi-import-operation').filter({ hasText: 'alpha_operation' }); const rowB = page.locator('.openapi-import-operation').filter({ hasText: 'beta_operation' }); await rowA.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0'); await rowA.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption('prof_a'); await rowB.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0'); await rowB.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption('prof_b'); await page.locator('#openapi-import-create').click(); await expect(page.locator('#openapi-import-plan-confirmation')).toBeVisible(); await expect(page.locator('[data-openapi-security-op-status="' + keyA + '"]')).toHaveText('Resolved'); await expect(page.locator('[data-openapi-security-op-status="' + keyB + '"]')).toHaveText('Blocked'); // The summary must surface the blocked operation, not mask it behind a resolved one. await expect(page.getByTestId('openapi-security-status')).toHaveText('Blocked'); }); test('[P1] editing the alternative after an authoritative blocker clears the blocked authority', async ({ page }) => { const key = 'get:/reset'; await page.route('**/imports/openapi/*/plans', async (route) => { await route.fulfill({ status: 422, contentType: 'application/json', body: JSON.stringify({ error: { code: 'import_plan_auth_unavailable', message: secretCanary } }), }); }); await openSecurityPreview(page, 'en', previewWith([ protectedOperation(key, 'reset_operation', [ { schemes: ['bearerAuth'], supported: true, findings: [] }, { schemes: ['basicAuth'], supported: true, findings: [] }, ]), ], [ { operation_key: key, alternative_index: 0, schemes: ['bearerAuth'], profiles: [{ id: 'prof_bearer', name: 'Bearer profile', kind: 'bearer' }] }, { operation_key: key, alternative_index: 1, schemes: ['basicAuth'], profiles: [{ id: 'prof_basic', name: 'Basic profile', kind: 'basic' }] }, ])); const row = page.locator('.openapi-import-operation').filter({ hasText: 'reset_operation' }); await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0'); await row.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption('prof_bearer'); await page.locator('#openapi-import-create').click(); await expect(page.locator('[data-openapi-security-op-status="' + key + '"]')).toHaveText('Blocked'); await expect(page.getByTestId('openapi-security-status')).toHaveText('Blocked'); // Editing must void the blocked authority and clear the bound profile. await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('1'); await expect(row.getByLabel(localized('Auth Profile', 'Профиль авторизации'))).toHaveValue(''); await expect(page.locator('[data-openapi-security-op-status="' + key + '"]')).toHaveText('Authentication required'); await expect(page.getByTestId('openapi-security-status')).toHaveText('Authentication required'); await expect(page.locator('body')).not.toContainText(secretCanary); }); test('[P1] binding then choosing skip removes the auth fields from the plan payload', async ({ page }) => { const suggestedName = 'protected_operation'; const planRequests = []; await page.route('**/api/admin/workspaces/*/operations', async (route) => { await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ items: [{ id: 'op_skip_target', name: suggestedName, protocol: 'rest', status: 'draft' }], page: 1, page_size: 1, total: 1, }), }); }); await page.route('**/imports/openapi/*/plans', async (route) => { planRequests.push(route.request().postDataJSON()); await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ plan_reference: 'plan_skip_atdd', plan_digest: 'e'.repeat(64), expires_at: '2099-01-01T00:00:00Z', selection_mode: 'full', counts: { selected: 1, excluded: 0, actionable: 0, blocked: 0 }, candidates: [{ key: operationKey, name: suggestedName, state: 'excluded', action: 'skip', target_operation_id: 'op_skip_target', confirmed_name: null, auth_profile_id: null, security_alternative_index: null, reason: 'skipped', }], }), }); }); await openSecurityPreview(page, 'en'); const row = page.locator('.openapi-import-operation').filter({ hasText: suggestedName }); await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0'); await row.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId); await row.locator('[data-openapi-decision-action]').selectOption('skip'); await expect(row.locator('.openapi-import-security-controls')).toHaveCount(0); await page.locator('#openapi-import-create').click(); await expect.poll(() => planRequests.length).toBe(1); const decision = planRequests[0].decisions[0]; expect(decision).toMatchObject({ operation_key: operationKey, action: 'skip', target_operation_id: 'op_skip_target' }); expect(decision).not.toHaveProperty('auth_profile_id'); expect(decision).not.toHaveProperty('security_alternative_index'); }); test('[P1] language change during a pending Apply keeps security controls disabled', async ({ page }) => { let releaseApply; const applyHeld = new Promise((resolve) => { releaseApply = resolve; }); await page.route('**/imports/openapi/*/plans', async (route) => { const payload = route.request().postDataJSON(); await route.fulfill({ contentType: 'application/json', body: JSON.stringify(actionablePlan(payload.decisions[0])) }); }); await page.route('**/imports/openapi/*/apply', async (route) => { await applyHeld; try { await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ plan_digest: 'c'.repeat(64), counts: { created: 1 }, outcomes: [{ key: operationKey, name: 'protected_operation', status: 'created' }], }), }); } catch (_error) { // The context change aborts the request; it must not update the modal. } }); await openSecurityPreview(page, 'en'); const row = page.locator('.openapi-import-operation').filter({ hasText: 'protected_operation' }); const alternative = row.getByLabel(localized('Security alternative', 'Вариант безопасности')); const profile = row.getByLabel(localized('Auth Profile', 'Профиль авторизации')); await alternative.selectOption('0'); await profile.selectOption(profileId); await page.locator('#openapi-import-create').click(); await expect(page.getByTestId('openapi-security-status')).toHaveText('Resolved'); await page.locator('#openapi-import-plan-apply').click(); await expect(alternative).toBeDisabled(); // A language change while Apply is in flight must not re-render and re-enable // the security controls. await page.evaluate(() => window.setLang('ru')); await expect(alternative).toBeDisabled(); await expect(profile).toBeDisabled(); await expect(page.locator('#openapi-import-file-select')).toBeDisabled(); releaseApply(); }); test('[P1] a rejected Apply clears a previously resolved security authority', async ({ page }) => { await page.route('**/imports/openapi/*/plans', async (route) => { const payload = route.request().postDataJSON(); await route.fulfill({ contentType: 'application/json', body: JSON.stringify(actionablePlan(payload.decisions[0])) }); }); await page.route('**/imports/openapi/*/apply', async (route) => { await route.fulfill({ status: 422, contentType: 'application/json', body: JSON.stringify({ error: { code: 'import_plan_auth_unavailable', message: secretCanary }, recovery: 'repreview_required' }), }); }); await openSecurityPreview(page, 'en'); const row = page.locator('.openapi-import-operation').filter({ hasText: 'protected_operation' }); await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0'); await row.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId); await page.locator('#openapi-import-create').click(); await expect(page.getByTestId('openapi-security-status')).toHaveText('Resolved'); await page.locator('#openapi-import-plan-apply').click(); // The rejected Apply must not retain the prior resolved authority. await expect(page.getByTestId('openapi-security-status')).toHaveText('Unresolved'); await expect(page.locator('body')).not.toContainText(secretCanary); }); test('[P1] a delayed plan response cannot restore authority after cancel', async ({ page }) => { let releasePlan; const planHeld = new Promise((resolve) => { releasePlan = resolve; }); let planFulfilled = false; await page.route('**/imports/openapi/*/plans', async (route) => { await planHeld; await route.fulfill({ contentType: 'application/json', body: JSON.stringify(actionablePlan({ action: 'create', auth_profile_id: profileId, security_alternative_index: 0 })), }); planFulfilled = true; }); await openSecurityPreview(page, 'en'); const row = page.locator('.openapi-import-operation').filter({ hasText: 'protected_operation' }); await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0'); await row.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId); const planRequest = page.waitForRequest((request) => request.method() === 'POST' && /\/imports\/openapi\/[^/]+\/plans$/.test(request.url())); await page.locator('#openapi-import-create').click(); await planRequest; await page.locator('#openapi-import-cancel').click(); releasePlan(); await expect.poll(() => planFulfilled).toBe(true); await expect(page.locator('#openapi-import-plan-confirmation')).toBeHidden(); await expect(page.getByTestId('openapi-security-status')).toHaveText('Unresolved'); }); test('[P1] a quoted or backslash operation key cannot break per-operation status', async ({ page }) => { const key = 'get:/quoted"path\\segment'; const planRequests = []; await page.route('**/imports/openapi/*/plans', async (route) => { planRequests.push(route.request().postDataJSON()); await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ plan_reference: 'plan_quoted_key_atdd', plan_digest: 'a'.repeat(64), expires_at: '2099-01-01T00:00:00Z', selection_mode: 'full', counts: { selected: 1, excluded: 0, actionable: 1, blocked: 0 }, candidates: [{ key, name: 'quoted_operation', state: 'actionable', action: 'create', target_operation_id: null, confirmed_name: null, auth_profile_id: profileId, security_alternative_index: 0, reason: null, }], }), }); }); await openSecurityPreview(page, 'en', previewWith([ protectedOperation(key, 'quoted_operation', [{ schemes: ['bearerAuth'], supported: true, findings: [] }]), ], [ { operation_key: key, alternative_index: 0, schemes: ['bearerAuth'], profiles: [{ id: profileId, name: 'Bearer profile', kind: 'bearer' }] }, ])); // Rendering a CSS-hostile key must not throw and the preview must render. await expect(page.locator('#openapi-import-preview-panel')).toBeVisible(); const row = page.locator('.openapi-import-operation').filter({ hasText: 'quoted_operation' }); await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0'); await row.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId); await page.locator('#openapi-import-create').click(); await expect.poll(() => planRequests.length).toBe(1); expect(planRequests[0].decisions[0].operation_key).toBe(key); // Status is matched by dataset value, never by interpolating the key into CSS. await expect(row.locator('.openapi-import-security-op-status')).toHaveText('Resolved'); await expect(page.getByTestId('openapi-security-status')).toHaveText('Resolved'); }); test('[P1] localizes unsupported findings and empty-profile guidance in RU and EN', async ({ page }) => { const key = 'get:/locale'; await openSecurityPreview(page, 'ru', previewWith([ protectedOperation(key, 'locale_operation', [ { schemes: ['bearerAuth'], supported: true, findings: [] }, { schemes: ['oauthAuth', 'apiKeyAuth'], supported: false, findings: ['unsupported_security_and_requirement'] }, ]), ], [])); const row = page.locator('.openapi-import-operation').filter({ hasText: 'locale_operation' }); const alternative = row.getByLabel(localized('Security alternative', 'Вариант безопасности')); const profile = row.getByLabel(localized('Auth Profile', 'Профиль авторизации')); // RU: exact unsupported finding copy and empty-profile guidance. await expect(row.locator('.openapi-import-security-findings')).toContainText( 'Это security requirement невозможно выполнить со схемой, поддержанной Crank, или доступным профилем авторизации.'); await alternative.selectOption('0'); await expect(profile).toBeDisabled(); await expect(row.locator('.openapi-import-security-guidance')).toHaveText( 'Для выбранного варианта нет совместимых профилей авторизации. Выберите другой вариант или создайте план для повторной проверки.'); const opStatus = row.locator('.openapi-import-security-op-status'); await expect(opStatus).toHaveAttribute('role', 'status'); await expect(opStatus).toHaveAttribute('aria-live', 'polite'); // EN: switching language invalidates an unconfirmed preview, so re-preview // and assert the exact translated copy in the second locale. await page.evaluate(() => window.setLang('en')); await page.locator('#openapi-import-preview').click(); await expect(page.locator('#openapi-import-preview-panel')).toBeVisible(); await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0'); await expect(row.locator('.openapi-import-security-findings')).toContainText( 'This security requirement cannot be satisfied with a supported scheme or an available Auth Profile.'); await expect(row.getByLabel(localized('Auth Profile', 'Профиль авторизации'))).toBeDisabled(); await expect(row.locator('.openapi-import-security-guidance')).toHaveText( 'No compatible Auth Profiles for the selected alternative. Choose another alternative or create a plan to revalidate.'); }); test('[P1] a stale security plan cannot restore authority after a language or workspace change', async ({ page }) => { const releases = []; let planReleased = 0; await page.route('**/imports/openapi/*/plans', async (route) => { await new Promise((resolve) => releases.push(resolve)); planReleased += 1; try { await route.fulfill({ contentType: 'application/json', body: JSON.stringify(actionablePlan({ action: 'create', auth_profile_id: profileId, security_alternative_index: 0 })), }); } catch (_error) { // The context change aborts the request; it must not update the modal. } }); await openSecurityPreview(page, 'en'); async function bindSelection() { const row = page.locator('.openapi-import-operation').filter({ hasText: 'protected_operation' }); await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0'); await row.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId); } async function startPlan() { const request = page.waitForRequest((r) => r.method() === 'POST' && /\/imports\/openapi\/[^/]+\/plans$/.test(r.url())); await page.locator('#openapi-import-create').click(); await request; await expect.poll(() => releases.length).toBeGreaterThanOrEqual(1); } // 1) Language change while a security plan is pending. await bindSelection(); await startPlan(); await page.evaluate(() => window.setLang('ru')); releases.shift()(); await expect.poll(() => planReleased).toBeGreaterThanOrEqual(1); await expect(page.getByTestId('openapi-security-status')).toHaveText('Не разрешено'); await expect(page.locator('.openapi-import-security-controls')).toHaveCount(0); // 2) Workspace change while a security plan is pending. await page.locator('#openapi-import-preview').click(); await expect(page.locator('#openapi-import-preview-panel')).toBeVisible(); await bindSelection(); await startPlan(); await page.evaluate(() => { window.dispatchEvent(new CustomEvent('crank:workspacechange', { detail: { id: 'ws-stale-security' } })); }); releases.shift()(); await expect.poll(() => planReleased).toBeGreaterThanOrEqual(2); await expect(page.getByTestId('openapi-security-status')).toHaveText('Не разрешено'); await expect(page.locator('.openapi-import-security-controls')).toHaveCount(0); await expect(page.locator('#openapi-import-preview-panel')).toBeHidden(); }); /* ── Real API evidence ───────────────────────────────────────────────── */ test('[P1][api] real preview/plan round-trip resolves a typed reference (real secret + bearer profile)', async ({ page }) => { await login(page); await dismissOnboardingIfOpen(page); await page.evaluate(() => window.setLang('en')); const workspace = await getCurrentWorkspace(page); const prefix = uniqueName('secmap'); const secretValue = 'secmap-bearer-' + prefix; const secret = await browserJson( page, 'POST', `/api/admin/workspaces/${encodeURIComponent(workspace.id)}/secrets`, { name: prefix + '_secret', kind: 'token', value: secretValue }, ); let profile = null; try { profile = await browserJson( page, 'POST', `/api/admin/workspaces/${encodeURIComponent(workspace.id)}/auth-profiles`, { name: prefix + '_profile', kind: 'bearer', config: { bearer: { header_name: 'Authorization', secret_id: secret.id } }, }, ); expect(String(profile.id)).toMatch(/^auth_/); await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click(); await page.locator('#openapi-import-file').setInputFiles({ name: 'security-mapping-real.yaml', mimeType: 'application/yaml', buffer: Buffer.from([ 'openapi: 3.0.3', 'info: { title: Security mapping real, version: "1" }', 'servers: [{ url: "https://api.example.test" }]', 'paths:', ' /' + prefix + ':', ' get:', ' operationId: ' + prefix + '_operation', ' security:', ' - bearerAuth: []', ' - {}', ' responses:', ' \'200\': { description: OK }', 'components:', ' securitySchemes:', ' bearerAuth: { type: http, scheme: bearer }', ].join('\n')), }); await page.locator('#openapi-import-preview').click(); await expect(page.locator('#openapi-import-preview-panel')).toBeVisible(); const alternative = page.getByLabel(localized('Security alternative', 'Вариант безопасности')); const profileSelect = page.getByLabel(localized('Auth Profile', 'Профиль авторизации')); const bearerOption = alternative.locator('option', { hasText: 'bearerAuth' }); await bearerOption.waitFor({ state: 'attached' }); const bearerIndex = await bearerOption.getAttribute('value'); expect(bearerIndex).toMatch(/^\d+$/); // option value, not the select's current value await alternative.selectOption(bearerIndex); const realProfileOption = profileSelect.locator('option[value="' + profile.id + '"]'); await expect(realProfileOption).toBeAttached(); await profileSelect.selectOption(profile.id); const planRequest = page.waitForRequest((request) => request.method() === 'POST' && /\/imports\/openapi\/[^/]+\/plans$/.test(request.url()), ); await page.locator('#openapi-import-create').click(); const sent = await planRequest; const response = await sent.response(); // Happy path is deterministic: the created profile matches the bearer // scheme, so the real API must accept the typed reference. expect(response.status()).toBe(200); const payload = await sent.postDataJSON(); const planDecision = (payload.decisions || [])[0]; expect(planDecision).toMatchObject({ auth_profile_id: profile.id, security_alternative_index: Number(bearerIndex) }); await expect(page.locator('#openapi-import-plan-confirmation')).toBeVisible(); await expect(page.getByTestId('openapi-security-status')).toHaveText('Resolved'); await expect(page.locator('body')).not.toContainText(secretValue); } finally { // Best-effort cleanup. The Secret is guarded (409) while the live profile // references it; the referenced Auth Profile has no delete endpoint, so we // only attempt to release the Secret and never widen the backend surface. try { await browserJson( page, 'DELETE', `/api/admin/workspaces/${encodeURIComponent(workspace.id)}/secrets/${encodeURIComponent(secret.id)}`, [], [404, 409], ); } catch (_error) {} } });