story 2-11-security-mapping-ui: implemented and reviewed via bmad-loop
This commit is contained in:
1 parent
b18a84b2c5
commit
4307c1d90d
7 files changed
+1840
-17
No files matched your search
@@ -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-contract>
|
||||
|
||||
## 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 |
|
||||
|
||||
</intent-contract>
|
||||
|
||||
## 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.
|
||||
@@ -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-<n>` 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.
|
||||
Reference in new issue
Block a user