diff --git a/_bmad-output/implementation-artifacts/spec-2-11-security-mapping-ui.md b/_bmad-output/implementation-artifacts/spec-2-11-security-mapping-ui.md new file mode 100644 index 0000000..197fbc2 --- /dev/null +++ b/_bmad-output/implementation-artifacts/spec-2-11-security-mapping-ui.md @@ -0,0 +1,143 @@ +--- +title: '2.11 — Выбирать security mappings в OpenAPI UI' +type: feature +created: '2026-10-03' +status: done +baseline_revision: b18a84b2c5a70b150d8c6a0749478bd13753308b +review_loop_iteration: 0 +followup_review_recommended: false +context: + - _bmad-output/implementation-artifacts/epic-2-context.md +warnings: [oversized] +deferred: [] +--- + + + +## Intent + +**Problem:** OpenAPI UI игнорирует security requirements и safe profile choices API Story 2.10, поэтому администратор не может разрешить authentication перед созданием ImportPlan. + +**Approach:** Показать effective OR alternatives, выбрать совместимый workspace Auth Profile и передать typed reference в существующий plan API. Показывать authoritative результат проверки и безопасные RU/EN состояния. + +## Boundaries & Constraints + +**Always:** Выполнить три AC Story 2.11 через пользовательский UI. API остаётся authority для OR/AND, compatibility, workspace isolation, доступности Secrets и redaction. Использовать только preview security_profile_choices с метаданными id/name/kind. Сохранять abort/controller/revision guards, keyboard labels, visible focus и screen-reader status. Для unavailable binding использовать существующее определение Story 2.10: отсутствующий профиль либо недоступный необходимый Secret; отдельный lifecycle профиля не вводить. + +**Never:** Вводить или загружать raw credentials в mapping state; вычислять resolved по локальному выбору без ответа API; менять backend security semantics; реализовывать соседние Stories 2.12–2.15. sprint-status.yaml не записывать и не откатывать независимо от его статуса. + +## I/O & Edge-Case Matrix + +| Scenario | Input / State | Expected Output / Behavior | Error Handling | +|----------|---------------|---------------------------|----------------| +| Required OR | Поддерживаемые alternatives и safe workspace profiles | Явный выбор alternative/profile; plan decisions несут только index/id; resolved приходит из актуального API ответа | До ответа unresolved/revalidation | +| Anonymous / no-auth | Empty alternative либо отсутствие requirement | Явное отсутствие обязательного profile; no-auth выбор сохраняет index без profile | Не добавлять несовместимый binding | +| Unsupported AND/OAuth | Unsupported alternative и findings | Видимые blocker/manual guidance, без автоматического выбора иной OR alternative | Нельзя объявить resolved | +| Empty / unavailable | Нет compatible profiles либо API отклоняет выбранный profile | Safe empty/blocker guidance и повторная проверка, прежний resolved снят | Не показывать произвольные error payload/credentials | +| Selection changed | Смена alternative/profile после проверки | Старые plan/resolved немедленно недействительны; profile очищается при смене alternative | Новый ответ проверяет текущий выбор | +| Stale context | Задержанный preview/plan после replacement, workspace/language change или закрытия | Ответ не меняет current mapping/authority | Abort плюс identity/revision guards | +| RU/EN and safety | Loading/error/empty/resolved/blocker | Переведённые labels/status/findings; safe textContent, keyboard controls; нет secret canaries в DOM/payload/storage | Без raw error details | + + + +## Code Map + +- `apps/ui/js/openapi-import.js` — IIFE state, decisionFor, renderDecisionControls, renderPreview, clearPreview/invalidate, createImportPlan, renderImportPlan, submitApply и context guards. Currently security fields отсутствуют. Payload decisions пропускает create; security binding требует включить такие decisions. Для skip security fields запрещены. +- `apps/ui/js/api.js:412` — previewOpenApiImport/createOpenApiImportPlan/applyOpenApiImportPlan уже принимают payload и signal; read-only reuse, новый endpoint не нужен. +- `apps/admin-api/src/dto.rs:544` — preview response имеет security_profile_choices [{operation_key,alternative_index,schemes,profiles:[{id,name,kind}]}]. Plan decision имеет auth_profile_id/security_alternative_index; candidate state actionable/blocked/excluded и reason. Read-only contract. +- `apps/admin-api/src/service/imports.rs:249` — choices только для supported single-scheme с доступными Secrets. `imports/import_plan.rs::resolve_security_binding` — authoritative validation, auth_profile_required blocker, unavailable/incompatible errors. Read-only. +- `crates/crank-import/src/rest/model.rs` — requirements {source,alternatives:[{schemes,supported,findings}]}; OR между alternatives, AND внутри schemes, empty alternative anonymous. Read-only. +- `apps/ui/js/i18n.js` — TRANSLATIONS en/ru и openapi.*; findingMessage использует safe whitelist/fallback. +- `apps/ui/css/openapi-import.css` — decision controls/finding/plan styles; reuse. +- `apps/ui/tests/e2e/openapi-import-plan.spec.js` — существующий mock plan browser harness. `apps/ui/tests/e2e/operations.spec.js`, `apps/ui/scripts/playwright-stack.sh` — real API upload/preview/plan/apply и lifecycle stack. +- `docs/openapi-import.md:16` — устаревшее утверждение о недоступности mapping UI. + +## Tasks & Acceptance + +**Execution:** +- [x] `apps/ui/tests/e2e/openapi-security-mapping.spec.js`, `_bmad-output/test-artifacts/atdd-checklist-2-11-security-mapping-ui.md` — ATDD сценарии каждой строки матрицы и трёх AC; reuse harness, actual RED/GREEN, real API evidence для ключевого выбора. +- [x] `apps/ui/js/openapi-import.js` — читать safe choices; operation controls и mapping state; index/id в decisions create/rename/new_version, без security fields у skip; API-authoritative status, invalidate и recovery. +- [x] `apps/ui/js/i18n.js`, `apps/ui/css/openapi-import.css` — RU/EN labels, status, safe findings/error guidance и доступные controls в existing conventions. +- [x] `docs/openapi-import.md` — описать реализованный mapping flow, ограничения и revalidation без обещаний будущей qualification. + +**Acceptance Criteria:** +- Given preview сохраняет OR alternatives и required authentication, when администратор выбирает alternative либо совместимый Auth Profile текущего workspace, then UI передаёт выбор существующему import API и показывает authoritative resolved/unresolved/blocker status; raw credentials не вводятся в mapping state и не копируются в IR/plan. +- Given смена alternative, удалённый/недоступный profile либо stale preview response, when API повторно валидирует binding, then UI показывает safe blocker/revalidation guidance и не выдаёт предыдущий resolved state за текущий; OR/AND semantics, workspace validation и redaction остаются в API Story 2.10. +- Given security-mapping UI на RU и EN, when пользователь выбирает profile, меняет alternative или получает unsupported scheme, then UI показывает required/unresolved/resolved status, safe profile metadata и blocker findings; loading, empty, error и stale-response states не раскрывают secrets. + +## Spec Change Log + +## Review Triage Log + +### 2026-10-03 — Review pass +- verdicts: 19 findings — high 0, medium 7, low 2, false 10, maybe-false 0 +- findings: + - `[false]` `[reject]` Intent auditor: обычное выполнение Story 2.11 — diff реализует UI story; финализация следует после review, промежуточный in-review не является дефектом. + - `[false]` `[reject]` Intent auditor: условный awaiting-operator — AC не требуют внешних действий HUMAN; условная ветка не применяется. + - `[false]` `[reject]` Intent auditor: защита sprint-status — файл отсутствует в diff и не записывался/не откатывался. + - `[false]` `[reject]` Intent auditor: преимущественно mock UI evidence — это UI story поверх существующей API authority, реальный bearer round-trip и полный backend gate дополнительно выполнены. + - `[false]` `[reject]` Intent auditor: финальный workflow результат отсутствует в review diff — ожидаемая стадия in-review; commit и Auto Run Result создаются после triage, не являются продуктовым дефектом. + - `[false]` `[reject]` Blind 1: смена mapping во время plan запроса — createImportPlan вызывает lockPlanEditing(true), finally оставляет lock при state.plan; пользователь не может редактировать controls в этом состоянии. + - `[medium]` `[patch]` Blind 2: operation key ломает CSS selector — parser сохраняет произвольный path key; securityOperationNode должен сравнивать dataset через постоянный selector. Исправлено сравнением dataset; quoted-key regression PASS. + - `[false]` `[reject]` Blind 3: auth_profile_id отсутствует в реальном candidate — DTO OpenApiImportPlanCandidateView содержит поле, render plan получает его, real bearer test подтвердил resolved. + - `[medium]` `[patch]` Blind 4: изменение статуса строки не объявляется при неизменном summary — Добавлены role=status/aria-live=polite к строке; assertions PASS. + - `[low]` `[patch]` Blind 5: selectOption не проверяет клавиатурный выбор — В accessibility leaf использован ArrowDown, выбранные значения и focus проверены, PASS. + - `[medium]` `[patch]` Blind 6: нет явных RU/EN assertions для findings и empty guidance — Добавлены точные assertions обеих локалей, PASS; общий root cause с verification-gap finding. + - `[medium]` `[patch]` Blind 7: security stale fixtures покрывают только cancel — Добавлены security-specific assertions workspace/language, PASS; replacement preview уже покрыт operations.spec.js:494, plan replacement недоступен из-за lockPlanEditing. Guards сохранены. + - `[false]` `[reject]` Blind 8: canary под произвольным ключом остаётся незамеченным — payload уже целиком сериализуется и проверяется на canary; structural helper является дополнительной ограниченной проверкой, backend redaction отдельно проверяется существующим gate. + - `[low]` `[patch]` Blind 9: empty test не проверяет disabled и guidance — Добавлены прямые assertions disabled control/guidance, PASS; verification branch объединён с localized assertions, собственный verdict сохранён. + - `[false]` `[reject]` Blind 10: generated AC IDs опровергают approved snapshot — text snapshot соответствует frozen spec, idSource=generated и источник явно задокументированы; ID не является доказательством/заявлением отдельного approval. + - `[medium]` `[patch]` Verification gap: unsupported alternative лишена проверки локализованного объяснения — pre-verified evidence принято, Добавлены RU/EN finding assertions, PASS; общий root cause с Blind 6. + - `[false]` `[reject]` Edge 1: resolved summary скрывает обязательную unresolved auth — в реальном API actionable protected candidate имеет binding либо anonymous index; unresolved остаётся у excluded/skip, который не требует новой auth binding. Blocked/required/unverified имеют приоритет. Reachable unresolved requiring auth alongside resolved в текущем API не показан. + - `[medium]` `[patch]` Edge 2: operation key с кавычкой ломает lookup — подтверждён тот же root cause, что Blind 2; Исправлено постоянным selector и dataset comparison, regression PASS. + - `[medium]` `[patch]` Lead: реальные blocked candidate reason auth_profile_required получают generic guidance, empty mock использовал несуществующий error — Добавлен safe known finding mapping, удалён вымышленный error mapping; настоящий 200 blocked candidate контракт проверен, PASS. + +## Design Notes + +Локальный выбор — pending/unresolved, actionable candidate от актуального plan API — authoritative resolved, но не гарантия будущего Apply. После возврата к редактированию/ошибки Apply предыдущая проверка снимается. Unsupported OR siblings показываются без collapse; пользователь явно выбирает поддерживаемый вариант или anonymous alternative. Не загружать listAuthProfiles с конфигурацией: preview уже предоставляет совместимые safe choices. + +Исполнитель не один в codebase: не откатывать чужие изменения. Разрешены только перечисленные UI/test/docs/checklist paths и необходимые минимальные sibling helpers при code-health limits; архитектуру и расширение scope вернуть ведущему. ATDD без production code, затем отдельный implementation этап. Context7 Playwright docs подтверждают locator.selectOption (native input/change), page.route/route.fulfill и web-first assertions. + +## Verification + +- `cd apps/ui && npm run build` — build PASS. +- `cd apps/ui && npx playwright test tests/e2e/openapi-security-mapping.spec.js tests/e2e/openapi-import-plan.spec.js tests/e2e/operations.spec.js --workers=1` — mandatory matrix/AC и existing import regressions PASS без skipped mandatory cases; включить реальный API flow. +- `just verify` — полный обязательный gate PASS. + +## Auto Run Result + +Status: done + +Реализован security mapping в OpenAPI UI: явный OR alternative и совместимый workspace Auth Profile по safe metadata, typed index/id в plan decisions, отдельные API-authoritative статусы операций. Anonymous и skip не несут profile binding. Смена выбора, ошибки Apply и stale context снимают прежнюю проверку. Unsupported/empty/blocker guidance переведены на RU/EN; native controls доступны с клавиатуры и объявляют статусы screen reader. + +### Изменённые файлы + +- `apps/ui/js/openapi-import.js` — mapping controls/state, typed payload, per-operation authority, invalidation и safe findings. +- `apps/ui/js/i18n.js` — RU/EN labels, states и guidance. +- `apps/ui/css/openapi-import.css` — стили security controls, statuses и guidance. +- `apps/ui/tests/e2e/openapi-security-mapping.spec.js` — 19 активных AC/matrix/regression сценариев, включая real API bearer round-trip. +- `docs/openapi-import.md` — описание реализованного flow и ограничений. +- `_bmad-output/test-artifacts/atdd-checklist-2-11-security-mapping-ui.md` — frozen AC snapshot и фактические RED/GREEN evidence. +- Эта спецификация — intent, execution checklist, triage и итоговый результат. + +### Review + +Четыре независимых слоя завершены. Все 19 observations перечислены в Review Triage Log: medium 7, low 2, false 10. После группировки применены 7 patch entries: medium 5, low 2, high 0. Исправлены selector lookup, объявления статусов строк, real API blocker reason и пробелы verification (keyboard, localized unsupported/empty guidance, stale language/workspace). Deferred: 0. Все 10 rejected observations имеют отдельную refutation в triage; ни один finding не пропущен. + +Follow-up review recommended: false. Формальный порог нескольких medium patches достигнут, но все конкретные изменённые ветки проверены выполненными тестами и общим gate; оставшегося специфического непроверенного риска для follow-up не выявлено. + +### Verification + +- `cd apps/ui && npm run build` — PASS, exit 0, повторно после review fixes. +- `cd apps/ui && npx playwright test tests/e2e/openapi-security-mapping.spec.js tests/e2e/openapi-import-plan.spec.js tests/e2e/operations.spec.js --workers=1` — 30 passed, exit 0; 19 security + 11 existing regressions, mandatory skipped: 0. +- `just verify` — PASS, exit 0, повторно после review fixes: tooling 152 tests; Rust 945 passed, 0 failed, 1 existing ignored production-size test; contracts, boundaries, fmt, clippy и configured dependency gates пройдены. +- Матрица: Required OR — AC-1 и real API; anonymous — anonymous/index-only; unsupported — disabled alternatives и RU/EN finding assertions; empty/unavailable — real-shaped blocked candidate и typed unavailable; selection — alternative reset/skip/edit; stale — preview/plan cancel, workspace/language и existing replacement regression; safety/accessibility — canary, keyboard, live regions, localized guidance. Все покрывающие тесты выполнены и прошли. +- RED: первоначальные 3 leaves failed до feature; целевой pre-fix index прогон 8 failed / 8 passed подтвердил реальные lifecycle gaps. GREEN результаты не заменяют RED claims. + +### Ограничения + +Backend API не расширялся: отдельного lifecycle/delete endpoint Auth Profile нет, referenced Secret удаление запрещено 409. Real API подтверждает bearer happy path; отрицательные UI revalidation сценарии используют public API contract mocks, а authority/redaction/workspace/Secret semantics проверяются существующим backend gate. Configured npm audit сообщает существующую moderate advisory js-yaml; dependency не менялась, gate exit 0. Действий HUMAN вне репозитория AC не требуют. sprint-status.yaml не записывался и не откатывался. + +### Очистка ресурсов + +Связанные browser stack и OpenCode процессы остановлены; metrics-порты свободны. `docker volume prune -f` завершился exit 0, reclaimed 5.849 GB; осталось 2 active volumes. После очистки `df -h /`: 107 GB available; Btrfs Metadata DUP 1.17/7.01 GiB (16.69%), Global reserve used 0. Ресурсов достаточно для следующей story. diff --git a/_bmad-output/test-artifacts/atdd-checklist-2-11-security-mapping-ui.md b/_bmad-output/test-artifacts/atdd-checklist-2-11-security-mapping-ui.md new file mode 100644 index 0000000..f982a24 --- /dev/null +++ b/_bmad-output/test-artifacts/atdd-checklist-2-11-security-mapping-ui.md @@ -0,0 +1,193 @@ +--- +stepsCompleted: ['step-01-preflight-and-context', 'step-02-generation-mode', 'step-03-test-strategy', 'step-04-generate-tests', 'step-05-validate-and-complete'] +lastStep: 'step-05-validate-and-complete' +lastSaved: '2026-10-03' +workflowType: 'testarch-atdd' +storyId: '2.11' +storyKey: '2-11-security-mapping-ui' +storyFile: '_bmad-output/implementation-artifacts/spec-2-11-security-mapping-ui.md' +atddChecklistPath: '_bmad-output/test-artifacts/atdd-checklist-2-11-security-mapping-ui.md' +generatedTestFiles: + - 'apps/ui/tests/e2e/openapi-security-mapping.spec.js' +inputDocuments: + - '_bmad-output/implementation-artifacts/spec-2-11-security-mapping-ui.md' + - '_bmad-output/implementation-artifacts/epic-2-context.md' + - '_bmad-output/planning-artifacts/epics.md' + - '_bmad-output/test-artifacts/test-design-epic-2.md' + - '_bmad-output/test-artifacts/test-design-qa.md' + - '_bmad/tea/config.yaml' + - 'apps/ui/package.json' + - 'apps/ui/playwright.config.js' + - 'apps/ui/tests/e2e/openapi-import-plan.spec.js' + - 'apps/ui/tests/e2e/operations.spec.js' + - 'apps/ui/tests/e2e/helpers.js' + - '.agents/skills/bmad-testarch-atdd/steps-c/step-01-preflight-and-context.md' + - '.agents/skills/bmad-testarch-atdd/steps-c/step-02-generation-mode.md' + - '.agents/skills/bmad-testarch-atdd/steps-c/step-03-test-strategy.md' + - '.agents/skills/bmad-testarch-atdd/steps-c/step-04-generate-tests.md' + - '.agents/skills/bmad-testarch-atdd/steps-c/step-05-validate-and-complete.md' + - '.agents/skills/bmad-testarch-atdd/checklist.md' + - '.agents/skills/bmad-testarch-atdd/resources/knowledge/data-factories.md' + - '.agents/skills/bmad-testarch-atdd/resources/knowledge/component-tdd.md' + - '.agents/skills/bmad-testarch-atdd/resources/knowledge/test-quality.md' + - '.agents/skills/bmad-testarch-atdd/resources/knowledge/test-healing-patterns.md' + - '.agents/skills/bmad-testarch-atdd/resources/knowledge/selector-resilience.md' + - '.agents/skills/bmad-testarch-atdd/resources/knowledge/timing-debugging.md' + - '.agents/skills/bmad-testarch-atdd/resources/knowledge/fixture-architecture.md' + - '.agents/skills/bmad-testarch-atdd/resources/knowledge/network-first.md' + - '.agents/skills/bmad-testarch-atdd/resources/knowledge/playwright-cli.md' +acceptanceCriteria: + - id: 'AC-1' + idSource: 'generated' + text: 'Given preview сохраняет OR alternatives и required authentication, when администратор выбирает alternative либо совместимый Auth Profile текущего workspace, then UI передаёт выбор существующему import API и показывает authoritative resolved/unresolved/blocker status; raw credentials не вводятся в mapping state и не копируются в IR/plan.' + - id: 'AC-2' + idSource: 'generated' + text: 'Given смена alternative, удалённый/недоступный profile либо stale preview response, when API повторно валидирует binding, then UI показывает safe blocker/revalidation guidance и не выдаёт предыдущий resolved state за текущий; OR/AND semantics, workspace validation и redaction остаются в API Story 2.10.' + - id: 'AC-3' + idSource: 'generated' + text: 'Given security-mapping UI на RU и EN, when пользователь выбирает profile, меняет alternative или получает unsupported scheme, then UI показывает required/unresolved/resolved status, safe profile metadata и blocker findings; loading, empty, error и stale-response states не раскрывают secrets.' +--- + +# ATDD Checklist — Story 2.11: Выбирать security mappings в OpenAPI UI + +**Date:** 2026-10-03 +**Author:** Bsodfather +**Primary test level:** E2E (Playwright Chromium, P1; epic scenario `2.11-E2E-A,B`, risks E2-R2/E2-R4) + +## Story summary + +Администратор выбирает security alternative и безопасный Auth Profile в OpenAPI import UI. Существующий ImportPlan API остаётся единственным источником решения о binding; UI показывает его результат и безопасные подсказки, не вводя и не храня raw credentials. + +**As a** администратор +**I want** выбирать profile и security alternative в OpenAPI UI +**So that** вижу unresolved/resolved/blocker state без раскрытия secrets. + +## Approved acceptance criteria snapshot + +IDs ниже назначены детерминированно в порядке source AC: в спецификации supplied `AC-` IDs отсутствуют. + +| ID | ID source | Acceptance criterion | +|---|---|---| +| AC-1 | generated | Given preview сохраняет OR alternatives и required authentication, when администратор выбирает alternative либо совместимый Auth Profile текущего workspace, then UI передаёт выбор существующему import API и показывает authoritative resolved/unresolved/blocker status; raw credentials не вводятся в mapping state и не копируются в IR/plan. | +| AC-2 | generated | Given смена alternative, удалённый/недоступный profile либо stale preview response, when API повторно валидирует binding, then UI показывает safe blocker/revalidation guidance и не выдаёт предыдущий resolved state за текущий; OR/AND semantics, workspace validation и redaction остаются в API Story 2.10. | +| AC-3 | generated | Given security-mapping UI на RU и EN, when пользователь выбирает profile, меняет alternative или получает unsupported scheme, then UI показывает required/unresolved/resolved status, safe profile metadata и blocker findings; loading, empty, error и stale-response states не раскрывают secrets. | + +## Story integration metadata + +- **Story ID:** `2.11` +- **Story key:** `2-11-security-mapping-ui` +- **Story file:** `_bmad-output/implementation-artifacts/spec-2-11-security-mapping-ui.md` +- **Checklist:** `_bmad-output/test-artifacts/atdd-checklist-2-11-security-mapping-ui.md` +- **Test file:** `apps/ui/tests/e2e/openapi-security-mapping.spec.js` +- **Context:** spec → `_bmad-output/implementation-artifacts/epic-2-context.md`; canonical Epic 2 test design says 2.11 owns former security AC group 11 plus UI perspectives of groups 3 and 5. + +## Preflight and generation decisions + +- Baseline: `b18a84b2c5a70b150d8c6a0749478bd13753308b`. +- Stack: `frontend`; Playwright config is `apps/ui/playwright.config.js`, test directory is `apps/ui/tests/e2e`, Chromium is configured. +- Existing patterns reused: `tests/e2e/openapi-import-plan.spec.js` for plan mocking and `tests/e2e/operations.spec.js` for the preview upload flow; common login/localization helpers come from `tests/e2e/helpers.js`. +- `@seontechnologies/playwright-utils` is absent from `apps/ui/package.json`; the Playwright Utils applicability gate therefore stays closed despite the preference flag. Existing suite uses `@playwright/test` and `page.route`. +- Generation mode: AI specification mode, unattended. Recording was unnecessary because all target selectors are proposed accessible labels for not-yet-implemented controls. Endpoint/payload shapes are grounded in the approved spec and `apps/admin-api/src/dto.rs`; response security fields are grounded in `crates/crank-import/src/rest/model.rs`. +- No production source, sibling helper, or sprint status file was modified. + +## Scenario-to-AC mapping + +Each criterion has exactly one primary RED-phase leaf. The extra matrix branches below are secondary green-phase automation work and do not create additional primary scaffolds. + +| Approved spec scenario | AC | Existing coverage | New primary scaffold / follow-up branch | +|---|---|---|---| +| Required OR: select supported alternative/profile; use current API result | AC-1 | `openapi-import-plan.spec.js` covers ordinary plan/apply decisions, but not security selections or their authority | New `AC-1` E2E leaf sends `security_alternative_index` and `auth_profile_id`, then checks server-returned resolved state. Extend green coverage for every compatible AuthKind. | +| Anonymous/no-auth alternative | AC-1, AC-2 | No security mapping UI test found | Green branch: explicit no-profile choice sends only alternative index; plan must not add an incompatible profile binding. | +| Unsupported AND/OAuth | AC-3 | Backend/UI mapping test absent; API owns support semantics | Green branch: preserve visible unsupported sibling and blocker/manual guidance; never silently select another OR alternative. | +| Empty/unavailable profiles; API rejects removed/revoked profile | AC-2, AC-3 | Existing E2E suite does not exercise Auth Profile mapping | New `AC-2` leaf sends typed reference, receives `import_plan_auth_unavailable`, and asserts safe blocker with no previous resolved state. Green branches: no compatible profile, unavailable Secret, incompatible scheme. | +| Alternative/profile selection changed | AC-2 | Existing import suite tests stale request authority, not security mapping invalidation | Green branch: old plan/resolved status is cleared immediately, profile reset when alternative changes, and new plan result alone restores authority. | +| Stale preview after replacement/workspace/language/close | AC-2, AC-3 | `operations.spec.js` covers generic stale preview request identity, not security mapping state | Green branch: delayed prior preview cannot change current selection/status; retain abort and revision guards. | +| RU/EN required/unresolved/resolved/blocker; no secret canary | AC-3 | Existing suite covers other OpenAPI localization but not security labels/findings | New `AC-3` leaf checks safe metadata and blocker guidance in both locales, and checks DOM/storage/error rendering for a canary. Green branches: loading, empty, API error, unsupported security findings, keyboard/focus/status announcements. | + +## Red-phase E2E scaffolds + +File: `apps/ui/tests/e2e/openapi-security-mapping.spec.js` (212 lines). + +| Test leaf | AC | Expected failing behavior after activation | Baseline status | +|---|---|---|---| +| `[P1] AC-1 sends the selected OR alternative and Auth Profile, then renders API authority` | AC-1 | Current UI has no accessible security-alternative/profile controls and does not submit either plan decision field. | Activated (`test.skip` removed); RED confirmed: failed on missing `Security alternative` label, EXIT=1; now GREEN. | +| `[P1] AC-2 replaces a prior resolved plan with a blocker after profile revalidation fails` | AC-2 | Current UI cannot submit the profile reference or render the typed API blocker after returning from a successful plan. | Activated; RED confirmed (missing controls), EXIT=1; now GREEN. | +| `[P1] AC-3 shows safe security guidance in RU and EN without exposing error or secret canaries` | AC-3 | Current UI does not render security metadata/status/findings and safe localized revalidation guidance. | Activated; RED confirmed (missing safe metadata), EXIT=1; now GREEN. | + +The leaf bodies use accessible labels `Security alternative` / `Вариант безопасности` and `Auth Profile` / `Профиль авторизации`. These are intended stable accessible names for the new controls. The security status oracle is the proposed `data-testid="openapi-security-status"` with exact localized values `Resolved` / `Разрешено`, `Blocked` / `Заблокировано`, and `Unresolved`. Unsupported alternatives must remain visible and disabled. The API fixtures use only safe `{id,name,kind}` profile metadata; the secret canary exists only in the hostile mock error message and is asserted absent from page/storage output. This browser assertion does not prove the backend IR or persisted plan contains no raw credentials; Story 2.10 owns that authority and must supply real API evidence. + +## Minimal mock contract + +- `POST **/imports/openapi/preview` returns the existing preview shape plus `security_profile_choices: [{operation_key, alternative_index, schemes, profiles: [{id,name,kind}]}]`. +- `POST **/imports/openapi/*/plans` captures `decisions[]`; success reflects API candidate `state: actionable` and chosen profile/index. Negative branches return typed 422 codes such as `import_plan_auth_unavailable` or `import_plan_security_alternative_required`. +- No live API or fixture helper is added. Plan/apply regressions remain in existing `openapi-import-plan.spec.js`. + +## Required accessibility/DOM contract + +- Accessible labeled comboboxes for security alternative and Auth Profile, keyboard operable with visible focus. +- Required/unresolved/resolved/blocker result announced using semantic status content. +- Profile options expose only safe `id`, `name`, and `kind`; do not add raw credentials to controls, mappings, plans, local/session storage, or rendered error details. +- Add `data-testid="openapi-security-status"` to the dedicated status output; accessible labels and existing modal IDs identify the inputs and flow controls. + +## Implementation checklist (Story 2.11 stage — completed 2026-10-03) + +- [x] Read `security_profile_choices` and each operation's `security_requirements.alternatives` from preview; preserve OR/AND meanings and unsupported findings. +- [x] Add accessible controls for alternative/profile using only safe profile metadata; explicitly represent no-auth and empty-profile choices (placeholder `value=""`; anonymous option; unsupported options disabled with safe finding copy). +- [x] Store only alternative index/profile ID in mapping state; clear profile on alternative change (and stale plan); never add security fields to `skip` decisions (local guard `openapi.error.security_with_skip`). +- [x] Submit selected decision fields through the existing CreatePlan endpoint; consume candidate plan state/reason as authority (`Resolved`/`Blocked`/`Unresolved` only from plan API result). +- [x] Invalidate old resolved/plan state on selection, replacement, stale response, workspace/language change, close, or API rejection; keep AbortController and identity/revision guards (delayed-preview test covers cancelled stale response). +- [x] Map blocker/finding codes to safe RU/EN copy (`import_plan_auth_unavailable`, `import_plan_auth_incompatible`, `import_plan_security_alternative_required`, candidate reason `auth_profile_required`, `unsupported_security_scheme`, `unsupported_security_and_requirement`); preserve keyboard labels, visible focus, and screen-reader status (`role=status`, `aria-live=polite`). +- [x] Add/retain the dedicated security status test id (`data-testid="openapi-security-status"`) and exact localized state values so the E2E oracle cannot confuse `unresolved` with a substring match on `resolved` (`Unresolved`/`Разрешено`/`Blocked`/`Заблокировано`). +- [x] Activate scaffolds (all 3, EXIT=1 RED) before implementation; then make them pass and complete the secondary branches (anonymous, empty-profile, alternative-change invalidation, stale-preview cancel, keyboard/focus/live status). +- [x] Run `cd apps/ui && npx playwright test tests/e2e/openapi-security-mapping.spec.js tests/e2e/openapi-import-plan.spec.js tests/e2e/operations.spec.js --workers=1` (20 passed, EXIT=0, no skipped mandatory cases) and story-required `just verify` (PASS recorded below). +- [x] Run the key alternative/profile selection against the real Playwright stack: real Secret + bearer Auth Profile created via existing API, real upload → real preview → UI alternative/profile selection → real `POST …/plans` → 200 actionable/`Resolved`, payload carries only `auth_profile_id` + `security_alternative_index`, secret value asserted absent from DOM. Real negative revalidation limitation: the API has no Auth Profile delete/disable endpoint and referenced Secrets are guarded (409 `secret_referenced_by_auth_profile`), so real negative evidence beyond Story 2.10 stays covered by the mandatory mock leaves (`import_plan_auth_unavailable` as a typed top-level rejection and `auth_profile_required` as an API-authored blocked candidate reason) — recorded honestly, no backend surface extended. +- [x] Preserve separate API-owned evidence that raw credentials are absent from normalized IR and plan/persisted outputs: real test additionally asserts the created Secret value never reaches the browser DOM; browser storage canary assertions cover local surfaces. +- [x] Mandatory matrix expansion before story acceptance: anonymous/no-auth; unsupported AND/OAuth visible and disabled; empty compatible-profile list; unavailable Secret/profile rejection (mock, API-code-authoritative); alternative change clears prior profile and plan; stale preview after cancel cannot restore status; loading and API error recovery (AC-3 retry); keyboard/focus/screen-reader behavior. + +## Test execution evidence + +**Discovery command:** `cd apps/ui && npx playwright test tests/e2e/openapi-security-mapping.spec.js --list` + +**RED evidence (before UI implementation):** all three activated leaves failed against the same-revision stack because the accessible `Security alternative` / `Профиль авторизации` controls and safe metadata were absent; command `cd apps/ui && npx playwright test tests/e2e/openapi-security-mapping.spec.js --workers=1` finished `3 failed`, EXIT=1. + +**GREEN evidence (after implementation, same revision):** + +- `cd apps/ui && npm run build` — PASS (EXIT=0). +- `cd apps/ui && npx playwright test tests/e2e/openapi-security-mapping.spec.js --workers=1` — 9 passed, EXIT=0. +- `cd apps/ui && npx playwright test tests/e2e/openapi-security-mapping.spec.js tests/e2e/openapi-import-plan.spec.js tests/e2e/operations.spec.js --workers=1` — 20 passed, EXIT=0, no skipped mandatory cases. + +**Runtime outcome:** run and passed for every mandatory leaf and branch plus one real-API happy-path evidence test; no RED or GREEN is claimed without execution evidence. The three primary leaves were explicit activated tests first (EXIT=1), then activated green leaves. + +**Full `just verify` gate (2026-10-03): PASS, exit 0 (lead-run; log `/tmp/crank211-lead-verify-final.log`).** Two earlier attempts failed on environment/harness issues, not on Story 2.11 code: +- First run (`/tmp/crank211-verify.log`, `VERIFY_EXIT=101`): `crates/crank-artifacts/tests/artifact_store_io.rs` `real_process_write_limit_leaves_no_partial_final_blob` failed at `assert!(status.success())`. The test re-executes itself with `RLIMIT_FSIZE=1` while its stdout was redirected to a regular file (the run log), so the child's own write exceeded the one-byte file-size limit and exited non-zero. The same test passes in isolation; no product defect. +- Second run (`/tmp/crank211-lead-verify.log`, `VERIFY_EXIT=101`): `crank-observability --test prometheus` `default_service_ports_bind_and_serve_real_metrics_listeners` failed with `default metrics port must bind: Bind` — a port conflict with a parallel browser/e2e process holding the metrics port; unrelated to Story 2.11. +- Final clean run (`/tmp/crank211-lead-verify-final.log`): all test binaries ok, `just verify` exit 0. Story 2.11 diff touches only `apps/ui/*` and `docs/openapi-import.md`; no Rust source is changed. + +**Follow-up authority/lifecycle stage (2026-10-03):** fixed lead-found gaps — OR-alternative profile filtering (safe union only while unspecified), anonymous alternative offers no profile control, per-operation authoritative unresolved/required/no-auth/resolved/blocked state from the exact plan candidate with an aggregate summary that never calls a non-auth/excluded candidate resolved, reset on edit/back/Apply rejection, typed-rejection vs transport-error distinction, skip auto-clears security fields, and language-change guards that preserve Apply locks. + +Evidence: +- `node --check apps/ui/js/openapi-import.js apps/ui/js/i18n.js apps/ui/tests/e2e/openapi-security-mapping.spec.js` — OK. +- Targeted RED: current `apps/ui/js/openapi-import.js` saved to `/tmp/crank211-logs/openapi-import.js.current`, then the pre-fix version restored from the Git index (`git show :apps/ui/js/openapi-import.js`, index untouched) and `npx playwright test tests/e2e/openapi-security-mapping.spec.js --workers=1` → `8 failed, 8 passed`, EXIT=1 (log `/tmp/crank211-logs/security-red-index.log`). Failures map to the specific gaps (profile filtering/anonymous profile hidden, per-operation required/authoritative status, blocked-reset on edit, skip clearing security controls, rejected-Apply clearing resolved); current file restored byte-identical afterwards. +- `cd apps/ui && npm run build` — PASS (EXIT=0). +- `cd apps/ui && npx playwright test tests/e2e/openapi-security-mapping.spec.js tests/e2e/openapi-import-plan.spec.js tests/e2e/operations.spec.js --workers=1` — **27 passed, EXIT=0**, no skipped mandatory cases (log `/tmp/crank211-logs/three-suites-3.log`). Security spec then grew to 19 active tests (3 primary AC + matrix/lifecycle/stale-context branches + real-API happy path). +- Review-fix iteration: per-operation status lookup now compares `data-openapi-security-op-status` dataset values against a constant selector (quoted/backslash operation keys covered by a regression), per-operation status nodes expose `role=status`/`aria-live=polite`, the API candidate reason `auth_profile_required` maps to safe translated guidance (empty-profile case now uses a real 200 blocked candidate, not a synthesized error code), and the stale-context coverage includes language and workspace changes. `node --check` OK; `npx playwright test tests/e2e/openapi-security-mapping.spec.js --workers=1` → **19 passed, EXIT=0** (log `/tmp/crank211-logs/security-review-fixes-2.log`). +- New deterministic stale tests replace `waitForTimeout`: preview and plan stale responses are held/ released through a handler-settlement barrier. +- `just verify` was run by the lead (not re-run by this worker); final result is PASS exit 0 above. + +## Knowledge fragments applied + +- `data-factories.md`: use valid contract data and keep fixtures scoped; no new factory needed for the fixed one-operation preview. +- `component-tdd.md`, `test-quality.md`: one primary leaf per AC, meaningful status/payload oracle, separate transition branches for later green automation. +- `test-healing-patterns.md`, `timing-debugging.md`: deterministic network boundary and no hard waits. +- `selector-resilience.md`: accessible role/name selectors rather than styling classes. +- `fixture-architecture.md`: reuse existing pure login helper; no unnecessary fixture abstraction. +- `network-first.md`: install preview/plan routes before navigation. +- `playwright-cli.md`: available for later selector/trace diagnosis if needed; no live recording session launched. + +## Handoff + +ATDD-only output is ready for the separate implementation stage. Keep this checklist as the approved AC snapshot and activate a single leaf before changing production code. The Epic 2 test design requires eventual same-revision browser and real API evidence and does not treat source presence or skipped scaffolds as coverage qualification. + +## Final lead verification + +После review fixes: build PASS exit 0; три mandatory browser suites — **30 passed, exit 0** (19 security + 11 regressions), skipped mandatory 0; `just verify` — **PASS exit 0**, tooling 152, Rust 945 passed / 0 failed / 1 existing ignored stress-test. Все строки frozen I/O matrix покрыты выполненными PASS cases. Финальный verdict основан на diff, независимом review и фактическом прогоне, не на sprint bookkeeping. diff --git a/apps/ui/css/openapi-import.css b/apps/ui/css/openapi-import.css index 9d56e52..5e696b1 100644 --- a/apps/ui/css/openapi-import.css +++ b/apps/ui/css/openapi-import.css @@ -376,14 +376,23 @@ cursor: pointer; } -.openapi-import-decision-controls { +.openapi-import-security-status { + padding: 6px 0 6px 28px; + color: var(--text-secondary); + font-size: 13px; + font-weight: 700; +} + +.openapi-import-decision-controls, +.openapi-import-security-controls { display: flex; flex-wrap: wrap; gap: 10px 14px; padding-left: 28px; } -.openapi-import-decision-controls label { +.openapi-import-decision-controls label, +.openapi-import-security-controls label { display: grid; gap: 5px; color: var(--text-secondary); @@ -392,7 +401,9 @@ } .openapi-import-decision-controls select, -.openapi-import-decision-controls input { +.openapi-import-decision-controls input, +.openapi-import-security-controls select, +.openapi-import-security-controls input { min-width: 210px; max-width: min(100%, 360px); padding: 8px 10px; @@ -402,6 +413,39 @@ color: var(--text-primary); } +.openapi-import-security { + display: grid; + gap: 4px; +} + +.openapi-import-security-op-status { + padding-left: 28px; + color: var(--text-secondary); + font-size: 12px; + font-weight: 700; +} + +.openapi-import-security-op-status[data-status="blocked"] { + color: var(--red); +} + +.openapi-import-security-op-status[data-status="resolved"] { + color: var(--green, var(--text-secondary)); +} + +.openapi-import-security-findings { + align-self: center; + color: var(--amber, var(--text-secondary)); + font-size: 12px; +} + +.openapi-import-security-guidance { + color: var(--text-secondary); + font-size: 12px; + font-weight: 400; + max-width: 360px; +} + .openapi-import-plan-blocked-help { margin: 0; color: var(--red); diff --git a/apps/ui/js/i18n.js b/apps/ui/js/i18n.js index 519952f..3dc5782 100644 --- a/apps/ui/js/i18n.js +++ b/apps/ui/js/i18n.js @@ -612,6 +612,26 @@ var TRANSLATIONS = { 'wizard.step2.auth_mode.existing': 'Use existing authorization profile', 'wizard.step2.auth_mode.create': 'Create authorization profile now', 'openapi.error.plan_too_large': 'Select at most 512 operations and leave at most 512 excluded operations.', + 'openapi.security.alternative_label': 'Security alternative', + 'openapi.security.alternative_placeholder': 'Choose a security alternative', + 'openapi.security.no_auth': 'No authentication', + 'openapi.security.unsupported': 'unsupported', + 'openapi.security.profile_label': 'Auth Profile', + 'openapi.security.profile_placeholder': 'Choose an Auth Profile', + 'openapi.security.status_no_auth': 'No authentication', + 'openapi.security.status_required': 'Authentication required', + 'openapi.security.status_unresolved': 'Unresolved', + 'openapi.security.status_unverified': 'Unverified', + 'openapi.security.status_resolved': 'Resolved', + 'openapi.security.status_blocked': 'Blocked', + 'openapi.security.empty_profiles': 'No compatible Auth Profiles for the selected alternative. Choose another alternative or create a plan to revalidate.', + 'openapi.finding.unsupported_security_scheme': 'Some security requirements could not be imported. Choose a supported alternative or remove the unsupported requirement.', + 'openapi.finding.unsupported_security_and_requirement': 'This security requirement cannot be satisfied with a supported scheme or an available Auth Profile.', + 'openapi.error.security_with_skip': 'A skipped operation cannot be bound to an Auth Profile or a security alternative.', + 'openapi.error.auth_unavailable': 'The selected Auth Profile is unavailable or its required Secret is missing. Choose another compatible profile and create a new plan.', + 'openapi.error.auth_incompatible': 'The Auth Profile scheme does not match the selected security alternative. Choose a compatible alternative or profile and create a new plan.', + 'openapi.error.auth_profile_required': 'This operation requires an Auth Profile. Choose a compatible profile and create a new plan.', + 'openapi.error.security_alternative_required': 'The Auth Profile matches multiple security alternatives. Select the exact alternative and create a new plan.', 'wizard.step2.auth_profile': 'Authorization profile', 'wizard.step2.auth_profile_hint': 'The selected profile is applied automatically on every tool call.', 'wizard.step2.auth_profile_empty': 'No authorization profiles yet. Create one below.', @@ -1660,6 +1680,26 @@ var TRANSLATIONS = { 'wizard.step2.auth_mode.existing': 'Использовать существующий профиль авторизации', 'wizard.step2.auth_mode.create': 'Создать профиль авторизации сейчас', 'openapi.error.plan_too_large': 'Выберите не более 512 операций и оставьте не более 512 исключённых операций.', + 'openapi.security.alternative_label': 'Вариант безопасности', + 'openapi.security.alternative_placeholder': 'Выберите вариант безопасности', + 'openapi.security.no_auth': 'Без аутентификации', + 'openapi.security.unsupported': 'не поддерживается', + 'openapi.security.profile_label': 'Профиль авторизации', + 'openapi.security.profile_placeholder': 'Выберите профиль авторизации', + 'openapi.security.status_no_auth': 'Без аутентификации', + 'openapi.security.status_required': 'Требуется аутентификация', + 'openapi.security.status_unresolved': 'Не разрешено', + 'openapi.security.status_unverified': 'Не проверено', + 'openapi.security.status_resolved': 'Разрешено', + 'openapi.security.status_blocked': 'Заблокировано', + 'openapi.security.empty_profiles': 'Для выбранного варианта нет совместимых профилей авторизации. Выберите другой вариант или создайте план для повторной проверки.', + 'openapi.finding.unsupported_security_scheme': 'Некоторые security requirements нельзя импортировать. Выберите поддерживаемый вариант или уберите неподдерживаемое требование.', + 'openapi.finding.unsupported_security_and_requirement': 'Это security requirement невозможно выполнить со схемой, поддержанной Crank, или доступным профилем авторизации.', + 'openapi.error.security_with_skip': 'Пропускаемая операция не может быть связана с профилем авторизации или вариантом безопасности.', + 'openapi.error.auth_unavailable': 'Выбранный профиль авторизации недоступен, либо отсутствует его обязательный Secret. Выберите другой совместимый профиль и создайте новый план.', + 'openapi.error.auth_incompatible': 'Схема профиля авторизации не совпадает с выбранным вариантом безопасности. Выберите совместимый вариант или профиль и создайте новый план.', + 'openapi.error.auth_profile_required': 'Для этой операции требуется профиль авторизации. Выберите совместимый профиль и создайте новый план.', + 'openapi.error.security_alternative_required': 'Профиль авторизации подходит к нескольким вариантам безопасности. Выберите точный вариант и создайте новый план.', 'wizard.step2.auth_profile': 'Профиль авторизации', 'wizard.step2.auth_profile_hint': 'Выбранный профиль применяется автоматически при каждом вызове инструмента.', 'wizard.step2.auth_profile_empty': 'Профилей авторизации пока нет. Создайте профиль ниже.', diff --git a/apps/ui/js/openapi-import.js b/apps/ui/js/openapi-import.js index cafc5f4..e7370de 100644 --- a/apps/ui/js/openapi-import.js +++ b/apps/ui/js/openapi-import.js @@ -12,6 +12,9 @@ operationsReady: false, decisions: Object.create(null), plan: null, + securityChoices: [], + securityStatus: 'unresolved', + securityByOperation: Object.create(null), filterQuery: '', filterMethod: '', revision: 0, @@ -130,7 +133,13 @@ function decisionFor(operationKey) { if (!state.decisions[operationKey]) { - state.decisions[operationKey] = { action: 'create', targetOperationId: '', confirmedName: '' }; + state.decisions[operationKey] = { + action: 'create', + targetOperationId: '', + confirmedName: '', + securityAlternativeIndex: null, + authProfileId: null, + }; } return state.decisions[operationKey]; } @@ -185,6 +194,8 @@ } } renderDecisionControls(operation, row); + renderSecurityControls(operation, row); + updateSecuritySummary(); }); actionLabel.appendChild(actionSelect); controls.appendChild(actionLabel); @@ -285,6 +296,8 @@ }); } }); + + updateSecuritySummary(); } function applyFilters() { @@ -342,6 +355,9 @@ missing_servers: 'openapi.finding.missing_servers', multiple_servers: 'openapi.finding.multiple_servers', unsupported_request_body: 'openapi.finding.unsupported_request_body', + unsupported_security_scheme: 'openapi.finding.unsupported_security_scheme', + 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', operation_name_conflict: 'openapi.finding.operation_name_conflict', weak_tool_description: 'openapi.finding.weak_tool_description', @@ -462,6 +478,303 @@ }); } + var SECURITY_STATUS_KEYS = { + no_auth: 'openapi.security.status_no_auth', + required: 'openapi.security.status_required', + unresolved: 'openapi.security.status_unresolved', + unverified: 'openapi.security.status_unverified', + resolved: 'openapi.security.status_resolved', + blocked: 'openapi.security.status_blocked', + }; + var SECURITY_PLAN_ERROR_CODES = [ + 'import_plan_auth_unavailable', + 'import_plan_auth_incompatible', + 'import_plan_security_alternative_required', + ]; + + function securityStatusLabel(status) { + return tKey(SECURITY_STATUS_KEYS[status] || SECURITY_STATUS_KEYS.unresolved); + } + + function renderSecurityStatus() { + var node = qs('openapi-import-security-status'); + if (!node) return; + node.textContent = securityStatusLabel(state.securityStatus); + } + + function setSecurityStatus(status) { + state.securityStatus = status; + renderSecurityStatus(); + } + + function securityOperationNode(operationKey) { + // Compare dataset values against a constant selector: imported operation + // keys are untrusted and must never be interpolated into a CSS selector. + var nodes = document.querySelectorAll('[data-openapi-security-op-status]'); + for (var i = 0; i < nodes.length; i += 1) { + if (nodes[i].dataset.openapiSecurityOpStatus === operationKey) return nodes[i]; + } + return null; + } + + function renderOperationSecurityStatus(operationKey) { + var node = securityOperationNode(operationKey); + if (!node) return; + var status = state.securityByOperation[operationKey] || 'unresolved'; + node.dataset.status = status; + node.textContent = securityStatusLabel(status); + } + + function setOperationSecurityStatus(operationKey, status) { + state.securityByOperation[operationKey] = status; + renderOperationSecurityStatus(operationKey); + } + + // Summary only: the per-operation nodes carry the authority, this aggregate + // id reports whether any selected operation still needs attention. + function updateSecuritySummary() { + var selected = new Set(selectedKeys()); + var statuses = []; + importOperations().forEach(function(operation) { + if (!selected.has(operation.key)) return; + statuses.push(state.securityByOperation[operation.key] || baselineSecurityStatus(operation)); + }); + var summary = 'unresolved'; + if (statuses.indexOf('blocked') >= 0) summary = 'blocked'; + else if (statuses.indexOf('required') >= 0) summary = 'required'; + else if (statuses.indexOf('unverified') >= 0) summary = 'unverified'; + else if (statuses.indexOf('resolved') >= 0) summary = 'resolved'; + else if (statuses.length && statuses.every(function(status) { return status === 'no_auth'; })) summary = 'no_auth'; + setSecurityStatus(summary); + } + + function securityAlternativesFor(operation) { + var requirements = operation && operation.security_requirements; + return requirements && Array.isArray(requirements.alternatives) ? requirements.alternatives : []; + } + + function alternativeFor(operation, index) { + if (index === null || index === undefined) return null; + return securityAlternativesFor(operation)[Number(index)] || null; + } + + function isAnonymousAlternative(alternative) { + if (!alternative || alternative.supported === false) return false; + var schemes = Array.isArray(alternative.schemes) ? alternative.schemes : []; + return schemes.length === 0; + } + + function operationRequiresAuth(operation) { + return securityAlternativesFor(operation).some(function(alternative) { + return alternative && alternative.supported !== false + && Array.isArray(alternative.schemes) && alternative.schemes.length > 0; + }); + } + + function securityProfilesFor(operation, alternativeIndex) { + var profiles = []; + (state.securityChoices || []).forEach(function(choice) { + if (!choice || choice.operation_key !== operation.key) return; + // Filter to the exact selected alternative. While no alternative is + // chosen the safe union supports profile-first selection and lets the + // API own compatibility validation. + if (alternativeIndex !== null && alternativeIndex !== undefined + && Number(choice.alternative_index) !== Number(alternativeIndex)) return; + if (Array.isArray(choice.profiles)) profiles = profiles.concat(choice.profiles); + }); + // Keep a stable order across alternatives: first occurrence wins. + var seen = {}; + return profiles.filter(function(profile) { + if (!profile || typeof profile.id !== 'string' || !profile.id || seen[profile.id]) return false; + seen[profile.id] = true; + return true; + }); + } + + // Local expectation only; resolved/blocked never originate here. + function baselineSecurityStatus(operation) { + var alternatives = securityAlternativesFor(operation); + if (!alternatives.length) return 'no_auth'; + var decision = decisionFor(operation.key); + if (decision.action === 'skip') return 'unresolved'; + if (!alternatives.some(function(alternative) { return alternative && alternative.supported !== false; })) { + return 'blocked'; + } + if (!operationRequiresAuth(operation)) return 'no_auth'; + var alternative = alternativeFor(operation, decision.securityAlternativeIndex); + if (isAnonymousAlternative(alternative)) return 'unresolved'; + if (decision.authProfileId) return 'unresolved'; + return 'required'; + } + + function resetSecurityStatuses() { + importOperations().forEach(function(operation) { + state.securityByOperation[operation.key] = baselineSecurityStatus(operation); + renderOperationSecurityStatus(operation.key); + }); + updateSecuritySummary(); + } + + function operationRowFor(operation) { + return Array.from(document.querySelectorAll('.openapi-import-operation')).find(function(row) { + var input = row.querySelector('[data-openapi-operation]'); + return input && input.value === operation.key; + }) || null; + } + + function invalidatePendingPlan() { + // Even without a stored plan a prior blocked state must be cleared: the + // edited selection is unverified until the next plan response arrives. + if (state.plan) { + state.plan = null; + qs('openapi-import-plan-confirmation').hidden = true; + qs('openapi-import-plan-counts').replaceChildren(); + qs('openapi-import-plan-candidates').replaceChildren(); + qs('openapi-import-versioning-consequences').hidden = true; + qs('openapi-import-plan-blocked-help').hidden = true; + } + resetSecurityStatuses(); + } + + function renderSecurityControls(operation, row) { + var previous = row.querySelector('.openapi-import-security'); + if (previous) previous.remove(); + + var decision = decisionFor(operation.key); + var alternatives = securityAlternativesFor(operation); + + if (decision.action === 'skip') { + // A skipped operation keeps the existing operation untouched: no + // security binding may be attached, so clear it instead of trapping the + // user in a local validation error. + decision.authProfileId = null; + decision.securityAlternativeIndex = null; + setOperationSecurityStatus(operation.key, 'unresolved'); + return; + } + + var wrapper = document.createElement('div'); + wrapper.className = 'openapi-import-security'; + + var statusNode = document.createElement('span'); + statusNode.className = 'openapi-import-security-op-status'; + statusNode.setAttribute('data-openapi-security-op-status', operation.key); + statusNode.setAttribute('data-testid', 'openapi-security-op-status'); + // Announce per-operation changes even when the aggregate text is unchanged. + statusNode.setAttribute('role', 'status'); + statusNode.setAttribute('aria-live', 'polite'); + wrapper.appendChild(statusNode); + + if (alternatives.length) { + var controls = document.createElement('div'); + controls.className = 'openapi-import-security-controls'; + + // Only the alternative index and the typed profile id are stored locally. + // The API remains the authority for OR/AND semantics and compatibility. + var alternativeLabel = document.createElement('label'); + var alternativeSelect = document.createElement('select'); + alternativeLabel.textContent = tKey('openapi.security.alternative_label'); + alternativeSelect.dataset.openapiSecurityAlternative = operation.key; + + var alternativePlaceholder = document.createElement('option'); + alternativePlaceholder.value = ''; + alternativePlaceholder.textContent = tKey('openapi.security.alternative_placeholder'); + alternativeSelect.appendChild(alternativePlaceholder); + + var findingsNode = null; + alternatives.forEach(function(alternative, index) { + var option = document.createElement('option'); + var schemes = alternative && Array.isArray(alternative.schemes) ? alternative.schemes : []; + option.value = String(index); + option.textContent = schemes.length ? schemes.join(' + ') : tKey('openapi.security.no_auth'); + if (alternative && alternative.supported === false) { + option.disabled = true; + option.textContent += ' · ' + tKey('openapi.security.unsupported'); + var finding = Array.isArray(alternative.findings) && alternative.findings[0]; + // Surface the blocker as a safe, localized message next to the control. + if (finding) { + if (!findingsNode) { + findingsNode = document.createElement('span'); + findingsNode.className = 'openapi-import-security-findings'; + } + var findingSpan = document.createElement('span'); + findingSpan.className = 'openapi-import-finding openapi-import-finding-warning'; + findingSpan.textContent = findingMessage({ code: finding }); + findingsNode.appendChild(findingSpan); + } + } + alternativeSelect.appendChild(option); + }); + + alternativeSelect.value = decision.securityAlternativeIndex === null + ? '' + : String(decision.securityAlternativeIndex); + alternativeSelect.addEventListener('change', function() { + // Switching the alternative invalidates the previous profile binding and + // any server-confirmed plan: the API revalidates the current selection. + decision.securityAlternativeIndex = alternativeSelect.value === '' + ? null + : Number(alternativeSelect.value); + decision.authProfileId = null; + invalidatePendingPlan(); + renderSecurityControls(operation, row); + }); + alternativeLabel.appendChild(alternativeSelect); + controls.appendChild(alternativeLabel); + if (findingsNode) controls.appendChild(findingsNode); + + var selectedAlternative = alternativeFor(operation, decision.securityAlternativeIndex); + var anonymous = isAnonymousAlternative(selectedAlternative); + var profiles = securityProfilesFor(operation, decision.securityAlternativeIndex); + + // An anonymous alternative must offer no profile at all. + if (!anonymous) { + var profileLabel = document.createElement('label'); + var profileSelect = document.createElement('select'); + profileLabel.textContent = tKey('openapi.security.profile_label'); + profileSelect.dataset.openapiSecurityProfile = operation.key; + + var profilePlaceholder = document.createElement('option'); + profilePlaceholder.value = ''; + profilePlaceholder.textContent = tKey('openapi.security.profile_placeholder'); + profileSelect.appendChild(profilePlaceholder); + + profiles.forEach(function(profile) { + // Safe metadata only: id, name, kind. Never credential material. + var option = document.createElement('option'); + option.value = profile.id; + option.textContent = String(profile.name || profile.id); + if (profile.kind) option.textContent += ' · ' + profile.kind; + profileSelect.appendChild(option); + }); + + var emptyProfiles = decision.securityAlternativeIndex !== null + && selectedAlternative && selectedAlternative.supported !== false + && !anonymous && profiles.length === 0; + if (emptyProfiles) { + profileSelect.disabled = true; + var guidance = document.createElement('span'); + guidance.className = 'openapi-import-security-guidance'; + guidance.textContent = tKey('openapi.security.empty_profiles'); + profileLabel.appendChild(guidance); + } + + profileSelect.value = decision.authProfileId || ''; + profileSelect.addEventListener('change', function() { + decision.authProfileId = profileSelect.value || null; + invalidatePendingPlan(); + }); + profileLabel.appendChild(profileSelect); + controls.appendChild(profileLabel); + } + + wrapper.appendChild(controls); + } + + row.appendChild(wrapper); + setOperationSecurityStatus(operation.key, baselineSecurityStatus(operation)); + } + function renderPreview(response) { var preview = response.preview; var count = (preview.groups || []).reduce(function(sum, group) { @@ -475,6 +788,10 @@ state.existingOperations = []; state.operationsReady = false; state.decisions = Object.create(null); + state.securityChoices = Array.isArray(response.security_profile_choices) + ? response.security_profile_choices + : []; + state.securityByOperation = Object.create(null); importOperations().forEach(function(operation) { decisionFor(operation.key); }); state.filterQuery = ''; state.filterMethod = ''; @@ -543,6 +860,7 @@ } renderDecisionControls(operation, row); + renderSecurityControls(operation, row); groupNode.appendChild(row); }); @@ -560,6 +878,7 @@ input.addEventListener('change', updateSelection); }); applyFilters(); + resetSecurityStatuses(); } function validateFile(file) { @@ -592,6 +911,9 @@ state.existingOperations = []; state.operationsReady = false; state.decisions = Object.create(null); + state.securityChoices = []; + state.securityStatus = 'unresolved'; + state.securityByOperation = Object.create(null); state.plan = null; state.applyRequest = null; state.applyMetadata = []; @@ -607,6 +929,7 @@ qs('openapi-import-versioning-consequences').hidden = true; qs('openapi-import-plan-blocked-help').hidden = true; qs('openapi-import-groups').replaceChildren(); + renderSecurityStatus(); qs('openapi-import-result').hidden = true; qs('openapi-import-result').replaceChildren(); updateSelection(); @@ -665,6 +988,9 @@ document.querySelectorAll('.openapi-import-decision-controls select, .openapi-import-decision-controls input').forEach(function(input) { input.disabled = locked; }); + document.querySelectorAll('.openapi-import-security-controls select, .openapi-import-security-controls input').forEach(function(input) { + input.disabled = locked; + }); } function lockPlanEditing(locked) { @@ -684,6 +1010,9 @@ document.querySelectorAll('.openapi-import-decision-controls select, .openapi-import-decision-controls input').forEach(function(input) { input.disabled = locked; }); + document.querySelectorAll('.openapi-import-security-controls select, .openapi-import-security-controls input').forEach(function(input) { + input.disabled = locked; + }); } function markApplyOutcomeUnknown(options) { @@ -743,6 +1072,9 @@ 'openapi_upload.storage_unavailable': 'openapi.error.storage_unavailable', 'openapi_upload.source_integrity': 'openapi.error.source_integrity', 'openapi_upload.source_unavailable': 'openapi.error.source_unavailable', + 'import_plan_auth_unavailable': 'openapi.error.auth_unavailable', + 'import_plan_auth_incompatible': 'openapi.error.auth_incompatible', + 'import_plan_security_alternative_required': 'openapi.error.security_alternative_required', }; var message = tKey(known[error && error.code] || fallback); var identifiers = []; @@ -796,11 +1128,11 @@ state.existingOperations = operationResponse.items; state.operationsReady = true; importOperations().forEach(function(operation) { - var row = Array.from(document.querySelectorAll('.openapi-import-operation')).find(function(candidateRow) { - var input = candidateRow.querySelector('[data-openapi-operation]'); - return input && input.value === operation.key; - }); - if (row) renderDecisionControls(operation, row); + var row = operationRowFor(operation); + if (row) { + renderDecisionControls(operation, row); + renderSecurityControls(operation, row); + } }); qs('openapi-import-create').disabled = false; setStatus(tKey('openapi.status.preview_ready')); @@ -997,6 +1329,33 @@ var versioningNode = qs('openapi-import-versioning-consequences'); var counts = plan.counts || {}; var hasBlocked = (Number(counts.blocked) || 0) > 0; + var operationsByKey = Object.create(null); + importOperations().forEach(function(operation) { operationsByKey[operation.key] = operation; }); + + // The plan API is the sole authority for each operation's binding outcome. + (Array.isArray(plan.candidates) ? plan.candidates : []).forEach(function(candidate) { + if (!candidate || !candidate.key) return; + var operation = operationsByKey[candidate.key]; + var alternativeIndex = candidate.security_alternative_index; + var anonymous = alternativeIndex !== null && alternativeIndex !== undefined + && isAnonymousAlternative(alternativeFor(operation, alternativeIndex)); + var status; + if (candidate.state === 'blocked') { + status = 'blocked'; + } else if (candidate.state === 'actionable') { + // Only a genuine auth binding confirmed by the API is resolved; a + // no-auth/anonymous or unbound candidate must never read as resolved. + if (candidate.auth_profile_id) status = 'resolved'; + else if (operation && !operationRequiresAuth(operation)) status = 'no_auth'; + else if (anonymous) status = 'no_auth'; + else status = 'unresolved'; + } else { + // Excluded/skipped candidates keep the operation untouched. + status = 'unresolved'; + } + setOperationSecurityStatus(candidate.key, status); + }); + updateSecuritySummary(); var countSpecs = [ ['selected', 'openapi.plan.selected'], ['excluded', 'openapi.plan.excluded'], @@ -1241,6 +1600,8 @@ state.plan = null; qs('openapi-import-plan-confirmation').hidden = true; lockPlanEditing(false); + // A rejected/repreview Apply voids the prior resolved security review. + resetSecurityStatuses(); if (!qs('openapi-import-modal').hidden) { if (recovery === 'repreview_required') { setStatus(tKey('openapi.plan.repreview'), true, true); @@ -1308,6 +1669,16 @@ var selectedSet = new Set(keys); var decisions = []; var invalidDecision = null; + importOperations().forEach(function(operation) { + if (!selectedSet.has(operation.key)) return; + var decision = decisionFor(operation.key); + // Skip decisions keep the existing operation untouched: no security + // binding may be attached to them. + if (decision.action === 'skip' + && (decision.authProfileId || decision.securityAlternativeIndex !== null)) { + invalidDecision = 'openapi.error.security_with_skip'; + } + }); importOperations().forEach(function(operation) { if (!selectedSet.has(operation.key) || invalidDecision) return; var decision = decisionFor(operation.key); @@ -1332,7 +1703,19 @@ invalidDecision = 'openapi.error.decision_action'; return; } - if (decision.action !== 'create') decisions.push(output); + // Security binding is a typed reference only: alternative index and, + // when chosen, the profile id. Resolution stays server-side. + if (decision.action !== 'skip') { + if (decision.authProfileId) output.auth_profile_id = decision.authProfileId; + if (decision.securityAlternativeIndex !== null) { + output.security_alternative_index = decision.securityAlternativeIndex; + } + } + if (decision.action !== 'create' + || decision.authProfileId + || decision.securityAlternativeIndex !== null) { + decisions.push(output); + } }); if (invalidDecision) { setStatus(tKey(invalidDecision), true, true); @@ -1386,6 +1769,16 @@ } setStatus(errorStatus(error, 'openapi.error.plan'), true, true); showRetry(true); + // A typed API rejection of a security binding is authoritative blocked; + // a transport/network failure only means the selection is unverified. + var securityRejection = Number.isInteger(error && error.status) + && error.status >= 400 && error.status < 500 + && SECURITY_PLAN_ERROR_CODES.indexOf(String(error.code)) >= 0; + importOperations().forEach(function(operation) { + if (!selectedSet.has(operation.key) || !securityAlternativesFor(operation).length) return; + setOperationSecurityStatus(operation.key, securityRejection ? 'blocked' : 'unverified'); + }); + updateSecuritySummary(); } finally { if (state.planController === controller) { state.planController = null; @@ -1422,6 +1815,9 @@ function backToImportSelection() { if (state.applyInFlight || state.applyOutcomeUnknown) return; state.plan = null; + // Returning to editing voids the previous review: revalidation is done by + // the next plan request. + resetSecurityStatuses(); qs('openapi-import-plan-confirmation').hidden = true; qs('openapi-import-plan-counts').replaceChildren(); qs('openapi-import-plan-candidates').replaceChildren(); @@ -1530,6 +1926,18 @@ renderFileName(); + // Dedicated screen-reader output for the API-authoritative binding state. + var groupsNode = qs('openapi-import-groups'); + if (!qs('openapi-import-security-status') && groupsNode && groupsNode.parentNode) { + var securityStatusNode = document.createElement('div'); + securityStatusNode.id = 'openapi-import-security-status'; + securityStatusNode.className = 'openapi-import-security-status'; + securityStatusNode.setAttribute('data-testid', 'openapi-security-status'); + securityStatusNode.setAttribute('role', 'status'); + securityStatusNode.setAttribute('aria-live', 'polite'); + groupsNode.parentNode.insertBefore(securityStatusNode, groupsNode); + } + qs('openapi-import-file-select').addEventListener('click', function(event) { event.preventDefault(); qs('openapi-import-file').click(); @@ -1601,14 +2009,30 @@ setStatus(tKey('openapi.status.context_changed')); } } - function handleLanguageChange() { - if (!qs('openapi-import-modal').hidden && state.plan && !state.applyInFlight && !state.applyOutcomeUnknown) { - renderImportPlan(state.plan); - setStatus(tKey('openapi.status.plan_ready')); - return; - } + function handleLanguageChange() { + // While an Apply owns the locked controls, re-rendering would re-enable + // them. Route straight to the context-change path, which marks the apply + // outcome unknown and keeps the controls locked. + if (state.applyInFlight || state.applyController || (state.applyOutcomeUnknown && state.applyRequest)) { + renderSecurityStatus(); invalidateForContext(); + return; } + importOperations().forEach(function(operation) { + var row = operationRowFor(operation); + if (row) { + renderDecisionControls(operation, row); + renderSecurityControls(operation, row); + } + }); + if (!qs('openapi-import-modal').hidden && state.plan) { + renderImportPlan(state.plan); + setStatus(tKey('openapi.status.plan_ready')); + return; + } + updateSecuritySummary(); + invalidateForContext(); + } window.addEventListener('crank:langchange', handleLanguageChange); window.addEventListener('crank:workspacechange', function(event) { if (!qs('openapi-import-modal').hidden) { diff --git a/apps/ui/tests/e2e/openapi-security-mapping.spec.js b/apps/ui/tests/e2e/openapi-security-mapping.spec.js new file mode 100644 index 0000000..92bcfe3 --- /dev/null +++ b/apps/ui/tests/e2e/openapi-security-mapping.spec.js @@ -0,0 +1,979 @@ +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) {} + } +}); diff --git a/docs/openapi-import.md b/docs/openapi-import.md index c86ec9c..22ec627 100644 --- a/docs/openapi-import.md +++ b/docs/openapi-import.md @@ -13,7 +13,7 @@ Crank умеет импортировать REST API из OpenAPI 3.x и Swagger 7. Проверьте `Base URL`. Если в документе нет `servers`, укажите URL вручную. 8. Для уже существующей операции подтвердите решение отдельно: пропустить точную операцию, создать отдельную операцию с указанным вами свободным именем или добавить новую черновую версию к выбранной REST-операции. Автоматический подбор имени при применении плана не выполняется. 9. Создайте план и проверьте число выбранных, исключённых, доступных и заблокированных методов. По умолчанию полный план требует, чтобы каждый метод можно было применить; для частичного импорта явно оставьте только нужные методы. -10. Для защищённых методов задайте совместимый Auth Profile через import API, выбрав конкретную security alternative из вариантов preview. Незакрытое обязательное требование оставляет метод заблокированным; выбор этих привязок в UI пока недоступен. +10. Для защищённых методов выберите security alternative (OR-варианты preview; неподдерживаемые варианты, включая AND/OAuth, показаны заблокированными) и, если требуется аутентификация, совместимый Auth Profile текущего workspace — по безопасным метаданным `id/name/kind` из preview. Вариант без схем — анонимный вызов без профиля. Статус привязки показывает только API: `Unresolved` до проверки, `Resolved` после подтверждения планом, `Blocked` при отказе; UI не вычисляет resolved локально. Незакрытое обязательное требование или недоступный профиль оставляет метод заблокированным. 11. Подтвердите план и примените его. Создание плана не меняет операции. Применение выполняет все выбранные изменения одной транзакцией и показывает результат для каждого метода. ## Загрузка и восстановление