Compare commits

...
Author SHA1 Message Date
bsodfather 9e9c326c3e fix(import): align external URI identity with HTTP transport
CI / Rust Checks (pull_request) Successful in 25m55s
CI / UI Checks (pull_request) Successful in 5s
CI / Community Image Smoke (pull_request) Successful in 7m42s
CI / Frontend E2E (pull_request) Successful in 12m39s
CI / Deploy (pull_request) Skipped
Share pure URL canonicalization between snapshot materialization and resolution. Preserve historical v5/v6 previews while advancing normalization to v6 and the support matrix to 1.0.4. Cover encoded-dot paths, apostrophe queries, relative children, and no-refetch apply/replay.
2026-10-11 08:33:43 +03:00
bsodfather 178093e81b Импорт OpenAPI: закрыть пробелы проверок второго этапа (#95)
CI / Rust Checks (push) Successful in 25m23s
CI / UI Checks (push) Successful in 6s
CI / Community Image Smoke (push) Successful in 2m0s
CI / Frontend E2E (push) Successful in 9m12s
CI / Deploy (push) Successful in 1m22s
2026-10-10 11:54:58 +00:00
bsodfather ad23cd9a46 fix(import): подтвердить обязательные гарантии второго эпика
CI / Rust Checks (pull_request) Successful in 24m43s
CI / UI Checks (pull_request) Successful in 6s
CI / Community Image Smoke (pull_request) Successful in 9m5s
CI / Frontend E2E (pull_request) Successful in 12m43s
CI / Deploy (pull_request) Skipped
2026-10-10 13:25:05 +03:00
bsodfather 31f6f00d3b Безопасность: сократить серверные образы и проверять все уязвимости (#93)
CI / Rust Checks (push) Successful in 22m49s
CI / UI Checks (push) Successful in 6s
CI / Community Image Smoke (push) Successful in 1m54s
CI / Frontend E2E (push) Successful in 6m59s
CI / Deploy (push) Successful in 1m41s
2026-10-09 23:15:05 +00:00
bsodfather f685616ae8 fix(security): minimize runtime images and enforce complete vulnerability scans
CI / Rust Checks (pull_request) Successful in 23m1s
CI / UI Checks (pull_request) Successful in 6s
CI / Community Image Smoke (pull_request) Successful in 7m28s
CI / Frontend E2E (pull_request) Successful in 9m33s
CI / Deploy (pull_request) Skipped
2026-10-10 01:41:38 +03:00
bsodfather 0c1fb38e31 Merge pull request 'Завершить импорт OpenAPI и пошаговый первый запуск (2-15)' (#90) from fix/2-15-verify-and-deliver-20261005 into main
CI / Rust Checks (push) Successful in 22m50s
CI / UI Checks (push) Successful in 6s
CI / Community Image Smoke (push) Successful in 2m25s
CI / Frontend E2E (push) Successful in 7m52s
CI / Deploy (push) Successful in 1m39s
2026-10-09 17:09:54 +00:00
bsodfather 249b777bec Исправить перекрытие навигации и обновить пакеты образов
CI / Rust Checks (pull_request) Successful in 22m46s
CI / UI Checks (pull_request) Successful in 6s
CI / Frontend E2E (pull_request) Successful in 11m48s
CI / Community Image Smoke (pull_request) Successful in 13m42s
CI / Deploy (pull_request) Skipped
2026-10-09 19:13:02 +03:00
bsodfather f48754aaf5 fix(ci): use a pinned Gitea compatible artifact action
CI / Rust Checks (pull_request) Successful in 22m57s
CI / UI Checks (pull_request) Successful in 6s
CI / Frontend E2E (pull_request) Successful in 12m27s
CI / Community Image Smoke (pull_request) Failing after 16m23s
CI / Deploy (pull_request) Skipped
2026-10-09 17:53:47 +03:00
bsodfather e93de7015a feat(import): complete OpenAPI onboarding and verify delivery
CI / Rust Checks (pull_request) Failing after 1s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
2026-10-09 17:50:38 +03:00
bsodfather bb3e376767 Исправить уязвимость образов и восстановить развёртывание Crank (#85)
CI / Rust Checks (push) Successful in 15m29s
CI / UI Checks (push) Successful in 6s
CI / Community Image Smoke (push) Successful in 1m51s
CI / Frontend E2E (push) Successful in 5m10s
CI / Deploy (push) Successful in 1m38s
2026-10-05 05:14:42 +00:00
bsodfather 3f4ea248c7 fix(deploy): update vulnerable pcre2 in UI image
CI / Rust Checks (pull_request) Successful in 15m33s
CI / UI Checks (pull_request) Successful in 6s
CI / Community Image Smoke (pull_request) Successful in 7m18s
CI / Frontend E2E (pull_request) Successful in 7m53s
CI / Deploy (pull_request) Skipped
2026-10-05 07:47:51 +03:00
bsodfather 7c9bc079da fix(deploy): update vulnerable Debian library before image scan
CI / Rust Checks (pull_request) Successful in 16m40s
CI / UI Checks (pull_request) Successful in 6s
CI / Frontend E2E (pull_request) Successful in 9m3s
CI / Community Image Smoke (pull_request) Failing after 11m0s
CI / Deploy (pull_request) Skipped
2026-10-05 07:15:21 +03:00
bsodfather c7cd4d8ef2 Исправления эпика 1 после ретроспективы (#83)
CI / Rust Checks (push) Successful in 15m25s
CI / UI Checks (push) Successful in 5s
CI / Community Image Smoke (push) Successful in 1m19s
CI / Frontend E2E (push) Successful in 5m7s
CI / Deploy (push) Failing after 26s
2026-10-04 23:38:00 +00:00
bsodfather eacfab0dd8 test: stabilize browser session setup and OpenAPI assertions
CI / Rust Checks (pull_request) Successful in 15m33s
CI / UI Checks (pull_request) Successful in 5s
CI / Community Image Smoke (pull_request) Successful in 6m28s
CI / Frontend E2E (pull_request) Successful in 7m27s
CI / Deploy (pull_request) Skipped
2026-10-05 02:13:18 +03:00
bsodfather ca32d3767f docs: annotate onboarding key disclosure test in archived report
CI / Rust Checks (pull_request) Successful in 16m32s
CI / UI Checks (pull_request) Successful in 6s
CI / Frontend E2E (pull_request) Failing after 10m8s
CI / Community Image Smoke (pull_request) Successful in 15m33s
CI / Deploy (pull_request) Skipped
2026-10-05 01:06:28 +03:00
bsodfather e959f094e3 docs: normalize archived verification output whitespace
CI / Rust Checks (pull_request) Failing after 5m28s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
2026-10-05 00:58:53 +03:00
bsodfather a36f3e2181 docs: preserve isolated epic 1 PR verification evidence
CI / Rust Checks (pull_request) Canceled after 2m31s
CI / UI Checks (pull_request) Canceled after 0s
CI / Frontend E2E (pull_request) Canceled after 0s
CI / Community Image Smoke (pull_request) Canceled after 0s
CI / Deploy (pull_request) Canceled after 0s
2026-10-05 00:56:56 +03:00
bsodfather fa320c34cb fix: copy vendored SQLx into Docker build stages
CI / Rust Checks (pull_request) Canceled after 15m29s
CI / UI Checks (pull_request) Canceled after 0s
CI / Frontend E2E (pull_request) Canceled after 0s
CI / Community Image Smoke (pull_request) Canceled after 0s
CI / Deploy (pull_request) Canceled after 0s
2026-10-05 00:19:54 +03:00
bsodfather 18e27f3994 docs(evidence): normalize sanitized diagnostic whitespace
CI / Rust Checks (pull_request) Failing after 16m45s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
2026-10-05 00:01:04 +03:00
bsodfather ce5b9af5ab docs(epic-1): record verified retrospective completion evidence 2026-10-05 00:01:04 +03:00
bsodfather c6805e2345 test(ui): preserve auto-opened onboarding panel in recovery check 2026-10-05 00:01:04 +03:00
bsodfather 45f3cabe44 fix(tooling): exclude upstream SQLx from Community marker scan 2026-10-04 23:57:40 +03:00
bsodfather 284eb8180e fix(deps): bound SQLx pool maintenance and reserve idle counters 2026-10-04 23:57:40 +03:00
bsodfather 7aa854de26 fix(epic-1): repair atomic agent edits and dispatch certainty 2026-10-04 23:57:40 +03:00
bsodfather 82b215dd74 Merge pull request 'Bmad loop/20260927 234647 43b3/2 10 security schemes secrets' (#5) from bmad-loop/20260927-234647-43b3/2-10-security-schemes-secrets into main
CI / Rust Checks (push) Successful in 22m6s
CI / UI Checks (push) Successful in 11s
CI / Frontend E2E (push) Failing after 9m34s
CI / Community Image Smoke (push) Successful in 16m5s
CI / Deploy (push) Has been skipped
Reviewed-on: #5
2026-09-27 21:25:01 +00:00
bsodfather 028d8183c3 docs(story): complete 2.10 auto run result
CI / Rust Checks (pull_request) Successful in 22m34s
CI / UI Checks (pull_request) Successful in 8s
CI / Frontend E2E (pull_request) Failing after 23s
CI / Community Image Smoke (pull_request) Successful in 16m20s
CI / Deploy (pull_request) Has been skipped
2026-09-27 23:45:07 +03:00
bsodfather 41a0e46110 feat(import): bind OpenAPI security schemes safely 2026-09-27 23:42:11 +03:00
445 changed files with 98734 additions and 1780 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
docs/epic-1-completion/evidence/*.patch -whitespace
+63 -7
View File
@@ -21,6 +21,8 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Install Rust toolchain
run: |
@@ -109,6 +111,31 @@ jobs:
- name: Check Rust boundaries
run: scripts/check-rust-boundaries.sh
- name: Run offline OpenAPI support corpus gate
run: cargo test -p crank-import --test corpus -- --test-threads=1
- name: Check OpenAPI matrix and corpus compatibility versions
env:
MATRIX_BASE_REF: ${{ gitea.base_ref }}
MATRIX_EVENT_BEFORE: ${{ gitea.event.before }}
run: |
if [ -n "$MATRIX_BASE_REF" ]; then
base_ref="origin/$MATRIX_BASE_REF"
elif [ -n "$MATRIX_EVENT_BEFORE" ] && ! printf '%s' "$MATRIX_EVENT_BEFORE" | grep -Eq '^0+$'; then
base_ref="$MATRIX_EVENT_BEFORE"
else
base_ref="$(git merge-base HEAD origin/main)"
fi
python3 scripts/check-openapi-matrix-compatibility.py --base "$base_ref"
- name: Save OpenAPI corpus evidence
if: always()
uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 # v4
with:
name: openapi-corpus-evidence
path: crates/crank-import/target/openapi-corpus/evidence-*.json
if-no-files-found: warn
- name: Run clippy
run: cargo clippy --workspace --all-targets --all-features --jobs "$CARGO_BUILD_JOBS" -- -D warnings
@@ -217,7 +244,7 @@ jobs:
run: |
mkdir -p ../../.tmp
rm -f ../../.tmp/openapi-playwright.json ../../.tmp/openapi-ui-evidence.json
PLAYWRIGHT_JSON_OUTPUT=../../.tmp/openapi-playwright.json npx playwright test
PLAYWRIGHT_JSON_OUTPUT=../../.tmp/openapi-playwright.json npx playwright test --retries=0
- name: Collect sanitized OpenAPI UI evidence
working-directory: apps/ui
@@ -264,9 +291,26 @@ jobs:
- name: Build Community images
run: |
docker build -f apps/admin-api/Dockerfile -t crank/admin-api:ci .
docker build -f apps/mcp-server/Dockerfile -t crank/mcp-server:ci .
docker build -f apps/ui/Dockerfile -t crank/ui:ci .
docker build --pull --build-arg CRANK_SECURITY_REFRESH=${{ gitea.sha }} \
-f apps/admin-api/Dockerfile -t crank/admin-api:ci .
docker build --pull --build-arg CRANK_SECURITY_REFRESH=${{ gitea.sha }} \
-f apps/mcp-server/Dockerfile -t crank/mcp-server:ci .
docker build --pull -f apps/ui/Dockerfile -t crank/ui:ci .
- name: Scan Community images
run: |
scripts/scan-images.sh \
crank/admin-api:ci \
crank/mcp-server:ci \
crank/ui:ci
- name: Save Community image scan evidence
if: always()
uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 # v4
with:
name: image-scan-evidence
path: .tmp/image-scan-evidence
if-no-files-found: warn
- name: Start Community image stack
run: |
@@ -395,15 +439,19 @@ jobs:
- name: Build and push images
run: |
docker build -f apps/admin-api/Dockerfile \
docker build --pull \
--build-arg CRANK_SECURITY_REFRESH=${{ env.IMAGE_TAG }} \
-f apps/admin-api/Dockerfile \
-t '${{ env.ADMIN_API_IMAGE }}:${{ env.IMAGE_TAG }}' \
-t '${{ env.ADMIN_API_IMAGE }}:main' \
.
docker build -f apps/mcp-server/Dockerfile \
docker build --pull \
--build-arg CRANK_SECURITY_REFRESH=${{ env.IMAGE_TAG }} \
-f apps/mcp-server/Dockerfile \
-t '${{ env.MCP_SERVER_IMAGE }}:${{ env.IMAGE_TAG }}' \
-t '${{ env.MCP_SERVER_IMAGE }}:main' \
.
docker build -f apps/ui/Dockerfile \
docker build --pull -f apps/ui/Dockerfile \
-t '${{ env.UI_IMAGE }}:${{ env.IMAGE_TAG }}' \
-t '${{ env.UI_IMAGE }}:main' \
.
@@ -418,6 +466,14 @@ jobs:
docker push '${{ env.UI_IMAGE }}:${{ env.IMAGE_TAG }}'
docker push '${{ env.UI_IMAGE }}:main'
- name: Save deploy image scan evidence
if: always()
uses: https://github.com/ChristopherHX/gitea-upload-artifact@81f940d004763f986ba3582c007fd842dd5cb0d7 # v4
with:
name: deploy-image-scan-evidence
path: .tmp/image-scan-evidence
if-no-files-found: warn
- name: Configure SSH key
run: |
. "$OPENBAO_ENV_FILE"
+5
View File
@@ -38,6 +38,11 @@ npx playwright test
[`docs/capability-baseline/manifest.json`](./docs/capability-baseline/manifest.json),
sanitized results и SHA-256. Нельзя вручную объявлять pass для failed, flaky,
skipped, not-run или manual-only evidence.
- Для записи результатов этапа и разделения исторического capability baseline
и текущего completion evidence следуйте
[правилам evidence разработки](./docs/development-evidence.md). Перед этапом
фиксируйте полный clean Git baseline; проверенную реализацию указывайте
отдельной ревизией.
- Не добавляйте секреты, токены, приватные адреса и локальные настройки.
- Не коммитьте `AGENTS.md`, `TASKS.md`, `.env` и временные файлы.
- Для изменений SQL-запросов обновляйте `.sqlx`, если это требуется SQLx.
Generated
+16 -15
View File
@@ -43,7 +43,9 @@ dependencies = [
"metrics",
"metrics-util",
"opentelemetry",
"opentelemetry-proto",
"opentelemetry_sdk",
"prost",
"rand 0.10.2",
"reqwest 0.12.28",
"serde",
@@ -221,9 +223,9 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "aws-lc-rs"
version = "1.17.3"
version = "1.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00bdb5da18dac48ca2cc7cd4a98e533e8635a58e2361d13a1a4ee3888e0d72f1"
checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e"
dependencies = [
"aws-lc-sys",
"zeroize",
@@ -231,9 +233,9 @@ dependencies = [
[[package]]
name = "aws-lc-sys"
version = "0.43.0"
version = "0.45.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "43103168cc76fe62678a375e722fc9cb3a0146159ac5828bc4f0dfd755c2224c"
checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27"
dependencies = [
"cc",
"cmake",
@@ -766,6 +768,7 @@ dependencies = [
"serde",
"serde_json",
"serde_yaml",
"sha2 0.10.9",
"thiserror 2.0.18",
"url",
]
@@ -1142,7 +1145,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -2671,7 +2674,7 @@ dependencies = [
"once_cell",
"socket2 0.5.10",
"tracing",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -3010,14 +3013,14 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
name = "rustls"
version = "0.23.41"
version = "0.23.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b92b125634d9b795e7beca796cc790df15a7fb38323bf3196fda83292d06b1f"
checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
dependencies = [
"aws-lc-rs",
"log",
@@ -3069,7 +3072,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -3080,9 +3083,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"
[[package]]
name = "rustls-webpki"
version = "0.103.13"
version = "0.103.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"
checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
dependencies = [
"aws-lc-rs",
"ring",
@@ -3537,8 +3540,6 @@ dependencies = [
[[package]]
name = "sqlx-core"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05b44e85bf579a8eeb4ceaa77a3a523baf2bf0e9bac7e40f405d537b5d2d5ccb"
dependencies = [
"base64",
"bytes",
@@ -4473,7 +4474,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
+4
View File
@@ -18,8 +18,12 @@ members = [
"crates/crank-adapter-rest",
"crates/crank-artifacts",
]
exclude = ["vendor/sqlx-core"]
resolver = "3"
[patch.crates-io]
sqlx-core = { path = "vendor/sqlx-core" }
[workspace.package]
edition = "2024"
license = "AGPL-3.0-only"
@@ -2,9 +2,10 @@
title: '2.10 — Привязать security schemes через безопасный import API'
type: feature
created: '2026-09-13'
status: blocked
status: done
baseline_revision: c562d5368d810d1730f5d392ae0c6c106143a97c
review_loop_iteration: 0
followup_review_recommended: false
followup_review_recommended: true
context:
- '_bmad-output/project-context.md'
- '_bmad-output/implementation-artifacts/epic-2-context.md'
@@ -73,13 +74,13 @@ deferred: []
**Execution (intent gap разрешён пользователем 2026-09-13; реализация выполняется при повторном запуске оркестратора):**
- [ ] `crates/crank-import/src/rest/{model.rs,openapi3.rs,swagger2.rs,normalize.rs,normalize_projection.rs,payload.rs}` — добавить typed schemes и effective requirements, deterministic OR/AND projection, source coverage и blockers без credentials.
- [ ] `crates/crank-import/src/rest/{metadata_findings.rs,normalize_finding_validation.rs}`, `apps/admin-api/src/service/imports.rs`, `apps/admin-api/src/service/imports/external_references.rs` — проверять secret-bearing inputs до persistence и исключить raw values из IR/diagnostics.
- [ ] `apps/admin-api/src/{app.rs,dto.rs,service/imports.rs}` — предоставить выбор/revalidation alternative и совместимых workspace profiles, включить mappings в application digest, сохранять только profile reference.
- [ ] `crates/crank-registry/src/postgres/import_job.rs` — проверять существование и workspace профиля, совместимость binding и доступность всех необходимых связанных Secrets по существующим правилам active/current version в transaction перед mutation; независимый lifecycle профиля не добавлять.
- [ ] `apps/admin-api/src/service/imports/job_contract.rs` — сохранить исторический v4 replay при изменении normalizer/projection contract.
- [ ] `crates/crank-import/tests/`, `apps/admin-api/tests/integration/openapi_import/`, `crates/crank-runtime/tests/` — покрыть все строки матрицы и AC fixtures/negative tests, в том числе race, foreign refs, redaction canaries и digest mismatch.
- [ ] `docs/openapi-import.md` — описать security API, поддерживаемые mappings, blockers и revalidation; не обещать непроверенные semantics.
- [x] `crates/crank-import/src/rest/{model.rs,openapi3.rs,swagger2.rs,normalize.rs,normalize_projection.rs,payload.rs}` — добавить typed schemes и effective requirements, deterministic OR/AND projection, source coverage и blockers без credentials.
- [x] `crates/crank-import/src/rest/{metadata_findings.rs,normalize_finding_validation.rs}`, `apps/admin-api/src/service/imports.rs`, `apps/admin-api/src/service/imports/external_references.rs` — проверять secret-bearing inputs до persistence и исключить raw values из IR/diagnostics.
- [x] `apps/admin-api/src/{app.rs,dto.rs,service/imports.rs}` — предоставить выбор/revalidation alternative и совместимых workspace profiles, включить mappings в application digest, сохранять только profile reference.
- [x] `crates/crank-registry/src/postgres/import_job.rs` — проверять существование и workspace профиля, совместимость binding и доступность всех необходимых связанных Secrets по существующим правилам active/current version в transaction перед mutation; независимый lifecycle профиля не добавлять.
- [x] `apps/admin-api/src/service/imports/job_contract.rs` — сохранить исторический v4 replay при изменении normalizer/projection contract.
- [x] `crates/crank-import/tests/`, `apps/admin-api/tests/integration/openapi_import/`, `crates/crank-runtime/tests/` — покрыть все строки матрицы и AC fixtures/negative tests, в том числе race, foreign refs, redaction canaries и digest mismatch.
- [x] `docs/openapi-import.md` — описать security API, поддерживаемые mappings, blockers и revalidation; не обещать непроверенные semantics.
**Acceptance Criteria (из Story 2.10; семантика доступности binding уточнена решением пользователя 2026-09-13):**
@@ -149,6 +150,23 @@ deferred: []
## Review Triage Log
### 2026-09-27 — Review pass
- verdicts: 13 findings — high 9, medium 1, low 2, false 1, maybe-false 0
- findings:
- `[high]` `[patch]` camelCase `clientSecret`/`accessToken` не распознаются — `sensitive_key` приводит регистр, но сравнивает только целые слова или `_`-границы; literal может остаться в source. Исправить распознавание и покрыть canary. В `security_literals.rs` добавлена проверка camelCase; canary-тест проходит.
- `[high]` `[patch]` числовые/boolean credential values пропускаются — `walk` обрабатывает лишь строки, хотя значения под чувствительным ключом тоже являются literal; заменить их безопасным redaction marker и покрыть тестом. В `walk` скаляры под sensitive context заменяются `[REDACTED]`; null оставлен без finding, тест проходит.
- `[high]` `[patch]` JWT в generic example пропускается — путь и значение могут не содержать текстовых маркеров; добавить строгую JWT-эвристику и canary-тест. `is_jwt` проверяет форму и длины сегментов; JWT canary и benign `1.2.3` проверены.
- `[high]` `[patch]` secret в query URL пропускается — проверяется userinfo, но не ключи query вроде `access_token`; отклонять такой source до persistence и проверять отсутствие canary в IR. Добавлена проверка чувствительных query keys с redaction; OAuth URL fixture проверяет и безопасный, и секретный вариант.
- `[high]` `[patch]` Cookie/Set-Cookie example пропускается — response header example без слова `token` не получает sensitive context; покрыть header/cookie примеры. Добавлен контекст Cookie/Set-Cookie и canary-тест.
- `[medium]` `[patch]` credential как ключ объекта example остаётся в pointer/source tree — для распознаваемого token-shaped ключа значение редактируется, а имя ключа нет; редактировать весь example object и указывать безопасный parent pointer. JWT-shaped key приводит к redaction всего example object с parent pointer; canary-тест проходит.
- `[low]` `[patch]` transaction-level auth error не локализуется — `From<RegistryError>` всегда выдаёт английский текст, хотя `create_openapi_import` знает locale; преобразовать этот вариант на границе import API. В import Apply вариант RegistryError преобразуется с locale; Ru integration test проходит.
- `[low]` `[patch]` документация не уточняет zero-based `alternative_index` — код индексирует `Vec` напрямую; добавить одну фразу. В `docs/openapi-import.md` добавлено явное правило нулевой индексации.
- `[high]` `[patch]` AC-12 не проверяет перечисленные literal paths — тесты не содержат camelCase/JWT/query URL/Cookie; добавить canary-fixtures к исправлению сканера. `scanner_redacts_contextual_credentials_non_strings_jwts_and_cookie_examples` и OAuth URL fixture добавлены и прошли.
- `[high]` `[patch]` тест redacted bearer hint не проверяет safe finding — сейчас проверяется только отсутствие canary в IR; добавить проверку source location и сериализованного finding. Проверяются точный safe pointer, код finding и сериализованный report без canary.
- `[high]` `[patch]` edge-case слой подтвердил camelCase/JWT пропуски — тот же `sensitive_key` и `looks_secret_value`, что в строках 1 и 3; покрывается тем же исправлением. Закрыто общей scanner patch и canary-тестами строк 1 и 3.
- `[high]` `[patch]` query API-key parameter с произвольным example пропускается — имя параметра и example обходятся отдельно, `in: query` не включает sensitive context; связать context с именем `api_key` и добавить тест. Сканер использует sibling `name`/`in` для example context; canary-тест проходит.
- `[false]` `[reject]` API rejection вместо redacted preview finding не означает отсутствия finding — `normalize.rs` создаёт `secret_literal_redacted` в IR, а admin API до persistence отклоняет опасный upload с безопасной ошибкой; контракт не требует сохранять небезопасный source ради preview.
## Design Notes
Pure importer хранит schemes/requirements, но не читает Auth Profiles или Secrets. Workspace-safe lookup принадлежит admin service, authoritative проверка непосредственно перед созданием Draft — registry transaction. Текущий единичный profile reference позволяет выдавать blocker для unsupported AND: это прямо предусмотрено AC и не требует расширения runtime до составного auth.
@@ -157,12 +175,15 @@ Pure importer хранит schemes/requirements, но не читает Auth Pro
## Verification
**Commands (не запускались; production code не изменён):**
- `cargo test -p crank-import --all-targets` — PASS: 99 tests; security metadata, inheritance, OR/AND, Swagger 2.0, redaction, JWT/cookie/query credential canaries.
- `cargo test -p admin-api --test integration -- --test-threads=1` — PASS: 88 integration tests; upload, mappings, workspace isolation, Secret availability, replay и digest drift.
- `cargo test -p crank-runtime --all-targets` — PASS: 83 tests; существующий trusted auth path не менялся.
- `cargo test -p crank-registry --test integration import_auth_binding -- --test-threads=1` — PASS: 5 tests; transaction revalidation и no-partial-Draft race.
- `just rust-code-health`, `just dependencies`, `just fmt-check`, `just clippy` — PASS после разнесения oversized модулей, обновления `rustls` в `Cargo.lock` до 0.23.45 и исправления формата теста.
- `just verify` — PASS: полный workspace gate завершился с exit 0 (через pipe/`tee`). Первый прогон остановился на file-size gate, второй — на устаревшей advisory `RUSTSEC-2026-0285`, третий — на `clippy`, четвёртый — на `rustfmt`, пятый и шестой запуск упали в `crank-artifacts::real_process_write_limit_leaves_no_partial_final_blob` из-за перенаправления stdout в обычный файл: дочерний тест ставит `RLIMIT_FSIZE=1`, и его собственный вывод попал под лимит. Это воспроизведено отдельной командой с редиректом; без него scoped target прошёл 7/7. Финальный полный прогон через pipe/`tee` прошёл; код теста не менялся.
- После review patch повторный `just verify` — PASS (exit 0): все workspace tests, fmt, clippy, code health и dependency gate. Включены новые scanner canaries и исправленная локализация ошибки binding.
- `cargo test -p crank-import --all-targets` — schemes, inheritance, OR/AND, deterministic projection и redaction.
- `cargo test -p admin-api --test integration -- --test-threads=1` — реальные upload/binding/revalidation/Apply, no-mutation и workspace isolation.
- `cargo test -p crank-runtime --all-targets` — auth resolution и trusted injection.
- `just verify` — обязательный полный gate после реализации.
**Matrix test audit:** Schemes, Effective security и Alternatives покрыты `crates/crank-import/tests/security_schemes.rs`; Binding, Credential availability, Shared Secret и Stale source — `apps/admin-api/tests/integration/openapi_import/security.rs` и `crates/crank-registry/tests/integration/import_auth_binding.rs`; Secret source — importer scanner tests, primary/external upload integration и telemetry canary tests. Все указанные story tests и полный workspace gate запускались и прошли.
## Auto Run Result
@@ -183,3 +204,24 @@ Blocking condition: intent gap
Основание остановки: правило `step-02-plan.md`, INSTRUCTIONS 5: “Multiple defensible readings of the intent that lead to observably different outcomes, with nothing in the intent to select between them, are an intent gap — do not resolve one by picking a reading.”
Это пробел нормативного scope, а не внешнее действие оператора. AC не требуют покупки домена, выдачи реального API key или действий в vendor console; `awaiting-operator` к данной остановке не применяется.
### 2026-09-27 — повторный Auto Run Result
Status: done
Реализованы typed security schemes и OR/AND requirements в IR/preview, безопасный выбор Auth Profile при import, повторная проверка Secret/profile в транзакции перед созданием Draft, redaction credential literals и совместимость исторического replay. Небезопасный source отклоняется до сохранения artifacts. Документирован API contract; ATDD сценарии и матрица AC покрыты тестами.
Изменённые файлы:
- `crates/crank-import/src/rest/{model,security,security_literals,normalize*,openapi3*,swagger2*,payload,legacy_payload,mod}.rs` — typed security metadata, effective requirements, безопасный scan/redaction и совместимый replay.
- `apps/admin-api/src/{dto,error,service/imports*}.rs` — API выбора Auth Profile, проверка mapping и безопасная локализованная ошибка.
- `crates/crank-registry/src/{model,error,lib,postgres/import_job}.rs` — повторная transaction-level проверка binding до создания Draft.
- `crates/crank-import/tests/security_schemes.rs`, `apps/admin-api/tests/integration/openapi_import*`, `apps/admin-api/tests/integration/openapi_source*`, `crates/crank-registry/tests/integration*` — acceptance и regression tests, включая race, replay и credential canaries.
- `docs/openapi-import.md` — контракт import API и индексация alternatives.
- `_bmad-output/test-artifacts/atdd-{checklist,summary}-2-10-security-schemes-secrets.*` — RED/GREEN и результаты проверок.
- `Cargo.lock` — обновление `rustls` для dependency gate.
- Этот spec — матрица AC, Review Triage Log, Verification и итоговый статус.
Review: 13 findings; 12 исправлены (9 high, 1 medium, 2 low), отложенных нет. Один finding отклонён как false: он утверждал, что API rejection не показывает redacted preview finding, но pure importer формирует `secret_literal_redacted`, а Admin API намеренно отклоняет опасный upload до сохранения source; AC не требует сохранять небезопасный source ради preview. Открытых intent gaps нет. Повторный `just verify` прошёл с exit 0 после всех review patches; importer 99/99, Admin API integration 88/88, registry auth-binding 5/5, runtime 83/83.
Остаточный риск: распознавание произвольных секретов без явного контекста остаётся эвристическим. Рекомендована независимая follow-up проверка scanner coverage при дальнейшем расширении форматов. Внешних действий оператора для AC этой истории нет.
@@ -0,0 +1,137 @@
---
stepsCompleted: ['step-01-preflight-and-context', 'step-02-generation-mode', 'step-03-test-strategy', 'step-04c-aggregate', 'step-05-validate-and-complete']
lastStep: 'step-05-validate-and-complete'
lastSaved: '2026-09-27'
storyId: '2.10'
storyKey: '2-10-security-schemes-secrets'
storyFile: '_bmad-output/implementation-artifacts/spec-2-10-security-schemes-secrets.md'
atddChecklistPath: '_bmad-output/test-artifacts/atdd-checklist-2-10-security-schemes-secrets.md'
generatedTestFiles:
- 'crates/crank-import/tests/security_schemes.rs'
- 'apps/admin-api/tests/integration/openapi_import/security.rs'
- 'apps/admin-api/tests/integration/openapi_import/external_references.rs'
- 'crates/crank-registry/tests/integration/import_auth_binding.rs'
inputDocuments:
- '_bmad-output/implementation-artifacts/spec-2-10-security-schemes-secrets.md'
- '_bmad-output/implementation-artifacts/epic-2-context.md'
- '_bmad-output/implementation-artifacts/1-10-lifecycle-auth-profiles-machine-keys.md'
- '_bmad-output/implementation-artifacts/spec-2-9-http-contract.md'
- '_bmad-output/test-artifacts/test-design-epic-2.md'
- '_bmad-output/test-artifacts/test-design-qa.md'
- '_bmad/tea/config.yaml'
- 'Cargo.toml'
- 'apps/admin-api/Cargo.toml'
- 'crates/crank-import/Cargo.toml'
- 'crates/crank-runtime/Cargo.toml'
acceptanceCriteria:
- id: AC-1
idSource: generated
text: 'Given OpenAPI 3.x components.securitySchemes или Swagger 2.0 securityDefinitions; When importer анализирует schemes; Then bearer HTTP, basic HTTP и API key в header/query/cookie преобразуются в typed security metadata; And source names, locations и применимые format hints сохраняются без credential values.'
- id: AC-2
idSource: generated
text: 'Given global security requirement; When Operation не задаёт собственный override; Then candidate наследует global requirement согласно specification semantics; And operation-level requirement или explicit no-auth корректно заменяет global rule.'
- id: AC-3
idSource: generated
text: 'Given security requirement с несколькими alternatives; When source определяет OR-семантику; Then preview сохраняет все допустимые alternatives и позволяет выбрать поддерживаемый вариант; And importer не объединяет alternatives в ложное обязательное AND.'
- id: AC-4
idSource: generated
text: 'Given security requirement, требующий несколько schemes одновременно; When source определяет AND-семантику; Then candidate сохраняет составное требование, если runtime contract его поддерживает; And иначе affected Operation получает blocker finding с перечислением несохраняемой semantics.'
- id: AC-5
idSource: generated
text: 'Given bearer, basic или API-key requirement; When формируется preview; Then администратору предлагается выбрать совместимый Auth Profile из текущего workspace либо оставить явный unresolved binding; And unresolved required authentication блокирует actionable Draft/Apply для affected Operation.'
- id: AC-6
idSource: generated
text: 'Given выбранный Auth Profile; When создаётся candidate или ImportPlan; Then сохраняется только typed AuthProfileRef и scheme metadata; And raw secret, password, token, API key, hash или encrypted ciphertext не копируется в source snapshot, IR, findings, plan или Operation export.'
- id: AC-7
idSource: generated
text: 'Given OAuth2, OpenID Connect, mutual TLS или неизвестная scheme; When release scope не поддерживает автоматическое mapping; Then importer создаёт explicit manual-configuration/unsupported finding; And не извлекает client secret, token URL credential, example token или vendor-extension secret.'
- id: AC-8
idSource: generated
text: 'Given OpenAPI document содержит literal credential в example, default, extension, URL userinfo или header example; When security analysis выполняется; Then значение не используется как credential и создаёт redacted secret finding; And raw value не появляется в preview UI, logs, traces, metrics или diagnostics.'
- id: AC-9
idSource: generated
text: 'Given Auth Profile отсутствует/удалён, принадлежит другому workspace либо любой необходимый связанный Secret недоступен по существующим правилам active/current version; When preview либо Apply проверяет binding; Then reference отклоняется до создания Draft; And ошибка не раскрывает metadata foreign profile.'
- id: AC-10
idSource: generated
text: 'Given профили A и B используют один активный Secret с доступной текущей версией; When проверяются binding этих профилей; Then оба binding допустимы при выполнении остальных проверок; And после отключения общего Secret оба binding отклоняются до создания Draft; тест с disabled Secret не является доказательством независимого отзыва Auth Profile, который остаётся вне scope.'
- id: AC-11
idSource: generated
text: 'Given исходная security scheme изменилась после preview; When старый ImportPlan пытаются применить к новому source; Then plan digest mismatch блокирует Apply; And требуется новый preview и явное подтверждение Auth Profile mappings.'
- id: AC-12
idSource: generated
text: 'Given security scheme test suite; When выполняются fixtures и negative tests; Then покрыты global/operation overrides, no-auth, bearer/basic/API-key locations, OR/AND requirements, OAuth/OpenID/unknown schemes, secret-like examples, missing/deleted и cross-workspace profile refs, недоступные Secrets по правилам active/current version и блокировка обоих профилей при отключении общего Secret; And redaction tests и `just verify` проходят.'
---
# ATDD Checklist — Story 2.10: Security Schemes and Secrets
## Preflight
- **Approval/source:** the approved, frozen acceptance contract is the Story 2.10 spec. Its recorded 2026-09-13 decision defines binding availability through the existing active/current Secret rules; it does not add independent Auth Profile revocation.
- **Story identity:** ID `2.10`; canonical key `2-10-security-schemes-secrets` from the spec filename.
- **Stack and harness:** repository is Rust backend plus an existing UI. This story's approved scope is API/parser/runtime, so primary level is Rust unit/integration/API contract; UI/E2E belongs to Story 2.11. `cargo test` and `just verify` are configured.
- **Risk and design:** P0, FR-10, E2-R2 (score 9), seed scenarios `2.10-API-A` and `2.10-API-B`. The epic test design calls for preserving security semantics and rejecting unsupported/foreign bindings, with secret canaries absent from API/IR/plan/export surfaces.
- **Implementation observation:** security metadata now flows through typed IR/preview; Admin API accepts profile mappings, rejects unsafe literals before persistence, and validates binding availability within Apply. Current verification evidence is recorded below and is scoped to the commands actually run.
- **Generation mode:** backend/API source analysis. No browser recording; no Story 2.11 UI scaffolds.
- **Contract boundary:** implementation added focused tests in the existing importer, Admin API and registry harnesses. No skipped or placeholder tests are used as evidence.
## Acceptance Criteria Snapshot and Scenario Mapping
AC IDs below are deterministic IDs assigned in source order because the spec does not declare `AC-<n>` IDs. The exact snapshot is also stored in frontmatter.
| Scenario | AC | Test level / priority | Primary reusable test path | Required scenario and current status |
|---|---|---|---|---|
| 2.10-API-A1 | AC-1 | Importer unit / P0 | `security_alternatives_preserve_or_and_and_preview_exposes_typed_schemes`; `swagger2_security_definitions_project_basic_and_api_key_header_and_query` in `crates/crank-import/tests/security_schemes.rs` | **PASS** in importer suite: OpenAPI typed scheme metadata and Swagger 2.0 basic/API-key locations are projected. |
| 2.10-API-A2 | AC-2 | Importer unit / P0 | `security_requirements_inherit_and_operation_empty_array_disables_auth` in `crates/crank-import/tests/security_schemes.rs` | **PASS** in importer suite: global inheritance, multi-scheme operation requirement, explicit empty override. |
| 2.10-API-A3 | AC-3 | Importer + preview API / P0 | `security_alternatives_preserve_or_and_and_preview_exposes_typed_schemes`; `selected_supported_or_and_explicit_no_auth_alternatives_apply_without_collapsing_semantics` in `apps/admin-api/tests/integration/openapi_import/security.rs` | **PASS** in importer and Admin API integration suites: OR alternatives remain distinct and selected supported option applies. |
| 2.10-API-A4 | AC-4 | Importer unit + preview API / P0 | `security_requirements_inherit_and_operation_empty_array_disables_auth`; `security_alternatives_preserve_or_and_and_preview_exposes_typed_schemes` in `crates/crank-import/tests/security_schemes.rs` | **PASS** in importer suite: AND composition is retained and unsupported composition becomes a blocker. |
| 2.10-API-B1 | AC-5 | Admin API integration / P0 | `auth_profiles_are_workspace_scoped_revalidated_and_shared_secret_availability_is_current`; `selected_supported_or_and_explicit_no_auth_alternatives_apply_without_collapsing_semantics` in `apps/admin-api/tests/integration/openapi_import/security.rs` | **PASS** in Admin API integration suite: choices are workspace-scoped, supported mapping applies, unresolved required auth is blocked. |
| 2.10-API-B2 | AC-6 | Importer + API/registry integration / P0 | `ac_6_never_copies_literal_secret_canaries_into_normalized_ir` in `crates/crank-import/tests/security_schemes.rs`; `auth_profiles_are_workspace_scoped_revalidated_and_shared_secret_availability_is_current` in `apps/admin-api/tests/integration/openapi_import/security.rs`; `no_auth_requires_no_profile_reference` in `crates/crank-registry/tests/integration/import_auth_binding.rs` | **PASS** in importer, Admin API and registry suites. Tests assert canary/ciphertext/hash absence from IR/serialized Operation and no profile ref for no-auth. |
| 2.10-API-A5 | AC-7 | Importer unit / P0 | `unsupported_security_schemes_create_blockers_without_copying_credentials` in `crates/crank-import/tests/security_schemes.rs` | **PASS** in importer suite: OAuth/OIDC/mTLS/unknown produce explicit unsupported/blocker findings without credential extraction. |
| 2.10-API-A6 | AC-8 | Importer + Admin API integration / P0 | `scanner_finds_examples_defaults_extensions_and_url_userinfo_without_values`; `scanner_redacts_contextual_credentials_non_strings_jwts_and_cookie_examples`; `scanner_keeps_version_examples_and_null_credential_defaults`; `unsafe_bearer_format_canary_is_redacted_and_not_projected` in `crates/crank-import/tests/security_schemes.rs`; `literal_credential_is_rejected_before_any_import_artifact_or_job_is_created` in Admin API `security.rs`; `external_literal_credential_is_rejected_before_snapshot_persistence` in `external_references.rs` | **PASS** in importer/Admin API suites: canaries redact from findings and literal credentials are rejected before primary or external source persistence. |
| 2.10-API-B3 | AC-9 | Admin API + registry integration / P0 | `auth_profiles_are_workspace_scoped_revalidated_and_shared_secret_availability_is_current` in Admin API `security.rs`; `missing_and_foreign_profiles_have_the_same_safe_error_and_insert_no_operation`; `apply_rejects_kind_parameter_and_missing_current_version_before_mutation` in `crates/crank-registry/tests/integration/import_auth_binding.rs` | **PASS** in Admin API and registry suites. Foreign/missing errors are indistinguishable and no Draft mutation occurs. |
| 2.10-API-B4 | AC-10 | Admin API + registry integration / P0 | `auth_profiles_are_workspace_scoped_revalidated_and_shared_secret_availability_is_current` in Admin API `security.rs`; `apply_accepts_current_compatible_profile_and_shared_secret_then_rejects_disabled_secret` in `crates/crank-registry/tests/integration/import_auth_binding.rs` | **PASS** in Admin API and registry suites. Shared Secret permits both profiles while active and rejects them when disabled; independent profile revocation is not asserted. |
| 2.10-API-B5 | AC-11 | Admin API integration / P0 | `changed_security_scheme_after_preview_fails_digest_check_without_draft_mutation` in `apps/admin-api/tests/integration/openapi_import/security.rs` | **PASS** in Admin API integration suite: stale digest blocks Apply without creating Draft. |
| 2.10-API-GATE | AC-12 | Suite / P0 | `cargo test -p crank-import --all-targets`; `cargo test -p admin-api --test integration openapi_import -- --test-threads=1`; `cargo test -p crank-registry --test integration import_auth_binding -- --test-threads=1`; `just verify` | Importer, Admin API and registry suites **PASS**; final `just verify` **PASS**. Earlier failed attempts were repaired; the unrelated artifact subprocess failure was caused by redirecting stdout to a regular file and disappeared when the gate ran through a pipe. |
### Reuse inventory (not a claim of AC coverage)
- Importer behavior patterns: `crates/crank-import/tests/security_schemes.rs`, `swagger2_contract.rs`, `unit.rs`, `preview.rs`, and `http_replay.rs`.
- API/import persistence patterns: `apps/admin-api/tests/integration/openapi_import/http_contract.rs` and `external_references.rs`.
- Runtime auth injection patterns: `crates/crank-runtime/tests/stages.rs` and `integration/confirmation.rs`.
- The AC rows point to the actual tests observed in the current implementation. Importer, Admin API and registry test runs are complete; broad `just verify` has now passed.
## Test Strategy and TDD State
- **Primary level:** importer unit tests for pure OpenAPI semantics; Admin API + registry integration for profile scope, secret availability, transaction revalidation, and no-Draft guarantees; runtime tests only for unchanged trusted credential injection behavior.
- **Duplicate coverage:** do not duplicate existing general reference, source digest, redaction, or runtime-auth tests. Add assertions only for the Story 2.10 security contract and its import boundary.
- **Fixture requirements:** OAS 3.0, OAS 3.1, and Swagger 2.0 docs; deterministic secret canaries in example/default/extension/userinfo/header-example positions; workspace A/B profiles sharing one Secret; active/current and disabled Secret states; source mutation after preview. Never use customer credentials.
- **Assertion order:** primary assertion checks the exact promised value/state (typed scheme/effective requirement, blocker, absence of Draft, or digest rejection) before broad serialized-object checks. Setup results from an unimplemented endpoint remain opaque until the criterion assertion.
- **TDD record:** the initial two active tests genuinely failed before implementation (historical RED below); after implementation both now pass. No skipped tests are counted as RED or GREEN evidence.
## Handoff
- Story-level importer, Admin API and registry evidence is recorded above; all scenarios mapped to AC-1..AC-11 passed in those suites.
- AC-12 is satisfied: full `just verify` completed successfully. Earlier gate failures were fixed or traced to the output-redirection harness.
- Runtime suite: root reports `cargo test -p crank-runtime --all-targets` passed (83 tests).
## Historical RED Evidence (Before Implementation)
`cargo test -p crank-import --test normalization_details -- --nocapture` failed as intended: 11 passed, 2 failed, 0 ignored. AC-1 failed because `WorkspaceBearer` was absent from operation projection; AC-6 failed because `atdd-secret-canary-2-10` appeared in normalized IR. These failures were fixed by implementation and the tests now pass.
## Verification Results (Current Worktree)
| Command | Result | Interpretation |
|---|---|---|
| `cargo test -p crank-import --all-targets` | **PASS** — 99 tests passed, 0 failed, 0 ignored. | Includes security normalization, OpenAPI/Swagger mapping and redaction cases after review fixes. |
| `cargo test -p admin-api --test integration openapi_import -- --test-threads=1` | **PASS** — 24 passed, 0 failed, 0 ignored; 64 filtered out. | Includes mapping choices, literal-credential rejection, workspace/profile revalidation, shared Secret availability and digest drift. |
| `cargo test -p crank-registry --test integration import_auth_binding -- --test-threads=1` | **PASS** — 5 passed, 0 failed, 0 ignored; 95 filtered out. | Includes transaction-level profile, Secret state, no-auth and no-partial-mutation checks. |
| `cargo test -p crank-runtime --all-targets` | **PASS** — 83 passed, 0 failed, 0 ignored (result reported by root). | Runtime regression suite is green; no security scheme behavior is implemented in the runtime crate. |
| `just verify` | **PASS** — full workspace gate finished with exit 0, including fmt, clippy, dependencies and all workspace tests. | Earlier failures were corrected; artifact subprocess needed a pipe instead of regular-file stdout. |
| `git diff --check` | **PASS**. | No whitespace errors in current diff. |
## Completion Summary
- Story ID/key: `2.10` / `2-10-security-schemes-secrets`.
- AC snapshot: 12 source criteria mapped one-to-one to scenario IDs.
- Tests: security-specific tests were added to existing importer, Admin API and registry suites. The scenario table maps each AC to exact test names and package-level evidence.
- Current evidence after review fixes: importer 99/99, Admin API integration 88/88, registry auth-binding integration 5/5. Historical RED is retained separately; repeat full `just verify` passed.
@@ -0,0 +1,81 @@
{
"story_id": "2.10",
"story_key": "2-10-security-schemes-secrets",
"story_file": "_bmad-output/implementation-artifacts/spec-2-10-security-schemes-secrets.md",
"checklist": "_bmad-output/test-artifacts/atdd-checklist-2-10-security-schemes-secrets.md",
"tdd_phase": "GREEN",
"acceptance_criteria_total": 12,
"active_red_tests": 0,
"historical_red_tests": [
{
"scenario": "2.10-API-A1",
"acceptance_criterion": "AC-1",
"test": "security_schemes::ac_1_projects_openapi_security_scheme_identity_onto_operation_metadata",
"result": "FAIL_BEFORE_IMPLEMENTATION_THEN_PASS",
"observed": "operation projection does not contain WorkspaceBearer"
},
{
"scenario": "2.10-API-B2",
"acceptance_criterion": "AC-6",
"test": "security_schemes::ac_6_never_copies_literal_secret_canaries_into_normalized_ir",
"result": "FAIL_BEFORE_IMPLEMENTATION_THEN_PASS",
"observed": "normalized IR contains atdd-secret-canary-2-10"
}
],
"pending_acceptance_criteria": [],
"generated_test_files": [
"crates/crank-import/tests/security_schemes.rs",
"apps/admin-api/tests/integration/openapi_import/security.rs",
"apps/admin-api/tests/integration/openapi_import/external_references.rs",
"crates/crank-registry/tests/integration/import_auth_binding.rs"
],
"existing_suite_baseline": {
"command": "cargo test -p crank-import --all-targets",
"result": "PASS",
"passed": 99,
"failed": 0,
"ignored": 0,
"timing": "current implementation"
},
"other_passed_suites": [
{
"command": "cargo test -p admin-api --test integration openapi_import -- --test-threads=1",
"result": "PASS",
"passed": 24,
"failed": 0,
"ignored": 0,
"filtered_out": 64
},
{
"command": "cargo test -p crank-registry --test integration import_auth_binding -- --test-threads=1",
"result": "PASS",
"passed": 5,
"failed": 0,
"ignored": 0,
"filtered_out": 95
},
{
"command": "cargo test -p crank-runtime --all-targets",
"result": "PASS",
"passed": 83,
"failed": 0,
"ignored": 0,
"reported_by": "root"
}
],
"other_checks": [
{
"command": "just verify",
"result": "PASS",
"detail": "Repeat full workspace gate after review fixes exited 0; earlier file-size, advisory, fmt/clippy and stdout-redirection failures were resolved."
},
{
"command": "git diff --check",
"result": "PASS"
}
],
"all_tests_skipped": false,
"expected_to_fail": false,
"e2e_tests": 0,
"note": "Historical RED evidence is preserved; all active acceptance tests and the final just verify gate pass. No skipped scaffold is counted as RED."
}
+2
View File
@@ -52,7 +52,9 @@ crank-test-support = { path = "../../crates/crank-test-support" }
metrics.workspace = true
metrics-util = "0.20.4"
opentelemetry.workspace = true
opentelemetry-proto.workspace = true
opentelemetry_sdk.workspace = true
prost.workspace = true
reqwest.workspace = true
serial_test = "3"
tower.workspace = true
+38 -8
View File
@@ -3,6 +3,7 @@ FROM rust:1.96.1-bookworm AS builder
WORKDIR /app
COPY Cargo.toml Cargo.lock ./
COPY vendor ./vendor
COPY .sqlx ./.sqlx
COPY apps ./apps
COPY crates ./crates
@@ -14,23 +15,52 @@ RUN --mount=type=cache,id=crank-admin-cargo-registry,target=/usr/local/cargo/reg
&& cp /app/target/release/admin-api /tmp/admin-api \
&& cp /app/target/release/crank-migrate /tmp/crank-migrate
FROM debian:bookworm-slim
# Trusted CA bundle source for the package stage. The slim image ships no CA
# certificates, so the HTTPS Debian mirror can only be reached after seeding
# them; the Rust base image provides the bundle without rebuilding the app.
FROM rust:1.96.1-bookworm AS ca-bundle
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
RUN test -s /etc/ssl/certs/ca-certificates.crt
WORKDIR /app
# Package stage: install the security-refreshed Debian packages, then assemble
# the minimal runtime rootfs. Kept independent of the Rust builder so it can be
# built and reviewed on its own.
FROM debian:bookworm-slim AS runtime-rootfs
ARG CRANK_SECURITY_REFRESH
COPY --from=ca-bundle /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
COPY scripts/prepare-runtime-rootfs.sh /usr/local/bin/prepare-runtime-rootfs
RUN sed -i 's|http://deb.debian.org|https://deb.debian.org|g' /etc/apt/sources.list.d/debian.sources \
&& apt-get update \
&& apt-get install -y --no-install-recommends --only-upgrade \
base-files libc6 libgcc-s1 gcc-12-base bash dash libtinfo6 libselinux1 libpcre2-8-0 coreutils \
&& rm -rf /var/lib/apt/lists/* \
&& dpkg --compare-versions "$(dpkg-query -W -f='${Version}' libpcre2-8-0)" ge '10.42-1+deb12u2' \
&& sh /usr/local/bin/prepare-runtime-rootfs /runtime \
&& echo "crank-security-refresh=${CRANK_SECURITY_REFRESH}"
COPY apps/admin-api/docker-entrypoint.sh /runtime/usr/local/bin/crank-admin-entrypoint
COPY scripts/docker-http-healthcheck.sh /runtime/usr/local/bin/crank-http-healthcheck
RUN chmod 0755 /runtime/usr/local/bin/crank-admin-entrypoint \
&& chmod 0755 /runtime/usr/local/bin/crank-http-healthcheck
FROM scratch
COPY --from=ca-bundle /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
COPY --from=runtime-rootfs /runtime /
COPY --from=builder /tmp/admin-api /usr/local/bin/admin-api
COPY --from=builder /tmp/crank-migrate /usr/local/bin/crank-migrate
COPY apps/admin-api/docker-entrypoint.sh /usr/local/bin/crank-admin-entrypoint
COPY scripts/docker-http-healthcheck.sh /usr/local/bin/crank-http-healthcheck
RUN test -s /etc/ssl/certs/ca-certificates.crt \
&& chmod 0755 /usr/local/bin/crank-admin-entrypoint /usr/local/bin/crank-http-healthcheck
ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
ENV CRANK_ADMIN_BIND=0.0.0.0:3001
ENV CRANK_STORAGE_ROOT=/var/lib/crank/storage
WORKDIR /app
EXPOSE 3001
ENTRYPOINT ["/usr/local/bin/crank-admin-entrypoint"]
+12 -1
View File
@@ -4,7 +4,7 @@ set -eu
# Docker creates a fresh named volume as root:root 0755. The artifact store
# deliberately rejects that mode: before starting the API, provision exactly
# the private root its pinned-directory checks require.
if [ "$#" -gt 0 ] && [ "$1" = "admin-api" ]; then
provision_storage_root() {
storage_root="${CRANK_STORAGE_ROOT:-/var/lib/crank/storage}"
case "$storage_root" in
/*) ;;
@@ -20,6 +20,17 @@ if [ "$#" -gt 0 ] && [ "$1" = "admin-api" ]; then
umask 077
mkdir -p -- "$storage_root"
chmod 0700 -- "$storage_root"
}
# The dedicated init service calls this entrypoint as `crank-storage-init`; it
# provisions the artifact root and exits without running a server binary.
if [ "${1:-}" = "crank-storage-init" ]; then
provision_storage_root
exit 0
fi
if [ "${1:-}" = "admin-api" ]; then
provision_storage_root
fi
exec "$@"
@@ -0,0 +1,49 @@
//! Read-only database observation for the local Playwright harness.
//! This example is never packaged as an application endpoint or executable.
#[tokio::main]
async fn main() {
let workspace = std::env::args().nth(1).expect("test workspace argument");
assert!(
!workspace.is_empty()
&& workspace.len() <= 128
&& workspace
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || b"_-".contains(&byte)),
"invalid test workspace argument"
);
let config = crank_config::parse_migrator(
crank_config::ConfigSource::from_os_for_migrator().expect("test configuration source"),
)
.expect("test database configuration");
let database = config.database;
let options = if let Some(url) = &database.url {
url.expose_secret()
.parse::<sqlx::postgres::PgConnectOptions>()
.expect("test database URL")
} else {
sqlx::postgres::PgConnectOptions::new()
.host(&database.host)
.port(database.port)
.database(&database.database)
.username(&database.username)
.password(database.password.expose_secret())
};
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(1)
.connect_with(options)
.await
.expect("test database connection");
let (sources, operations, versions): (i64, i64, i64) = sqlx::query_as(
"select
(select count(*) from artifact_sources where workspace_id=$1),
(select count(*) from operations where workspace_id=$1),
(select count(*) from operation_versions v
join operations o on o.id=v.operation_id where o.workspace_id=$1)",
)
.bind(workspace)
.fetch_one(&pool)
.await
.expect("test storage observation");
println!("{{\"sources\":{sources},\"operations\":{operations},\"versions\":{versions}}}");
}
+28 -2
View File
@@ -27,12 +27,18 @@ use crate::{
},
auth_profiles::{create_auth_profile, get_auth_profile, list_auth_profiles},
capabilities::get_capabilities,
imports::{create_openapi_import, preview_openapi_import},
imports::{
apply_openapi_import_plan, create_openapi_import, create_openapi_import_plan,
preview_openapi_import, revalidate_openapi_import_plan,
},
observability::{
approve_approval, deny_approval, export_logs_csv, export_usage_csv, get_agent_usage,
get_approval, get_log, get_operation_usage, get_usage, list_approvals, list_logs,
},
onboarding::{get_onboarding, record_onboarding_event, reset_onboarding_selection},
onboarding::{
get_onboarding, record_onboarding_event, register_onboarding_import_context,
reset_onboarding_selection, select_onboarding_import_draft,
},
operations::{
analyze_operation_quality, archive_operation, create_operation, create_version,
delete_operation, export_operation, generate_draft, get_operation,
@@ -58,6 +64,18 @@ pub fn build_app(state: AppState) -> Router {
"/imports/openapi/{job_id}/create",
post(create_openapi_import),
)
.route(
"/imports/openapi/{job_id}/plans",
post(create_openapi_import_plan).layer(DefaultBodyLimit::max(16 * 1024 * 1024)),
)
.route(
"/imports/openapi/plans/{plan_id}",
get(revalidate_openapi_import_plan),
)
.route(
"/imports/openapi/{plan_id}/apply",
post(apply_openapi_import_plan).layer(DefaultBodyLimit::max(16 * 1024)),
)
.route(
"/operations/analyze-quality",
post(analyze_operation_quality),
@@ -158,6 +176,14 @@ pub fn build_app(state: AppState) -> Router {
.route(
"/onboarding/reset-selection",
post(reset_onboarding_selection),
)
.route(
"/onboarding/import-context",
post(register_onboarding_import_context).layer(DefaultBodyLimit::max(16 * 1024)),
)
.route(
"/onboarding/select-draft",
post(select_onboarding_import_draft).layer(DefaultBodyLimit::max(16 * 1024)),
);
let workspace_root_router = Router::new()
+13
View File
@@ -186,6 +186,19 @@ async fn run() -> Result<ExitCode, CliError> {
})
.collect::<Vec<_>>();
let plan = json!({ "schema_version": 1, "sequence": sequence });
if option == Some("--target-version") {
let target_version = plan["sequence"]
.as_array()
.and_then(|sequence| sequence.last())
.and_then(|migration| migration["version"].as_i64())
.ok_or(CliError::new(
"migration_sequence_invalid",
"plan.target_version",
"contact_operator",
))?;
println!("{target_version}");
return Ok(ExitCode::SUCCESS);
}
if option == Some("--check") {
let bytes = std::fs::read("docs/schemas/migration-sequence.json")
.map_err(|_| CliError::new("contract_drift", "plan.read", "contact_operator"))?;
+161
View File
@@ -353,6 +353,35 @@ pub struct OnboardingResponse {
pub platform_api_key_id: Option<String>,
pub mcp_endpoint: Option<String>,
pub first_call: Option<OnboardingFirstCallEvidence>,
pub import_context: Option<OnboardingImportContextView>,
}
#[derive(Clone, Debug, Serialize)]
pub struct OnboardingImportChoiceView {
pub key: String,
pub name: String,
pub outcome: String,
pub operation_id: Option<String>,
pub version: Option<u32>,
pub reason: Option<String>,
pub selectable: bool,
}
#[derive(Clone, Debug, Serialize)]
pub struct OnboardingImportDriftView {
pub reason: String,
pub current_operation_version: Option<u32>,
}
#[derive(Clone, Debug, Serialize)]
pub struct OnboardingImportContextView {
pub application_idempotency_key: String,
pub plan_digest: String,
pub report: Value,
pub choices: Vec<OnboardingImportChoiceView>,
pub selected_operation_id: Option<String>,
pub selected_operation_version: Option<u32>,
pub drift: Option<OnboardingImportDriftView>,
}
#[derive(Clone, Debug, Serialize)]
@@ -375,6 +404,38 @@ pub struct ResetOnboardingSelectionResponse {
pub onboarding: OnboardingResponse,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RegisterOnboardingImportContextPayload {
pub application_idempotency_key: String,
pub plan_digest: String,
pub expected_revision: i64,
}
#[derive(Clone, Debug, Serialize)]
pub struct RegisterOnboardingImportContextResponse {
pub registered: bool,
#[serde(flatten)]
pub onboarding: OnboardingResponse,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SelectOnboardingImportDraftPayload {
pub application_idempotency_key: String,
pub plan_digest: String,
pub operation_id: String,
pub operation_version: u32,
pub expected_revision: i64,
}
#[derive(Clone, Debug, Serialize)]
pub struct SelectOnboardingImportDraftResponse {
pub selected: bool,
#[serde(flatten)]
pub onboarding: OnboardingResponse,
}
#[derive(Clone, Debug, Serialize)]
pub struct WorkspaceCatalogSnapshotResponse {
pub kind: String,
@@ -542,6 +603,23 @@ pub struct OpenApiImportPreviewResponse {
pub job_id: String,
pub expires_at: String,
pub preview: crank_import::rest::ImportPreview,
#[serde(default)]
pub security_profile_choices: Vec<OpenApiImportSecurityProfileChoice>,
}
#[derive(Clone, Debug, Serialize)]
pub struct OpenApiImportSecurityProfileChoice {
pub operation_key: String,
pub alternative_index: usize,
pub schemes: Vec<String>,
pub profiles: Vec<OpenApiImportAuthProfileChoice>,
}
#[derive(Clone, Debug, Serialize)]
pub struct OpenApiImportAuthProfileChoice {
pub id: String,
pub name: String,
pub kind: crank_core::AuthKind,
}
#[derive(Clone, Debug, Deserialize)]
@@ -575,6 +653,89 @@ pub struct OpenApiImportSkippedOperation {
pub reason: String,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OpenApiImportPlanCreatePayload {
#[serde(default = "default_openapi_plan_selection_mode")]
pub selection_mode: String,
#[serde(default)]
pub selected_operation_keys: Vec<String>,
#[serde(default)]
pub server_url: Option<String>,
#[serde(default)]
pub decisions: Vec<OpenApiImportPlanDecision>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OpenApiImportPlanApplyPayload {
pub plan_digest: String,
pub idempotency_key: String,
}
fn default_openapi_plan_selection_mode() -> String {
"full".to_owned()
}
#[derive(Clone, Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OpenApiImportPlanDecision {
pub operation_key: String,
pub action: String,
#[serde(default)]
pub target_operation_id: Option<String>,
#[serde(default)]
pub confirmed_name: Option<String>,
#[serde(default)]
pub auth_profile_id: Option<String>,
#[serde(default)]
pub security_alternative_index: Option<usize>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct OpenApiImportPlanCounts {
pub selected: usize,
pub excluded: usize,
pub actionable: usize,
pub blocked: usize,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct OpenApiImportPlanCandidateView {
pub key: String,
pub name: String,
pub state: String,
pub action: Option<String>,
pub target_operation_id: Option<String>,
pub confirmed_name: Option<String>,
pub auth_profile_id: Option<String>,
pub security_alternative_index: Option<usize>,
pub reason: Option<String>,
}
#[derive(Clone, Debug, Serialize)]
pub struct OpenApiImportPlanCreateResponse {
pub plan_reference: String,
pub plan_digest: String,
pub catalog_revision: String,
pub support_matrix_version: String,
pub expires_at: String,
pub selection_mode: String,
pub counts: OpenApiImportPlanCounts,
pub candidates: Vec<OpenApiImportPlanCandidateView>,
}
#[derive(Clone, Debug, Serialize)]
pub struct OpenApiImportPlanRevalidationResponse {
pub plan_reference: String,
pub plan_digest: String,
pub revalidation_status: String,
pub revalidation_required: bool,
pub reason: Option<String>,
pub counts: OpenApiImportPlanCounts,
pub candidates: Vec<OpenApiImportPlanCandidateView>,
}
#[derive(Clone, Debug, Serialize)]
pub struct CreatedOperationResponse {
pub operation_id: String,
+111
View File
@@ -664,6 +664,29 @@ impl From<RegistryError> for ApiError {
"onboarding domain steps are not complete",
json!({"error_code":"onboarding_incomplete"}),
),
RegistryError::OnboardingImportDraftUnavailable => Self::unprocessable_with_context(
"the requested operation is not an actionable imported Draft",
json!({
"error_code":"onboarding_import_draft_unavailable",
"recovery":"reload_import_report"
}),
),
RegistryError::OnboardingImportApplicationUnavailable => {
Self::unprocessable_with_context(
"no committed import apply report matches the requested application",
json!({
"error_code":"onboarding_import_application_unavailable",
"recovery":"reload_import_report"
}),
)
}
RegistryError::OnboardingImportContextUnavailable => Self::unprocessable_with_context(
"the workspace has no durable import context for the requested application",
json!({
"error_code":"onboarding_import_context_unavailable",
"recovery":"register_import_context"
}),
),
RegistryError::InvalidEnumRepresentation { field } => Self::validation_with_context(
format!("unsupported enum representation for field {field}"),
json!({ "field": field }),
@@ -687,6 +710,94 @@ impl From<RegistryError> for ApiError {
format!("import job {job_id} was already applied with different parameters"),
json!({ "job_id": job_id }),
),
RegistryError::InvalidImportPlan { field } => Self::validation_with_context(
format!("invalid import plan input for field {field}"),
json!({
"field": field,
"error_code": "import_plan_invalid_input"
}),
),
RegistryError::ImportPlanConflict { plan_id } => Self::conflict_with_context(
format!("import plan {plan_id} already exists with different material"),
json!({
"plan_id": plan_id,
"error_code": "import_plan_conflict",
"recovery": "repreview_required"
}),
),
RegistryError::ImportPlanJobUnavailable { job_id } => Self::not_found_with_context(
format!("import job {job_id} is unavailable for planning"),
json!({ "job_id": job_id, "error_code": "import_plan_job_unavailable" }),
),
RegistryError::ImportPlanJobTerminal { job_id }
| RegistryError::ImportPlanJobExpired { job_id } => Self::conflict_with_context(
format!("import job {job_id} is not in planning state"),
json!({
"job_id": job_id,
"error_code": "import_plan_job_terminal",
"recovery": "repreview_required",
"repreview_required": true
}),
),
RegistryError::ImportPlanNotFound { .. } => Self::not_found_with_context(
"import plan was not found in this workspace",
json!({ "error_code": "import_plan_not_found" }),
),
RegistryError::ImportPlanExpired { .. } => Self::conflict_with_context(
"import plan has expired; create a fresh preview",
json!({
"error_code": "import_plan_expired",
"recovery": "repreview_required",
"repreview_required": true
}),
),
RegistryError::ImportPlanPayloadCorrupt { .. } => Self::conflict_with_context(
"import plan is invalid; create a fresh preview",
json!({
"error_code": "import_plan_payload_invalid",
"recovery": "repreview_required",
"repreview_required": true
}),
),
RegistryError::ImportPlanFingerprintStale { .. } => Self::conflict_with_context(
"import plan no longer matches the verified preview; create a fresh preview",
json!({
"error_code": "import_plan_fingerprint_stale",
"recovery": "repreview_required",
"repreview_required": true
}),
),
RegistryError::ImportPlanKeyDigestConflict { .. } => Self::conflict_with_context(
"idempotency key was already committed for different plan material",
json!({
"error_code": "import_plan_key_digest_conflict",
"recovery": "repreview_required",
"repreview_required": true
}),
),
RegistryError::ImportPlanNameConflict { .. } => Self::conflict_with_context(
"an operation name changed after the plan was created",
json!({
"error_code": "import_plan_name_conflict",
"recovery": "confirm_skip_rename_or_new_version"
}),
),
RegistryError::ImportPlanTargetStale { .. } => Self::conflict_with_context(
"an operation changed after the plan was created; create a fresh preview",
json!({
"error_code": "import_plan_target_stale",
"recovery": "repreview_required",
"repreview_required": true
}),
),
RegistryError::ImportPlanAuthUnavailable { .. } => Self::conflict_with_context(
"an authentication profile is unavailable; create a fresh preview",
json!({
"error_code": "import_plan_auth_unavailable",
"recovery": "repreview_required",
"repreview_required": true
}),
),
RegistryError::SourceNotFound { .. } => Self::not_found_with_context(
"artifact source was not found",
json!({
@@ -12,6 +12,7 @@ use std::{
use async_trait::async_trait;
use crank_artifacts::{ReconciliationRegistration, RegisteredArtifact};
use crank_registry::MigrationAuthority;
use sqlx::Row;
use super::*;
@@ -688,3 +689,6 @@ async fn expired_claim_cursor_prevents_unsafe_prefix_starvation_across_ticks() {
.unwrap();
assert_eq!(second_lifecycle, "unavailable");
}
#[path = "tests/commit_failure.rs"]
mod commit_failure;
@@ -0,0 +1,149 @@
use super::*;
#[tokio::test]
async fn finalize_commit_failure_stays_retryable_and_recovers_on_a_fresh_cycle() {
let database_url =
crank_test_support::postgres_schema_url("admin_reconciliation_commit_failure").await;
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
MigrationAuthority::apply(&pool).await.unwrap();
let registry = PostgresRegistry::connect(&database_url).await.unwrap();
let root = TestRoot::new();
let store = ArtifactStore::open(&root.0).unwrap();
let now = OffsetDateTime::now_utc();
let artifact = store
.put_registered(b"commit-failure physical absence\n")
.unwrap();
let outcome = registry
.claim_artifact_reconciliation(ClaimArtifactReconciliationRequest {
artifact: &artifact,
token: ArtifactClaimToken::generate(),
claimed_at: now - time::Duration::minutes(10),
lease_expires_at: now - time::Duration::minutes(5),
detached_grace: time::Duration::hours(24),
})
.await
.unwrap();
assert!(matches!(outcome, ArtifactClaimOutcome::Claimed(_)));
remove_registered_artifact(&store, &artifact);
sqlx::query(
"update artifact_blobs
set claim_expires_at = clock_timestamp() - interval '1 second'
where digest = $1",
)
.bind(artifact.artifact_ref().digest_hex())
.execute(registry.pool())
.await
.unwrap();
// A deferred constraint trigger fails the COMMIT that records
// `unavailable`, modelling a real failure after the physical unlink that
// removed the last bytes already succeeded. It lives only in this isolated
// test schema.
sqlx::raw_sql(
"create function crank_test_fail_unavailable() returns trigger language plpgsql as $$
begin
if new.storage_lifecycle = 'unavailable' then
raise exception 'injected finalize commit failure';
end if;
return new;
end $$;
create constraint trigger crank_test_fail_unavailable_guard
after update on artifact_blobs
deferrable initially deferred
for each row execute function crank_test_fail_unavailable();",
)
.execute(registry.pool())
.await
.unwrap();
let backend = PostgresReconciliationBackend::new(registry.clone(), Arc::new(store.clone()));
let mut coordinator = ReconciliationCoordinator::new(backend);
let failed = coordinator.tick().await.unwrap();
// A real commit failure must surface as retryable work, never as idle.
assert!(failed.retryable);
assert_eq!(failed.mutation_attempts, 1);
assert_eq!(
store
.reconciliation_presence(artifact.artifact_ref())
.unwrap(),
ReconciliationPresence::Absent
);
let retained = sqlx::query(
"select claim_token, claim_expires_at, storage_lifecycle
from artifact_blobs where digest = $1",
)
.bind(artifact.artifact_ref().digest_hex())
.fetch_one(registry.pool())
.await
.unwrap();
assert!(
retained
.try_get::<Option<String>, _>("claim_token")
.unwrap()
.is_some(),
"the failed commit must roll back the claim clear"
);
assert!(
retained
.try_get::<Option<time::OffsetDateTime>, _>("claim_expires_at")
.unwrap()
.is_some()
);
assert_eq!(
retained.get::<String, _>("storage_lifecycle"),
"available",
"the failed commit must roll back the unavailable transition"
);
// Removing the injected trigger and retrying a fresh coordinator clears the
// retained claim and records the confirmed absence as `unavailable`.
sqlx::raw_sql(
"drop trigger crank_test_fail_unavailable_guard on artifact_blobs;
drop function crank_test_fail_unavailable();",
)
.execute(registry.pool())
.await
.unwrap();
sqlx::query(
"update artifact_blobs
set claim_expires_at = clock_timestamp() - interval '1 second'
where digest = $1",
)
.bind(artifact.artifact_ref().digest_hex())
.execute(registry.pool())
.await
.unwrap();
let mut recovered_coordinator = ReconciliationCoordinator::new(
PostgresReconciliationBackend::new(registry.clone(), Arc::new(store.clone())),
);
let recovered = recovered_coordinator.tick().await.unwrap();
assert!(!recovered.retryable);
assert_eq!(
store
.reconciliation_presence(artifact.artifact_ref())
.unwrap(),
ReconciliationPresence::Absent
);
let cleared = sqlx::query(
"select claim_token, claim_expires_at, storage_lifecycle
from artifact_blobs where digest = $1",
)
.bind(artifact.artifact_ref().digest_hex())
.fetch_one(registry.pool())
.await
.unwrap();
assert_eq!(
cleared.try_get::<Option<String>, _>("claim_token").unwrap(),
None
);
assert_eq!(
cleared
.try_get::<Option<time::OffsetDateTime>, _>("claim_expires_at")
.unwrap(),
None
);
assert_eq!(cleared.get::<String, _>("storage_lifecycle"), "unavailable");
}
+73 -1
View File
@@ -10,7 +10,10 @@ use serde_json::{Value, json};
use crate::{
error::ApiError,
service::{OpenApiImportCreatePayload, OpenApiUpload, OpenApiUploadLocale},
service::{
OpenApiImportCreatePayload, OpenApiImportPlanApplyPayload, OpenApiImportPlanCreatePayload,
OpenApiUpload, OpenApiUploadLocale,
},
state::AppState,
};
@@ -25,6 +28,12 @@ pub struct WorkspaceImportPath {
pub job_id: String,
}
#[derive(Deserialize)]
pub struct WorkspacePlanPath {
pub workspace_id: String,
pub plan_id: String,
}
pub async fn preview_openapi_import(
Path(path): Path<WorkspacePath>,
State(state): State<AppState>,
@@ -198,6 +207,69 @@ pub async fn create_openapi_import(
Ok(Json(json!(imported)))
}
pub async fn create_openapi_import_plan(
Path(path): Path<WorkspaceImportPath>,
State(state): State<AppState>,
headers: HeaderMap,
Json(payload): Json<OpenApiImportPlanCreatePayload>,
) -> Result<Json<Value>, ApiError> {
let plan = state
.service
.create_openapi_import_plan_with_locale(
&path.workspace_id.as_str().into(),
&path.job_id.as_str().into(),
payload,
openapi_upload_locale(&headers),
)
.await?;
Ok(Json(json!(plan)))
}
pub async fn revalidate_openapi_import_plan(
Path(path): Path<WorkspacePlanPath>,
State(state): State<AppState>,
headers: HeaderMap,
) -> Result<Json<Value>, ApiError> {
let plan = state
.service
.revalidate_openapi_import_plan_with_locale(
&path.workspace_id.as_str().into(),
&path.plan_id.as_str().into(),
openapi_upload_locale(&headers),
)
.await?;
Ok(Json(json!(plan)))
}
pub async fn apply_openapi_import_plan(
Path(path): Path<WorkspacePlanPath>,
State(state): State<AppState>,
headers: HeaderMap,
Json(payload): Json<OpenApiImportPlanApplyPayload>,
) -> Result<impl IntoResponse, ApiError> {
let report = state
.service
.apply_openapi_import_plan_with_locale(
&path.workspace_id.as_str().into(),
&path.plan_id.as_str().into(),
payload,
openapi_upload_locale(&headers),
)
.await?;
let status = if report.status == crank_registry::ImportPlanApplyStatus::Rejected {
axum::http::StatusCode::CONFLICT
} else {
axum::http::StatusCode::OK
};
Ok((
status,
Json(
serde_json::to_value(report)
.map_err(|_| ApiError::internal("could not serialize import plan report"))?,
),
))
}
#[cfg(test)]
mod tests {
use axum::http::{HeaderMap, HeaderValue};
+28
View File
@@ -7,7 +7,9 @@ use crate::{
error::ApiError,
service::{
OnboardingEventPayload, OnboardingEventResponse, OnboardingResponse,
RegisterOnboardingImportContextPayload, RegisterOnboardingImportContextResponse,
ResetOnboardingSelectionPayload, ResetOnboardingSelectionResponse,
SelectOnboardingImportDraftPayload, SelectOnboardingImportDraftResponse,
},
state::AppState,
};
@@ -57,3 +59,29 @@ pub async fn record_onboarding_event(
.await?,
))
}
pub async fn register_onboarding_import_context(
Path(path): Path<WorkspaceOnboardingPath>,
State(state): State<AppState>,
Json(payload): Json<RegisterOnboardingImportContextPayload>,
) -> Result<Json<RegisterOnboardingImportContextResponse>, ApiError> {
Ok(Json(
state
.service
.register_onboarding_import_context(&path.workspace_id.as_str().into(), payload)
.await?,
))
}
pub async fn select_onboarding_import_draft(
Path(path): Path<WorkspaceOnboardingPath>,
State(state): State<AppState>,
Json(payload): Json<SelectOnboardingImportDraftPayload>,
) -> Result<Json<SelectOnboardingImportDraftResponse>, ApiError> {
Ok(Json(
state
.service
.select_onboarding_import_draft(&path.workspace_id.as_str().into(), payload)
.await?,
))
}
+9 -43
View File
@@ -5,9 +5,8 @@ use crank_core::{
ToolAccessMode, ToolSelectionPolicy, UsagePeriod, WorkspaceId, search_tool_catalog,
};
use crank_registry::{
AgentStateExpectation, AgentVersionRecord, CreateAgentDraftVersionRequest, CreateAgentRequest,
PublishAgentRequest, SaveAgentCatalogConfigRequest, UpdateAgentSummaryRequest, UsageBucket,
UsageQuery,
AgentStateExpectation, AgentVersionRecord, CreateAgentRequest, PublishAgentRequest,
SaveAgentCatalogConfigRequest, UpdateAgentSummaryRequest, UsageBucket, UsageQuery,
};
use serde_json::json;
use sha2::{Digest, Sha256};
@@ -471,8 +470,9 @@ impl AdminService {
payload: AgentCatalogPayload,
expected_state: Option<&AgentStateExpectation>,
) -> Result<AgentVersionRecord, ApiError> {
let agent = self.get_agent(workspace_id, agent_id).await?;
let current_version = self
.ensure_editable_agent_version(workspace_id, agent_id)
.get_agent_version(workspace_id, agent_id, agent.current_draft_version)
.await?;
let (payload, requested_policy) = payload.into_parts();
let bindings = payload
@@ -492,8 +492,9 @@ impl AdminService {
.unwrap_or_else(|| current_version.snapshot.tool_selection_policy.clone());
validate_tool_selection_policy(&tool_selection_policy, &bindings)?;
self.registry
.save_agent_catalog_config(SaveAgentCatalogConfigRequest {
let saved_version = self
.registry
.save_agent_catalog_config_editable(SaveAgentCatalogConfigRequest {
workspace_id,
agent_id,
agent_version: current_version.version,
@@ -505,47 +506,12 @@ impl AdminService {
info!(
name: "admin.agent.bindings_saved",
agent_id = %agent_id.as_str(),
version = current_version.version,
version = saved_version,
binding_count = bindings.len(),
"agent bindings saved"
);
self.get_agent_version(workspace_id, agent_id, current_version.version)
.await
}
async fn ensure_editable_agent_version(
&self,
workspace_id: &WorkspaceId,
agent_id: &AgentId,
) -> Result<AgentVersionRecord, ApiError> {
let agent = self.get_agent(workspace_id, agent_id).await?;
let current = self
.get_agent_version(workspace_id, agent_id, agent.current_draft_version)
.await?;
if agent.latest_published_version != Some(agent.current_draft_version) {
return Ok(current);
}
let now = OffsetDateTime::now_utc();
let draft = AgentVersion {
agent_id: agent_id.clone(),
version: current.version + 1,
status: AgentStatus::Draft,
instructions: current.snapshot.instructions.clone(),
tool_selection_policy: current.snapshot.tool_selection_policy.clone(),
created_at: now,
};
self.registry
.create_agent_draft_version(CreateAgentDraftVersionRequest {
workspace_id,
agent_id,
version: &draft,
bindings: &current.bindings,
updated_at: &now,
})
.await?;
self.get_agent_version(workspace_id, agent_id, draft.version)
self.get_agent_version(workspace_id, agent_id, saved_version)
.await
}
+349 -393
View File
@@ -2,20 +2,22 @@ use std::collections::{BTreeMap, BTreeSet};
use crank_artifacts::{ArtifactError, MAX_ARTIFACT_BYTES};
use crank_core::{
ExecutionConfig, OperationSecurityLevel, Protocol, ToolQualityFinding, ToolQualitySeverity,
WorkspaceId,
AuthProfileId, ExecutionConfig, OperationId, OperationSecurityLevel, OperationStatus, Protocol,
SecretStatus, ToolQualityFinding, ToolQualitySeverity, WorkspaceId,
};
use crank_import::rest::{
ImportFinding, ImportFindingSeverity, ImportOperationCandidate, NORMALIZER_VERSION,
PROJECTION_VERSION, operation_draft_from_candidate,
ImportFinding, ImportFindingSeverity, ImportNameConflict, ImportOperationCandidate,
NORMALIZER_VERSION, PROJECTION_VERSION, canonical_external_document_uri,
operation_draft_from_candidate, validate_document_source_safe,
};
use crank_registry::{
ApplyImportJobRequest, ArtifactSourceId, ArtifactSourceSensitivity,
CreateArtifactSourceRequest, CreateImportJobRequest, FinishImportJobRequest,
ImportConflictMode, ImportJobApplyResult, ImportJobId, ImportJobKind, ImportJobSourceEnvelope,
ImportJobStatus, ImportOperationDraft, RegistryError,
CreateArtifactSourceRequest, CreateImportJobRequest, CreateImportPlanRequest,
FinishImportJobRequest, ImportConflictMode, ImportJob, ImportJobApplyResult, ImportJobId,
ImportJobKind, ImportJobSourceEnvelope, ImportJobStatus, ImportOperationDraft, ImportPlanId,
RegistryError, RegistryOperation,
};
use serde_json::json;
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use time::{Duration, OffsetDateTime, format_description::well_known::Rfc3339};
use tracing::{info, instrument};
@@ -23,25 +25,170 @@ use tracing::{info, instrument};
use crate::{
error::ApiError,
service::{
AdminService, OpenApiImportCreatePayload, OpenApiImportCreateResponse,
OpenApiImportCreatedOperation, OpenApiImportPreviewResponse, OpenApiImportSkippedOperation,
OpenApiUpload, OpenApiUploadLocale, OperationPayload, new_prefixed_id,
AdminService, OpenApiImportAuthProfileChoice, OpenApiImportCreatePayload,
OpenApiImportCreateResponse, OpenApiImportCreatedOperation, OpenApiImportPlanApplyPayload,
OpenApiImportPlanCandidateView, OpenApiImportPlanCounts, OpenApiImportPlanCreatePayload,
OpenApiImportPlanCreateResponse, OpenApiImportPlanDecision,
OpenApiImportPlanRevalidationResponse, OpenApiImportPreviewResponse,
OpenApiImportSecurityProfileChoice, OpenApiImportSkippedOperation, OpenApiUpload,
OpenApiUploadLocale, OperationPayload, new_prefixed_id,
},
};
mod external_references;
mod import_plan;
mod job_contract;
mod plan_apply;
mod verified_preview;
use external_references::ImportReplayContext;
use import_plan::import_plan_repreview_error;
use job_contract::{
SourceDetachGuard, import_job_dependencies, import_job_normalization_config, import_job_source,
};
use verified_preview::{
ImportPreviewResolution, artifact_error, openapi_source_error, parse_verified_preview,
preview_digest, preview_has_blocker,
};
const IMPORT_JOB_TTL_HOURS: i64 = 24;
const OPENAPI_PARSE_DEADLINE: std::time::Duration = std::time::Duration::from_secs(30);
const OPENAPI_PARSE_CONCURRENCY: usize = 4;
const MAX_IMPORT_PLAN_KEYS: usize = 2_000;
const OPENAPI_SUPPORT_MATRIX_VERSION: &str = "1.0.4";
const MAX_IMPORT_PLAN_KEY_BYTES: usize = 4_096;
const MAX_IMPORT_PLAN_SERVER_URL_BYTES: usize = 8_192;
const MAX_IMPORT_PLAN_NAME_BYTES: usize = 256;
const MAX_IMPORT_PLAN_ID_REF_BYTES: usize = 128;
static OPENAPI_PARSE_SLOTS: tokio::sync::Semaphore =
tokio::sync::Semaphore::const_new(OPENAPI_PARSE_CONCURRENCY);
fn preview_name_conflicts(
preview: &crank_import::rest::ImportPreview,
catalog_names: &[String],
) -> Vec<ImportNameConflict> {
let operations = preview
.groups
.iter()
.flat_map(|group| group.operations.iter())
.collect::<Vec<_>>();
let mut operation_ids = BTreeMap::<&str, usize>::new();
for candidate in &operations {
if let Some(id) = candidate.operation_id.as_deref() {
*operation_ids.entry(id).or_default() += 1;
}
}
let occupied = catalog_names
.iter()
.map(String::as_str)
.collect::<BTreeSet<_>>();
let mut proposals = catalog_names.iter().cloned().collect::<BTreeSet<_>>();
proposals.extend(
operations
.iter()
.map(|candidate| candidate.suggested_name.clone()),
);
let mut conflicts = Vec::new();
for candidate in operations {
let duplicate = candidate
.operation_id
.as_deref()
.is_some_and(|id| operation_ids.get(id).is_some_and(|count| *count > 1));
let invalid = candidate.operation_id.as_deref().is_some_and(|id| {
id.is_empty()
|| id.len() > MAX_IMPORT_PLAN_NAME_BYTES
|| !id.bytes().enumerate().all(|(index, ch)| {
ch.is_ascii_alphabetic() || ch == b'_' || (index > 0 && ch.is_ascii_digit())
})
});
let taken = occupied.contains(candidate.suggested_name.as_str());
if !duplicate && !invalid && !taken {
continue;
}
let base = candidate
.suggested_name
.chars()
.take(240)
.collect::<String>();
let proposal = next_available_name(&base, &mut proposals);
for conflict_type in [
duplicate.then_some("duplicate_name"),
invalid.then_some("invalid_name"),
taken.then_some("taken_name"),
]
.into_iter()
.flatten()
{
conflicts.push(ImportNameConflict {
operation_key: candidate.key.clone(),
conflict_type: conflict_type.to_owned(),
proposed_name: proposal.clone(),
source_location: candidate.source_location.as_ref().map(|location| {
crank_import::rest::SourceLocation {
pointer: if candidate.operation_id.is_some() {
format!("{}/operationId", location.pointer)
} else {
location.pointer.clone()
},
}
}),
});
}
}
conflicts
}
fn next_available_name(base: &str, occupied: &mut BTreeSet<String>) -> String {
// A catalog may contain more names than the preview candidate cap. With
// occupied.len() + 1 suffixes, at least one candidate must be free.
(2..=occupied.len() + 2)
.map(|index| format!("{base}_{index}"))
.find(|name| occupied.insert(name.clone()))
.expect("finite occupied names always leave a free suffix")
}
fn attach_preview_readiness(
preview: &mut crank_import::rest::ImportPreview,
choices: &[OpenApiImportSecurityProfileChoice],
) {
let document_blocked = preview.findings.iter().any(|finding| {
finding.severity == ImportFindingSeverity::Error && finding.operation_key.is_none()
});
for candidate in preview
.groups
.iter_mut()
.flat_map(|group| group.operations.iter_mut())
{
let blocked = document_blocked
|| candidate
.findings
.iter()
.any(|finding| finding.severity == ImportFindingSeverity::Error);
let alternatives = &candidate.security_requirements.alternatives;
let public = alternatives.is_empty()
|| alternatives
.iter()
.any(|alternative| alternative.supported && alternative.schemes.is_empty());
candidate.status = if blocked {
"blocked"
} else if public {
"actionable"
} else if alternatives.iter().enumerate().any(|(index, alternative)| {
alternative.supported
&& choices.iter().any(|choice| {
choice.operation_key == candidate.key
&& choice.alternative_index == index
&& !choice.profiles.is_empty()
})
}) {
"unresolved"
} else {
"blocked"
}
.to_owned();
}
}
impl AdminService {
#[instrument(skip(self, upload), fields(workspace_id = %workspace_id.as_str()))]
pub async fn preview_openapi_import(
@@ -53,20 +200,52 @@ impl AdminService {
validate_openapi_upload(&upload)?;
let OpenApiUpload {
bytes,
bytes: raw_bytes,
mime_type,
locale,
} = upload;
let store = self.artifact_store.clone();
let artifact = tokio::task::spawn_blocking(move || store.put_registered(&bytes))
.await
.map_err(|_| ApiError::openapi_upload(locale, "storage_unavailable"))?
.map_err(|error| artifact_error(locale, error))?;
let raw_document = std::str::from_utf8(&raw_bytes)
.map_err(|_| ApiError::openapi_upload(locale, "invalid_utf8"))?;
validate_document_source_safe(raw_document, &self.external_reference_normalization)
.map_err(|_| ApiError::openapi_upload(locale, "invalid_document"))?;
let now = OffsetDateTime::now_utc();
let mut dependencies = self
.materialize_external_reference_snapshots(workspace_id, &raw_bytes, now)
.await;
if dependencies.unsafe_source {
return Err(ApiError::openapi_upload(locale, "invalid_document"));
}
let source_digest =
crank_import::rest::SourceDigest::parse(format!("{:x}", Sha256::digest(&raw_bytes)))
.map_err(|_| ApiError::openapi_upload(locale, "invalid_document"))?;
if crank_import::rest::validate_resolved_bundle_source_safe(
raw_document,
source_digest,
&dependencies.snapshots,
&self.external_reference_normalization,
)
.is_err()
{
dependencies.detach_all().await;
return Err(ApiError::openapi_upload(locale, "invalid_document"));
}
let bytes = raw_bytes;
let store = self.artifact_store.clone();
let artifact_result = tokio::task::spawn_blocking(move || store.put_registered(&bytes))
.await
.map_err(|_| ApiError::openapi_upload(locale, "storage_unavailable"))
.and_then(|result| result.map_err(|error| artifact_error(locale, error)));
let artifact = match artifact_result {
Ok(artifact) => artifact,
Err(error) => {
dependencies.detach_all().await;
return Err(error);
}
};
let expires_at = now + Duration::hours(IMPORT_JOB_TTL_HOURS);
let job_id = ImportJobId::new(new_prefixed_id("imp"));
let source_id = ArtifactSourceId::new(new_prefixed_id("src_openapi"));
let source = self
let source_result = self
.registry
.create_artifact_source(CreateArtifactSourceRequest {
workspace_id,
@@ -76,7 +255,14 @@ impl AdminService {
sensitivity: ArtifactSourceSensitivity::Internal,
created_at: now,
})
.await?;
.await;
let source = match source_result {
Ok(source) => source,
Err(error) => {
dependencies.detach_all().await;
return Err(ApiError::from(error));
}
};
let mut detach_guard = SourceDetachGuard::new(
self.registry.clone(),
workspace_id.clone(),
@@ -102,9 +288,6 @@ impl AdminService {
detach_guard.detach_now().await;
return Err(ApiError::openapi_upload(locale, "source_integrity"));
}
let mut dependencies = self
.materialize_external_reference_snapshots(workspace_id, &verified.bytes, now)
.await;
let parsed = match parse_verified_preview(
verified.bytes,
artifact.artifact_ref().digest_hex().to_owned(),
@@ -132,6 +315,39 @@ impl AdminService {
detach_guard.detach_now().await;
return Err(ApiError::openapi_upload(locale, "no_methods"));
}
let candidate_count: usize = parsed
.preview
.groups
.iter()
.map(|group| group.operations.len())
.sum();
if candidate_count > MAX_IMPORT_PLAN_KEYS {
dependencies.detach_all().await;
detach_guard.detach_now().await;
return Err(ApiError::validation_with_context(
"OpenAPI preview has too many candidates",
json!({ "error_code": "openapi_preview_too_many_candidates", "limit": MAX_IMPORT_PLAN_KEYS }),
));
}
let security_profile_choices = match self
.security_profile_choices(workspace_id, &parsed.preview)
.await
{
Ok(choices) => choices,
Err(error) => {
dependencies.detach_all().await;
detach_guard.detach_now().await;
return Err(error);
}
};
let catalog_names = match self.registry.list_import_catalog_names(workspace_id).await {
Ok(names) => names,
Err(error) => {
dependencies.detach_all().await;
detach_guard.detach_now().await;
return Err(ApiError::from(error));
}
};
let source_envelope = ImportJobSourceEnvelope {
source_id,
digest: artifact.artifact_ref().clone(),
@@ -179,15 +395,92 @@ impl AdminService {
dependencies.disarm();
detach_guard.disarm();
let mut response_preview = parsed.preview;
response_preview.conflicts = preview_name_conflicts(&response_preview, &catalog_names);
attach_preview_readiness(&mut response_preview, &security_profile_choices);
Ok(OpenApiImportPreviewResponse {
job_id: job_id.as_str().to_owned(),
expires_at: expires_at
.format(&Rfc3339)
.map_err(|error| ApiError::internal(error.to_string()))?,
preview: parsed.preview,
preview: response_preview,
security_profile_choices,
})
}
async fn security_profile_choices(
&self,
workspace_id: &WorkspaceId,
preview: &crank_import::rest::ImportPreview,
) -> Result<Vec<OpenApiImportSecurityProfileChoice>, ApiError> {
let profiles = self.registry.list_auth_profiles(workspace_id).await?;
let mut available = Vec::new();
for profile in profiles {
if profile.kind != profile.config.kind() {
continue;
}
let mut usable = true;
for secret_id in profile.config.secret_ids() {
let Some(secret) = self.registry.get_secret(workspace_id, secret_id).await? else {
usable = false;
break;
};
if secret.secret.status != SecretStatus::Active
|| self
.registry
.get_current_secret_version(workspace_id, secret_id)
.await?
.is_none()
{
usable = false;
break;
}
}
if usable {
available.push(profile);
}
}
let mut choices = Vec::new();
for operation in preview
.groups
.iter()
.flat_map(|group| group.operations.iter())
{
for (alternative_index, alternative) in operation
.security_requirements
.alternatives
.iter()
.enumerate()
{
if !alternative.supported || alternative.schemes.len() != 1 {
continue;
}
let Some(scheme) = operation.security_schemes.get(&alternative.schemes[0]) else {
continue;
};
let profiles = available
.iter()
.filter(|profile| {
import_plan::auth_config_matches_scheme(&profile.config, scheme)
})
.map(|profile| OpenApiImportAuthProfileChoice {
id: profile.id.as_str().to_owned(),
name: profile.name.clone(),
kind: profile.kind,
})
.collect::<Vec<_>>();
choices.push(OpenApiImportSecurityProfileChoice {
operation_key: operation.key.clone(),
alternative_index,
schemes: alternative.schemes.clone(),
profiles,
});
}
}
Ok(choices)
}
#[instrument(skip(self, payload), fields(workspace_id = %workspace_id.as_str(), job_id = %job_id.as_str()))]
pub async fn create_openapi_import(
&self,
@@ -230,7 +523,11 @@ impl AdminService {
)
})?;
if job.expires_at <= OffsetDateTime::now_utc() {
return Err(ApiError::validation("import preview has expired"));
let message = match locale {
OpenApiUploadLocale::Ru => "срок действия preview импорта истёк",
OpenApiUploadLocale::En => "import preview has expired",
};
return Err(ApiError::validation(message));
}
if job.kind != ImportJobKind::OpenApi {
return Err(ApiError::validation("import job kind is not openapi"));
@@ -276,141 +573,20 @@ impl AdminService {
return Ok(openapi_import_response(applied));
}
let source = match import_job_source(&job.preview_payload, locale) {
Ok(source) => source,
Err(error) => {
return self
.fail_openapi_import_or_replay(
&replay_context,
"import_source_verification_failed",
error,
)
.await;
}
};
let verified = match self
.registry
.read_artifact_source(
std::sync::Arc::clone(&self.artifact_store),
workspace_id,
&source.source_id,
)
let resolved_preview = match self
.resolve_verified_openapi_preview(workspace_id, &job, locale)
.await
{
Ok(verified) => verified,
Err(
error @ (RegistryError::SourceNotFound { .. } | RegistryError::SourceUnavailable),
) => {
Ok(resolved) => resolved,
Err(ImportPreviewResolution::Fatal(error_code, error)) => {
return self
.fail_openapi_import_or_replay(
&replay_context,
"import_source_verification_failed",
openapi_source_error(locale, error),
)
.fail_openapi_import_or_replay(&replay_context, error_code, error)
.await;
}
Err(error @ RegistryError::SourceIntegrity) => {
return self
.fail_openapi_import_or_replay(
&replay_context,
"import_source_verification_failed",
openapi_source_error(locale, error),
)
.await;
}
Err(error) => return Err(openapi_source_error(locale, error)),
Err(ImportPreviewResolution::NonFatal(error)) => return Err(error),
};
if verified.source.blob.artifact_ref != source.digest {
return self
.fail_openapi_import_or_replay(
&replay_context,
"import_source_verification_failed",
ApiError::openapi_upload(locale, "source_integrity"),
)
.await;
}
let replay_contract = match import_replay_contract(&job.preview_payload, locale) {
Ok(contract) => contract,
Err(error) => {
return self
.fail_openapi_import_or_replay(
&replay_context,
"import_replay_verification_failed",
error,
)
.await;
}
};
let parsed = match replay_contract {
ImportReplayContract::PersistedV2(parsed) => parsed,
ImportReplayContract::LegacyV1 | ImportReplayContract::Current => {
let legacy_v1 = matches!(replay_contract, ImportReplayContract::LegacyV1);
let dependency_snapshots = match self
.read_import_job_dependencies(workspace_id, &job.preview_payload, locale)
.await
{
Ok(snapshots) => snapshots,
Err(error) => {
return self
.fail_openapi_import_or_replay(
&replay_context,
"import_dependency_verification_failed",
error,
)
.await;
}
};
let normalization_config = match import_job_normalization_config(
&job.preview_payload,
&self.external_reference_normalization,
legacy_v1,
locale,
) {
Ok(config) => config,
Err(error) => {
return self
.fail_openapi_import_or_replay(
&replay_context,
"import_replay_verification_failed",
error,
)
.await;
}
};
let parsed = match parse_verified_preview(
verified.bytes,
source.digest.digest_hex().to_owned(),
dependency_snapshots,
normalization_config,
locale,
legacy_v1,
)
.await
{
Ok(parsed) => parsed,
Err(error) => {
return self
.fail_openapi_import_or_replay(
&replay_context,
"import_replay_verification_failed",
error,
)
.await;
}
};
if let Err(error) = verify_preview_contract(&job.preview_payload, &parsed, locale) {
return self
.fail_openapi_import_or_replay(
&replay_context,
"import_replay_verification_failed",
error,
)
.await;
}
parsed
}
};
if preview_has_blocker(&parsed.preview, &selected) {
let preview = resolved_preview.preview;
if preview_has_blocker(&preview, &selected) {
return self
.fail_openapi_import_or_replay(
&replay_context,
@@ -420,7 +596,7 @@ impl AdminService {
.await;
}
let mut candidates = BTreeMap::new();
for group in &parsed.preview.groups {
for group in &preview.groups {
for operation in &group.operations {
candidates.insert(operation.key.clone(), operation);
}
@@ -488,24 +664,6 @@ impl AdminService {
}
}
fn canonical_external_document_uri(base: Option<&str>, reference: &str) -> Option<String> {
if reference.starts_with('#') {
return None;
}
let mut url = match base {
Some(base) => url::Url::parse(base).ok()?.join(reference).ok()?,
None => url::Url::parse(reference).ok()?,
};
if !matches!(url.scheme(), "http" | "https")
|| !url.username().is_empty()
|| url.password().is_some()
{
return None;
}
url.set_fragment(None);
Some(url.to_string())
}
fn openapi_import_response(applied: ImportJobApplyResult) -> OpenApiImportCreateResponse {
let created = applied
.created
@@ -532,6 +690,7 @@ fn openapi_import_response(applied: ImportJobApplyResult) -> OpenApiImportCreate
operation.name
),
operation_key: Some(operation.operation_key.clone()),
source_location: None,
})
})
.collect::<Vec<_>>();
@@ -550,6 +709,7 @@ fn openapi_import_response(applied: ImportJobApplyResult) -> OpenApiImportCreate
format!("Операция {name} уже существует и была пропущена.")
},
operation_key: Some(operation.operation_key.clone()),
source_location: None,
});
OpenApiImportSkippedOperation {
operation_key: operation.operation_key.clone(),
@@ -599,227 +759,6 @@ fn validate_openapi_upload(upload: &OpenApiUpload) -> Result<(), ApiError> {
Ok(())
}
struct ParsedOpenApiPreview {
preview: crank_import::rest::ImportPreview,
ir_fingerprint: String,
}
enum ImportReplayContract {
LegacyV1,
PersistedV2(ParsedOpenApiPreview),
Current,
}
fn import_replay_contract(
payload: &serde_json::Value,
locale: OpenApiUploadLocale,
) -> Result<ImportReplayContract, ApiError> {
let Some(normalization) = payload.get("normalization") else {
return Ok(ImportReplayContract::LegacyV1);
};
let normalizer = normalization
.get("normalizer_version")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| ApiError::openapi_upload(locale, "source_integrity"))?;
let projection = normalization
.get("projection_version")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| ApiError::openapi_upload(locale, "source_integrity"))?;
let ir_fingerprint = normalization
.get("ir_fingerprint")
.and_then(serde_json::Value::as_str)
.filter(|value| is_lower_sha256(value))
.ok_or_else(|| ApiError::openapi_upload(locale, "source_integrity"))?;
let expected_preview_digest = payload
.get("preview_digest")
.and_then(serde_json::Value::as_str)
.filter(|value| is_lower_sha256(value))
.ok_or_else(|| ApiError::openapi_upload(locale, "source_integrity"))?;
if normalizer == NORMALIZER_VERSION && projection == PROJECTION_VERSION {
return Ok(ImportReplayContract::Current);
}
// Historical preview payloads are replayed as their persisted projection.
// They must never be parsed again with the current v4 semantics.
if !matches!(
(normalizer, projection),
("normalized-ir-v2", "preview-v2") | ("normalized-ir-v3", "preview-v3")
) {
return Err(ApiError::openapi_upload(locale, "source_integrity"));
}
let preview_value = payload
.get("preview")
.cloned()
.ok_or_else(|| ApiError::openapi_upload(locale, "source_integrity"))?;
if preview_digest(&preview_value)? != expected_preview_digest {
return Err(ApiError::openapi_upload(locale, "source_integrity"));
}
let preview = serde_json::from_value(preview_value)
.map_err(|_| ApiError::openapi_upload(locale, "source_integrity"))?;
Ok(ImportReplayContract::PersistedV2(ParsedOpenApiPreview {
preview,
ir_fingerprint: ir_fingerprint.to_owned(),
}))
}
fn is_lower_sha256(value: &str) -> bool {
value.len() == 64
&& value
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}
async fn parse_verified_preview(
bytes: Vec<u8>,
digest: String,
snapshots: Vec<crank_import::rest::ExternalDocumentSnapshot>,
normalization_config: crank_import::rest::NormalizationConfig,
locale: OpenApiUploadLocale,
legacy_v1: bool,
) -> Result<ParsedOpenApiPreview, ApiError> {
let started = tokio::time::Instant::now();
let permit = tokio::time::timeout(OPENAPI_PARSE_DEADLINE, OPENAPI_PARSE_SLOTS.acquire())
.await
.map_err(|_| ApiError::openapi_upload(locale, "parser_unavailable"))?
.map_err(|_| ApiError::openapi_upload(locale, "parser_unavailable"))?;
let parsing = tokio::task::spawn_blocking(move || {
// Keep the permit inside the blocking task. Timing out the caller
// cannot cancel CPU work already running, but abandoned parsers remain
// globally bounded and release capacity when they actually finish.
let _permit = permit;
let document = std::str::from_utf8(&bytes)
.map_err(|_| ApiError::openapi_upload(locale, "invalid_utf8"))?;
if legacy_v1 {
return crank_import::rest::preview_document_legacy_v1(document)
.map(|preview| ParsedOpenApiPreview {
preview,
ir_fingerprint: String::new(),
})
.map_err(|_| ApiError::openapi_upload(locale, "invalid_document"));
}
let digest = crank_import::rest::SourceDigest::parse(digest)
.map_err(|_| ApiError::openapi_upload(locale, "source_integrity"))?;
let ir = crank_import::rest::normalize_verified_bundle(
document,
digest,
&snapshots,
&normalization_config,
)
.map_err(|error| match error {
crank_import::rest::ImportParseError::NoMethods => {
ApiError::openapi_upload(locale, "no_methods")
}
_ => ApiError::openapi_upload(locale, "invalid_document"),
})?;
let ir_fingerprint = preview_digest(
&serde_json::to_value(&ir)
.map_err(|_| ApiError::openapi_upload(locale, "invalid_document"))?,
)?;
Ok::<_, ApiError>(ParsedOpenApiPreview {
preview: crank_import::rest::preview_from_ir(&ir),
ir_fingerprint,
})
});
let remaining = OPENAPI_PARSE_DEADLINE
.checked_sub(started.elapsed())
.unwrap_or(std::time::Duration::ZERO);
tokio::time::timeout(remaining, parsing)
.await
.map_err(|_| ApiError::openapi_upload(locale, "parser_unavailable"))?
.map_err(|_| ApiError::openapi_upload(locale, "parser_unavailable"))?
}
fn artifact_error(locale: OpenApiUploadLocale, error: ArtifactError) -> ApiError {
match error {
ArtifactError::EmptySource => ApiError::openapi_upload(locale, "empty_file"),
ArtifactError::SourceTooLarge => ApiError::openapi_upload(locale, "file_too_large"),
ArtifactError::Integrity => ApiError::openapi_upload(locale, "source_integrity"),
ArtifactError::Storage
| ArtifactError::NotFound
| ArtifactError::InvalidReference
| ArtifactError::UnsafeRoot => ApiError::openapi_upload(locale, "storage_unavailable"),
}
}
fn openapi_source_error(locale: OpenApiUploadLocale, error: RegistryError) -> ApiError {
match error {
RegistryError::SourceNotFound { .. } | RegistryError::SourceUnavailable => {
ApiError::openapi_upload(locale, "source_unavailable")
}
RegistryError::SourceIntegrity => ApiError::openapi_upload(locale, "source_integrity"),
other => ApiError::from(other),
}
}
fn preview_digest(preview: &serde_json::Value) -> Result<String, ApiError> {
let canonical =
serde_json::to_vec(preview).map_err(|error| ApiError::internal(error.to_string()))?;
Ok(format!("{:x}", Sha256::digest(canonical)))
}
fn verify_preview_contract(
payload: &serde_json::Value,
parsed: &ParsedOpenApiPreview,
locale: OpenApiUploadLocale,
) -> Result<(), ApiError> {
// Pre-fingerprint jobs are legacy rolling-upgrade records. They retain the
// old reparse behavior; new jobs fail closed if parser output drifts or a
// persisted preview has been changed.
let expected = payload
.get("preview_digest")
.and_then(serde_json::Value::as_str);
if payload.get("normalization").is_some() && expected.is_none() {
return Err(ApiError::openapi_upload(locale, "source_integrity"));
}
let Some(expected) = expected else {
return Ok(());
};
let actual = preview_digest(
&serde_json::to_value(&parsed.preview)
.map_err(|error| ApiError::internal(error.to_string()))?,
)?;
if actual == expected {
if let Some(normalization) = payload.get("normalization") {
let normalizer = normalization
.get("normalizer_version")
.and_then(serde_json::Value::as_str);
let projection = normalization
.get("projection_version")
.and_then(serde_json::Value::as_str);
let fingerprint = normalization
.get("ir_fingerprint")
.and_then(serde_json::Value::as_str);
if normalizer != Some(NORMALIZER_VERSION)
|| projection != Some(PROJECTION_VERSION)
|| fingerprint != Some(parsed.ir_fingerprint.as_str())
{
return Err(ApiError::openapi_upload(locale, "source_integrity"));
}
}
Ok(())
} else {
Err(ApiError::openapi_upload(locale, "source_integrity"))
}
}
fn preview_has_blocker(
preview: &crank_import::rest::ImportPreview,
selected_operation_keys: &BTreeSet<String>,
) -> bool {
preview
.findings
.iter()
.any(|finding| finding.severity == ImportFindingSeverity::Error)
|| preview
.groups
.iter()
.flat_map(|group| group.operations.iter())
.filter(|operation| selected_operation_keys.contains(&operation.key))
.flat_map(|operation| operation.findings.iter())
.any(|finding| finding.severity == ImportFindingSeverity::Error)
}
fn openapi_application_key(payload: &OpenApiImportCreatePayload) -> Result<String, ApiError> {
let selected_operation_keys = payload
.selected_operation_keys
@@ -869,3 +808,20 @@ fn tool_quality_finding_from_import(finding: &ImportFinding) -> ToolQualityFindi
field_path: finding.operation_key.clone(),
}
}
#[cfg(test)]
mod preview_name_tests {
use super::next_available_name;
use std::collections::BTreeSet;
#[test]
fn crowded_catalog_still_gets_a_free_deterministic_proposal() {
let mut occupied = (2..=2_002)
.map(|index| format!("shared_{index}"))
.collect::<BTreeSet<_>>();
occupied.insert("shared".to_owned());
assert_eq!(next_available_name("shared", &mut occupied), "shared_2003");
assert_eq!(next_available_name("shared", &mut occupied), "shared_2004");
}
}
@@ -7,6 +7,13 @@ pub(super) struct MaterializedDependencies {
envelopes: Vec<ImportJobSourceEnvelope>,
canonical_uris: Vec<String>,
guards: Vec<SourceDetachGuard>,
pub(super) unsafe_source: bool,
}
struct StagedDependency {
canonical_uri: String,
bytes: Vec<u8>,
document: String,
}
pub(super) struct ImportReplayContext<'a> {
@@ -24,6 +31,7 @@ impl MaterializedDependencies {
envelopes: Vec::new(),
canonical_uris: Vec::new(),
guards: Vec::new(),
unsafe_source: false,
}
}
@@ -176,8 +184,8 @@ impl AdminService {
}
}
let mut seen = BTreeSet::new();
let mut result = MaterializedDependencies::empty();
let mut dependency_by_digest = BTreeMap::<String, usize>::new();
let mut staged = Vec::<StagedDependency>::new();
let mut staged_documents = vec![primary.to_owned()];
while let Some((canonical_uri, depth)) = queue.pop_front() {
if !seen.insert(canonical_uri.clone())
|| depth > self.external_reference_normalization.max_reference_depth
@@ -194,32 +202,77 @@ impl AdminService {
materialization_failure(
"fetch",
external_fetch_error_code(&error),
result.snapshots.len(),
staged.len(),
);
continue;
}
};
let Ok(document) = std::str::from_utf8(&bytes).map(str::to_owned) else {
materialization_failure(
"dependency_decode",
"invalid_utf8",
result.snapshots.len(),
);
materialization_failure("dependency_decode", "invalid_utf8", staged.len());
continue;
};
let Ok(references) = crank_import::rest::external_reference_uris(
&document,
&self.external_reference_normalization,
) else {
materialization_failure(
"dependency_scan",
"invalid_document",
result.snapshots.len(),
);
materialization_failure("dependency_scan", "invalid_document", staged.len());
continue;
};
staged_documents.push(document.clone());
staged.push(StagedDependency {
canonical_uri: canonical_uri.clone(),
bytes,
document,
});
for reference in references {
if let Some(uri) = canonical_external_document_uri(Some(&canonical_uri), &reference)
{
queue.push_back((uri, depth.saturating_add(1)));
}
}
}
let staged_snapshots = staged
.iter()
.filter_map(|dependency| {
let digest = format!("{:x}", Sha256::digest(&dependency.bytes));
let digest = crank_import::rest::SourceDigest::parse(digest).ok()?;
Some(crank_import::rest::ExternalDocumentSnapshot {
canonical_uri: dependency.canonical_uri.clone(),
digest,
document: dependency.document.clone(),
})
})
.collect::<Vec<_>>();
let primary_digest =
crank_import::rest::SourceDigest::parse(format!("{:x}", Sha256::digest(primary_bytes)))
.expect("SHA-256 digest is valid");
let raw_bundle_is_unsafe = crank_import::rest::validate_document_bundle_source_safe(
&staged_documents
.iter()
.map(String::as_str)
.collect::<Vec<_>>(),
&self.external_reference_normalization,
)
.is_err();
let resolved_bundle_is_unsafe = crank_import::rest::validate_resolved_bundle_source_safe(
primary,
primary_digest,
&staged_snapshots,
&self.external_reference_normalization,
)
.is_err();
if raw_bundle_is_unsafe || resolved_bundle_is_unsafe {
materialization_failure("dependency_redaction", "invalid_document", staged.len());
let mut rejected = MaterializedDependencies::empty();
rejected.unsafe_source = true;
return rejected;
}
let mut result = MaterializedDependencies::empty();
let mut dependency_by_digest = BTreeMap::<String, usize>::new();
for dependency in staged {
let store = self.artifact_store.clone();
let artifact_bytes = bytes.clone();
let artifact_bytes = dependency.bytes.clone();
let Ok(Ok(artifact)) =
tokio::task::spawn_blocking(move || store.put_registered(&artifact_bytes)).await
else {
@@ -295,31 +348,22 @@ impl AdminService {
dependency_by_digest.insert(digest_key, index);
index
};
let dependency = &result.envelopes[envelope_index];
let snapshot_digest = match crank_import::rest::SourceDigest::parse(
dependency.digest.digest_hex().to_owned(),
) {
Ok(digest) => digest,
Err(_) => {
materialization_failure("snapshot", "source_integrity", result.snapshots.len());
continue;
}
let dependency_envelope = &result.envelopes[envelope_index];
let Ok(snapshot_digest) = crank_import::rest::SourceDigest::parse(
dependency_envelope.digest.digest_hex().to_owned(),
) else {
materialization_failure("snapshot", "source_integrity", result.snapshots.len());
continue;
};
result
.snapshots
.push(crank_import::rest::ExternalDocumentSnapshot {
canonical_uri: canonical_uri.clone(),
canonical_uri: dependency.canonical_uri.clone(),
digest: snapshot_digest,
document,
document: dependency.document,
});
materialized_count.store(result.snapshots.len(), std::sync::atomic::Ordering::Relaxed);
result.canonical_uris.push(canonical_uri.clone());
for reference in references {
if let Some(uri) = canonical_external_document_uri(Some(&canonical_uri), &reference)
{
queue.push_back((uri, depth.saturating_add(1)));
}
}
result.canonical_uris.push(dependency.canonical_uri);
}
// Registry ownership is one envelope per immutable digest, while the
// resolver may map several canonical URIs to that same snapshot. Keep
@@ -0,0 +1,976 @@
mod validation;
use super::*;
use crank_core::AuthConfig;
use crank_import::rest::SecurityRequirementsSource as SecuritySource;
impl AdminService {
pub async fn create_openapi_import_plan(
&self,
workspace_id: &WorkspaceId,
job_id: &ImportJobId,
payload: OpenApiImportPlanCreatePayload,
) -> Result<OpenApiImportPlanCreateResponse, ApiError> {
self.create_openapi_import_plan_with_locale(
workspace_id,
job_id,
payload,
OpenApiUploadLocale::En,
)
.await
}
#[instrument(skip(self, payload), fields(workspace_id = %workspace_id.as_str(), job_id = %job_id.as_str()))]
pub async fn create_openapi_import_plan_with_locale(
&self,
workspace_id: &WorkspaceId,
job_id: &ImportJobId,
payload: OpenApiImportPlanCreatePayload,
locale: OpenApiUploadLocale,
) -> Result<OpenApiImportPlanCreateResponse, ApiError> {
self.ensure_workspace_exists(workspace_id).await?;
let now = OffsetDateTime::now_utc();
let job = self
.registry
.get_import_job(workspace_id, job_id)
.await?
.ok_or_else(|| {
ApiError::not_found_with_context(
"import job was not found",
json!({ "job_id": job_id.as_str() }),
)
})?;
if job.kind != ImportJobKind::OpenApi {
return Err(ApiError::validation("import job kind is not openapi"));
}
if job.expires_at <= now {
let message = match locale {
OpenApiUploadLocale::Ru => "срок действия preview импорта истёк",
OpenApiUploadLocale::En => "import preview has expired",
};
return Err(ApiError::validation(message));
}
if job.status != ImportJobStatus::Pending {
return Err(import_plan_repreview_error(
locale,
"import_plan_job_terminal",
));
}
if payload.decisions.len() > MAX_IMPORT_PLAN_KEYS {
return Err(ApiError::validation(
"too many decision blocks for this import plan",
));
}
if payload.server_url.as_deref().is_some_and(|server_url| {
server_url.is_empty() || server_url.len() > MAX_IMPORT_PLAN_SERVER_URL_BYTES
}) {
return Err(ApiError::validation_with_context(
"server_url is empty or too long",
json!({ "error_code": "import_plan_invalid_input" }),
));
}
// The plan is anchored to the verified job snapshots. A stale or
// corrupt preview is reported as bounded re-preview guidance and
// never mutates the job: other stored plans may still reference the
// same job and its replay must remain readable.
let resolved = self
.resolve_verified_openapi_preview(workspace_id, &job, locale)
.await
.map_err(|resolution| match resolution {
ImportPreviewResolution::Fatal(error_code, _) => {
import_plan_repreview_error(locale, error_code)
}
ImportPreviewResolution::NonFatal(error) => error,
})?;
let preview = &resolved.preview;
let catalog_revision = self.registry.import_catalog_revision(workspace_id).await?;
// Stored external dependency snapshots are re-verified for every
// replay variant (including historically persisted ones) without a
// network fetch: detached or altered snapshots are re-preview
// material and no plan is created.
self.read_import_job_dependencies(workspace_id, &job.preview_payload, locale)
.await
.map_err(|_| {
import_plan_repreview_error(locale, "import_dependency_verification_failed")
})?;
let candidates: BTreeMap<String, &ImportOperationCandidate> = preview
.groups
.iter()
.flat_map(|group| group.operations.iter())
.map(|operation| (operation.key.clone(), operation))
.collect();
let all_set: BTreeSet<String> = candidates.keys().cloned().collect();
if all_set.len() > MAX_IMPORT_PLAN_KEYS {
return Err(ApiError::validation_with_context(
"too many candidates for an import plan",
json!({ "error_code": "import_plan_invalid_input" }),
));
}
let selected = resolve_plan_selection(
&payload.selection_mode,
&payload.selected_operation_keys,
&all_set,
)?;
if selected.len() > MAX_IMPORT_PLAN_KEYS
|| all_set.len() - selected.len() > MAX_IMPORT_PLAN_KEYS
{
return Err(ApiError::validation_with_context(
"too many candidates for an import plan",
json!({ "error_code": "import_plan_invalid_input" }),
));
}
let selected_keys: Vec<String> = selected.iter().cloned().collect();
let excluded: Vec<String> = all_set
.iter()
.filter(|key| !selected.contains(*key))
.cloned()
.collect();
let excluded_reasons = excluded
.iter()
.map(|key| {
let name = candidates
.get(key)
.map(|candidate| candidate.draft.name.clone())
.unwrap_or_else(|| key.clone());
let reason = preview
.findings
.iter()
.find(|finding| {
finding.severity == ImportFindingSeverity::Error
&& finding.operation_key.is_none()
})
.map(|finding| finding.code.clone())
.or_else(|| {
candidates.get(key).and_then(|candidate| {
candidate
.findings
.iter()
.find(|finding| finding.severity == ImportFindingSeverity::Error)
.map(|finding| finding.code.clone())
})
})
.unwrap_or_else(|| "not_selected".to_owned());
(key.clone(), (name, reason))
})
.collect::<BTreeMap<_, _>>();
let decisions = validation::validate_plan_decisions(&payload.decisions, &selected)?;
let global_blocker = preview
.findings
.iter()
.find(|finding| {
finding.severity == ImportFindingSeverity::Error && finding.operation_key.is_none()
})
.map(|finding| finding.code.clone());
let mut planned = Vec::with_capacity(selected_keys.len());
for key in &selected_keys {
let Some(candidate) = candidates.get(key) else {
unreachable!("selection is validated against the candidate set");
};
let blocker = global_blocker.clone().or_else(|| {
candidate
.findings
.iter()
.find(|finding| finding.severity == ImportFindingSeverity::Error)
.map(|finding| finding.code.clone())
});
let candidate_plan = self
.plan_import_candidate(
workspace_id,
payload.server_url.as_deref(),
candidate,
decisions.get(key).copied(),
blocker,
locale,
)
.await?;
planned.push(candidate_plan);
}
let counts = OpenApiImportPlanCounts {
selected: planned.len(),
excluded: excluded.len(),
actionable: planned
.iter()
.filter(|candidate| !candidate.blocked)
.count(),
blocked: planned.iter().filter(|candidate| candidate.blocked).count(),
};
if payload.selection_mode == "partial" && counts.blocked != 0 {
return Err(ApiError::validation_with_context(
"partial selection includes blocked candidates",
json!({ "error_code": "import_plan_partial_blocked" }),
));
}
if self.registry.import_catalog_revision(workspace_id).await? != catalog_revision {
return Err(import_plan_repreview_error(
locale,
"import_plan_catalog_stale",
));
}
// Server-authored immutable plan. Client-supplied candidate material,
// digests or payload fields are not read: every value below derives
// from the verified job preview and the revalidated decisions.
let all_keys: Vec<String> = all_set.iter().cloned().collect();
let plan_counts_value = json!({
"selected": counts.selected,
"excluded": counts.excluded,
"actionable": counts.actionable,
"blocked": counts.blocked,
});
let plan_reference = new_prefixed_id("plan");
let plan_payload = json!({
"schema_version": "import-plan-v2",
"plan_reference": plan_reference,
"job_id": job_id.as_str(),
"server_url": payload.server_url,
"source": {
"source_id": resolved.source.source_id.as_str(),
"digest": resolved.source.digest.as_str(),
},
"dependencies": job.preview_payload.get("dependencies").cloned().unwrap_or(json!([])),
"fingerprint": resolved.fingerprint,
"catalog_revision": catalog_revision,
"support_matrix_version": OPENAPI_SUPPORT_MATRIX_VERSION,
"findings": {
"document": preview.findings,
"candidates": candidates.iter().map(|(key, candidate)| json!({
"key": key,
"findings": candidate.findings,
})).collect::<Vec<_>>(),
},
"selection": {
"mode": payload.selection_mode,
"all": all_keys,
"selected": selected_keys,
"excluded": excluded,
},
"excluded_reasons": excluded_reasons.iter().map(|(key, (name, reason))| json!({
"key": key,
"name": name,
"reason": reason,
})).collect::<Vec<_>>(),
"counts": plan_counts_value,
"candidates": planned.iter().map(plan_candidate_payload).collect::<Result<Vec<_>, _>>()?,
});
let plan_reference_id = ImportPlanId::new(&plan_reference);
let created = self
.registry
.create_import_plan(CreateImportPlanRequest {
id: &plan_reference_id,
workspace_id,
job_id,
payload: &plan_payload,
created_at: &now,
expires_at: &job.expires_at,
})
.await
.map_err(ApiError::from)?;
let mut candidate_views: Vec<OpenApiImportPlanCandidateView> = planned
.iter()
.map(|candidate| OpenApiImportPlanCandidateView {
key: candidate.key.clone(),
name: candidate.name.clone(),
state: if candidate.blocked {
"blocked"
} else {
"actionable"
}
.to_owned(),
action: Some(candidate.action.clone()),
target_operation_id: candidate.target_operation_id.clone(),
confirmed_name: candidate.confirmed_name.clone(),
auth_profile_id: candidate.auth_profile_id.clone(),
security_alternative_index: candidate.security_alternative_index,
reason: candidate.reason.clone(),
})
.collect();
candidate_views.extend(excluded.iter().map(|key| {
let name = excluded_reasons
.get(key)
.map(|(name, _)| name.clone())
.unwrap_or_else(|| key.clone());
OpenApiImportPlanCandidateView {
key: key.clone(),
name,
state: "excluded".to_owned(),
action: None,
target_operation_id: None,
confirmed_name: None,
auth_profile_id: None,
security_alternative_index: None,
reason: excluded_reasons.get(key).map(|(_, reason)| reason.clone()),
}
}));
Ok(OpenApiImportPlanCreateResponse {
plan_reference: created.id.as_str().to_owned(),
plan_digest: created.digest,
catalog_revision,
support_matrix_version: OPENAPI_SUPPORT_MATRIX_VERSION.to_owned(),
expires_at: created
.expires_at
.format(&Rfc3339)
.map_err(|error| ApiError::internal(error.to_string()))?,
selection_mode: payload.selection_mode,
counts,
candidates: candidate_views,
})
}
/// Materializes one selected candidate of the plan: the confirmed
/// decision, the exact authorized target with its expected state and the
/// full Draft snapshot (create/rename/new_version) or the bounded
/// redacted rejection reason (blocked).
async fn plan_import_candidate(
&self,
workspace_id: &WorkspaceId,
server_url: Option<&str>,
candidate: &ImportOperationCandidate,
decision: Option<&OpenApiImportPlanDecision>,
blocker_reason: Option<String>,
locale: OpenApiUploadLocale,
) -> Result<PlannedCandidate, ApiError> {
let action = decision
.map(|decision| decision.action.as_str())
.unwrap_or("create");
let target_operation_id =
decision.and_then(|decision| decision.target_operation_id.clone());
let confirmed_name = decision.and_then(|decision| decision.confirmed_name.clone());
let auth_profile_id = decision.and_then(|decision| decision.auth_profile_id.clone());
let requested_security_alternative =
decision.and_then(|decision| decision.security_alternative_index);
let mut blocker_reason = blocker_reason;
let candidate_name = candidate.draft.name.clone();
let mut blocked = blocker_reason.is_some();
// Explicit skip/new_version targets are always resolved in the
// workspace: an unknown target, a name mismatch, or an incompatible
// protocol is a request error even when the candidate is already
// blocked.
let mut target = None;
let mut target_summary = None;
let mut next_version: Option<u32> = None;
if matches!(action, "skip" | "new_version") {
let target_id = target_operation_id
.as_ref()
.expect("target_operation_id is validated for skip/new_version")
.clone();
let target_operation = OperationId::new(target_id.clone());
let summary = self
.registry
.get_operation_summary(workspace_id, &target_operation)
.await?
.ok_or_else(|| {
ApiError::validation_with_context(
"decision target operation was not found in this workspace",
json!({
"target_operation_id": target_id,
"error_code": "import_plan_target_invalid"
}),
)
})?;
if summary.name != candidate_name {
return Err(ApiError::validation_with_context(
"decision target does not match the candidate name in this workspace",
json!({
"target_operation_id": target_id,
"error_code": "import_plan_target_invalid"
}),
));
}
if action == "new_version"
&& (summary.protocol != Protocol::Rest
|| summary.status == OperationStatus::Archived)
{
return Err(ApiError::validation_with_context(
"new_version target must be an active REST operation",
json!({
"target_operation_id": target_id,
"error_code": "import_plan_target_invalid"
}),
));
}
target = Some(json!({
"operation_id": target_id,
"name": summary.name,
"expected_state": {
"status": serde_json::to_value(summary.status)
.map_err(|error| ApiError::internal(error.to_string()))?,
"current_draft_version": summary.current_draft_version,
"latest_published_version": summary.latest_published_version,
},
}));
if action == "new_version" {
let version = summary
.current_draft_version
.checked_add(1)
.filter(|value| i32::try_from(*value).is_ok())
.ok_or_else(|| {
ApiError::conflict_with_context(
"operation revision limit reached",
json!({ "error_code": "operation_revision_exhausted" }),
)
})?;
next_version = Some(version);
}
target_summary = Some(summary);
}
// create/rename must land on a name that is free now; the server
// never auto-selects a replacement when the confirmed name is taken.
if !blocked && matches!(action, "create" | "rename") {
let final_name = confirmed_name.as_deref().unwrap_or(candidate_name.as_str());
if self
.find_operation_by_name(workspace_id, final_name)
.await?
.is_some()
{
if action == "create" && decision.is_none() {
return Ok(PlannedCandidate {
key: candidate.key.clone(),
name: candidate_name,
blocked: true,
reason: Some("operation_name_conflict".to_owned()),
action: action.to_owned(),
target_operation_id,
confirmed_name,
auth_profile_id,
security_alternative_index: requested_security_alternative,
auth_requirement: None,
auth_snapshot: None,
target: None,
operation: None,
});
}
let message = match locale {
OpenApiUploadLocale::Ru => {
format!("операция с именем {final_name} уже существует")
}
OpenApiUploadLocale::En => {
format!("operation with name {final_name} already exists")
}
};
return Err(ApiError::conflict_with_context(
message,
json!({
"name": final_name,
"error_code": "import_plan_name_conflict",
"recovery": "confirm_skip_rename_or_new_version"
}),
));
}
}
// Use an explicit decision or inherit the target reference for new_version.
let mut auth_profile_ref = auth_profile_id
.as_deref()
.map(|id| AuthProfileId::new(id.to_owned()));
let mut inherited_auth_profile = false;
if let Some(summary) = target_summary.as_ref()
&& !blocked
&& action == "new_version"
&& auth_profile_ref.is_none()
&& (candidate.security_requirements.source == SecuritySource::None
|| !candidate.security_requirements.alternatives.is_empty())
{
let record = self
.registry
.get_operation_version(workspace_id, &summary.id, summary.current_draft_version)
.await?
.ok_or_else(|| ApiError::internal("current operation version is unavailable"))?;
auth_profile_ref = record.snapshot.execution_config.auth_profile_ref;
inherited_auth_profile = auth_profile_ref.is_some();
}
let auth_profile_id = auth_profile_ref.as_ref().map(|id| id.as_str().to_owned());
let inherited_unconstrained_auth = inherited_auth_profile
&& action == "new_version"
&& candidate.security_requirements.source
== crank_import::rest::SecurityRequirementsSource::None
&& candidate.security_requirements.alternatives.is_empty()
&& requested_security_alternative.is_none();
let security_alternative_index = if blocked {
requested_security_alternative
} else if inherited_unconstrained_auth {
None
} else {
resolve_security_binding(
self,
workspace_id,
candidate,
auth_profile_ref.as_ref(),
requested_security_alternative,
&mut blocker_reason,
)
.await?
};
blocked = blocker_reason.is_some();
let auth_requirement = if !blocked && inherited_unconstrained_auth {
Some(json!({ "kind": "unconstrained" }))
} else if !blocked && auth_profile_ref.is_some() {
security_alternative_index
.and_then(|index| candidate.security_requirements.alternatives.get(index))
.and_then(|alternative| {
(alternative.schemes.len() == 1).then(|| &alternative.schemes[0])
})
.and_then(|scheme_name| candidate.security_schemes.get(scheme_name))
.and_then(|scheme| match &scheme.kind {
crank_import::rest::NormalizedSecuritySchemeKind::Http { scheme, .. } => {
match scheme.to_ascii_lowercase().as_str() {
"bearer" => Some(json!({ "kind": "bearer" })),
"basic" => Some(json!({ "kind": "basic" })),
_ => None,
}
}
crank_import::rest::NormalizedSecuritySchemeKind::ApiKey {
location: crank_import::rest::SecurityParameterLocation::Header,
parameter_name,
..
} => {
Some(json!({ "kind": "api_key_header", "parameter_name": parameter_name }))
}
crank_import::rest::NormalizedSecuritySchemeKind::ApiKey {
location: crank_import::rest::SecurityParameterLocation::Query,
parameter_name,
..
} => Some(json!({ "kind": "api_key_query", "parameter_name": parameter_name })),
_ => None,
})
} else {
None
};
if blocked {
return Ok(PlannedCandidate {
key: candidate.key.clone(),
name: candidate_name,
blocked: true,
reason: blocker_reason,
action: action.to_owned(),
target_operation_id,
confirmed_name,
auth_profile_id,
security_alternative_index,
auth_requirement,
auth_snapshot: None,
target,
operation: None,
});
}
if action == "skip" {
return Ok(PlannedCandidate {
key: candidate.key.clone(),
name: candidate_name,
blocked: false,
reason: None,
action: action.to_owned(),
target_operation_id,
confirmed_name,
auth_profile_id,
security_alternative_index,
auth_requirement: None,
auth_snapshot: None,
target,
operation: None,
});
}
let mut draft = operation_draft_from_candidate(candidate, server_url);
if action == "rename" {
draft.name = confirmed_name
.clone()
.expect("rename decisions carry the exact confirmed_name");
}
attach_import_findings(&mut draft, candidate);
let operation = self.new_operation_snapshot(OperationPayload {
name: draft.name.clone(),
display_name: draft.display_name.clone(),
category: draft.category,
protocol: Protocol::Rest,
security_level: OperationSecurityLevel::Standard,
target: crank_core::Target::Rest(draft.target),
input_schema: draft.input_schema,
output_schema: draft.output_schema,
input_mapping: draft.input_mapping,
output_mapping: draft.output_mapping,
execution_config: ExecutionConfig {
timeout_ms: 10_000,
retry_policy: None,
response_cache: None,
idempotency: None,
safety: None,
approval_policy: None,
auth_profile_ref,
headers: BTreeMap::new(),
},
tool_description: draft.tool_description,
wizard_state: draft.wizard_state,
})?;
// The same workspace/auth secret validator the operation creation
// path uses: the referenced profile and its active secret refs must
// resolve in this workspace before the plan is accepted.
self.validate_registry_operation_in_workspace(workspace_id, &operation)
.await?;
let mut operation = operation;
if action == "new_version" {
let target_id = target_operation_id
.clone()
.expect("new_version decisions carry target_operation_id");
operation.id = OperationId::new(target_id);
operation.version = next_version.expect("new_version computes the next Draft version");
}
let auth_snapshot = match operation.execution_config.auth_profile_ref.as_ref() {
Some(profile_id) => Some(self.import_auth_snapshot(workspace_id, profile_id).await?),
None => None,
};
Ok(PlannedCandidate {
key: candidate.key.clone(),
name: draft.name,
blocked: false,
reason: None,
action: action.to_owned(),
target_operation_id,
confirmed_name,
auth_profile_id,
security_alternative_index,
auth_requirement,
auth_snapshot,
target,
operation: Some(operation),
})
}
/// Captures only profile configuration and secret metadata. Credential
/// values never enter the plan; Apply compares this snapshot under locks.
async fn import_auth_snapshot(
&self,
workspace_id: &WorkspaceId,
profile_id: &AuthProfileId,
) -> Result<Value, ApiError> {
let unavailable = || {
ApiError::unprocessable_with_context(
"The selected authentication profile is unavailable for this import.",
json!({ "error_code": "import_plan_auth_unavailable" }),
)
};
let profile = self
.registry
.get_auth_profile(workspace_id, profile_id)
.await?
.ok_or_else(unavailable)?;
let mut secret_ids: Vec<String> = profile
.config
.secret_ids()
.into_iter()
.map(|id| id.as_str().to_owned())
.collect();
secret_ids.sort();
secret_ids.dedup();
let mut secrets = Vec::with_capacity(secret_ids.len());
for id in secret_ids {
let secret = self
.registry
.get_secret(workspace_id, &crank_core::SecretId::new(id.clone()))
.await?
.ok_or_else(unavailable)?
.secret;
secrets.push(json!({
"id": id,
"status": secret.status,
"current_version": secret.current_version,
"updated_at": secret.updated_at.format(&Rfc3339)
.map_err(|error| ApiError::internal(error.to_string()))?,
}));
}
Ok(json!({
"profile_id": profile_id.as_str(),
"name": profile.name,
"kind": profile.kind,
"config": profile.config,
"updated_at": profile.updated_at.format(&Rfc3339)
.map_err(|error| ApiError::internal(error.to_string()))?,
"secrets": secrets,
}))
}
}
struct PlannedCandidate {
key: String,
name: String,
blocked: bool,
reason: Option<String>,
action: String,
target_operation_id: Option<String>,
confirmed_name: Option<String>,
auth_profile_id: Option<String>,
security_alternative_index: Option<usize>,
auth_requirement: Option<Value>,
auth_snapshot: Option<Value>,
target: Option<Value>,
operation: Option<RegistryOperation>,
}
pub(super) fn import_plan_repreview_error(
locale: OpenApiUploadLocale,
error_code: &'static str,
) -> ApiError {
let message = match locale {
OpenApiUploadLocale::Ru => {
"не удалось повторно проверить план импорта; создайте новый preview"
}
OpenApiUploadLocale::En => "import plan revalidation failed; create a fresh preview",
};
ApiError::conflict_with_context(
message,
json!({
"error_code": error_code,
"recovery": "repreview_required",
"repreview_required": true
}),
)
}
/// Closes the selection against the current preview: `full` keeps every
/// candidate (an explicit list must equal the whole candidate set), `partial`
/// requires a non-empty exact subset. Unknown or duplicate keys are rejected
/// before any plan material exists.
fn resolve_plan_selection(
selection_mode: &str,
requested: &[String],
all: &BTreeSet<String>,
) -> Result<BTreeSet<String>, ApiError> {
if !matches!(selection_mode, "full" | "partial") {
return Err(ApiError::validation_with_context(
"selection_mode must be full or partial",
json!({ "error_code": "import_plan_invalid_input" }),
));
}
if requested.len() > MAX_IMPORT_PLAN_KEYS {
return Err(ApiError::validation_with_context(
"too many selected_operation_keys for this import plan",
json!({ "error_code": "import_plan_invalid_input" }),
));
}
for key in requested {
if key.is_empty() || key.len() > MAX_IMPORT_PLAN_KEY_BYTES {
return Err(ApiError::validation_with_context(
"selected_operation_keys entries are empty or too long",
json!({ "error_code": "import_plan_invalid_input" }),
));
}
}
let requested_set: BTreeSet<&String> = requested.iter().collect();
if requested_set.len() != requested.len() {
return Err(ApiError::validation_with_context(
"selected_operation_keys contains duplicates",
json!({ "error_code": "import_plan_invalid_input" }),
));
}
let all_set: BTreeSet<&String> = all.iter().collect();
match selection_mode {
"full" => {
if !requested_set.is_empty() && requested_set != all_set {
return Err(ApiError::validation_with_context(
"full selection covers the entire candidate set; selected_operation_keys does not match the preview",
json!({ "error_code": "import_plan_selection_mismatch" }),
));
}
Ok(all.clone())
}
_ => {
if requested_set.is_empty() {
return Err(ApiError::validation_with_context(
"partial selection requires at least one selected_operation_key",
json!({ "error_code": "import_plan_invalid_input" }),
));
}
if !requested_set.is_subset(&all_set) {
return Err(ApiError::validation_with_context(
"selected_operation_keys reference operations absent from the preview",
json!({ "error_code": "import_plan_unknown_operation_key" }),
));
}
Ok(requested.iter().cloned().collect())
}
}
}
async fn resolve_security_binding(
service: &AdminService,
workspace_id: &WorkspaceId,
candidate: &ImportOperationCandidate,
profile_ref: Option<&AuthProfileId>,
requested_index: Option<usize>,
blocker_reason: &mut Option<String>,
) -> Result<Option<usize>, ApiError> {
let alternatives = &candidate.security_requirements.alternatives;
if alternatives.is_empty() {
if profile_ref.is_some() || requested_index.is_some() {
return Err(ApiError::validation_with_context(
"security binding was supplied for an operation with no security requirement",
json!({ "operation_key": candidate.key, "error_code": "import_plan_auth_incompatible" }),
));
}
return Ok(None);
}
let public_index = alternatives
.iter()
.position(|alternative| alternative.supported && alternative.schemes.is_empty());
let compatible = if let Some(profile_ref) = profile_ref {
let profile = service
.registry
.get_auth_profile(workspace_id, profile_ref)
.await?
.ok_or_else(|| {
ApiError::unprocessable_with_context(
"selected Auth Profile is unavailable in this workspace",
json!({ "error_code": "import_plan_auth_unavailable" }),
)
})?;
let compatible = alternatives
.iter()
.enumerate()
.filter(|(_, alternative)| {
alternative.supported
&& alternative.schemes.len() == 1
&& candidate
.security_schemes
.get(&alternative.schemes[0])
.is_some_and(|scheme| auth_config_matches_scheme(&profile.config, scheme))
})
.map(|(index, _)| index)
.collect::<Vec<_>>();
Some((profile, compatible))
} else {
None
};
if let Some((_, compatible_indices)) = compatible.as_ref() {
let selected = match requested_index {
Some(index) if compatible_indices.contains(&index) => index,
Some(_) => {
return Err(ApiError::validation_with_context(
"selected Auth Profile is incompatible with the selected security alternative",
json!({ "operation_key": candidate.key, "error_code": "import_plan_auth_incompatible" }),
));
}
None if compatible_indices.len() == 1 => compatible_indices[0],
None if compatible_indices.is_empty() => {
return Err(ApiError::validation_with_context(
"selected Auth Profile is incompatible with the source security schemes",
json!({ "operation_key": candidate.key, "error_code": "import_plan_auth_incompatible" }),
));
}
None => {
return Err(ApiError::validation_with_context(
"security_alternative_index is required when a profile matches multiple alternatives",
json!({ "operation_key": candidate.key, "error_code": "import_plan_security_alternative_required" }),
));
}
};
return Ok(Some(selected));
}
if let Some(index) = requested_index {
if alternatives
.get(index)
.is_none_or(|alternative| !alternative.supported)
{
return Err(ApiError::validation_with_context(
"selected security alternative is unsupported",
json!({ "operation_key": candidate.key, "error_code": "import_plan_auth_incompatible" }),
));
}
if alternatives[index].schemes.is_empty() {
return Ok(Some(index));
}
}
if let Some(public_index) = public_index
&& requested_index.is_none()
{
return Ok(Some(public_index));
}
*blocker_reason = Some("auth_profile_required".to_owned());
Ok(requested_index)
}
pub(super) fn auth_config_matches_scheme(
config: &AuthConfig,
scheme: &crank_import::rest::NormalizedSecurityScheme,
) -> bool {
use crank_import::rest::{NormalizedSecuritySchemeKind, SecurityParameterLocation};
match (&scheme.kind, config) {
(NormalizedSecuritySchemeKind::Http { scheme, .. }, AuthConfig::Bearer(_)) => {
scheme.eq_ignore_ascii_case("bearer")
}
(NormalizedSecuritySchemeKind::Http { scheme, .. }, AuthConfig::Basic(_)) => {
scheme.eq_ignore_ascii_case("basic")
}
(
NormalizedSecuritySchemeKind::ApiKey {
location: SecurityParameterLocation::Header,
parameter_name,
..
},
AuthConfig::ApiKeyHeader(config),
) => parameter_name.eq_ignore_ascii_case(&config.header_name),
(
NormalizedSecuritySchemeKind::ApiKey {
location: SecurityParameterLocation::Query,
parameter_name,
..
},
AuthConfig::ApiKeyQuery(config),
) => parameter_name == &config.param_name,
_ => false,
}
}
/// Serializes one planned candidate into the versioned plan payload: the
/// redacted decision, the bounded rejection reason (if any), the exact
/// authorized target with expected state and, for mutating actions, the full
/// server-authored Draft snapshot.
fn plan_candidate_payload(candidate: &PlannedCandidate) -> Result<Value, ApiError> {
let mut object = json!({
"key": candidate.key,
"name": candidate.name,
"state": if candidate.blocked { "blocked" } else { "actionable" },
"decision": {
"action": candidate.action,
"target_operation_id": candidate.target_operation_id,
"confirmed_name": candidate.confirmed_name,
"auth_profile_id": candidate.auth_profile_id,
"security_alternative_index": candidate.security_alternative_index,
},
});
if let Some(reason) = &candidate.reason {
object["reason"] = json!(reason);
}
if let Some(target) = &candidate.target {
object["target"] = target.clone();
}
if let Some(auth_snapshot) = &candidate.auth_snapshot {
object["auth_snapshot"] = auth_snapshot.clone();
}
if let Some(auth_requirement) = &candidate.auth_requirement {
object["auth_requirement"] = auth_requirement.clone();
}
if let Some(operation) = &candidate.operation {
let value = serde_json::to_value(operation)
.map_err(|error| ApiError::internal(error.to_string()))?;
object["operation"] = value;
}
Ok(object)
}
@@ -0,0 +1,128 @@
use super::*;
/// Binds decisions to selected candidates with action-specific field rules:
/// unknown/duplicate keys, foreign fields and oversized references are
/// rejected before the plan is materialized.
pub(super) fn validate_plan_decisions<'input>(
decisions: &'input [OpenApiImportPlanDecision],
selected: &BTreeSet<String>,
) -> Result<BTreeMap<String, &'input OpenApiImportPlanDecision>, ApiError> {
let invalid = |context: Value| {
Err(ApiError::validation_with_context(
"import plan decision is invalid",
context,
))
};
let mut mapping = BTreeMap::new();
for decision in decisions {
if decision.operation_key.is_empty()
|| decision.operation_key.len() > MAX_IMPORT_PLAN_KEY_BYTES
{
return invalid(json!({
"operation_key": decision.operation_key,
"error_code": "import_plan_invalid_input"
}));
}
if !matches!(
decision.action.as_str(),
"create" | "skip" | "rename" | "new_version"
) {
return invalid(json!({
"operation_key": decision.operation_key,
"error_code": "import_plan_invalid_input"
}));
}
validate_decision_fields(decision)?;
if !selected.contains(&decision.operation_key) {
return invalid(json!({
"operation_key": decision.operation_key,
"error_code": "import_plan_decision_unselected"
}));
}
if mapping
.insert(decision.operation_key.clone(), decision)
.is_some()
{
return invalid(json!({
"operation_key": decision.operation_key,
"error_code": "import_plan_invalid_input"
}));
}
}
Ok(mapping)
}
fn validate_decision_fields(decision: &OpenApiImportPlanDecision) -> Result<(), ApiError> {
let context = json!({
"operation_key": decision.operation_key,
"error_code": "import_plan_invalid_input"
});
let invalid = |message: &str| -> Result<(), ApiError> {
Err(ApiError::validation_with_context(message, context.clone()))
};
if decision
.target_operation_id
.as_deref()
.is_some_and(|value| value.is_empty() || value.len() > MAX_IMPORT_PLAN_ID_REF_BYTES)
{
return invalid("decision target_operation_id is empty or too long");
}
if decision
.confirmed_name
.as_deref()
.is_some_and(|value| value.is_empty() || value.len() > MAX_IMPORT_PLAN_NAME_BYTES)
{
return invalid("decision confirmed_name is empty or too long");
}
if decision
.auth_profile_id
.as_deref()
.is_some_and(|value| value.is_empty() || value.len() > MAX_IMPORT_PLAN_ID_REF_BYTES)
{
return invalid("decision auth_profile_id is empty or too long");
}
if decision
.security_alternative_index
.is_some_and(|index| index > MAX_IMPORT_PLAN_KEYS)
{
return invalid("decision security_alternative_index is too large");
}
match decision.action.as_str() {
"create" => {
if decision.target_operation_id.is_some() || decision.confirmed_name.is_some() {
return invalid(
"target_operation_id and confirmed_name are not allowed for action create",
);
}
}
"skip" => {
if decision.auth_profile_id.is_some() || decision.security_alternative_index.is_some() {
return invalid("security binding is not allowed for action skip");
}
if decision.target_operation_id.is_none() {
return invalid("action skip requires the exact target_operation_id");
}
if decision.confirmed_name.is_some() {
return invalid("confirmed_name is not allowed for action skip");
}
}
"rename" => {
if decision.target_operation_id.is_some() {
return invalid("target_operation_id is not allowed for action rename");
}
if decision.confirmed_name.is_none() {
return invalid("action rename requires the exact confirmed_name");
}
}
"new_version" => {
if decision.target_operation_id.is_none() {
return invalid("action new_version requires the exact target_operation_id");
}
if decision.confirmed_name.is_some() {
return invalid("confirmed_name is not allowed for action new_version");
}
}
_ => unreachable!("decision action is validated before the field rules"),
}
Ok(())
}
@@ -0,0 +1,440 @@
use super::*;
use crank_registry::{ApplyImportPlanRequest, ImportPlanApplyReport};
const MAX_IMPORT_PLAN_IDEMPOTENCY_KEY_BYTES: usize = 128;
impl AdminService {
/// Reads an immutable plan and checks its current authority without Apply mutations.
pub async fn revalidate_openapi_import_plan(
&self,
workspace_id: &WorkspaceId,
plan_id: &ImportPlanId,
) -> Result<OpenApiImportPlanRevalidationResponse, ApiError> {
self.revalidate_openapi_import_plan_with_locale(
workspace_id,
plan_id,
OpenApiUploadLocale::En,
)
.await
}
/// Locale-aware variant used by the HTTP boundary.
pub async fn revalidate_openapi_import_plan_with_locale(
&self,
workspace_id: &WorkspaceId,
plan_id: &ImportPlanId,
locale: OpenApiUploadLocale,
) -> Result<OpenApiImportPlanRevalidationResponse, ApiError> {
self.ensure_workspace_exists(workspace_id).await?;
let plan = self
.registry
.get_import_plan(workspace_id, plan_id)
.await?
.ok_or_else(|| {
ApiError::not_found_with_context(
"import plan was not found in this workspace",
json!({ "error_code": "import_plan_not_found" }),
)
})?;
let mut reason = None;
let now = OffsetDateTime::now_utc();
if plan.expires_at <= now {
reason = Some("import_plan_expired");
} else if let Some(job) = self
.registry
.get_import_job(workspace_id, &plan.job_id)
.await?
{
if job.kind != ImportJobKind::OpenApi
|| job.status != ImportJobStatus::Pending
|| job.expires_at <= now
{
reason = Some("import_plan_job_terminal");
} else {
match self
.resolve_verified_openapi_preview(workspace_id, &job, locale)
.await
{
Ok(resolved) => {
let v2 = plan.payload.get("schema_version").and_then(Value::as_str)
== Some("import-plan-v2");
if self
.read_import_job_dependencies(
workspace_id,
&job.preview_payload,
locale,
)
.await
.is_err()
{
reason = Some("import_dependency_verification_failed");
} else if !v2 {
// Historical plans stay readable for audit, but lack the
// catalog evidence required for current Apply authority.
reason = Some("importer_version_changed");
} else if resolved
.fingerprint
.get("normalizer_version")
.and_then(Value::as_str)
!= Some(NORMALIZER_VERSION)
|| resolved
.fingerprint
.get("projection_version")
.and_then(Value::as_str)
!= Some(PROJECTION_VERSION)
|| plan
.payload
.get("support_matrix_version")
.and_then(Value::as_str)
!= Some(OPENAPI_SUPPORT_MATRIX_VERSION)
{
reason = Some("importer_version_changed");
} else if self
.registry
.revalidate_import_plan(workspace_id, plan_id, &resolved.fingerprint)
.await
.is_err()
{
reason = Some("import_plan_revalidation_failed");
}
}
Err(_) => reason = Some("import_preview_revalidation_failed"),
}
}
} else {
reason = Some("import_plan_job_unavailable");
}
let counts = &plan.payload["counts"];
let count = |key: &str| {
counts
.get(key)
.and_then(Value::as_u64)
.and_then(|value| usize::try_from(value).ok())
.unwrap_or(0)
};
let selected = plan.payload["candidates"]
.as_array()
.into_iter()
.flatten()
.map(|candidate| {
let decision = &candidate["decision"];
let string = |value: &Value| value.as_str().map(str::to_owned);
OpenApiImportPlanCandidateView {
key: string(&candidate["key"]).unwrap_or_default(),
name: string(&candidate["name"]).unwrap_or_default(),
state: string(&candidate["state"]).unwrap_or_default(),
action: string(&decision["action"]),
target_operation_id: string(&decision["target_operation_id"]),
confirmed_name: string(&decision["confirmed_name"]),
auth_profile_id: string(&decision["auth_profile_id"]),
security_alternative_index: decision["security_alternative_index"]
.as_u64()
.and_then(|value| usize::try_from(value).ok()),
reason: string(&candidate["reason"]),
}
});
let excluded = plan
.payload
.pointer("/selection/excluded")
.and_then(Value::as_array)
.into_iter()
.flatten()
.filter_map(Value::as_str)
.map(|key| OpenApiImportPlanCandidateView {
key: key.to_owned(),
name: excluded_candidate_display_name(&plan.payload, key),
state: "excluded".to_owned(),
action: None,
target_operation_id: None,
confirmed_name: None,
auth_profile_id: None,
security_alternative_index: None,
reason: plan.payload["excluded_reasons"]
.as_array()
.and_then(|items| items.iter().find(|item| item["key"].as_str() == Some(key)))
.and_then(|item| item["reason"].as_str())
.map(str::to_owned)
.or_else(|| Some("not_selected".to_owned())),
});
Ok(OpenApiImportPlanRevalidationResponse {
plan_reference: plan.id.as_str().to_owned(),
plan_digest: plan.digest,
revalidation_status: if reason.is_some() { "stale" } else { "current" }.to_owned(),
revalidation_required: reason.is_some(),
reason: reason.map(str::to_owned),
counts: OpenApiImportPlanCounts {
selected: count("selected"),
excluded: count("excluded"),
actionable: count("actionable"),
blocked: count("blocked"),
},
candidates: selected.chain(excluded).collect(),
})
}
pub async fn apply_openapi_import_plan(
&self,
workspace_id: &WorkspaceId,
plan_id: &ImportPlanId,
payload: OpenApiImportPlanApplyPayload,
) -> Result<ImportPlanApplyReport, ApiError> {
self.apply_openapi_import_plan_with_locale(
workspace_id,
plan_id,
payload,
OpenApiUploadLocale::En,
)
.await
}
#[instrument(skip(self, payload), fields(workspace_id = %workspace_id.as_str(), plan_id = %plan_id.as_str()))]
pub async fn apply_openapi_import_plan_with_locale(
&self,
workspace_id: &WorkspaceId,
plan_id: &ImportPlanId,
payload: OpenApiImportPlanApplyPayload,
locale: OpenApiUploadLocale,
) -> Result<ImportPlanApplyReport, ApiError> {
self.ensure_workspace_exists(workspace_id).await?;
validate_apply_payload(&payload)?;
// The replay row is deliberately checked before the plan or job.
// Its report remains authoritative after normal TTL cleanup removes
// those source rows.
if let Some(application) = self
.registry
.get_import_plan_application(workspace_id, &payload.idempotency_key)
.await?
{
if application.plan_digest != payload.plan_digest {
return Err(key_digest_conflict(locale));
}
return Ok(application.result.report);
}
let plan = self
.registry
.get_import_plan(workspace_id, plan_id)
.await?
.ok_or_else(|| {
ApiError::not_found_with_context(
"import plan was not found in this workspace",
json!({ "error_code": "import_plan_not_found" }),
)
})?;
if plan.digest != payload.plan_digest {
return Err(import_plan_repreview_error(
locale,
"import_plan_digest_mismatch",
));
}
let now = OffsetDateTime::now_utc();
if plan.expires_at <= now {
return Err(import_plan_repreview_error(locale, "import_plan_expired"));
}
let job = self
.registry
.get_import_job(workspace_id, &plan.job_id)
.await?
.ok_or_else(|| import_plan_repreview_error(locale, "import_plan_job_unavailable"))?;
if job.kind != ImportJobKind::OpenApi {
return Err(import_plan_repreview_error(
locale,
"import_plan_job_kind_mismatch",
));
}
if job.status != ImportJobStatus::Pending || job.expires_at <= now {
return Err(import_plan_repreview_error(
locale,
"import_plan_job_terminal",
));
}
let resolved = self
.resolve_verified_openapi_preview(workspace_id, &job, locale)
.await
.map_err(|resolution| match resolution {
ImportPreviewResolution::Fatal(error_code, _) => {
import_plan_repreview_error(locale, error_code)
}
ImportPreviewResolution::NonFatal(_) => {
import_plan_repreview_error(locale, "import_preview_revalidation_failed")
}
})?;
// Applying a new plan requires the current normalizer/projection
// contract. Historic jobs remain available to the legacy replay path,
// but a plan created from a historic projection must be previewed
// again before it can authorize mutations.
if resolved
.fingerprint
.get("normalizer_version")
.and_then(Value::as_str)
!= Some(NORMALIZER_VERSION)
|| resolved
.fingerprint
.get("projection_version")
.and_then(Value::as_str)
!= Some(PROJECTION_VERSION)
|| (plan.payload.get("schema_version").and_then(Value::as_str)
== Some("import-plan-v2")
&& plan
.payload
.get("support_matrix_version")
.and_then(Value::as_str)
!= Some(OPENAPI_SUPPORT_MATRIX_VERSION))
{
return Err(import_plan_repreview_error(
locale,
"importer_version_changed",
));
}
// Verify every persisted external snapshot again without making a
// network request. The registry repeats source/dependency checks
// under its transaction before it mutates operations.
self.read_import_job_dependencies(workspace_id, &job.preview_payload, locale)
.await
.map_err(|_| {
import_plan_repreview_error(locale, "import_dependency_verification_failed")
})?;
let result = self
.registry
.apply_import_plan(&ApplyImportPlanRequest {
workspace_id,
plan_id,
plan_digest: &payload.plan_digest,
idempotency_key: &payload.idempotency_key,
verified_fingerprint: &resolved.fingerprint,
applied_at: &now,
})
.await
.map_err(|error| map_apply_registry_error(locale, error))?;
Ok(result.report)
}
}
fn excluded_candidate_display_name(plan: &Value, key: &str) -> String {
plan["excluded_reasons"]
.as_array()
.and_then(|items| items.iter().find(|item| item["key"].as_str() == Some(key)))
.and_then(|item| item["name"].as_str())
.filter(|name| !name.is_empty())
.unwrap_or(key)
.to_owned()
}
fn validate_apply_payload(payload: &OpenApiImportPlanApplyPayload) -> Result<(), ApiError> {
let digest_valid = payload.plan_digest.len() == 64
&& payload
.plan_digest
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte));
if !digest_valid {
return Err(ApiError::validation_with_context(
"plan_digest must be 64 lowercase hexadecimal characters",
json!({ "error_code": "import_plan_invalid_input" }),
));
}
if !(1..=MAX_IMPORT_PLAN_IDEMPOTENCY_KEY_BYTES).contains(&payload.idempotency_key.len())
|| payload.idempotency_key.trim() != payload.idempotency_key
|| payload.idempotency_key.chars().any(char::is_control)
{
return Err(ApiError::validation_with_context(
"idempotency_key must be a non-empty bounded printable value",
json!({ "error_code": "import_plan_invalid_input" }),
));
}
Ok(())
}
fn map_apply_registry_error(locale: OpenApiUploadLocale, error: RegistryError) -> ApiError {
match error {
RegistryError::ImportPlanNotFound { .. } => ApiError::not_found_with_context(
"import plan was not found in this workspace",
json!({ "error_code": "import_plan_not_found" }),
),
RegistryError::ImportPlanExpired { .. } => {
import_plan_repreview_error(locale, "import_plan_expired")
}
RegistryError::ImportPlanPayloadCorrupt { .. } => {
import_plan_repreview_error(locale, "import_plan_payload_invalid")
}
RegistryError::ImportPlanFingerprintStale { .. } => {
import_plan_repreview_error(locale, "import_plan_fingerprint_stale")
}
RegistryError::ImportPlanKeyDigestConflict { .. } => key_digest_conflict(locale),
RegistryError::ImportPlanNameConflict { .. } => {
let message = match locale {
OpenApiUploadLocale::Ru => "имя операции изменилось после создания плана",
OpenApiUploadLocale::En => "an operation name changed after the plan was created",
};
ApiError::conflict_with_context(
message,
json!({
"error_code": "import_plan_name_conflict",
"recovery": "confirm_skip_rename_or_new_version"
}),
)
}
RegistryError::ImportPlanTargetStale { .. } => {
import_plan_repreview_error(locale, "import_plan_target_stale")
}
RegistryError::ImportPlanAuthUnavailable { .. } => {
import_plan_repreview_error(locale, "import_plan_auth_unavailable")
}
other => ApiError::from(other),
}
}
fn key_digest_conflict(locale: OpenApiUploadLocale) -> ApiError {
let message = match locale {
OpenApiUploadLocale::Ru => {
"ключ идемпотентности уже зафиксирован для другого материала плана; создайте новый preview"
}
OpenApiUploadLocale::En => {
"idempotency key was already committed for different plan material"
}
};
ApiError::conflict_with_context(
message,
json!({
"error_code": "import_plan_key_digest_conflict",
"recovery": "repreview_required",
"repreview_required": true
}),
)
}
#[cfg(test)]
mod tests {
use super::excluded_candidate_display_name;
use serde_json::json;
#[test]
fn excluded_candidate_name_uses_persisted_display_name_and_legacy_key_fallback() {
let current = json!({
"excluded_reasons": [{
"key": "GET /alpha",
"name": "Alpha display label",
"reason": "not_selected"
}]
});
assert_eq!(
excluded_candidate_display_name(&current, "GET /alpha"),
"Alpha display label"
);
let historic = json!({
"excluded_reasons": [{ "key": "GET /alpha", "reason": "not_selected" }]
});
assert_eq!(
excluded_candidate_display_name(&historic, "GET /alpha"),
"GET /alpha"
);
}
}
@@ -0,0 +1,405 @@
use super::*;
/// Revalidates the verified source/dependency snapshots and the persisted
/// replay contract of a stored job without mutating the job. Both the
/// legacy Apply and the ImportPlan creation derive from this result, so
/// the legacy failure-text code travels with the outcome.
impl AdminService {
pub(super) async fn resolve_verified_openapi_preview(
&self,
workspace_id: &WorkspaceId,
job: &ImportJob,
locale: OpenApiUploadLocale,
) -> Result<ResolvedOpenApiPreview, ImportPreviewResolution> {
let source = match import_job_source(&job.preview_payload, locale) {
Ok(source) => source,
Err(error) => {
return Err(ImportPreviewResolution::Fatal(
"import_source_verification_failed",
error,
));
}
};
let verified = match self
.registry
.read_artifact_source(
std::sync::Arc::clone(&self.artifact_store),
workspace_id,
&source.source_id,
)
.await
{
Ok(verified) => verified,
Err(
error @ (RegistryError::SourceNotFound { .. } | RegistryError::SourceUnavailable),
) => {
return Err(ImportPreviewResolution::Fatal(
"import_source_verification_failed",
openapi_source_error(locale, error),
));
}
Err(error @ RegistryError::SourceIntegrity) => {
return Err(ImportPreviewResolution::Fatal(
"import_source_verification_failed",
openapi_source_error(locale, error),
));
}
Err(error) => {
return Err(ImportPreviewResolution::NonFatal(openapi_source_error(
locale, error,
)));
}
};
if verified.source.blob.artifact_ref != source.digest {
return Err(ImportPreviewResolution::Fatal(
"import_source_verification_failed",
ApiError::openapi_upload(locale, "source_integrity"),
));
}
let replay_contract = match import_replay_contract(&job.preview_payload, locale) {
Ok(contract) => contract,
Err(error) => {
return Err(ImportPreviewResolution::Fatal(
"import_replay_verification_failed",
error,
));
}
};
let (preview, normalizer_version, projection_version, ir_fingerprint) =
match replay_contract {
ImportReplayContract::PersistedV2(replay) => (
replay.preview.preview,
replay.normalizer_version,
replay.projection_version,
replay.preview.ir_fingerprint,
),
ImportReplayContract::LegacyV1 | ImportReplayContract::Current => {
let legacy_v1 = matches!(replay_contract, ImportReplayContract::LegacyV1);
let dependency_snapshots = self
.read_import_job_dependencies(workspace_id, &job.preview_payload, locale)
.await
.map_err(|error| {
ImportPreviewResolution::Fatal(
"import_dependency_verification_failed",
error,
)
})?;
let normalization_config = import_job_normalization_config(
&job.preview_payload,
&self.external_reference_normalization,
legacy_v1,
locale,
)
.map_err(|error| {
ImportPreviewResolution::Fatal("import_replay_verification_failed", error)
})?;
let parsed = parse_verified_preview(
verified.bytes,
source.digest.digest_hex().to_owned(),
dependency_snapshots,
normalization_config,
locale,
legacy_v1,
)
.await
.map_err(|error| {
ImportPreviewResolution::Fatal("import_replay_verification_failed", error)
})?;
if let Err(error) =
verify_preview_contract(&job.preview_payload, &parsed, locale)
{
return Err(ImportPreviewResolution::Fatal(
"import_replay_verification_failed",
error,
));
}
if legacy_v1 {
(parsed.preview, String::new(), String::new(), String::new())
} else {
(
parsed.preview,
NORMALIZER_VERSION.to_owned(),
PROJECTION_VERSION.to_owned(),
parsed.ir_fingerprint,
)
}
}
};
Ok(ResolvedOpenApiPreview {
source,
preview,
fingerprint: json!({
"normalizer_version": if normalizer_version.is_empty() { Value::Null } else { Value::String(normalizer_version) },
"projection_version": if projection_version.is_empty() { Value::Null } else { Value::String(projection_version) },
"ir_fingerprint": if ir_fingerprint.is_empty() { Value::Null } else { Value::String(ir_fingerprint) },
"preview_digest": job.preview_payload.get("preview_digest").and_then(Value::as_str).map(|digest| Value::String(digest.to_owned())).unwrap_or(Value::Null),
}),
})
}
}
pub(super) struct ParsedOpenApiPreview {
pub(super) preview: crank_import::rest::ImportPreview,
pub(super) ir_fingerprint: String,
}
/// Verified job preview material shared by the legacy Apply path and the
/// ImportPlan creation: the replay contract has held, no job mutation
/// happened.
pub(super) struct ResolvedOpenApiPreview {
pub(super) source: ImportJobSourceEnvelope,
pub(super) preview: crank_import::rest::ImportPreview,
pub(super) fingerprint: Value,
}
/// Outcome of a failed preview revalidation. `Fatal` codes are the same
/// stable failure texts the legacy path records on a failed job; the plan
/// path must surface the same material as a bounded re-preview conflict
/// without touching the job, because other stored plans may anchor to it.
pub(super) enum ImportPreviewResolution {
Fatal(&'static str, ApiError),
NonFatal(ApiError),
}
struct PersistedOpenApiReplay {
preview: ParsedOpenApiPreview,
normalizer_version: String,
projection_version: String,
}
enum ImportReplayContract {
LegacyV1,
PersistedV2(Box<PersistedOpenApiReplay>),
Current,
}
fn import_replay_contract(
payload: &serde_json::Value,
locale: OpenApiUploadLocale,
) -> Result<ImportReplayContract, ApiError> {
let Some(normalization) = payload.get("normalization") else {
return Ok(ImportReplayContract::LegacyV1);
};
let normalizer = normalization
.get("normalizer_version")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| ApiError::openapi_upload(locale, "source_integrity"))?;
let projection = normalization
.get("projection_version")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| ApiError::openapi_upload(locale, "source_integrity"))?;
let ir_fingerprint = normalization
.get("ir_fingerprint")
.and_then(serde_json::Value::as_str)
.filter(|value| is_lower_sha256(value))
.ok_or_else(|| ApiError::openapi_upload(locale, "source_integrity"))?;
let expected_preview_digest = payload
.get("preview_digest")
.and_then(serde_json::Value::as_str)
.filter(|value| is_lower_sha256(value))
.ok_or_else(|| ApiError::openapi_upload(locale, "source_integrity"))?;
if normalizer == NORMALIZER_VERSION && projection == PROJECTION_VERSION {
return Ok(ImportReplayContract::Current);
}
// Historical preview payloads are replayed as their persisted projection.
// They must never be parsed again with current normalization semantics.
if !matches!(
(normalizer, projection),
("normalized-ir-v2", "preview-v2")
| ("normalized-ir-v3", "preview-v3")
| ("normalized-ir-v4", "preview-v4")
| ("normalized-ir-v5", "preview-v5")
// The v5/preview-v6 pair predates the shared external-URI identity
// (normalized-ir-v6). Its saved projection is authoritative and is
// replayed verbatim, never reparsed under the current normalizer.
| ("normalized-ir-v5", "preview-v6")
) {
return Err(ApiError::openapi_upload(locale, "source_integrity"));
}
let preview_value = payload
.get("preview")
.cloned()
.ok_or_else(|| ApiError::openapi_upload(locale, "source_integrity"))?;
if preview_digest(&preview_value)? != expected_preview_digest {
return Err(ApiError::openapi_upload(locale, "source_integrity"));
}
let preview = serde_json::from_value(preview_value)
.map_err(|_| ApiError::openapi_upload(locale, "source_integrity"))?;
Ok(ImportReplayContract::PersistedV2(Box::new(
PersistedOpenApiReplay {
preview: ParsedOpenApiPreview {
preview,
ir_fingerprint: ir_fingerprint.to_owned(),
},
normalizer_version: normalizer.to_owned(),
projection_version: projection.to_owned(),
},
)))
}
fn is_lower_sha256(value: &str) -> bool {
value.len() == 64
&& value
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
}
pub(super) async fn parse_verified_preview(
bytes: Vec<u8>,
digest: String,
snapshots: Vec<crank_import::rest::ExternalDocumentSnapshot>,
normalization_config: crank_import::rest::NormalizationConfig,
locale: OpenApiUploadLocale,
legacy_v1: bool,
) -> Result<ParsedOpenApiPreview, ApiError> {
let started = tokio::time::Instant::now();
let permit = tokio::time::timeout(OPENAPI_PARSE_DEADLINE, OPENAPI_PARSE_SLOTS.acquire())
.await
.map_err(|_| ApiError::openapi_upload(locale, "parser_unavailable"))?
.map_err(|_| ApiError::openapi_upload(locale, "parser_unavailable"))?;
let parsing = tokio::task::spawn_blocking(move || {
// Keep the permit inside the blocking task. Timing out the caller
// cannot cancel CPU work already running, but abandoned parsers remain
// globally bounded and release capacity when they actually finish.
let _permit = permit;
let document = std::str::from_utf8(&bytes)
.map_err(|_| ApiError::openapi_upload(locale, "invalid_utf8"))?;
if legacy_v1 {
return crank_import::rest::preview_document_legacy_v1(document)
.map(|preview| ParsedOpenApiPreview {
preview,
ir_fingerprint: String::new(),
})
.map_err(|_| ApiError::openapi_upload(locale, "invalid_document"));
}
let digest = crank_import::rest::SourceDigest::parse(digest)
.map_err(|_| ApiError::openapi_upload(locale, "source_integrity"))?;
let ir = crank_import::rest::normalize_verified_bundle(
document,
digest,
&snapshots,
&normalization_config,
)
.map_err(|error| match error {
crank_import::rest::ImportParseError::NoMethods => {
ApiError::openapi_upload(locale, "no_methods")
}
_ => ApiError::openapi_upload(locale, "invalid_document"),
})?;
let ir_fingerprint = preview_digest(
&serde_json::to_value(&ir)
.map_err(|_| ApiError::openapi_upload(locale, "invalid_document"))?,
)?;
Ok::<_, ApiError>(ParsedOpenApiPreview {
preview: crank_import::rest::preview_from_ir(&ir),
ir_fingerprint,
})
});
let remaining = OPENAPI_PARSE_DEADLINE
.checked_sub(started.elapsed())
.unwrap_or(std::time::Duration::ZERO);
tokio::time::timeout(remaining, parsing)
.await
.map_err(|_| ApiError::openapi_upload(locale, "parser_unavailable"))?
.map_err(|_| ApiError::openapi_upload(locale, "parser_unavailable"))?
}
pub(super) fn artifact_error(locale: OpenApiUploadLocale, error: ArtifactError) -> ApiError {
match error {
ArtifactError::EmptySource => ApiError::openapi_upload(locale, "empty_file"),
ArtifactError::SourceTooLarge => ApiError::openapi_upload(locale, "file_too_large"),
ArtifactError::Integrity => ApiError::openapi_upload(locale, "source_integrity"),
ArtifactError::Storage
| ArtifactError::NotFound
| ArtifactError::InvalidReference
| ArtifactError::UnsafeRoot => ApiError::openapi_upload(locale, "storage_unavailable"),
}
}
pub(super) fn openapi_source_error(locale: OpenApiUploadLocale, error: RegistryError) -> ApiError {
match error {
RegistryError::SourceNotFound { .. } | RegistryError::SourceUnavailable => {
ApiError::openapi_upload(locale, "source_unavailable")
}
RegistryError::SourceIntegrity => ApiError::openapi_upload(locale, "source_integrity"),
other => ApiError::from(other),
}
}
pub(super) fn preview_digest(preview: &serde_json::Value) -> Result<String, ApiError> {
let canonical =
serde_json::to_vec(preview).map_err(|error| ApiError::internal(error.to_string()))?;
Ok(format!("{:x}", Sha256::digest(canonical)))
}
fn verify_preview_contract(
payload: &serde_json::Value,
parsed: &ParsedOpenApiPreview,
locale: OpenApiUploadLocale,
) -> Result<(), ApiError> {
// Pre-fingerprint jobs are legacy rolling-upgrade records. They retain the
// old reparse behavior; new jobs fail closed if parser output drifts or a
// persisted preview has been changed.
let expected = payload
.get("preview_digest")
.and_then(serde_json::Value::as_str);
if payload.get("normalization").is_some() && expected.is_none() {
return Err(ApiError::openapi_upload(locale, "source_integrity"));
}
let Some(expected) = expected else {
return Ok(());
};
let actual = preview_digest(
&serde_json::to_value(&parsed.preview)
.map_err(|error| ApiError::internal(error.to_string()))?,
)?;
if actual == expected {
if let Some(normalization) = payload.get("normalization") {
let normalizer = normalization
.get("normalizer_version")
.and_then(serde_json::Value::as_str);
let projection = normalization
.get("projection_version")
.and_then(serde_json::Value::as_str);
let fingerprint = normalization
.get("ir_fingerprint")
.and_then(serde_json::Value::as_str);
if normalizer != Some(NORMALIZER_VERSION)
|| projection != Some(PROJECTION_VERSION)
|| fingerprint != Some(parsed.ir_fingerprint.as_str())
{
return Err(ApiError::openapi_upload(locale, "source_integrity"));
}
}
Ok(())
} else {
Err(ApiError::openapi_upload(locale, "source_integrity"))
}
}
pub(super) fn preview_has_blocker(
preview: &crank_import::rest::ImportPreview,
selected_operation_keys: &BTreeSet<String>,
) -> bool {
preview
.findings
.iter()
.any(|finding| finding.severity == ImportFindingSeverity::Error)
|| preview
.groups
.iter()
.flat_map(|group| group.operations.iter())
.filter(|operation| selected_operation_keys.contains(&operation.key))
.any(|operation| {
operation
.findings
.iter()
.any(|finding| finding.severity == ImportFindingSeverity::Error)
|| (!operation.security_requirements.alternatives.is_empty()
&& !operation.security_requirements.alternatives.iter().any(
|alternative| alternative.supported && alternative.schemes.is_empty(),
))
})
}
+153 -15
View File
@@ -1,8 +1,10 @@
use crank_core::{
OnboardingProjection, OnboardingStepId, ProductEventId, ProductEventKind, WorkspaceId,
OnboardingProjection, OnboardingStepId, OperationId, ProductEventId, ProductEventKind,
WorkspaceId,
};
use crank_registry::{
OnboardingPresentationMilestone, RecordOnboardingMilestoneRequest, RegistryError,
OnboardingImportContext, OnboardingPresentationMilestone, RecordOnboardingMilestoneRequest,
RegisterOnboardingImportContextRequest, RegistryError, SelectOnboardingImportDraftRequest,
};
use serde_json::json;
use time::OffsetDateTime;
@@ -11,7 +13,10 @@ use crate::{
error::ApiError,
service::{
AdminService, OnboardingEventPayload, OnboardingEventResponse, OnboardingFirstCallEvidence,
OnboardingResponse, OnboardingStepView, ResetOnboardingSelectionResponse, format_timestamp,
OnboardingImportChoiceView, OnboardingImportContextView, OnboardingImportDriftView,
OnboardingResponse, OnboardingStepView, RegisterOnboardingImportContextPayload,
RegisterOnboardingImportContextResponse, ResetOnboardingSelectionResponse,
SelectOnboardingImportDraftPayload, SelectOnboardingImportDraftResponse, format_timestamp,
new_prefixed_id,
},
};
@@ -22,11 +27,12 @@ impl AdminService {
workspace_id: &WorkspaceId,
) -> Result<OnboardingResponse, ApiError> {
self.ensure_workspace_exists(workspace_id).await?;
let projection = self
let snapshot = self
.registry
.ensure_onboarding_eligibility(workspace_id, OffsetDateTime::now_utc())
.ensure_onboarding_eligibility_snapshot(workspace_id, OffsetDateTime::now_utc())
.await?;
self.map_onboarding_response(projection).await
self.map_onboarding_response(snapshot.projection, snapshot.import_context)
.await
}
pub async fn record_onboarding_event(
@@ -67,13 +73,12 @@ impl AdminService {
};
// Presentation events must never exist outside the server-owned cohort,
// including a direct API call before the first UI snapshot GET.
let current = self
.registry
.ensure_onboarding_eligibility(workspace_id, OffsetDateTime::now_utc())
self.registry
.ensure_onboarding_eligibility_snapshot(workspace_id, OffsetDateTime::now_utc())
.await?;
let outcome = self
.registry
.record_onboarding_milestone(RecordOnboardingMilestoneRequest {
.record_onboarding_milestone_snapshot(RecordOnboardingMilestoneRequest {
workspace_id,
event_id: &ProductEventId::new(new_prefixed_id("pe")),
milestone,
@@ -94,9 +99,18 @@ impl AdminService {
.as_ref()
.is_some_and(|record| record.event.kind == event_kind)
{
let latest = self
.registry
.ensure_onboarding_eligibility_snapshot(
workspace_id,
OffsetDateTime::now_utc(),
)
.await?;
return Ok(OnboardingEventResponse {
accepted: false,
onboarding: self.map_onboarding_response(current).await?,
onboarding: self
.map_onboarding_response(latest.projection, latest.import_context)
.await?,
});
}
if replay.is_some() {
@@ -122,7 +136,12 @@ impl AdminService {
};
Ok(OnboardingEventResponse {
accepted: outcome.accepted,
onboarding: self.map_onboarding_response(outcome.projection).await?,
onboarding: self
.map_onboarding_response(
outcome.snapshot.projection,
outcome.snapshot.import_context,
)
.await?,
})
}
@@ -132,9 +151,13 @@ impl AdminService {
expected_revision: i64,
) -> Result<ResetOnboardingSelectionResponse, ApiError> {
self.ensure_workspace_exists(workspace_id).await?;
let projection = self
let snapshot = self
.registry
.reset_onboarding_selection(workspace_id, expected_revision, OffsetDateTime::now_utc())
.reset_onboarding_selection_snapshot(
workspace_id,
expected_revision,
OffsetDateTime::now_utc(),
)
.await
.map_err(|error| match error {
RegistryError::OnboardingStaleRevision => ApiError::conflict_with_context(
@@ -145,13 +168,76 @@ impl AdminService {
})?;
Ok(ResetOnboardingSelectionResponse {
selection_reset: true,
onboarding: self.map_onboarding_response(projection).await?,
onboarding: self
.map_onboarding_response(snapshot.projection, snapshot.import_context)
.await?,
})
}
pub async fn register_onboarding_import_context(
&self,
workspace_id: &WorkspaceId,
payload: RegisterOnboardingImportContextPayload,
) -> Result<RegisterOnboardingImportContextResponse, ApiError> {
self.ensure_workspace_exists(workspace_id).await?;
validate_application_identity(&payload.application_idempotency_key, &payload.plan_digest)?;
let snapshot = self
.registry
.register_onboarding_import_context_snapshot(RegisterOnboardingImportContextRequest {
workspace_id,
application_idempotency_key: &payload.application_idempotency_key,
plan_digest: &payload.plan_digest,
expected_revision: payload.expected_revision,
occurred_at: OffsetDateTime::now_utc(),
})
.await?;
Ok(RegisterOnboardingImportContextResponse {
registered: true,
onboarding: self
.map_onboarding_response(snapshot.projection, snapshot.import_context)
.await?,
})
}
pub async fn select_onboarding_import_draft(
&self,
workspace_id: &WorkspaceId,
payload: SelectOnboardingImportDraftPayload,
) -> Result<SelectOnboardingImportDraftResponse, ApiError> {
self.ensure_workspace_exists(workspace_id).await?;
validate_application_identity(&payload.application_idempotency_key, &payload.plan_digest)?;
if payload.operation_id.is_empty() || payload.operation_id.len() > 128 {
return Err(ApiError::validation(
"operation_id must contain 1..128 bytes",
));
}
if payload.operation_version == 0 {
return Err(ApiError::validation("operation_version must be positive"));
}
let snapshot = self
.registry
.select_onboarding_import_draft_snapshot(SelectOnboardingImportDraftRequest {
workspace_id,
application_idempotency_key: &payload.application_idempotency_key,
plan_digest: &payload.plan_digest,
operation_id: &OperationId::new(payload.operation_id),
operation_version: payload.operation_version,
expected_revision: payload.expected_revision,
occurred_at: OffsetDateTime::now_utc(),
})
.await?;
Ok(SelectOnboardingImportDraftResponse {
selected: true,
onboarding: self
.map_onboarding_response(snapshot.projection, snapshot.import_context)
.await?,
})
}
async fn map_onboarding_response(
&self,
projection: OnboardingProjection,
import_context: Option<OnboardingImportContext>,
) -> Result<OnboardingResponse, ApiError> {
let endpoint = if let Some(agent_id) = projection.agent_id.as_ref() {
let workspace = self.get_workspace(&projection.workspace_id).await?;
@@ -195,6 +281,7 @@ impl AdminService {
_ => None,
};
let first_incomplete = projection.steps.iter().position(|step| !step.completed);
let import_context = import_context.map(map_import_context);
Ok(OnboardingResponse {
schema_version: 1,
workspace_id: projection.workspace_id.as_str().to_owned(),
@@ -244,10 +331,61 @@ impl AdminService {
.map(|id| id.as_str().to_owned()),
mcp_endpoint: endpoint,
first_call,
import_context,
})
}
}
fn map_import_context(context: OnboardingImportContext) -> OnboardingImportContextView {
OnboardingImportContextView {
application_idempotency_key: context.application_idempotency_key,
plan_digest: context.plan_digest,
report: context.report,
choices: context
.choices
.into_iter()
.map(|choice| OnboardingImportChoiceView {
key: choice.key,
name: choice.name,
outcome: choice.outcome,
operation_id: choice.operation_id,
version: choice.version,
reason: choice.reason,
selectable: choice.selectable,
})
.collect(),
selected_operation_id: context
.selected_operation_id
.map(|id| id.as_str().to_owned()),
selected_operation_version: context.selected_operation_version,
drift: context.drift.map(|drift| OnboardingImportDriftView {
reason: drift.reason,
current_operation_version: drift.current_operation_version,
}),
}
}
fn validate_application_identity(
application_idempotency_key: &str,
plan_digest: &str,
) -> Result<(), ApiError> {
if application_idempotency_key.is_empty() || application_idempotency_key.len() > 128 {
return Err(ApiError::validation(
"application_idempotency_key must contain 1..128 bytes",
));
}
let valid_digest = plan_digest.len() == 64
&& plan_digest
.bytes()
.all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte));
if !valid_digest {
return Err(ApiError::validation(
"plan_digest must be 64 lowercase hex characters",
));
}
Ok(())
}
fn action_code(step: OnboardingStepId) -> &'static str {
match step {
OnboardingStepId::Operation => "create_operation",
+11 -1
View File
@@ -16,6 +16,13 @@ const REGISTERED_MASTER_KEY: &str = "registered-master-key-CANARY_SECRET_VALUE-0
const WRONG_MASTER_KEY: &str = "wrong-master-key-CANARY_SECRET_VALUE-0000000000000";
static NEXT_STORAGE_ROOT: AtomicU64 = AtomicU64::new(0);
fn isolated_metrics_bind() -> String {
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("ephemeral metrics port");
let addr = listener.local_addr().unwrap().to_string();
drop(listener);
addr
}
fn run_with(entries: &[(&str, &str)]) -> String {
let mut command = Command::new(env!("CARGO_BIN_EXE_admin-api"));
for field in crank_config::field_registry() {
@@ -27,6 +34,7 @@ fn run_with(entries: &[(&str, &str)]) -> String {
("CRANK_PASSWORD_PEPPER", "pepper"),
("CRANK_BOOTSTRAP_ADMIN_EMAIL", "owner@example.test"),
("CRANK_BOOTSTRAP_ADMIN_PASSWORD", "password"),
("CRANK_ADMIN_METRICS_BIND", isolated_metrics_bind().as_str()),
]);
for (name, value) in entries {
command.env(name, value);
@@ -111,7 +119,7 @@ async fn real_admin_startup_runs_immediate_import_maintenance() {
.fetch_one(&pool)
.await
.unwrap(),
Some(13),
Some(15),
"migration binary must install the current canonical ledger",
);
sqlx::query(
@@ -137,6 +145,7 @@ async fn real_admin_startup_runs_immediate_import_maintenance() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let bind_addr = listener.local_addr().unwrap().to_string();
drop(listener);
let metrics_bind = isolated_metrics_bind();
let mut command = Command::new(env!("CARGO_BIN_EXE_admin-api"));
for field in crank_config::field_registry() {
@@ -151,6 +160,7 @@ async fn real_admin_startup_runs_immediate_import_maintenance() {
("CRANK_BOOTSTRAP_ADMIN_EMAIL", "owner@example.test"),
("CRANK_BOOTSTRAP_ADMIN_PASSWORD", "password"),
("CRANK_ADMIN_BIND", bind_addr.as_str()),
("CRANK_ADMIN_METRICS_BIND", metrics_bind.as_str()),
("CRANK_STORAGE_ROOT", storage_root.to_str().unwrap()),
])
.stdout(Stdio::null())
+1
View File
@@ -1,5 +1,6 @@
mod integration {
mod agent_catalog;
mod agent_catalog_edit;
mod auth_rate_limit;
mod common;
mod community_access_usage;
@@ -0,0 +1,889 @@
use super::common::*;
use crank_core::{Workspace, WorkspaceId, WorkspaceStatus};
use crank_registry::{CreateWorkspaceRequest, PostgresRegistry};
use serde_json::{Value, json};
use serial_test::serial;
use time::OffsetDateTime;
const DEFAULT_WORKSPACE_ID: &str = "ws_default";
fn binding(operation_id: &str, tool_name: &str, tool_title: &str) -> Value {
json!({
"operation_id": operation_id,
"operation_version": 1,
"tool_name": tool_name,
"tool_title": tool_title,
"tool_description_override": null,
"enabled": true
})
}
async fn create_draft_operation(
client: &reqwest::Client,
base_url: &TestServer,
upstream: &str,
name: &str,
) -> String {
let operation = assert_success_json(
client
.post(format!("{base_url}/operations"))
.json(&test_operation_payload(upstream, name))
.send()
.await
.unwrap(),
)
.await;
operation["operation_id"].as_str().unwrap().to_owned()
}
async fn create_published_operation(
client: &reqwest::Client,
base_url: &TestServer,
upstream: &str,
name: &str,
) -> String {
let operation_id = create_draft_operation(client, base_url, upstream, name).await;
let etag = operation_etag(client, base_url, &operation_id).await;
assert_success_json(
client
.post(format!("{base_url}/operations/{operation_id}/publish"))
.header(reqwest::header::IF_MATCH, etag)
.json(&json!({ "version": 1 }))
.send()
.await
.unwrap(),
)
.await;
operation_id
}
async fn create_published_agent(
client: &reqwest::Client,
base_url: &TestServer,
slug: &str,
operation_id: &str,
tool_name: &str,
) -> (String, Value) {
let agent = assert_success_json(
client
.post(format!("{base_url}/agents"))
.json(&json!({
"slug": slug,
"display_name": slug,
"description": "agent catalog edit fixture",
"instructions": { "system_prompt": "Use only published bindings" },
"tool_selection_policy": {}
}))
.send()
.await
.unwrap(),
)
.await;
let agent_id = agent["agent_id"].as_str().unwrap().to_owned();
let etag = agent_etag(client, base_url, &agent_id).await;
assert_success_json(
client
.post(format!("{base_url}/agents/{agent_id}/bindings"))
.header(reqwest::header::IF_MATCH, etag)
.json(&json!([binding(operation_id, tool_name, "Base Tool")]))
.send()
.await
.unwrap(),
)
.await;
let etag = agent_etag(client, base_url, &agent_id).await;
assert_success_json(
client
.post(format!("{base_url}/agents/{agent_id}/publish"))
.header(reqwest::header::IF_MATCH, etag)
.json(&json!({ "version": 1 }))
.send()
.await
.unwrap(),
)
.await;
let published_v1 = assert_success_json(
client
.get(format!("{base_url}/agents/{agent_id}/versions/1"))
.send()
.await
.unwrap(),
)
.await;
(agent_id, published_v1)
}
async fn agent_version_count(db: &PostgresRegistry, agent_id: &str) -> i64 {
sqlx::query_scalar("select count(*) from agent_versions where agent_id = $1")
.bind(agent_id)
.fetch_one(db.pool())
.await
.unwrap()
}
async fn assert_no_durable_draft(
client: &reqwest::Client,
db: &PostgresRegistry,
base_url: &TestServer,
agent_id: &str,
published_v1: &Value,
) {
let summary = assert_success_json(
client
.get(format!("{base_url}/agents/{agent_id}"))
.send()
.await
.unwrap(),
)
.await;
assert_eq!(
summary["current_draft_version"], 1,
"a rejected edit must not fork a Draft Version: {summary}"
);
assert_eq!(summary["latest_published_version"], 1, "{summary}");
assert_eq!(summary["status"], "published", "{summary}");
assert_eq!(
agent_version_count(db, agent_id).await,
1,
"a rejected edit must not persist a new Agent Version row"
);
let published_after = assert_success_json(
client
.get(format!("{base_url}/agents/{agent_id}/versions/1"))
.send()
.await
.unwrap(),
)
.await;
assert_eq!(
&published_after, published_v1,
"the Published snapshot and its bindings must stay unchanged after a rejected edit"
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn published_agent_first_edit_forks_one_draft_and_keeps_published_snapshot() {
let registry = test_registry().await;
let db = registry.clone();
let storage_root = test_storage_root("agent_catalog_edit_first");
let upstream_base_url = spawn_upstream_server().await;
let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
let client = authorized_client(&base_url).await;
let operation_id =
create_published_operation(&client, &base_url, &upstream_base_url, "edit_first_tool").await;
let (agent_id, published_v1) = create_published_agent(
&client,
&base_url,
"edit-first",
&operation_id,
"edit_first_tool",
)
.await;
let summary_before = assert_success_json(
client
.get(format!("{base_url}/agents/{agent_id}"))
.send()
.await
.unwrap(),
)
.await;
assert_eq!(summary_before["current_draft_version"], 1);
assert_eq!(summary_before["latest_published_version"], 1);
assert_eq!(summary_before["status"], "published");
let desired_policy = json!({
"mode": "search",
"groups": [{
"id": "crm-group",
"name": "CRM",
"description": "CRM tools",
"tool_names": ["edit_first_tool"]
}],
"search": { "max_results": 5 }
});
let edit_etag = agent_etag(&client, &base_url, &agent_id).await;
let response = client
.post(format!("{base_url}/agents/{agent_id}/bindings"))
.header(reqwest::header::IF_MATCH, edit_etag)
.json(&json!({
"bindings": [binding(&operation_id, "edit_first_tool", "Edited Tool")],
"tool_selection_policy": desired_policy
}))
.send()
.await
.unwrap();
let status = response.status();
let body = response.json::<Value>().await.unwrap();
assert_eq!(
status,
reqwest::StatusCode::OK,
"the first edit of a Published Agent must fork and save under the original If-Match: {body}"
);
assert_eq!(body["version"], 2, "{body}");
let summary_after = assert_success_json(
client
.get(format!("{base_url}/agents/{agent_id}"))
.send()
.await
.unwrap(),
)
.await;
assert_eq!(summary_after["current_draft_version"], 2, "{summary_after}");
assert_eq!(
summary_after["latest_published_version"], 1,
"{summary_after}"
);
assert_eq!(summary_after["status"], "published", "{summary_after}");
assert_eq!(
agent_version_count(&db, &agent_id).await,
2,
"the first edit must create exactly one additional Draft Version"
);
let draft = assert_success_json(
client
.get(format!("{base_url}/agents/{agent_id}/versions/2"))
.send()
.await
.unwrap(),
)
.await;
assert_eq!(draft["status"], "draft", "{draft}");
assert_eq!(
draft["snapshot"]["instructions"],
published_v1["snapshot"]["instructions"]
);
assert_eq!(draft["bindings"].as_array().unwrap().len(), 1, "{draft}");
assert_eq!(draft["bindings"][0]["tool_title"], "Edited Tool", "{draft}");
assert_eq!(
draft["snapshot"]["tool_selection_policy"]["mode"], "search",
"{draft}"
);
assert_eq!(
draft["snapshot"]["tool_selection_policy"]["search"]["max_results"], 5,
"{draft}"
);
let published_after = assert_success_json(
client
.get(format!("{base_url}/agents/{agent_id}/versions/1"))
.send()
.await
.unwrap(),
)
.await;
assert_eq!(
published_after, published_v1,
"the Published v1 snapshot must not change when the Draft is forked"
);
let next_etag = agent_etag(&client, &base_url, &agent_id).await;
let second_response = client
.post(format!("{base_url}/agents/{agent_id}/bindings"))
.header(reqwest::header::IF_MATCH, next_etag)
.json(&json!({
"bindings": [binding(&operation_id, "edit_first_tool", "Edited Again")],
"tool_selection_policy": desired_policy
}))
.send()
.await
.unwrap();
let second_status = second_response.status();
let second_body = second_response.text().await.unwrap();
assert_eq!(
second_status,
reqwest::StatusCode::OK,
"a subsequent valid edit on the Draft must succeed: {second_body}"
);
assert_eq!(
agent_version_count(&db, &agent_id).await,
2,
"a subsequent valid edit must stay on the existing Draft v2"
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn rejected_invalid_policy_leaves_no_durable_draft() {
let registry = test_registry().await;
let db = registry.clone();
let storage_root = test_storage_root("agent_catalog_edit_invalid_policy");
let upstream_base_url = spawn_upstream_server().await;
let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
let client = authorized_client(&base_url).await;
let operation_id =
create_published_operation(&client, &base_url, &upstream_base_url, "edit_policy_tool")
.await;
let (agent_id, published_v1) = create_published_agent(
&client,
&base_url,
"edit-policy",
&operation_id,
"edit_policy_tool",
)
.await;
let etag = agent_etag(&client, &base_url, &agent_id).await;
let response = client
.post(format!("{base_url}/agents/{agent_id}/bindings"))
.header(reqwest::header::IF_MATCH, etag)
.json(&json!({
"bindings": [],
"tool_selection_policy": {
"mode": "direct",
"groups": [{
"id": "group-1",
"name": "Group",
"description": "groups require search mode",
"tool_names": []
}]
}
}))
.send()
.await
.unwrap();
let status = response.status();
let body = response.text().await.unwrap();
assert_eq!(
status,
reqwest::StatusCode::BAD_REQUEST,
"a grouping policy in direct mode must be rejected: {body}"
);
assert_no_durable_draft(&client, &db, &base_url, &agent_id, &published_v1).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn rejected_unpublished_operation_leaves_no_durable_draft() {
let registry = test_registry().await;
let db = registry.clone();
let storage_root = test_storage_root("agent_catalog_edit_draft_op");
let upstream_base_url = spawn_upstream_server().await;
let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
let client = authorized_client(&base_url).await;
let live_operation =
create_published_operation(&client, &base_url, &upstream_base_url, "edit_live_tool").await;
let (agent_id, published_v1) = create_published_agent(
&client,
&base_url,
"edit-draft-op",
&live_operation,
"edit_live_tool",
)
.await;
let draft_operation =
create_draft_operation(&client, &base_url, &upstream_base_url, "edit_draft_tool").await;
let etag = agent_etag(&client, &base_url, &agent_id).await;
let response = client
.post(format!("{base_url}/agents/{agent_id}/bindings"))
.header(reqwest::header::IF_MATCH, etag)
.json(&json!([binding(
&draft_operation,
"edit_draft_tool",
"Draft Tool"
)]))
.send()
.await
.unwrap();
let status = response.status();
let body = response.text().await.unwrap();
assert_eq!(
status,
reqwest::StatusCode::UNPROCESSABLE_ENTITY,
"binding an unpublished Operation must be rejected: {body}"
);
let body: Value = serde_json::from_str(&body).unwrap();
assert_eq!(
body["error"]["code"], "agent_binding_not_published",
"{body}"
);
assert_no_durable_draft(&client, &db, &base_url, &agent_id, &published_v1).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn rejected_archived_operation_leaves_no_durable_draft() {
let registry = test_registry().await;
let db = registry.clone();
let storage_root = test_storage_root("agent_catalog_edit_archived_op");
let upstream_base_url = spawn_upstream_server().await;
let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
let client = authorized_client(&base_url).await;
let live_operation = create_published_operation(
&client,
&base_url,
&upstream_base_url,
"edit_live_tool_arch",
)
.await;
let (agent_id, published_v1) = create_published_agent(
&client,
&base_url,
"edit-archived-op",
&live_operation,
"edit_live_tool_arch",
)
.await;
let archived_operation =
create_published_operation(&client, &base_url, &upstream_base_url, "edit_archived_tool")
.await;
let operation_etag = operation_etag(&client, &base_url, &archived_operation).await;
let archived = client
.post(format!(
"{base_url}/operations/{archived_operation}/archive"
))
.header(reqwest::header::IF_MATCH, operation_etag)
.send()
.await
.unwrap();
let archived_status = archived.status();
let archived_body = archived.text().await.unwrap();
assert!(archived_status.is_success(), "{archived_body}");
let etag = agent_etag(&client, &base_url, &agent_id).await;
let response = client
.post(format!("{base_url}/agents/{agent_id}/bindings"))
.header(reqwest::header::IF_MATCH, etag)
.json(&json!([binding(
&archived_operation,
"edit_archived_tool",
"Archived Tool"
)]))
.send()
.await
.unwrap();
let status = response.status();
let body = response.text().await.unwrap();
assert_eq!(
status,
reqwest::StatusCode::UNPROCESSABLE_ENTITY,
"binding an archived Operation must be rejected: {body}"
);
let body: Value = serde_json::from_str(&body).unwrap();
assert_eq!(
body["error"]["code"], "agent_binding_archived_operation",
"{body}"
);
assert_no_durable_draft(&client, &db, &base_url, &agent_id, &published_v1).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn rejected_foreign_operation_leaves_no_durable_draft() {
let registry = test_registry().await;
let db = registry.clone();
let storage_root = test_storage_root("agent_catalog_edit_foreign_op");
let upstream_base_url = spawn_upstream_server().await;
let base_url = spawn_admin_api(build_test_app(registry.clone(), storage_root)).await;
let client = authorized_client(&base_url).await;
let live_operation = create_published_operation(
&client,
&base_url,
&upstream_base_url,
"edit_live_tool_foreign",
)
.await;
let (agent_id, published_v1) = create_published_agent(
&client,
&base_url,
"edit-foreign-op",
&live_operation,
"edit_live_tool_foreign",
)
.await;
let foreign_workspace = WorkspaceId::new("ws_agent_edit_foreign");
let now = OffsetDateTime::now_utc();
db.create_workspace(CreateWorkspaceRequest {
workspace: &Workspace {
id: foreign_workspace.clone(),
slug: "agent-edit-foreign".to_owned(),
display_name: "Agent Edit Foreign".to_owned(),
status: WorkspaceStatus::Active,
settings: json!({}),
created_at: now,
updated_at: now,
},
})
.await
.unwrap();
let foreign_service = test_service(
db.clone(),
test_storage_root("agent_catalog_edit_foreign_service"),
test_auth_settings(),
test_secret_crypto(),
);
let foreign_operation = foreign_service
.create_operation(
&foreign_workspace,
test_operation_payload(&upstream_base_url, "edit_foreign_tool"),
)
.await
.unwrap();
let foreign_operation_id = foreign_operation.operation_id;
let etag = agent_etag(&client, &base_url, &agent_id).await;
let response = client
.post(format!("{base_url}/agents/{agent_id}/bindings"))
.header(reqwest::header::IF_MATCH, etag)
.json(&json!([binding(
&foreign_operation_id,
"edit_foreign_tool",
"Foreign Tool"
)]))
.send()
.await
.unwrap();
let status = response.status();
let body = response.text().await.unwrap();
assert_eq!(
status,
reqwest::StatusCode::NOT_FOUND,
"binding an Operation from another workspace must be rejected: {body}"
);
let body: Value = serde_json::from_str(&body).unwrap();
assert_eq!(
body["error"]["code"], "agent_binding_scope_denied",
"{body}"
);
assert_no_durable_draft(&client, &db, &base_url, &agent_id, &published_v1).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn concurrent_first_edits_with_same_etag_have_one_winner() {
let registry = test_registry().await;
let db = registry.clone();
let storage_root = test_storage_root("agent_catalog_edit_concurrent");
let upstream_base_url = spawn_upstream_server().await;
let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
let client = authorized_client(&base_url).await;
let operation_id =
create_published_operation(&client, &base_url, &upstream_base_url, "edit_race_tool").await;
let (agent_id, published_v1) = create_published_agent(
&client,
&base_url,
"edit-race",
&operation_id,
"edit_race_tool",
)
.await;
// Single original precondition taken once from the Published state.
let original_etag = agent_etag(&client, &base_url, &agent_id).await;
let endpoint = format!("{base_url}/agents/{agent_id}/bindings");
let payload_a = json!([binding(&operation_id, "edit_race_tool", "Race Winner A")]);
let payload_b = json!([binding(&operation_id, "edit_race_tool", "Race Winner B")]);
let spawn_edit = |payload: Value, etag: String, endpoint: String| {
let client = client.clone();
tokio::spawn(async move {
let response = client
.post(endpoint)
.header(reqwest::header::IF_MATCH, etag)
.json(&payload)
.send()
.await
.unwrap();
let status = response.status();
let body = response.json::<Value>().await.unwrap();
(status, body)
})
};
let first = spawn_edit(payload_a, original_etag.clone(), endpoint.clone());
let second = spawn_edit(payload_b, original_etag, endpoint);
let (first, second) = tokio::join!(first, second);
let results = vec![first.unwrap(), second.unwrap()];
let successes = results
.iter()
.filter(|(status, _)| status.is_success())
.count();
let conflicts = results
.iter()
.filter(|(status, _)| *status == reqwest::StatusCode::CONFLICT)
.count();
assert_eq!(
successes, 1,
"exactly one concurrent first edit must win: {results:?}"
);
assert_eq!(
conflicts, 1,
"the losing concurrent first edit must report a stable conflict: {results:?}"
);
let conflict_body = results
.iter()
.find(|(status, _)| *status == reqwest::StatusCode::CONFLICT)
.map(|(_, body)| body)
.unwrap();
assert_eq!(
conflict_body["error"]["code"], "agent_stale_revision",
"{conflict_body}"
);
let summary = assert_success_json(
client
.get(format!("{base_url}/agents/{agent_id}"))
.send()
.await
.unwrap(),
)
.await;
assert_eq!(summary["current_draft_version"], 2, "{summary}");
assert_eq!(summary["latest_published_version"], 1, "{summary}");
assert_eq!(
agent_version_count(&db, &agent_id).await,
2,
"the losing concurrent edit must not fork a second Draft"
);
let published_after = assert_success_json(
client
.get(format!("{base_url}/agents/{agent_id}/versions/1"))
.send()
.await
.unwrap(),
)
.await;
assert_eq!(published_after, published_v1);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn first_edit_after_operation_archive_leaves_no_durable_draft() {
let registry = test_registry().await;
let db = registry.clone();
let storage_root = test_storage_root("agent_catalog_edit_archive_ordering");
let upstream_base_url = spawn_upstream_server().await;
let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
let client = authorized_client(&base_url).await;
let live_operation =
create_published_operation(&client, &base_url, &upstream_base_url, "edit_order_live").await;
let (agent_id, published_v1) = create_published_agent(
&client,
&base_url,
"edit-order",
&live_operation,
"edit_order_live",
)
.await;
let archived_operation = create_published_operation(
&client,
&base_url,
&upstream_base_url,
"edit_order_archived",
)
.await;
let operation_etag = operation_etag(&client, &base_url, &archived_operation).await;
let archived = client
.post(format!(
"{base_url}/operations/{archived_operation}/archive"
))
.header(reqwest::header::IF_MATCH, operation_etag)
.send()
.await
.unwrap();
let archived_status = archived.status();
let archived_body = archived.text().await.unwrap();
assert!(archived_status.is_success(), "{archived_body}");
let etag = agent_etag(&client, &base_url, &agent_id).await;
let response = client
.post(format!("{base_url}/agents/{agent_id}/bindings"))
.header(reqwest::header::IF_MATCH, etag)
.json(&json!([binding(
&archived_operation,
"edit_order_archived",
"Archived Order Tool"
)]))
.send()
.await
.unwrap();
let status = response.status();
let body = response.text().await.unwrap();
assert!(
status.is_client_error(),
"a first edit that references an archived Operation must be rejected: {status}: {body}"
);
assert_no_durable_draft(&client, &db, &base_url, &agent_id, &published_v1).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
#[serial]
async fn first_edit_rejects_when_operation_archives_during_save() {
let registry = test_registry().await;
let db = registry.clone();
let storage_root = test_storage_root("agent_catalog_edit_archive_race");
let upstream_base_url = spawn_upstream_server().await;
let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
let client = authorized_client(&base_url).await;
let live_operation =
create_published_operation(&client, &base_url, &upstream_base_url, "edit_race_live").await;
let (agent_id, published_v1) = create_published_agent(
&client,
&base_url,
"edit-archive-race",
&live_operation,
"edit_race_live",
)
.await;
let target_operation =
create_published_operation(&client, &base_url, &upstream_base_url, "edit_race_target")
.await;
// Read the edit precondition before taking the Operation lock; Agent detail
// may itself inspect bound Operations.
let etag_response = client
.get(format!("{base_url}/agents/{agent_id}"))
.send()
.await
.unwrap();
let etag_status = etag_response.status();
let etag = etag_response
.headers()
.get(reqwest::header::ETAG)
.and_then(|value| value.to_str().ok())
.map(str::to_owned);
let etag_body = etag_response.text().await.unwrap();
assert_eq!(
etag_status,
reqwest::StatusCode::OK,
"reading the Agent ETag before the archive race must succeed: {etag_body}"
);
let etag = etag.expect("Agent detail must expose an ETag");
// Use an independent pool for the holder and pg_stat_activity monitor. The
// fixture registry has one connection, which the request needs to reach the
// Operation lock wait.
let lock_registry =
PostgresRegistry::connect_with_options((*db.pool().connect_options()).clone())
.await
.unwrap();
// Hold the target Operation row lock from a separate connection so the edit
// transaction cannot complete its binding write until the archive wins.
let mut holder = lock_registry.pool().begin().await.unwrap();
sqlx::query("select id from operations where workspace_id = $1 and id = $2 for update")
.bind(DEFAULT_WORKSPACE_ID)
.bind(&target_operation)
.fetch_one(&mut *holder)
.await
.unwrap();
let holder_pid: i32 = sqlx::query_scalar("select pg_backend_pid()")
.fetch_one(&mut *holder)
.await
.unwrap();
let edit_client = client.clone();
let endpoint = format!("{base_url}/agents/{agent_id}/bindings");
let edit_target = target_operation.clone();
let edit = tokio::spawn(async move {
let response = edit_client
.post(endpoint)
.header(reqwest::header::IF_MATCH, etag)
.json(&json!([binding(
&edit_target,
"edit_race_target",
"Archive Race Tool"
)]))
.send()
.await
.unwrap();
let status = response.status();
let body = response.text().await.unwrap();
(status, body)
});
// Wait for PostgreSQL to report the request blocked by this exact holder.
// If the request completes first (the baseline CAS path), keep going so the
// durable-draft assertion below reports that regression directly.
let lock_wait = async {
loop {
if edit.is_finished() {
return false;
}
let blocked: bool = sqlx::query_scalar(
"select exists (
select 1
from pg_stat_activity
where wait_event_type = 'Lock'
and $1 = any(pg_blocking_pids(pid))
and query ilike '%select status from operations%'
)",
)
.bind(holder_pid)
.fetch_one(lock_registry.pool())
.await
.unwrap();
if blocked {
return true;
}
tokio::task::yield_now().await;
}
};
let saw_operation_lock_wait =
match tokio::time::timeout(std::time::Duration::from_secs(10), lock_wait).await {
Ok(saw_wait) => saw_wait,
Err(_) => {
edit.abort();
holder.rollback().await.unwrap();
let _ = edit.await;
panic!("timed out waiting for the edit to block on the held Operation row lock");
}
};
sqlx::query(
"update operations
set status = 'archived', updated_at = now()
where workspace_id = $1 and id = $2",
)
.bind(DEFAULT_WORKSPACE_ID)
.bind(&target_operation)
.execute(&mut *holder)
.await
.unwrap();
holder.commit().await.unwrap();
let (status, body) = edit.await.unwrap();
assert!(
status.is_client_error(),
"an edit racing an Operation archive must be rejected: {status}: {body}"
);
assert_no_durable_draft(&client, &db, &base_url, &agent_id, &published_v1).await;
assert!(
saw_operation_lock_wait,
"a corrected save path must wait on the holder's Operation row lock before archive commits"
);
}
+28 -3
View File
@@ -3,6 +3,7 @@
use std::{
collections::BTreeMap,
env, fmt,
str::FromStr,
sync::Arc,
time::{SystemTime, UNIX_EPOCH},
};
@@ -15,7 +16,9 @@ use crank_core::{
};
use crank_core::{IdentityError, IdentityProvider, IdentityProviderKind, LoginOutcome};
use crank_mapping::{MappingRule, MappingSet};
use crank_registry::{MASTER_KEY_CIPHER_CONTRACT, MasterKeyIdentityCandidate, PostgresRegistry};
use crank_registry::{
MASTER_KEY_CIPHER_CONTRACT, MasterKeyIdentityCandidate, PostgresPoolConfig, PostgresRegistry,
};
use crank_runtime::SecretCrypto;
use crank_schema::{Schema, SchemaKind};
use serde_json::{Value, json};
@@ -358,11 +361,33 @@ pub(super) async fn create_lead(Json(payload): Json<Value>) -> Json<Value> {
pub(super) async fn test_registry() -> PostgresRegistry {
let database_url = crank_test_support::postgres_schema_url("test_admin_api").await;
let pool = sqlx::PgPool::connect(&database_url).await.unwrap();
test_registry_at_url(&database_url, None).await
}
pub(super) async fn test_registry_with_single_connection() -> (PostgresRegistry, String) {
let database_url = crank_test_support::postgres_schema_url("test_admin_api_replay").await;
let pool_config = PostgresPoolConfig::try_new(1, 0, 5_000, 60_000, 1_800_000).unwrap();
let registry = test_registry_at_url(&database_url, Some(pool_config)).await;
(registry, database_url)
}
async fn test_registry_at_url(
database_url: &str,
pool_config: Option<PostgresPoolConfig>,
) -> PostgresRegistry {
let pool = sqlx::PgPool::connect(database_url).await.unwrap();
crank_registry::MigrationAuthority::apply(&pool)
.await
.unwrap();
let registry = PostgresRegistry::connect(&database_url).await.unwrap();
let registry = match pool_config {
Some(config) => {
let options = sqlx::postgres::PgConnectOptions::from_str(database_url).unwrap();
PostgresRegistry::connect_with_options_and_pool_config(options, config)
.await
.unwrap()
}
None => PostgresRegistry::connect(database_url).await.unwrap(),
};
let secret_crypto = test_secret_crypto();
registry
.verify_or_register_master_key_identity(MasterKeyIdentityCandidate {
@@ -5,6 +5,10 @@ use super::common::*;
use serde_json::{Value, json};
use serial_test::serial;
mod replay;
mod telemetry;
mod telemetry_startup;
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn exposes_server_authoritative_onboarding_projection() {
@@ -264,6 +268,573 @@ async fn direct_presentation_mutation_cannot_precede_server_eligibility() {
assert_eq!(snapshot["status"], "in_progress");
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn import_context_registration_and_selection_are_revision_guarded() {
let registry = test_registry().await;
let storage_root = test_storage_root("onboarding_select_draft");
let pool = registry.pool();
insert_admin_import_fixture(pool).await;
let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
let client = authorized_client(&base_url).await;
let initial = client
.get(format!("{base_url}/onboarding"))
.send()
.await
.unwrap()
.json::<Value>()
.await
.unwrap();
let revision = initial["revision"].as_i64().unwrap();
assert!(initial["import_context"].is_null());
// Forged identity: no committed immutable apply report.
let forged = client
.post(format!("{base_url}/onboarding/import-context"))
.json(&json!({
"application_idempotency_key": "idem_missing",
"plan_digest": "b".repeat(64),
"expected_revision": revision,
}))
.send()
.await
.unwrap();
let forged_status = forged.status();
let forged = forged.json::<Value>().await.unwrap();
assert_eq!(
forged_status,
reqwest::StatusCode::UNPROCESSABLE_ENTITY,
"body={forged}"
);
assert_eq!(
forged["error"]["code"],
"onboarding_import_application_unavailable"
);
// Stale revision cannot register a context.
let stale = client
.post(format!("{base_url}/onboarding/import-context"))
.json(&json!({
"application_idempotency_key": "idem_admin_import",
"plan_digest": "b".repeat(64),
"expected_revision": revision + 1,
}))
.send()
.await
.unwrap();
let stale_status = stale.status();
let stale = stale.json::<Value>().await.unwrap();
assert_eq!(stale_status, reqwest::StatusCode::CONFLICT, "body={stale}");
assert_eq!(stale["error"]["code"], "onboarding_stale_revision");
// A valid registration stores a pending, recoverable import context and
// suppresses generic automatic Operation selection.
let registered = client
.post(format!("{base_url}/onboarding/import-context"))
.json(&json!({
"application_idempotency_key": "idem_admin_import",
"plan_digest": "b".repeat(64),
"expected_revision": revision,
}))
.send()
.await
.unwrap();
let registered_status = registered.status();
let registered = registered.json::<Value>().await.unwrap();
assert_eq!(
registered_status,
reqwest::StatusCode::OK,
"body={registered}"
);
assert_eq!(registered["registered"], true);
assert_eq!(registered["operation_id"], Value::Null);
assert_eq!(
registered["import_context"]["selected_operation_id"],
Value::Null
);
assert_eq!(registered["import_context"]["plan_digest"], "b".repeat(64));
assert_eq!(
registered["import_context"]["report"]["schema_version"],
"import-plan-apply-report-v1"
);
assert_eq!(
registered["import_context"]["choices"][0]["selectable"],
true
);
let registered_revision = registered["revision"].as_i64().unwrap();
// Selecting under a different application identity is rejected.
let mismatched = client
.post(format!("{base_url}/onboarding/select-draft"))
.json(&json!({
"application_idempotency_key": "idem_other",
"plan_digest": "b".repeat(64),
"operation_id": "op_admin_import",
"operation_version": 1,
"expected_revision": registered_revision,
}))
.send()
.await
.unwrap();
let mismatched_status = mismatched.status();
let mismatched = mismatched.json::<Value>().await.unwrap();
assert_eq!(
mismatched_status,
reqwest::StatusCode::UNPROCESSABLE_ENTITY,
"body={mismatched}"
);
assert_eq!(
mismatched["error"]["code"],
"onboarding_import_context_unavailable"
);
// A forged operation is not a successful outcome of the report.
let forged = client
.post(format!("{base_url}/onboarding/select-draft"))
.json(&json!({
"application_idempotency_key": "idem_admin_import",
"plan_digest": "b".repeat(64),
"operation_id": "op_forged",
"operation_version": 1,
"expected_revision": registered_revision,
}))
.send()
.await
.unwrap();
let forged_status = forged.status();
let forged = forged.json::<Value>().await.unwrap();
assert_eq!(
forged_status,
reqwest::StatusCode::UNPROCESSABLE_ENTITY,
"body={forged}"
);
assert_eq!(
forged["error"]["code"],
"onboarding_import_draft_unavailable"
);
// Unknown/raw client fields are rejected outright.
let unknown = client
.post(format!("{base_url}/onboarding/select-draft"))
.json(&json!({
"application_idempotency_key": "idem_admin_import",
"plan_digest": "b".repeat(64),
"operation_id": "op_admin_import",
"operation_version": 1,
"expected_revision": registered_revision,
"raw_credential": "crk_forbidden_canary",
}))
.send()
.await
.unwrap();
let unknown_status = unknown.status();
let unknown = unknown.text().await.unwrap();
assert_eq!(
unknown_status,
reqwest::StatusCode::UNPROCESSABLE_ENTITY,
"body={unknown}"
);
// A verified choice anchors the exact imported Draft.
let selected = client
.post(format!("{base_url}/onboarding/select-draft"))
.json(&json!({
"application_idempotency_key": "idem_admin_import",
"plan_digest": "b".repeat(64),
"operation_id": "op_admin_import",
"operation_version": 1,
"expected_revision": registered_revision,
}))
.send()
.await
.unwrap();
let selected_status = selected.status();
let selected = selected.json::<Value>().await.unwrap();
assert_eq!(selected_status, reqwest::StatusCode::OK, "body={selected}");
assert_eq!(selected["selected"], true);
assert_eq!(selected["operation_id"], "op_admin_import");
assert_eq!(selected["status"], "in_progress");
assert_eq!(selected["import_context"]["selected_operation_version"], 1);
// Recovery after a fresh GET preserves the explicit selection.
let recovered = client
.get(format!("{base_url}/onboarding"))
.send()
.await
.unwrap()
.json::<Value>()
.await
.unwrap();
assert_eq!(
recovered["import_context"]["selected_operation_id"],
"op_admin_import"
);
assert_eq!(recovered["import_context"]["selected_operation_version"], 1);
assert!(recovered["import_context"]["drift"].is_null());
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn onboarding_revision_round_trips_through_js_safe_integer() {
let registry = test_registry().await;
let storage_root = test_storage_root("onboarding_revision_round_trip");
let pool = registry.pool();
insert_admin_import_fixture(pool).await;
let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
let client = authorized_client(&base_url).await;
// Real GET JSON -> browser JS Number -> POST expected_revision CAS. The
// deterministic SQL mask keeps the revision a safe integer so the value
// survives the f64 round trip that a browser performs.
let value = client
.get(format!("{base_url}/onboarding"))
.send()
.await
.unwrap()
.json::<Value>()
.await
.unwrap();
let revision = value["revision"].as_i64().unwrap();
assert!(revision >= 0);
assert!(
revision <= 9_007_199_254_740_991,
"revision must stay within Number.MAX_SAFE_INTEGER"
);
let js_round_trip = (revision as f64) as i64;
assert_eq!(
js_round_trip, revision,
"revision must round trip through a browser JS Number"
);
let registered = client
.post(format!("{base_url}/onboarding/import-context"))
.json(&json!({
"application_idempotency_key": "idem_admin_import",
"plan_digest": "b".repeat(64),
"expected_revision": js_round_trip,
}))
.send()
.await
.unwrap();
let registered_status = registered.status();
let registered = registered.json::<Value>().await.unwrap();
assert_eq!(
registered_status,
reqwest::StatusCode::OK,
"body={registered}"
);
let registered_revision = registered["revision"].as_i64().unwrap();
assert!((registered_revision as f64) as i64 == registered_revision);
// A stale JS-safe revision is rejected without mutation.
let stale = client
.post(format!("{base_url}/onboarding/select-draft"))
.json(&json!({
"application_idempotency_key": "idem_admin_import",
"plan_digest": "b".repeat(64),
"operation_id": "op_admin_import",
"operation_version": 1,
"expected_revision": registered_revision - 1,
}))
.send()
.await
.unwrap();
let stale_status = stale.status();
let stale = stale.json::<Value>().await.unwrap();
assert_eq!(stale_status, reqwest::StatusCode::CONFLICT, "body={stale}");
assert_eq!(stale["error"]["code"], "onboarding_stale_revision");
let selected = client
.post(format!("{base_url}/onboarding/select-draft"))
.json(&json!({
"application_idempotency_key": "idem_admin_import",
"plan_digest": "b".repeat(64),
"operation_id": "op_admin_import",
"operation_version": 1,
"expected_revision": (registered_revision as f64) as i64,
}))
.send()
.await
.unwrap();
let selected_status = selected.status();
let selected = selected.json::<Value>().await.unwrap();
assert_eq!(selected_status, reqwest::StatusCode::OK, "body={selected}");
assert_eq!(selected["selected"], true);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn import_context_snapshot_stays_consistent_when_candidate_changes() {
let registry = test_registry().await;
let storage_root = test_storage_root("onboarding_import_snapshot");
let pool = registry.pool().clone();
insert_admin_import_fixture(&pool).await;
let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
let client = authorized_client(&base_url).await;
let initial = client
.get(format!("{base_url}/onboarding"))
.send()
.await
.unwrap()
.json::<Value>()
.await
.unwrap();
let revision = initial["revision"].as_i64().unwrap();
let registered = client
.post(format!("{base_url}/onboarding/import-context"))
.json(&json!({
"application_idempotency_key": "idem_admin_import",
"plan_digest": "b".repeat(64),
"expected_revision": revision,
}))
.send()
.await
.unwrap();
let registered_status = registered.status();
let registered = registered.json::<Value>().await.unwrap();
assert_eq!(
registered_status,
reqwest::StatusCode::OK,
"body={registered}"
);
let registered_revision = registered["revision"].as_i64().unwrap();
// Projection revision and import_context come from one authoritative
// snapshot: the choice is actionable and nothing is selected yet.
assert_eq!(
registered["import_context"]["selected_operation_id"],
Value::Null
);
assert_eq!(
registered["import_context"]["choices"][0]["outcome"],
"created"
);
assert_eq!(
registered["import_context"]["choices"][0]["selectable"],
true
);
// The pending candidate becomes non-actionable between requests.
sqlx::query("update operations set status = 'archived' where id = 'op_admin_import'")
.execute(&pool)
.await
.unwrap();
let snapshot = client
.get(format!("{base_url}/onboarding"))
.send()
.await
.unwrap()
.json::<Value>()
.await
.unwrap();
let snapshot_revision = snapshot["revision"].as_i64().unwrap();
assert_ne!(snapshot_revision, registered_revision);
// The same response carries the updated revision and matching choices.
assert_eq!(
snapshot["import_context"]["choices"][0]["selectable"],
false
);
let stale = client
.post(format!("{base_url}/onboarding/select-draft"))
.json(&json!({
"application_idempotency_key": "idem_admin_import",
"plan_digest": "b".repeat(64),
"operation_id": "op_admin_import",
"operation_version": 1,
"expected_revision": registered_revision,
}))
.send()
.await
.unwrap();
let stale_status = stale.status();
let stale = stale.json::<Value>().await.unwrap();
assert_eq!(stale_status, reqwest::StatusCode::CONFLICT, "body={stale}");
assert_eq!(stale["error"]["code"], "onboarding_stale_revision");
let unavailable = client
.post(format!("{base_url}/onboarding/select-draft"))
.json(&json!({
"application_idempotency_key": "idem_admin_import",
"plan_digest": "b".repeat(64),
"operation_id": "op_admin_import",
"operation_version": 1,
"expected_revision": snapshot_revision,
}))
.send()
.await
.unwrap();
let unavailable_status = unavailable.status();
let unavailable = unavailable.json::<Value>().await.unwrap();
assert_eq!(
unavailable_status,
reqwest::StatusCode::UNPROCESSABLE_ENTITY,
"body={unavailable}"
);
assert_eq!(
unavailable["error"]["code"],
"onboarding_import_draft_unavailable"
);
let selected: Option<String> = sqlx::query_scalar(
"select selected_operation_id from onboarding_import_selections
where workspace_id = 'ws_default'",
)
.fetch_one(&pool)
.await
.unwrap();
assert!(
selected.is_none(),
"rejected selections must not mutate state"
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
#[serial]
async fn concurrent_archive_vs_select_draft_rejects_without_mutation() {
let registry = test_registry().await;
let storage_root = test_storage_root("onboarding_concurrent_select");
let pool = registry.pool().clone();
insert_admin_import_fixture(&pool).await;
let base_url = spawn_admin_api(build_test_app(registry, storage_root)).await;
let client = authorized_client(&base_url).await;
let initial = client
.get(format!("{base_url}/onboarding"))
.send()
.await
.unwrap()
.json::<Value>()
.await
.unwrap();
let revision = initial["revision"].as_i64().unwrap();
let registered = client
.post(format!("{base_url}/onboarding/import-context"))
.json(&json!({
"application_idempotency_key": "idem_admin_import",
"plan_digest": "b".repeat(64),
"expected_revision": revision,
}))
.send()
.await
.unwrap()
.json::<Value>()
.await
.unwrap();
let registered_revision = registered["revision"].as_i64().unwrap();
// Hold the exact candidate row lock while the HTTP selection contends.
let mut blocker = pool.begin().await.unwrap();
sqlx::query("select id from operations where workspace_id = $1 and id = $2 for update")
.bind("ws_default")
.bind("op_admin_import")
.fetch_one(&mut *blocker)
.await
.unwrap();
let select_client = client.clone();
let select_url = format!("{base_url}/onboarding/select-draft");
let select_task = tokio::spawn(async move {
select_client
.post(select_url)
.json(&json!({
"application_idempotency_key": "idem_admin_import",
"plan_digest": "b".repeat(64),
"operation_id": "op_admin_import",
"operation_version": 1,
"expected_revision": registered_revision,
}))
.send()
.await
.unwrap()
});
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
sqlx::query(
"update operations set status = 'archived', updated_at = now()
where workspace_id = 'ws_default' and id = 'op_admin_import'",
)
.execute(&mut *blocker)
.await
.unwrap();
blocker.commit().await.unwrap();
let response = select_task.await.unwrap();
let status = response.status();
let body = response.json::<Value>().await.unwrap();
assert!(
status == reqwest::StatusCode::CONFLICT
|| status == reqwest::StatusCode::UNPROCESSABLE_ENTITY,
"concurrent archive must reject the selection: status={status} body={body}"
);
let selected: Option<String> = sqlx::query_scalar(
"select selected_operation_id from onboarding_import_selections
where workspace_id = 'ws_default'",
)
.fetch_one(&pool)
.await
.unwrap();
assert!(
selected.is_none(),
"rejected selection must not mutate state"
);
}
async fn insert_admin_import_fixture(pool: &sqlx::PgPool) {
sqlx::query(
"insert into operations (
id, workspace_id, name, display_name, category, protocol, security_level, status,
current_draft_version, latest_published_version, created_at, updated_at
) values ('op_admin_import', 'ws_default', 'admin_import', 'Admin Import', 'general',
'rest', 'standard', 'draft', 1, null, now(), now())",
)
.execute(pool)
.await
.unwrap();
sqlx::query(
"insert into operation_versions (
operation_id, version, status, target_json, input_schema_json, output_schema_json,
input_mapping_json, output_mapping_json, execution_config_json,
tool_description_json, name, display_name, category, protocol, security_level,
snapshot_provenance, snapshot_observed_at, created_at
) values ('op_admin_import', 1, 'draft', '{}'::jsonb, '{}'::jsonb, '{}'::jsonb,
'{}'::jsonb, '{}'::jsonb, '{}'::jsonb, '{}'::jsonb,
'admin_import', 'Admin Import', 'general', 'rest', 'standard',
'native_v4', now(), now())",
)
.execute(pool)
.await
.unwrap();
sqlx::query(
"insert into import_plan_applications (
workspace_id, idempotency_key, plan_id, plan_digest, report, created_at
) values ('ws_default', 'idem_admin_import', 'plan_admin', $1, $2, now())",
)
.bind("b".repeat(64))
.bind(json!({
"schema_version": "import-plan-apply-report-v1",
"status": "applied",
"source_digest": "c".repeat(64),
"outcomes": [{
"key": "candidate_admin",
"name": "adminImport",
"outcome": "created",
"operation_id": "op_admin_import",
"version": 1,
}],
}))
.execute(pool)
.await
.unwrap();
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn reset_selection_is_explicit_and_revision_guarded() {
@@ -0,0 +1,160 @@
use super::*;
use std::{future::Future, pin::Pin, task::Poll};
use crank_core::{OperationId, ProductEventId, WorkspaceId};
use crank_registry::{
OnboardingPresentationMilestone, PostgresRegistry, RecordOnboardingMilestoneRequest,
RegisterOnboardingImportContextRequest, SelectOnboardingImportDraftRequest,
};
use time::OffsetDateTime;
async fn poll_once_is_pending<F: Future>(mut future: Pin<&mut F>) -> bool {
std::future::poll_fn(|cx| Poll::Ready(future.as_mut().poll(cx).is_pending())).await
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn stale_same_kind_replay_returns_projection_after_concurrent_change() {
let (registry, database_url) = test_registry_with_single_connection().await;
let pool = registry.pool().clone();
let external_registry = PostgresRegistry::connect(&database_url).await.unwrap();
let raw = sqlx::PgPool::connect(&database_url).await.unwrap();
let workspace_id = WorkspaceId::new("ws_default");
insert_admin_import_fixture(&raw).await;
let service = test_service(
registry.clone(),
test_storage_root("onboarding_stale_replay"),
test_auth_settings(),
test_secret_crypto(),
);
let now = OffsetDateTime::now_utc();
let initial = registry
.ensure_onboarding_eligibility_snapshot(&workspace_id, now)
.await
.unwrap();
let registered = registry
.register_onboarding_import_context_snapshot(RegisterOnboardingImportContextRequest {
workspace_id: &workspace_id,
application_idempotency_key: "idem_admin_import",
plan_digest: &"b".repeat(64),
expected_revision: initial.projection.revision,
occurred_at: now,
})
.await
.unwrap();
let selected = registry
.select_onboarding_import_draft_snapshot(SelectOnboardingImportDraftRequest {
workspace_id: &workspace_id,
application_idempotency_key: "idem_admin_import",
plan_digest: &"b".repeat(64),
operation_id: &OperationId::new("op_admin_import"),
operation_version: 1,
expected_revision: registered.projection.revision,
occurred_at: now,
})
.await
.unwrap();
let legacy_key = "legacy-started-replay";
registry
.record_onboarding_milestone_snapshot(RecordOnboardingMilestoneRequest {
workspace_id: &workspace_id,
event_id: &ProductEventId::new("pe_legacy_started_replay"),
milestone: OnboardingPresentationMilestone::Started,
idempotency_key: legacy_key,
expected_revision: selected.projection.revision,
occurred_at: now,
eligible_since: initial.projection.eligible_since,
})
.await
.unwrap();
let before = registry
.ensure_onboarding_eligibility_snapshot(&workspace_id, now)
.await
.unwrap();
assert!(before.import_context.as_ref().unwrap().choices[0].selectable);
let mut service_call = Box::pin(service.record_onboarding_event(
&workspace_id,
admin_api::dto::OnboardingEventPayload {
event: "started".to_owned(),
idempotency_key: legacy_key.to_owned(),
expected_revision: before.projection.revision,
completed_steps: None,
},
));
// Queue the service's workspace lookup ahead of the first connection
// barrier, then prove that the first onboarding snapshot is queued ahead
// of the second barrier. sqlx's pool acquisition queue is FIFO.
let held = pool.acquire().await.unwrap();
assert!(poll_once_is_pending(service_call.as_mut()).await);
let mut first_barrier = Box::pin(pool.acquire());
assert!(poll_once_is_pending(first_barrier.as_mut()).await);
drop(held);
let first_connection = tokio::select! {
connection = first_barrier.as_mut() => connection.unwrap(),
_ = service_call.as_mut() => panic!("service call completed before first snapshot barrier"),
};
assert!(poll_once_is_pending(service_call.as_mut()).await);
let mut second_barrier = Box::pin(pool.acquire());
assert!(poll_once_is_pending(second_barrier.as_mut()).await);
drop(first_connection);
let second_connection = tokio::select! {
connection = second_barrier.as_mut() => connection.unwrap(),
_ = service_call.as_mut() => panic!("service call completed before second snapshot barrier"),
};
assert!(poll_once_is_pending(service_call.as_mut()).await);
// The first snapshot has completed and the event write is now queued
// behind the second barrier. Change the projection and import context from
// an independent registry connection before allowing that write to observe state.
sqlx::query(
"update operations set status = 'archived', updated_at = now()
where workspace_id = 'ws_default' and id = 'op_admin_import'",
)
.execute(&raw)
.await
.unwrap();
let pre_mutation = external_registry
.ensure_onboarding_eligibility_snapshot(&workspace_id, now)
.await
.unwrap();
external_registry
.record_onboarding_milestone_snapshot(RecordOnboardingMilestoneRequest {
workspace_id: &workspace_id,
event_id: &ProductEventId::new("pe_replay_race_mutation"),
milestone: OnboardingPresentationMilestone::Dismissed,
idempotency_key: "mutation-between-snapshots",
expected_revision: pre_mutation.projection.revision,
occurred_at: now,
eligible_since: None,
})
.await
.unwrap();
let fresh = external_registry
.ensure_onboarding_eligibility_snapshot(&workspace_id, now)
.await
.unwrap();
assert_ne!(fresh.projection.revision, pre_mutation.projection.revision);
assert!(!fresh.import_context.as_ref().unwrap().choices[0].selectable);
assert!(fresh.import_context.as_ref().unwrap().drift.is_some());
drop(second_connection);
let response = service_call.await.unwrap();
assert!(!response.accepted);
assert_eq!(
response.onboarding.revision, fresh.projection.revision,
"same-kind idempotency replay must return the latest projection after the concurrent mutation"
);
assert!(!response.onboarding.import_context.as_ref().unwrap().choices[0].selectable);
assert!(
response
.onboarding
.import_context
.as_ref()
.unwrap()
.drift
.is_some()
);
}
@@ -0,0 +1,301 @@
use super::*;
use std::{collections::BTreeSet, time::Duration};
use axum::{
Router,
body::Bytes,
extract::Request,
http::StatusCode,
middleware::{self, Next},
routing::post,
};
use crank_core::{ProductEventKind, WorkspaceId};
use crank_observability::{
OtlpBatchConfig, OtlpTraceConfig, ServiceIdentity, build_tracer_provider,
};
use opentelemetry::trace::TracerProvider as _;
use opentelemetry_proto::tonic::{
collector::trace::v1::ExportTraceServiceRequest,
common::v1::{KeyValue, any_value},
};
use opentelemetry_sdk::trace::SdkTracerProvider;
use prost::Message;
use tokio::{net::TcpListener, sync::mpsc};
use tracing::instrument::WithSubscriber;
use tracing_subscriber::layer::SubscriberExt;
pub(super) const RAW_DOCUMENT_CANARY: &str = "openapi: 3.1.0 raw-document-canary";
pub(super) const USER_ID_CANARY: &str = "user-id-canary-should-not-export";
const REQUEST_ID: &str = "req_onboarding_optin_0001";
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn onboarding_http_event_keeps_default_trace_export_disabled() {
let registry = test_registry().await;
let workspace_id = WorkspaceId::new("ws_default");
let config = OtlpTraceConfig::default();
let identity = service_identity();
assert!(!config.is_enabled());
assert!(
build_tracer_provider(&identity, &config)
.expect("disabled OTLP config is valid")
.is_none(),
"default config must not construct an exporter or batch queue"
);
let (collector_listener, _) = loopback_listener().await;
let (dispatch, provider) = local_trace_dispatch();
let app = app_with_request_dispatch(
build_test_app(
registry.clone(),
test_storage_root("onboarding_telemetry_default"),
),
dispatch,
);
let base_url = spawn_admin_api(app).await;
let client = authorized_client(&base_url).await;
let revision = onboarding_revision(&client, &base_url).await;
reject_canary_payload(&client, &base_url, revision).await;
let event = post_started_event(&client, &base_url, revision, false).await;
assert_eq!(event.status(), reqwest::StatusCode::OK);
assert_eq!(event.json::<Value>().await.unwrap()["accepted"], true);
assert_event_is_local(&registry, &workspace_id, "ui:telemetry-default-event").await;
assert!(
tokio::time::timeout(Duration::from_millis(300), collector_listener.accept())
.await
.is_err(),
"default telemetry config must make no connection to the external collector"
);
provider
.shutdown()
.expect("local trace provider shuts down");
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn onboarding_http_event_exports_only_sanitized_trace_when_operator_opts_in() {
let registry = test_registry().await;
let workspace_id = WorkspaceId::new("ws_default");
let (endpoint, mut exported_requests, collector_task) = spawn_otlp_collector().await;
let config = OtlpTraceConfig::try_new(
Some(endpoint),
Some("http/protobuf".to_owned()),
Duration::from_secs(2),
OtlpBatchConfig::try_new(128, 128, Duration::from_secs(60), Duration::from_secs(2))
.unwrap(),
)
.unwrap();
let identity = service_identity();
assert!(config.is_enabled());
let (provider, tracer) = build_tracer_provider(&identity, &config)
.expect("explicit OTLP config is valid")
.expect("operator endpoint enables the real exporter");
let subscriber =
tracing_subscriber::registry().with(tracing_opentelemetry::layer().with_tracer(tracer));
let dispatch = tracing::Dispatch::new(subscriber);
let app = app_with_request_dispatch(
build_test_app(
registry.clone(),
test_storage_root("onboarding_telemetry_optin"),
),
dispatch,
);
let base_url = spawn_admin_api(app).await;
let client = authorized_client(&base_url).await;
let revision = onboarding_revision(&client, &base_url).await;
reject_canary_payload(&client, &base_url, revision).await;
let event = post_started_event(&client, &base_url, revision, true).await;
assert_eq!(event.status(), reqwest::StatusCode::OK);
assert_eq!(event.json::<Value>().await.unwrap()["accepted"], true);
assert_event_is_local(&registry, &workspace_id, "ui:telemetry-optin-event").await;
provider
.force_flush()
.expect("flush trace spans to the operator collector");
provider.shutdown().expect("exporter shuts down cleanly");
let mut request_count = 0;
let mut onboarding_request_id_exported = false;
while let Ok(body) = exported_requests.try_recv() {
request_count += 1;
let export = ExportTraceServiceRequest::decode(body.as_ref())
.expect("collector receives valid OTLP protobuf");
for resource_spans in export.resource_spans {
for scope_spans in resource_spans.scope_spans {
for span in scope_spans.spans {
assert_eq!(span.name, "http.request");
assert!(span.events.is_empty());
assert!(span.links.is_empty());
let attribute_keys: BTreeSet<&str> = span
.attributes
.iter()
.map(|attribute| attribute.key.as_str())
.collect();
assert!(
attribute_keys.iter().all(|key| *key == "request_id"),
"request spans may export only the request_id attribute"
);
if string_attribute(&span.attributes, "request_id") == Some(REQUEST_ID) {
onboarding_request_id_exported = true;
}
}
}
}
assert!(!body_contains(&body, RAW_DOCUMENT_CANARY));
assert!(!body_contains(&body, USER_ID_CANARY));
}
assert!(
request_count > 0,
"explicit opt-in must reach the collector"
);
assert!(
onboarding_request_id_exported,
"the collected trace must include the real onboarding HTTP request"
);
collector_task.abort();
}
fn service_identity() -> ServiceIdentity {
ServiceIdentity::try_new("admin-api", "integration-test", "test")
.expect("static service identity is valid")
}
fn local_trace_dispatch() -> (tracing::Dispatch, SdkTracerProvider) {
let provider = SdkTracerProvider::builder().build();
let tracer = provider.tracer("crank");
let subscriber =
tracing_subscriber::registry().with(tracing_opentelemetry::layer().with_tracer(tracer));
(tracing::Dispatch::new(subscriber), provider)
}
fn app_with_request_dispatch(app: Router, dispatch: tracing::Dispatch) -> Router {
app.layer(middleware::from_fn(move |request: Request, next: Next| {
let dispatch = dispatch.clone();
async move { next.run(request).with_subscriber(dispatch).await }
}))
}
pub(super) async fn loopback_listener() -> (TcpListener, String) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let endpoint = format!("http://{}/v1/traces", listener.local_addr().unwrap());
(listener, endpoint)
}
pub(super) async fn spawn_otlp_collector() -> (
String,
mpsc::UnboundedReceiver<Bytes>,
tokio::task::JoinHandle<()>,
) {
let (listener, endpoint) = loopback_listener().await;
let (sender, receiver) = mpsc::unbounded_channel();
let app = Router::new().route(
"/v1/traces",
post(move |body: Bytes| {
let sender = sender.clone();
async move {
let _ = sender.send(body);
StatusCode::OK
}
}),
);
let handle = tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
(endpoint, receiver, handle)
}
pub(super) async fn onboarding_revision(
client: &reqwest::Client,
base_url: &(impl AsRef<str> + ?Sized),
) -> i64 {
let base_url = base_url.as_ref();
let response = client
.get(format!("{base_url}/onboarding"))
.send()
.await
.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::OK);
response.json::<Value>().await.unwrap()["revision"]
.as_i64()
.expect("onboarding returns a server revision")
}
pub(super) async fn reject_canary_payload(
client: &reqwest::Client,
base_url: &(impl AsRef<str> + ?Sized),
revision: i64,
) {
let base_url = base_url.as_ref();
let response = client
.post(format!("{base_url}/onboarding/events"))
.json(&json!({
"event": "started",
"idempotency_key": "ui:telemetry-canary-rejection",
"expected_revision": revision,
"user_id": USER_ID_CANARY,
"openapi_document": RAW_DOCUMENT_CANARY,
}))
.send()
.await
.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::UNPROCESSABLE_ENTITY);
let body = response.text().await.unwrap();
assert!(!body.contains(USER_ID_CANARY));
assert!(!body.contains(RAW_DOCUMENT_CANARY));
}
async fn post_started_event(
client: &reqwest::Client,
base_url: &(impl AsRef<str> + ?Sized),
revision: i64,
with_request_id: bool,
) -> reqwest::Response {
let base_url = base_url.as_ref();
let mut request = client
.post(format!("{base_url}/onboarding/events"))
.json(&json!({
"event": "started",
"idempotency_key": if with_request_id {
"ui:telemetry-optin-event"
} else {
"ui:telemetry-default-event"
},
"expected_revision": revision,
}));
if with_request_id {
request = request.header("x-request-id", REQUEST_ID);
}
request.send().await.unwrap()
}
async fn assert_event_is_local(
registry: &crank_registry::PostgresRegistry,
workspace_id: &WorkspaceId,
idempotency_key: &str,
) {
let record = registry
.get_product_event_by_idempotency_key(workspace_id, idempotency_key)
.await
.unwrap()
.expect("successful HTTP event is persisted in the local product event store");
assert_eq!(record.event.kind, ProductEventKind::OnboardingStarted);
assert_eq!(record.event.idempotency_key, idempotency_key);
}
pub(super) fn string_attribute<'a>(attributes: &'a [KeyValue], key: &str) -> Option<&'a str> {
attributes.iter().find_map(|attribute| {
(attribute.key == key)
.then_some(attribute.value.as_ref()?.value.as_ref()?)
.and_then(|value| match value {
any_value::Value::StringValue(value) => Some(value.as_str()),
_ => None,
})
})
}
pub(super) fn body_contains(body: &[u8], canary: &str) -> bool {
body.windows(canary.len())
.any(|window| window == canary.as_bytes())
}
@@ -0,0 +1,290 @@
use super::telemetry::{
RAW_DOCUMENT_CANARY, USER_ID_CANARY, body_contains, loopback_listener, onboarding_revision,
reject_canary_payload, string_attribute,
};
use super::*;
use axum::{
Router,
body::{self, Bytes},
extract::Request,
http::StatusCode,
routing::any,
};
use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest;
use prost::Message;
use std::{
collections::BTreeSet,
fs::{self, OpenOptions},
net::TcpListener as StdTcpListener,
os::unix::fs::{OpenOptionsExt, PermissionsExt},
path::PathBuf,
process::{Child, Command, Stdio},
time::{Duration, Instant},
};
const MASTER_KEY: &str = "test-master-key-00000000000000000000000000000000";
const SESSION_SECRET: &str = "test-session-secret";
const PASSWORD_PEPPER: &str = "test-password-pepper";
const ADMIN_EMAIL: &str = "owner@crank.local";
const ADMIN_PASSWORD: &str = "test-password";
const REQUEST_ID: &str = "req_admin_process_optin_0001";
struct AdminProcess {
child: Child,
log_path: PathBuf,
secrets: Vec<String>,
}
impl AdminProcess {
fn stop_and_assert_logs_are_safe(&mut self) {
let _ = self.child.kill();
self.child.wait().expect("admin-api child must be reaped");
let logs = fs::read_to_string(&self.log_path).expect("child log must be readable");
for secret in &self.secrets {
assert!(
!logs.contains(secret),
"admin-api process log must not contain configured secrets or request canaries"
);
}
}
}
impl Drop for AdminProcess {
fn drop(&mut self) {
let _ = self.child.kill();
let _ = self.child.wait();
}
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn production_admin_process_keeps_default_otlp_export_disabled() {
let (registry, database_url) = test_registry_with_single_connection().await;
let _registry = registry;
let storage_root = test_storage_root("onboarding_telemetry_startup_default");
let (collector_listener, _) = loopback_listener().await;
let (mut process, base_url) = start_admin_process(&database_url, &storage_root, None);
wait_until_ready(&mut process, &base_url).await;
let workspace_url = format!("{base_url}/api/admin/workspaces/ws_default");
let client = authorized_client(&workspace_url).await;
let revision = onboarding_revision(&client, &workspace_url).await;
reject_canary_payload(&client, &workspace_url, revision).await;
let response = post_startup_event(&client, &workspace_url, revision, false).await;
assert_eq!(response.status(), reqwest::StatusCode::OK);
assert_eq!(response.json::<Value>().await.unwrap()["accepted"], true);
assert!(
tokio::time::timeout(Duration::from_secs(2), collector_listener.accept())
.await
.is_err(),
"default production startup must not connect to an OTLP collector"
);
process.stop_and_assert_logs_are_safe();
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn production_admin_process_exports_only_sanitized_request_trace_when_opted_in() {
let (registry, database_url) = test_registry_with_single_connection().await;
let _registry = registry;
let storage_root = test_storage_root("onboarding_telemetry_startup_optin");
let (endpoint, mut exported_requests, collector_task) = spawn_startup_collector().await;
let (mut process, base_url) =
start_admin_process(&database_url, &storage_root, Some(&endpoint));
wait_until_ready(&mut process, &base_url).await;
let workspace_url = format!("{base_url}/api/admin/workspaces/ws_default");
let client = authorized_client(&workspace_url).await;
let revision = onboarding_revision(&client, &workspace_url).await;
reject_canary_payload(&client, &workspace_url, revision).await;
let response = post_startup_event(&client, &workspace_url, revision, true).await;
assert_eq!(response.status(), reqwest::StatusCode::OK);
assert_eq!(response.json::<Value>().await.unwrap()["accepted"], true);
let mut request_id_exported = false;
tokio::time::timeout(Duration::from_secs(12), async {
while !request_id_exported {
let (path, body) = exported_requests
.recv()
.await
.expect("collector task must remain active");
assert_eq!(path, "/v1/traces", "trace-specific endpoint path is exact");
let export = ExportTraceServiceRequest::decode(body.as_ref())
.expect("production process must send valid OTLP protobuf");
for resource_spans in export.resource_spans {
for scope_spans in resource_spans.scope_spans {
for span in scope_spans.spans {
assert_eq!(span.name, "http.request");
assert!(span.events.is_empty());
assert!(span.links.is_empty());
let attribute_keys: BTreeSet<&str> = span
.attributes
.iter()
.map(|attribute| attribute.key.as_str())
.collect();
assert!(
attribute_keys.iter().all(|key| *key == "request_id"),
"production request spans may export only the request_id attribute"
);
if string_attribute(&span.attributes, "request_id") == Some(REQUEST_ID) {
request_id_exported = true;
}
let encoded = format!("{} {:?}", span.name, span.attributes);
assert!(!encoded.contains(USER_ID_CANARY));
assert!(!encoded.contains(RAW_DOCUMENT_CANARY));
}
}
}
assert!(!body_contains(&body, USER_ID_CANARY));
assert!(!body_contains(&body, RAW_DOCUMENT_CANARY));
}
})
.await
.expect("production exporter must send the onboarding request in a bounded OTLP batch");
assert!(
request_id_exported,
"collector must receive the trace for the onboarding event request"
);
process.stop_and_assert_logs_are_safe();
collector_task.abort();
}
fn start_admin_process(
database_url: &str,
storage_root: &std::path::Path,
otlp_endpoint: Option<&str>,
) -> (AdminProcess, String) {
fs::create_dir_all(storage_root).expect("isolated storage root must be created");
#[cfg(unix)]
fs::set_permissions(storage_root, fs::Permissions::from_mode(0o700))
.expect("isolated storage root must be private");
let listener = StdTcpListener::bind("127.0.0.1:0").expect("reserve an ephemeral API port");
let address = listener.local_addr().unwrap();
drop(listener);
let base_url = format!("http://{address}");
let log_path = storage_root.join("admin-api.log");
let stdout = OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(&log_path)
.expect("private child log must be created");
let stderr = stdout.try_clone().expect("child stderr log handle");
let mut command = Command::new(env!("CARGO_BIN_EXE_admin-api"));
command
.env_clear()
.env("CRANK_DATABASE_URL", database_url)
.env("CRANK_ADMIN_BIND", address.to_string())
.env("CRANK_STORAGE_ROOT", storage_root)
.env("CRANK_MASTER_KEY", MASTER_KEY)
.env("CRANK_SESSION_SECRET", SESSION_SECRET)
.env("CRANK_PASSWORD_PEPPER", PASSWORD_PEPPER)
.env("CRANK_SESSION_TTL_HOURS", "24")
.env("CRANK_BOOTSTRAP_ADMIN_EMAIL", ADMIN_EMAIL)
.env("CRANK_BOOTSTRAP_ADMIN_PASSWORD", ADMIN_PASSWORD)
.env("CRANK_BOOTSTRAP_ADMIN_DISPLAY_NAME", "Integration Test")
.env("CRANK_METRICS_ENABLED", "false")
.env("CRANK_BASE_URL", &base_url)
.env("CRANK_LOG_LEVEL", "info")
.stdout(Stdio::from(stdout))
.stderr(Stdio::from(stderr));
if let Some(endpoint) = otlp_endpoint {
command
.env("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", endpoint)
.env("OTEL_EXPORTER_OTLP_TRACES_PROTOCOL", "http/protobuf")
.env("OTEL_BSP_MAX_QUEUE_SIZE", "16")
.env("OTEL_BSP_MAX_EXPORT_BATCH_SIZE", "1")
.env("OTEL_BSP_SCHEDULE_DELAY", "100")
.env("OTEL_BSP_EXPORT_TIMEOUT", "2000");
}
let child = command.spawn().expect("production admin-api binary starts");
(
AdminProcess {
child,
log_path,
secrets: vec![
database_url.to_owned(),
MASTER_KEY.to_owned(),
SESSION_SECRET.to_owned(),
PASSWORD_PEPPER.to_owned(),
ADMIN_PASSWORD.to_owned(),
USER_ID_CANARY.to_owned(),
RAW_DOCUMENT_CANARY.to_owned(),
],
},
base_url,
)
}
async fn spawn_startup_collector() -> (
String,
tokio::sync::mpsc::UnboundedReceiver<(String, Bytes)>,
tokio::task::JoinHandle<()>,
) {
let (listener, endpoint) = loopback_listener().await;
let (sender, receiver) = tokio::sync::mpsc::unbounded_channel();
let app = Router::new().fallback(any(move |request: Request| {
let sender = sender.clone();
async move {
let path = request.uri().path().to_owned();
let body = body::to_bytes(request.into_body(), usize::MAX)
.await
.expect("collector request body must be readable");
let _ = sender.send((path, body));
StatusCode::OK
}
}));
let handle = tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
(endpoint, receiver, handle)
}
async fn wait_until_ready(process: &mut AdminProcess, base_url: &str) {
let deadline = Instant::now() + Duration::from_secs(45);
loop {
if let Some(status) = process.child.try_wait().expect("child status is readable") {
panic!("production admin-api exited before readiness: {status}");
}
if reqwest::Client::new()
.get(format!("{base_url}/health"))
.timeout(Duration::from_millis(500))
.send()
.await
.is_ok_and(|response| response.status().is_success())
{
return;
}
assert!(
Instant::now() < deadline,
"production admin-api readiness deadline"
);
tokio::time::sleep(Duration::from_millis(100)).await;
}
}
async fn post_startup_event(
client: &reqwest::Client,
workspace_url: &str,
revision: i64,
with_request_id: bool,
) -> reqwest::Response {
let mut request = client
.post(format!("{workspace_url}/onboarding/events"))
.json(&json!({
"event": "started",
"idempotency_key": if with_request_id {
"ui:telemetry-process-optin"
} else {
"ui:telemetry-process-default"
},
"expected_revision": revision,
}));
if with_request_id {
request = request.header("x-request-id", REQUEST_ID);
}
request.send().await.unwrap()
}
@@ -11,6 +11,120 @@ use super::common::{
mod external_references;
mod http_contract;
mod import_plan_apply;
mod import_plan_create;
mod large_preview;
mod upload_outcomes;
mod v5_replay;
#[tokio::test]
#[serial]
async fn upload_rejects_credential_literals_before_persisting_source_artifacts() {
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_storage_redaction");
let service = test_service(
registry.clone(),
storage_root,
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let upload = OpenApiUpload {
bytes: br#"{
"openapi":"3.0.3",
"info":{"title":"Redaction persistence","version":"1"},
"servers":[{"url":"https://bare-canary@api.example.test/v1?api_key=query-canary"}],
"components":{"securitySchemes":{"key":{"type":"apiKey","in":"header","name":"X-Api-Key"}}},
"paths":{"/private":{"get":{
"operationId":"privateOperation",
"parameters":[{"name":"X-Api-Key","in":"header","example":"opaque-canary-42"}],
"responses":{"200":{"description":"ok"}},
"x-client-secret":true
}}}
}"#
.to_vec(),
mime_type: "application/json".to_owned(),
locale: OpenApiUploadLocale::En,
};
let error = service
.preview_openapi_import(&workspace_id, upload)
.await
.expect_err("credential-bearing uploads must be rejected before persistence");
let rendered_error = format!("{error:?}");
assert!(
rendered_error.contains("invalid_document"),
"unexpected typed error: {rendered_error}"
);
for canary in ["bare-canary", "query-canary", "opaque-canary-42"] {
assert!(
!rendered_error.contains(canary),
"API error leaked {canary}"
);
}
let source_count: i64 =
sqlx::query_scalar("select count(*) from artifact_sources where workspace_id = $1")
.bind(workspace_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap();
assert_eq!(source_count, 0, "unsafe upload created an artifact source");
}
#[tokio::test]
#[serial]
async fn legacy_apply_rejects_required_auth_without_binding_before_creating_draft() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_unresolved_auth"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let upload = OpenApiUpload {
bytes: br#"{
"openapi":"3.0.3",
"info":{"title":"Required auth","version":"1"},
"servers":[{"url":"https://api.example.test"}],
"components":{"securitySchemes":{"bearer":{"type":"http","scheme":"bearer"}}},
"security":[{"bearer":[]}],
"paths":{"/secure":{"get":{"operationId":"secureOperation","responses":{"200":{"description":"ok"}}}}}
}"#
.to_vec(),
mime_type: "application/json".to_owned(),
locale: OpenApiUploadLocale::En,
};
let preview = service
.preview_openapi_import(&workspace_id, upload)
.await
.unwrap();
let result = service
.create_openapi_import(
&workspace_id,
&preview.job_id.as_str().into(),
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /secure".to_owned()],
server_url: None,
conflict_mode: "rename".to_owned(),
},
)
.await;
let error = result.expect_err("legacy apply cannot bypass unresolved required auth");
assert!(format!("{error:?}").contains("invalid_document"));
assert!(
service
.list_operations(&workspace_id)
.await
.unwrap()
.is_empty()
);
let job = registry
.get_import_job(&workspace_id, &preview.job_id.as_str().into())
.await
.unwrap()
.unwrap();
assert_eq!(job.status, ImportJobStatus::Failed);
}
const OPENAPI3: &str = r#"
openapi: 3.0.3
@@ -78,11 +192,11 @@ async fn previews_openapi_and_creates_draft_operations() {
assert_eq!(preview_job.status, ImportJobStatus::Pending);
assert_eq!(
preview_job.preview_payload["normalization"]["normalizer_version"],
"normalized-ir-v4"
crank_import::rest::NORMALIZER_VERSION
);
assert_eq!(
preview_job.preview_payload["normalization"]["projection_version"],
"preview-v4"
crank_import::rest::PROJECTION_VERSION
);
assert!(preview_job.preview_payload["normalization"]["ir_fingerprint"].is_string());
@@ -1,10 +1,25 @@
use super::super::common::test_service_with_external_references;
use super::super::common::{
authorized_client, build_test_app_with_external_references, spawn_admin_api,
test_service_with_external_references,
};
mod isolation;
mod uri_transport;
use super::*;
use axum::{Router, routing::get};
use admin_api::error::ApiError;
use axum::{Router, body::to_bytes, http::StatusCode, response::IntoResponse, routing::get};
use crank_artifacts::ArtifactStore;
use crank_core::{Workspace, WorkspaceStatus};
use crank_registry::{ArtifactSourceId, CreateWorkspaceRequest, RegistryError};
use reqwest::multipart::{Form, Part};
use sha2::{Digest, Sha256};
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
use time::OffsetDateTime;
// Serialized by the integration harness at baseline f5f40cb167a82b1e3c1ea2475db5cbaed9d9abfa; this v4 payload preserves the then-current security blocker and digest.
const BASELINE_V4_SECURITY_PREVIEW_PAYLOAD: &str = r###"{"dependencies":[],"dependency_snapshots":[],"normalization":{"config":{"external_references_enabled":false,"max_aliases":128,"max_bytes":262144,"max_collection_items":10000,"max_depth":64,"max_expanded_nodes":100000,"max_external_document_bytes":262144,"max_nodes":50000,"max_reference_depth":32,"max_reference_documents":32,"max_references":4096,"max_scalar_bytes":262144,"normalizer_version":"normalized-ir-v4","projection_version":"preview-v4"},"ir_fingerprint":"ae2319de76c13d631b26843623092d966e5deea7cda9e3e40e4acc6fa36a25a8","normalizer_version":"normalized-ir-v4","projection_version":"preview-v4"},"preview":{"findings":[{"code":"unsupported_security_requirement","message":"Требование безопасности должно быть привязано к настроенному Auth Profile перед публикацией этой операции; остальные операции не блокируются.","operation_key":"GET /secure","severity":"error"}],"groups":[{"key":"imported_operation","operations":[{"category":"imported","description":"Выполняет GET /public","draft":{"category":"imported","display_name":"Public","input_mapping":{},"input_schema":{"description":"Входные параметры MCP-инструмента","nullable":false,"required":true,"type":"object"},"name":"public","output_mapping":{"rules":[{"required":true,"source":"$.response.body","target":"$.output"}]},"output_schema":{"description":"Успешный ответ без тела","nullable":false,"required":true,"type":"null"},"target":{"base_url":"https://api.example.test","method":"GET","path_template":"/public","response_contract":[{"schema_variant":0,"status_code":200}]},"tool_description":{"description":"Выполняет GET /public","examples":[{"input":{}}],"title":"Public"},"wizard_state":{}},"findings":[{"code":"missing_summary","message":"У метода нет summary, отображаемое имя будет сгенерировано автоматически.","operation_key":"GET /public","severity":"warning"},{"code":"missing_description","message":"У метода нет description. Перед публикацией лучше описать, когда агенту стоит вызывать этот инструмент.","operation_key":"GET /public","severity":"warning"},{"code":"missing_response_schema","message":"У метода не найдена схема успешного ответа, результат будет описан как общий объект.","operation_key":"GET /public","severity":"warning"},{"code":"no_input_fields","message":"У инструмента нет входных параметров. Это нормально для справочных методов, но проверьте, что агенту не нужно передавать фильтры.","operation_key":"GET /public","severity":"info"},{"code":"empty_output_schema","message":"В ответе не найдено отдельных полей. Перед публикацией проверьте схему ответа и маппинг результата.","operation_key":"GET /public","severity":"warning"},{"code":"weak_tool_description","message":"Описание инструмента слишком короткое или техническое. Перед публикацией добавьте, когда агент должен вызывать инструмент и что будет в успешном ответе.","operation_key":"GET /public","severity":"warning"},{"code":"weak_tool_name","message":"Имя инструмента `public` выглядит слишком общим. Лучше использовать имя с конкретным действием и объектом.","operation_key":"GET /public","severity":"warning"}],"input_fields":0,"key":"GET /public","method":"GET","operation_id":"public","output_fields":0,"path":"/public","server_urls":["https://api.example.test"],"suggested_display_name":"Public","suggested_name":"public"},{"category":"imported","description":"Выполняет GET /secure","draft":{"category":"imported","display_name":"Secure","input_mapping":{},"input_schema":{"description":"Входные параметры MCP-инструмента","nullable":false,"required":true,"type":"object"},"name":"secure","output_mapping":{"rules":[{"required":true,"source":"$.response.body","target":"$.output"}]},"output_schema":{"description":"Успешный ответ без тела","nullable":false,"required":true,"type":"null"},"target":{"base_url":"https://api.example.test","method":"GET","path_template":"/secure","response_contract":[{"schema_variant":0,"status_code":200}]},"tool_description":{"description":"Выполняет GET /secure","examples":[{"input":{}}],"title":"Secure"},"wizard_state":{}},"findings":[{"code":"missing_summary","message":"У мет Line truncated
#[tokio::test]
#[serial]
@@ -35,16 +50,18 @@ async fn external_relative_chain_survives_reversed_builder_order_and_apply_never
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_external_snapshot");
let service = test_service_with_external_references(
registry.clone(),
test_storage_root("openapi_import_external_snapshot"),
storage_root.clone(),
vec![format!("{origin}/")],
);
let workspace_id = WorkspaceId::new("ws_default");
let foreign_workspace_id = create_workspace(&registry, "ws_external_snapshot_foreign").await;
let upload = OpenApiUpload {
bytes: format!(
r#"
@@ -93,6 +110,60 @@ paths:
2
);
// The preview response contains only the normalized result. Ownership
// envelopes, storage digests, and remote origins stay in the persisted
// job payload and are verified through the workspace-scoped registry API.
let public_preview = serde_json::to_string(&preview).unwrap();
assert!(!public_preview.contains("src_openapi_dep_"));
assert!(!public_preview.contains(&origin));
let dependencies = job.preview_payload["dependencies"].as_array().unwrap();
let store = Arc::new(ArtifactStore::open(&storage_root).unwrap());
for dependency in dependencies {
let source_id = ArtifactSourceId::new(dependency["source_id"].as_str().unwrap());
let digest = dependency["digest"].as_str().unwrap();
let canonical_uri = dependency["canonical_uri"].as_str().unwrap();
let source = registry
.get_artifact_source(&workspace_id, &source_id)
.await
.unwrap();
assert_eq!(source.workspace_id, workspace_id);
assert_eq!(source.blob.artifact_ref.as_str(), digest);
let verified = registry
.read_artifact_source(Arc::clone(&store), &workspace_id, &source_id)
.await
.unwrap();
assert_eq!(verified.source.blob.artifact_ref.as_str(), digest);
let expected_bytes = if canonical_uri.ends_with("/root.yaml") {
b"Item: { $ref: './child.yaml#/Item' }".as_slice()
} else {
assert!(canonical_uri.ends_with("/child.yaml"));
b"Item: { type: object, required: [id], properties: { id: { type: string } } }"
.as_slice()
};
assert_eq!(verified.bytes, expected_bytes);
let foreign_read = registry
.read_artifact_source(Arc::clone(&store), &foreign_workspace_id, &source_id)
.await
.expect_err("foreign workspace must not read an owned snapshot");
let unknown_source_id = ArtifactSourceId::new("src_unknown_scope_probe");
let unknown_read = registry
.read_artifact_source(
Arc::clone(&store),
&foreign_workspace_id,
&unknown_source_id,
)
.await
.expect_err("unknown source must have the same scoped outcome");
let foreign_body = source_not_found_body(foreign_read).await;
let unknown_body = source_not_found_body(unknown_read).await;
assert_eq!(foreign_body, unknown_body);
let rendered_body = foreign_body.to_string();
assert!(!rendered_body.contains(digest));
assert!(!rendered_body.contains(canonical_uri));
assert!(!rendered_body.contains(source_id.as_str()));
}
let applied = service
.create_openapi_import(
&workspace_id,
@@ -105,6 +176,7 @@ paths:
)
.await
.unwrap();
server.abort();
assert_eq!(applied.created.len(), 1);
assert_eq!(fetches.load(Ordering::SeqCst), 2);
let active_sources: i64 = sqlx::query_scalar(
@@ -117,6 +189,168 @@ paths:
assert_eq!(active_sources, 0);
}
fn external_upload(origin: &str) -> OpenApiUpload {
OpenApiUpload {
bytes: format!(
r#"
openapi: 3.1.0
info: {{ title: Scoped external snapshot }}
servers: [{{ url: https://api.example.test }}]
paths:
/items:
get:
operationId: listItems
responses:
'200':
description: ok
content:
application/json:
schema: {{ $ref: '{origin}/schema.yaml#/Item' }}
"#
)
.into_bytes(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
}
}
async fn create_workspace(registry: &crank_registry::PostgresRegistry, id: &str) -> WorkspaceId {
let workspace_id = WorkspaceId::new(id);
let now = OffsetDateTime::now_utc();
registry
.create_workspace(CreateWorkspaceRequest {
workspace: &Workspace {
id: workspace_id.clone(),
slug: id.replace('_', "-"),
display_name: id.to_owned(),
status: WorkspaceStatus::Active,
settings: serde_json::json!({}),
created_at: now,
updated_at: now,
},
})
.await
.unwrap();
workspace_id
}
async fn source_not_found_body(error: RegistryError) -> serde_json::Value {
assert!(matches!(&error, RegistryError::SourceNotFound { .. }));
let response = ApiError::from(error).into_response();
assert_eq!(response.status(), StatusCode::NOT_FOUND);
let body = to_bytes(response.into_body(), usize::MAX).await.unwrap();
serde_json::from_slice(&body).unwrap()
}
#[tokio::test]
#[serial]
async fn external_secret_document_is_rejected_before_blob_registration() {
let external_document = "Item: { type: object, x-api-key: external-secret-canary-42, properties: { id: { type: string } } }";
let fetched = Arc::new(AtomicUsize::new(0));
let fetch_count = Arc::clone(&fetched);
let app = Router::new().route(
"/schemas.yaml",
get(move || {
let fetch_count = Arc::clone(&fetch_count);
async move {
fetch_count.fetch_add(1, Ordering::SeqCst);
external_document
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_external_secret_rejected");
let service = test_service_with_external_references(
registry.clone(),
storage_root.clone(),
vec![format!("{origin}/")],
);
let workspace_id = WorkspaceId::new("ws_default");
let error = service
.preview_openapi_import(
&workspace_id,
OpenApiUpload {
bytes: format!(
r#"
openapi: 3.1.0
info: {{ title: Safe primary with unsafe external }}
servers: [{{ url: https://api.example.test }}]
paths:
/items:
get:
operationId: listItems
responses:
'200':
description: ok
content: {{ application/json: {{ schema: {{ $ref: '{origin}/schemas.yaml#/Item' }} }} }}
"#
)
.into_bytes(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
},
)
.await
.expect_err("unsafe external bundle must be rejected before source persistence");
server.abort();
assert_eq!(fetched.load(Ordering::SeqCst), 1);
let rendered_error = format!("{error:?}");
assert!(rendered_error.contains("invalid_document"));
assert!(!rendered_error.contains("external-secret-canary-42"));
// The raw dependency's content-addressed path must not exist even as an
// unregistered blob, and no other stored file may contain its literal.
let external_digest = format!("{:x}", Sha256::digest(external_document.as_bytes()));
let external_blob = storage_root
.join("sha256")
.join(&external_digest[..2])
.join(&external_digest);
assert!(
!external_blob.exists(),
"secret-bearing external response was written to the artifact store"
);
assert!(!storage_contains_literal(
&storage_root,
b"external-secret-canary-42"
));
let dependency_sources: i64 = sqlx::query_scalar(
"select count(*) from artifact_sources
where workspace_id = $1 and source_id like 'src_openapi_dep_%'",
)
.bind(workspace_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap();
assert_eq!(dependency_sources, 0);
let active_sources: i64 = sqlx::query_scalar(
"select count(*) from artifact_sources where workspace_id = $1 and lifecycle = 'active'",
)
.bind(workspace_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap();
assert_eq!(active_sources, 0);
}
fn storage_contains_literal(root: &std::path::Path, literal: &[u8]) -> bool {
std::fs::read_dir(root).unwrap().any(|entry| {
let path = entry.unwrap().path();
if path.is_dir() {
storage_contains_literal(&path, literal)
} else {
std::fs::read(path)
.unwrap()
.windows(literal.len())
.any(|window| window == literal)
}
})
}
#[tokio::test]
#[serial]
async fn missing_external_snapshot_fails_closed_before_draft_mutation() {
@@ -316,7 +550,7 @@ async fn external_materialization_uses_one_wall_clock_timeout_and_cleans_cancell
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let timeout_server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
@@ -368,6 +602,7 @@ paths:
)
.await
.unwrap();
timeout_server.abort();
assert!(started.elapsed() < std::time::Duration::from_millis(800));
assert_eq!(fetches.load(Ordering::SeqCst), 2);
let job = registry
@@ -403,7 +638,10 @@ paths:
.fetch_one(registry.pool())
.await
.unwrap();
assert_eq!(detached_dependencies, 1);
assert_eq!(
detached_dependencies, 0,
"staged dependencies must not be persisted before the fetch chain completes"
);
}
#[tokio::test]
@@ -606,3 +844,90 @@ async fn exact_v3_contract_replays_persisted_preview_without_v4_or_dependency_re
.unwrap();
assert_eq!(completed.status, ImportJobStatus::Completed);
}
#[tokio::test]
#[serial]
async fn exact_v4_security_contract_replays_its_persisted_security_classification() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_v4_security_compatibility"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let upload = OpenApiUpload {
bytes: br#"{
"openapi":"3.0.3",
"info":{"title":"Historical security","version":"1"},
"servers":[{"url":"https://api.example.test"}],
"components":{"securitySchemes":{"basic":{"type":"http","scheme":"basic"}}},
"security":[{"basic":[]}],
"paths":{
"/secure":{"get":{"operationId":"secure","responses":{"200":{"description":"ok"}}}},
"/public":{"get":{"operationId":"public","security":[],"responses":{"200":{"description":"ok"}}}}
}
}"#
.to_vec(),
mime_type: "application/json".to_owned(),
locale: OpenApiUploadLocale::En,
};
let preview = service
.preview_openapi_import(&workspace_id, upload)
.await
.unwrap();
let job_id: crank_registry::ImportJobId = preview.job_id.as_str().into();
let job = registry
.get_import_job(&workspace_id, &job_id)
.await
.unwrap()
.unwrap();
// Keep the genuine baseline-v4 normalization/projection, preview and digest intact.
// Only bind its source envelope to this test's newly registered immutable source blob.
let mut payload: serde_json::Value =
serde_json::from_str(BASELINE_V4_SECURITY_PREVIEW_PAYLOAD).unwrap();
assert_eq!(
payload.pointer("/source/digest"),
job.preview_payload.pointer("/source/digest"),
"baseline fixture must refer to the exact uploaded source bytes",
);
payload["source"]["source_id"] = job.preview_payload["source"]["source_id"].clone();
assert_eq!(
payload["normalization"]["normalizer_version"],
"normalized-ir-v4"
);
assert_eq!(payload["normalization"]["projection_version"], "preview-v4");
sqlx::query("update import_jobs set preview_payload = $1::jsonb where id = $2")
.bind(serde_json::to_string(&payload).unwrap())
.bind(job_id.as_str())
.execute(registry.pool())
.await
.unwrap();
let result = service
.create_openapi_import(
&workspace_id,
&job_id,
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /secure".to_owned()],
server_url: Some("https://api.example.test".to_owned()),
conflict_mode: "skip".to_owned(),
},
)
.await;
let error =
result.expect_err("historical v4 security blocker must refuse the selected candidate");
assert!(
format!("{error:?}").contains("invalid_document"),
"v4 contract was rejected before candidate validation: {error:?}"
);
assert!(
service
.list_operations(&workspace_id)
.await
.unwrap()
.is_empty()
);
}
mod security_bundle;
@@ -0,0 +1,287 @@
use super::*;
use std::time::Duration;
use tokio::sync::Notify;
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn concurrent_external_previews_keep_snapshot_ownership_workspace_scoped() {
let fetches = Arc::new(AtomicUsize::new(0));
let fetch_count = Arc::clone(&fetches);
let app = Router::new().route(
"/schema.yaml",
get(move || {
let fetch_count = Arc::clone(&fetch_count);
async move {
fetch_count.fetch_add(1, Ordering::SeqCst);
"Item: { type: object, properties: { id: { type: string } } }"
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_external_workspace_isolation");
let service = test_service_with_external_references(
registry.clone(),
storage_root.clone(),
vec![format!("{origin}/")],
);
let workspace_a = create_workspace(&registry, "ws_external_concurrent_a").await;
let workspace_b = create_workspace(&registry, "ws_external_concurrent_b").await;
let (preview_a, preview_b) = tokio::join!(
service.preview_openapi_import(&workspace_a, external_upload(&origin)),
service.preview_openapi_import(&workspace_b, external_upload(&origin)),
);
let preview_a = preview_a.unwrap();
let preview_b = preview_b.unwrap();
server.abort();
assert_eq!(
fetches.load(Ordering::SeqCst),
2,
"each workspace fetches its own preview snapshot"
);
assert_ne!(preview_a.job_id, preview_b.job_id);
let job_a = registry
.get_import_job(&workspace_a, &preview_a.job_id.as_str().into())
.await
.unwrap()
.unwrap();
let job_b = registry
.get_import_job(&workspace_b, &preview_b.job_id.as_str().into())
.await
.unwrap()
.unwrap();
let dependency_a = &job_a.preview_payload["dependencies"][0];
let dependency_b = &job_b.preview_payload["dependencies"][0];
let source_a = ArtifactSourceId::new(dependency_a["source_id"].as_str().unwrap());
let source_b = ArtifactSourceId::new(dependency_b["source_id"].as_str().unwrap());
let digest_a = dependency_a["digest"].as_str().unwrap();
let digest_b = dependency_b["digest"].as_str().unwrap();
let canonical_uri = dependency_a["canonical_uri"].as_str().unwrap();
assert_eq!(
digest_a, digest_b,
"identical bytes may share the immutable blob"
);
assert_eq!(dependency_b["canonical_uri"], dependency_a["canonical_uri"]);
assert_ne!(
source_a, source_b,
"each workspace owns a distinct source relation"
);
let public_a = serde_json::to_string(&preview_a).unwrap();
let public_b = serde_json::to_string(&preview_b).unwrap();
for response in [&public_a, &public_b] {
assert!(!response.contains("src_openapi_dep_"));
assert!(!response.contains(digest_a));
assert!(!response.contains(canonical_uri));
}
let store = Arc::new(ArtifactStore::open(&storage_root).unwrap());
for (workspace_id, source_id) in [(&workspace_a, &source_a), (&workspace_b, &source_b)] {
let source = registry
.get_artifact_source(workspace_id, source_id)
.await
.unwrap();
assert_eq!(source.workspace_id, *workspace_id);
assert_eq!(source.blob.artifact_ref.as_str(), digest_a);
let verified = registry
.read_artifact_source(Arc::clone(&store), workspace_id, source_id)
.await
.unwrap();
assert_eq!(
verified.bytes,
b"Item: { type: object, properties: { id: { type: string } } }"
);
}
let foreign_body = source_not_found_body(
registry
.read_artifact_source(Arc::clone(&store), &workspace_b, &source_a)
.await
.expect_err("workspace B cannot resolve workspace A source"),
)
.await;
let unknown_source = ArtifactSourceId::new("src_unknown_workspace_probe");
let unknown_body = source_not_found_body(
registry
.read_artifact_source(Arc::clone(&store), &workspace_b, &unknown_source)
.await
.expect_err("unknown source is indistinguishable from a foreign source"),
)
.await;
assert_eq!(foreign_body, unknown_body);
let response = foreign_body.to_string();
assert!(!response.contains(digest_a));
assert!(!response.contains(canonical_uri));
assert!(!response.contains(source_a.as_str()));
assert!(!response.contains("exists"));
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn existing_foreign_snapshot_does_not_short_circuit_second_workspace_fetch() {
let fetches = Arc::new(AtomicUsize::new(0));
let fetch_count = Arc::clone(&fetches);
let second_fetch_entered = Arc::new(Notify::new());
let entered = Arc::clone(&second_fetch_entered);
let release_second_fetch = Arc::new(Notify::new());
let release = Arc::clone(&release_second_fetch);
let app = Router::new().route(
"/schema.yaml",
get(move || {
let fetch_count = Arc::clone(&fetch_count);
let entered = Arc::clone(&entered);
let release = Arc::clone(&release);
async move {
let request_number = fetch_count.fetch_add(1, Ordering::SeqCst) + 1;
if request_number == 2 {
entered.notify_one();
release.notified().await;
}
"Item: { type: object, properties: { id: { type: string } } }"
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
let service = test_service_with_external_references(
registry.clone(),
test_storage_root("openapi_import_external_fetch_oracle"),
vec![format!("{origin}/")],
);
let workspace_a = create_workspace(&registry, "ws_external_oracle_a").await;
let workspace_b = create_workspace(&registry, "ws_external_oracle_b").await;
let preview_a = service
.preview_openapi_import(&workspace_a, external_upload(&origin))
.await
.unwrap();
assert_eq!(fetches.load(Ordering::SeqCst), 1);
let preview_b_origin = origin.clone();
let preview_b_workspace = workspace_b.clone();
let mut preview_b_task = tokio::spawn(async move {
service
.preview_openapi_import(&preview_b_workspace, external_upload(&preview_b_origin))
.await
});
tokio::time::timeout(Duration::from_secs(10), second_fetch_entered.notified())
.await
.expect("the second preview must reach its HTTP fetch");
// The fixture holds the real HTTP response. Poll the preview once after
// observing that fetch; it must remain pending until the fixture releases it.
tokio::select! {
biased;
result = &mut preview_b_task => panic!("second preview bypassed its held fetch: {result:?}"),
_ = tokio::task::yield_now() => {}
}
assert_eq!(fetches.load(Ordering::SeqCst), 2);
release_second_fetch.notify_one();
let preview_b = tokio::time::timeout(Duration::from_secs(10), &mut preview_b_task)
.await
.expect("the released second preview should complete")
.unwrap()
.unwrap();
server.abort();
let job_a = registry
.get_import_job(&workspace_a, &preview_a.job_id.as_str().into())
.await
.unwrap()
.unwrap();
let job_b = registry
.get_import_job(&workspace_b, &preview_b.job_id.as_str().into())
.await
.unwrap()
.unwrap();
let source_a = ArtifactSourceId::new(
job_a.preview_payload["dependencies"][0]["source_id"]
.as_str()
.unwrap(),
);
let source_b = ArtifactSourceId::new(
job_b.preview_payload["dependencies"][0]["source_id"]
.as_str()
.unwrap(),
);
assert_ne!(source_a, source_b);
assert_eq!(fetches.load(Ordering::SeqCst), 2);
}
#[tokio::test]
#[serial]
async fn file_origin_and_relative_chain_are_blocked_without_file_or_network_access() {
const PRIVATE_FILE_BYTES: &str = "PrivateCanary: file-origin-secret-must-never-be-read";
const HYPOTHETICAL_FILE_ROOT: &str = "Item: { $ref: './private/canary.yaml#/Secret' }";
let file_fixture_root = test_storage_root("openapi_import_file_origin_fixture");
let private_directory = file_fixture_root.join("private");
std::fs::create_dir_all(&private_directory).unwrap();
std::fs::write(file_fixture_root.join("root.yaml"), HYPOTHETICAL_FILE_ROOT).unwrap();
std::fs::write(
private_directory.join("canary.yaml"),
format!("Secret: {{ type: string, example: '{PRIVATE_FILE_BYTES}' }}"),
)
.unwrap();
let file_origin = url::Url::from_file_path(file_fixture_root.join("root.yaml")).unwrap();
let file_origin_for_response = file_origin.clone();
let requests = Arc::new(AtomicUsize::new(0));
let request_count = Arc::clone(&requests);
let app = Router::new().route(
"/schema.yaml",
get(move || {
let request_count = Arc::clone(&request_count);
async move {
request_count.fetch_add(1, Ordering::SeqCst);
format!("Item: {{ $ref: '{file_origin_for_response}#/Item' }}")
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
let service = test_service_with_external_references(
registry,
test_storage_root("openapi_import_file_origin_blocked"),
vec![format!("{origin}/")],
);
let preview = service
.preview_openapi_import(&WorkspaceId::new("ws_default"), external_upload(&origin))
.await
.unwrap();
server.abort();
assert_eq!(
requests.load(Ordering::SeqCst),
1,
"only the explicitly allowlisted HTTP root is fetched"
);
let findings = preview
.preview
.groups
.iter()
.flat_map(|group| &group.operations)
.flat_map(|operation| &operation.findings)
.chain(preview.preview.findings.iter())
.collect::<Vec<_>>();
assert!(
findings.iter().any(|finding| {
finding.severity == crank_import::rest::ImportFindingSeverity::Error
&& finding.code == "reference_target_missing"
}),
"file origin must produce a blocking unresolved-reference finding"
);
let report = serde_json::to_string(&preview).unwrap();
assert!(!report.contains(file_origin.as_str()));
assert!(!report.contains(PRIVATE_FILE_BYTES));
assert!(!report.contains(HYPOTHETICAL_FILE_ROOT));
}
@@ -0,0 +1,413 @@
use super::*;
// --- Referenced security credentials RED regressions ---
// These tests prove that credential literals hidden behind local/external $ref
// security scheme + parameter splits are rejected before artifact persistence.
#[tokio::test]
#[serial]
async fn referenced_security_credentials_local_scheme_ref_with_parameter_default_canary_rejected() {
let canary = b"local-ref-canary-001-Zx9qK";
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_local_scheme_ref_canary");
let service = test_service(
registry.clone(),
storage_root.clone(),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let upload = OpenApiUpload {
bytes: r##"{
"openapi":"3.1.0",
"info":{"title":"Local ref scheme","version":"1"},
"servers":[{"url":"https://api.example.test"}],
"x-scheme":{"type":"apiKey","in":"header","name":"X-Custom"},
"x-key":{"type":"string","default":"local-ref-canary-001-Zx9qK"},
"components":{
"securitySchemes":{"custom":{"$ref":"#/x-scheme"}}
},
"security":[{"custom":[]}],
"paths":{
"/test":{"get":{
"operationId":"test", "security":[{"custom":[]}],
"parameters":[{"name":"X-Custom","in":"header","schema":{"$ref":"#/x-key"}}],
"responses":{"200":{"description":"ok"}}
}}
}
}"##
.as_bytes()
.to_vec(),
mime_type: "application/json".to_owned(),
locale: OpenApiUploadLocale::En,
};
let result = service.preview_openapi_import(&workspace_id, upload).await;
// Canary must NOT appear in the API response (error or preview).
let response_repr = match &result {
Ok(preview) => serde_json::to_string(preview).unwrap(),
Err(err) => format!("{err:?}"),
};
assert!(
response_repr.contains("invalid_document"),
"unsafe local ref bundle was not rejected: {response_repr}"
);
assert!(
!response_repr.contains(std::str::from_utf8(canary).unwrap()),
"credential canary leaked into API response"
);
// Canary must NOT be persisted to artifact storage.
assert!(
!storage_contains_literal(&storage_root, canary),
"raw credential literal from referenced local scheme ref persisted to storage"
);
assert_rejected_bundle_unpersisted(&registry, &workspace_id, &storage_root).await;
}
#[tokio::test]
#[serial]
async fn encoded_access_token_fragment_is_rejected_before_persistence() {
let canary = b"fragment-ingress-canary-004-Qm7vN";
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_encoded_fragment_canary");
let service = test_service(
registry.clone(),
storage_root.clone(),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let upload = OpenApiUpload {
bytes: br##"{
"openapi":"3.1.0",
"info":{"title":"Encoded fragment credential","version":"1"},
"servers":[{"url":"https://api.example.test/v1#%61%63%63%65%73%73%5F%74%6F%6B%65%6E=fragment-ingress-canary-004-Qm7vN"}],
"paths":{"/health":{"get":{"responses":{"200":{"description":"ok"}}}}}
}"##
.to_vec(),
mime_type: "application/json".to_owned(),
locale: OpenApiUploadLocale::En,
};
let error = service
.preview_openapi_import(&workspace_id, upload)
.await
.expect_err("encoded access_token fragment must be rejected at ingress");
let rendered_error = format!("{error:?}");
assert!(rendered_error.contains("invalid_document"));
assert!(rendered_error.len() <= 512, "error must remain bounded");
assert!(!rendered_error.contains("fragment-ingress-canary-004-Qm7vN"));
assert!(!rendered_error.contains("%61%63%63%65%73%73%5F%74%6F%6B%65%6E"));
assert_rejected_bundle_unpersisted(&registry, &workspace_id, &storage_root).await;
assert!(!storage_contains_literal(&storage_root, canary));
}
#[tokio::test]
#[serial]
async fn referenced_security_credentials_external_scheme_ref_local_parameter_default_canary_rejected()
{
let canary = b"split-ext-canary-002-Yw8pJ";
// External document defines the apiKey security scheme with header X-Custom.
let external_doc = r#"{"x-scheme":{"type":"apiKey","in":"header","name":"X-Custom"}}"#;
let fetched = Arc::new(AtomicUsize::new(0));
let fetch_count = Arc::clone(&fetched);
let app = Router::new().route(
"/scheme.yaml",
get(move || {
let fc = Arc::clone(&fetch_count);
async move {
fc.fetch_add(1, Ordering::SeqCst);
external_doc.to_owned()
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_ext_scheme_ref_canary");
let service = test_service_with_external_references(
registry.clone(),
storage_root.clone(),
vec![format!("{origin}/")],
);
let workspace_id = WorkspaceId::new("ws_default");
// Primary references the external scheme; contains a local parameter
// with name X-Custom and schema.default = canary.
let upload = OpenApiUpload {
bytes: format!(
r#"{{
"openapi":"3.1.0",
"info":{{"title":"Ext scheme ref","version":"1"}},
"servers":[{{"url":"https://api.example.test"}}],
"components":{{
"securitySchemes":{{"custom":{{"$ref":"{origin}/scheme.yaml#/x-scheme"}}}}
}},
"security":[{{"custom":[]}}],
"paths":{{
"/test":{{"get":{{
"operationId":"test", "security":[{{"custom":[]}}],
"parameters":[{{"name":"X-Custom","in":"header","schema":{{"type":"string","default":"{canary}"}}}}],
"responses":{{"200":{{"description":"ok"}}}}
}}}}
}}
}}"#,
origin = origin,
canary = std::str::from_utf8(canary).unwrap(),
)
.into_bytes(),
mime_type: "application/json".to_owned(),
locale: OpenApiUploadLocale::En,
};
let result = service.preview_openapi_import(&workspace_id, upload).await;
server.abort();
assert_eq!(
fetched.load(Ordering::SeqCst),
1,
"external scheme must be fetched before the split is checked"
);
let response_repr = match &result {
Ok(preview) => serde_json::to_string(preview).unwrap(),
Err(err) => format!("{err:?}"),
};
assert!(
response_repr.contains("invalid_document"),
"unsafe external scheme bundle was not rejected: {response_repr}"
);
assert!(
!response_repr.contains(std::str::from_utf8(canary).unwrap()),
"credential canary leaked into API response"
);
assert!(
!storage_contains_literal(&storage_root, canary),
"raw credential literal from split external scheme ref persisted to storage"
);
assert_rejected_bundle_unpersisted(&registry, &workspace_id, &storage_root).await;
}
#[tokio::test]
#[serial]
async fn referenced_security_credentials_local_scheme_external_parameter_default_canary_rejected() {
let canary = b"split-local-canary-003-Xv7oI";
// External document defines a parameter schema whose default is the canary.
let external_doc = format!(
r#"{{"x-key":{{"type":"string","default":"{canary}"}}}}"#,
canary = std::str::from_utf8(canary).unwrap(),
);
let fetched = Arc::new(AtomicUsize::new(0));
let fetch_count = Arc::clone(&fetched);
let app = Router::new().route(
"/key.yaml",
get(move || {
let fc = Arc::clone(&fetch_count);
async move {
fc.fetch_add(1, Ordering::SeqCst);
external_doc.clone()
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_local_scheme_ext_param_canary");
let service = test_service_with_external_references(
registry.clone(),
storage_root.clone(),
vec![format!("{origin}/")],
);
let workspace_id = WorkspaceId::new("ws_default");
// Primary declares the scheme directly (no $ref); parameter schema is
// an external $ref whose resolved default would be the canary.
let upload = OpenApiUpload {
bytes: format!(
r#"{{
"openapi":"3.1.0",
"info":{{"title":"Local scheme ext param","version":"1"}},
"servers":[{{"url":"https://api.example.test"}}],
"components":{{
"securitySchemes":{{"custom":{{"type":"apiKey","in":"header","name":"X-Custom"}}}}
}},
"security":[{{"custom":[]}}],
"paths":{{
"/test":{{"get":{{
"operationId":"test", "security":[{{"custom":[]}}],
"parameters":[{{"name":"X-Custom","in":"header","schema":{{"$ref":"{origin}/key.yaml#/x-key"}}}}],
"responses":{{"200":{{"description":"ok"}}}}
}}}}
}}
}}"#,
origin = origin,
)
.into_bytes(),
mime_type: "application/json".to_owned(),
locale: OpenApiUploadLocale::En,
};
let result = service.preview_openapi_import(&workspace_id, upload).await;
server.abort();
assert_eq!(
fetched.load(Ordering::SeqCst),
1,
"external parameter must be fetched before the split is checked"
);
let response_repr = match &result {
Ok(preview) => serde_json::to_string(preview).unwrap(),
Err(err) => format!("{err:?}"),
};
assert!(
response_repr.contains("invalid_document"),
"unsafe external parameter bundle was not rejected: {response_repr}"
);
assert!(
!response_repr.contains(std::str::from_utf8(canary).unwrap()),
"credential canary leaked into API response"
);
assert!(
!storage_contains_literal(&storage_root, canary),
"raw credential literal from external referenced parameter persisted to storage"
);
assert_rejected_bundle_unpersisted(&registry, &workspace_id, &storage_root).await;
}
#[tokio::test]
#[serial]
async fn safe_external_security_scheme_and_parameter_are_preserved() {
let external_doc = r#"{"x-scheme":{"type":"apiKey","in":"header","name":"X-Custom"}}"#;
let fetched = Arc::new(AtomicUsize::new(0));
let fetch_count = Arc::clone(&fetched);
let app = Router::new().route(
"/scheme.yaml",
get(move || {
let count = Arc::clone(&fetch_count);
async move {
count.fetch_add(1, Ordering::SeqCst);
external_doc
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_safe_external_security_ref");
let service = test_service_with_external_references(
registry.clone(),
storage_root,
vec![format!("{origin}/")],
);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(
&workspace_id,
OpenApiUpload {
bytes: format!(
r#"openapi: 3.1.0
info: {{ title: Safe external scheme, version: '1' }}
servers: [{{ url: https://api.example.test }}]
components:
securitySchemes:
custom: {{ $ref: '{origin}/scheme.yaml#/x-scheme' }}
security: [{{ custom: [] }}]
paths:
/test:
get:
operationId: safeExternalSecurity
security: [{{ custom: [] }}]
parameters:
- name: X-Custom
in: header
schema: {{ type: string }}
- name: locale
in: query
schema: {{ type: string, default: en }}
responses:
'200': {{ description: ok }}
"#
)
.into_bytes(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
},
)
.await
.expect("safe referenced schemes and parameters remain importable");
server.abort();
assert_eq!(fetched.load(Ordering::SeqCst), 1);
let operation = preview
.preview
.groups
.iter()
.flat_map(|group| &group.operations)
.find(|operation| operation.key == "GET /test")
.expect("operation preview is preserved");
assert!(matches!(
&operation.security_schemes["custom"].kind,
crank_import::rest::NormalizedSecuritySchemeKind::ApiKey {
parameter_name,
location: crank_import::rest::SecurityParameterLocation::Header,
..
} if parameter_name == "X-Custom"
));
let input_schema = serde_json::to_value(&operation.draft.input_schema).unwrap();
assert_eq!(
input_schema.pointer("/fields/locale/default_value"),
Some(&serde_json::json!("en")),
"benign locale default must remain visible in the preview"
);
let job = registry
.get_import_job(&workspace_id, &preview.job_id.as_str().into())
.await
.unwrap()
.unwrap();
assert_eq!(
job.preview_payload["dependency_snapshots"]
.as_array()
.unwrap()
.len(),
1
);
}
async fn assert_rejected_bundle_unpersisted(
registry: &crank_registry::PostgresRegistry,
workspace_id: &WorkspaceId,
storage_root: &std::path::Path,
) {
let sources: i64 =
sqlx::query_scalar("select count(*) from artifact_sources where workspace_id = $1")
.bind(workspace_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap();
let jobs: i64 = sqlx::query_scalar("select count(*) from import_jobs where workspace_id = $1")
.bind(workspace_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap();
assert_eq!(sources, 0, "rejected bundle registered a source");
assert_eq!(jobs, 0, "rejected bundle created an import job");
assert!(
!storage_has_files(storage_root),
"rejected bundle stored artifact bytes"
);
}
fn storage_has_files(path: &std::path::Path) -> bool {
std::fs::read_dir(path).unwrap().any(|entry| {
let path = entry.unwrap().path();
if path.is_dir() {
storage_has_files(&path)
} else {
true
}
})
}
@@ -0,0 +1,603 @@
//! F1 transport-parity cases for the Admin external-reference import.
//!
//! The external materializer stores snapshot keys produced by the URL transport
//! (`url::Url`), which collapses a `%2e%2e` path segment and percent-encodes an
//! apostrophe in a query (`'` -> `%27`). Because the materializer and the pure
//! resolver used different URI keys, both references produced a false
//! `external_reference_unavailable` blocker. These cases run the real allowlisted
//! fixture server through preview -> apply -> replay (service) and through the
//! authenticated multipart route (outer). They are registered from
//! `external_references.rs` so the parent file stays within the repository
//! file-size budget; shared helpers and imports come from `super`.
use super::*;
// F1 acceptance (both cases): the service preview -> apply -> replay path. The
// assertions verify the transport-canonical keys resolve, the dependency
// bytes/digests verify, apply never refetches, and replay is a stable no-op.
#[tokio::test]
#[serial]
async fn transport_canonical_external_uris_resolve_without_false_blocker_or_refetch() {
// Distinct bytes so each canonical URI owns a distinct content-addressed
// blob; byte-identical documents collapse into a single dependency envelope
// (the recorded alias/digest observation) and could not be told apart.
const ROOT_ITEM: &str =
"Item: { type: object, required: [id], properties: { id: { type: string } } }";
const QUERY_ITEM: &str =
"Item: { type: object, required: [id], properties: { id: { type: integer } } }";
let fetches = Arc::new(AtomicUsize::new(0));
let root_fetches = Arc::clone(&fetches);
let query_fetches = Arc::clone(&fetches);
let app = Router::new()
.route(
"/root.yaml",
get(move || {
let fetches = Arc::clone(&root_fetches);
async move {
fetches.fetch_add(1, Ordering::SeqCst);
ROOT_ITEM
}
}),
)
.route(
"/schema.json",
get(move || {
let fetches = Arc::clone(&query_fetches);
async move {
fetches.fetch_add(1, Ordering::SeqCst);
QUERY_ITEM
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let fixture_server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_external_uri_transport_parity");
let service = test_service_with_external_references(
registry.clone(),
storage_root.clone(),
vec![format!("{origin}/")],
);
let workspace_id = WorkspaceId::new("ws_default");
let upload = OpenApiUpload {
bytes: format!(
r##"
openapi: 3.1.0
info: {{ title: External URI transport parity }}
servers: [{{ url: https://api.example.test }}]
paths:
/dot:
get:
operationId: encodedDot
responses:
'200':
description: ok
content: {{ application/json: {{ schema: {{ $ref: '{origin}/a/%2e%2e/root.yaml#/Item' }} }} }}
/query:
get:
operationId: quotedQuery
responses:
'200':
description: ok
content: {{ application/json: {{ schema: {{ $ref: "{origin}/schema.json?filter='x'#/Item" }} }} }}
"##
)
.into_bytes(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
};
let preview = service
.preview_openapi_import(&workspace_id, upload)
.await
.unwrap();
// Materialization first: the external materializer must have downloaded and
// stored both snapshots under the transport-canonical keys before resolution
// is judged. This separates the F1 resolver key mismatch from a snapshot that
// was never fetched at all.
let job_id: crank_registry::ImportJobId = preview.job_id.as_str().into();
let job = registry
.get_import_job(&workspace_id, &job_id)
.await
.unwrap()
.unwrap();
let dependencies = job.preview_payload["dependencies"].as_array().unwrap();
assert_eq!(dependencies.len(), 2);
let canonical_uris = dependencies
.iter()
.map(|dependency| dependency["canonical_uri"].as_str().unwrap().to_owned())
.collect::<std::collections::BTreeSet<_>>();
assert_eq!(
canonical_uris,
std::collections::BTreeSet::from([
format!("{origin}/root.yaml"),
format!("{origin}/schema.json?filter=%27x%27"),
]),
"materialized dependency keys must be the transport-canonical URIs"
);
assert_eq!(
fetches.load(Ordering::SeqCst),
2,
"both external documents must be fetched exactly once during preview"
);
// Dependency bytes and digests verify against the workspace-scoped store.
let store = Arc::new(ArtifactStore::open(&storage_root).unwrap());
for dependency in dependencies {
let source_id = ArtifactSourceId::new(dependency["source_id"].as_str().unwrap());
let digest = dependency["digest"].as_str().unwrap();
let verified = registry
.read_artifact_source(Arc::clone(&store), &workspace_id, &source_id)
.await
.unwrap();
assert_eq!(verified.source.blob.artifact_ref.as_str(), digest);
let canonical_uri = dependency["canonical_uri"].as_str().unwrap();
let expected = if canonical_uri.ends_with("/root.yaml") {
ROOT_ITEM
} else {
QUERY_ITEM
};
assert_eq!(verified.bytes, expected.as_bytes());
}
// Criterion-defining: neither transport-canonical URI may become a false
// blocker. Collected across all operations so one failure reports both.
let false_blockers = preview
.preview
.groups
.iter()
.flat_map(|group| &group.operations)
.flat_map(|operation| {
operation
.findings
.iter()
.filter(|finding| finding.code == "external_reference_unavailable")
.map(|_| operation.key.clone())
})
.collect::<Vec<_>>();
assert!(
false_blockers.is_empty(),
"both transport-canonical URIs must resolve; false external blockers: {false_blockers:?}"
);
let resolved = preview
.preview
.groups
.iter()
.flat_map(|group| &group.operations)
.map(|operation| (operation.key.clone(), operation.output_fields))
.collect::<std::collections::BTreeMap<_, _>>();
assert_eq!(resolved["GET /dot"], 1, "encoded-dot schema must resolve");
assert_eq!(
resolved["GET /query"], 1,
"quoted-query schema must resolve"
);
// Apply consumes the saved snapshots and must not refetch.
let created = service
.create_openapi_import(
&workspace_id,
&job_id,
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /dot".to_owned(), "GET /query".to_owned()],
server_url: None,
conflict_mode: "skip".to_owned(),
},
)
.await
.unwrap();
assert_eq!(created.created.len(), 2);
assert_eq!(
fetches.load(Ordering::SeqCst),
2,
"apply must reuse the saved dependency snapshots"
);
let drafts_after_apply = registry.list_operations(&workspace_id).await.unwrap().len();
// AC-2 replay: re-issue the SAME request key/payload. The import is already
// applied, so the service must return the stored application result, create
// no extra Draft, and refetch nothing. The fixture server stays alive until
// after the replay so the counter would observe any real request.
let replay = service
.create_openapi_import(
&workspace_id,
&job_id,
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /dot".to_owned(), "GET /query".to_owned()],
server_url: None,
conflict_mode: "skip".to_owned(),
},
)
.await
.unwrap();
assert_eq!(
replay.created, created.created,
"replay must return the stored application result for the same request key and payload"
);
assert_eq!(replay.created.len(), 2);
assert_eq!(
fetches.load(Ordering::SeqCst),
2,
"replay must not refetch dependency snapshots"
);
fixture_server.abort();
let completed = registry
.get_import_job(&workspace_id, &job_id)
.await
.unwrap()
.unwrap();
assert_eq!(completed.status, ImportJobStatus::Completed);
assert_eq!(
registry.list_operations(&workspace_id).await.unwrap().len(),
drafts_after_apply,
"replay must not create extra Drafts"
);
}
// F1 outer path: the same references uploaded as authenticated multipart through
// the outer router must preview without a false blocker, and the materializer
// must have stored both transport-canonical snapshots before resolution is
// judged. The run then continues through the real router apply and a replay of
// the same payload key while the fixture is still alive: the stored application
// result must be returned unchanged, no extra Draft may appear, and the fetch
// counter must not grow.
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn outer_authenticated_multipart_preview_matches_transport_canonical_uri() {
// Distinct bytes so the two canonical URIs cannot collapse into one
// dependency envelope; both remain valid resolvable schemas.
const ROOT_ITEM: &str =
"Item: { type: object, required: [id], properties: { id: { type: string } } }";
const QUERY_ITEM: &str =
"Item: { type: object, required: [id], properties: { id: { type: integer } } }";
let fetches = Arc::new(AtomicUsize::new(0));
let root_fetches = Arc::clone(&fetches);
let query_fetches = Arc::clone(&fetches);
let fixture = Router::new()
.route(
"/root.yaml",
get(move || {
let fetches = Arc::clone(&root_fetches);
async move {
fetches.fetch_add(1, Ordering::SeqCst);
ROOT_ITEM
}
}),
)
.route(
"/schema.json",
get(move || {
let fetches = Arc::clone(&query_fetches);
async move {
fetches.fetch_add(1, Ordering::SeqCst);
QUERY_ITEM
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let fixture_server = tokio::spawn(async move { axum::serve(listener, fixture).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
let app = build_test_app_with_external_references(
registry.clone(),
test_storage_root("openapi_import_external_uri_multipart"),
vec![format!("{origin}/")],
);
let server = spawn_admin_api(app).await;
let client = authorized_client(&server).await;
let document = format!(
r##"
openapi: 3.1.0
info: {{ title: Multipart transport parity }}
servers: [{{ url: https://api.example.test }}]
paths:
/dot:
get:
operationId: encodedDot
responses:
'200':
description: ok
content: {{ application/json: {{ schema: {{ $ref: '{origin}/a/%2e%2e/root.yaml#/Item' }} }} }}
/query:
get:
operationId: quotedQuery
responses:
'200':
description: ok
content: {{ application/json: {{ schema: {{ $ref: "{origin}/schema.json?filter='x'#/Item" }} }} }}
"##
);
let response = client
.post(format!("{server}/imports/openapi/preview"))
.multipart(
Form::new().part(
"file",
Part::bytes(document.into_bytes())
.file_name("openapi.yaml".to_owned())
.mime_str("application/yaml")
.unwrap(),
),
)
.send()
.await
.unwrap();
let status = response.status();
let body = response.json::<serde_json::Value>().await.unwrap();
assert_eq!(status, reqwest::StatusCode::OK, "{body}");
// The materializer must have downloaded both snapshots under the
// transport-canonical keys before the blocker check is meaningful.
let job_id_str = body["job_id"].as_str().unwrap().to_owned();
let job_id: crank_registry::ImportJobId = job_id_str.as_str().into();
let job = registry
.get_import_job(&WorkspaceId::new("ws_default"), &job_id)
.await
.unwrap()
.unwrap();
let canonical_uris = job.preview_payload["dependencies"]
.as_array()
.unwrap()
.iter()
.map(|dependency| dependency["canonical_uri"].as_str().unwrap().to_owned())
.collect::<std::collections::BTreeSet<_>>();
assert_eq!(
canonical_uris,
std::collections::BTreeSet::from([
format!("{origin}/root.yaml"),
format!("{origin}/schema.json?filter=%27x%27"),
]),
"both transport-canonical external URIs must be materialized"
);
assert_eq!(
fetches.load(Ordering::SeqCst),
2,
"preview must fetch each external document exactly once"
);
assert!(
!body.to_string().contains("external_reference_unavailable"),
"outer multipart preview must not report a false external blocker: {body}"
);
let resolved = body["preview"]["groups"][0]["operations"]
.as_array()
.unwrap()
.iter()
.map(|operation| {
(
operation["key"].as_str().unwrap().to_owned(),
operation["output_fields"].clone(),
)
})
.collect::<std::collections::BTreeMap<_, _>>();
assert_eq!(resolved["GET /dot"], serde_json::json!(1));
assert_eq!(resolved["GET /query"], serde_json::json!(1));
// AC-2: apply through the real authenticated router, then replay the SAME
// payload key. The fixture stays alive so a real refetch would move the
// counter, and the same application key must not create another Draft.
let create_payload = serde_json::json!({
"selected_operation_keys": ["GET /dot", "GET /query"],
"server_url": null,
"conflict_mode": "skip"
});
let create_response = client
.post(format!("{server}/imports/openapi/{job_id_str}/create"))
.json(&create_payload)
.send()
.await
.unwrap();
assert_eq!(
create_response.status(),
reqwest::StatusCode::OK,
"apply through the router must succeed"
);
let created: serde_json::Value = create_response.json().await.unwrap();
assert_eq!(created["created"].as_array().unwrap().len(), 2);
assert_eq!(
fetches.load(Ordering::SeqCst),
2,
"apply must reuse the saved dependency snapshots"
);
let drafts_after_apply = client
.get(format!("{server}/operations"))
.send()
.await
.unwrap()
.json::<serde_json::Value>()
.await
.unwrap()["total"]
.clone();
assert_eq!(drafts_after_apply, serde_json::json!(2));
let replay_response = client
.post(format!("{server}/imports/openapi/{job_id_str}/create"))
.json(&create_payload)
.send()
.await
.unwrap();
assert_eq!(replay_response.status(), reqwest::StatusCode::OK);
let replay: serde_json::Value = replay_response.json().await.unwrap();
assert_eq!(
replay, created,
"replaying the same payload key must return the stored application result"
);
assert_eq!(
fetches.load(Ordering::SeqCst),
2,
"replay must not refetch dependency snapshots"
);
let drafts_after_replay = client
.get(format!("{server}/operations"))
.send()
.await
.unwrap()
.json::<serde_json::Value>()
.await
.unwrap()["total"]
.clone();
assert_eq!(
drafts_after_replay, drafts_after_apply,
"replay must not create extra Drafts"
);
fixture_server.abort();
}
// AC-3 over real HTTP: the primary document references an encoded-dot root alias
// (`/a/%2e%2e/root.yaml`) whose document contains a relative child `$ref`. The
// materializer must canonicalize the alias to `/root.yaml`, then join the child
// against that real canonical root (not the raw alias), so `/child.yaml` is
// fetched exactly once and the derived schema resolves through the chain.
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn encoded_dot_root_alias_chain_resolves_relative_child_against_canonical_root_over_http() {
const ROOT_ALIAS_DOCUMENT: &str = "Item: { $ref: './child.yaml#/Item' }";
const CHILD_ITEM: &str =
"Item: { type: object, required: [id], properties: { id: { type: string } } }";
let fetches = Arc::new(AtomicUsize::new(0));
let root_fetches = Arc::clone(&fetches);
let child_fetches = Arc::clone(&fetches);
let app = Router::new()
.route(
"/root.yaml",
get(move || {
let fetches = Arc::clone(&root_fetches);
async move {
fetches.fetch_add(1, Ordering::SeqCst);
ROOT_ALIAS_DOCUMENT
}
}),
)
.route(
"/child.yaml",
get(move || {
let fetches = Arc::clone(&child_fetches);
async move {
fetches.fetch_add(1, Ordering::SeqCst);
CHILD_ITEM
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let fixture_server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_external_uri_dot_root_chain");
let service = test_service_with_external_references(
registry.clone(),
storage_root.clone(),
vec![format!("{origin}/")],
);
let workspace_id = WorkspaceId::new("ws_default");
let upload = OpenApiUpload {
bytes: format!(
r##"
openapi: 3.1.0
info: {{ title: Canonical root alias chain }}
servers: [{{ url: https://api.example.test }}]
paths:
/items:
get:
operationId: listItems
responses:
'200':
description: ok
content: {{ application/json: {{ schema: {{ $ref: '{origin}/a/%2e%2e/root.yaml#/Item' }} }} }}
"##
)
.into_bytes(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
};
let preview = service
.preview_openapi_import(&workspace_id, upload)
.await
.unwrap();
let job_id: crank_registry::ImportJobId = preview.job_id.as_str().into();
let job = registry
.get_import_job(&workspace_id, &job_id)
.await
.unwrap()
.unwrap();
let dependencies = job.preview_payload["dependencies"].as_array().unwrap();
assert_eq!(dependencies.len(), 2);
let canonical_uris = dependencies
.iter()
.map(|dependency| dependency["canonical_uri"].as_str().unwrap().to_owned())
.collect::<std::collections::BTreeSet<_>>();
assert_eq!(
canonical_uris,
std::collections::BTreeSet::from([
format!("{origin}/root.yaml"),
format!("{origin}/child.yaml"),
]),
"the child must be materialized relative to the canonical root, not the raw encoded-dot alias"
);
assert_eq!(
fetches.load(Ordering::SeqCst),
2,
"the canonical root alias and its relative child must each be fetched exactly once"
);
// Dependency bytes and digests verify against the workspace-scoped store.
let store = Arc::new(ArtifactStore::open(&storage_root).unwrap());
for dependency in dependencies {
let source_id = ArtifactSourceId::new(dependency["source_id"].as_str().unwrap());
let digest = dependency["digest"].as_str().unwrap();
let verified = registry
.read_artifact_source(Arc::clone(&store), &workspace_id, &source_id)
.await
.unwrap();
assert_eq!(verified.source.blob.artifact_ref.as_str(), digest);
let canonical_uri = dependency["canonical_uri"].as_str().unwrap();
let expected = if canonical_uri.ends_with("/root.yaml") {
ROOT_ALIAS_DOCUMENT
} else {
CHILD_ITEM
};
assert_eq!(verified.bytes, expected.as_bytes());
}
// No false blocker: the chain resolves through the canonical root.
let false_blockers = preview
.preview
.groups
.iter()
.flat_map(|group| &group.operations)
.flat_map(|operation| {
operation
.findings
.iter()
.filter(|finding| finding.code == "external_reference_unavailable")
.map(|_| operation.key.clone())
})
.collect::<Vec<_>>();
assert!(
false_blockers.is_empty(),
"the encoded-dot root alias chain must resolve; false blockers: {false_blockers:?}"
);
assert_eq!(preview.preview.groups[0].operations[0].output_fields, 1);
// The derived schema must be the child object reached through the canonical
// root, projected into the persisted preview.
let output_schema =
&job.preview_payload["preview"]["groups"][0]["operations"][0]["draft"]["output_schema"];
assert_eq!(
output_schema["type"], "object",
"the operation output schema must be the child object derived through the chain: {output_schema}"
);
assert_eq!(
output_schema["fields"]["id"]["type"], "string",
"the child `id` property must survive resolution: {output_schema}"
);
fixture_server.abort();
}
@@ -0,0 +1,170 @@
{
"dependencies": [],
"dependency_snapshots": [],
"normalization": {
"config": {
"external_references_enabled": false,
"max_aliases": 128,
"max_bytes": 262144,
"max_collection_items": 10000,
"max_depth": 64,
"max_expanded_nodes": 100000,
"max_external_document_bytes": 262144,
"max_nodes": 50000,
"max_reference_depth": 32,
"max_reference_documents": 32,
"max_references": 4096,
"max_scalar_bytes": 262144,
"normalizer_version": "normalized-ir-v5",
"projection_version": "preview-v6"
},
"ir_fingerprint": "1e7a724e849b657d79d78f494d962ba5ebc164f154902153a8ed0610e0744679",
"normalizer_version": "normalized-ir-v5",
"projection_version": "preview-v6"
},
"preview": {
"findings": [],
"groups": [
{
"key": "imported_operation",
"operations": [
{
"category": "imported",
"description": "Выполняет GET /items",
"draft": {
"category": "imported",
"display_name": "List Items",
"input_mapping": {},
"input_schema": {
"description": "Входные параметры MCP-инструмента",
"nullable": false,
"required": true,
"type": "object"
},
"name": "list_items",
"output_mapping": {
"rules": [
{
"required": true,
"source": "$.response.body.id",
"target": "$.output.id"
}
]
},
"output_schema": {
"description": "Ответ API",
"fields": {
"id": {
"nullable": false,
"required": true,
"type": "string"
}
},
"nullable": false,
"required": true,
"type": "object"
},
"target": {
"base_url": "https://api.example.test",
"method": "GET",
"path_template": "/items",
"response_contract": [
{
"media_type": "application/json",
"schema_variant": 0,
"status_code": 200
}
]
},
"tool_description": {
"description": "Выполняет GET /items",
"examples": [
{
"input": {}
}
],
"title": "List Items"
},
"wizard_state": {}
},
"findings": [
{
"code": "missing_summary",
"message": "У метода нет summary, отображаемое имя будет сгенерировано автоматически.",
"operation_key": "GET /items",
"severity": "warning",
"source_location": {
"pointer": "/paths/~1items/get"
}
},
{
"code": "missing_description",
"message": "У метода нет description. Перед публикацией лучше описать, когда агенту стоит вызывать этот инструмент.",
"operation_key": "GET /items",
"severity": "warning",
"source_location": {
"pointer": "/paths/~1items/get"
}
},
{
"code": "no_input_fields",
"message": "У инструмента нет входных параметров. Это нормально для справочных методов, но проверьте, что агенту не нужно передавать фильтры.",
"operation_key": "GET /items",
"severity": "info",
"source_location": {
"pointer": "/paths/~1items/get"
}
},
{
"code": "weak_tool_description",
"message": "Описание инструмента слишком короткое или техническое. Перед публикацией добавьте, когда агент должен вызывать инструмент и что будет в успешном ответе.",
"operation_key": "GET /items",
"severity": "warning",
"source_location": {
"pointer": "/paths/~1items/get"
}
},
{
"code": "weak_tool_name",
"message": "Имя инструмента `list_items` выглядит слишком общим. Лучше использовать имя с конкретным действием и объектом.",
"operation_key": "GET /items",
"severity": "warning",
"source_location": {
"pointer": "/paths/~1items/get"
}
}
],
"input_fields": 0,
"key": "GET /items",
"method": "GET",
"operation_id": "listItems",
"output_fields": 1,
"path": "/items",
"server_urls": [
"https://api.example.test"
],
"source_location": {
"pointer": "/paths/~1items/get"
},
"suggested_display_name": "List Items",
"suggested_name": "list_items"
}
],
"title": "Без группы"
}
],
"source": {
"format": "openapi",
"servers": [
"https://api.example.test"
],
"title": "URI preview parity",
"version": "3.1.0"
}
},
"preview_digest": "ab615bbb932979b3c9d7d78223fc932069e1d7443860a24c682edddc0de11637",
"source": {
"digest": "sha256:edc9f4ec760d76a6830ae5b9932881d898626faffbc0067162ddb44ebdf8b94c",
"source_id": "src_openapi_01a1278095397d018780ab3dafd4b464"
}
}
@@ -26,10 +26,17 @@ async fn http_contract_preview_apply_and_replay_preserve_json_multipart_schemas_
.unwrap()
.preview_payload["preview"]
.clone();
assert_eq!(
persisted_preview_before_apply,
serde_json::to_value(&preview.preview).unwrap()
);
// Readiness is workspace-aware response metadata, not part of the immutable
// projection persisted with the source job.
let mut response_projection = serde_json::to_value(&preview.preview).unwrap();
for group in response_projection["groups"].as_array_mut().unwrap() {
for operation in group["operations"].as_array_mut().unwrap() {
assert_eq!(operation["status"], "actionable");
operation.as_object_mut().unwrap().remove("status");
}
}
assert!(preview.preview.conflicts.is_empty());
assert_eq!(persisted_preview_before_apply, response_projection);
let operations = preview
.preview
@@ -0,0 +1,995 @@
use serde_json::{Value, json};
use serial_test::serial;
use std::{sync::Arc, time::Duration};
use async_trait::async_trait;
use crank_community_mcp::session::InMemorySessionStore;
use crank_core::{
MachineAccessMode, MachineCredentialVerifier, MachineCredentialVerifierError,
OperationSecurityLevel, PlatformApiKeyScope, VerifiedMachineCredential,
};
struct CorpusMcpCredentialVerifier;
#[async_trait]
impl MachineCredentialVerifier for CorpusMcpCredentialVerifier {
async fn verify_bearer_token(
&self,
_workspace_slug: &str,
_agent_slug: &str,
token: &str,
) -> Result<Option<VerifiedMachineCredential>, MachineCredentialVerifierError> {
Ok(
(token == "corpus-test-token").then_some(VerifiedMachineCredential {
machine_access_mode: MachineAccessMode::StaticAgentKey,
max_security_level: OperationSecurityLevel::Standard,
scopes: vec![PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
platform_api_key_id: None,
}),
)
}
}
use super::super::common::*;
#[cfg(debug_assertions)]
mod crash_recovery;
const OPENAPI_SINGLE: &str = r#"
openapi: 3.0.3
info: { title: Apply test }
servers: [{ url: https://api.example.test }]
paths:
/alpha:
get:
operationId: alpha
responses: { '200': { description: ok } }
"#;
const OPENAPI_TWO_OPERATIONS: &str = r#"
openapi: 3.0.3
info: { title: Partial Apply test }
servers: [{ url: https://api.example.test }]
paths:
/alpha:
get:
operationId: alpha
responses: { '200': { description: ok } }
/beta:
get:
operationId: beta
responses: { '200': { description: ok } }
"#;
const OPENAPI_TWO_APIKEY_OPERATIONS: &str = r#"
openapi: 3.0.3
info: { title: Authenticated Apply test, version: '1' }
servers: [{ url: https://api.example.test }]
components: { securitySchemes: { apiKey: { type: apiKey, in: header, name: X-Api-Key } } }
security: [{ apiKey: [] }]
paths:
/alpha: { get: { operationId: alpha, responses: { '200': { description: ok } } } }
/beta: { get: { operationId: beta, responses: { '200': { description: ok } } } }
"#;
const OPENAPI_SINGLE_APIKEY_OPERATION: &str = r#"
openapi: 3.0.3
info: { title: Authenticated Apply test, version: '1' }
servers: [{ url: https://api.example.test }]
components: { securitySchemes: { apiKey: { type: apiKey, in: header, name: X-Api-Key } } }
paths:
/alpha: { get: { operationId: alpha, security: [{ apiKey: [] }], responses: { '200': { description: ok } } } }
"#;
const OPENAPI_WITH_BLOCKER: &str = r#"
openapi: 3.0.3
info: { title: Blocked full Apply test }
servers: [{ url: https://api.example.test }]
paths:
/actionable:
get:
operationId: actionable
responses: { '200': { description: ok } }
/blocked:
post:
operationId: blocked
requestBody:
required: true
content:
application/xml:
schema: { type: string }
responses: { '200': { description: ok } }
"#;
#[derive(Clone)]
struct CreatedPlan {
reference: String,
digest: String,
body: Value,
preview: Value,
}
async fn create_plan(
client: &reqwest::Client,
base_url: impl AsRef<str>,
document: &str,
plan_payload: Value,
) -> CreatedPlan {
let base_url = base_url.as_ref();
let upload = reqwest::multipart::Part::bytes(document.as_bytes().to_vec())
.file_name("import.yaml")
.mime_str("application/yaml")
.unwrap();
let preview_response = client
.post(format!("{base_url}/imports/openapi/preview"))
.multipart(reqwest::multipart::Form::new().part("file", upload))
.send()
.await
.expect("OpenAPI preview request should reach the Admin API");
assert_eq!(
preview_response.status(),
reqwest::StatusCode::OK,
"preview failed: {}",
preview_response.text().await.unwrap_or_default()
);
let preview: Value = preview_response.json().await.unwrap();
let job_id = preview["job_id"]
.as_str()
.expect("preview response must include the persisted job ID");
let plan_response = client
.post(format!("{base_url}/imports/openapi/{job_id}/plans"))
.json(&plan_payload)
.send()
.await
.expect("ImportPlan request should reach the Admin API");
let status = plan_response.status();
let body: Value = plan_response.json().await.unwrap_or(Value::Null);
assert_eq!(
status,
reqwest::StatusCode::OK,
"plan creation failed: {body}"
);
let reference = body["plan_reference"]
.as_str()
.expect("CreatePlan must return its server-issued reference")
.to_owned();
let digest = body["plan_digest"]
.as_str()
.expect("CreatePlan must return its server-derived digest")
.to_owned();
assert!(reference.starts_with("plan_"));
assert_eq!(digest.len(), 64);
assert!(digest.bytes().all(|byte| byte.is_ascii_hexdigit()));
CreatedPlan {
reference,
digest,
body,
preview,
}
}
async fn apply_plan(
client: &reqwest::Client,
base_url: impl AsRef<str>,
plan: &CreatedPlan,
idempotency_key: &str,
) -> (reqwest::StatusCode, Value) {
let base_url = base_url.as_ref();
let response = client
.post(format!(
"{base_url}/imports/openapi/{}/apply",
plan.reference
))
.json(&json!({
"plan_digest": plan.digest,
"idempotency_key": idempotency_key
}))
.send()
.await
.expect("Apply request should reach the Admin API");
let status = response.status();
let body = response.json::<Value>().await.unwrap_or(Value::Null);
(status, body)
}
async fn operation_list(client: &reqwest::Client, base_url: impl AsRef<str>) -> Value {
let base_url = base_url.as_ref();
let response = client
.get(format!("{base_url}/operations"))
.send()
.await
.expect("operation list request should reach the Admin API");
assert_eq!(response.status(), reqwest::StatusCode::OK);
response.json().await.unwrap()
}
fn full_plan() -> Value {
json!({ "selection_mode": "full", "selected_operation_keys": [] })
}
fn report_has_outcome_status(report: &Value, expected: &str) -> bool {
report["outcomes"].as_array().is_some_and(|outcomes| {
outcomes
.iter()
.any(|outcome| outcome["status"] == expected || outcome["outcome"] == expected)
})
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn apply_creates_one_draft_from_a_server_created_plan() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry,
test_storage_root("import_plan_apply_new_draft"),
))
.await;
let client = authorized_client(&base_url).await;
let plan = create_plan(&client, &base_url, OPENAPI_SINGLE, full_plan()).await;
assert_eq!(plan.body["counts"]["actionable"], 1);
let (status, report) = apply_plan(&client, &base_url, &plan, "apply-new-draft").await;
assert_eq!(status, reqwest::StatusCode::OK, "Apply failed: {report}");
assert_eq!(report["plan_digest"], plan.digest);
assert_eq!(report["outcomes"].as_array().unwrap().len(), 1);
assert!(report_has_outcome_status(&report, "created"));
assert!(report["outcomes"].to_string().contains("GET /alpha"));
let operations = operation_list(&client, &base_url).await;
assert_eq!(operations["total"], 1);
assert_eq!(operations["items"][0]["status"], "draft");
assert_eq!(operations["items"][0]["current_draft_version"], 1);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn full_apply_with_a_blocked_candidate_is_atomic_and_reports_the_failure() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry,
test_storage_root("import_plan_apply_full_blocked"),
))
.await;
let client = authorized_client(&base_url).await;
let plan = create_plan(&client, &base_url, OPENAPI_WITH_BLOCKER, full_plan()).await;
assert_eq!(plan.body["counts"]["blocked"], 1);
let before = operation_list(&client, &base_url).await;
let (status, report) = apply_plan(&client, &base_url, &plan, "apply-full-blocked").await;
assert_eq!(
status,
reqwest::StatusCode::CONFLICT,
"unexpected report: {report}"
);
assert_eq!(operation_list(&client, &base_url).await, before);
assert!(
report["outcomes"].is_array(),
"blocked Apply must return outcomes: {report}"
);
assert!(report_has_outcome_status(&report, "rejected"));
assert!(report["outcomes"].to_string().contains("POST /blocked"));
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn explicit_partial_plan_applies_only_selected_candidates_and_explains_exclusions() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry,
test_storage_root("import_plan_apply_partial"),
))
.await;
let client = authorized_client(&base_url).await;
let plan = create_plan(
&client,
&base_url,
OPENAPI_TWO_OPERATIONS,
json!({
"selection_mode": "partial",
"selected_operation_keys": ["GET /alpha"]
}),
)
.await;
assert_eq!(plan.body["counts"]["selected"], 1);
assert_eq!(plan.body["counts"]["excluded"], 1);
let (status, report) = apply_plan(&client, &base_url, &plan, "apply-partial").await;
assert_eq!(status, reqwest::StatusCode::OK, "Apply failed: {report}");
assert!(report["outcomes"].is_array());
assert!(report_has_outcome_status(&report, "created"));
let report_text = report.to_string();
assert!(report_text.contains("GET /alpha"));
assert!(report_text.contains("GET /beta"));
assert!(report_text.contains("excluded"));
let operations = operation_list(&client, &base_url).await;
assert_eq!(operations["total"], 1);
assert_eq!(operations["items"][0]["name"], "alpha");
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn same_key_and_digest_replay_report_without_extra_draft_and_changed_digest_conflicts() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry,
test_storage_root("import_plan_apply_idempotency"),
))
.await;
let client = authorized_client(&base_url).await;
let plan = create_plan(&client, &base_url, OPENAPI_SINGLE, full_plan()).await;
let (first_status, first_report) =
apply_plan(&client, &base_url, &plan, "stable-apply-key").await;
assert_eq!(
first_status,
reqwest::StatusCode::OK,
"Apply failed: {first_report}"
);
let operations_after_first = operation_list(&client, &base_url).await;
let (replay_status, replay_report) =
apply_plan(&client, &base_url, &plan, "stable-apply-key").await;
assert_eq!(replay_status, reqwest::StatusCode::OK);
assert_eq!(replay_report, first_report);
assert_eq!(
operation_list(&client, &base_url).await,
operations_after_first
);
let changed = CreatedPlan {
reference: plan.reference.clone(),
digest: "0".repeat(64),
body: plan.body.clone(),
preview: plan.preview.clone(),
};
let (changed_status, _) = apply_plan(&client, &base_url, &changed, "stable-apply-key").await;
assert_eq!(changed_status, reqwest::StatusCode::CONFLICT);
assert_eq!(
operation_list(&client, &base_url).await,
operations_after_first
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn concurrent_same_key_apply_converges_on_one_persisted_report() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry,
test_storage_root("import_plan_apply_concurrent_replay"),
))
.await;
let client = authorized_client(&base_url).await;
let plan = create_plan(&client, &base_url, OPENAPI_SINGLE, full_plan()).await;
let (left, right) = tokio::join!(
apply_plan(&client, &base_url, &plan, "concurrent-apply-key"),
apply_plan(&client, &base_url, &plan, "concurrent-apply-key"),
);
assert_eq!(left.0, reqwest::StatusCode::OK, "left: {}", left.1);
assert_eq!(right.0, reqwest::StatusCode::OK, "right: {}", right.1);
assert_eq!(left.1, right.1);
assert_eq!(operation_list(&client, &base_url).await["total"], 1);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn apply_rejects_client_candidate_fields_and_malformed_digest() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry,
test_storage_root("import_plan_apply_input_validation"),
))
.await;
let client = authorized_client(&base_url).await;
let plan = create_plan(&client, &base_url, OPENAPI_SINGLE, full_plan()).await;
let url = format!("{base_url}/imports/openapi/{}/apply", plan.reference);
let extra_fields = client
.post(&url)
.json(&json!({
"plan_digest": plan.digest,
"idempotency_key": "validation-key",
"operations": [{ "operation_id": "attacker-chosen" }]
}))
.send()
.await
.unwrap();
assert_eq!(
extra_fields.status(),
reqwest::StatusCode::UNPROCESSABLE_ENTITY
);
let malformed_digest = client
.post(url)
.json(&json!({
"plan_digest": "not-a-digest",
"idempotency_key": "validation-key"
}))
.send()
.await
.unwrap();
assert_eq!(malformed_digest.status(), reqwest::StatusCode::BAD_REQUEST);
assert_eq!(operation_list(&client, &base_url).await["total"], 0);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn exact_skip_and_rename_decisions_affect_only_the_confirmed_operations() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry,
test_storage_root("import_plan_apply_skip_rename"),
))
.await;
let client = authorized_client(&base_url).await;
let initial = create_plan(&client, &base_url, OPENAPI_SINGLE, full_plan()).await;
let (initial_status, initial_report) =
apply_plan(&client, &base_url, &initial, "skip-rename-seed").await;
assert_eq!(initial_status, reqwest::StatusCode::OK, "{initial_report}");
let before_skip = operation_list(&client, &base_url).await;
let operation_id = before_skip["items"][0]["id"]
.as_str()
.expect("operation list includes the workspace operation ID");
let skip = create_plan(
&client,
&base_url,
OPENAPI_SINGLE,
json!({
"selection_mode": "full",
"selected_operation_keys": [],
"decisions": [{
"operation_key": "GET /alpha",
"action": "skip",
"target_operation_id": operation_id
}]
}),
)
.await;
let (skip_status, skip_report) =
apply_plan(&client, &base_url, &skip, "skip-exact-target").await;
assert_eq!(skip_status, reqwest::StatusCode::OK, "{skip_report}");
assert!(report_has_outcome_status(&skip_report, "skipped"));
assert_eq!(skip_report["outcomes"][0]["operation_id"], operation_id);
assert_eq!(operation_list(&client, &base_url).await, before_skip);
let rename = create_plan(
&client,
&base_url,
OPENAPI_SINGLE,
json!({
"selection_mode": "full",
"selected_operation_keys": [],
"decisions": [{
"operation_key": "GET /alpha",
"action": "rename",
"confirmed_name": "alpha_imported"
}]
}),
)
.await;
let (rename_status, rename_report) =
apply_plan(&client, &base_url, &rename, "rename-confirmed-name").await;
assert_eq!(rename_status, reqwest::StatusCode::OK, "{rename_report}");
assert!(report_has_outcome_status(&rename_report, "renamed"));
let after_rename = operation_list(&client, &base_url).await;
assert_eq!(after_rename["total"], 2);
assert!(
after_rename["items"]
.as_array()
.unwrap()
.iter()
.any(|item| { item["name"] == "alpha_imported" && item["status"] == "draft" })
);
assert!(
after_rename["items"]
.as_array()
.unwrap()
.iter()
.any(|item| { item["id"] == operation_id && item["name"] == "alpha" })
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn new_version_preserves_published_version_and_prior_version() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry,
test_storage_root("import_plan_apply_new_version_published"),
))
.await;
let client = authorized_client(&base_url).await;
let seed = create_plan(&client, &base_url, OPENAPI_SINGLE, full_plan()).await;
let (seed_status, seed_report) =
apply_plan(&client, &base_url, &seed, "new-version-seed").await;
assert_eq!(seed_status, reqwest::StatusCode::OK, "{seed_report}");
let seeded = operation_list(&client, &base_url).await;
let operation_id = seeded["items"][0]["id"].as_str().unwrap().to_owned();
let publish = client
.post(format!("{base_url}/operations/{operation_id}/publish"))
.header(
reqwest::header::IF_MATCH,
operation_etag(&client, &base_url, &operation_id).await,
)
.json(&json!({ "version": 1 }))
.send()
.await
.expect("publish request should reach the Admin API");
assert_eq!(publish.status(), reqwest::StatusCode::OK);
let published: Value = publish.json().await.unwrap();
assert_eq!(published["published_version"], 1);
let prior_version_before: Value = client
.get(format!("{base_url}/operations/{operation_id}/versions/1"))
.send()
.await
.unwrap()
.json()
.await
.unwrap();
let plan = create_plan(
&client,
&base_url,
OPENAPI_SINGLE,
json!({
"selection_mode": "full",
"selected_operation_keys": [],
"decisions": [{
"operation_key": "GET /alpha",
"action": "new_version",
"target_operation_id": operation_id
}]
}),
)
.await;
let (status, report) = apply_plan(&client, &base_url, &plan, "new-version-exact-target").await;
assert_eq!(status, reqwest::StatusCode::OK, "{report}");
assert!(report_has_outcome_status(&report, "versioned"));
assert_eq!(report["outcomes"][0]["operation_id"], operation_id);
assert_eq!(report["outcomes"][0]["version"], 2);
let after = operation_list(&client, &base_url).await;
assert_eq!(after["total"], 1);
assert_eq!(after["items"][0]["id"], operation_id);
assert_eq!(after["items"][0]["latest_published_version"], 1);
assert_eq!(after["items"][0]["current_draft_version"], 2);
let published_again: Value = client
.get(format!("{base_url}/operations/{operation_id}/versions/1"))
.send()
.await
.unwrap()
.json()
.await
.unwrap();
assert_eq!(published_again, prior_version_before);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn disabled_auth_secret_rejects_apply_without_leaking_credentials() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry.clone(),
test_storage_root("import_plan_apply_revoked_auth"),
))
.await;
let client = authorized_client(&base_url).await;
let secret_canary = "import-plan-auth-canary-must-not-leak";
let secret_response = client
.post(format!("{base_url}/secrets"))
.json(&json!({
"name": "import-plan-auth-token",
"kind": "token",
"value": { "token": secret_canary }
}))
.send()
.await
.unwrap();
assert_eq!(secret_response.status(), reqwest::StatusCode::OK);
let secret: Value = secret_response.json().await.unwrap();
let secret_id = secret["id"].as_str().unwrap();
let profile_response = client
.post(format!("{base_url}/auth-profiles"))
.json(&json!({
"name": "import-plan-auth-profile",
"kind": "api_key_header",
"config": {
"api_key_header": {
"header_name": "X-Api-Key",
"secret_id": secret_id
}
}
}))
.send()
.await
.unwrap();
assert_eq!(profile_response.status(), reqwest::StatusCode::OK);
let profile: Value = profile_response.json().await.unwrap();
let auth_profile_id = profile["id"].as_str().unwrap();
let redacted_plan = create_plan(
&client,
&base_url,
OPENAPI_TWO_APIKEY_OPERATIONS,
json!({
"selection_mode": "partial",
"selected_operation_keys": ["GET /beta"],
"decisions": [{
"operation_key": "GET /beta",
"action": "create",
"auth_profile_id": auth_profile_id
}]
}),
)
.await;
let (redacted_status, redacted_report) =
apply_plan(&client, &base_url, &redacted_plan, "redacted-auth-report").await;
assert_eq!(
redacted_status,
reqwest::StatusCode::OK,
"{redacted_report}"
);
assert!(redacted_report["source_digest"].is_string());
assert!(!redacted_report.to_string().contains(secret_canary));
assert!(!redacted_report.to_string().contains("ciphertext"));
let plan = create_plan(
&client,
&base_url,
OPENAPI_SINGLE_APIKEY_OPERATION,
json!({
"selection_mode": "full",
"selected_operation_keys": [],
"decisions": [{
"operation_key": "GET /alpha",
"action": "create",
"auth_profile_id": auth_profile_id
}]
}),
)
.await;
// A profile can remain active while its credential mapping changes.
// The confirmed plan must not silently adopt the new configuration.
sqlx::query(
"update auth_profiles
set config_json = jsonb_set(config_json, '{api_key_header,header_name}', '\"X-Changed-Key\"'),
updated_at = now()
where workspace_id = $1 and id = $2",
)
.bind("ws_default")
.bind(auth_profile_id)
.execute(registry.pool())
.await
.unwrap();
let (drift_status, drift_error) =
apply_plan(&client, &base_url, &plan, "changed-auth-config-apply").await;
assert_eq!(drift_status, reqwest::StatusCode::CONFLICT, "{drift_error}");
assert_eq!(
drift_error["error"]["context"]["error_code"],
"import_plan_auth_unavailable"
);
assert_eq!(operation_list(&client, &base_url).await["total"], 1);
let plan = create_plan(
&client,
&base_url,
&OPENAPI_SINGLE_APIKEY_OPERATION.replace("X-Api-Key", "X-Changed-Key"),
json!({
"selection_mode": "full",
"selected_operation_keys": [],
"decisions": [{
"operation_key": "GET /alpha",
"action": "create",
"auth_profile_id": auth_profile_id
}]
}),
)
.await;
// There is no profile revoke endpoint; disabling its backing credential
// models revocation between confirmation and apply.
sqlx::query(
"update secrets set status = 'disabled', updated_at = now() where workspace_id = $1 and id = $2",
)
.bind("ws_default")
.bind(secret_id)
.execute(registry.pool())
.await
.unwrap();
let (status, error) = apply_plan(&client, &base_url, &plan, "revoked-auth-apply").await;
assert_eq!(status, reqwest::StatusCode::CONFLICT, "{error}");
assert_eq!(
error["error"]["context"]["error_code"],
"import_plan_auth_unavailable"
);
let response_text = error.to_string();
assert!(!response_text.contains(secret_canary));
assert!(!response_text.contains("ciphertext"));
let after = operation_list(&client, &base_url).await;
assert_eq!(after["total"], 1);
assert_eq!(after["items"][0]["name"], "beta");
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn profiles_sharing_active_secret_are_selectable_and_both_block_after_disable() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry.clone(),
test_storage_root("import_plan_shared_auth_secret"),
))
.await;
let client = authorized_client(&base_url).await;
let secret_response = client
.post(format!("{base_url}/secrets"))
.json(&json!({
"name": "shared-import-auth-token",
"kind": "token",
"value": { "token": "shared-import-canary" }
}))
.send()
.await
.unwrap();
assert_eq!(secret_response.status(), reqwest::StatusCode::OK);
let secret: Value = secret_response.json().await.unwrap();
let secret_id = secret["id"].as_str().unwrap();
let make_profile = |name: &str| {
client
.post(format!("{base_url}/auth-profiles"))
.json(&json!({
"name": name,
"kind": "api_key_header",
"config": { "api_key_header": {
"header_name": "X-Api-Key",
"secret_id": secret_id
}}
}))
};
let first: Value = make_profile("shared-auth-a")
.send()
.await
.unwrap()
.json()
.await
.unwrap();
let second: Value = make_profile("shared-auth-b")
.send()
.await
.unwrap()
.json()
.await
.unwrap();
let document = r#"{
"openapi":"3.0.3",
"info":{"title":"Shared profile test","version":"1"},
"servers":[{"url":"https://api.example.test"}],
"components":{"securitySchemes":{"key":{"type":"apiKey","in":"header","name":"X-Api-Key"}}},
"paths":{
"/a":{"get":{"operationId":"sharedA","security":[{"key":[]}],"responses":{"200":{"description":"ok"}}}},
"/b":{"get":{"operationId":"sharedB","security":[{"key":[]}],"responses":{"200":{"description":"ok"}}}}
}
}"#;
let plan = create_plan(
&client,
&base_url,
document,
json!({
"selection_mode":"full",
"selected_operation_keys":[],
"decisions":[
{"operation_key":"GET /a","action":"create","auth_profile_id":first["id"]},
{"operation_key":"GET /b","action":"create","auth_profile_id":second["id"]}
]
}),
)
.await;
let (status, report) = apply_plan(&client, &base_url, &plan, "shared-secret-active").await;
assert_eq!(status, reqwest::StatusCode::OK, "{report}");
assert_eq!(operation_list(&client, &base_url).await["total"], 2);
let first_id = first["id"].as_str().unwrap();
let second_id = second["id"].as_str().unwrap();
let disabled_document = document
.replace("sharedA", "sharedAAfterDisable")
.replace("sharedB", "sharedBAfterDisable");
let mut disabled_plans = Vec::new();
for (key, profile_id) in [("GET /a", first_id), ("GET /b", second_id)] {
disabled_plans.push((
key,
create_plan(
&client,
&base_url,
&disabled_document,
json!({
"selection_mode":"partial",
"selected_operation_keys":[key],
"decisions":[{"operation_key":key,"action":"create","auth_profile_id":profile_id}]
}),
)
.await,
));
}
sqlx::query("update secrets set status = 'disabled', updated_at = now() where workspace_id = $1 and id = $2")
.bind("ws_default")
.bind(secret_id)
.execute(registry.pool())
.await
.unwrap();
for (key, plan) in disabled_plans {
let (status, error) = apply_plan(
&client,
&base_url,
&plan,
&format!("shared-secret-disabled-{key}"),
)
.await;
assert_eq!(status, reqwest::StatusCode::CONFLICT, "{error}");
assert_eq!(
error["error"]["context"]["error_code"],
"import_plan_auth_unavailable"
);
assert_eq!(operation_list(&client, &base_url).await["total"], 2);
}
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn ac_4_corpus_operation_completes_the_real_http_to_mcp_workflow() {
use axum::{Json, Router};
let registry = test_registry().await;
let (request_tx, mut request_rx) = tokio::sync::mpsc::unbounded_channel();
let upstream =
Router::new().fallback(move |method: axum::http::Method, uri: axum::http::Uri| {
let request_tx = request_tx.clone();
async move {
request_tx.send((method, uri)).unwrap();
Json(json!({"id":"corpus-0"}))
}
});
let upstream_base = spawn_admin_api(upstream).await;
let storage = test_storage_root("corpus_ac4");
let base_url = spawn_admin_api(build_test_app(registry.clone(), storage)).await;
let client = authorized_client(&base_url).await;
let fixture_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../crates/crank-import/tests/corpus/representative-00.json");
let mut fixture: Value = serde_json::from_slice(&std::fs::read(fixture_path).unwrap()).unwrap();
let upstream_origin = upstream_base
.as_ref()
.split("/api/admin/workspaces/")
.next()
.unwrap();
fixture["servers"] = json!([{ "url": upstream_origin }]);
let document = serde_json::to_string(&fixture).unwrap();
let plan = create_plan(&client, &base_url, &document, full_plan()).await;
assert_eq!(plan.body["counts"]["actionable"], 1);
let (status, report) = apply_plan(&client, &base_url, &plan, "corpus-ac4-import").await;
assert_eq!(status, reqwest::StatusCode::OK, "Apply failed: {report}");
assert!(report_has_outcome_status(&report, "created"));
let operations = operation_list(&client, &base_url).await;
assert_eq!(operations["total"], 1);
assert_eq!(operations["items"][0]["status"], "draft");
let operation_id = operations["items"][0]["id"].as_str().unwrap().to_owned();
// The admin test run performs the persisted Draft validation and a real
// HTTP execution against the local fixture server before publication.
let test_run = client
.post(format!("{base_url}/operations/{operation_id}/test-runs"))
.json(&json!({"version":1,"input":{}}))
.send()
.await
.unwrap();
assert_eq!(test_run.status(), reqwest::StatusCode::OK);
let test_result: Value = test_run.json().await.unwrap();
assert_eq!(test_result["ok"], true, "Draft test failed: {test_result}");
let published = client
.post(format!("{base_url}/operations/{operation_id}/publish"))
.header(
reqwest::header::IF_MATCH,
operation_etag(&client, &base_url, &operation_id).await,
)
.json(&json!({"version":1}))
.send()
.await
.unwrap();
assert_eq!(published.status(), reqwest::StatusCode::OK);
let agent = client.post(format!("{base_url}/agents")).json(&json!({
"slug":"corpus-regression-agent","display_name":"Corpus Regression Agent",
"description":"Local corpus acceptance fixture","instructions":{},"tool_selection_policy":{}
})).send().await.unwrap().json::<Value>().await.unwrap();
let agent_id = agent["agent_id"].as_str().unwrap();
let bindings = client.post(format!("{base_url}/agents/{agent_id}/bindings"))
.header(reqwest::header::IF_MATCH, agent_etag(&client, &base_url, agent_id).await)
.json(&json!([{"operation_id":operation_id,"operation_version":1,"tool_name":"corpusOperation00","tool_title":"Synthetic operation 00","enabled":true}]))
.send().await.unwrap();
assert_eq!(bindings.status(), reqwest::StatusCode::OK);
let agent_publish = client
.post(format!("{base_url}/agents/{agent_id}/publish"))
.header(
reqwest::header::IF_MATCH,
agent_etag(&client, &base_url, agent_id).await,
)
.json(&json!({"version":1}))
.send()
.await
.unwrap();
assert_eq!(agent_publish.status(), reqwest::StatusCode::OK);
let mcp = crank_community_mcp::build_app(
registry,
Duration::ZERO,
None,
test_secret_crypto(),
crank_runtime::community_with_outbound_policy(
crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]),
)
.build(),
crank_runtime::RequestRateLimiter::new(
crank_runtime::RequestRateLimitConfig::new(100, 100).unwrap(),
),
Arc::new(crank_runtime::InMemoryCoordinationStateStore::default()),
Arc::new(InMemorySessionStore::default()),
Arc::new(CorpusMcpCredentialVerifier),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, mcp).await.unwrap();
});
let mcp_base = format!("http://{address}");
let mcp_url = format!("{mcp_base}/v1/default/corpus-regression-agent");
let initialized = client.post(&mcp_url).bearer_auth("corpus-test-token")
.header("accept", "application/json, text/event-stream")
.json(&json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"corpus","version":"1"}}}))
.send().await.unwrap();
assert_eq!(initialized.status(), reqwest::StatusCode::OK);
let session = initialized
.headers()
.get("mcp-session-id")
.unwrap()
.to_str()
.unwrap()
.to_owned();
let notification = client
.post(&mcp_url)
.bearer_auth("corpus-test-token")
.header("accept", "application/json, text/event-stream")
.header("mcp-session-id", &session)
.header("mcp-protocol-version", "2025-11-25")
.json(&json!({"jsonrpc":"2.0","method":"notifications/initialized","params":{}}))
.send()
.await
.unwrap();
assert_eq!(notification.status(), reqwest::StatusCode::ACCEPTED);
let called = client.post(&mcp_url).bearer_auth("corpus-test-token")
.header("accept", "application/json, text/event-stream").header("mcp-session-id", session)
.header("mcp-protocol-version", "2025-11-25")
.json(&json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"corpusOperation00","arguments":{}}}))
.send().await.unwrap();
assert_eq!(called.status(), reqwest::StatusCode::OK);
let call: Value = called.json().await.unwrap();
assert_eq!(call["result"]["isError"], false, "MCP call failed: {call}");
assert_eq!(call["result"]["structuredContent"]["id"], "corpus-0");
for stage in ["Draft test run", "MCP call"] {
let (method, uri) = request_rx
.try_recv()
.unwrap_or_else(|_| panic!("{stage} missed upstream"));
assert_eq!(method, axum::http::Method::GET, "{stage}");
assert_eq!(uri.path(), "/items/0", "{stage}");
}
}
mod corpus_hostile;
mod locale;
mod security_source;
mod support_matrix;
@@ -0,0 +1,292 @@
use super::*;
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn ac_5_hostile_corpus_cases_are_bounded_atomic_and_redacted() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(registry, test_storage_root("corpus_ac5"))).await;
let client = authorized_client(&base_url).await;
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../crates/crank-import/tests/corpus");
let hostile_xml = std::fs::read_to_string(root.join("hostile-xml.json")).unwrap();
let before = operation_list(&client, &base_url).await;
let started = std::time::Instant::now();
let plan = create_plan(&client, &base_url, &hostile_xml, full_plan()).await;
assert!(
started.elapsed() < Duration::from_secs(5),
"hostile document exceeded bounded test budget"
);
assert!(
plan.body["counts"]["blocked"].as_u64().unwrap_or(0) > 0,
"hostile XML must be a blocker: {}",
plan.body
);
let xml_candidate = &plan.preview["preview"]["groups"][0]["operations"][0];
assert_eq!(xml_candidate["key"], "GET /xml");
assert!(
xml_candidate["findings"]
.as_array()
.is_some_and(|findings| findings.iter().any(|finding| finding["code"]
== "unsupported_xml_response_media_type"
&& finding["severity"] == "error")),
"HTTP preview must expose the exact XML blocker: {}",
plan.preview
);
assert_eq!(
plan.body["candidates"][0]["reason"], "unsupported_xml_response_media_type",
"HTTP plan must retain the XML blocker: {}",
plan.body
);
let (status, report) = apply_plan(&client, &base_url, &plan, "corpus-ac5-hostile").await;
assert_eq!(
status,
reqwest::StatusCode::CONFLICT,
"blocker must reject atomically: {report}"
);
assert_eq!(operation_list(&client, &base_url).await, before);
// Credential-bearing sources are rejected before their original bytes
// can enter artifact storage, rather than producing a persisted plan.
for file in [
"hostile-secret.json",
"hostile-malformed.json",
"hostile-oversized.json",
] {
let source = std::fs::read(root.join(file)).unwrap();
let started = std::time::Instant::now();
let upload = reqwest::multipart::Part::bytes(source)
.file_name(file)
.mime_str("application/json")
.unwrap();
let response = client
.post(format!("{base_url}/imports/openapi/preview"))
.multipart(reqwest::multipart::Form::new().part("file", upload))
.send()
.await
.unwrap();
let status = response.status();
let body = response.text().await.unwrap_or_default();
assert!(
!status.is_success(),
"{file} unexpectedly passed preview: {body}"
);
assert!(
started.elapsed() < Duration::from_secs(5),
"{file} exceeded bounded upload/parse time"
);
assert!(
!body.contains("sk_test_corpus_secret_canary"),
"hostile error response leaked a secret canary"
);
assert_eq!(
operation_list(&client, &base_url).await,
before,
"{file} mutated the operation registry"
);
}
// Real HTTP preview+plan: a root security requirement combined with an
// explicit empty operation override must leave the public operation
// actionable and leave the inherited one unresolved without a profile.
let mixed_security: Value = serde_json::json!({
"openapi": "3.0.3",
"info": { "title": "Mixed security plan probe", "version": "1" },
"servers": [{ "url": "https://security.example.test" }],
"components": { "securitySchemes": { "probe": { "type": "http", "scheme": "basic" } } },
"security": [{ "probe": [] }],
"paths": {
"/public": { "get": { "security": [], "operationId": "securityPublic",
"responses": { "200": { "description": "ok" } } } },
"/secured": { "get": { "operationId": "securitySecured",
"responses": { "200": { "description": "ok" } } } }
}
});
let security_mixed = serde_json::to_string(&mixed_security).unwrap();
let security_plan = create_plan(&client, &base_url, &security_mixed, full_plan()).await;
assert_eq!(
security_plan.body["counts"]["selected"], 2,
"{}",
security_plan.body
);
assert_eq!(
security_plan.body["counts"]["actionable"], 1,
"{}",
security_plan.body
);
assert_eq!(
security_plan.body["counts"]["blocked"], 1,
"{}",
security_plan.body
);
let security_candidates = security_plan.body["candidates"].as_array().unwrap();
let by_key = |key: &str| {
security_candidates
.iter()
.find(|candidate| candidate["key"] == key)
.unwrap_or_else(|| panic!("candidate {key} missing: {}", security_plan.body))
};
let public = by_key("GET /public");
let secured = by_key("GET /secured");
assert_eq!(
public["state"].as_str(),
Some("actionable"),
"public candidate with empty security override must stay actionable: {}",
security_plan.body
);
assert!(
public["reason"].is_null(),
"public candidate must not carry a security blocker: {}",
security_plan.body
);
assert_eq!(
secured["state"].as_str(),
Some("blocked"),
"inherited security requirement must block the affected candidate: {}",
security_plan.body
);
assert_eq!(
secured["reason"].as_str(),
Some("auth_profile_required"),
"secured candidate must expose its unresolved binding: {}",
security_plan.body
);
assert_eq!(
operation_list(&client, &base_url).await,
before,
"security-scoped plan must not mutate the operation registry"
);
let (blocked_status, blocked_report) = apply_plan(
&client,
&base_url,
&security_plan,
"corpus-ac5-security-blocked",
)
.await;
assert_eq!(
blocked_status,
reqwest::StatusCode::CONFLICT,
"{blocked_report}"
);
assert_eq!(operation_list(&client, &base_url).await, before);
let public_plan = create_plan(
&client,
&base_url,
&security_mixed,
json!({
"selection_mode": "partial",
"selected_operation_keys": ["GET /public"]
}),
)
.await;
assert_eq!(public_plan.body["counts"]["actionable"], 1);
assert_eq!(public_plan.body["counts"]["blocked"], 0);
let (public_status, public_report) = apply_plan(
&client,
&base_url,
&public_plan,
"corpus-ac5-security-public",
)
.await;
assert_eq!(public_status, reqwest::StatusCode::OK, "{public_report}");
assert!(report_has_outcome_status(&public_report, "created"));
let after = operation_list(&client, &base_url).await;
assert_eq!(after["total"], 1, "{after}");
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn p0_api_malformed_local_security_is_atomic_across_openapi_versions() {
for (version, document) in [
(
"openapi-3.1",
serde_json::json!({
"openapi": "3.1.0",
"info": { "title": "Security API regression", "version": "1" },
"servers": [{ "url": "https://security.example.test" }],
"security": [{ "probe": [] }],
"paths": {
"/bad": { "get": { "security": "basic", "operationId": "badOp",
"responses": { "200": { "description": "ok" } } } },
"/public": { "get": { "security": [], "operationId": "publicOp",
"responses": { "200": { "description": "ok" } } } }
}
}),
),
(
"swagger-2.0",
serde_json::json!({
"swagger": "2.0",
"info": { "title": "Security API regression", "version": "1" },
"host": "security.example.test",
"schemes": ["https"],
"security": [{ "apiKey": [] }],
"paths": {
"/bad": { "get": { "security": "apikey", "operationId": "badOp",
"responses": { "200": { "description": "ok" } } } },
"/public": { "get": { "security": [], "operationId": "publicOp",
"responses": { "200": { "description": "ok" } } } }
}
}),
),
] {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry,
test_storage_root(&format!("security_api_{version}")),
))
.await;
let client = authorized_client(&base_url).await;
let source = serde_json::to_string(&document).unwrap();
let before = operation_list(&client, &base_url).await;
let plan = create_plan(&client, &base_url, &source, full_plan()).await;
assert_eq!(
plan.body["counts"]["actionable"], 1,
"{version}: {}",
plan.body
);
assert_eq!(
plan.body["counts"]["blocked"], 1,
"{version}: {}",
plan.body
);
let candidates = plan.body["candidates"].as_array().unwrap();
let bad = candidates
.iter()
.find(|item| item["key"] == "GET /bad")
.unwrap();
let public = candidates
.iter()
.find(|item| item["key"] == "GET /public")
.unwrap();
assert_eq!(bad["state"], "blocked", "{version}: {}", plan.body);
assert_eq!(bad["reason"], "invalid_security_requirements");
assert_eq!(public["state"], "actionable", "{version}: {}", plan.body);
assert!(public["reason"].is_null());
let (status, report) = apply_plan(&client, &base_url, &plan, "security-full").await;
assert_eq!(status, reqwest::StatusCode::CONFLICT, "{version}: {report}");
assert_eq!(operation_list(&client, &base_url).await, before);
let public_plan = create_plan(
&client,
&base_url,
&source,
json!({
"selection_mode": "partial",
"selected_operation_keys": ["GET /public"]
}),
)
.await;
assert_eq!(public_plan.body["counts"]["actionable"], 1);
assert_eq!(public_plan.body["counts"]["blocked"], 0);
let (status, report) =
apply_plan(&client, &base_url, &public_plan, "security-public").await;
assert_eq!(status, reqwest::StatusCode::OK, "{version}: {report}");
assert!(report_has_outcome_status(&report, "created"));
let after = operation_list(&client, &base_url).await;
assert_eq!(after["total"], 1, "{version}: {after}");
assert_eq!(after["items"][0]["status"], "draft");
}
}
@@ -0,0 +1,330 @@
//! Kill the actual HTTP-serving process at durable Apply boundaries, then
//! restart the same production router against the parent's database/storage.
use super::*;
use crank_artifacts::test_support::{FaultAction, set_checkpoint};
use std::{
path::PathBuf,
process::{Child, Command, Stdio},
time::Instant,
};
const CHILD_TEST: &str =
"integration::openapi_import::import_plan_apply::crash_recovery::http_apply_crash_child";
const CHILD_CONFIG: &str = "CRANK_TEST_APPLY_CRASH_CONFIG";
struct PrivateConfigGuard(PathBuf);
impl Drop for PrivateConfigGuard {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
struct ChildGuard(Child);
impl Drop for ChildGuard {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
// Child configuration contains only isolated test fixture credentials. Keep it
// in a private file and never include it in assertions, stdout or task logs.
#[tokio::test(flavor = "multi_thread")]
async fn http_apply_crash_child() {
let Ok(path) = std::env::var(CHILD_CONFIG) else {
return;
};
let config: Value = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap();
let registry = crank_registry::PostgresRegistry::connect(config["database"].as_str().unwrap())
.await
.unwrap();
let root = PathBuf::from(config["storage"].as_str().unwrap());
let server = spawn_admin_api(build_test_app(registry, root)).await;
set_checkpoint(config["stage"].as_str().unwrap(), FaultAction::Exit);
std::fs::write(config["ready"].as_str().unwrap(), server.as_ref()).unwrap();
std::future::pending::<()>().await;
}
async fn counts(registry: &crank_registry::PostgresRegistry) -> (i64, i64, i64) {
sqlx::query_as(
"select (select count(*) from operations),
(select count(*) from operation_versions),
(select count(*) from import_plan_applications)",
)
.fetch_one(registry.pool())
.await
.unwrap()
}
async fn crash_then_restart(stage: &str, committed: bool) {
use std::os::unix::fs::PermissionsExt;
let (registry, database_url) = test_registry_with_single_connection().await;
let root = test_storage_root(stage);
std::fs::create_dir_all(&root).unwrap();
std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap();
let server = spawn_admin_api(build_test_app(registry.clone(), root.clone())).await;
let client = authorized_client(&server).await;
let plan = create_plan(&client, &server, OPENAPI_SINGLE, full_plan()).await;
let store = crank_artifacts::ArtifactStore::open(&root).unwrap();
let artifact = store.put_registered(OPENAPI_SINGLE.as_bytes()).unwrap();
let key = format!("crash-{stage}");
assert_eq!(counts(&registry).await, (0, 0, 0));
drop(server);
let ready = root.join("child.ready");
let config_path = root.join("child-config.json");
let _private_config = PrivateConfigGuard(config_path.clone());
{
use std::io::Write;
use std::os::unix::fs::OpenOptionsExt;
let mut file = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(&config_path)
.unwrap();
let config = json!({"database":database_url,"storage":root,"stage":stage,"ready":ready});
file.write_all(&serde_json::to_vec(&config).unwrap())
.unwrap();
}
let mut child = ChildGuard(
Command::new(std::env::current_exe().unwrap())
.args(["--exact", CHILD_TEST, "--nocapture"])
.env(CHILD_CONFIG, &config_path)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
.unwrap(),
);
let start = Instant::now();
let child_url = loop {
if let Ok(url) = std::fs::read_to_string(&ready) {
break url;
}
assert!(
child.0.try_wait().unwrap().is_none(),
"child exited before HTTP readiness"
);
assert!(
start.elapsed() < Duration::from_secs(30),
"child HTTP readiness deadline"
);
tokio::time::sleep(Duration::from_millis(10)).await;
};
let response = client
.post(format!(
"{child_url}/imports/openapi/{}/apply",
plan.reference
))
.json(&json!({"plan_digest":plan.digest,"idempotency_key":key}))
.timeout(Duration::from_secs(30))
.send()
.await;
assert!(response.is_err(), "crash must prevent an HTTP response");
let status = loop {
if let Some(status) = child.0.try_wait().unwrap() {
break status;
}
assert!(
start.elapsed() < Duration::from_secs(35),
"child crash deadline"
);
tokio::time::sleep(Duration::from_millis(10)).await;
};
assert_eq!(
status.code(),
Some(86),
"must hit the exact armed commit boundary"
);
std::fs::remove_file(config_path).unwrap();
std::fs::remove_file(ready).unwrap();
let expected = if committed { (1, 1, 1) } else { (0, 0, 0) };
// An independent connection can observe only fully committed state.
assert_eq!(counts(&registry).await, expected);
let before: Option<Value> = sqlx::query_scalar(
"select report from import_plan_applications where workspace_id='ws_default' and idempotency_key=$1",
).bind(&key).fetch_optional(registry.pool()).await.unwrap();
assert_eq!(before.is_some(), committed);
// The source of this nonexpired job remains referenced after process loss;
// cleanup cannot make its plan snapshot eligible for orphan deletion.
assert_eq!(sqlx::query_scalar::<_, i64>(
"select count(*) from artifact_sources where workspace_id='ws_default' and lifecycle='active'",
).fetch_one(registry.pool()).await.unwrap(), 1);
let cleanup = registry.cleanup_expired_import_jobs(32).await;
assert!(cleanup.is_ok());
let now = time::OffsetDateTime::now_utc();
let claim = registry
.claim_artifact_reconciliation(crank_registry::ClaimArtifactReconciliationRequest {
artifact: &artifact,
token: crank_registry::ArtifactClaimToken::generate(),
claimed_at: now,
lease_expires_at: now + time::Duration::minutes(5),
detached_grace: time::Duration::hours(24),
})
.await
.unwrap();
assert!(matches!(
claim,
crank_registry::ArtifactClaimOutcome::ActiveReference
));
assert_eq!(
store.read(artifact.artifact_ref()).unwrap(),
OPENAPI_SINGLE.as_bytes()
);
assert_eq!(sqlx::query_scalar::<_, i64>(
"select count(*) from artifact_sources where workspace_id='ws_default' and lifecycle='active'",
).fetch_one(registry.pool()).await.unwrap(), 1);
let restarted = spawn_admin_api(build_test_app(registry.clone(), root)).await;
let (status, report) = apply_plan(&client, &restarted, &plan, &key).await;
assert_eq!(status, reqwest::StatusCode::OK);
if let Some(before) = before {
assert_eq!(
report, before,
"restart must return the committed immutable report"
);
}
assert_eq!(report["plan_digest"], plan.digest);
assert_eq!(report["counts"]["created"], 1);
let (status, replay) = apply_plan(&client, &restarted, &plan, &key).await;
assert_eq!(status, reqwest::StatusCode::OK);
assert_eq!(
replay, report,
"exact retry must be byte-equivalent structured report"
);
assert_eq!(counts(&registry).await, (1, 1, 1));
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn http_process_crash_before_commit_rolls_back_and_retries_after_restart() {
crash_then_restart("apply_before_commit", false).await;
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn http_process_crash_after_commit_before_response_replays_after_restart() {
crash_then_restart("apply_after_commit", true).await;
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn concurrent_distinct_overlapping_http_plans_have_one_coherent_commit() {
let (seed_registry, database_url) = test_registry_with_single_connection().await;
// The ordinary test registry has only one connection and would serialize
// both requests before their transactions even start.
let registry = crank_registry::PostgresRegistry::connect_with_options_and_pool_config(
database_url
.parse::<sqlx::postgres::PgConnectOptions>()
.unwrap(),
crank_registry::PostgresPoolConfig::try_new(4, 0, 5_000, 60_000, 1_800_000).unwrap(),
)
.await
.unwrap();
drop(seed_registry);
let server = spawn_admin_api(build_test_app(
registry.clone(),
test_storage_root("distinct-overlap-plans"),
))
.await;
let client = authorized_client(&server).await;
let a = create_plan(&client, &server, OPENAPI_SINGLE, full_plan()).await;
let b = create_plan(&client, &server, OPENAPI_TWO_OPERATIONS, full_plan()).await;
assert_ne!(a.reference, b.reference);
assert_ne!(a.digest, b.digest);
let a_key = "overlap-distinct-a";
let b_key = "overlap-distinct-b";
// Hold the production workspace row lock until BOTH independent Apply
// transactions are blocked on it. Merely joining requests could otherwise
// exercise two sequential transactions.
let mut gate = registry.pool().begin().await.unwrap();
let gate_pid: i32 = sqlx::query_scalar("select pg_backend_pid()")
.fetch_one(&mut *gate)
.await
.unwrap();
sqlx::query("select id from workspaces where id = 'ws_default' for update")
.fetch_one(&mut *gate)
.await
.unwrap();
let a_task = tokio::spawn({
let (client, server, a) = (client.clone(), server.to_string(), a.clone());
async move { apply_plan(&client, &server, &a, a_key).await }
});
let b_task = tokio::spawn({
let (client, server, b) = (client.clone(), server.to_string(), b.clone());
async move { apply_plan(&client, &server, &b, b_key).await }
});
let mut observed_waiting = 0;
let barrier_result = tokio::time::timeout(Duration::from_secs(15), async {
loop {
let waiting: i64 = sqlx::query_scalar(
"with recursive blocked(pid) as (
select pid from pg_catalog.pg_stat_activity
where $1 = any(pg_catalog.pg_blocking_pids(pid))
union
select activity.pid from pg_catalog.pg_stat_activity activity
join blocked on blocked.pid = any(pg_catalog.pg_blocking_pids(activity.pid))
)
select count(distinct pid) from blocked",
)
.bind(gate_pid)
.fetch_one(registry.pool())
.await
.unwrap();
observed_waiting = waiting;
if waiting == 2 {
break;
}
assert!(!a_task.is_finished() && !b_task.is_finished());
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await;
assert!(
barrier_result.is_ok(),
"both distinct Apply transactions must reach the workspace lock; observed {observed_waiting}"
);
gate.commit().await.unwrap();
let ((a_status, a_report), (b_status, b_report)) =
(a_task.await.unwrap(), b_task.await.unwrap());
assert!(
a_status.is_success() ^ b_status.is_success(),
"exactly one overlapping plan commits: {a_status}/{b_status}"
);
let (winner, loser_status, loser) = if a_status.is_success() {
(&a_report, b_status, &b_report)
} else {
(&b_report, a_status, &a_report)
};
assert_eq!(loser_status, reqwest::StatusCode::CONFLICT);
let error_code = loser
.pointer("/error/context/error_code")
.and_then(Value::as_str)
.unwrap();
assert!(
matches!(
error_code,
"import_plan_fingerprint_stale" | "import_plan_name_conflict"
),
"loser must get the exact typed catalog/name conflict, got {error_code}"
);
let expected = winner["counts"]["created"].as_i64().unwrap();
assert!(expected == 1 || expected == 2);
assert_eq!(
counts(&registry).await,
(expected, expected, 1),
"loser cannot leave partial Operations/versions/application"
);
let (winning_plan, winning_key) = if a_status.is_success() {
(&a, a_key)
} else {
(&b, b_key)
};
let (status, replay) = apply_plan(&client, &server, winning_plan, winning_key).await;
assert_eq!(status, reqwest::StatusCode::OK);
assert_eq!(&replay, winner);
assert_eq!(counts(&registry).await, (expected, expected, 1));
}
@@ -0,0 +1,198 @@
use super::*;
use crank_core::WorkspaceId;
use crank_registry::{CreateImportPlanRequest, ImportPlanId};
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn plan_apply_localizes_repreview_guidance_by_accept_language() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry,
test_storage_root("import_plan_apply_locale"),
))
.await;
let client = authorized_client(&base_url).await;
let plan = create_plan(&client, &base_url, OPENAPI_SINGLE, full_plan()).await;
let url = format!(
"{}/imports/openapi/{}/apply",
base_url.as_ref(),
plan.reference
);
let wrong_digest = "0".repeat(64);
// Russian session: Russian recovery guidance, identical machine code and
// recovery flags.
let ru = client
.post(&url)
.header("accept-language", "ru")
.json(&json!({ "plan_digest": wrong_digest, "idempotency_key": "locale-ru" }))
.send()
.await
.unwrap();
assert_eq!(ru.status(), reqwest::StatusCode::CONFLICT);
let ru_body: Value = ru.json().await.unwrap();
assert_eq!(
ru_body["error"]["context"]["error_code"],
"import_plan_digest_mismatch"
);
assert_eq!(
ru_body["error"]["context"]["repreview_required"],
json!(true)
);
assert_eq!(
ru_body["error"]["context"]["recovery"],
"repreview_required"
);
assert!(
ru_body["error"]["message"]
.as_str()
.unwrap_or_default()
.contains("создайте новый preview"),
"Russian session must receive Russian guidance: {ru_body:?}"
);
// No locale header keeps the English default behavior.
let en = client
.post(&url)
.json(&json!({ "plan_digest": wrong_digest, "idempotency_key": "locale-en" }))
.send()
.await
.unwrap();
assert_eq!(en.status(), reqwest::StatusCode::CONFLICT);
let en_body: Value = en.json().await.unwrap();
assert_eq!(
en_body["error"]["context"]["error_code"],
"import_plan_digest_mismatch"
);
assert!(
en_body["error"]["message"]
.as_str()
.unwrap_or_default()
.contains("create a fresh preview"),
"EN default must remain English: {en_body:?}"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn plan_apply_localizes_registry_name_conflict_by_accept_language() {
let registry = test_registry().await;
let storage_root = test_storage_root("import_plan_apply_locale_name_conflict");
let service = test_service(
registry.clone(),
storage_root.clone(),
test_auth_settings(),
test_secret_crypto(),
);
let base_url = spawn_admin_api(build_test_app(registry.clone(), storage_root)).await;
let client = authorized_client(&base_url).await;
let workspace_id = WorkspaceId::new("ws_default");
let created = create_plan(&client, &base_url, OPENAPI_SINGLE, full_plan()).await;
// Keep a historical v1-shaped plan to exercise the registry's typed
// name-conflict mapping directly. A v2 plan would stop earlier at the
// catalog-revision guard after the concurrent name claim below.
let original_id: ImportPlanId = created.reference.as_str().into();
let original = registry
.get_import_plan(&workspace_id, &original_id)
.await
.unwrap()
.expect("HTTP-created plan is persisted");
let legacy_id: ImportPlanId = "plan_locale_apply_name_conflict_v1".into();
let mut legacy_payload = original.payload.clone();
legacy_payload["schema_version"] = json!("import-plan-v1");
legacy_payload["plan_reference"] = json!(legacy_id.as_str());
let legacy_fields = legacy_payload.as_object_mut().unwrap();
for field in [
"catalog_revision",
"excluded_reasons",
"findings",
"support_matrix_version",
] {
legacy_fields.remove(field);
}
let legacy = registry
.create_import_plan(CreateImportPlanRequest {
id: &legacy_id,
workspace_id: &workspace_id,
job_id: &original.job_id,
payload: &legacy_payload,
created_at: &original.created_at,
expires_at: &original.expires_at,
})
.await
.unwrap();
let candidate_name = created.body["candidates"][0]["name"]
.as_str()
.expect("plan contains its candidate name");
service
.create_operation(
&workspace_id,
test_operation_payload("https://api.example.test", candidate_name),
)
.await
.unwrap();
let url = format!(
"{}/imports/openapi/{}/apply",
base_url.as_ref(),
legacy_id.as_str()
);
for (locale, idempotency_key, expected_message) in [
(
Some("ru"),
"name-conflict-ru",
"имя операции изменилось после создания плана",
),
(
None,
"name-conflict-en",
"an operation name changed after the plan was created",
),
] {
let mut request = client.post(&url).json(&json!({
"plan_digest": legacy.digest,
"idempotency_key": idempotency_key
}));
if let Some(locale) = locale {
request = request.header("accept-language", locale);
}
let response = request.send().await.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::CONFLICT);
let body: Value = response.json().await.unwrap();
assert_eq!(
body["error"]["context"]["error_code"],
"import_plan_name_conflict"
);
assert_eq!(
body["error"]["context"]["recovery"],
"confirm_skip_rename_or_new_version"
);
assert_eq!(body["error"]["message"], expected_message);
}
let matching_operations: i64 =
sqlx::query_scalar("select count(*) from operations where workspace_id = $1 and name = $2")
.bind(workspace_id.as_str())
.bind(candidate_name)
.fetch_one(registry.pool())
.await
.unwrap();
assert_eq!(
matching_operations, 1,
"Apply must not create another operation"
);
let applications: i64 = sqlx::query_scalar(
"select count(*) from import_plan_applications where workspace_id = $1 and plan_id = $2",
)
.bind(workspace_id.as_str())
.bind(legacy_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap();
assert_eq!(
applications, 0,
"a rejected Apply must not persist an application"
);
}
@@ -0,0 +1,184 @@
use super::*;
const SECURITY_SOURCE_A: &str = r#"
openapi: 3.0.3
info: { title: Security source A, version: '1' }
servers: [{ url: https://api.example.test }]
components:
securitySchemes:
apiKey:
type: apiKey
in: header
name: X-Api-Key
paths:
/secure:
get:
operationId: secureWithApiKey
security: [{ apiKey: [] }]
responses: { '200': { description: ok } }
"#;
const SECURITY_SOURCE_B: &str = r#"
openapi: 3.0.3
info: { title: Security source A, version: '1' }
servers: [{ url: https://api.example.test }]
components:
securitySchemes:
apiKey:
type: apiKey
in: header
name: X-Rotated-Key
paths:
/secure:
get:
operationId: secureWithApiKey
security: [{ apiKey: [] }]
responses: { '200': { description: ok } }
"#;
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn changed_security_scheme_invalidates_old_plan_before_draft_creation() {
let registry = test_registry().await;
let storage_root = test_storage_root("import_plan_security_source_change");
let base_url = spawn_admin_api(build_test_app(registry.clone(), storage_root)).await;
let client = authorized_client(&base_url).await;
let secret_response = client
.post(format!("{base_url}/secrets"))
.json(&json!({
"name": "security-source-test-secret",
"kind": "token",
"value": { "token": "source-change-canary" }
}))
.send()
.await
.unwrap();
assert_eq!(secret_response.status(), reqwest::StatusCode::OK);
let secret: Value = secret_response.json().await.unwrap();
let profile_response = client
.post(format!("{base_url}/auth-profiles"))
.json(&json!({
"name": "security-source-test-profile",
"kind": "api_key_header",
"config": { "api_key_header": {
"header_name": "X-Api-Key",
"secret_id": secret["id"]
}}
}))
.send()
.await
.unwrap();
assert_eq!(profile_response.status(), reqwest::StatusCode::OK);
let profile: Value = profile_response.json().await.unwrap();
let plan = create_plan(
&client,
&base_url,
SECURITY_SOURCE_A,
json!({
"selection_mode": "full",
"selected_operation_keys": [],
"decisions": [{
"operation_key": "GET /secure",
"action": "create",
"auth_profile_id": profile["id"]
}]
}),
)
.await;
assert_eq!(plan.body["candidates"][0]["auth_profile_id"], profile["id"]);
assert_eq!(plan.body["candidates"][0]["security_alternative_index"], 0);
let stored_plan = registry
.get_import_plan(
&crank_core::WorkspaceId::new("ws_default"),
&plan.reference.clone().into(),
)
.await
.unwrap()
.unwrap();
assert_eq!(
stored_plan.payload["candidates"][0]["operation"]["execution_config"]["auth_profile_ref"],
profile["id"],
"the old plan must persist its explicit profile binding"
);
assert_eq!(
stored_plan.payload["candidates"][0]["auth_requirement"]["parameter_name"],
"X-Api-Key"
);
// Register a second immutable source with only the security parameter
// changed. Its own upload/preview proves these are valid changed bytes,
// rather than corruption of the first content-addressed artifact.
let source_b_upload = reqwest::multipart::Part::bytes(SECURITY_SOURCE_B.as_bytes().to_vec())
.file_name("security-b.yaml")
.mime_str("application/yaml")
.unwrap();
let source_b_response = client
.post(format!("{base_url}/imports/openapi/preview"))
.multipart(reqwest::multipart::Form::new().part("file", source_b_upload))
.send()
.await
.unwrap();
assert_eq!(source_b_response.status(), reqwest::StatusCode::OK);
let source_b_preview: Value = source_b_response.json().await.unwrap();
assert_eq!(
source_b_preview["preview"]["groups"][0]["operations"][0]["security_schemes"]["apiKey"]["kind"]
["parameter_name"],
"X-Rotated-Key"
);
let workspace_id = crank_core::WorkspaceId::new("ws_default");
let original_job_id: crank_registry::ImportJobId =
plan.preview["job_id"].as_str().unwrap().into();
let changed_job_id: crank_registry::ImportJobId =
source_b_preview["job_id"].as_str().unwrap().into();
let original_job = registry
.get_import_job(&workspace_id, &original_job_id)
.await
.unwrap()
.unwrap();
let changed_job = registry
.get_import_job(&workspace_id, &changed_job_id)
.await
.unwrap()
.unwrap();
assert_ne!(
original_job.preview_payload["source"]["digest"],
changed_job.preview_payload["source"]["digest"],
"the changed scheme must come from a different verified source artifact"
);
assert_eq!(
stored_plan.payload["source"]["digest"], original_job.preview_payload["source"]["digest"],
"the plan must remain anchored to source A"
);
// Simulate the existing new-source/re-preview condition on the anchored
// pending job while retaining its original plan. The replacement is a
// separately registered and digest-verified B snapshot; Apply must
// compare the newly derived fingerprint with the old plan fingerprint.
sqlx::query("update import_jobs set preview_payload = $3 where id = $1 and workspace_id = $2")
.bind(original_job_id.as_str())
.bind(workspace_id.as_str())
.bind(&changed_job.preview_payload)
.execute(registry.pool())
.await
.unwrap();
let replaced_job = registry
.get_import_job(&workspace_id, &original_job_id)
.await
.unwrap()
.unwrap();
assert_eq!(
replaced_job.preview_payload["source"]["digest"],
changed_job.preview_payload["source"]["digest"]
);
let (status, error) = apply_plan(&client, &base_url, &plan, "security-source-changed").await;
assert_eq!(status, reqwest::StatusCode::CONFLICT, "{error}");
assert_eq!(
error["error"]["context"]["error_code"], "import_plan_fingerprint_stale",
"the old plan must require re-preview after source security changes"
);
assert_eq!(error["error"]["context"]["repreview_required"], true);
assert_eq!(operation_list(&client, &base_url).await["total"], 0);
}
@@ -0,0 +1,171 @@
use super::*;
use admin_api::error::ApiError;
use admin_api::service::{
OpenApiImportPlanApplyPayload, OpenApiImportPlanCreatePayload, OpenApiUpload,
OpenApiUploadLocale,
};
use crank_core::WorkspaceId;
use crank_registry::{CreateImportPlanRequest, ImportPlanId};
fn single_operation_upload() -> OpenApiUpload {
OpenApiUpload {
bytes: OPENAPI_SINGLE.as_bytes().to_vec(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
}
}
#[tokio::test]
#[serial]
async fn older_support_matrix_rejects_new_apply_but_keeps_plan_auditable() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_old_support_matrix_apply"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, single_operation_upload())
.await
.unwrap();
let job_id = preview.job_id.as_str().into();
let created = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
OpenApiImportPlanCreatePayload {
selection_mode: "full".to_owned(),
selected_operation_keys: Vec::new(),
server_url: None,
decisions: Vec::new(),
},
)
.await
.unwrap();
let original_id: ImportPlanId = created.plan_reference.as_str().into();
let original = registry
.get_import_plan(&workspace_id, &original_id)
.await
.unwrap()
.unwrap();
// 1.0.2 is the historical matrix contract and 1.0.3 the immediate previous
// one; against the shipped 1.0.4 matrix both must stay stale and must not
// authorize a new Apply, while the original immutable plan stays auditable.
for version in ["1.0.2", "1.0.3"] {
// Model an immutable plan saved under an earlier support matrix. The
// registry derives its valid semantic digest from the changed payload.
let old_id: ImportPlanId =
format!("plan_older_support_matrix_{}", version.replace('.', "_")).into();
let mut old_payload = original.payload.clone();
old_payload["plan_reference"] = json!(old_id.as_str());
old_payload["support_matrix_version"] = json!(version);
let older = registry
.create_import_plan(CreateImportPlanRequest {
id: &old_id,
workspace_id: &workspace_id,
job_id: &original.job_id,
payload: &old_payload,
created_at: &original.created_at,
expires_at: &original.expires_at,
})
.await
.unwrap();
assert_ne!(older.digest, original.digest);
let audit = service
.revalidate_openapi_import_plan(&workspace_id, &old_id)
.await
.unwrap();
assert_eq!(audit.revalidation_status, "stale", "{version}");
assert!(audit.revalidation_required, "{version}");
assert_eq!(
audit.reason.as_deref(),
Some("importer_version_changed"),
"{version}"
);
let error = service
.apply_openapi_import_plan(
&workspace_id,
&old_id,
OpenApiImportPlanApplyPayload {
plan_digest: older.digest,
idempotency_key: format!("old-matrix-{version}"),
},
)
.await
.expect_err("old support matrix must not authorize a new Apply");
match error {
ApiError::Conflict {
context: Some(context),
..
} => assert_eq!(context["error_code"], "importer_version_changed"),
other => panic!("expected typed re-preview conflict, got {other:?}"),
}
assert!(
service
.list_operations(&workspace_id)
.await
.unwrap()
.is_empty(),
"{version} apply must not mutate the workspace"
);
}
}
// The runtime matrix version stamped into a fresh plan must equal the version
// recorded in the machine matrix the corpus validates. Reading the machine YAML
// (rather than a second literal) keeps an app release honest: it can never
// advertise a matrix the repository does not actually ship.
#[tokio::test]
#[serial]
async fn fresh_plan_support_matrix_version_matches_machine_matrix() {
let machine_text = std::fs::read_to_string(
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../crates/crank-import/tests/support-matrix.yaml"),
)
.unwrap();
let machine: serde_yaml::Value = serde_yaml::from_str(&machine_text).unwrap();
let machine_version = machine["matrix_version"].as_str().unwrap().to_owned();
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_support_matrix_runtime_version"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, single_operation_upload())
.await
.unwrap();
let job_id = preview.job_id.as_str().into();
let created = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
OpenApiImportPlanCreatePayload {
selection_mode: "full".to_owned(),
selected_operation_keys: Vec::new(),
server_url: None,
decisions: Vec::new(),
},
)
.await
.unwrap();
let stored = registry
.get_import_plan(&workspace_id, &created.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
assert_eq!(
stored.payload["support_matrix_version"],
json!(machine_version),
"the runtime support-matrix version must match the machine matrix"
);
}
@@ -0,0 +1,997 @@
use super::*;
pub(crate) const OPENAPI_SINGLE_SECURITY: &str = r#"
openapi: 3.0.3
info: { title: Import security, version: '1' }
servers: [{ url: https://api.example.test }]
components:
securitySchemes:
Key: { type: apiKey, in: header, name: X-Api-Key }
Bearer: { type: http, scheme: bearer }
paths:
/v2/latest:
get:
operationId: latestRates
security: [{ Key: [] }, { Bearer: [] }]
responses: { '200': { description: ok } }
"#;
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn preview_name_conflicts_are_typed_and_deterministic() {
let registry = test_registry().await;
let upstream = spawn_upstream_server().await;
let service = test_service(
registry,
test_storage_root("openapi_preview_name_conflicts"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace = WorkspaceId::new("ws_default");
service
.create_operation(
&workspace,
test_operation_payload(&upstream, "duplicate_id"),
)
.await
.unwrap();
let document = r#"
openapi: 3.0.3
info: { title: Naming }
servers: [{ url: https://api.example.test }]
paths:
/one:
get:
operationId: duplicate_id
responses: { '200': { description: ok } }
/two:
get:
operationId: duplicate_id
responses: { '200': { description: ok } }
/bad:
get:
operationId: bad-id
responses: { '200': { description: ok } }
"#;
let first = service
.preview_openapi_import(&workspace, upload(document))
.await
.unwrap();
let repeated = service
.preview_openapi_import(&workspace, upload(document))
.await
.unwrap();
assert_eq!(first.preview.conflicts, repeated.preview.conflicts);
assert!(
first
.preview
.conflicts
.iter()
.any(|item| item.conflict_type == "duplicate_name")
);
assert!(
first
.preview
.conflicts
.iter()
.any(|item| item.conflict_type == "invalid_name")
);
assert!(
first
.preview
.conflicts
.iter()
.any(|item| item.conflict_type == "taken_name")
);
assert!(first.preview.conflicts.iter().all(|item| {
item.source_location
.as_ref()
.is_some_and(|location| location.pointer.starts_with("/paths/"))
&& !item.proposed_name.is_empty()
}));
assert_eq!(service.list_operations(&workspace).await.unwrap().len(), 1);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn reopening_plan_is_read_only_and_reports_catalog_drift() {
let registry = test_registry().await;
let upstream = spawn_upstream_server().await;
let service = test_service(
registry,
test_storage_root("openapi_plan_reopen_catalog"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let plan = service
.create_openapi_import_plan(&workspace, &job_id, plan_payload("full", vec![], vec![]))
.await
.unwrap();
let plan_id = plan.plan_reference.as_str().into();
let current = service
.revalidate_openapi_import_plan(&workspace, &plan_id)
.await
.unwrap();
assert_eq!(current.revalidation_status, "current");
assert!(!current.revalidation_required);
assert!(
service
.list_operations(&workspace)
.await
.unwrap()
.is_empty()
);
service
.create_operation(
&workspace,
test_operation_payload(&upstream, "unrelated_operation"),
)
.await
.unwrap();
let stale = service
.revalidate_openapi_import_plan(&workspace, &plan_id)
.await
.unwrap();
assert_eq!(stale.revalidation_status, "stale");
assert!(stale.revalidation_required);
assert_eq!(service.list_operations(&workspace).await.unwrap().len(), 1);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn full_plan_is_server_authored_with_bounded_confirmation_and_no_mutation() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_full"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
assert_eq!(preview.preview.groups[0].operations[0].status, "actionable");
let job_id: ImportJobId = preview.job_id.as_str().into();
let job = registry
.get_import_job(&workspace_id, &job_id)
.await
.unwrap()
.unwrap();
let plan = service
.create_openapi_import_plan(&workspace_id, &job_id, plan_payload("full", vec![], vec![]))
.await
.unwrap();
assert!(plan.plan_reference.starts_with("plan_"));
assert!(
plan.plan_digest.len() == 64
&& plan
.plan_digest
.bytes()
.all(|byte| byte.is_ascii_hexdigit())
);
assert_eq!(plan.selection_mode, "full");
assert_eq!(plan.counts.selected, 1);
assert_eq!(plan.counts.excluded, 0);
assert_eq!(plan.counts.actionable, 1);
assert_eq!(plan.counts.blocked, 0);
let candidate = &plan.candidates[0];
assert_eq!(candidate.key, "GET /v2/latest");
assert_eq!(candidate.name, "latest_rates");
assert_eq!(candidate.state, "actionable");
assert_eq!(candidate.action.as_deref(), Some("create"));
assert_eq!(candidate.reason, None);
let expires_at = OffsetDateTime::parse(
&plan.expires_at,
&time::format_description::well_known::Rfc3339,
)
.unwrap();
assert!(expires_at > OffsetDateTime::now_utc());
assert!(expires_at <= job.expires_at);
let stored = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
.await
.unwrap()
.expect("the created plan must be readable in its workspace");
assert_eq!(stored.digest, plan.plan_digest);
assert_eq!(stored.payload["schema_version"], "import-plan-v2");
assert_eq!(stored.payload["catalog_revision"], plan.catalog_revision);
assert_eq!(stored.payload["support_matrix_version"], "1.0.4");
assert!(stored.payload["findings"]["document"].is_array());
assert!(stored.payload["findings"]["candidates"].is_array());
assert_eq!(stored.expires_at, expires_at);
assert_eq!(
stored.payload["selection"]["selected"],
json!(["GET /v2/latest"])
);
assert_eq!(stored.payload["selection"]["excluded"], json!([]));
assert_eq!(stored.payload["counts"]["actionable"], json!(1));
let candidate = &stored.payload["candidates"][0];
assert_eq!(candidate["decision"]["action"], "create");
assert!(
candidate["operation"]["id"]
.as_str()
.unwrap()
.starts_with("op_")
);
assert_eq!(candidate["operation"]["status"], "draft");
assert_eq!(
stored.payload["source"]["digest"],
job.preview_payload["source"]["digest"]
);
assert!(stored.payload["fingerprint"]["ir_fingerprint"].is_string());
let repeated = service
.create_openapi_import_plan(&workspace_id, &job_id, plan_payload("full", vec![], vec![]))
.await
.unwrap();
assert_ne!(repeated.plan_reference, plan.plan_reference);
assert_eq!(repeated.plan_digest, plan.plan_digest);
let repeated_stored = registry
.get_import_plan(&workspace_id, &repeated.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
assert_ne!(
repeated_stored.payload["candidates"][0]["operation"]["id"],
stored.payload["candidates"][0]["operation"]["id"]
);
// Planning is non-mutating: no operation exists and the job stays pending.
assert!(
service
.list_operations(&workspace_id)
.await
.unwrap()
.is_empty()
);
let job = registry
.get_import_job(&workspace_id, &job_id)
.await
.unwrap()
.unwrap();
assert_eq!(job.status, ImportJobStatus::Pending);
assert_eq!(job.error_text, None);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn partial_plan_counts_selection_and_rejects_invalid_request_material() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_partial"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_TWO_OPS))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let keys = preview_operation_keys(&preview);
assert_eq!(keys.len(), 2);
let (first, second) = (keys[0].clone(), keys[1].clone());
let expected_display_name = preview
.preview
.groups
.iter()
.flat_map(|group| &group.operations)
.find(|candidate| candidate.key == second)
.expect("excluded candidate is in preview")
.draft
.name
.clone();
let plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload("partial", vec![first.clone()], vec![]),
)
.await
.unwrap();
assert_eq!(plan.counts.selected, 1);
assert_eq!(plan.counts.excluded, 1);
assert_eq!(plan.counts.actionable, 1);
assert_eq!(plan.counts.blocked, 0);
let excluded = plan
.candidates
.iter()
.find(|candidate| candidate.key == second)
.expect("the excluded candidate is listed for confirmation");
assert_eq!(excluded.state, "excluded");
assert_eq!(excluded.name, expected_display_name);
assert_eq!(excluded.reason.as_deref(), Some("not_selected"));
let stored = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
assert_eq!(
stored.payload["excluded_reasons"],
json!([{
"key": second,
"name": expected_display_name,
"reason": "not_selected",
}])
);
let plan_id: crank_registry::ImportPlanId = plan.plan_reference.as_str().into();
let revalidated = service
.revalidate_openapi_import_plan(&workspace_id, &plan_id)
.await
.unwrap();
let revalidated_excluded = revalidated
.candidates
.iter()
.find(|candidate| candidate.key == second)
.expect("excluded candidate remains visible during revalidation");
assert_eq!(revalidated_excluded.name, expected_display_name);
let stored = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
let expected_all = json!([first, second]);
assert_eq!(stored.payload["selection"]["all"], expected_all);
// `excluded` candidates never receive a decision, target or draft material.
let listed = stored.payload["candidates"].as_array().unwrap();
assert_eq!(listed.len(), 1);
assert_eq!(listed[0]["key"], first);
assert!(listed[0].get("target").is_none());
let cases: Vec<(OpenApiImportPlanCreatePayload, &'static str)> = vec![
(
plan_payload("full", vec![first.clone()], vec![]),
"import_plan_selection_mismatch",
),
(
plan_payload("partial", vec!["GET /unknown".to_owned()], vec![]),
"import_plan_unknown_operation_key",
),
(
plan_payload("partial", vec![], vec![]),
"import_plan_invalid_input",
),
(
plan_payload("partial", vec![first.clone(), first.clone()], vec![]),
"import_plan_invalid_input",
),
(
plan_payload("bogus", vec![first.clone()], vec![]),
"import_plan_invalid_input",
),
(
plan_payload(
"partial",
vec![first.clone()],
vec![decision("GET /other", "create", None, None, None)],
),
"import_plan_decision_unselected",
),
(
plan_payload(
"partial",
vec![first.clone(), second.clone()],
vec![
decision(&first, "create", None, None, None),
decision(&first, "skip", Some("op_other"), None, None),
],
),
"import_plan_invalid_input",
),
(
plan_payload(
"partial",
vec![first.clone()],
vec![decision(&first, "skip", None, None, None)],
),
"import_plan_invalid_input",
),
(
plan_payload(
"partial",
vec![first.clone()],
vec![decision(
&first,
"skip",
Some("op_other"),
Some("other_name"),
None,
)],
),
"import_plan_invalid_input",
),
(
plan_payload(
"partial",
vec![first.clone(), second.clone()],
vec![decision(
&first,
"skip",
Some("op_other"),
None,
Some("auth_profile_any"),
)],
),
"import_plan_invalid_input",
),
(
plan_payload(
"partial",
vec![first.clone(), second.clone()],
vec![
decision(&first, "create", None, Some("renamed"), None),
decision(&second, "rename", Some("op_other"), None, None),
],
),
"import_plan_invalid_input",
),
(
plan_payload(
"partial",
vec![first.clone()],
vec![decision(&first, "rename", None, None, None)],
),
"import_plan_invalid_input",
),
(
plan_payload(
"partial",
vec![first.clone()],
vec![decision(&first, "new_version", None, None, None)],
),
"import_plan_invalid_input",
),
];
for (payload, expected_code) in cases {
let error = service
.create_openapi_import_plan(&workspace_id, &job_id, payload)
.await
.expect_err("invalid plan material must be rejected");
assert_error_code(&error, expected_code);
assert_http_status(error, axum::http::StatusCode::BAD_REQUEST);
}
// The successful plan above still exists untouched.
let readable = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
.await
.unwrap();
assert!(readable.is_some());
assert!(
service
.list_operations(&workspace_id)
.await
.unwrap()
.is_empty()
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn client_supplied_candidate_material_has_no_authority() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_client_authority"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
// Client-supplied digests, payloads or candidate arrays are not part of
// the request contract and must not influence the server-authored plan.
let request = json!({
"selection_mode": "full",
"selected_operation_keys": [],
"plan_digest": format!("sha256:{}", "ab".repeat(32)),
"plan_payload": {
"schema_version": "import-plan-client-v999",
"candidates": [{ "key": "GET /forged", "name": "forged" }],
},
"candidates": [{ "key": "GET /forged" }],
});
assert!(
serde_json::from_value::<OpenApiImportPlanCreatePayload>(request).is_err(),
"client-supplied candidate material must be rejected at the request boundary"
);
let payload: OpenApiImportPlanCreatePayload = serde_json::from_value(json!({
"selection_mode": "full",
"selected_operation_keys": []
}))
.unwrap();
let plan = service
.create_openapi_import_plan(&workspace_id, &job_id, payload)
.await
.unwrap();
let stored = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
let material = stored.payload.to_string();
assert!(!material.contains("import-plan-client-v999"));
assert!(!material.contains("GET /forged"));
assert!(!material.contains("abababab"));
assert_eq!(
stored.payload["selection"]["all"],
json!(["GET /v2/latest"])
);
assert_eq!(stored.payload["schema_version"], "import-plan-v2");
assert!(stored.digest.len() == 64 && stored.digest.bytes().all(|b| b.is_ascii_hexdigit()));
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn plan_creation_is_workspace_scoped() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_scope"),
test_auth_settings(),
test_secret_crypto(),
);
let primary = WorkspaceId::new("ws_default");
let secondary = WorkspaceId::new("ws_plan_scope_secondary");
let created_at = OffsetDateTime::now_utc();
registry
.create_workspace(CreateWorkspaceRequest {
workspace: &Workspace {
id: secondary.clone(),
slug: "ws-plan-scope-secondary".to_owned(),
display_name: "Plan scope secondary".to_owned(),
status: WorkspaceStatus::Active,
settings: json!({}),
created_at,
updated_at: created_at,
},
})
.await
.unwrap();
let preview = service
.preview_openapi_import(&primary, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let plan = service
.create_openapi_import_plan(&primary, &job_id, plan_payload("full", vec![], vec![]))
.await
.unwrap();
let cross_scope_error = service
.create_openapi_import_plan(&secondary, &job_id, plan_payload("full", vec![], vec![]))
.await
.expect_err("a foreign job must be invisible, not planned");
assert_http_status(cross_scope_error, axum::http::StatusCode::NOT_FOUND);
let stored = registry
.get_import_plan(&secondary, &plan.plan_reference.as_str().into())
.await
.unwrap();
assert!(stored.is_none(), "a foreign plan id must be invisible");
let reopen_error = service
.revalidate_openapi_import_plan(&secondary, &plan.plan_reference.as_str().into())
.await
.expect_err("a foreign plan cannot be reopened");
assert_http_status(reopen_error, axum::http::StatusCode::NOT_FOUND);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn exact_skip_rename_and_new_version_decisions_are_saved_verbatim() {
let registry = test_registry().await;
let upstream_base_url = spawn_upstream_server().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_decisions"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
// A conflicting existing operation so `create` is no longer safe by default.
let existing = service
.create_operation(
&workspace_id,
test_operation_payload(&upstream_base_url, "latest_rates"),
)
.await
.unwrap();
let operation_id = existing.operation_id;
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"full",
vec![],
vec![decision(
"GET /v2/latest",
"skip",
Some(operation_id.as_str()),
None,
None,
)],
),
)
.await
.expect("skip must target the exact existing operation");
let stored = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
let candidate = &stored.payload["candidates"][0];
assert_eq!(plan.counts.actionable, 1);
assert_eq!(candidate["decision"]["action"], "skip");
assert_eq!(candidate["target"]["operation_id"], json!(operation_id));
assert_eq!(
candidate["target"]["expected_state"],
json!({
"status": "draft",
"current_draft_version": 1,
"latest_published_version": null
})
);
assert!(
candidate.get("operation").is_none(),
"skip must not create draft material"
);
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let renamed = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"full",
vec![],
vec![decision(
"GET /v2/latest",
"rename",
None,
Some("latest_rates_confirmed"),
None,
)],
),
)
.await
.unwrap();
let stored = registry
.get_import_plan(&workspace_id, &renamed.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
assert_eq!(
stored.payload["candidates"][0]["decision"]["confirmed_name"],
"latest_rates_confirmed"
);
assert_eq!(
stored.payload["candidates"][0]["operation"]["name"],
"latest_rates_confirmed"
);
assert!(
stored.payload["candidates"][0]["operation"]["id"]
.as_str()
.unwrap()
.starts_with("op_")
);
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let versioned = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"full",
vec![],
vec![decision(
"GET /v2/latest",
"new_version",
Some(operation_id.as_str()),
None,
None,
)],
),
)
.await
.unwrap();
let stored = registry
.get_import_plan(&workspace_id, &versioned.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
let candidate = &stored.payload["candidates"][0];
assert_eq!(
candidate["operation"]["id"], operation_id,
"new_version snapshot must bind the exact target operation"
);
assert_eq!(candidate["operation"]["version"], 2);
assert_eq!(
candidate["target"]["expected_state"],
json!({
"status": "draft",
"current_draft_version": 1,
"latest_published_version": null
})
);
// Planning never mutates: only the original Draft Version exists.
let operations = service.list_operations(&workspace_id).await.unwrap();
assert_eq!(operations.len(), 1);
assert_eq!(operations[0].name, "latest_rates");
assert_eq!(operations[0].current_draft_version, 1);
// A mismatched target is rejected with the stable target code.
let other = service
.create_operation(
&workspace_id,
test_operation_payload(&upstream_base_url, "other_operation"),
)
.await
.unwrap();
for mismatched in [
vec![decision(
"GET /v2/latest",
"skip",
Some(other.operation_id.as_str()),
None,
None,
)],
vec![decision(
"GET /v2/latest",
"new_version",
Some(other.operation_id.as_str()),
None,
None,
)],
] {
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let error = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload("full", vec![], mismatched),
)
.await
.expect_err("a mismatched target must be rejected");
assert_error_code(&error, "import_plan_target_invalid");
assert_http_status(error, axum::http::StatusCode::BAD_REQUEST);
}
// An explicit `create` against a taken name conflicts; the server never
// auto-selects a replacement name.
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let error = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"full",
vec![],
vec![decision("GET /v2/latest", "create", None, None, None)],
),
)
.await
.expect_err("create with a taken name must conflict");
assert_error_code(&error, "import_plan_name_conflict");
assert_http_status(error, axum::http::StatusCode::CONFLICT);
// Without an explicit decision the same collision stays a bounded,
// redacted blocked candidate inside the immutable plan.
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let plan = service
.create_openapi_import_plan(&workspace_id, &job_id, plan_payload("full", vec![], vec![]))
.await
.unwrap();
assert_eq!(plan.counts.actionable, 0);
assert_eq!(plan.counts.blocked, 1);
let stored = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
let candidate = &stored.payload["candidates"][0];
assert_eq!(candidate["state"], "blocked");
assert_eq!(candidate["reason"], "operation_name_conflict");
assert!(candidate.get("operation").is_none());
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn stale_or_terminal_jobs_preview_again_without_mutating_the_job() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_stale"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
sqlx::query(
"update import_jobs
set preview_payload = jsonb_set(preview_payload, '{preview_digest}', to_jsonb($1::text))
where id = $2",
)
.bind("0".repeat(64))
.bind(job_id.as_str())
.execute(registry.pool())
.await
.unwrap();
let error = service
.create_openapi_import_plan(&workspace_id, &job_id, plan_payload("full", vec![], vec![]))
.await
.expect_err("a stale preview contract must be rejected");
assert_error_code(&error, "import_replay_verification_failed");
let context = public_error_context(&error).cloned().unwrap();
assert_eq!(context["repreview_required"], json!(true));
assert_eq!(
context.get("recovery").and_then(Value::as_str),
Some("repreview_required")
);
assert_http_status(error, axum::http::StatusCode::CONFLICT);
// Unlike the legacy path the job itself is untouched: other stored
// plans anchored to it must remain readable.
let job = registry
.get_import_job(&workspace_id, &job_id)
.await
.unwrap()
.unwrap();
assert_eq!(job.status, ImportJobStatus::Pending);
assert_eq!(job.error_text, None);
assert!(job.finished_at.is_none());
assert!(
service
.list_operations(&workspace_id)
.await
.unwrap()
.is_empty()
);
let completed_at = OffsetDateTime::now_utc();
registry
.finish_import_job(FinishImportJobRequest {
id: &job_id,
status: ImportJobStatus::Failed,
created_operation_ids: &json!([]),
error_text: Some("test_finalized"),
finished_at: &completed_at,
})
.await
.unwrap();
let error = service
.create_openapi_import_plan(&workspace_id, &job_id, plan_payload("full", vec![], vec![]))
.await
.expect_err("a terminal job cannot be planned");
assert_error_code(&error, "import_plan_job_terminal");
assert_http_status(error, axum::http::StatusCode::CONFLICT);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn public_plan_route_returns_bounded_confirmation_and_requires_a_session() {
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_plan_http");
let service = test_service(
registry.clone(),
storage_root.clone(),
test_auth_settings(),
test_secret_crypto(),
);
let app = build_test_app(registry.clone(), storage_root);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id = preview.job_id.clone();
let server = spawn_admin_api(app).await;
let client = authorized_client(&server).await;
let url = format!("{}/imports/openapi/{}/plans", server.as_ref(), job_id);
// Without a session (and thus without a workspace owner context) the
// public contract refuses and no plan is created.
let anonymous = reqwest::Client::new();
let denied = anonymous
.post(&url)
.json(&json!({ "selection_mode": "full", "selected_operation_keys": [] }))
.send()
.await
.unwrap();
assert_eq!(denied.status(), reqwest::StatusCode::UNAUTHORIZED);
let accepted = client
.post(&url)
.json(&json!({ "selection_mode": "full", "selected_operation_keys": [] }))
.send()
.await
.unwrap();
assert_eq!(accepted.status(), reqwest::StatusCode::OK);
let body: Value = accepted.json().await.unwrap();
let plan_reference = body["plan_reference"].as_str().unwrap_or_default();
assert!(
plan_reference.starts_with("plan_"),
"plan reference must be server-issued: {body:?}"
);
let plan_digest = body["plan_digest"].as_str().unwrap_or_default();
assert!(
plan_digest.len() == 64 && plan_digest.bytes().all(|b| b.is_ascii_hexdigit()),
"plan digest must be the registry-derived SHA-256: {body:?}"
);
assert_eq!(body["selection_mode"], "full");
assert_eq!(
body["counts"],
json!({ "selected": 1, "excluded": 0, "actionable": 1, "blocked": 0 })
);
assert_eq!(body["candidates"].as_array().unwrap().len(), 1);
assert_eq!(body["candidates"][0]["key"], "GET /v2/latest");
assert_eq!(body["candidates"][0]["state"], "actionable");
assert_eq!(body["candidates"][0]["action"], "create");
assert!(body["expires_at"].is_string());
// The HTTP response is the bounded confirmation only: no draft snapshot,
// no raw preview material, no secret material.
assert!(body["candidates"][0].get("operation").is_none());
assert!(!body.to_string().to_lowercase().contains("password"));
// The plan is readable in the same workspace right after the 200.
let plan_id = crank_registry::ImportPlanId::new(plan_reference);
let readable = registry
.get_import_plan(&workspace_id, &plan_id)
.await
.unwrap()
.expect("the HTTP-created plan must be persisted");
assert_eq!(readable.digest, plan_digest);
}
@@ -0,0 +1,135 @@
use super::*;
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn partial_plan_applies_when_excluded_operation_name_exceeds_selected_name_limit() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_long_excluded_name"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let long_operation_id = "a".repeat(257);
let document = format!(
r#"openapi: 3.0.3
info:
title: Long excluded operation name
version: "1"
servers:
- url: https://api.example.test
paths:
/selected:
get:
operationId: selectedMethod
responses:
"200":
description: ok
/excluded:
get:
operationId: {long_operation_id}
responses:
"200":
description: ok
"#
);
let preview = service
.preview_openapi_import(&workspace_id, upload(&document))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let selected_key = "GET /selected";
let excluded_key = "GET /excluded";
let excluded_draft_name = preview
.preview
.groups
.iter()
.flat_map(|group| &group.operations)
.find(|candidate| candidate.key == excluded_key)
.expect("long-name method is present in preview")
.draft
.name
.clone();
assert_eq!(excluded_draft_name, long_operation_id);
assert!(excluded_draft_name.len() > 256);
let plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"partial",
vec![selected_key.to_owned()],
vec![decision(selected_key, "create", None, None, None)],
),
)
.await
.unwrap();
let created_excluded = plan
.candidates
.iter()
.find(|candidate| candidate.key == excluded_key)
.expect("excluded method is returned by plan creation");
assert_eq!(created_excluded.name, excluded_draft_name);
assert_eq!(plan.counts.selected, 1);
assert_eq!(plan.counts.excluded, 1);
let plan_id = crank_registry::ImportPlanId::new(plan.plan_reference.clone());
let stored = registry
.get_import_plan(&workspace_id, &plan_id)
.await
.unwrap()
.expect("created plan is persisted");
assert_eq!(
stored.payload["excluded_reasons"][0]["name"],
excluded_draft_name
);
let revalidated = service
.revalidate_openapi_import_plan(&workspace_id, &plan_id)
.await
.unwrap();
let revalidated_excluded = revalidated
.candidates
.iter()
.find(|candidate| candidate.key == excluded_key)
.expect("excluded method remains visible during revalidation");
assert_eq!(revalidated_excluded.name, excluded_draft_name);
let report = service
.apply_openapi_import_plan(
&workspace_id,
&plan_id,
admin_api::service::OpenApiImportPlanApplyPayload {
plan_digest: plan.plan_digest,
idempotency_key: "long-excluded-name-apply".to_owned(),
},
)
.await
.expect("excluded descriptive metadata must not invalidate a partial plan");
assert_eq!(
report.status,
crank_registry::ImportPlanApplyStatus::Applied
);
assert_eq!(report.counts.created, 1);
assert_eq!(
report
.outcomes
.iter()
.find(|outcome| outcome.key == selected_key)
.expect("selected method appears in apply report")
.outcome,
crank_registry::ImportPlanCandidateOutcome::Created
);
let reported_excluded = report
.outcomes
.iter()
.find(|outcome| outcome.key == excluded_key)
.expect("apply report includes the excluded method");
assert_eq!(reported_excluded.name, excluded_draft_name);
let operations = service.list_operations(&workspace_id).await.unwrap();
assert_eq!(operations.len(), 1, "only the selected method is applied");
assert_eq!(operations[0].status, crank_core::OperationStatus::Draft);
assert_eq!(operations[0].current_draft_version, 1);
}
@@ -0,0 +1,360 @@
use super::*;
/// Server-created plan reached through the public HTTP contract, so the locale
/// tests exercise the real route handlers rather than the service methods.
struct HttpPlan {
plan_reference: String,
plan_digest: String,
}
async fn create_http_plan(client: &reqwest::Client, base_url: &str) -> HttpPlan {
let upload_part = reqwest::multipart::Part::bytes(OPENAPI_SINGLE.as_bytes().to_vec())
.file_name("import.yaml")
.mime_str("application/yaml")
.unwrap();
let preview = client
.post(format!("{base_url}/imports/openapi/preview"))
.multipart(reqwest::multipart::Form::new().part("file", upload_part))
.send()
.await
.unwrap();
assert_eq!(preview.status(), reqwest::StatusCode::OK);
let preview: Value = preview.json().await.unwrap();
let job_id = preview["job_id"].as_str().unwrap().to_owned();
let plan = client
.post(format!("{base_url}/imports/openapi/{job_id}/plans"))
.json(&json!({ "selection_mode": "full", "selected_operation_keys": [] }))
.send()
.await
.unwrap();
assert_eq!(plan.status(), reqwest::StatusCode::OK);
let plan: Value = plan.json().await.unwrap();
HttpPlan {
plan_reference: plan["plan_reference"].as_str().unwrap().to_owned(),
plan_digest: plan["plan_digest"].as_str().unwrap().to_owned(),
}
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn plan_create_localizes_repreview_guidance_by_accept_language() {
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_plan_locale_create");
let service = test_service(
registry.clone(),
storage_root.clone(),
test_auth_settings(),
test_secret_crypto(),
);
let app = build_test_app(registry.clone(), storage_root);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id = preview.job_id.clone();
// Corrupt the persisted preview contract so plan creation must ask for a
// fresh preview.
sqlx::query(
"update import_jobs
set preview_payload = jsonb_set(preview_payload, '{preview_digest}', to_jsonb($1::text))
where id = $2",
)
.bind("0".repeat(64))
.bind(&job_id)
.execute(registry.pool())
.await
.unwrap();
let server = spawn_admin_api(app).await;
let client = authorized_client(&server).await;
let url = format!("{}/imports/openapi/{}/plans", server.as_ref(), job_id);
// Russian session: Russian recovery guidance, identical machine code and
// recovery flags.
let ru = client
.post(&url)
.header("accept-language", "ru-RU, ru;q=0.9")
.json(&json!({ "selection_mode": "full", "selected_operation_keys": [] }))
.send()
.await
.unwrap();
assert_eq!(ru.status(), reqwest::StatusCode::CONFLICT);
let ru_body: Value = ru.json().await.unwrap();
assert_eq!(
ru_body["error"]["context"]["error_code"],
"import_replay_verification_failed"
);
assert_eq!(
ru_body["error"]["context"]["repreview_required"],
json!(true)
);
assert_eq!(
ru_body["error"]["context"]["recovery"],
"repreview_required"
);
assert!(
ru_body["error"]["message"]
.as_str()
.unwrap_or_default()
.contains("создайте новый preview"),
"Russian session must receive Russian guidance: {ru_body:?}"
);
// No locale header keeps the English default behavior.
let en = client
.post(&url)
.json(&json!({ "selection_mode": "full", "selected_operation_keys": [] }))
.send()
.await
.unwrap();
assert_eq!(en.status(), reqwest::StatusCode::CONFLICT);
let en_body: Value = en.json().await.unwrap();
assert_eq!(
en_body["error"]["context"]["error_code"],
"import_replay_verification_failed"
);
assert!(
en_body["error"]["message"]
.as_str()
.unwrap_or_default()
.contains("create a fresh preview"),
"EN default must remain English: {en_body:?}"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn plan_revalidate_accepts_locale_without_machine_drift() {
let registry = test_registry().await;
let app = build_test_app(
registry,
test_storage_root("openapi_import_plan_locale_revalidate"),
);
let server = spawn_admin_api(app).await;
let client = authorized_client(&server).await;
let plan = create_http_plan(&client, server.as_ref()).await;
let url = format!(
"{}/imports/openapi/plans/{}",
server.as_ref(),
plan.plan_reference
);
let ru = client
.get(&url)
.header("accept-language", "ru")
.send()
.await
.unwrap();
assert_eq!(ru.status(), reqwest::StatusCode::OK);
let ru: Value = ru.json().await.unwrap();
assert_eq!(ru["plan_digest"], plan.plan_digest);
assert_eq!(ru["revalidation_status"], "current");
assert_eq!(ru["revalidation_required"], false);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn plan_create_localizes_expired_preview_by_accept_language() {
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_plan_locale_expired");
let service = test_service(
registry.clone(),
storage_root.clone(),
test_auth_settings(),
test_secret_crypto(),
);
let app = build_test_app(registry.clone(), storage_root);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id = preview.job_id.clone();
// Expire the preview job without corrupting its replay contract.
sqlx::query("update import_jobs set expires_at = now() - interval '1 minute' where id = $1")
.bind(&job_id)
.execute(registry.pool())
.await
.unwrap();
let server = spawn_admin_api(app).await;
let client = authorized_client(&server).await;
let url = format!("{}/imports/openapi/{}/plans", server.as_ref(), job_id);
let body = json!({ "selection_mode": "full", "selected_operation_keys": [] });
let ru = client
.post(&url)
.header("accept-language", "ru")
.json(&body)
.send()
.await
.unwrap();
assert_eq!(ru.status(), reqwest::StatusCode::BAD_REQUEST);
let ru_body: Value = ru.json().await.unwrap();
assert_eq!(ru_body["error"]["code"], "validation_error");
assert!(
ru_body["error"].get("context").is_none(),
"expired-preview validation keeps no context: {ru_body:?}"
);
assert!(
ru_body["error"]["message"]
.as_str()
.unwrap_or_default()
.contains("истёк"),
"Russian session must receive Russian guidance: {ru_body:?}"
);
// No locale header keeps the English default behavior.
let en = client.post(&url).json(&body).send().await.unwrap();
assert_eq!(en.status(), reqwest::StatusCode::BAD_REQUEST);
let en_body: Value = en.json().await.unwrap();
assert_eq!(en_body["error"]["code"], "validation_error");
assert!(en_body["error"].get("context").is_none());
assert_eq!(en_body["error"]["message"], "import preview has expired");
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn plan_create_localizes_name_conflict_guidance_by_accept_language() {
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_plan_locale_name_conflict");
let service = test_service(
registry.clone(),
storage_root.clone(),
test_auth_settings(),
test_secret_crypto(),
);
let app = build_test_app(registry.clone(), storage_root);
let workspace_id = WorkspaceId::new("ws_default");
// Occupy the candidate's suggested name so an explicit `create` decision
// conflicts.
service
.create_operation(
&workspace_id,
test_operation_payload("https://api.example.test", "latest_rates"),
)
.await
.unwrap();
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id = preview.job_id.clone();
let server = spawn_admin_api(app).await;
let client = authorized_client(&server).await;
let url = format!("{}/imports/openapi/{}/plans", server.as_ref(), job_id);
let body = json!({
"selection_mode": "full",
"selected_operation_keys": [],
"decisions": [{
"operation_key": "GET /v2/latest",
"action": "create",
}]
});
let ru = client
.post(&url)
.header("accept-language", "ru")
.json(&body)
.send()
.await
.unwrap();
assert_eq!(ru.status(), reqwest::StatusCode::CONFLICT);
let ru_body: Value = ru.json().await.unwrap();
assert_eq!(
ru_body["error"]["context"]["error_code"],
"import_plan_name_conflict"
);
assert_eq!(
ru_body["error"]["context"]["recovery"],
"confirm_skip_rename_or_new_version"
);
assert!(
ru_body["error"]["message"]
.as_str()
.unwrap_or_default()
.contains("уже существует"),
"Russian session must receive Russian guidance: {ru_body:?}"
);
// No locale header keeps the exact English wording.
let en = client.post(&url).json(&body).send().await.unwrap();
assert_eq!(en.status(), reqwest::StatusCode::CONFLICT);
let en_body: Value = en.json().await.unwrap();
assert_eq!(
en_body["error"]["context"]["error_code"],
"import_plan_name_conflict"
);
assert_eq!(
en_body["error"]["message"],
"operation with name latest_rates already exists"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn legacy_create_localizes_expired_preview_by_accept_language() {
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_legacy_create_locale_expired");
let service = test_service(
registry.clone(),
storage_root.clone(),
test_auth_settings(),
test_secret_crypto(),
);
let app = build_test_app(registry.clone(), storage_root);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id = preview.job_id.clone();
// Expire the preview job so the legacy create route /imports/openapi/{id}/create
// rejects before any selection work.
sqlx::query("update import_jobs set expires_at = now() - interval '1 minute' where id = $1")
.bind(&job_id)
.execute(registry.pool())
.await
.unwrap();
let server = spawn_admin_api(app).await;
let client = authorized_client(&server).await;
let url = format!("{}/imports/openapi/{}/create", server.as_ref(), job_id);
let body = json!({ "selected_operation_keys": [] });
let ru = client
.post(&url)
.header("accept-language", "ru")
.json(&body)
.send()
.await
.unwrap();
assert_eq!(ru.status(), reqwest::StatusCode::BAD_REQUEST);
let ru_body: Value = ru.json().await.unwrap();
assert_eq!(ru_body["error"]["code"], "validation_error");
assert!(
ru_body["error"].get("context").is_none(),
"legacy expired-preview validation keeps no context: {ru_body:?}"
);
assert!(
ru_body["error"]["message"]
.as_str()
.unwrap_or_default()
.contains("истёк"),
"Russian session must receive Russian guidance: {ru_body:?}"
);
// No locale header keeps the exact English wording.
let en = client.post(&url).json(&body).send().await.unwrap();
assert_eq!(en.status(), reqwest::StatusCode::BAD_REQUEST);
let en_body: Value = en.json().await.unwrap();
assert_eq!(en_body["error"]["code"], "validation_error");
assert_eq!(en_body["error"]["message"], "import preview has expired");
}
@@ -0,0 +1,170 @@
use admin_api::{
error::ApiError,
service::{
AuthProfilePayload, OpenApiImportPlanCreatePayload, OpenApiImportPlanDecision,
OpenApiUpload, OpenApiUploadLocale, SecretPayload,
},
};
use axum::response::IntoResponse;
use crank_core::{
ApiKeyHeaderAuthConfig, AuthConfig, AuthKind, AuthProfileId, OperationId, SecretId, SecretKind,
Workspace, WorkspaceId, WorkspaceStatus,
};
use crank_registry::{
CreateWorkspaceRequest, FinishImportJobRequest, ImportJobId, ImportJobStatus,
};
use serde_json::{Value, json};
use serial_test::serial;
use time::OffsetDateTime;
use super::super::common::*;
const OPENAPI_SINGLE: &str = r#"
openapi: 3.0.3
info:
title: Frankfurter API
servers:
- url: https://api.frankfurter.dev
paths:
/v2/latest:
get:
operationId: latestRates
summary: Получить последние курсы валют
tags: [currency]
parameters:
- name: base
in: query
required: true
schema: { type: string }
responses:
'200':
description: OK
content:
application/json:
schema:
type: object
properties:
base: { type: string }
rates:
type: object
"#;
const OPENAPI_TWO_OPS: &str = r#"
openapi: 3.0.3
info: { title: Two Operations }
servers: [{ url: https://api.example.test }]
paths:
/alpha:
get:
operationId: alpha
responses: { '200': { description: ok } }
/beta:
get:
operationId: betaOp
responses: { '200': { description: ok } }
"#;
const OPENAPI_GLOBAL_BLOCKER: &str = r#"
openapi: 3.0.3
info: { title: Global blocker }
servers: [{ url: https://api.example.test }]
paths:
/valid:
get:
responses: { '200': { description: ok } }
/broken: not-a-path-item
"#;
fn upload(document: &str) -> OpenApiUpload {
OpenApiUpload {
bytes: document.as_bytes().to_vec(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
}
}
fn preview_operation_keys(
preview: &admin_api::service::OpenApiImportPreviewResponse,
) -> Vec<String> {
let mut keys = preview
.preview
.groups
.iter()
.flat_map(|group| &group.operations)
.map(|operation| operation.key.clone())
.collect::<Vec<_>>();
keys.sort();
keys
}
fn decision(
key: &str,
action: &str,
target: Option<&str>,
name: Option<&str>,
auth: Option<&str>,
) -> OpenApiImportPlanDecision {
OpenApiImportPlanDecision {
operation_key: key.to_owned(),
action: action.to_owned(),
target_operation_id: target.map(ToOwned::to_owned),
confirmed_name: name.map(ToOwned::to_owned),
auth_profile_id: auth.map(ToOwned::to_owned),
security_alternative_index: None,
}
}
fn plan_payload(
selection_mode: &str,
selected: Vec<String>,
decisions: Vec<OpenApiImportPlanDecision>,
) -> OpenApiImportPlanCreatePayload {
OpenApiImportPlanCreatePayload {
selection_mode: selection_mode.to_owned(),
selected_operation_keys: selected,
server_url: None,
decisions,
}
}
fn public_error_context(error: &ApiError) -> Option<&Value> {
match error {
ApiError::Unauthorized { context, .. }
| ApiError::Forbidden { context, .. }
| ApiError::Validation { context, .. }
| ApiError::Unprocessable { context, .. }
| ApiError::NotFound { context, .. }
| ApiError::Conflict { context, .. }
| ApiError::PayloadTooLarge { context, .. }
| ApiError::PreconditionRequired { context, .. }
| ApiError::RateLimited { context, .. }
| ApiError::Internal { context, .. } => context.as_ref(),
}
}
fn assert_error_code(error: &ApiError, expected_code: &str) {
assert_eq!(
public_error_context(error)
.and_then(|context| context.get("error_code"))
.and_then(Value::as_str),
Some(expected_code),
"unexpected API error: {error:?}"
);
}
/// Asserts the rendered HTTP status of a rejection without private accessors.
fn assert_http_status(error: ApiError, expected: axum::http::StatusCode) {
assert_eq!(
error.into_response().status(),
expected,
"the rendered status must match the public contract"
);
}
mod creation;
mod excluded_names;
mod locale;
mod route_get;
pub(super) use creation::OPENAPI_SINGLE_SECURITY;
mod security_availability;
mod security_binding;
mod validation;
@@ -0,0 +1,87 @@
use super::*;
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn persisted_plan_get_requires_owner_and_reports_catalog_drift() {
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_plan_get_route");
let service = test_service(
registry.clone(),
storage_root.clone(),
test_auth_settings(),
test_secret_crypto(),
);
let workspace = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let plan = service
.create_openapi_import_plan(&workspace, &job_id, plan_payload("full", vec![], vec![]))
.await
.unwrap();
let plan_id = plan.plan_reference.clone();
let plan_digest = plan.plan_digest.clone();
let foreign_workspace = WorkspaceId::new("ws_plan_get_foreign");
let now = OffsetDateTime::now_utc();
registry
.create_workspace(CreateWorkspaceRequest {
workspace: &Workspace {
id: foreign_workspace.clone(),
slug: "ws-plan-get-foreign".to_owned(),
display_name: "Foreign plan workspace".to_owned(),
status: WorkspaceStatus::Active,
settings: json!({}),
created_at: now,
updated_at: now,
},
})
.await
.unwrap();
let server = spawn_admin_api(build_test_app(registry, storage_root)).await;
let client = authorized_client(&server).await;
let url = format!("{server}/imports/openapi/plans/{plan_id}");
let anonymous = reqwest::Client::new().get(&url).send().await.unwrap();
assert_eq!(anonymous.status(), reqwest::StatusCode::UNAUTHORIZED);
let foreign = client
.get(url.replace("ws_default", foreign_workspace.as_str()))
.send()
.await
.unwrap();
assert_eq!(foreign.status(), reqwest::StatusCode::FORBIDDEN);
let current = client.get(&url).send().await.unwrap();
assert_eq!(current.status(), reqwest::StatusCode::OK);
let current: Value = current.json().await.unwrap();
assert_eq!(current["plan_reference"], plan_id);
assert_eq!(current["plan_digest"], plan_digest);
assert_eq!(current["revalidation_status"], "current");
assert_eq!(current["revalidation_required"], false);
assert!(
service
.list_operations(&workspace)
.await
.unwrap()
.is_empty()
);
let upstream = spawn_upstream_server().await;
service
.create_operation(
&workspace,
test_operation_payload(&upstream, "plan_get_catalog_drift"),
)
.await
.unwrap();
let stale = client.get(&url).send().await.unwrap();
assert_eq!(stale.status(), reqwest::StatusCode::OK);
let stale: Value = stale.json().await.unwrap();
assert_eq!(stale["plan_reference"], plan_id);
assert_eq!(stale["plan_digest"], plan_digest);
assert_eq!(stale["revalidation_status"], "stale");
assert_eq!(stale["revalidation_required"], true);
assert_eq!(service.list_operations(&workspace).await.unwrap().len(), 1);
}
@@ -0,0 +1,292 @@
use super::*;
const OPENAPI_SECURITY_BINDING: &str = r#"
openapi: 3.0.3
info: { title: Security binding availability, version: '1' }
servers: [{ url: https://api.example.test }]
components:
securitySchemes:
Key: { type: apiKey, in: header, name: X-Api-Key }
Bearer: { type: http, scheme: bearer }
paths:
/v2/latest:
get:
operationId: latestRates
security: [{ Key: [] }, { Bearer: [] }]
responses: { '200': { description: ok } }
"#;
fn security_upload() -> OpenApiUpload {
OpenApiUpload {
bytes: OPENAPI_SECURITY_BINDING.as_bytes().to_vec(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
}
}
fn binding_decision(auth_profile_id: &str) -> OpenApiImportPlanDecision {
let mut binding = decision(
"GET /v2/latest",
"create",
None,
None,
Some(auth_profile_id),
);
binding.security_alternative_index = Some(0);
binding
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn security_binding_refuses_foreign_and_unavailable_auth_material_before_draft() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_plan_security_availability"),
test_auth_settings(),
test_secret_crypto(),
);
let primary = WorkspaceId::new("ws_default");
let foreign = WorkspaceId::new("ws_security_foreign");
let created_at = OffsetDateTime::now_utc();
registry
.create_workspace(CreateWorkspaceRequest {
workspace: &Workspace {
id: foreign.clone(),
slug: "ws-security-foreign".to_owned(),
display_name: "Foreign security workspace".to_owned(),
status: WorkspaceStatus::Active,
settings: json!({}),
created_at,
updated_at: created_at,
},
})
.await
.unwrap();
let foreign_canary = "foreign-security-profile-canary";
let foreign_secret = service
.create_secret(
&foreign,
None,
SecretPayload {
name: "foreign-security-secret".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": foreign_canary }),
},
None,
)
.await
.unwrap();
let foreign_profile = service
.create_auth_profile(
&foreign,
AuthProfilePayload {
name: "foreign-security-profile-name".to_owned(),
kind: AuthKind::ApiKeyHeader,
config: AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
header_name: "X-Api-Key".to_owned(),
secret_id: SecretId::new(foreign_secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
// A foreign profile is absent from the current workspace's advertised
// choices and submission fails with a generic workspace-safe error.
let preview = service
.preview_openapi_import(&primary, security_upload())
.await
.unwrap();
let preview_text = serde_json::to_string(&preview).unwrap();
for private_value in [
foreign_profile.id.as_str(),
foreign_profile.name.as_str(),
foreign_secret.id.as_str(),
foreign_canary,
] {
assert!(
!preview_text.contains(private_value),
"foreign profile metadata appeared in preview choices"
);
}
assert!(preview.security_profile_choices.iter().all(|choice| {
choice
.profiles
.iter()
.all(|profile| profile.id != foreign_profile.id.as_str())
}));
let job_id: ImportJobId = preview.job_id.as_str().into();
let foreign_error = service
.create_openapi_import_plan(
&primary,
&job_id,
plan_payload(
"full",
vec![],
vec![binding_decision(foreign_profile.id.as_str())],
),
)
.await
.expect_err("a profile from another workspace must not bind");
assert_error_code(&foreign_error, "import_plan_auth_unavailable");
let foreign_error_text = format!("{foreign_error:?}");
assert_http_status(foreign_error, axum::http::StatusCode::UNPROCESSABLE_ENTITY);
for private_value in [
foreign_profile.id.as_str(),
foreign_profile.name.as_str(),
foreign_secret.id.as_str(),
foreign_canary,
] {
assert!(
!foreign_error_text.contains(private_value),
"foreign profile or secret metadata leaked: {foreign_error_text}"
);
}
// A previously valid local profile whose Secret is disabled is removed
// from choices and cannot be used in a newly confirmed ImportPlan.
let disabled_canary = "disabled-security-secret-canary";
let disabled_secret = service
.create_secret(
&primary,
None,
SecretPayload {
name: "disabled-security-secret".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": disabled_canary }),
},
None,
)
.await
.unwrap();
let disabled_profile = service
.create_auth_profile(
&primary,
AuthProfilePayload {
name: "disabled-security-profile".to_owned(),
kind: AuthKind::ApiKeyHeader,
config: AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
header_name: "X-Api-Key".to_owned(),
secret_id: SecretId::new(disabled_secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
sqlx::query(
"update secrets set status = 'disabled', updated_at = now() where workspace_id = $1 and id = $2",
)
.bind(primary.as_str())
.bind(disabled_secret.id.as_str())
.execute(registry.pool())
.await
.unwrap();
let preview = service
.preview_openapi_import(&primary, security_upload())
.await
.unwrap();
assert!(preview.security_profile_choices.iter().all(|choice| {
choice
.profiles
.iter()
.all(|profile| profile.id != disabled_profile.id.as_str())
}));
let job_id: ImportJobId = preview.job_id.as_str().into();
let disabled_error = service
.create_openapi_import_plan(
&primary,
&job_id,
plan_payload(
"full",
vec![],
vec![binding_decision(disabled_profile.id.as_str())],
),
)
.await
.expect_err("a disabled linked Secret must reject the profile binding");
assert_error_code(&disabled_error, "secret_not_active");
let disabled_error_text = format!("{disabled_error:?}");
assert!(!disabled_error_text.contains(disabled_canary));
// A profile whose active Secret has no stored current version is equally
// unavailable. Direct SQL models the broken persisted reference while
// retaining the real Admin preview and plan validation paths.
let missing_version_canary = "missing-version-security-canary";
let missing_version_secret = service
.create_secret(
&primary,
None,
SecretPayload {
name: "missing-version-security-secret".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": missing_version_canary }),
},
None,
)
.await
.unwrap();
let missing_version_profile = service
.create_auth_profile(
&primary,
AuthProfilePayload {
name: "missing-version-security-profile".to_owned(),
kind: AuthKind::ApiKeyHeader,
config: AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
header_name: "X-Api-Key".to_owned(),
secret_id: SecretId::new(missing_version_secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
sqlx::query("delete from secret_versions where secret_id = $1 and version = 1")
.bind(missing_version_secret.id.as_str())
.execute(registry.pool())
.await
.unwrap();
let preview = service
.preview_openapi_import(&primary, security_upload())
.await
.unwrap();
assert!(preview.security_profile_choices.iter().all(|choice| {
choice
.profiles
.iter()
.all(|profile| profile.id != missing_version_profile.id.as_str())
}));
let job_id: ImportJobId = preview.job_id.as_str().into();
let missing_version_error = service
.create_openapi_import_plan(
&primary,
&job_id,
plan_payload(
"full",
vec![],
vec![binding_decision(missing_version_profile.id.as_str())],
),
)
.await
.expect_err("a Secret without a current version must reject the profile binding");
assert_error_code(&missing_version_error, "operation_auth_profile_invalid");
let missing_version_error_text = format!("{missing_version_error:?}");
for private_value in [
missing_version_profile.id.as_str(),
missing_version_profile.name.as_str(),
missing_version_secret.id.as_str(),
missing_version_canary,
] {
assert!(
!missing_version_error_text.contains(private_value),
"missing-version Secret metadata leaked: {missing_version_error_text}"
);
}
assert!(
service.list_operations(&primary).await.unwrap().is_empty(),
"no unavailable profile binding may create a Draft"
);
}
@@ -0,0 +1,770 @@
use super::*;
const OPENAPI_SINGLE_PUBLIC: &str = r#"
openapi: 3.0.3
info: { title: Public import, version: '1' }
servers: [{ url: https://api.example.test }]
paths:
/v2/latest:
get:
operationId: latestRates
responses: { '200': { description: ok } }
"#;
const OPENAPI_SINGLE_EXPLICIT_NO_AUTH: &str = r#"
openapi: 3.0.3
info: { title: Explicit no auth import, version: '1' }
servers: [{ url: https://api.example.test }]
paths:
/v2/latest:
get:
operationId: latestRates
security: []
responses: { '200': { description: ok } }
"#;
const OPENAPI_BASIC_AND_QUERY_SECURITY: &str = r#"
openapi: 3.0.3
info: { title: Basic and query import, version: '1' }
servers: [{ url: https://api.example.test }]
components:
securitySchemes:
Basic: { type: http, scheme: basic }
QueryKey: { type: apiKey, in: query, name: access_token }
paths:
/v2/basic:
get:
operationId: basicRates
security: [{ Basic: [] }, { QueryKey: [] }]
responses: { '200': { description: ok } }
/v2/query:
get:
operationId: queryRates
security: [{ Basic: [] }, { QueryKey: [] }]
responses: { '200': { description: ok } }
"#;
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn auth_profile_references_are_validated_stored_and_inherited() {
let registry = test_registry().await;
let upstream_base_url = spawn_upstream_server().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_auth"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let secret_token = "plan-secret-canary-2-13";
let secret = service
.create_secret(
&workspace_id,
None,
SecretPayload {
name: "plan-auth-token".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": secret_token }),
},
None,
)
.await
.unwrap();
let auth_profile = service
.create_auth_profile(
&workspace_id,
AuthProfilePayload {
name: "plan-auth-profile".to_owned(),
kind: AuthKind::ApiKeyHeader,
config: AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
header_name: "X-Api-Key".to_owned(),
secret_id: SecretId::new(secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
let bearer_secret = service
.create_secret(
&workspace_id,
None,
SecretPayload {
name: "plan-bearer-token".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": "bearer-choice-canary" }),
},
None,
)
.await
.unwrap();
let bearer_profile = service
.create_auth_profile(
&workspace_id,
AuthProfilePayload {
name: "plan-bearer-profile".to_owned(),
kind: AuthKind::Bearer,
config: AuthConfig::Bearer(crank_core::BearerAuthConfig {
header_name: "Authorization".to_owned(),
secret_id: SecretId::new(bearer_secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE_SECURITY))
.await
.unwrap();
assert_eq!(preview.preview.groups[0].operations[0].status, "unresolved");
let selectable = preview
.security_profile_choices
.iter()
.find(|choice| choice.operation_key == "GET /v2/latest" && choice.alternative_index == 0)
.expect("preview must expose choices for supported security alternatives");
assert!(selectable.profiles.iter().any(|choice| {
choice.id == auth_profile.id.as_str() && choice.kind == AuthKind::ApiKeyHeader
}));
assert!(
selectable
.profiles
.iter()
.all(|choice| { choice.id != bearer_profile.id.as_str() })
);
let bearer_choice = preview
.security_profile_choices
.iter()
.find(|choice| choice.operation_key == "GET /v2/latest" && choice.alternative_index == 1)
.expect("preview must expose profile choices for the second OR alternative");
assert!(bearer_choice.profiles.iter().any(|choice| {
choice.id == bearer_profile.id.as_str() && choice.kind == AuthKind::Bearer
}));
assert!(
bearer_choice
.profiles
.iter()
.all(|choice| { choice.id != auth_profile.id.as_str() })
);
let job_id: ImportJobId = preview.job_id.as_str().into();
let mut auth_decision = decision(
"GET /v2/latest",
"create",
None,
None,
Some(auth_profile.id.as_str()),
);
auth_decision.security_alternative_index = Some(0);
let plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload("full", vec![], vec![auth_decision]),
)
.await
.unwrap();
let stored = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
assert_eq!(
stored.payload["candidates"][0]["operation"]["execution_config"]["auth_profile_ref"],
auth_profile.id.as_str()
);
assert_eq!(
stored.payload["candidates"][0]["decision"]["security_alternative_index"],
0
);
// Only the reference survives: no secret material anywhere in the plan.
assert!(!stored.payload.to_string().contains(secret_token));
assert_eq!(
plan.candidates.first().unwrap().auth_profile_id.as_deref(),
Some(auth_profile.id.as_str())
);
let mut bearer_decision = decision(
"GET /v2/latest",
"create",
None,
None,
Some(bearer_profile.id.as_str()),
);
bearer_decision.security_alternative_index = Some(1);
let bearer_plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload("full", vec![], vec![bearer_decision]),
)
.await
.unwrap();
let stored_bearer = registry
.get_import_plan(&workspace_id, &bearer_plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
assert_eq!(
stored_bearer.payload["candidates"][0]["operation"]["execution_config"]["auth_profile_ref"],
bearer_profile.id.as_str()
);
assert_eq!(
stored_bearer.payload["candidates"][0]["decision"]["security_alternative_index"],
1
);
assert!(
!stored_bearer
.payload
.to_string()
.contains("bearer-choice-canary")
);
// An unknown profile reference fails closed in the workspace scope check.
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE_SECURITY))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let error = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"full",
vec![],
vec![decision(
"GET /v2/latest",
"create",
None,
None,
Some("auth_missing_profile"),
)],
),
)
.await
.expect_err("an unknown auth profile reference must be rejected");
assert_error_code(&error, "import_plan_auth_unavailable");
assert_http_status(error, axum::http::StatusCode::UNPROCESSABLE_ENTITY);
// `new_version` without an explicit choice inherits the target's ref.
let existing = service
.create_operation(&workspace_id, {
let mut payload = test_operation_payload(&upstream_base_url, "latest_rates");
payload.execution_config.auth_profile_ref =
Some(AuthProfileId::new(auth_profile.id.as_str()));
payload
})
.await
.expect("an existing operation with the candidate name");
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE_SECURITY))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"full",
vec![],
vec![decision(
"GET /v2/latest",
"new_version",
Some(existing.operation_id.as_str()),
None,
None,
)],
),
)
.await
.unwrap();
let stored = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
let candidate = &stored.payload["candidates"][0];
assert_eq!(
candidate["decision"]["auth_profile_id"],
auth_profile.id.as_str(),
"the inherited target reference is reflected in the candidate summary"
);
assert_eq!(
candidate["operation"]["execution_config"]["auth_profile_ref"],
auth_profile.id.as_str(),
"the inherited target reference must be retained in the snapshot"
);
assert!(!stored.payload.to_string().contains(secret_token));
let public_preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE_PUBLIC))
.await
.unwrap();
let public_job_id: ImportJobId = public_preview.job_id.as_str().into();
let public_plan = service
.create_openapi_import_plan(
&workspace_id,
&public_job_id,
plan_payload(
"full",
vec![],
vec![decision(
"GET /v2/latest",
"new_version",
Some(existing.operation_id.as_str()),
None,
None,
)],
),
)
.await
.expect("a no-security source may inherit the target's existing profile");
let public_stored = registry
.get_import_plan(&workspace_id, &public_plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
assert_eq!(
public_stored.payload["candidates"][0]["auth_requirement"]["kind"], "unconstrained",
"no source security declaration is represented explicitly for transactional Apply"
);
let report = service
.apply_openapi_import_plan(
&workspace_id,
&crank_registry::ImportPlanId::new(public_plan.plan_reference.clone()),
admin_api::service::OpenApiImportPlanApplyPayload {
plan_digest: public_plan.plan_digest.clone(),
idempotency_key: "new-version-inherited-public".to_owned(),
},
)
.await
.expect("Apply must retain profile and Secret transactional validation");
assert_eq!(
report.status,
crank_registry::ImportPlanApplyStatus::Applied
);
assert_eq!(
report.outcomes[0].outcome,
crank_registry::ImportPlanCandidateOutcome::Versioned
);
assert_eq!(report.outcomes[0].version, Some(2));
let operation = service
.list_operations(&workspace_id)
.await
.unwrap()
.into_iter()
.find(|operation| operation.id == existing.operation_id.as_str())
.unwrap();
assert_eq!(operation.current_draft_version, 2);
let explicit_no_auth_preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE_EXPLICIT_NO_AUTH))
.await
.unwrap();
let explicit_no_auth_job_id: ImportJobId = explicit_no_auth_preview.job_id.as_str().into();
let incompatible_profile_decision = decision(
"GET /v2/latest",
"new_version",
Some(existing.operation_id.as_str()),
None,
Some(auth_profile.id.as_str()),
);
let error = service
.create_openapi_import_plan(
&workspace_id,
&explicit_no_auth_job_id,
plan_payload("full", vec![], vec![incompatible_profile_decision]),
)
.await
.expect_err("explicit Auth Profile stays incompatible with security: []");
assert_error_code(&error, "import_plan_auth_incompatible");
let explicit_no_auth_plan = service
.create_openapi_import_plan(
&workspace_id,
&explicit_no_auth_job_id,
plan_payload(
"full",
vec![],
vec![decision(
"GET /v2/latest",
"new_version",
Some(existing.operation_id.as_str()),
None,
None,
)],
),
)
.await
.expect("an explicit empty security requirement clears inherited auth");
let no_auth_stored = registry
.get_import_plan(
&workspace_id,
&explicit_no_auth_plan.plan_reference.as_str().into(),
)
.await
.unwrap()
.unwrap();
assert!(no_auth_stored.payload["candidates"][0]["operation"]["execution_config"]
["auth_profile_ref"]
.is_null());
let no_auth_report = service
.apply_openapi_import_plan(
&workspace_id,
&crank_registry::ImportPlanId::new(explicit_no_auth_plan.plan_reference.clone()),
admin_api::service::OpenApiImportPlanApplyPayload {
plan_digest: explicit_no_auth_plan.plan_digest.clone(),
idempotency_key: "new-version-explicit-no-auth".to_owned(),
},
)
.await
.expect("explicit no-auth new_version applies without inherited credentials");
assert_eq!(
no_auth_report.outcomes[0].outcome,
crank_registry::ImportPlanCandidateOutcome::Versioned
);
assert_eq!(no_auth_report.outcomes[0].version, Some(3));
let operation = service
.list_operations(&workspace_id)
.await
.unwrap()
.into_iter()
.find(|operation| operation.id == existing.operation_id.as_str())
.unwrap();
assert_eq!(operation.current_draft_version, 3);
let operation_id = OperationId::new(existing.operation_id.clone());
let version = registry
.get_operation_version(&workspace_id, &operation_id, 3)
.await
.unwrap()
.unwrap();
assert!(version.snapshot.execution_config.auth_profile_ref.is_none());
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn basic_and_query_profiles_bind_to_matching_security_alternatives_and_apply() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_basic_query_auth"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let username_secret = service
.create_secret(
&workspace_id,
None,
SecretPayload {
name: "basic-username".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": "plan-user" }),
},
None,
)
.await
.unwrap();
let password_secret = service
.create_secret(
&workspace_id,
None,
SecretPayload {
name: "basic-password".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": "plan-password-canary" }),
},
None,
)
.await
.unwrap();
let basic_profile = service
.create_auth_profile(
&workspace_id,
AuthProfilePayload {
name: "basic-profile".to_owned(),
kind: AuthKind::Basic,
config: AuthConfig::Basic(crank_core::BasicAuthConfig {
username_secret_id: SecretId::new(username_secret.id.as_str()),
password_secret_id: SecretId::new(password_secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
let query_secret = service
.create_secret(
&workspace_id,
None,
SecretPayload {
name: "query-key".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": "query-key-canary" }),
},
None,
)
.await
.unwrap();
let query_profile = service
.create_auth_profile(
&workspace_id,
AuthProfilePayload {
name: "query-profile".to_owned(),
kind: AuthKind::ApiKeyQuery,
config: AuthConfig::ApiKeyQuery(crank_core::ApiKeyQueryAuthConfig {
param_name: "access_token".to_owned(),
secret_id: SecretId::new(query_secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
let incompatible_secret = service
.create_secret(
&workspace_id,
None,
SecretPayload {
name: "incompatible-token".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": "incompatible-canary" }),
},
None,
)
.await
.unwrap();
let incompatible_profile = service
.create_auth_profile(
&workspace_id,
AuthProfilePayload {
name: "incompatible-bearer-profile".to_owned(),
kind: AuthKind::Bearer,
config: AuthConfig::Bearer(crank_core::BearerAuthConfig {
header_name: "Authorization".to_owned(),
secret_id: SecretId::new(incompatible_secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_BASIC_AND_QUERY_SECURITY))
.await
.unwrap();
for operation_key in ["GET /v2/basic", "GET /v2/query"] {
let basic_alternative = preview
.security_profile_choices
.iter()
.find(|choice| choice.operation_key == operation_key && choice.alternative_index == 0)
.expect("Basic alternative must be represented in preview");
assert!(basic_alternative.profiles.iter().any(|choice| {
choice.id == basic_profile.id.as_str() && choice.kind == AuthKind::Basic
}));
assert!(
basic_alternative
.profiles
.iter()
.all(|choice| choice.id != query_profile.id.as_str())
);
assert!(
basic_alternative
.profiles
.iter()
.all(|choice| choice.id != incompatible_profile.id.as_str())
);
let query_alternative = preview
.security_profile_choices
.iter()
.find(|choice| choice.operation_key == operation_key && choice.alternative_index == 1)
.expect("query alternative must be represented in preview");
assert!(query_alternative.profiles.iter().any(|choice| {
choice.id == query_profile.id.as_str() && choice.kind == AuthKind::ApiKeyQuery
}));
assert!(
query_alternative
.profiles
.iter()
.all(|choice| choice.id != basic_profile.id.as_str())
);
assert!(
query_alternative
.profiles
.iter()
.all(|choice| choice.id != incompatible_profile.id.as_str())
);
}
let job_id: ImportJobId = preview.job_id.as_str().into();
let mut basic_decision = decision(
"GET /v2/basic",
"create",
None,
None,
Some(basic_profile.id.as_str()),
);
basic_decision.security_alternative_index = Some(0);
let basic_plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"partial",
vec!["GET /v2/basic".to_owned()],
vec![basic_decision],
),
)
.await
.unwrap();
assert_eq!(basic_plan.counts.actionable, 1);
let basic_candidate = basic_plan
.candidates
.iter()
.find(|candidate| candidate.key == "GET /v2/basic")
.unwrap();
assert_eq!(
basic_candidate.auth_profile_id.as_deref(),
Some(basic_profile.id.as_str())
);
let mut query_decision = decision(
"GET /v2/query",
"create",
None,
None,
Some(query_profile.id.as_str()),
);
query_decision.security_alternative_index = Some(1);
let query_plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"partial",
vec!["GET /v2/query".to_owned()],
vec![query_decision.clone()],
),
)
.await
.unwrap();
assert_eq!(query_plan.counts.actionable, 1);
let query_candidate = query_plan
.candidates
.iter()
.find(|candidate| candidate.key == "GET /v2/query")
.unwrap();
assert_eq!(
query_candidate.auth_profile_id.as_deref(),
Some(query_profile.id.as_str())
);
for (index, (plan, expected_profile, idempotency_key)) in [
(
&basic_plan,
basic_profile.id.as_str(),
"apply-basic-profile",
),
(
&query_plan,
query_profile.id.as_str(),
"apply-query-profile",
),
]
.into_iter()
.enumerate()
{
let fresh_plan;
let plan = if index == 1 {
let stale = service
.apply_openapi_import_plan(
&workspace_id,
&crank_registry::ImportPlanId::new(plan.plan_reference.clone()),
admin_api::service::OpenApiImportPlanApplyPayload {
plan_digest: plan.plan_digest.clone(),
idempotency_key: "stale-query-profile".to_owned(),
},
)
.await
.expect_err("the earlier query plan is stale after catalog mutation");
assert_error_code(&stale, "import_plan_fingerprint_stale");
let refreshed = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_BASIC_AND_QUERY_SECURITY))
.await
.unwrap();
fresh_plan = service
.create_openapi_import_plan(
&workspace_id,
&refreshed.job_id.as_str().into(),
plan_payload(
"partial",
vec!["GET /v2/query".to_owned()],
vec![query_decision.clone()],
),
)
.await
.unwrap();
&fresh_plan
} else {
plan
};
let report = service
.apply_openapi_import_plan(
&workspace_id,
&crank_registry::ImportPlanId::new(plan.plan_reference.clone()),
admin_api::service::OpenApiImportPlanApplyPayload {
plan_digest: plan.plan_digest.clone(),
idempotency_key: idempotency_key.to_owned(),
},
)
.await
.unwrap();
assert_eq!(
report.status,
crank_registry::ImportPlanApplyStatus::Applied
);
let operation_id = OperationId::new(report.outcomes[0].operation_id.clone().unwrap());
let version = registry
.get_operation_version(&workspace_id, &operation_id, 1)
.await
.unwrap()
.unwrap();
assert_eq!(
version
.snapshot
.execution_config
.auth_profile_ref
.as_ref()
.map(|profile_id| profile_id.as_str()),
Some(expected_profile)
);
}
let basic_stored = registry
.get_import_plan(&workspace_id, &basic_plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
assert!(
!basic_stored
.payload
.to_string()
.contains("plan-password-canary")
);
let query_stored = registry
.get_import_plan(&workspace_id, &query_plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
assert!(
!query_stored
.payload
.to_string()
.contains("query-key-canary")
);
}
@@ -0,0 +1,350 @@
use super::*;
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn preview_rejects_candidate_2001_without_truncation_or_operations() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_preview_candidate_limit"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace = WorkspaceId::new("ws_default");
let mut document = String::from(
"openapi: 3.0.3\ninfo: { title: Limit }\nservers: [{ url: https://api.example.test }]\npaths:\n",
);
for index in 0..2001 {
document.push_str(&format!(" /p{index}:\n get:\n operationId: op{index}\n responses: {{ '200': {{ description: ok }} }}\n"));
}
let error = service
.preview_openapi_import(&workspace, upload(&document))
.await
.expect_err("candidate 2001 must be rejected as a whole");
assert_error_code(&error, "openapi_preview_too_many_candidates");
assert!(
service
.list_operations(&workspace)
.await
.unwrap()
.is_empty()
);
let active_sources: i64 = sqlx::query_scalar(
"select count(*) from artifact_sources where workspace_id = $1 and lifecycle = 'active'",
)
.bind(workspace.as_str())
.fetch_one(registry.pool())
.await
.unwrap();
assert_eq!(active_sources, 0);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn partial_plan_rejects_selected_blocker_before_persistence() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_partial_blocker"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_GLOBAL_BLOCKER))
.await
.unwrap();
assert_eq!(preview.preview.groups[0].operations[0].status, "blocked");
let job_id: ImportJobId = preview.job_id.as_str().into();
let key = preview.preview.groups[0].operations[0].key.clone();
let error = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload("partial", vec![key], vec![]),
)
.await
.expect_err("blocked partial selection must be rejected");
assert_error_code(&error, "import_plan_partial_blocked");
assert!(
service
.list_operations(&workspace_id)
.await
.unwrap()
.is_empty()
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn explicit_targets_are_checked_even_when_the_candidate_is_blocked() {
let registry = test_registry().await;
let upstream_base_url = spawn_upstream_server().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_blocked_target"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_GLOBAL_BLOCKER))
.await
.unwrap();
let blocker_code = preview
.preview
.findings
.iter()
.find(|finding| finding.severity == crank_import::rest::ImportFindingSeverity::Error)
.map(|finding| finding.code.clone())
.expect("the fixture produces a global error finding");
let candidate = &preview.preview.groups[0].operations[0];
let job_id: ImportJobId = preview.job_id.as_str().into();
// A mismatched/unknown explicit target is a request error even though
// the candidate is already blocked by the preview.
let error = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"full",
vec![],
vec![decision(
&candidate.key,
"skip",
Some("op_does_not_exist"),
None,
None,
)],
),
)
.await
.expect_err("an unknown target is a request error even for a blocked candidate");
assert_error_code(&error, "import_plan_target_invalid");
assert_http_status(error, axum::http::StatusCode::BAD_REQUEST);
// A resolvable exact target is recorded while the candidate stays
// blocked with its bounded redacted reason.
let existing = service
.create_operation(
&workspace_id,
test_operation_payload(&upstream_base_url, &candidate.draft.name),
)
.await
.unwrap();
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_GLOBAL_BLOCKER))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"full",
vec![],
vec![decision(
&candidate.key,
"skip",
Some(existing.operation_id.as_str()),
None,
None,
)],
),
)
.await
.expect("a valid explicit target is accepted for a blocked candidate");
let stored = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
let candidate = &stored.payload["candidates"][0];
assert_eq!(candidate["state"], "blocked");
assert_eq!(candidate["reason"], blocker_code);
assert_eq!(
candidate["target"]["operation_id"],
json!(existing.operation_id)
);
assert!(
candidate.get("operation").is_none(),
"a blocked candidate never stores draft material"
);
assert!(service.list_operations(&workspace_id).await.unwrap().len() <= 1);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn archived_rest_target_cannot_be_planned_for_new_version() {
let registry = test_registry().await;
let upstream_base_url = spawn_upstream_server().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_archived_target"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let existing = service
.create_operation(
&workspace_id,
test_operation_payload(&upstream_base_url, "latest_rates"),
)
.await
.unwrap();
registry
.archive_operation(
&workspace_id,
&OperationId::new(existing.operation_id.clone()),
&time::OffsetDateTime::now_utc(),
)
.await
.unwrap();
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let error = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"full",
vec![],
vec![decision(
"GET /v2/latest",
"new_version",
Some(existing.operation_id.as_str()),
None,
None,
)],
),
)
.await
.expect_err("archived target cannot accept a new Draft Version");
assert_error_code(&error, "import_plan_target_invalid");
assert_http_status(error, axum::http::StatusCode::BAD_REQUEST);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn detached_dependency_snapshot_repreview_requires_without_a_plan() {
let app = axum::Router::new().route(
"/schema.yaml",
axum::routing::get(|| async {
"Result: { type: object, properties: { id: { type: string } } }"
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
let service = test_service_with_external_references(
registry.clone(),
test_storage_root("openapi_import_plan_dependency_stale"),
vec![format!("{origin}/")],
);
let workspace_id = WorkspaceId::new("ws_default");
let upload = OpenApiUpload {
bytes: format!(
r#"
openapi: 3.1.0
info: {{ title: External dependency }}
servers: [{{ url: https://api.example.test }}]
paths:
/items:
get:
operationId: listItems
responses:
'200':
description: ok
content:
application/json:
schema: {{ $ref: '{origin}/schema.yaml#/Result' }}
"#
)
.into_bytes(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
};
let preview = service
.preview_openapi_import(&workspace_id, upload)
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let job = registry
.get_import_job(&workspace_id, &job_id)
.await
.unwrap()
.unwrap();
let dependency_sources = job.preview_payload["dependencies"]
.as_array()
.cloned()
.unwrap();
assert!(
!dependency_sources.is_empty(),
"fixture must create a dependency"
);
// The plan is creatable while the stored snapshot is still active.
let fresh = service
.create_openapi_import_plan(&workspace_id, &job_id, plan_payload("full", vec![], vec![]))
.await
.expect("an active dependency snapshot must not block planning");
assert_eq!(
registry
.get_import_plan(&workspace_id, &fresh.plan_reference.as_str().into())
.await
.unwrap()
.unwrap()
.payload["dependencies"]
.as_array()
.unwrap()
.len(),
dependency_sources.len()
);
// Detach one stored snapshot: the same job now requires re-preview and
// no plan is created; the legacy job itself stays untouched.
let victim = &dependency_sources[0];
sqlx::query(
"update artifact_sources
set lifecycle = 'detached', updated_at = now(), detached_at = now()
where workspace_id = $1 and source_id = $2",
)
.bind(workspace_id.as_str())
.bind(victim["source_id"].as_str().unwrap())
.execute(registry.pool())
.await
.unwrap();
let error = service
.create_openapi_import_plan(&workspace_id, &job_id, plan_payload("full", vec![], vec![]))
.await
.expect_err("a detached dependency snapshot is re-preview material");
assert_error_code(&error, "import_dependency_verification_failed");
let context = public_error_context(&error).cloned().unwrap();
assert_eq!(context["repreview_required"], json!(true));
assert_http_status(error, axum::http::StatusCode::CONFLICT);
let job = registry
.get_import_job(&workspace_id, &job_id)
.await
.unwrap()
.unwrap();
assert_eq!(job.status, ImportJobStatus::Pending);
assert_eq!(job.error_text, None);
assert!(job.finished_at.is_none());
assert!(
service
.list_operations(&workspace_id)
.await
.unwrap()
.is_empty()
);
}
@@ -0,0 +1,142 @@
use super::*;
use admin_api::service::OpenApiImportPlanCreatePayload;
use std::fmt::Write as _;
const OPERATION_COUNT: usize = 2_000;
const MAX_UPLOAD_BYTES: usize = 256 * 1024;
const MAX_STORED_PLAN_BYTES: usize = 16 * 1024 * 1024;
fn large_openapi_document() -> String {
let mut document = String::from(
"openapi: 3.0.3\n\
info: { title: Large preview, version: '1' }\n\
servers: [{ url: 'https://api.example.test' }]\n\
paths:\n",
);
for index in 0..OPERATION_COUNT {
writeln!(
document,
" /p{index:04}:\n get:\n operationId: o{index:04}\n responses: {{ '200': {{ description: ok }} }}"
)
.unwrap();
}
document
}
#[tokio::test]
#[serial]
async fn previews_and_plans_two_thousand_operations_without_catalog_mutation() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_large_preview"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let document = large_openapi_document();
assert!(
document.len() <= MAX_UPLOAD_BYTES,
"generated document is {} bytes, over the 256 KiB upload limit",
document.len()
);
let preview = service
.preview_openapi_import(
&workspace_id,
OpenApiUpload {
bytes: document.into_bytes(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
},
)
.await
.expect("valid 2,000-operation OpenAPI document should preview");
let preview_candidates = preview
.preview
.groups
.iter()
.flat_map(|group| &group.operations)
.collect::<Vec<_>>();
assert_eq!(preview_candidates.len(), OPERATION_COUNT);
assert_eq!(preview_candidates[0].key, "GET /p0000");
assert_eq!(preview_candidates[OPERATION_COUNT - 1].key, "GET /p1999");
assert!(preview_candidates.iter().all(|candidate| {
candidate.status == "actionable"
&& candidate.method == crank_core::HttpMethod::Get
&& candidate.path.starts_with("/p")
}));
let job_id: crank_registry::ImportJobId = preview.job_id.as_str().into();
let plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
OpenApiImportPlanCreatePayload {
selection_mode: "full".to_owned(),
selected_operation_keys: Vec::new(),
server_url: None,
decisions: Vec::new(),
},
)
.await
.expect("full plan should include all 2,000 operations");
assert_eq!(plan.counts.selected, OPERATION_COUNT);
assert_eq!(plan.counts.actionable, OPERATION_COUNT);
assert_eq!(plan.counts.excluded, 0);
assert_eq!(plan.counts.blocked, 0);
assert_eq!(plan.candidates.len(), OPERATION_COUNT);
assert!(plan.candidates.iter().all(|candidate| {
candidate.state == "actionable" && candidate.action.as_deref() == Some("create")
}));
let plan_id = plan.plan_reference.as_str().into();
let stored = registry
.get_import_plan(&workspace_id, &plan_id)
.await
.unwrap()
.expect("full plan should be persisted and readable");
let stored_payload_bytes = serde_json::to_vec(&stored.payload).unwrap().len();
assert!(
stored_payload_bytes <= MAX_STORED_PLAN_BYTES,
"stored plan payload is {stored_payload_bytes} bytes, over 16 MiB"
);
let stored_candidates = stored.payload["candidates"]
.as_array()
.expect("stored plan contains its full candidate list");
assert_eq!(stored_candidates.len(), OPERATION_COUNT);
assert!(stored_candidates.iter().all(|candidate| {
candidate["state"] == "actionable" && candidate["decision"]["action"] == "create"
}));
assert_eq!(stored.payload["counts"]["selected"], OPERATION_COUNT);
assert_eq!(stored.payload["counts"]["actionable"], OPERATION_COUNT);
let revalidated = service
.revalidate_openapi_import_plan(&workspace_id, &plan_id)
.await
.expect("revalidating the unchanged plan should be read-only and current");
assert_eq!(revalidated.revalidation_status, "current");
assert!(!revalidated.revalidation_required);
assert_eq!(revalidated.counts.selected, OPERATION_COUNT);
assert_eq!(revalidated.counts.actionable, OPERATION_COUNT);
assert_eq!(revalidated.counts.excluded, 0);
assert_eq!(revalidated.counts.blocked, 0);
assert_eq!(revalidated.candidates.len(), OPERATION_COUNT);
let (operations, operation_versions) = sqlx::query_as::<_, (i64, i64)>(
"select
(select count(*) from operations where workspace_id = $1),
(select count(*) from operation_versions ov
join operations o on o.id = ov.operation_id where o.workspace_id = $1)",
)
.bind(workspace_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap();
assert_eq!(operations, 0, "preview and plan must not create operations");
assert_eq!(
operation_versions, 0,
"preview and plan must not create operation versions"
);
}
@@ -0,0 +1,262 @@
use super::*;
use admin_api::error::ApiError;
use crank_artifacts::MAX_ARTIFACT_BYTES;
use crank_core::HttpMethod;
#[derive(Debug, PartialEq, Eq)]
struct CatalogCounts {
operations: i64,
operation_versions: i64,
auth_profiles: i64,
agent_operation_bindings: i64,
}
async fn catalog_counts(
registry: &crank_registry::PostgresRegistry,
workspace_id: &WorkspaceId,
) -> CatalogCounts {
let (operations, operation_versions, auth_profiles, agent_operation_bindings) =
sqlx::query_as::<_, (i64, i64, i64, i64)>(
"select
(select count(*) from operations where workspace_id = $1),
(select count(*) from operation_versions ov
join operations o on o.id = ov.operation_id where o.workspace_id = $1),
(select count(*) from auth_profiles where workspace_id = $1),
(select count(*) from agent_operation_bindings b
join operations o on o.id = b.operation_id where o.workspace_id = $1)",
)
.bind(workspace_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap();
CatalogCounts {
operations,
operation_versions,
auth_profiles,
agent_operation_bindings,
}
}
fn upload(bytes: Vec<u8>) -> OpenApiUpload {
OpenApiUpload {
bytes,
mime_type: "application/json".to_owned(),
locale: OpenApiUploadLocale::En,
}
}
const PREVIEWABLE_DOCUMENT: &[u8] = br#"{
"openapi":"3.0.3",
"info":{"title":"Preview lifecycle","version":"1"},
"paths":{"/ready":{"get":{"responses":{"200":{"description":"ok"}}}}}
}"#;
async fn insert_malformed_auth_profile(
registry: &crank_registry::PostgresRegistry,
workspace_id: &WorkspaceId,
) {
sqlx::query(
"insert into auth_profiles
(id, workspace_id, name, kind, config_json, created_at, updated_at)
values ('auth_decode_failure', $1, 'decode-failure', 'bearer', 'null'::jsonb, now(), now())",
)
.bind(workspace_id.as_str())
.execute(registry.pool())
.await
.unwrap();
}
async fn insert_catalog_overflow(
registry: &crank_registry::PostgresRegistry,
workspace_id: &WorkspaceId,
) {
sqlx::query(
"insert into operations
(id, workspace_id, name, display_name, protocol, status, created_at, updated_at)
select 'op_catalog_' || g, $1, 'catalog_op_' || g, 'Catalog Op ' || g,
'rest', 'draft', now(), now()
from generate_series(1, 10001) as g",
)
.bind(workspace_id.as_str())
.execute(registry.pool())
.await
.unwrap();
}
async fn durable_import_jobs(
registry: &crank_registry::PostgresRegistry,
workspace_id: &WorkspaceId,
) -> i64 {
sqlx::query_scalar("select count(*) from import_jobs where workspace_id = $1")
.bind(workspace_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap()
}
async fn active_artifact_sources(
registry: &crank_registry::PostgresRegistry,
workspace_id: &WorkspaceId,
) -> i64 {
sqlx::query_scalar(
"select count(*) from artifact_sources where workspace_id = $1 and lifecycle = 'active'",
)
.bind(workspace_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap()
}
fn assert_upload_error(error: ApiError, variant: &str, code: &str) {
let context = match (variant, error) {
("validation", ApiError::Validation { context, .. }) => context,
("payload_too_large", ApiError::PayloadTooLarge { context, .. }) => context,
(expected, actual) => panic!("expected {expected} error, got {actual:?}"),
}
.expect("OpenAPI upload errors carry a machine-readable code");
assert_eq!(context["error_code"], format!("openapi_upload.{code}"));
}
#[tokio::test]
#[serial]
async fn preview_outcomes_do_not_mutate_operation_catalog() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_upload_outcomes"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let before = catalog_counts(&registry, &workspace_id).await;
let preview = service
.preview_openapi_import(
&workspace_id,
upload(
br#"{
"openapi":"3.0.3",
"info":{"title":"Upload outcomes","version":"1"},
"paths":{"/ready":{"get":{"responses":{"200":{"description":"ok"}}}}}
}"#
.to_vec(),
),
)
.await
.expect("valid OpenAPI document should return a preview");
let candidates = preview
.preview
.groups
.iter()
.flat_map(|group| &group.operations)
.collect::<Vec<_>>();
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].method, HttpMethod::Get);
assert_eq!(candidates[0].path, "/ready");
assert_eq!(candidates[0].key, "GET /ready");
assert_eq!(catalog_counts(&registry, &workspace_id).await, before);
let before = catalog_counts(&registry, &workspace_id).await;
let error = service
.preview_openapi_import(&workspace_id, upload(Vec::new()))
.await
.expect_err("empty upload should be rejected");
assert_upload_error(error, "validation", "empty_file");
assert_eq!(catalog_counts(&registry, &workspace_id).await, before);
let before = catalog_counts(&registry, &workspace_id).await;
let error = service
.preview_openapi_import(&workspace_id, upload(b"{".to_vec()))
.await
.expect_err("malformed OpenAPI document should be rejected");
assert_upload_error(error, "validation", "invalid_document");
assert_eq!(catalog_counts(&registry, &workspace_id).await, before);
let before = catalog_counts(&registry, &workspace_id).await;
let error = service
.preview_openapi_import(&workspace_id, upload(vec![b' '; MAX_ARTIFACT_BYTES + 1]))
.await
.expect_err("oversized upload should be rejected");
assert_upload_error(error, "payload_too_large", "file_too_large");
assert_eq!(catalog_counts(&registry, &workspace_id).await, before);
let before = catalog_counts(&registry, &workspace_id).await;
let error = service
.preview_openapi_import(
&workspace_id,
upload(
br#"{
"openapi":"3.0.3",
"info":{"title":"No methods","version":"1"},
"paths":{}
}"#
.to_vec(),
),
)
.await
.expect_err("document without supported methods should be rejected");
assert_upload_error(error, "validation", "no_methods");
assert_eq!(catalog_counts(&registry, &workspace_id).await, before);
}
#[tokio::test]
#[serial]
async fn preview_profile_decode_failure_leaves_no_pending_job_or_source() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_upload_profile_decode_failure"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
insert_malformed_auth_profile(&registry, &workspace_id).await;
service
.preview_openapi_import(&workspace_id, upload(PREVIEWABLE_DOCUMENT.to_vec()))
.await
.expect_err("malformed auth profile must fail preview enrichment");
assert_eq!(
durable_import_jobs(&registry, &workspace_id).await,
0,
"profile lookup failure must not leave a durable import job"
);
assert_eq!(
active_artifact_sources(&registry, &workspace_id).await,
0,
"profile lookup failure must not leave attached sources"
);
}
#[tokio::test]
#[serial]
async fn preview_catalog_limit_failure_leaves_no_pending_job_or_source() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_upload_catalog_limit_failure"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
insert_catalog_overflow(&registry, &workspace_id).await;
service
.preview_openapi_import(&workspace_id, upload(PREVIEWABLE_DOCUMENT.to_vec()))
.await
.expect_err("catalog over the import limit must fail preview enrichment");
assert_eq!(
durable_import_jobs(&registry, &workspace_id).await,
0,
"catalog lookup failure must not leave a durable import job"
);
assert_eq!(
active_artifact_sources(&registry, &workspace_id).await,
0,
"catalog lookup failure must not leave attached sources"
);
}
@@ -0,0 +1,263 @@
use super::*;
#[tokio::test]
#[serial]
async fn exact_v5_contract_replays_saved_preview_without_source_locations() {
use sha2::{Digest, Sha256};
fn remove_source_locations(value: &mut serde_json::Value) {
match value {
serde_json::Value::Object(object) => {
object.remove("source_location");
for value in object.values_mut() {
remove_source_locations(value);
}
}
serde_json::Value::Array(values) => {
for value in values {
remove_source_locations(value);
}
}
_ => {}
}
}
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_v5_compatibility"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, openapi_upload())
.await
.unwrap();
let job_id: crank_registry::ImportJobId = preview.job_id.as_str().into();
let mut payload = registry
.get_import_job(&workspace_id, &job_id)
.await
.unwrap()
.unwrap()
.preview_payload;
// A preview persisted under v5 has the then-current projection and digest,
// without the source_location fields added by v6.
let persisted_preview = payload
.get_mut("preview")
.expect("newly saved job includes its preview");
assert!(persisted_preview.to_string().contains("source_location"));
remove_source_locations(persisted_preview);
let digest = format!(
"{:x}",
Sha256::digest(serde_json::to_vec(persisted_preview).unwrap())
);
payload["normalization"]["normalizer_version"] = "normalized-ir-v5".into();
payload["normalization"]["projection_version"] = "preview-v5".into();
payload["normalization"]["config"]["normalizer_version"] = "normalized-ir-v5".into();
payload["normalization"]["config"]["projection_version"] = "preview-v5".into();
payload["preview_digest"] = digest.into();
// If v5 is reparsed, this deliberately absent dependency makes the replay fail.
payload["dependency_snapshots"] = serde_json::json!([{
"source_id": "src_openapi_dep_v5_must_not_be_read",
"digest": format!("sha256:{}", "0".repeat(64)),
"canonical_uri": "https://schemas.example.test/v5.yaml"
}]);
sqlx::query("update import_jobs set preview_payload = $1::jsonb where id = $2")
.bind(serde_json::to_string(&payload).unwrap())
.bind(job_id.as_str())
.execute(registry.pool())
.await
.unwrap();
let result = service
.create_openapi_import(
&workspace_id,
&job_id,
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
server_url: Some("https://api.frankfurter.dev".to_owned()),
conflict_mode: "skip".to_owned(),
},
)
.await
.unwrap();
assert_eq!(result.created.len(), 1);
let completed = registry
.get_import_job(&workspace_id, &job_id)
.await
.unwrap()
.unwrap();
assert_eq!(completed.status, ImportJobStatus::Completed);
}
// Deterministic baseline source for the v5/v6 replay characterization. It uses
// a local reference so the preview is self-contained (no external dependency
// or ephemeral fixture port) while still exercising the reference graph.
const URI_PREVIEW_DOCUMENT: &str = r#"
openapi: 3.1.0
info: { title: URI preview parity, version: '1' }
servers: [{ url: https://api.example.test }]
paths:
/items:
get:
operationId: listItems
responses:
'200':
description: ok
content: { application/json: { schema: { $ref: '#/components/schemas/Item' } } }
components:
schemas:
Item: { type: object, required: [id], properties: { id: { type: string } } }
"#;
fn uri_preview_upload() -> OpenApiUpload {
OpenApiUpload {
bytes: URI_PREVIEW_DOCUMENT.as_bytes().to_vec(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
}
}
fn v5_v6_fixture_path() -> std::path::PathBuf {
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/integration/openapi_import/fixtures/v5-v6-uri-preview.json")
}
// AC-4 (history): a preview persisted under the historical (v5, v6) contract
// must replay unchanged, and a new preview of the same source must use the
// current contract. Captured from baseline execution before the URI change.
#[tokio::test]
#[serial]
async fn v5_v6_uri_preview_replays_unchanged_and_new_preview_uses_current_contract() {
let fixture_text = std::fs::read_to_string(v5_v6_fixture_path())
.expect("baseline v5/v6 URI preview fixture must be captured before the change");
let fixture: serde_json::Value = serde_json::from_str(&fixture_text).unwrap();
assert_eq!(
fixture["normalization"]["normalizer_version"],
serde_json::json!("normalized-ir-v5")
);
assert_eq!(
fixture["normalization"]["projection_version"],
serde_json::json!("preview-v6")
);
let fixture_preview = fixture["preview"].clone();
let fixture_digest = fixture["preview_digest"].clone();
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_v5_v6_replay"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
// A current preview of the same bytes must use the current contract.
let fresh = service
.preview_openapi_import(&workspace_id, uri_preview_upload())
.await
.unwrap();
let job_id: crank_registry::ImportJobId = fresh.job_id.as_str().into();
let fresh_job = registry
.get_import_job(&workspace_id, &job_id)
.await
.unwrap()
.unwrap();
assert_eq!(
fresh_job.preview_payload["source"]["digest"], fixture["source"]["digest"],
"fixture must refer to the exact captured source bytes"
);
assert_eq!(
fresh_job.preview_payload["normalization"]["normalizer_version"],
serde_json::json!(crank_import::rest::NORMALIZER_VERSION)
);
assert_eq!(
fresh_job.preview_payload["normalization"]["projection_version"],
serde_json::json!(crank_import::rest::PROJECTION_VERSION)
);
// Bind the historical payload to this run's freshly registered source blob.
let mut payload = fixture.clone();
payload["source"]["source_id"] = fresh_job.preview_payload["source"]["source_id"].clone();
sqlx::query("update import_jobs set preview_payload = $1::jsonb where id = $2")
.bind(serde_json::to_string(&payload).unwrap())
.bind(job_id.as_str())
.execute(registry.pool())
.await
.unwrap();
let result = service
.create_openapi_import(
&workspace_id,
&job_id,
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /items".to_owned()],
server_url: None,
conflict_mode: "skip".to_owned(),
},
)
.await
.unwrap();
assert_eq!(result.created.len(), 1);
// The historical preview is replayed from its saved projection, never
// recomputed under the current normalizer.
let completed = registry
.get_import_job(&workspace_id, &job_id)
.await
.unwrap()
.unwrap();
assert_eq!(completed.status, ImportJobStatus::Completed);
assert_eq!(completed.preview_payload["preview"], fixture_preview);
assert_eq!(
completed.preview_payload["normalization"]["normalizer_version"],
serde_json::json!("normalized-ir-v5")
);
assert_eq!(
completed.preview_payload["normalization"]["projection_version"],
serde_json::json!("preview-v6")
);
assert_eq!(completed.preview_payload["preview_digest"], fixture_digest);
}
// AC-4 (version RED): a fresh preview of the fixture source must be stamped with
// the approved v6 normalizer contract. This is the version RED, distinct from
// the URI transport RED: it pins the exact approved literals instead of
// following the current `NORMALIZER_VERSION`/`PROJECTION_VERSION` constants,
// which do not by themselves prove the approved v6 value. Deliberately no
// if-current branch and no skip: the assertion is unconditional and is expected
// to fail until the implementation bumps the normalizer to `normalized-ir-v6`.
#[tokio::test]
#[serial]
async fn fresh_preview_matches_approved_v6_normalizer_contract() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_v5_v6_version_contract"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let fresh = service
.preview_openapi_import(&workspace_id, uri_preview_upload())
.await
.unwrap();
let job_id: crank_registry::ImportJobId = fresh.job_id.as_str().into();
let fresh_job = registry
.get_import_job(&workspace_id, &job_id)
.await
.unwrap()
.unwrap();
assert_eq!(
fresh_job.preview_payload["normalization"]["normalizer_version"],
serde_json::json!("normalized-ir-v6"),
"approved normalizer contract is normalized-ir-v6"
);
assert_eq!(
fresh_job.preview_payload["normalization"]["projection_version"],
serde_json::json!("preview-v6"),
"approved projection contract is preview-v6"
);
}
@@ -12,6 +12,7 @@ use serial_test::serial;
use time::{Duration, OffsetDateTime};
mod apply_failures;
mod body_limit;
mod telemetry;
const OPENAPI: &str = r#"
@@ -0,0 +1,142 @@
use super::*;
const DEFAULT_HTTP_BODY_BYTES: usize = 2 * 1024 * 1024;
const MAX_STORED_PLAN_BYTES: usize = 16 * 1024 * 1024;
const PATH_COUNT: usize = 49;
const PATH_LEN: usize = 3100;
const METHODS: [&str; 7] = ["get", "post", "put", "patch", "delete", "head", "options"];
const OPERATION_COUNT: usize = PATH_COUNT * METHODS.len();
// Complete descriptions and schemas avoid multiplying quality findings for
// long paths. The test must pass the stored-plan cap before exercising HTTP.
fn long_path_document_and_keys() -> (String, Vec<String>) {
let mut paths = serde_json::Map::new();
let mut keys = Vec::new();
for index in 0..PATH_COUNT {
let path = format!("/{index:04}{}", "a".repeat(PATH_LEN - 5));
let mut item = serde_json::Map::new();
item.insert(
"parameters".to_owned(),
serde_json::json!([{
"name": "filter", "in": "query", "description": "Record filter",
"schema": { "type": "string" }
}]),
);
for (method_index, method) in METHODS.iter().enumerate() {
keys.push(format!("{} {path}", method.to_uppercase()));
item.insert(
(*method).to_owned(),
serde_json::json!({
"operationId": format!("read_record_{index}_{method_index}"),
"summary": "Read record",
"description": "Returns a matching record for the requested filter.",
"responses": { "200": {
"description": "Matched record",
"content": { "application/json": { "schema": {
"type": "object", "properties": { "result": { "type": "string" } }
} } }
} }
}),
);
}
paths.insert(path, Value::Object(item));
}
(
serde_json::json!({
"openapi": "3.0.3", "info": { "title": "Long path keys", "version": "1" },
"servers": [{ "url": "https://api.example.test" }], "paths": paths
})
.to_string(),
keys,
)
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn plan_http_body_limit_accepts_valid_large_confirmation() {
let (document, keys) = long_path_document_and_keys();
assert!(document.len() <= MAX_ARTIFACT_BYTES);
assert_eq!(keys.len(), OPERATION_COUNT);
assert!(keys.iter().all(|key| key.len() <= 4096));
println!(
"B1_FIXTURE document_bytes={} operations={}",
document.len(),
keys.len()
);
let registry = test_registry().await;
let app = build_test_app(
registry.clone(),
test_storage_root("openapi_plan_body_limit"),
);
let server = spawn_admin_api(app).await;
let client = authorized_client(&server).await;
let response = client
.post(format!("{server}/imports/openapi/preview"))
.multipart(Form::new().part(
"file",
file_part(document.as_bytes(), "openapi.json", "application/json"),
))
.send()
.await
.unwrap();
let status = response.status();
let preview: Value = response.json().await.unwrap();
assert_eq!(status, reqwest::StatusCode::OK, "{preview}");
let job_id = preview["job_id"].as_str().unwrap();
// The smaller control proves actual persistence. Explicit create decisions
// add no semantic change, but repeat the keys in a larger HTTP request.
for explicit_decisions in [false, true] {
let decisions: Vec<Value> = if explicit_decisions {
keys.iter()
.map(|key| {
serde_json::json!({
"operation_key": key, "action": "create"
})
})
.collect()
} else {
Vec::new()
};
let payload = serde_json::json!({
"selection_mode": "full", "selected_operation_keys": keys, "decisions": decisions
});
let request_bytes = serde_json::to_vec(&payload).unwrap().len();
assert_eq!(request_bytes > DEFAULT_HTTP_BODY_BYTES, explicit_decisions);
let response = client
.post(format!("{server}/imports/openapi/{job_id}/plans"))
.json(&payload)
.send()
.await
.unwrap();
let status = response.status();
let body = response.text().await.unwrap();
println!(
"B1_HTTP explicit_decisions={explicit_decisions} request_bytes={request_bytes} status={status}"
);
assert_eq!(
status,
reqwest::StatusCode::OK,
"valid plan rejected: {}",
body.chars().take(2000).collect::<String>()
);
let plan: Value = serde_json::from_str(&body).unwrap();
assert_eq!(plan["counts"]["selected"], OPERATION_COUNT);
assert_eq!(plan["counts"]["actionable"], OPERATION_COUNT);
assert_eq!(plan["counts"]["blocked"], 0);
assert_eq!(plan["counts"]["excluded"], 0);
let plan_id: crank_registry::ImportPlanId = plan["plan_reference"].as_str().unwrap().into();
let stored = registry
.get_import_plan(&WorkspaceId::new("ws_default"), &plan_id)
.await
.unwrap()
.unwrap();
let stored_bytes = serde_json::to_vec(&stored.payload).unwrap().len();
println!(
"B1_PERSISTED explicit_decisions={explicit_decisions} stored_bytes={stored_bytes}"
);
assert!(stored_bytes <= MAX_STORED_PLAN_BYTES);
assert_eq!(stored.payload["counts"]["selected"], OPERATION_COUNT);
}
}
+24 -2
View File
@@ -40,7 +40,20 @@ fn plan_is_deterministic_and_committed_contract_is_current() {
);
assert_eq!(first.stdout, second.stdout);
let plan: serde_json::Value = serde_json::from_slice(&first.stdout).unwrap();
assert_eq!(plan["sequence"].as_array().unwrap().len(), 13);
assert_eq!(plan["sequence"].as_array().unwrap().len(), 15);
let target = command(&["plan", "--target-version"], None);
assert!(
target.status.success(),
"{}",
String::from_utf8_lossy(&target.stderr)
);
let last_version = plan["sequence"].as_array().unwrap().last().unwrap()["version"]
.as_i64()
.unwrap();
assert_eq!(
String::from_utf8(target.stdout).unwrap(),
format!("{last_version}\n")
);
let checked = command(&["plan", "--check"], None);
assert!(
@@ -50,6 +63,15 @@ fn plan_is_deterministic_and_committed_contract_is_current() {
);
}
#[test]
fn invalid_plan_option_is_rejected_without_success_output() {
let output = command(&["plan", "--not-an-option"], None);
assert!(!output.status.success());
assert!(output.stdout.is_empty());
let diagnostic: serde_json::Value = serde_json::from_slice(&output.stderr).unwrap();
assert_eq!(diagnostic["code"], "invalid_command");
}
#[test]
fn invalid_command_is_bounded_and_does_not_echo_arguments() {
let canary = "secret-command-canary";
@@ -82,7 +104,7 @@ async fn database_only_config_can_apply_and_preflight_a_fresh_schema() {
);
let result: serde_json::Value = serde_json::from_slice(&preflight.stdout).unwrap();
assert_eq!(result["status"], "current");
assert_eq!(result["version"], 13);
assert_eq!(result["version"], 15);
}
#[tokio::test]
@@ -48,3 +48,28 @@ fn admin_and_mcp_preserve_dispatch_uncertainty_without_changing_the_code() {
assert!(!mcp.recoverable);
}
}
#[test]
fn admin_and_mcp_project_new_uncertain_upstream_codes_consistently() {
for locale in [ExecutionLocale::En, ExecutionLocale::Ru] {
for code in [
ExecutionErrorCode::UpstreamRateLimited,
ExecutionErrorCode::UpstreamServerError,
ExecutionErrorCode::UpstreamResponseTooLarge,
ExecutionErrorCode::UpstreamStatusError,
] {
let failure = ExecutionFailure::new(code, CorrelationContext::generate())
.with_dispatch_uncertainty();
let admin = execution_test_failure_localized(&failure, locale);
let mcp = tool_error_contract_from_failure(&failure, locale);
assert_eq!(admin["code"], code.as_str());
assert_eq!(admin["retryability"], "manual_reconcile");
assert_eq!(admin["outcome_certainty"], "outcome_unknown");
assert_eq!(admin["retryability"], mcp.retryability);
assert_eq!(admin["outcome_certainty"], mcp.outcome_certainty);
assert_eq!(mcp.error_code, code.as_str());
assert!(!mcp.recoverable);
}
}
}
+37 -7
View File
@@ -3,6 +3,7 @@ FROM rust:1.96.1-bookworm AS deps
WORKDIR /app
COPY Cargo.toml Cargo.lock ./
COPY vendor ./vendor
COPY .sqlx ./.sqlx
COPY apps/admin-api/Cargo.toml apps/admin-api/Cargo.toml
COPY apps/mcp-server/Cargo.toml apps/mcp-server/Cargo.toml
@@ -41,6 +42,7 @@ FROM rust:1.96.1-bookworm AS builder
WORKDIR /app
COPY Cargo.toml Cargo.lock ./
COPY vendor ./vendor
COPY .sqlx ./.sqlx
COPY apps ./apps
COPY crates ./crates
@@ -51,20 +53,48 @@ RUN --mount=type=cache,id=crank-mcp-cargo-registry,target=/usr/local/cargo/regis
SQLX_OFFLINE=true cargo build --release -p mcp-server \
&& cp /app/target/release/mcp-server /tmp/mcp-server
FROM debian:bookworm-slim
# Trusted CA bundle source for the package stage. The slim image ships no CA
# certificates, so the HTTPS Debian mirror can only be reached after seeding
# them; the Rust base image provides the bundle without rebuilding the app.
FROM rust:1.96.1-bookworm AS ca-bundle
RUN test -s /etc/ssl/certs/ca-certificates.crt
# Package stage: install the security-refreshed Debian packages, then assemble
# the minimal runtime rootfs. Kept independent of the Rust builder so it can be
# built and reviewed on its own.
FROM debian:bookworm-slim AS runtime-rootfs
ARG CRANK_SECURITY_REFRESH
COPY --from=ca-bundle /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
COPY scripts/prepare-runtime-rootfs.sh /usr/local/bin/prepare-runtime-rootfs
RUN sed -i 's|http://deb.debian.org|https://deb.debian.org|g' /etc/apt/sources.list.d/debian.sources \
&& apt-get update \
&& apt-get install -y --no-install-recommends --only-upgrade \
base-files libc6 libgcc-s1 gcc-12-base bash dash libtinfo6 libselinux1 libpcre2-8-0 coreutils \
&& rm -rf /var/lib/apt/lists/* \
&& dpkg --compare-versions "$(dpkg-query -W -f='${Version}' libpcre2-8-0)" ge '10.42-1+deb12u2' \
&& sh /usr/local/bin/prepare-runtime-rootfs /runtime \
&& echo "crank-security-refresh=${CRANK_SECURITY_REFRESH}"
COPY scripts/docker-http-healthcheck.sh /runtime/usr/local/bin/crank-http-healthcheck
RUN chmod 0755 /runtime/usr/local/bin/crank-http-healthcheck
FROM scratch
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
WORKDIR /app
COPY --from=runtime-rootfs /runtime /
COPY --from=builder /tmp/mcp-server /usr/local/bin/mcp-server
COPY scripts/docker-http-healthcheck.sh /usr/local/bin/crank-http-healthcheck
RUN test -s /etc/ssl/certs/ca-certificates.crt \
&& chmod 0755 /usr/local/bin/crank-http-healthcheck
ENV PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
ENV CRANK_MCP_BIND=0.0.0.0:3002
WORKDIR /app
EXPOSE 3002
CMD ["mcp-server"]
+8
View File
@@ -10,12 +10,20 @@ const TEST_MASTER_KEY: &str = "test-master-key-00000000000000000000000000000000"
const REGISTERED_MASTER_KEY: &str = "registered-master-key-CANARY_SECRET_VALUE-00000000";
const WRONG_MASTER_KEY: &str = "wrong-master-key-CANARY_SECRET_VALUE-0000000000000";
fn isolated_metrics_bind() -> String {
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("ephemeral metrics port");
let addr = listener.local_addr().unwrap().to_string();
drop(listener);
addr
}
fn run_with(entries: &[(&str, &str)]) -> String {
let mut command = Command::new(env!("CARGO_BIN_EXE_mcp-server"));
for field in crank_config::field_registry() {
command.env_remove(field.env_name);
}
command.env("CRANK_MASTER_KEY", TEST_MASTER_KEY);
command.env("CRANK_MCP_METRICS_BIND", isolated_metrics_bind());
for (name, value) in entries {
command.env(name, value);
}
+1
View File
@@ -1,6 +1,7 @@
mod integration {
mod catalog_access;
mod common;
mod execution_certainty;
mod execution_stages;
mod jsonrpc_correlation;
mod request_context;
@@ -0,0 +1,145 @@
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
use std::time::Duration;
use axum::{Router, http::StatusCode, routing::post};
use crank_core::{
ExecutionErrorCode, InvocationSource, OutcomeCertainty, PlatformApiKeyScope, Retryability,
WorkspaceId,
};
use crank_registry::{ListInvocationLogsQuery, PublishRequest};
use serde_json::{Value, json};
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use tokio::net::TcpListener;
use super::common::{
agent_mcp_url, build_test_app, create_platform_api_key, initialize_session,
post_jsonrpc_response, publish_agent_for_operation, spawn_mcp_server, test_operation,
test_registry, test_workspace_id,
};
const REQUEST_ID: &str = "req_mcp_execution_certainty";
#[tokio::test]
async fn ambiguous_post_failure_is_reported_and_persisted_as_unknown() {
let registry = test_registry().await;
let upstream_calls = Arc::new(AtomicUsize::new(0));
let upstream_base_url = spawn_503_upstream(Arc::clone(&upstream_calls)).await;
let operation = test_operation(&upstream_base_url, "mcp_execution_certainty");
registry
.create_operation(&test_workspace_id(), &operation, Some("test"))
.await
.unwrap();
registry
.publish_operation(PublishRequest {
workspace_id: &test_workspace_id(),
operation_id: &operation.id,
version: 1,
published_at: &OffsetDateTime::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("test"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, "mcp-certainty-agent").await;
let api_key = create_platform_api_key(
&registry,
"mcp-certainty-agent",
"mcp-certainty-key",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let app = build_test_app(registry.clone(), Duration::ZERO, None);
let base_url = spawn_mcp_server(app).await;
let client = reqwest::Client::new();
let mcp_url = agent_mcp_url(&base_url, "mcp-certainty-agent");
let session_id = initialize_session(&client, &mcp_url, &api_key).await;
let response = post_jsonrpc_response(
&client,
&mcp_url,
&api_key,
Some(&session_id),
Some(REQUEST_ID),
json!({
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": operation.name,
"arguments": { "email": "user@example.com" }
}
}),
)
.await;
assert_eq!(response.status(), StatusCode::OK);
let response: Value = response.json().await.unwrap();
let tool_result = &response["result"];
let error = &tool_result["structuredContent"]["error"];
assert_eq!(tool_result["isError"], true);
assert_eq!(error["code"], "upstream_server_error");
assert_eq!(error["upstream_status"], 503);
assert_eq!(error["retryability"], "manual_reconcile");
assert_eq!(error["outcome_certainty"], "outcome_unknown");
assert_eq!(error["recoverable"], false);
assert_eq!(upstream_calls.load(Ordering::SeqCst), 1);
let logs = registry
.list_invocation_logs(ListInvocationLogsQuery {
workspace_id: &WorkspaceId::new("ws_default"),
level: None,
status: None,
outcome_group: None,
search_text: None,
source: Some(InvocationSource::AgentToolCall),
operation_id: Some(&operation.id),
agent_id: None,
created_after: None,
created_before: None,
cursor_created_at: None,
cursor_id: None,
limit: 10,
})
.await
.unwrap();
let invocation = logs
.iter()
.find(|record| record.log.request_id.as_deref() == Some(REQUEST_ID))
.expect("Invocation History entry for this MCP request");
assert_eq!(invocation.log.tool_name, operation.name);
assert_eq!(invocation.log.operation_version, Some(1));
assert_eq!(invocation.log.status_code, Some(503));
assert_eq!(
invocation.log.execution_error_code,
Some(ExecutionErrorCode::UpstreamServerError)
);
assert_eq!(
invocation.log.retryability,
Some(Retryability::ManualReconcile)
);
assert_eq!(
invocation.log.outcome_certainty,
Some(OutcomeCertainty::OutcomeUnknown)
);
}
async fn spawn_503_upstream(calls: Arc<AtomicUsize>) -> String {
let app = Router::new().route(
"/crm/leads",
post(move || {
let calls = Arc::clone(&calls);
async move {
calls.fetch_add(1, Ordering::SeqCst);
(StatusCode::SERVICE_UNAVAILABLE, "upstream unavailable")
}
}),
);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
format!("http://{address}")
}
+1
View File
@@ -13,6 +13,7 @@ RUN npm run build
FROM nginx:1.30.4-alpine3.24-slim
RUN apk add --no-cache --upgrade \
'pcre2>=10.49-r0' \
'libcrypto3>=3.5.8-r0' \
'libssl3>=3.5.8-r0'
+11 -2
View File
@@ -29,7 +29,7 @@
bottom: 76px;
z-index: 790;
width: min(410px, calc(100vw - 28px));
max-height: min(700px, calc(100vh - 104px));
max-height: min(700px, calc(100vh - 152px));
overflow: auto;
scroll-behavior: auto;
border: 1px solid var(--border-color, #30363d);
@@ -64,6 +64,15 @@
.onboarding-first-call-evidence dt { color: var(--text-muted, #8b949e); }
.onboarding-first-call-evidence dd { margin: 0; font-family: var(--font-mono, monospace); overflow-wrap: anywhere; }
.onboarding-deep-link-stale { position: fixed; left: 50%; top: 76px; z-index: 810; width: min(520px, calc(100vw - 28px)); transform: translateX(-50%); padding: 14px; border: 1px solid var(--amber, #d29922); border-radius: 10px; background: var(--surface-raised, #161b22); color: var(--text-primary, #f0f6fc); box-shadow: 0 12px 36px rgba(0, 0, 0, .35); }
.onboarding-openapi-path { margin-top: 14px; padding: 12px; border: 1px dashed var(--border-color, #30363d); border-radius: 9px; }
.onboarding-openapi-hint { margin: 0 0 8px; color: var(--text-muted, #8b949e); font-size: 12px; }
.onboarding-import-report { margin-top: 12px; padding: 12px; border: 1px solid var(--border-color, #30363d); border-radius: 9px; }
.onboarding-import-report h3 { margin: 0 0 8px; font-size: 14px; }
.onboarding-import-report-list { display: grid; gap: 8px; margin: 0; padding-left: 20px; }
.onboarding-import-report-item { display: grid; gap: 4px; overflow-wrap: anywhere; font-size: 12px; }
.onboarding-import-drift, .onboarding-import-error { color: var(--amber, #d29922); font-size: 12px; }
.onboarding-import-selected { color: var(--success, #3fb950); font-size: 12px; }
.onboarding-return-context { display: none; }
.onboarding-footer { display: flex; justify-content: space-between; gap: 8px; margin-top: 12px; }
.onboarding-link-button { border: 0; background: transparent; color: var(--text-muted, #8b949e); text-decoration: underline; cursor: pointer; font: inherit; font-size: 12px; }
@@ -80,7 +89,7 @@ body.wizard-page .onboarding-trigger {
body.wizard-page .onboarding-panel {
bottom: calc(150px + env(safe-area-inset-bottom, 0px));
max-height: min(700px, calc(100vh - 178px));
max-height: min(700px, calc(100vh - 226px));
}
@media (max-width: 640px) {
+358 -4
View File
@@ -160,6 +160,124 @@
margin-top: 18px;
}
.openapi-import-plan-confirmation {
display: grid;
gap: 12px;
padding: 18px;
border: 1px solid var(--border);
border-radius: 16px;
background: var(--bg-surface);
}
.openapi-import-plan-confirmation[hidden] {
display: none;
}
.openapi-import-plan-confirmation h3,
.openapi-import-plan-intro,
.openapi-import-plan-versioning,
.openapi-import-plan-summary {
margin: 0;
}
.openapi-import-plan-intro,
.openapi-import-plan-versioning {
color: var(--text-secondary);
font-size: 13px;
}
.openapi-import-plan-versioning:not([hidden]) {
padding: 12px;
border-left: 3px solid var(--accent);
border-radius: 6px;
background: var(--bg-overlay);
}
.openapi-import-plan-counts {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.openapi-import-plan-count {
padding: 6px 10px;
border: 1px solid var(--border);
border-radius: 999px;
color: var(--text-secondary);
font-size: 12px;
}
.openapi-import-plan-candidates,
.openapi-import-plan-outcomes {
display: grid;
gap: 8px;
}
.openapi-import-findings summary {
cursor: pointer;
color: var(--text-secondary);
font-weight: 700;
}
.openapi-import-findings-page {
display: grid;
gap: 4px;
padding-top: 6px;
}
.openapi-import-findings-pagination {
display: flex;
align-items: center;
justify-content: flex-start;
gap: 8px;
padding-top: 6px;
color: var(--text-secondary);
}
.openapi-import-plan-candidate,
.openapi-import-plan-outcome {
display: grid;
gap: 5px;
padding: 12px;
border: 1px solid var(--border-subtle);
border-radius: 12px;
background: var(--bg-overlay);
}
.openapi-import-plan-candidate[data-state="blocked"],
.openapi-import-plan-outcome[data-outcome="rejected"] {
border-color: color-mix(in srgb, var(--red) 45%, var(--border));
}
.openapi-import-plan-candidate code,
.openapi-import-plan-outcome code {
color: var(--text-muted);
font-size: 12px;
overflow-wrap: anywhere;
}
.openapi-import-plan-candidate p,
.openapi-import-plan-outcome p {
margin: 0;
color: var(--text-secondary);
font-size: 13px;
}
.openapi-import-plan-reason {
color: var(--text-muted) !important;
}
.openapi-import-plan-actions {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 10px;
}
.openapi-import-plan-summary {
color: var(--text-secondary);
}
.openapi-import-source,
.openapi-import-group {
border: 1px solid var(--border);
@@ -185,7 +303,6 @@
}
#openapi-import-server,
#openapi-import-conflict-mode,
#openapi-import-search,
#openapi-import-method-filter,
.openapi-import-server-custom {
@@ -238,6 +355,30 @@
gap: 14px;
}
.openapi-import-partial-toggle {
display: flex;
align-items: center;
gap: 9px;
width: fit-content;
color: var(--text-primary);
font-size: 13px;
font-weight: 700;
}
.openapi-import-pagination {
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
padding: 4px 0;
color: var(--text-secondary);
font-size: 13px;
}
.openapi-import-pagination[hidden] {
display: none;
}
.openapi-import-group-header {
display: flex;
align-items: center;
@@ -266,12 +407,109 @@
}
.openapi-import-operation {
display: grid;
gap: 10px;
padding: 14px 16px;
border-bottom: 1px solid var(--border);
}
.openapi-import-operation-selection {
display: grid;
grid-template-columns: auto 1fr auto;
gap: 12px;
align-items: start;
padding: 14px 16px;
border-bottom: 1px solid var(--border);
cursor: pointer;
}
.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-security-controls label {
display: grid;
gap: 5px;
color: var(--text-secondary);
font-size: 12px;
font-weight: 700;
}
.openapi-import-decision-controls select,
.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;
border: 1px solid var(--border);
border-radius: 10px;
background: var(--bg-surface);
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);
font-weight: 700;
}
.openapi-import-plan-version,
.openapi-import-plan-revalidation {
color: var(--text-secondary);
font-size: 12px;
overflow-wrap: anywhere;
}
.openapi-import-plan-stale {
padding: 10px 12px;
border: 1px solid var(--red);
border-radius: 10px;
color: var(--red);
font-weight: 700;
}
.openapi-import-operation:last-child {
@@ -288,6 +526,25 @@
font-size: 12px;
}
.openapi-import-source-location {
color: var(--text-muted);
font-size: 11px;
overflow-wrap: anywhere;
}
.openapi-import-conflict {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 6px;
color: var(--amber);
font-size: 12px;
}
.openapi-import-conflict-proposal {
color: var(--text-primary);
}
.openapi-import-method {
padding: 4px 8px;
border-radius: 999px;
@@ -297,6 +554,26 @@
font-weight: 800;
}
.openapi-import-operation-readiness {
justify-self: start;
padding: 4px 8px;
border-radius: 999px;
background: var(--surface-muted, #21262d);
color: var(--text-secondary);
font-size: 11px;
font-weight: 800;
}
.openapi-import-operation-readiness-actionable {
background: var(--green-glow, rgba(63, 185, 80, 0.16));
color: var(--green);
}
.openapi-import-operation-readiness-blocked {
background: var(--red-glow, rgba(248, 81, 73, 0.16));
color: var(--red);
}
.openapi-import-findings {
grid-column: 2 / -1;
display: grid;
@@ -304,6 +581,10 @@
font-size: 12px;
}
.openapi-import-operation .openapi-import-findings {
grid-column: auto;
}
.openapi-import-finding {
display: inline-flex;
align-items: baseline;
@@ -461,6 +742,17 @@
font-size: 13px;
}
.openapi-import-result-skipped-page {
margin-top: 6px;
}
.openapi-import-result-skipped-page ul {
max-height: 320px;
overflow: auto;
margin: 0;
padding-left: 22px;
}
.openapi-import-created-list {
display: grid;
gap: 6px;
@@ -475,6 +767,68 @@
text-decoration: none;
}
.openapi-import-blockers-summary {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-top: 12px;
padding: 10px 12px;
border: 1px solid var(--danger, #f85149);
border-radius: 8px;
color: var(--danger, #f85149);
font-size: 12px;
}
.openapi-import-blockers-summary[hidden] {
display: none;
}
.openapi-import-blockers-count {
font-weight: 700;
}
.openapi-import-blocker-code {
padding: 2px 6px;
border-radius: 5px;
background: rgba(248, 81, 73, .12);
font-family: var(--font-mono, monospace);
}
.onboarding-import-draft-choice {
margin-top: 14px;
padding: 12px;
border: 1px solid var(--accent, #58a6ff);
border-radius: 9px;
}
.onboarding-import-draft-choice-title {
display: block;
margin-bottom: 8px;
}
.onboarding-import-draft-choice-list {
display: grid;
gap: 8px;
}
.onboarding-import-draft-option-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding: 8px 0;
border-top: 1px solid var(--border-color, #30363d);
overflow-wrap: anywhere;
}
.onboarding-import-drift {
color: var(--amber, #d29922);
}
.onboarding-import-draft-selected {
color: var(--success, #3fb950);
}
@media (max-width: 720px) {
.openapi-import-toolbar {
grid-template-columns: 1fr;
@@ -484,7 +838,7 @@
justify-content: flex-start;
}
.openapi-import-operation {
.openapi-import-operation-selection {
grid-template-columns: auto 1fr;
}
+13 -1
View File
@@ -178,7 +178,19 @@
</div><!-- /step-sidebar -->
<!-- ── Main step panel ── -->
<div class="wizard-main"><div id="step-panel-container"><!-- steps loaded dynamically --></div></div>
<div class="wizard-main">
<div id="wizard-live-status" class="info-callout" role="status" aria-live="polite" aria-atomic="true" hidden style="margin-bottom: 20px;">
<svg class="info-callout-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
<circle cx="8" cy="8" r="7"/>
<path d="M8 11V8M8 5v-.5"/>
</svg>
<div class="info-callout-body">
<div class="info-callout-title" id="wizard-live-status-title" data-i18n="wizard.step5.draft_actions">Результат действия</div>
<div class="info-callout-text" id="wizard-live-status-text"></div>
</div>
</div>
<div id="step-panel-container"><!-- steps loaded dynamically --></div>
</div>
</div><!-- /wizard-body -->
<!-- ══ BOTTOM ACTION BAR ══ -->
-11
View File
@@ -131,17 +131,6 @@ tls:
<div class="section-divider-line"></div>
</div>
<div id="wizard-live-status" class="info-callout" role="status" aria-live="polite" aria-atomic="true" hidden style="margin-bottom: 20px;">
<svg class="info-callout-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round">
<circle cx="8" cy="8" r="7"/>
<path d="M8 11V8M8 5v-.5"/>
</svg>
<div class="info-callout-body">
<div class="info-callout-title" id="wizard-live-status-title" data-i18n="wizard.step5.draft_actions">Результат действия</div>
<div class="info-callout-text" id="wizard-live-status-text"></div>
</div>
</div>
<div id="wizard-mapping-warnings" class="mapping-warnings" hidden data-testid="wizard-mapping-warnings"></div>
<div class="config-card" id="agent-facing-preview-card" style="margin-bottom: 20px;">
+32 -9
View File
@@ -417,13 +417,6 @@
<select id="openapi-import-server"></select>
<input id="openapi-import-server-custom" class="openapi-import-server-custom" type="url" data-i18n-aria-label="openapi.server.custom_aria" aria-label="Свой Base URL" data-i18n-ph="openapi.server.placeholder" placeholder="Или укажите свой base URL, например https://api.example.com">
</div>
<div class="openapi-import-server-row">
<label for="openapi-import-conflict-mode" data-i18n="openapi.conflict.label">Если операция уже существует</label>
<select id="openapi-import-conflict-mode">
<option value="rename" selected data-i18n="openapi.conflict.rename">Создать копию с новым именем</option>
<option value="skip" data-i18n="openapi.conflict.skip">Пропустить</option>
</select>
</div>
<div class="openapi-import-toolbar">
<div class="openapi-import-filter">
<label for="openapi-import-search" data-i18n="openapi.search.label">Поиск методов</label>
@@ -440,13 +433,43 @@
<button class="btn-secondary" id="openapi-import-clear-visible" type="button" data-i18n="openapi.clear_visible">Снять видимые</button>
</div>
</div>
<label class="openapi-import-partial-toggle">
<input id="openapi-import-partial-mode" type="checkbox">
<span data-i18n="openapi.partial_mode">Enable partial import</span>
</label>
<div class="openapi-import-groups" id="openapi-import-groups"></div>
<nav class="openapi-import-pagination" id="openapi-import-pagination" data-testid="openapi-import-pagination" data-i18n-aria-label="openapi.pagination.label" aria-label="Pagination" hidden>
<button class="btn-secondary" id="openapi-import-page-previous" type="button" data-i18n="openapi.pagination.previous">Previous</button>
<span id="openapi-import-page-status" data-testid="openapi-import-page-status" role="status" aria-live="polite" aria-atomic="true"></span>
<button class="btn-secondary" id="openapi-import-page-next" type="button" data-i18n="openapi.pagination.next">Next</button>
</nav>
<div class="openapi-import-footer">
<span id="openapi-import-selection" data-i18n="openapi.selection.empty">Выбрано: 0</span>
<button class="btn-primary" id="openapi-import-create" type="button" data-i18n="openapi.create">Создать черновики</button>
<button class="btn-primary" id="openapi-import-create" type="button" data-i18n="openapi.plan.create">Просмотреть план импорта</button>
</div>
<div class="openapi-import-result" id="openapi-import-result" hidden></div>
<section class="openapi-import-plan-confirmation" id="openapi-import-plan-confirmation" data-testid="openapi-import-apply-confirmation" aria-labelledby="openapi-import-plan-title" hidden>
<h3 id="openapi-import-plan-title" data-i18n="openapi.plan.confirm_title">Подтвердите план импорта</h3>
<p class="openapi-import-plan-intro" data-i18n="openapi.plan.confirm_intro">Перед применением проверьте точный план сервера.</p>
<p class="openapi-import-plan-version" id="openapi-import-plan-version" data-testid="openapi-import-plan-version"></p>
<p class="openapi-import-plan-revalidation" id="openapi-import-plan-revalidation-status" data-testid="openapi-import-plan-revalidation-status" role="status" aria-live="polite" aria-atomic="true"></p>
<p class="openapi-import-plan-stale" id="openapi-import-plan-stale" data-testid="openapi-import-plan-stale" hidden></p>
<p class="openapi-import-plan-blocked-help" id="openapi-import-plan-blocked-help" data-i18n="openapi.plan.blocked_help" hidden>Исправьте решения для заблокированных операций и создайте план заново.</p>
<div class="openapi-import-plan-counts" id="openapi-import-plan-counts" data-testid="openapi-import-apply-counts"></div>
<nav class="openapi-import-pagination" id="openapi-import-plan-pagination" data-testid="openapi-import-plan-pagination" data-i18n-aria-label="openapi.pagination.plan_label" aria-label="Plan candidates" hidden>
<button class="btn-secondary" id="openapi-import-plan-page-previous" type="button" data-i18n="openapi.pagination.previous">Previous</button>
<span id="openapi-import-plan-page-status" data-testid="openapi-import-plan-page-status" role="status" aria-live="polite" aria-atomic="true"></span>
<button class="btn-secondary" id="openapi-import-plan-page-next" type="button" data-i18n="openapi.pagination.next">Next</button>
</nav>
<div class="openapi-import-plan-candidates" id="openapi-import-plan-candidates"></div>
<p class="openapi-import-plan-versioning" id="openapi-import-versioning-consequences" data-testid="openapi-import-versioning-consequences" hidden></p>
<div class="openapi-import-plan-actions">
<button class="btn-secondary" id="openapi-import-plan-reopen" type="button" data-testid="openapi-import-plan-reopen" data-i18n="openapi.plan.reopen">Reopen and check current plan</button>
<button class="btn-secondary" id="openapi-import-plan-back" type="button" data-i18n="openapi.plan.back">Назад к выбору</button>
<button class="btn-primary" id="openapi-import-plan-apply" type="button" data-testid="openapi-import-plan-apply" data-i18n="openapi.plan.apply">Применить импорт</button>
</div>
</section>
</div>
<div class="openapi-import-result" id="openapi-import-result" data-testid="openapi-import-apply-result" hidden></div>
</div>
</section>
</div>
+35
View File
@@ -328,6 +328,12 @@
expected_revision: expectedRevision,
});
},
registerOnboardingImportContext: function(workspaceId, payload) {
return post('/workspaces/' + encodeURIComponent(workspaceId) + '/onboarding/import-context', payload);
},
selectOnboardingImportDraft: function(workspaceId, payload) {
return post('/workspaces/' + encodeURIComponent(workspaceId) + '/onboarding/select-draft', payload);
},
updateWorkspace: function(workspaceId, payload) {
return patch('/workspaces/' + encodeURIComponent(workspaceId), payload);
},
@@ -436,6 +442,35 @@
signal: options && options.signal,
});
},
createOpenApiImportPlan: function(workspaceId, jobId, payload, options) {
return request(API_BASE + '/workspaces/' + encodeURIComponent(workspaceId) + '/imports/openapi/' + encodeURIComponent(jobId) + '/plans', {
method: 'POST',
headers: headers({
'Content-Type': 'application/json',
'Accept-Language': localStorage.getItem('crank_lang') === 'ru' ? 'ru' : 'en',
}),
body: JSON.stringify(payload),
signal: options && options.signal,
});
},
revalidateOpenApiImportPlan: function(workspaceId, planReference, options) {
return request(API_BASE + '/workspaces/' + encodeURIComponent(workspaceId) + '/imports/openapi/plans/' + encodeURIComponent(planReference), {
method: 'GET',
headers: headers({ 'Accept-Language': localStorage.getItem('crank_lang') === 'ru' ? 'ru' : 'en' }),
signal: options && options.signal,
});
},
applyOpenApiImportPlan: function(workspaceId, planReference, payload, options) {
return request(API_BASE + '/workspaces/' + encodeURIComponent(workspaceId) + '/imports/openapi/' + encodeURIComponent(planReference) + '/apply', {
method: 'POST',
headers: headers({
'Content-Type': 'application/json',
'Accept-Language': localStorage.getItem('crank_lang') === 'ru' ? 'ru' : 'en',
}),
body: JSON.stringify(payload),
signal: options && options.signal,
});
},
listAgents: function(workspaceId) {
return get('/workspaces/' + encodeURIComponent(workspaceId) + '/agents');
},
+218 -3
View File
@@ -611,6 +611,27 @@ var TRANSLATIONS = {
'wizard.step2.auth_mode.none': 'No auth',
'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.',
@@ -1658,6 +1679,27 @@ var TRANSLATIONS = {
'wizard.step2.auth_mode.none': 'Без авторизации',
'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': 'Профилей авторизации пока нет. Создайте профиль ниже.',
@@ -2092,12 +2134,81 @@ Object.assign(TRANSLATIONS.en, {
'openapi.method.all': 'All methods',
'openapi.select_visible': 'Select visible',
'openapi.clear_visible': 'Clear visible',
'openapi.partial_mode': 'Enable partial import',
'openapi.pagination.previous': 'Previous',
'openapi.pagination.next': 'Next',
'openapi.pagination.label': 'Preview pages',
'openapi.pagination.plan_label': 'Import plan candidates',
'openapi.pagination.result_label': 'Import results',
'openapi.findings.summary': 'Findings: {count}',
'openapi.pagination.status': 'Page {page} of {pages} · {total} matching operations',
'openapi.create': 'Create drafts',
'openapi.plan.create': 'Review import plan',
'openapi.plan.confirm_title': 'Confirm import plan',
'openapi.plan.confirm_intro': 'Review the exact server plan before applying it.',
'openapi.plan.reopen': 'Reopen and check current plan',
'openapi.plan.version': 'Review {version} · reference {reference} · digest {digest}',
'openapi.plan.revalidation_pending': 'Checking this saved plan…',
'openapi.plan.revalidation_current': 'The saved plan is current.',
'openapi.plan.revalidation_stale': 'The saved plan is stale.',
'openapi.plan.revalidation_error': 'The saved plan could not be verified.',
'openapi.plan.revalidation_guidance': 'Return to the preview and create a new plan before applying.',
'openapi.plan.back': 'Back to selection',
'openapi.plan.back_fix': 'Back to fix decisions',
'openapi.plan.apply': 'Apply import',
'openapi.plan.blocked_help': 'Fix the decisions for blocked operations, then create a new plan.',
'openapi.plan.exact_target': 'Exact operation',
'openapi.plan.confirmed_name': 'Confirmed name',
'openapi.decision.action_label': 'Import decision',
'openapi.decision.create': 'Create',
'openapi.decision.skip': 'Skip existing operation',
'openapi.decision.rename': 'Create with a confirmed name',
'openapi.decision.new_version': 'Create a new Draft Version',
'openapi.decision.target_label': 'Existing operation',
'openapi.decision.target_placeholder': 'Choose the exact operation',
'openapi.decision.confirmed_name_label': 'Confirmed name',
'openapi.decision.confirmed_name_placeholder': 'Enter the exact new name',
'openapi.plan.selected': 'Selected: {count}',
'openapi.plan.excluded': 'Excluded: {count}',
'openapi.plan.actionable': 'Actionable: {count}',
'openapi.plan.blocked': 'Blocked: {count}',
'openapi.plan.versioning_new': 'Creates a new Draft Version. The Published Version and history remain unchanged.',
'openapi.plan.action.create': 'Create a new Draft',
'openapi.plan.action.new_version': 'Create a new Draft Version',
'openapi.plan.action.rename': 'Create a separate Draft with the confirmed name',
'openapi.plan.action.skip': 'Keep the existing operation unchanged',
'openapi.plan.action.excluded': 'Excluded from this partial import',
'openapi.plan.action.blocked': 'Blocked and will not be applied',
'openapi.plan.result_title': 'Import plan result',
'openapi.plan.outcome.created': 'Created',
'openapi.plan.outcome.versioned': 'New Draft Version',
'openapi.plan.outcome.renamed': 'Created with confirmed name',
'openapi.plan.outcome.skipped': 'Skipped',
'openapi.plan.outcome.excluded': 'Excluded',
'openapi.plan.outcome.rejected': 'Rejected',
'openapi.plan.summary': 'Applied: {applied}; skipped: {skipped}; excluded: {excluded}; rejected: {rejected}.',
'openapi.plan.repreview': 'This plan is stale or could not be verified. Create a fresh preview and review a new plan.',
'openapi.plan.resolve_conflict': 'Review the conflict decision and create a new plan before applying again.',
'openapi.plan.retry_unknown': 'The Apply result is unknown. Retry sends the same plan reference, digest and idempotency key.',
'openapi.status.planning': 'Preparing the import plan…',
'openapi.status.plan_ready': 'Review the server plan and confirm to apply it.',
'openapi.status.applying': 'Applying the import plan…',
'openapi.status.applied': 'Import plan applied.',
'openapi.error.plan': 'The import plan could not be created.',
'openapi.error.apply': 'The import plan could not be applied.',
'openapi.error.operations_unavailable': 'The workspace operations could not be loaded. Retry the preview before creating a plan.',
'openapi.error.decision_target': 'Choose an exact existing operation for this decision.',
'openapi.error.confirmed_name': 'Enter the exact confirmed name for the rename decision.',
'openapi.error.decision_action': 'Choose a valid import decision.',
'openapi.status.loading_operations': 'Checking existing workspace operations…',
'openapi.selection.empty': 'Selected: 0',
'openapi.selection': 'Selected: {selected} of {total}, shown: {visible}',
'openapi.group.selection': 'selected {selected} of {total}, shown {visible}',
'openapi.group.select': 'Select group',
'openapi.group.select': 'Select group on this page',
'openapi.operation.fields': 'inputs: {input} · outputs: {output}',
'openapi.operation.readiness_actionable': 'Actionable',
'openapi.operation.readiness_blocked': 'Blocked',
'openapi.operation.readiness_unresolved': 'Authentication required',
'openapi.mapping.path': 'Path',
'openapi.mapping.query': 'Query',
'openapi.mapping.header': 'Header',
@@ -2106,6 +2217,8 @@ Object.assign(TRANSLATIONS.en, {
'openapi.source.summary': '{name} · {size} · methods: {count}',
'openapi.status.file_ready': 'File is ready for preview.',
'openapi.status.previewing': 'Uploading and parsing the document…',
'openapi.status.uploading': 'Uploading the document…',
'openapi.status.parsing': 'Parsing the OpenAPI document…',
'openapi.status.preview_ready': 'Document is ready. Select methods to import.',
'openapi.status.creating': 'Creating drafts…',
'openapi.status.created': 'Created: {created}; skipped: {skipped}.',
@@ -2134,6 +2247,7 @@ Object.assign(TRANSLATIONS.en, {
'openapi.finding.missing_servers': 'No base URL was found in the document.',
'openapi.finding.multiple_servers': 'Several base URLs are available; choose one before creating drafts.',
'openapi.finding.unsupported_request_body': 'This request body needs review in the wizard.',
'openapi.finding.external_reference_disabled': 'External references are blocked by default. Check the reference at this source location. A server administrator must add trusted addresses to the server allowlist. For offline use, prepare a self-contained OpenAPI file with its referenced schemas included before uploading; this screen accepts one file and does not upload separate reference files.',
'openapi.finding.operation_name_renamed': 'The operation name was adjusted to keep it unique.',
'openapi.finding.operation_name_conflict': 'An operation with this name already exists.',
'openapi.finding.weak_tool_description': 'The tool description is too short.',
@@ -2150,6 +2264,21 @@ Object.assign(TRANSLATIONS.en, {
'openapi.result.fix': 'Fix in wizard',
'openapi.result.open': 'Open in wizard',
'openapi.result.skipped': 'Skipped',
'openapi.result.skipped_count': 'Skipped: {count} candidates',
'openapi.blockers.summary': 'Blocked operations: {count}',
'onboarding.openapi_path': 'Start from an OpenAPI document',
'onboarding.openapi_hint': 'Use the canonical OpenAPI import: preview, review the exact plan, then apply it atomically.',
'onboarding.import.choose_draft': 'Choose one Draft to continue with test and publish',
'onboarding.import.report_title': 'OpenAPI import report and Draft choices',
'onboarding.import.continue': 'Continue with this Draft',
'onboarding.import.selected': 'Selected for onboarding',
'onboarding.import.drift': 'The selected Draft changed or is unavailable. Review the report and choose an available Draft again.',
'onboarding.import.registration_pending': 'Import report is being registered. Refresh onboarding before selecting.',
'onboarding.import.registration_failed': 'The import was applied, but its onboarding context could not be confirmed. Refresh to recover the report before continuing.',
'onboarding.import.selection_failed': 'This Draft could not be selected. Refresh the report and review the current Draft choices.',
'onboarding.import.conflict_reload': 'The onboarding state changed. The latest report has been loaded; review it before trying again.',
'onboarding.import.retry_registration': 'Retry report recovery',
'onboarding.import.view_report': 'View the full import report',
});
@@ -2208,12 +2337,81 @@ Object.assign(TRANSLATIONS.ru, {
'openapi.method.all': 'Все методы',
'openapi.select_visible': 'Выбрать видимые',
'openapi.clear_visible': 'Снять видимые',
'openapi.partial_mode': 'Включить частичный импорт',
'openapi.pagination.previous': 'Назад',
'openapi.pagination.next': 'Далее',
'openapi.pagination.label': 'Страницы предпросмотра',
'openapi.pagination.plan_label': 'Кандидаты плана импорта',
'openapi.pagination.result_label': 'Результаты импорта',
'openapi.findings.summary': 'Замечаний: {count}',
'openapi.pagination.status': 'Страница {page} из {pages} · операций по фильтру: {total}',
'openapi.create': 'Создать черновики',
'openapi.plan.create': 'Проверить план импорта',
'openapi.plan.confirm_title': 'Подтвердите план импорта',
'openapi.plan.confirm_intro': 'Перед применением проверьте точный план сервера.',
'openapi.plan.reopen': 'Повторно открыть и проверить план',
'openapi.plan.version': 'Проверка {version} · ссылка {reference} · digest {digest}',
'openapi.plan.revalidation_pending': 'Проверяем сохранённый план…',
'openapi.plan.revalidation_current': 'Сохранённый план актуален.',
'openapi.plan.revalidation_stale': 'Сохранённый план устарел.',
'openapi.plan.revalidation_error': 'Не удалось проверить сохранённый план.',
'openapi.plan.revalidation_guidance': 'Вернитесь к предпросмотру и создайте новый план перед применением.',
'openapi.plan.back': 'Назад к выбору',
'openapi.plan.back_fix': 'Назад к исправлению решений',
'openapi.plan.apply': 'Применить импорт',
'openapi.plan.blocked_help': 'Исправьте решения для заблокированных операций и создайте новый план.',
'openapi.plan.exact_target': 'Точная операция',
'openapi.plan.confirmed_name': 'Подтверждённое имя',
'openapi.decision.action_label': 'Решение для импорта',
'openapi.decision.create': 'Создать',
'openapi.decision.skip': 'Пропустить существующую операцию',
'openapi.decision.rename': 'Создать с подтверждённым именем',
'openapi.decision.new_version': 'Создать новую версию черновика',
'openapi.decision.target_label': 'Существующая операция',
'openapi.decision.target_placeholder': 'Выберите точную операцию',
'openapi.decision.confirmed_name_label': 'Подтверждённое имя',
'openapi.decision.confirmed_name_placeholder': 'Введите точное новое имя',
'openapi.plan.selected': 'Выбрано: {count}',
'openapi.plan.excluded': 'Исключено: {count}',
'openapi.plan.actionable': 'Можно применить: {count}',
'openapi.plan.blocked': 'Заблокировано: {count}',
'openapi.plan.versioning_new': 'Будет создана новая версия черновика. Опубликованная версия и история останутся без изменений.',
'openapi.plan.action.create': 'Создать черновик',
'openapi.plan.action.new_version': 'Создать новую версию черновика',
'openapi.plan.action.rename': 'Создать отдельный черновик с подтверждённым именем',
'openapi.plan.action.skip': 'Оставить существующую операцию без изменений',
'openapi.plan.action.excluded': 'Исключено из частичного импорта',
'openapi.plan.action.blocked': 'Заблокировано и не будет применено',
'openapi.plan.result_title': 'Результат плана импорта',
'openapi.plan.outcome.created': 'Создано',
'openapi.plan.outcome.versioned': 'Новая версия черновика',
'openapi.plan.outcome.renamed': 'Создано с подтверждённым именем',
'openapi.plan.outcome.skipped': 'Пропущено',
'openapi.plan.outcome.excluded': 'Исключено',
'openapi.plan.outcome.rejected': 'Отклонено',
'openapi.plan.summary': 'Применено: {applied}; пропущено: {skipped}; исключено: {excluded}; отклонено: {rejected}.',
'openapi.plan.repreview': 'План устарел или не прошёл проверку. Создайте новый предпросмотр и проверьте новый план.',
'openapi.plan.resolve_conflict': 'Проверьте решение конфликта и создайте новый план перед повторным применением.',
'openapi.plan.retry_unknown': 'Результат применения неизвестен. Повтор отправит те же ссылку, digest и ключ идемпотентности.',
'openapi.status.planning': 'Подготавливаю план импорта…',
'openapi.status.plan_ready': 'Проверьте план сервера и подтвердите его применение.',
'openapi.status.applying': 'Применяю план импорта…',
'openapi.status.applied': 'План импорта применён.',
'openapi.error.plan': 'Не удалось создать план импорта.',
'openapi.error.apply': 'Не удалось применить план импорта.',
'openapi.error.operations_unavailable': 'Не удалось загрузить операции workspace. Повторите предпросмотр перед созданием плана.',
'openapi.error.decision_target': 'Выберите точную существующую операцию для этого решения.',
'openapi.error.confirmed_name': 'Введите точное подтверждённое имя для переименования.',
'openapi.error.decision_action': 'Выберите допустимое решение для импорта.',
'openapi.status.loading_operations': 'Проверяю существующие операции workspace…',
'openapi.selection.empty': 'Выбрано: 0',
'openapi.selection': 'Выбрано: {selected} из {total}, показано: {visible}',
'openapi.group.selection': 'выбрано {selected} из {total}, показано {visible}',
'openapi.group.select': 'Выбрать группу',
'openapi.group.select': 'Выбрать группу на этой странице',
'openapi.operation.fields': 'входов: {input} · выходов: {output}',
'openapi.operation.readiness_actionable': 'Можно импортировать',
'openapi.operation.readiness_blocked': 'Заблокировано',
'openapi.operation.readiness_unresolved': 'Требуется авторизация',
'openapi.mapping.path': 'Path',
'openapi.mapping.query': 'Query',
'openapi.mapping.header': 'Header',
@@ -2222,6 +2420,8 @@ Object.assign(TRANSLATIONS.ru, {
'openapi.source.summary': '{name} · {size} · методов: {count}',
'openapi.status.file_ready': 'Файл готов к разбору.',
'openapi.status.previewing': 'Загружаю и разбираю документ…',
'openapi.status.uploading': 'Загружаю документ…',
'openapi.status.parsing': 'Разбираю документ OpenAPI…',
'openapi.status.preview_ready': 'Документ готов. Выберите методы для импорта.',
'openapi.status.creating': 'Создаю черновики…',
'openapi.status.created': 'Создано: {created}; пропущено: {skipped}.',
@@ -2250,6 +2450,7 @@ Object.assign(TRANSLATIONS.ru, {
'openapi.finding.missing_servers': 'В документе не найден base URL.',
'openapi.finding.multiple_servers': 'В документе несколько base URL; выберите один перед созданием черновиков.',
'openapi.finding.unsupported_request_body': 'Тело этого запроса нужно проверить в мастере.',
'openapi.finding.external_reference_disabled': 'Внешние ссылки по умолчанию запрещены. Проверьте ссылку по указанному пути. Администратор сервера может добавить доверенные адреса в список разрешённых адресов. Для работы без сети заранее подготовьте самодостаточный OpenAPI-файл, включив в него схемы из внешних ссылок; этот экран принимает один файл и не загружает отдельные файлы зависимостей.',
'openapi.finding.operation_name_renamed': 'Имя операции изменено, чтобы сохранить уникальность.',
'openapi.finding.operation_name_conflict': 'Операция с таким именем уже существует.',
'openapi.finding.weak_tool_description': 'Описание инструмента слишком короткое.',
@@ -2266,7 +2467,21 @@ Object.assign(TRANSLATIONS.ru, {
'openapi.result.fix': 'Исправить в мастере',
'openapi.result.open': 'Открыть в мастере',
'openapi.result.skipped': 'Пропущено',
'openapi.result.skipped_count': 'Пропущено кандидатов: {count}',
'openapi.blockers.summary': 'Заблокированные операции: {count}',
'onboarding.openapi_path': 'Начать с документа OpenAPI',
'onboarding.openapi_hint': 'Используйте канонический импорт OpenAPI: предпросмотр, проверка точного плана и атомарное применение.',
'onboarding.import.choose_draft': 'Выберите один черновик для продолжения тестирования и публикации',
'onboarding.import.report_title': 'Отчёт OpenAPI и выбор черновика',
'onboarding.import.continue': 'Продолжить с этим черновиком',
'onboarding.import.selected': 'Выбран для onboarding',
'onboarding.import.drift': 'Выбранный черновик изменился или недоступен. Проверьте отчёт и явно выберите доступный черновик.',
'onboarding.import.registration_pending': 'Отчёт импорта регистрируется. Обновите onboarding перед выбором.',
'onboarding.import.registration_failed': 'Импорт применён, но его контекст onboarding не подтверждён. Обновите страницу, чтобы восстановить отчёт.',
'onboarding.import.selection_failed': 'Не удалось выбрать этот черновик. Обновите отчёт и проверьте актуальные варианты.',
'onboarding.import.conflict_reload': 'Состояние onboarding изменилось. Загружен актуальный отчёт; проверьте его перед новой попыткой.',
'onboarding.import.retry_registration': 'Повторить восстановление отчёта',
'onboarding.import.view_report': 'Открыть полный отчёт импорта',
});
+253 -1
View File
@@ -12,6 +12,7 @@
refreshPromise: null,
refreshQueued: false,
startedRequested: false,
importError: null,
};
var channel = null;
var trigger = null;
@@ -79,7 +80,7 @@
function actionLabel(id) { return tKey('onboarding.action.' + id); }
function deepLink(step) {
var snapshot = state.snapshot || {};
var returnTo = encodeURIComponent(window.location.pathname + window.location.search);
var returnTo = encodeURIComponent(boundedReturnContext());
if (step.id === 'operation') return '/wizard/?onboarding=1&return=' + returnTo;
if (step.id === 'test' || step.id === 'publish_operation') {
if (!snapshot.operation_id) return '/wizard/?onboarding=1&return=' + returnTo;
@@ -100,6 +101,220 @@
return '/logs?agent_id=' + encodeURIComponent(snapshot.agent_id || '');
}
function navigate(step) { window.location.href = deepLink(step); }
function safeReturnContext(raw) {
if (typeof raw !== 'string' || raw.charAt(0) !== '/' || raw.indexOf('//') === 0
|| /[\u0000-\u001f\\]/.test(raw) || raw.length > 2048) return null;
var url;
try { url = new URL(raw, window.location.origin); } catch (_error) { return null; }
if (url.origin !== window.location.origin) return null;
var allowed = {
'/': [],
'/agents': ['onboarding', 'action', 'operationId', 'operationVersion'],
'/api-keys': ['onboarding', 'action', 'agentId', 'agentRevision'],
'/logs': ['log_id', 'agent_id', 'operation_id'],
'/secrets': [],
'/settings': [],
'/usage': [],
'/workspace-setup': [],
'/wizard/': ['mode', 'operationId', 'step', 'onboarding'],
};
var keys = allowed[url.pathname];
if (!keys) return null;
var safe = new URLSearchParams();
url.searchParams.forEach(function(value, key) {
if (keys.indexOf(key) < 0) return;
if (key === 'onboarding' && value === '1') safe.set(key, value);
else if (key === 'action' && value === 'create') safe.set(key, value);
else if (key === 'mode' && (value === 'create' || value === 'edit')) safe.set(key, value);
else if ((key === 'operationVersion' || key === 'agentRevision' || key === 'step')
&& /^[0-9]{1,16}$/.test(value)) safe.set(key, value);
else if (/^(?:operationId|agentId|log_id|agent_id|operation_id)$/.test(key)
&& /^[A-Za-z0-9_-]{1,128}$/.test(value)) safe.set(key, value);
});
var context = url.pathname + (safe.size ? '?' + safe.toString() : '');
return context.length <= 256 ? context : url.pathname;
}
function boundedReturnContext() {
return safeReturnContext(window.location.pathname + window.location.search) || '/';
}
function returnContextFromQuery() {
var candidate = new URLSearchParams(window.location.search).get('return');
return safeReturnContext(candidate) || boundedReturnContext();
}
function openOpenApiPath() {
if (!window.CrankOpenApiImport || typeof window.CrankOpenApiImport.open !== 'function') {
window.location.href = '/?onboarding_openapi=1&return=' + encodeURIComponent(boundedReturnContext());
return;
}
window.CrankOpenApiImport.open({
workspaceId: state.workspaceId,
onboarding: true,
returnContext: returnContextFromQuery(),
importContext: state.snapshot && state.snapshot.import_context,
onImported: function(identity) { return registerImportedApplication(identity); },
onSelectDraft: function(operationId, version, identity) { return selectImportedDraft(operationId, version, identity); },
});
}
async function registerImportedApplication(identity) {
var workspaceId = state.workspaceId;
var epoch = state.epoch;
if (!identity || !identity.applicationIdempotencyKey || !identity.planDigest
|| !window.CrankApi || typeof window.CrankApi.registerOnboardingImportContext !== 'function') {
throw new Error(tKey('onboarding.import.registration_failed'));
}
try {
var authoritative = await window.CrankApi.getOnboarding(workspaceId);
if (epoch !== state.epoch || workspaceId !== state.workspaceId || workspaceId !== (currentWorkspace() && currentWorkspace().id)) {
throw new Error(tKey('onboarding.import.registration_failed'));
}
state.snapshot = authoritative;
render();
var response = await window.CrankApi.registerOnboardingImportContext(workspaceId, {
application_idempotency_key: identity.applicationIdempotencyKey,
plan_digest: identity.planDigest,
expected_revision: Number(authoritative && authoritative.revision || 0),
});
if (epoch !== state.epoch || workspaceId !== state.workspaceId || workspaceId !== (currentWorkspace() && currentWorkspace().id)) {
throw new Error(tKey('onboarding.import.registration_failed'));
}
var current = response && response.onboarding ? response.onboarding : response;
if (!current || !current.import_context) throw new Error(tKey('onboarding.import.registration_failed'));
state.snapshot = current;
render();
return current;
} catch (error) {
if (epoch === state.epoch && workspaceId === state.workspaceId) {
await refresh();
var recovered = state.snapshot && state.snapshot.import_context;
if (recovered
&& recovered.application_idempotency_key === identity.applicationIdempotencyKey
&& recovered.plan_digest === identity.planDigest) return state.snapshot;
}
throw error;
}
}
async function selectImportedDraft(operationId, version, identity) {
if (!operationId || !window.CrankApi || typeof window.CrankApi.selectOnboardingImportDraft !== 'function') return null;
var workspaceId = state.workspaceId;
var epoch = state.epoch;
var context = state.snapshot && state.snapshot.import_context;
var applicationKey = identity && identity.applicationIdempotencyKey || (context && context.application_idempotency_key);
var digest = identity && identity.planDigest || (context && context.plan_digest);
if (!applicationKey || !digest || !Number.isInteger(version) || version < 1) {
throw new Error(tKey('onboarding.import.selection_failed'));
}
try {
var response = await window.CrankApi.selectOnboardingImportDraft(workspaceId, {
application_idempotency_key: applicationKey,
plan_digest: digest,
operation_id: operationId,
operation_version: version,
expected_revision: Number(state.snapshot && state.snapshot.revision || 0),
});
var current = response && response.onboarding ? response.onboarding : response;
if (epoch !== state.epoch || workspaceId !== state.workspaceId || workspaceId !== (currentWorkspace() && currentWorkspace().id)) {
throw new Error(tKey('onboarding.import.selection_failed'));
}
if (!current || !current.import_context
|| current.import_context.selected_operation_id !== operationId
|| Number(current.import_context.selected_operation_version) !== version) {
throw new Error(tKey('onboarding.import.selection_failed'));
}
if (current && typeof current === 'object' && 'revision' in current) {
state.snapshot = current;
render();
}
return response;
} catch (error) {
if (error && error.status === 409 && epoch === state.epoch && workspaceId === state.workspaceId) {
await refresh();
}
throw error;
}
}
function renderOpenApiPath() {
var section = document.createElement('div');
section.className = 'onboarding-openapi-path';
var hint = document.createElement('p');
hint.className = 'onboarding-openapi-hint';
hint.textContent = tKey('onboarding.openapi_hint');
var openButton = button(tKey('onboarding.openapi_path'), 'onboarding-openapi-path', openOpenApiPath, 'onboarding-step-action');
section.appendChild(hint);
section.appendChild(openButton);
return section;
}
async function continueWithImportedDraft(choice) {
var context = state.snapshot && state.snapshot.import_context;
if (!context || !choice || choice.selectable !== true) return;
state.importError = null;
render();
try {
await selectImportedDraft(choice.operation_id, choice.version, null);
window.location.href = '/wizard/?mode=edit&operationId=' + encodeURIComponent(choice.operation_id)
+ '&operationVersion=' + encodeURIComponent(choice.version) + '&onboarding=1'
+ '&return=' + encodeURIComponent(boundedReturnContext());
} catch (_error) {
state.importError = tKey('onboarding.import.selection_failed');
render();
}
}
function renderImportContext() {
var context = state.snapshot && state.snapshot.import_context;
if (!context) return null;
var section = document.createElement('section');
section.className = 'onboarding-import-report';
section.dataset.testid = 'onboarding-import-context';
var title = document.createElement('h3');
title.textContent = tKey('onboarding.import.report_title');
section.appendChild(title);
if (context.drift) {
var drift = document.createElement('p');
drift.className = 'onboarding-import-drift';
drift.setAttribute('role', 'alert');
drift.textContent = tKey('onboarding.import.drift');
section.appendChild(drift);
}
if (state.importError) {
var error = document.createElement('p');
error.className = 'onboarding-import-error';
error.setAttribute('role', 'alert');
error.textContent = state.importError;
section.appendChild(error);
}
var choices = Array.isArray(context.choices) ? context.choices : [];
function outcomeLabel(outcome) {
var key = 'openapi.plan.outcome.' + String(outcome || '');
return tKey(key) === key ? tKey('openapi.plan.outcome.rejected') : tKey(key);
}
function reasonLabel(reason) {
if (!reason) return '';
return window.CrankOpenApiImport && typeof window.CrankOpenApiImport.describeFinding === 'function'
? window.CrankOpenApiImport.describeFinding(reason)
: tKey('openapi.finding.generic');
}
var list = document.createElement('ul');
list.className = 'onboarding-import-report-list';
choices.forEach(function(choice) {
var item = document.createElement('li');
item.className = 'onboarding-import-report-item';
var summary = document.createElement('span');
summary.textContent = [choice.name || choice.key || '', outcomeLabel(choice.outcome), choice.version ? 'v' + choice.version : '', reasonLabel(choice.reason)]
.filter(Boolean).join(' · ');
item.appendChild(summary);
if (choice.selectable === true && (!context.selected_operation_id || context.drift)) {
item.appendChild(button(tKey('onboarding.import.continue'), null, function() { continueWithImportedDraft(choice); }, 'onboarding-step-action'));
} else if (choice.operation_id === context.selected_operation_id && Number(choice.version) === Number(context.selected_operation_version)) {
var selected = document.createElement('span');
selected.className = 'onboarding-import-selected';
selected.textContent = tKey('onboarding.import.selected');
item.appendChild(selected);
}
list.appendChild(item);
});
section.appendChild(list);
section.appendChild(button(tKey('onboarding.import.view_report'), null, openOpenApiPath, 'onboarding-link-button'));
return section;
}
function recordStarted() {
if (state.startedRequested || !state.snapshot || state.snapshot.completed) return;
state.startedRequested = true;
@@ -240,6 +455,17 @@
});
body.appendChild(list);
}
var returnContext = document.createElement('span');
returnContext.className = 'onboarding-return-context';
returnContext.dataset.testid = 'onboarding-return-context';
returnContext.hidden = true;
returnContext.textContent = returnContextFromQuery();
body.appendChild(returnContext);
if (!state.snapshot.completed) {
body.appendChild(renderOpenApiPath());
}
var importReport = renderImportContext();
if (importReport) body.appendChild(importReport);
var footer = document.createElement('div');
footer.className = 'onboarding-footer';
footer.appendChild(button(tKey('onboarding.refresh'), 'onboarding-refresh', refresh, 'onboarding-link-button'));
@@ -295,6 +521,7 @@
var snapshot = await window.CrankApi.getOnboarding(workspaceId);
if (epoch !== state.epoch || workspaceId !== (currentWorkspace() && currentWorkspace().id)) return;
state.snapshot = snapshot;
state.importError = null;
var preference = safePreference();
if (window.location.pathname === '/'
&& !preference.opened
@@ -304,6 +531,21 @@
setOpen(true);
}
renderDeepLinkRecovery(snapshot);
if (window.location.pathname === '/' && new URLSearchParams(window.location.search).get('onboarding_openapi') === '1'
&& window.CrankOpenApiImport && typeof window.CrankOpenApiImport.open === 'function') {
var openUrl = new URL(window.location.href);
openUrl.searchParams.delete('onboarding_openapi');
window.history.replaceState(window.history.state, '', openUrl.pathname + openUrl.search + openUrl.hash);
window.CrankOpenApiImport.open({
workspaceId: workspaceId,
onboarding: true,
returnContext: returnContextFromQuery(),
importContext: snapshot.import_context || null,
onImported: function(identity) { return registerImportedApplication(identity); },
onSelectDraft: function(operationId, version, identity) { return selectImportedDraft(operationId, version, identity); },
});
}
return snapshot;
} catch (error) {
if (epoch !== state.epoch) return;
state.error = error;
@@ -485,4 +727,14 @@
window.addEventListener('storage', function(event) { if (event.key === 'crank_onboarding_signal') refresh(); });
document.addEventListener('visibilitychange', function() { if (!document.hidden) refresh(); });
document.addEventListener('keydown', function(event) { if (event.key === 'Escape' && state.open) setOpen(false); });
// Shell menus own the pointer plane. Capture before their handlers stop
// propagation so the optional helper cannot cover an opened menu.
document.addEventListener('click', function(event) {
if (state.open && event.target instanceof Element
&& event.target.closest('.nav-avatar, .nav-hamburger')) {
// Keep keyboard focus on the shell control that the user just activated.
lastFocused = null;
setOpen(false);
}
}, true);
}());
+1790 -183
View File
File diff suppressed because it is too large. Load diff
+81
View File
@@ -1,6 +1,8 @@
var wizardOperationLoadGeneration = 0;
var wizardLifecycleActionBusy = false;
var wizardTestConfirmationToken = null;
var wizardSavedDraftPayload = null;
var wizardPinnedVersionStale = false;
function operationErrorCode(error) {
return error && error.payload && error.payload.error
@@ -130,12 +132,33 @@ async function saveOperation(stayOnPage) {
async function loadOperationForEdit() {
if (!wizardWorkspaceId || !wizardEditId) return;
var generation = ++wizardOperationLoadGeneration;
wizardCurrentOperation = null;
wizardCurrentVersion = null;
wizardSavedDraftPayload = null;
wizardPinnedVersionStale = false;
var pinnedVersionValue = new URLSearchParams(window.location.search).get('operationVersion');
var pinnedVersion = null;
if (pinnedVersionValue !== null) {
pinnedVersion = Number(pinnedVersionValue);
if (!/^[0-9]{1,10}$/.test(pinnedVersionValue) || !Number.isSafeInteger(pinnedVersion) || pinnedVersion < 1) {
wizardPinnedVersionStale = true;
showWizardLiveStatus(tKey('wizard.stale.title'), tKey('wizard.stale.body'), true);
return;
}
}
var requestedWorkspaceId = wizardWorkspaceId;
var requestedOperationId = wizardEditId;
var detail = await window.CrankApi.getOperation(requestedWorkspaceId, requestedOperationId);
if (generation !== wizardOperationLoadGeneration
|| requestedWorkspaceId !== wizardWorkspaceId
|| requestedOperationId !== wizardEditId) return;
var detailDraftVersion = Number(detail.draft_version_ref && detail.draft_version_ref.version
|| detail.current_draft_version);
if (pinnedVersion !== null && detailDraftVersion !== pinnedVersion) {
wizardPinnedVersionStale = true;
showWizardLiveStatus(tKey('wizard.stale.title'), tKey('wizard.stale.body'), true);
return;
}
wizardProtocol = detail.protocol || 'rest';
await loadWizardPanels([3]);
var draftVersion = await window.CrankApi.getOperationVersion(
@@ -146,9 +169,24 @@ async function loadOperationForEdit() {
if (generation !== wizardOperationLoadGeneration
|| requestedWorkspaceId !== wizardWorkspaceId
|| requestedOperationId !== wizardEditId) return;
if (pinnedVersion !== null) {
var currentDetail = await window.CrankApi.getOperation(requestedWorkspaceId, requestedOperationId);
if (generation !== wizardOperationLoadGeneration
|| requestedWorkspaceId !== wizardWorkspaceId
|| requestedOperationId !== wizardEditId) return;
var currentDraftVersion = Number(currentDetail.draft_version_ref && currentDetail.draft_version_ref.version
|| currentDetail.current_draft_version);
if (currentDraftVersion !== pinnedVersion) {
wizardPinnedVersionStale = true;
showWizardLiveStatus(tKey('wizard.stale.title'), tKey('wizard.stale.body'), true);
return;
}
detail = currentDetail;
}
wizardCurrentOperation = detail;
wizardCurrentVersion = draftVersion;
prefillWizardFromEdit(detail, draftVersion);
wizardSavedDraftPayload = updateOperationPayload(collectWizardPayload());
renderAgentFacingPreview();
renderImportQualityFindings(draftVersion);
}
@@ -375,6 +413,27 @@ function updateOperationPayload(payload) {
};
}
function canonicalDraftPayload(payload) {
var editablePayload = updateOperationPayload(payload);
delete editablePayload.category;
function sortKeys(value) {
if (Array.isArray(value)) return value.map(sortKeys);
if (!value || typeof value !== 'object') return value;
return Object.keys(value).sort().reduce(function(sorted, key) {
sorted[key] = sortKeys(value[key]);
return sorted;
}, {});
}
return JSON.stringify(sortKeys(editablePayload));
}
function draftPayloadMatchesBaseline(payload) {
return wizardSavedDraftPayload !== null
&& canonicalDraftPayload(payload) === canonicalDraftPayload(wizardSavedDraftPayload);
}
async function refreshCurrentOperationState() {
if (!wizardWorkspaceId || !wizardEditId) return null;
var detail = await window.CrankApi.getOperation(wizardWorkspaceId, wizardEditId);
@@ -396,6 +455,9 @@ async function refreshCurrentOperationState() {
}
async function persistCurrentDraft(stayOnPage) {
if (wizardPinnedVersionStale) {
throw new Error(tKey('wizard.stale.body'));
}
if (!wizardWorkspaceId) {
throw new Error(tKey('wizard.error.no_workspace'));
}
@@ -405,14 +467,33 @@ async function persistCurrentDraft(stayOnPage) {
var createdNow = false;
if (wizardMode === 'edit' && wizardEditId) {
if (draftPayloadMatchesBaseline(payload)) {
if (stayOnPage) {
var unchangedSaveDraftBtn = document.querySelector('.btn-save-draft');
if (unchangedSaveDraftBtn) {
var unchangedLabel = unchangedSaveDraftBtn.textContent;
unchangedSaveDraftBtn.textContent = tKey('wizard.save.saved');
setTimeout(function() {
unchangedSaveDraftBtn.textContent = unchangedLabel;
}, 1400);
}
}
return {
operation_id: wizardEditId,
version: currentDraftVersion(),
status: 'draft',
};
}
response = await window.CrankApi.updateOperation(
wizardWorkspaceId,
wizardEditId,
updateOperationPayload(payload)
);
wizardSavedDraftPayload = updateOperationPayload(payload);
} else {
response = await window.CrankApi.createOperation(wizardWorkspaceId, payload);
createdNow = true;
wizardSavedDraftPayload = updateOperationPayload(payload);
wizardEditId = response.operation_id;
wizardMode = 'edit';
history.replaceState(
+2 -2
View File
@@ -253,7 +253,7 @@
var source = mappingEntrySource(parsed[outputField]);
return {
output: outputField,
responsePath: responseSourceToPath(source) || outputField,
responsePath: responseSourceToPath(source),
};
});
}
@@ -492,7 +492,7 @@
responseRows.forEach(function(row) {
var responsePath = valueIn(row, 'responsePath');
var output = valueIn(row, 'output') || outputNameFromPath(responsePath);
if (!responsePath || !output) return;
if (!output) return;
responseMapping[output] = joinJsonPath('$.response.body', responsePath);
});
writeText('tool-output-mapping', dumpYaml(responseMapping));
+1 -1
View File
@@ -371,7 +371,7 @@ function startNewUpstream() {
setValue('new-auth-profile-password-secret', '');
updateUpstreamAuthUi();
var first = form.querySelector('input');
if (first) setTimeout(function() { first.focus(); }, 50);
if (first) first.focus();
}
}
+10
View File
@@ -21,6 +21,16 @@ server {
return 302 /;
}
location ~ ^/api/admin/workspaces/[^/]+/imports/openapi/[^/]+/plans$ {
client_max_body_size 16m;
proxy_pass http://admin-api:3001;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location /api/ {
proxy_pass http://admin-api:3001;
proxy_http_version 1.1;
+63 -6
View File
@@ -101,6 +101,7 @@ trap cleanup EXIT
trap 'exit 130' INT TERM
cleanup
rm -f "$TMP_DIR/admin-control.request" "$TMP_DIR/admin-control.ack"
show_startup_log() {
local log_file="$1"
@@ -235,7 +236,8 @@ chmod 700 "$CRANK_STORAGE_ROOT"
(
cd "$ROOT_DIR/apps/ui"
exec node scripts/playwright-http-fixture.js >"$LOG_DIR/http-fixture.log" 2>&1
exec env CRANK_E2E_STREAM_FIXTURE_PORT="$STREAM_FIXTURE_PORT" \
node scripts/playwright-http-fixture.js >"$LOG_DIR/http-fixture.log" 2>&1
) &
echo $! > "$TMP_DIR/http-fixture.pid"
@@ -292,12 +294,27 @@ if ! (
exit 1
fi
# Launch the built executable directly so the test lifecycle controls the
# actual server PID, rather than a Cargo wrapper. This control exists only in
# the local Playwright harness and adds no application endpoint/configuration.
(
cd "$ROOT_DIR"
exec env -u CRANK_MCP_BIND -u CRANK_MCP_REFRESH_MS CRANK_DEMO_SEED=true \
cargo run -p admin-api --bin admin-api >>"$LOG_DIR/admin-api.log" 2>&1
) &
echo $! > "$TMP_DIR/admin-api.pid"
cargo build -p admin-api --bin admin-api --example e2e_storage_counts >>"$LOG_DIR/admin-api.log" 2>&1
)
ADMIN_BINARY="${CARGO_TARGET_DIR:-$ROOT_DIR/target}/debug/admin-api"
if [[ "$ADMIN_BINARY" != /* ]]; then
ADMIN_BINARY="$ROOT_DIR/$ADMIN_BINARY"
fi
STORAGE_COUNTS_BINARY="$(dirname "$ADMIN_BINARY")/examples/e2e_storage_counts"
start_admin() {
(
cd "$ROOT_DIR"
exec env -u CRANK_MCP_BIND -u CRANK_MCP_REFRESH_MS CRANK_DEMO_SEED=true \
"$ADMIN_BINARY" >>"$LOG_DIR/admin-api.log" 2>&1
) &
echo $! > "$TMP_DIR/admin-api.pid"
}
start_admin
wait_for_http \
"admin-api" \
@@ -322,7 +339,9 @@ wait_for_http \
(
cd "$ROOT_DIR/apps/ui"
exec node scripts/playwright-ui-server.js >"$LOG_DIR/ui-server.log" 2>&1
exec env CRANK_E2E_UI_PORT="$UI_PORT" CRANK_E2E_ADMIN_PORT="$ADMIN_PORT" \
CRANK_E2E_MCP_PORT="$MCP_PORT" \
node scripts/playwright-ui-server.js >"$LOG_DIR/ui-server.log" 2>&1
) &
echo $! > "$TMP_DIR/ui-server.pid"
@@ -335,5 +354,43 @@ wait_for_http \
echo "Crank UI e2e stack is ready on http://127.0.0.1:$UI_PORT"
while true; do
if [[ -f "$TMP_DIR/admin-control.request" ]]; then
command=""
read -r command < "$TMP_DIR/admin-control.request" || true
rm -f "$TMP_DIR/admin-control.request"
case "$command" in
stop)
if [[ -f "$TMP_DIR/admin-api.pid" ]]; then
admin_pid="$(cat "$TMP_DIR/admin-api.pid")"
kill "$admin_pid" 2>/dev/null || true
wait "$admin_pid" || true
rm -f "$TMP_DIR/admin-api.pid"
fi
;;
start)
if [[ ! -f "$TMP_DIR/admin-api.pid" ]] || \
! kill -0 "$(cat "$TMP_DIR/admin-api.pid")" 2>/dev/null; then
start_admin
fi
wait_for_http "restarted admin-api" "http://127.0.0.1:$ADMIN_PORT/health" \
"$TMP_DIR/admin-api.pid" "$LOG_DIR/admin-api.log" || exit 1
;;
counts\ *)
workspace="${command#counts }"
if [[ ! "$workspace" =~ ^[a-zA-Z0-9_-]{1,128}$ ]]; then
echo "Invalid local storage observation scope" >&2
exit 1
fi
"$STORAGE_COUNTS_BINARY" "$workspace" > "$TMP_DIR/storage-counts.json.tmp"
mv "$TMP_DIR/storage-counts.json.tmp" "$TMP_DIR/storage-counts.json"
;;
*)
echo "Unknown local Admin API test control command" >&2
exit 1
;;
esac
printf '%s\n' "$command" > "$TMP_DIR/admin-control.ack.tmp"
mv "$TMP_DIR/admin-control.ack.tmp" "$TMP_DIR/admin-control.ack"
fi
sleep 1
done
+4
View File
@@ -15,6 +15,10 @@ async function login(page) {
await page.locator('.btn-signin').click();
await expect(page).toHaveURL(/\/$/);
await expect(page.locator('.page-title, .page-heading').first()).toBeVisible();
await page.waitForFunction(() => Boolean(window.CrankAuth && typeof window.CrankAuth.fetchSession === 'function'));
await page.evaluate(async () => {
await window.CrankAuth.fetchSession(false);
});
}
async function browserJson(page, method, urlPath, body, okStatuses = [200]) {
+19
View File
@@ -0,0 +1,19 @@
const { test, expect } = require('@playwright/test');
const { login } = require('./helpers');
test('login helper leaves a ready CSRF session under a delayed csrf refresh', async ({ page }) => {
let csrfRequests = 0;
await page.route('**/api/auth/session/csrf', async (route) => {
csrfRequests += 1;
await new Promise((resolve) => setTimeout(resolve, 800));
await route.continue();
});
await login(page);
const tokenReady = await page.evaluate(
() => Boolean(window.CrankAuth && typeof window.CrankAuth.getCsrfToken === 'function' && window.CrankAuth.getCsrfToken())
);
expect(tokenReady).toBe(true);
expect(csrfRequests).toBeGreaterThan(0);
});
@@ -0,0 +1,155 @@
const { test, expect } = require('@playwright/test');
const { getCurrentWorkspace, login } = require('./helpers');
function onboardingSnapshot(workspaceId) {
return {
schema_version: 1,
workspace_id: workspaceId,
revision: 1,
status: 'in_progress',
dismissed: false,
eligible_since: '2026-08-23T08:00:00Z',
started_at: '2026-08-23T08:01:00Z',
completed_at: null,
steps: [
{ kind: 'operation', status: 'complete', action: 'open_operation' },
{ kind: 'test', status: 'complete', action: 'open_operation' },
{ kind: 'publish', status: 'complete', action: 'open_operation' },
{ kind: 'agent', status: 'current', action: 'create_agent' },
{ kind: 'key', status: 'pending', action: 'create_key' },
{ kind: 'connection', status: 'pending', action: 'show_connection' },
{ kind: 'first_call', status: 'pending', action: 'open_logs' },
],
operation: { id: 'op_shell_layout', published_version: 1, last_test: null },
agent: null,
key: null,
connection: { status: 'pending', reason_code: 'key_required' },
first_call: null,
};
}
function rectsIntersect(a, b) {
return a.x < b.x + b.width
&& a.x + a.width > b.x
&& a.y < b.y + b.height
&& a.y + a.height > b.y;
}
async function openShellLayoutCase(page, path) {
await login(page);
const workspace = await getCurrentWorkspace(page);
await page.route(/\/api\/admin\/workspaces\/[^/]+\/onboarding(?:\/events)?(?:\?.*)?$/, async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(onboardingSnapshot(workspace.id)),
});
});
await page.goto(path);
// Open the full server-derived Getting Started panel explicitly. The panel is
// auto-opened for a fresh workspace, but the trigger is used when a previous
// navigation already persisted the "opened" UI preference.
const trigger = page.getByTestId('onboarding-trigger');
const checklist = page.getByTestId('onboarding-checklist');
if (!await checklist.isVisible()) await trigger.click();
await expect(checklist).toBeVisible();
await expect(checklist.locator('ol > li')).toHaveCount(7);
const avatar = page.getByTestId('shell-avatar');
await expect(avatar).toBeVisible();
const navbar = page.locator('.navbar');
const navbarBox = await navbar.boundingBox();
const avatarBox = await avatar.boundingBox();
const panelBox = await checklist.boundingBox();
// Real hit-testing at the avatar centre: whatever would receive the pointer
// event must be the avatar itself, not the onboarding panel or its head.
// Playwright's click actionability uses exactly this condition, so this is
// the deterministic equivalent of the CI830 shell-avatar.click interception.
const avatarCentre = {
x: avatarBox.x + avatarBox.width / 2,
y: avatarBox.y + avatarBox.height / 2,
};
const hit = await page.evaluate((centre) => {
const element = document.elementFromPoint(centre.x, centre.y);
if (!element) return null;
const owner = element.closest('[data-testid="shell-avatar"]');
return {
isAvatar: Boolean(owner),
tag: element.tagName,
className: String(element.className || ''),
testId: element.getAttribute('data-testid'),
};
}, avatarCentre);
console.log('shell-layout geometry', JSON.stringify({
path,
viewport: page.viewportSize(),
navbar: navbarBox,
avatar: avatarBox,
avatarCentre,
panel: panelBox,
hit,
}));
expect(hit, `no element at avatar centre ${JSON.stringify(avatarCentre)}`).not.toBeNull();
expect(
hit.isAvatar,
`avatar centre ${JSON.stringify(avatarCentre)} is covered by ${JSON.stringify(hit)}`,
).toBe(true);
// The sticky header owns the top of the viewport; an optional helper panel
// must never overlap it.
expect(
rectsIntersect(panelBox, navbarBox),
`onboarding panel ${JSON.stringify(panelBox)} overlaps header ${JSON.stringify(navbarBox)}`,
).toBe(false);
// A single real (non-forced) click on the avatar must open the shell user menu.
await avatar.click();
await expect(page.getByTestId('shell-user-name').first()).toBeVisible();
const settings = page.locator('.user-dropdown-item').first();
await expect.poll(() => settings.evaluate((element) => {
const box = element.getBoundingClientRect();
const hit = document.elementFromPoint(box.x + box.width / 2, box.y + box.height / 2);
return element === hit || element.contains(hit);
})).toBe(true);
await settings.click();
await expect(page).toHaveURL(/\/settings(?:#profile)?$/);
if (page.viewportSize().width <= 640) {
await page.goto(path);
if (!await checklist.isVisible()) await trigger.click();
await expect(checklist).toBeVisible();
await expect(checklist.locator('ol > li')).toHaveCount(7);
const hamburger = page.locator('.nav-hamburger');
await hamburger.focus();
await hamburger.press('Enter');
await expect(hamburger).toBeFocused();
const mobileNavigation = page.locator('.mobile-nav');
await expect(mobileNavigation).toBeVisible();
await mobileNavigation.locator('a[href="/agents"]').click();
await expect(page).toHaveURL(/\/agents\/?$/);
}
}
const CASES = [
{ path: '/', viewport: { width: 1280, height: 720 } },
{ path: '/', viewport: { width: 390, height: 720 } },
{ path: '/wizard/', viewport: { width: 1280, height: 720 } },
{ path: '/wizard/', viewport: { width: 390, height: 720 } },
];
for (const testCase of CASES) {
test.describe(`${testCase.path} at ${testCase.viewport.width}x${testCase.viewport.height}`, () => {
test.use({ viewport: testCase.viewport });
test('an open Getting Started panel never covers the shell avatar in the header', async ({ page }) => {
await openShellLayoutCase(page, testCase.path);
});
});
}
+69 -4
View File
@@ -133,6 +133,59 @@ test('optional Getting Started checklist is server-derived, resumable, bilingual
await expect(page.getByTestId('onboarding-checklist')).toHaveCSS('scroll-behavior', 'auto');
});
test('onboarding return context drops unknown query secrets and bounds allowlisted navigation context', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
await routeOnboarding(page, async (route) => {
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(onboardingSnapshot(workspace.id)),
});
});
await page.goto('/agents?onboarding=1&token=crk_return_secret_canary');
if (!await page.getByTestId('onboarding-checklist').isVisible()) await page.getByTestId('onboarding-trigger').click();
const returnContext = page.getByTestId('onboarding-return-context');
await expect(returnContext).toHaveText('/agents?onboarding=1');
await expect(returnContext).not.toContainText('crk_return_secret_canary');
await page.goto('/logs?log_id=' + 'a'.repeat(128) + '&agent_id=' + 'b'.repeat(128) + '&operation_id=' + 'c'.repeat(128));
if (!await page.getByTestId('onboarding-checklist').isVisible()) await page.getByTestId('onboarding-trigger').click();
await expect(page.getByTestId('onboarding-return-context')).toHaveText('/logs');
await page.goto('/secrets?token=crk_return_secret_canary');
if (!await page.getByTestId('onboarding-checklist').isVisible()) await page.getByTestId('onboarding-trigger').click();
await expect(page.getByTestId('onboarding-return-context')).toHaveText('/secrets');
});
test('a stale onboarding-pinned wizard version is rejected before loading or saving another Draft', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
const operationId = 'op_pinned';
let versionReads = 0;
let writes = 0;
await page.route(`**/workspaces/${workspace.id}/operations/${operationId}`, async (route) => {
if (route.request().method() !== 'GET') writes += 1;
await route.fulfill({ contentType: 'application/json', body: JSON.stringify({
id: operationId, protocol: 'rest', current_draft_version: 3,
draft_version_ref: { version: 3 },
}) });
});
await page.route(`**/operations/${operationId}/versions/*`, async (route) => {
versionReads += 1;
await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ version: 3 }) });
});
await page.goto(`/wizard/?mode=edit&operationId=${operationId}&operationVersion=2`);
await page.waitForFunction(() => window.CrankWizardReady === true);
await expect(page.locator('#wizard-live-status')).toBeVisible();
await expect(page.locator('#tool-name')).not.toHaveValue('wrong newer Draft');
await page.locator('.btn-save-draft').click();
expect(versionReads).toBe(0);
expect(writes).toBe(0);
expect(await page.evaluate(() => window.wizardCurrentOperation)).toBeNull();
});
test('onboarding error exposes safe support correlation and retries without a client completion bypass', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
@@ -156,7 +209,11 @@ test('onboarding error exposes safe support correlation and retries without a cl
});
await page.goto('/');
await page.getByTestId('onboarding-trigger').click();
await expect(page.getByTestId('onboarding-trigger')).toContainText(/3\s*\/\s*7/);
if (!await page.getByTestId('onboarding-checklist').isVisible()) {
await page.getByTestId('onboarding-trigger').click();
}
await expect(page.getByTestId('onboarding-checklist')).toBeVisible();
fail = true;
await page.getByTestId('onboarding-refresh').click();
const alert = page.getByRole('alert');
@@ -180,7 +237,7 @@ test('validation, upstream and compatibility errors recover from the last author
];
let failureIndex = -1;
await routeOnboarding(page, async (route) => {
if (failureIndex >= 0) {
if (failureIndex >= 0 && route.request().method() === 'GET') {
const failure = failures[failureIndex];
await route.fulfill({
status: failure.status,
@@ -198,7 +255,11 @@ test('validation, upstream and compatibility errors recover from the last author
});
await page.goto('/');
await page.getByTestId('onboarding-trigger').click();
await expect(page.getByTestId('onboarding-trigger')).toContainText(/3\s*\/\s*7/);
if (!await page.getByTestId('onboarding-checklist').isVisible()) {
await page.getByTestId('onboarding-trigger').click();
}
await expect(page.getByTestId('onboarding-checklist')).toBeVisible();
for (let index = 0; index < failures.length; index += 1) {
failureIndex = index;
await page.getByTestId('onboarding-refresh').click();
@@ -231,7 +292,11 @@ test('authentication recovery returns to an incomplete authoritative onboarding
});
await page.goto('/');
await page.getByTestId('onboarding-trigger').click();
// Wait for the initial projection and its automatic panel opening before toggling.
await expect(page.getByTestId('onboarding-trigger')).toContainText(/3\s*\/\s*7/);
if (!await page.getByTestId('onboarding-checklist').isVisible()) {
await page.getByTestId('onboarding-trigger').click();
}
rejectOnce = true;
await page.getByTestId('onboarding-refresh').click();
await expect(page).toHaveURL(/\/login/);
@@ -0,0 +1,336 @@
const { test, expect } = require('@playwright/test');
const { login, localized, uniqueName } = require('./helpers');
async function dismissOnboardingIfOpen(page) {
await page.locator('#crank-onboarding-panel').waitFor({ state: 'attached' });
await page.locator('[data-testid="onboarding-dismiss"]').waitFor({ state: 'attached' });
await page.evaluate(() => {
const dismiss = document.querySelector('[data-testid="onboarding-dismiss"]');
if (dismiss) dismiss.click();
});
await expect(page.locator('#crank-onboarding-panel')).toBeHidden();
}
function importDocument(prefix) {
return [
'openapi: 3.0.3',
'info: { title: ImportPlan UI test, version: \'1\' }',
'paths:',
' /' + prefix + '-selected:',
' get:',
' operationId: ' + prefix + '_selected',
' responses:',
' \'200\': { description: OK }',
' /' + prefix + '-excluded:',
' get:',
' operationId: ' + prefix + '_excluded',
' responses:',
' \'200\': { description: OK }',
].join('\n');
}
function planResponse(prefix) {
return {
plan_reference: 'plan_e2e_importplan_213',
plan_digest: 'a'.repeat(64),
expires_at: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
selection_mode: 'partial',
counts: { selected: 1, excluded: 1, actionable: 1, blocked: 0 },
candidates: [
{
key: 'GET /' + prefix + '-selected',
name: 'selected_operation',
state: 'actionable',
action: 'new_version',
target_operation_id: 'op_existing_target',
confirmed_name: null,
auth_profile_id: null,
reason: null,
},
{
key: 'GET /' + prefix + '-excluded',
name: 'excluded_operation',
state: 'excluded',
action: null,
target_operation_id: null,
confirmed_name: null,
auth_profile_id: null,
reason: 'not_selected',
},
],
};
}
async function preparePlanFlow(page, locale, reportFixture) {
const planCalls = [];
const applyCalls = [];
const prefix = uniqueName('plan_apply');
let releaseApplyResponse;
const applyResponseHeld = new Promise((resolve) => {
releaseApplyResponse = resolve;
});
// Keep this mock aligned with the public CreatePlan response shape.
await page.route('**/api/admin/workspaces/*/operations', async (route) => {
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({ items: [], page: 1, page_size: 0, total: 0 }),
});
});
await page.route(/\/imports\/openapi\/[^/]+\/plans$/, async (route) => {
planCalls.push({
url: route.request().url(),
payload: route.request().postDataJSON(),
});
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(planResponse(prefix)),
});
});
await page.route(/\/imports\/openapi\/[^/]+\/apply$/, async (route) => {
applyCalls.push({
url: route.request().url(),
payload: route.request().postDataJSON(),
});
// Keep the request pending until the test has checked the duplicate guard.
await applyResponseHeld;
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(reportFixture || {
plan_digest: 'a'.repeat(64),
counts: { selected: 1, excluded: 1, created: 0, versioned: 1 },
outcomes: [{ status: 'versioned' }],
}),
});
});
// Contain the legacy path so this red-phase test cannot mutate the E2E DB.
await page.route(/\/imports\/openapi\/[^/]+\/create$/, async (route) => {
await route.fulfill({
status: 409,
contentType: 'application/json',
body: JSON.stringify({ message: 'ImportPlan flow required' }),
});
});
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 expect(page.locator('#openapi-import-modal')).toBeVisible();
await page.locator('#openapi-import-file').setInputFiles({
name: 'import-plan.yaml',
mimeType: 'application/yaml',
buffer: Buffer.from(importDocument(prefix)),
});
const previewResponse = page.waitForResponse((response) =>
response.request().method() === 'POST'
&& response.url().includes('/imports/openapi/preview'),
);
await page.locator('#openapi-import-preview').click();
await previewResponse;
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
await page.locator('#openapi-import-server-custom').fill('https://api.example.test');
// The existing preview action becomes Plan creation followed by confirmation.
await page.locator('#openapi-import-create').click();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
await expect.poll(() => planCalls.length).toBe(1);
return { planCalls, applyCalls, prefix, releaseApplyResponse };
}
async function assertConfirmation(page, prefix) {
const confirmation = page.locator('[data-testid="openapi-import-apply-confirmation"]');
const counts = page.locator('[data-testid="openapi-import-apply-counts"]');
const versioning = page.locator('[data-testid="openapi-import-versioning-consequences"]');
await expect(counts).toContainText(localized('Selected: 1', 'Выбрано: 1'));
await expect(counts).toContainText(localized('Excluded: 1', 'Исключено: 1'));
await expect(counts).toContainText(localized('Actionable: 1', 'Можно применить: 1'));
await expect(counts).toContainText(localized('Blocked: 0', 'Заблокировано: 0'));
await expect(versioning).toContainText(localized('new Draft Version', 'новая версия черновика'));
await expect(versioning).toContainText(
localized('Published Version and history remain unchanged', 'Опубликованная версия и история останутся без изменений'),
);
await expect(confirmation).toContainText('GET /' + prefix + '-selected');
await expect(confirmation).toContainText('GET /' + prefix + '-excluded');
await expect(confirmation).toContainText('op_existing_target');
}
test('[P1] AC-13 renders server-confirmed partial and new_version consequences in RU and EN', async ({ page }) => {
// This test covers rendering of a stored server plan only. It does not
// specify how UI controls compose selection/decision request fields.
const { planCalls, prefix } = await preparePlanFlow(page, 'ru');
for (const locale of ['ru', 'en']) {
await test.step('confirmation in ' + locale, async () => {
await page.evaluate((language) => window.setLang(language), locale);
await assertConfirmation(page, prefix);
});
}
expect(planCalls).toHaveLength(1);
expect(planCalls[0].url).toMatch(/\/imports\/openapi\/[^/]+\/plans$/);
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]').getByRole('button', {
name: localized('Apply import', 'Применить импорт'),
})).toBeVisible();
});
test('[P1] AC-13 double-click sends one Apply with the stored reference, digest and idempotency key', async ({ page }) => {
const { applyCalls, releaseApplyResponse } = await preparePlanFlow(page, 'en');
const applyButton = page.getByRole('button', {
name: localized('Apply import', 'Применить импорт'),
});
await applyButton.dblclick();
await expect.poll(() => applyCalls.length).toBe(1);
await expect(applyButton).toBeDisabled();
releaseApplyResponse();
await expect(page.locator('[data-testid="openapi-import-apply-result"]')).toBeVisible();
expect(applyCalls).toHaveLength(1);
expect(applyCalls[0].url).toMatch(/\/imports\/openapi\/plan_e2e_importplan_213\/apply$/);
expect(applyCalls[0].payload).toMatchObject({
plan_digest: 'a'.repeat(64),
});
expect(typeof applyCalls[0].payload.idempotency_key).toBe('string');
expect(applyCalls[0].payload.idempotency_key.length).toBeGreaterThan(0);
});
for (const locale of ['en', 'ru']) {
test(`[P1] AC-2.13-13 renders every immutable Apply outcome in ${locale}`, async ({ page }) => {
const reportFixture = {
plan_digest: 'd'.repeat(64),
idempotency_key: 'apply-report-full-outcomes',
status: 'applied',
counts: { selected: 5, excluded: 0, created: 1, versioned: 1, renamed: 1, skipped: 1, rejected: 1 },
outcomes: [
{ key: 'GET /created', name: 'created_operation', status: 'created', version: 1 },
{ key: 'GET /versioned', name: 'versioned_operation', status: 'versioned', version: 2 },
{ key: 'GET /renamed', name: 'renamed_operation', status: 'renamed', version: 1 },
{ key: 'GET /skipped', name: 'skipped_operation', status: 'skipped', reason: 'not_selected' },
{
key: 'GET /rejected',
name: 'rejected_operation',
status: 'rejected',
reason: 'unsupported_schema',
message: 'raw-report-canary https://report-secret.example.test/internal',
},
],
};
const { releaseApplyResponse } = await preparePlanFlow(page, locale, reportFixture);
await page.locator('[data-testid="openapi-import-apply-confirmation"]').getByRole('button', {
name: localized('Apply import', 'Применить импорт'),
}).click();
releaseApplyResponse();
const report = page.locator('[data-testid="openapi-import-apply-result"]');
await expect(report).toBeVisible();
await expect(report.locator('.openapi-import-plan-summary')).toContainText(
localized('Applied: 3; skipped: 1; excluded: 0; rejected: 1.', 'Применено: 3; пропущено: 1; исключено: 0; отклонено: 1.'),
);
for (const outcome of reportFixture.outcomes) {
const row = report.locator(`[data-outcome="${outcome.status}"]`);
await expect(row).toHaveCount(1);
await expect(row).toContainText(outcome.name);
await expect(row).toContainText(outcome.key);
if (outcome.version) await expect(row).toContainText(`v${outcome.version}`);
if (outcome.reason) {
const reason = row.locator('.openapi-import-plan-reason');
await expect(reason).toBeVisible();
await expect(reason).toContainText(localized(
'This imported item needs review in the wizard.',
'Этот импортированный элемент нужно проверить в мастере.',
));
}
}
await expect(report.locator('[data-outcome="created"]')).toContainText(localized('Created', 'Создано'));
await expect(report.locator('[data-outcome="versioned"]')).toContainText(localized('New Draft Version', 'Новая версия черновика'));
await expect(report.locator('[data-outcome="renamed"]')).toContainText(localized('Created with confirmed name', 'Создано с подтверждённым именем'));
await expect(report.locator('[data-outcome="skipped"]')).toContainText(localized('Skipped', 'Пропущено'));
await expect(report.locator('[data-outcome="rejected"]')).toContainText(localized('Rejected', 'Отклонено'));
await expect(report).not.toContainText('raw-report-canary');
await expect(report).not.toContainText('https://report-secret.example.test/internal');
});
}
test('[P1] AC-13 submits the confirmed new_version decision for the exact existing operation', async ({ page }) => {
const prefix = uniqueName('plan_version');
const targetOperationId = 'op_exact_importplan_target';
const planCalls = [];
const expectedName = prefix + '_selected';
await page.route('**/api/admin/workspaces/*/operations', async (route) => {
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({
items: [{ id: targetOperationId, name: expectedName, protocol: 'rest', status: 'draft' }],
page: 1,
page_size: 1,
total: 1,
}),
});
});
await page.route(/\/imports\/openapi\/[^/]+\/plans$/, async (route) => {
const payload = route.request().postDataJSON();
planCalls.push(payload);
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({
plan_reference: 'plan_e2e_importplan_decision',
plan_digest: 'b'.repeat(64),
expires_at: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
selection_mode: payload.selection_mode,
counts: { selected: 1, excluded: 0, actionable: 1, blocked: 0 },
candidates: [{
key: payload.decisions[0].operation_key,
name: expectedName,
state: 'actionable',
action: 'new_version',
target_operation_id: targetOperationId,
confirmed_name: null,
auth_profile_id: null,
reason: null,
}],
}),
});
});
await login(page);
await dismissOnboardingIfOpen(page);
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await page.locator('#openapi-import-file').setInputFiles({
name: 'import-plan-decision.yaml',
mimeType: 'application/yaml',
buffer: Buffer.from(importDocument(prefix)),
});
const previewResponse = page.waitForResponse((response) =>
response.request().method() === 'POST' && response.url().includes('/imports/openapi/preview'),
);
await page.locator('#openapi-import-preview').click();
await previewResponse;
const operationRow = page.locator('.openapi-import-operation').filter({ hasText: expectedName });
const operationCheckbox = operationRow.locator('[data-openapi-operation]');
await expect(operationCheckbox).toBeVisible();
const operationKey = await operationCheckbox.inputValue();
await page.locator('#openapi-import-partial-mode').check();
for (const checkbox of await page.locator('[data-openapi-operation]').all()) {
if (await checkbox.inputValue() !== operationKey) await checkbox.uncheck();
}
await expect(operationRow.locator('.openapi-import-operation-meta')).toContainText(expectedName);
const action = operationRow.locator('[data-openapi-decision-action]');
await expect(action.locator('option[value="new_version"]')).toBeEnabled();
await action.selectOption('new_version');
await expect(operationRow.locator('[data-openapi-decision-target]')).toHaveValue(targetOperationId);
await page.locator('#openapi-import-server-custom').fill('https://api.example.test');
await page.locator('#openapi-import-create').click();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toContainText(targetOperationId);
expect(planCalls).toHaveLength(1);
expect(planCalls[0].selection_mode).toBe('partial');
expect(planCalls[0].selected_operation_keys).toEqual([operationKey]);
expect(planCalls[0].decisions).toEqual([{
operation_key: operationKey,
action: 'new_version',
target_operation_id: targetOperationId,
}]);
});
@@ -0,0 +1,943 @@
// Story 2.15 browser acceptance: OpenAPI branch in the guided onboarding.
//
// STATUS: ACTIVE. All leaves are activated and assert the behavior promised by the
// approved spec `_bmad-output/implementation-artifacts/spec-2-15-openapi-guided-onboarding.md`.
//
// Backend authority (immutable ImportPlan apply/replay, onboarding selection and
// event rollups, migration/schema guards) is covered by the Rust integration
// suites mapped in
// `_bmad-output/test-artifacts/atdd-checklist-2-15-openapi-guided-onboarding.md`.
// This file only covers user-observable browser behavior.
const { test, expect } = require('@playwright/test');
const { browserJson, getCurrentWorkspace, login, localized, uniqueName } = require('./helpers');
const SECRET_CANARY = 'crk_onboarding_raw_secret_canary';
const REPRESENTATIVE_OPENAPI = [
'openapi: 3.0.3',
"info: { title: 'Onboarding representative document', version: '1' }",
'servers: [{ url: http://127.0.0.1:3310 }]',
'paths:',
' /rates:',
' get:',
' operationId: listRates',
' responses:',
" '200':",
' description: JSON exchange rates',
' content:',
' application/json:',
' schema:',
' type: object',
' properties:',
' amount: { type: number }',
' base: { type: string }',
' date: { type: string }',
' rates:',
' type: object',
' properties:',
' EUR: { type: number }',
' /health:',
' get:',
' operationId: getHealth',
' responses:',
" '200':",
' description: JSON service health',
' content:',
' application/json:',
' schema:',
' type: object',
' properties:',
' status: { type: string }',
'',
].join('\n');
function representativeOpenApi(suffix) {
const safeSuffix = suffix.replace(/[^a-zA-Z0-9_]/g, '_');
return REPRESENTATIVE_OPENAPI
.replace('operationId: listRates', `operationId: listRates_${safeSuffix}`)
.replace('operationId: getHealth', `operationId: getHealth_${safeSuffix}`);
}
function importContext(report, overrides = {}) {
return Object.assign({
application_idempotency_key: report.idempotency_key,
plan_digest: report.plan_digest,
report,
choices: report.outcomes.map((outcome) => ({
key: outcome.key,
name: outcome.name,
outcome: outcome.outcome,
operation_id: outcome.operation_id,
version: outcome.version,
reason: outcome.reason,
selectable: ['created', 'versioned', 'renamed'].includes(outcome.outcome),
})),
selected_operation_id: null,
selected_operation_version: null,
drift: null,
}, overrides);
}
function registeredResponse(snapshot, context) {
return Object.assign({}, snapshot, {
registered: true,
revision: snapshot.revision + 1,
import_context: context,
});
}
function selectedResponse(snapshot, context, operationId, version) {
return Object.assign({}, snapshot, {
selected: true,
revision: snapshot.revision + 1,
operation_id: operationId,
operation_version: version,
import_context: Object.assign({}, context, {
selected_operation_id: operationId,
selected_operation_version: version,
}),
});
}
function onboardingSnapshot(workspaceId, overrides = {}) {
return {
schema_version: 1,
workspace_id: workspaceId,
revision: 7,
status: 'in_progress',
completed: false,
eligible_since: '2026-10-03T08:00:00Z',
steps: [
{ id: 'operation', completed: false, status: 'current', action_code: 'create_operation', reason_code: 'authoritative_evidence_missing' },
{ id: 'test', completed: false, status: 'pending', action_code: 'test_operation', reason_code: 'prerequisite_incomplete' },
{ id: 'publish_operation', completed: false, status: 'pending', action_code: 'publish_operation', reason_code: 'prerequisite_incomplete' },
{ id: 'agent', completed: false, status: 'pending', action_code: 'publish_agent', reason_code: 'prerequisite_incomplete' },
{ id: 'key', completed: false, status: 'pending', action_code: 'create_mcp_key', reason_code: 'prerequisite_incomplete' },
{ id: 'mcp_connection', completed: false, status: 'pending', action_code: 'connect_mcp_client', reason_code: 'prerequisite_incomplete' },
{ id: 'first_call', completed: false, status: 'pending', action_code: 'call_tool', reason_code: 'prerequisite_incomplete' },
],
operation_id: null,
operation_version: null,
agent_id: null,
catalog_revision: null,
platform_api_key_id: null,
mcp_endpoint: 'http://127.0.0.1:3302/mcp',
first_call: null,
...overrides,
};
}
function candidate(name, overrides = {}) {
const draft = {
name,
display_name: name,
category: 'default',
target: { method: 'GET', path: '/' + name, server_url: 'https://api.example.test' },
input_schema: { type: 'object', properties: {} },
output_schema: { type: 'object', properties: {} },
input_mapping: [],
output_mapping: [],
tool_description: {},
wizard_state: null,
};
return Object.assign(
{
key: 'GET /' + name,
method: 'GET',
path: '/' + name,
status: 'actionable',
operation_id: null,
suggested_name: name,
suggested_display_name: name,
description: 'ATDD candidate',
category: 'default',
input_fields: 0,
output_fields: 1,
server_urls: ['https://api.example.test'],
source_location: { pointer: '/paths/~1' + name + '/get' },
findings: [],
security_requirements: { source: 'none', alternatives: [] },
security_schemes: {},
draft,
},
overrides,
);
}
function previewResponse(operations, extra = {}) {
const base = {
job_id: 'imp_e2e_onboarding_215',
expires_at: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
preview: {
source: { format: 'openapi', version: '3.0.3', title: 'Onboarding ATDD', servers: ['https://api.example.test'] },
groups: [{ key: 'default', title: 'Default', operations }],
findings: [],
conflicts: [],
},
security_profile_choices: [],
};
return Object.assign(base, extra, {
preview: Object.assign(base.preview, extra.preview || {}),
});
}
function planResponse(candidates, overrides = {}) {
return Object.assign(
{
plan_reference: 'plan_e2e_onboarding_215',
plan_digest: 'a'.repeat(64),
expires_at: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
selection_mode: 'full',
counts: { selected: candidates.length, excluded: 0, actionable: candidates.length, blocked: 0 },
candidates,
},
overrides,
);
}
function applyReport(outcomes, overrides = {}) {
return Object.assign(
{
schema_version: 'import-plan-apply-report-v1',
status: 'applied',
plan_id: 'plan_e2e_onboarding_215',
plan_digest: 'a'.repeat(64),
job_id: 'imp_e2e_onboarding_215',
idempotency_key: 'onboarding:apply:1',
source_id: 'src_e2e_onboarding',
source_digest: 'b'.repeat(64),
dependencies: [],
counts: { created: outcomes.length, versioned: 0, renamed: 0, skipped: 0, excluded: 0, rejected: 0 },
outcomes,
summary: 'Plan applied',
recovery: 'none',
applied_at: '2026-10-03T08:05:00Z',
},
overrides,
);
}
async function routeOnboarding(page, snapshot) {
await page.route(
/\/api\/admin\/workspaces\/[^/]+\/onboarding(?:\/events|\/reset-selection)?(?:\?.*)?$/,
async (route) => {
if (route.request().method() === 'GET') {
await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(snapshot) });
return;
}
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify(Object.assign({ accepted: true }, snapshot)),
});
},
);
}
async function routePreview(page, body, status = 200) {
await page.route(/\/imports\/openapi\/preview(?:\?.*)?$/, (route) => route.fulfill({
status,
contentType: 'application/json',
body: JSON.stringify(body),
}));
}
async function routePlanCreate(page, body, status = 200) {
await page.route(/\/imports\/openapi\/[^/]+\/plans(?:\?.*)?$/, (route) => route.fulfill({
status,
contentType: 'application/json',
body: JSON.stringify(body),
}));
}
async function routeApply(page, body, status = 200) {
await page.route(/\/imports\/openapi\/[^/]+\/apply(?:\?.*)?$/, async (route) => {
const requestBody = route.request().postDataJSON();
const responseBody = typeof body === 'function' ? body(requestBody) : body;
await route.fulfill({ status, contentType: 'application/json', body: JSON.stringify(responseBody) });
});
}
async function openOnboarding(page) {
await login(page);
const workspace = await getCurrentWorkspace(page);
await routeOnboarding(page, onboardingSnapshot(workspace.id));
await page.goto('/?onboarding=1');
const checklist = page.getByTestId('onboarding-checklist');
if (!(await checklist.isVisible())) {
await page.getByTestId('onboarding-trigger').click();
}
await expect(checklist).toBeVisible();
return workspace;
}
async function chooseOpenApiPath(page) {
await page.getByTestId('onboarding-openapi-path').click();
await expect(page.locator('#openapi-import-modal')).toBeVisible();
}
async function uploadPreview(page, document = REPRESENTATIVE_OPENAPI) {
await page.locator('#openapi-import-file').setInputFiles({
name: 'openapi.yaml',
mimeType: 'application/yaml',
buffer: Buffer.from(document),
});
await page.locator('#openapi-import-preview').click();
}
function parseMcpResponse(response) {
return response.text().then((text) => {
const dataLine = text.split(/\r?\n/).find((line) => line.startsWith('data:'));
return JSON.parse(dataLine ? dataLine.slice(5).trim() : text);
});
}
async function mcpPost(request, endpoint, key, payload, sessionId) {
const headers = {
Authorization: `Bearer ${key}`,
Accept: 'application/json, text/event-stream',
'Content-Type': 'application/json',
};
if (sessionId) {
headers['MCP-Session-Id'] = sessionId;
headers['MCP-Protocol-Version'] = '2025-06-18';
}
return request.post(endpoint, { headers, data: payload });
}
test.describe('Story 2.15 OpenAPI guided onboarding acceptance', () => {
test('[P1] AC-1 a protected non-Operations entry safely routes to canonical OpenAPI and preserves same-origin return context', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
await routeOnboarding(page, onboardingSnapshot(workspace.id));
await page.goto('/agents?onboarding=1');
const trigger = page.getByTestId('onboarding-trigger');
if (!await trigger.isVisible()) await expect(trigger).toBeVisible();
if (!await page.getByTestId('onboarding-checklist').isVisible()) await trigger.click();
await expect(page.getByTestId('onboarding-openapi-path')).toBeVisible();
expect(await page.evaluate(() => Boolean(window.CrankOpenApiImport))).toBe(false);
// Without the Operations importer bundle, the visible onboarding entry
// routes to Operations with a bounded, same-origin return hint.
const operationsNavigation = page.waitForRequest((request) => {
const url = new URL(request.url());
return request.isNavigationRequest()
&& url.pathname === '/'
&& url.searchParams.get('onboarding_openapi') === '1';
});
await page.getByTestId('onboarding-openapi-path').click();
const navigation = await operationsNavigation;
expect(new URL(navigation.url()).origin).toBe(new URL(process.env.PLAYWRIGHT_BASE_URL || 'http://127.0.0.1:3300').origin);
expect(new URL(page.url()).pathname).toBe('/');
await expect(page.locator('#openapi-import-modal')).toBeVisible();
await expect(page.locator('#openapi-import-file')).toBeAttached();
const returnHint = new URL(page.url()).searchParams.get('return');
expect(returnHint).toBe('/agents?onboarding=1');
expect(returnHint.length).toBeLessThanOrEqual(256);
const returnContext = await page.getByTestId('onboarding-return-context').textContent();
expect(returnContext).toBe('/agents?onboarding=1');
expect(returnContext).not.toContain('://');
expect(new URL(page.url()).origin).toBe(new URL(process.env.PLAYWRIGHT_BASE_URL || 'http://127.0.0.1:3300').origin);
});
test('[P1] AC-2 guided preview shows methods, findings, the exact proposed Operation and apply consequences without hiding blockers', async ({ page }) => {
await openOnboarding(page);
const actionable = candidate('onboarding-rates');
const blocked = candidate('onboarding-blocked', {
status: 'blocked',
findings: [{ code: 'unsupported_xml_body', severity: 'Error', message: 'XML bodies are unsupported', operation_key: 'GET /onboarding-blocked', source_location: { pointer: '/paths/~1onboarding-blocked/post' } }],
});
await routePreview(page, previewResponse([actionable, blocked], {
preview: { findings: [{ code: 'unsupported_xml_body', severity: 'Error', message: 'XML bodies are unsupported', operation_key: blocked.key, source_location: { pointer: '/paths/~1onboarding-blocked/post' } }] },
}));
await chooseOpenApiPath(page);
await uploadPreview(page);
// Criterion-defining assertion: the exact proposed Operation is visible for the selected candidate.
await expect(page.locator('#openapi-import-groups')).toContainText(actionable.suggested_name);
await expect(page.locator('#openapi-import-groups')).toContainText('GET');
await expect(page.locator('[data-testid="openapi-import-finding-code"]')).toContainText('unsupported_xml_body');
// A blocker cannot be hidden to continue: the blocker summary is shown and
// creation stays unavailable until the finding is resolved.
await expect(page.locator('[data-testid="openapi-import-blockers"]')).toBeVisible();
await expect(page.locator('#openapi-import-create')).toBeDisabled();
});
test('[P1] AC-3 security mapping requires only a canonical Auth Profile reference and never stores a raw credential', async ({ page }) => {
await openOnboarding(page);
const workspace = await getCurrentWorkspace(page);
const profileName = uniqueName('onboarding_auth_profile');
const secretValue = SECRET_CANARY + '_' + uniqueName('value');
const secret = await browserJson(
page,
'POST',
`/api/admin/workspaces/${encodeURIComponent(workspace.id)}/secrets`,
{ name: uniqueName('onboarding_secret'), kind: 'token', value: secretValue },
);
const profile = await browserJson(
page,
'POST',
`/api/admin/workspaces/${encodeURIComponent(workspace.id)}/auth-profiles`,
{
name: profileName,
kind: 'bearer',
config: { bearer: { header_name: 'Authorization', secret_id: secret.id } },
},
);
await chooseOpenApiPath(page);
await page.locator('#openapi-import-file').setInputFiles({
name: 'onboarding-security.yaml',
mimeType: 'application/yaml',
buffer: Buffer.from([
'openapi: 3.0.3',
`info: { title: ${profileName}, version: "1" }`,
'servers: [{ url: "http://127.0.0.1:3310" }]',
'paths:',
' /rates:',
' get:',
' operationId: onboarding_secured_rates',
' security:',
' - bearerAuth: []',
' responses:',
" '200': { description: OK }",
'components:',
' securitySchemes:',
' bearerAuth: { type: http, scheme: bearer }',
].join('\n')),
});
const previewResponsePromise = page.waitForResponse((response) => response.request().method() === 'POST' && response.url().includes('/imports/openapi/preview'));
await page.locator('#openapi-import-preview').click();
const previewResponseReal = await previewResponsePromise;
expect(previewResponseReal.status()).toBe(200);
const previewArtifact = await previewResponseReal.json();
expect(JSON.stringify(previewArtifact)).not.toContain(secretValue);
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
// Criterion-defining assertion: the canonical Auth Profile picker is shown.
const alternative = page.getByLabel(localized('Security alternative', 'Вариант безопасности'));
const bearerOption = alternative.locator('option', { hasText: 'bearerAuth' });
await bearerOption.waitFor({ state: 'attached' });
const bearerIndex = await bearerOption.getAttribute('value');
expect(bearerIndex).toMatch(/^\d+$/);
await alternative.selectOption(bearerIndex);
const profilePicker = page.locator('#openapi-import-groups [data-openapi-security-profile]').first();
await expect(profilePicker).toBeVisible();
await profilePicker.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 sentPlanRequest = await planRequest;
const planPayload = sentPlanRequest.postDataJSON();
expect(planPayload.decisions[0]).toMatchObject({ auth_profile_id: profile.id });
expect(planPayload.decisions[0].security_alternative_index).toEqual(expect.any(Number));
const planResponseReal = await sentPlanRequest.response();
expect(planResponseReal.ok(), await planResponseReal.text()).toBe(true);
const planArtifact = await planResponseReal.json();
expect(JSON.stringify(planPayload)).not.toContain(secretValue);
// The canonical artifact, onboarding projection and browser state carry the
// typed reference only. Secret material remains server-side.
const onboarding = await browserJson(page, 'GET', `/api/admin/workspaces/${encodeURIComponent(workspace.id)}/onboarding`);
const browserState = await page.evaluate(() => JSON.stringify({
local: Object.values(localStorage),
session: Object.values(sessionStorage),
url: location.href,
body: document.body.innerText,
}));
for (const value of [JSON.stringify(previewArtifact), JSON.stringify(planArtifact), JSON.stringify(onboarding), browserState, JSON.stringify(planPayload)]) {
expect(value).not.toContain(secretValue);
}
expect(JSON.stringify(planPayload)).toContain(profile.id);
expect(JSON.stringify(planArtifact)).toContain(profile.id);
await expect(page.locator('body')).not.toContainText(secretValue);
});
test('[P1] AC-4 after atomic apply of multiple Drafts the onboarding explicitly selects one actionable Draft and never auto-publishes', async ({ page }) => {
await openOnboarding(page);
const first = candidate('onboarding-rates');
const second = candidate('onboarding-currencies');
await routePreview(page, previewResponse([first, second]));
await routePlanCreate(page, planResponse([
{ key: first.key, name: first.suggested_name, state: 'actionable', action: 'create' },
{ key: second.key, name: second.suggested_name, state: 'actionable', action: 'create' },
]));
const outcomes = [
{ key: first.key, name: first.suggested_name, outcome: 'created', operation_id: 'op_onboarding_rates', version: 1, reason: null },
{ key: second.key, name: second.suggested_name, outcome: 'created', operation_id: 'op_onboarding_currencies', version: 1, reason: null },
];
let report;
const initial = onboardingSnapshot((await getCurrentWorkspace(page)).id);
let context;
const registrationRequests = [];
const selectionRequests = [];
let latestOnboarding = initial;
await page.route(/\/api\/admin\/workspaces\/[^/]+\/onboarding(?:\?.*)?$/, async (route) => {
if (route.request().method() !== 'GET') return route.fallback();
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(latestOnboarding) });
});
await page.route(/\/api\/admin\/workspaces\/[^/]+\/onboarding\/import-context$/, async (route) => {
registrationRequests.push(route.request().postDataJSON());
context = importContext(report);
const response = registeredResponse(initial, context);
latestOnboarding = response;
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(response) });
});
await page.route(/\/api\/admin\/workspaces\/[^/]+\/onboarding\/select-draft$/, async (route) => {
const payload = route.request().postDataJSON();
selectionRequests.push(payload);
const response = selectedResponse(latestOnboarding, context, payload.operation_id, payload.operation_version);
latestOnboarding = response;
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(response) });
});
await routeApply(page, (payload) => {
report = applyReport(outcomes, {
idempotency_key: payload.idempotency_key,
plan_digest: payload.plan_digest,
});
return report;
});
const publishRequests = [];
page.on('request', (request) => {
if (/\/publish(?:es)?(?:\?|$)/.test(new URL(request.url()).pathname)) publishRequests.push(request.url());
});
await chooseOpenApiPath(page);
await uploadPreview(page);
await page.locator('#openapi-import-create').click();
await page.locator('[data-testid="openapi-import-plan-apply"]').click();
// Criterion-defining assertion: an explicit Draft chooser lists the created Drafts.
const chooser = page.getByTestId('onboarding-import-draft-choice');
await expect(chooser).toBeVisible();
await expect(chooser).toContainText(first.suggested_name);
await expect(chooser).toContainText(second.suggested_name);
// The full import report remains available and nothing is auto-published.
await expect(page.locator('#openapi-import-result')).toBeVisible();
expect(publishRequests).toEqual([]);
await expect.poll(() => registrationRequests.length).toBe(1);
expect(registrationRequests[0]).toEqual({
application_idempotency_key: report.idempotency_key,
plan_digest: report.plan_digest,
expected_revision: initial.revision,
});
expect(context.report).toEqual(report);
const chosen = page.waitForRequest((request) => request.method() === 'POST' && /\/onboarding\/select-draft$/.test(request.url()));
const firstChoice = chooser.locator('.onboarding-import-draft-option-row')
.filter({ hasText: first.suggested_name }).getByRole('button');
await firstChoice.click();
const selectedRequest = await chosen;
expect(selectedRequest.postDataJSON()).toEqual({
application_idempotency_key: report.idempotency_key,
plan_digest: report.plan_digest,
operation_id: 'op_onboarding_rates',
operation_version: 1,
expected_revision: initial.revision + 1,
});
});
test('[P1] AC-5 refresh or source correction restores the checklist from authoritative state without duplicating a version and requires a new preview for a changed digest', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
const pendingReport = applyReport([
{ key: 'GET /onboarding-rates', name: 'onboarding_rates', outcome: 'created', operation_id: 'op_imported_rates', version: 1, reason: null },
{ key: 'GET /onboarding-blocked', name: 'onboarding_blocked', outcome: 'rejected', operation_id: null, version: null, reason: 'unsupported_xml_body' },
], {
idempotency_key: 'ws_default:apply:openapi_onboarding:v1',
counts: { created: 1, versioned: 0, renamed: 0, skipped: 0, excluded: 0, rejected: 1 },
});
const imported = onboardingSnapshot(workspace.id, {
revision: 9,
operation_id: null,
operation_version: null,
import_context: importContext(pendingReport),
steps: [
{ id: 'operation', completed: false, status: 'current', action_code: 'create_operation', reason_code: 'authoritative_evidence_missing' },
{ id: 'test', completed: false, status: 'pending', action_code: 'test_operation', reason_code: 'prerequisite_incomplete' },
{ id: 'publish_operation', completed: false, status: 'pending', action_code: 'publish_operation', reason_code: 'prerequisite_incomplete' },
{ id: 'agent', completed: false, status: 'pending', action_code: 'publish_agent', reason_code: 'prerequisite_incomplete' },
{ id: 'key', completed: false, status: 'pending', action_code: 'create_mcp_key', reason_code: 'prerequisite_incomplete' },
{ id: 'mcp_connection', completed: false, status: 'pending', action_code: 'connect_mcp_client', reason_code: 'prerequisite_incomplete' },
{ id: 'first_call', completed: false, status: 'pending', action_code: 'call_tool', reason_code: 'prerequisite_incomplete' },
],
});
await routeOnboarding(page, imported);
await page.goto('/?onboarding=1');
const checklist = page.getByTestId('onboarding-checklist');
if (!(await checklist.isVisible())) await page.getByTestId('onboarding-trigger').click();
await expect(checklist.locator('[aria-current="step"]')).toContainText(localized('Create an Operation', 'Создать операцию'));
await expect(page.getByTestId('onboarding-import-context')).toContainText('onboarding_rates');
// A full page refresh must recover the pending report and every outcome
// from the authoritative onboarding projection before explicit selection.
await page.reload();
const resumed = page.getByTestId('onboarding-checklist');
if (!(await resumed.isVisible())) await page.getByTestId('onboarding-trigger').click();
await expect(resumed.locator('[aria-current="step"]')).toContainText(localized('Create an Operation', 'Создать операцию'));
await page.getByTestId('onboarding-openapi-path').click();
await expect(page.locator('#openapi-import-modal')).toBeVisible();
await expect(page.locator('#openapi-import-result')).toBeVisible();
await expect(page.locator('#openapi-import-result .openapi-import-plan-outcome[data-outcome="created"]')).toContainText('onboarding_rates');
await expect(page.locator('#openapi-import-result .openapi-import-plan-outcome[data-outcome="rejected"]')).toContainText('onboarding_blocked');
const restoredChooser = page.getByTestId('onboarding-import-draft-choice');
await expect(restoredChooser).toContainText('onboarding_rates');
await expect(restoredChooser).toContainText(localized(
'This imported item needs review in the wizard.',
'Этот импортированный элемент нужно проверить в мастере.',
));
// A changed source digest yields visible 409 recovery and disables Apply
// until a fresh preview/confirmation is created.
const resumeCandidate = candidate('onboarding-rates');
await page.locator('[data-openapi-close]').last().click();
await page.getByTestId('onboarding-openapi-path').click();
await routePreview(page, previewResponse([resumeCandidate]));
await uploadPreview(page);
await routePlanCreate(page, planResponse([
{ key: resumeCandidate.key, name: resumeCandidate.suggested_name, state: 'actionable', action: 'create' },
], { plan_reference: 'plan_e2e_onboarding_215_fresh', plan_digest: 'c'.repeat(64) }));
await page.locator('#openapi-import-create').click();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toContainText(resumeCandidate.suggested_name);
await page.route(/\/imports\/openapi\/plans\/[^/]+(?:\?.*)?$/, (route) => route.fulfill({
status: 409,
contentType: 'application/json',
body: JSON.stringify({ error: { code: 'import_plan_stale', message: 'Import source changed', context: { recovery: 'preview', reason: 'source_digest_changed' } } }),
}));
await page.locator('[data-testid="openapi-import-plan-reopen"]').click();
await expect(page.locator('[data-testid="openapi-import-plan-stale"]')).toBeVisible();
await expect(page.locator('[data-testid="openapi-import-plan-apply"]')).toBeDisabled();
await expect(page.locator('#openapi-import-status')).not.toHaveText('');
await page.locator('[data-openapi-close]').last().click();
await page.getByTestId('onboarding-openapi-path').click();
await routePreview(page, previewResponse([resumeCandidate], { job_id: 'imp_e2e_onboarding_215_recovered' }));
await uploadPreview(page);
await routePlanCreate(page, planResponse([
{ key: resumeCandidate.key, name: resumeCandidate.suggested_name, state: 'actionable', action: 'create' },
], { plan_reference: 'plan_e2e_onboarding_215_recovered', plan_digest: 'd'.repeat(64) }));
await page.locator('#openapi-import-create').click();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toContainText(resumeCandidate.suggested_name);
await page.locator('[data-openapi-close]').last().click();
await page.getByTestId('onboarding-openapi-path').click();
const selectionRequests = [];
await page.route(/\/api\/admin\/workspaces\/[^/]+\/onboarding\/select-draft$/, async (route) => {
const payload = route.request().postDataJSON();
selectionRequests.push(payload);
if (selectionRequests.length === 1) {
await route.fulfill({
status: 409,
contentType: 'application/json',
body: JSON.stringify({ error: { code: 'onboarding_stale_revision', message: 'Reload required', context: { recovery: 'reload' } } }),
});
return;
}
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(selectedResponse(imported, importContext(pendingReport), payload.operation_id, payload.operation_version)) });
});
const continueButton = page.getByTestId('onboarding-import-draft-choice').getByRole('button').first();
await continueButton.click();
await expect(page.locator('#openapi-import-status')).toContainText(/reload|latest report|state changed|обнов|измен/i);
await expect(page.locator('#openapi-import-modal')).toBeVisible();
await expect(continueButton).toBeVisible();
await continueButton.click();
await page.waitForURL(/\/wizard\/\?mode=edit/);
expect(selectionRequests).toHaveLength(2);
for (const payload of selectionRequests) {
expect(payload).toEqual({
application_idempotency_key: pendingReport.idempotency_key,
plan_digest: pendingReport.plan_digest,
operation_id: 'op_imported_rates',
operation_version: 1,
expected_revision: imported.revision,
});
}
});
test('[P1] AC-6 presentation event requests carry only the bounded client contract and make no external calls', async ({ page }) => {
const requests = [];
page.on('request', (request) => requests.push({ url: request.url(), postData: request.postData() }));
const workspace = await openOnboarding(page);
const actionable = candidate('onboarding-rates');
await routePreview(page, previewResponse([actionable]));
await routePlanCreate(page, planResponse([{ key: actionable.key, name: actionable.suggested_name, state: 'actionable', action: 'create' }]));
let report;
await routeApply(page, (payload) => {
report = applyReport([
{ key: actionable.key, name: actionable.suggested_name, outcome: 'created', operation_id: 'op_onboarding_rates', version: 1, reason: null },
], { idempotency_key: payload.idempotency_key, plan_digest: payload.plan_digest });
return report;
});
await page.route(/\/api\/admin\/workspaces\/[^/]+\/onboarding\/import-context$/, async (route) => {
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(registeredResponse(onboardingSnapshot(workspace.id), importContext(report))) });
});
await chooseOpenApiPath(page);
await uploadPreview(page);
await page.locator('#openapi-import-create').click();
await page.locator('[data-testid="openapi-import-plan-apply"]').click();
// Presentation requests are client-owned UI signals with a closed payload.
const eventPosts = requests.filter((item) => /\/onboarding\/events(?:\?|$)/.test(item.url));
expect(eventPosts.length).toBeGreaterThan(0);
eventPosts.forEach((item) => {
const payload = JSON.parse(item.postData || '{}');
expect(Object.keys(payload).sort()).toEqual(['event', 'expected_revision', 'idempotency_key']);
expect(payload.event).toMatch(/^(started|resumed|dismissed|abandoned)$/);
expect(payload.idempotency_key).toMatch(/^ui:/);
expect(typeof payload.expected_revision).toBe('number');
expect(JSON.stringify(payload)).not.toContain('openapi: 3.0');
expect(JSON.stringify(payload)).not.toContain(SECRET_CANARY);
expect(Object.keys(payload)).not.toContain('user_id');
});
// ...and keep all telemetry local unless the operator opts in (no external egress).
const external = requests.filter((item) => !/^https?:\/\/(?:127\.0\.0\.1|localhost)(?::\d+)?\//.test(item.url));
expect(external).toEqual([]);
// Server-owned properties for all three funnel milestones, including the
// exact keys and raw-data exclusion, are asserted against stored PG rows by
// `crates/crank-registry/tests/integration/onboarding_import_selection.rs`.
});
for (const locale of ['ru', 'en']) {
test(`[P1] AC-7 ${locale} OpenAPI import reaches an authoritative public MCP call after selection reset`, async ({ page, request }) => {
test.setTimeout(180_000);
await login(page);
const workspace = await getCurrentWorkspace(page);
// The shared E2E admin workspace may have terminal evidence from an earlier
// suite. Reset only its canonical onboarding selection; every milestone
// below is recreated through the real import/UI/public endpoint journey.
let reset;
for (let attempt = 0; attempt < 5; attempt += 1) {
const prior = await browserJson(page, 'GET', `/api/admin/workspaces/${encodeURIComponent(workspace.id)}/onboarding`);
reset = await browserJson(
page,
'POST',
`/api/admin/workspaces/${encodeURIComponent(workspace.id)}/onboarding/reset-selection`,
{ expected_revision: prior.revision },
[200, 409],
);
if (!reset.error) break;
expect(reset.error.code).toBe('onboarding_stale_revision');
}
expect(reset.error).toBeUndefined();
const resetProjection = reset.onboarding || reset;
expect(resetProjection.status).not.toBe('complete');
expect(resetProjection.import_context).toBeNull();
expect(resetProjection.first_call).toBeNull();
const suffix = uniqueName('openapi_onboarding').replace(/_/g, '-');
const agentSlug = `onboarding-${suffix}`.toLowerCase().replace(/[^a-z0-9-]/g, '-');
await page.goto('/?onboarding_openapi=1&return=%2F');
await expect(page.locator('#openapi-import-modal')).toBeVisible();
await page.evaluate((language) => window.setLang(language), locale);
await expect(page.locator('#openapi-import-modal')).toContainText(locale === 'ru' ? 'Импорт OpenAPI' : 'Import OpenAPI');
await uploadPreview(page, representativeOpenApi(suffix));
// Import preview, atomic apply of multiple candidates, and full report are
// all exercised against the real import API.
await expect(page.locator('#openapi-import-groups')).toContainText(/list.?rates/i);
await page.locator('#openapi-import-create').click();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
const importContextRequest = page.waitForRequest((r) => r.method() === 'POST' && /\/onboarding\/import-context$/.test(r.url()));
await page.locator('[data-testid="openapi-import-plan-apply"]').click();
await expect(page.locator('#openapi-import-result')).toBeVisible();
const registration = await importContextRequest;
expect(registration.postDataJSON()).toMatchObject({
application_idempotency_key: expect.any(String),
plan_digest: expect.stringMatching(/^[a-f0-9]{64}$/),
expected_revision: expect.any(Number),
});
expect(await registration.response().then((response) => response.ok())).toBe(true);
// Reload while the import context is still pending, then recover the full
// immutable report and every selectable/non-selectable outcome from GET.
await page.reload();
const checklistAfterReload = page.getByTestId('onboarding-checklist');
if (!await checklistAfterReload.isVisible()) await page.getByTestId('onboarding-trigger').click();
await expect(page.getByTestId('onboarding-import-context')).toContainText(/list.?rates/i);
await page.getByTestId('onboarding-openapi-path').click();
await expect(page.locator('#openapi-import-modal')).toBeVisible();
await expect(page.locator('#openapi-import-result')).toBeVisible();
await expect(page.locator('#openapi-import-result .openapi-import-plan-outcomes')).toContainText(/list.?rates/i);
const pendingContext = await browserJson(page, 'GET', `/api/admin/workspaces/${encodeURIComponent(workspace.id)}/onboarding`);
expect(pendingContext.import_context.report.outcomes.length).toBeGreaterThan(1);
expect(pendingContext.import_context.selected_operation_id).toBeNull();
expect(pendingContext.import_context.selected_operation_version).toBeNull();
expect(pendingContext.import_context.choices).toHaveLength(2);
expect(pendingContext.import_context.choices.every((choice) => choice.selectable)).toBe(true);
expect(pendingContext.import_context.report.outcomes.map((outcome) => outcome.outcome).sort()).toEqual(['created', 'created']);
const selectedChoice = pendingContext.import_context.choices.find((choice) => /list.?rates/i.test(choice.name));
expect(selectedChoice).toBeTruthy();
const chooser = page.getByTestId('onboarding-import-draft-choice');
await expect(chooser).toBeVisible();
const draftChoice = chooser.locator('.onboarding-import-draft-choice-list .onboarding-import-draft-option-row')
.filter({ hasText: /list.?rates/i }).getByRole('button');
await expect(draftChoice).toBeVisible();
const selectDraftRequest = page.waitForRequest((r) => r.method() === 'POST' && /\/onboarding\/select-draft$/.test(r.url()));
const selectedVersionResponse = page.waitForResponse((r) => r.request().method() === 'GET'
&& r.url().includes(`/operations/${selectedChoice.operation_id}/versions/${selectedChoice.version}`));
await draftChoice.click();
const selection = await selectDraftRequest;
const loadedVersion = await selectedVersionResponse;
expect(loadedVersion.ok()).toBe(true);
const importedVersion = await loadedVersion.json();
expect(importedVersion.snapshot.target).toMatchObject({ kind: 'rest', method: 'GET', path_template: '/rates', base_url: 'http://127.0.0.1:3310' });
expect(selection.postDataJSON()).toMatchObject({
application_idempotency_key: registration.postDataJSON().application_idempotency_key,
plan_digest: registration.postDataJSON().plan_digest,
operation_id: expect.any(String),
operation_version: expect.any(Number),
expected_revision: expect.any(Number),
});
await page.waitForFunction(() => window.CrankWizardReady === true && window.currentStep === 1);
await expect(page.locator('[data-testid="wizard-protocol-rest"]')).toBeVisible();
const selectedOperationId = selection.postDataJSON().operation_id;
const selectedVersion = selection.postDataJSON().operation_version;
await expect(page).toHaveURL(new RegExp(`operationId=${selectedOperationId}`));
expect(new URL(page.url()).searchParams.get('operationVersion')).toBe(String(selectedVersion));
await expect(page.locator('#tool-name')).toHaveValue(/list.?rates/i);
const operationWrites = [];
page.on('request', (r) => {
const path = new URL(r.url()).pathname;
const createsOperation = r.method() === 'POST' && /\/api\/admin\/workspaces\/[^/]+\/operations$/.test(path);
const updatesOperation = r.method() === 'PATCH' && /\/api\/admin\/workspaces\/[^/]+\/operations\/[^/]+$/.test(path);
const createsVersion = r.method() === 'POST' && /\/api\/admin\/workspaces\/[^/]+\/operations\/[^/]+\/versions$/.test(path);
if (createsOperation || updatesOperation || createsVersion) operationWrites.push({ method: r.method(), url: r.url() });
});
// The selected imported Draft is edited in normal wizard edit mode. A
// no-op lifecycle save must retain its exact version without creating a
// duplicate, then test and publish that same version.
const testedVersions = [];
const publishedVersions = [];
page.on('request', (r) => {
if (r.method() === 'POST' && r.url().includes(`/operations/${selectedOperationId}/test-runs`)) {
testedVersions.push(r.postDataJSON().version);
}
if (r.method() === 'POST' && r.url().includes(`/operations/${selectedOperationId}/publish`)) {
publishedVersions.push(r.postDataJSON().version);
}
});
const testResponse = page.waitForResponse((r) => r.request().method() === 'POST' && r.url().includes(`/operations/${selectedOperationId}/test-runs`));
await page.evaluate(() => window.CrankWizardShell.doGoToStep(5));
await page.locator('#wizard-run-test').click();
const tested = await testResponse;
expect(tested.ok(), await tested.text()).toBe(true);
const testResult = await tested.json();
expect(testResult.ok, JSON.stringify(testResult)).toBe(true);
await expect.poll(() => testedVersions).toEqual([selectedVersion]);
await expect(page.locator('#wizard-test-request-id')).not.toHaveText('');
page.once('dialog', (dialog) => dialog.accept());
const qualityResponse = page.waitForResponse((r) => r.request().method() === 'POST' && r.url().includes('/operations/analyze-quality'));
const publishResponse = page.waitForResponse((r) => r.request().method() === 'POST' && r.url().includes(`/operations/${selectedOperationId}/publish`));
await page.locator('#wizard-publish-operation').click();
const quality = await qualityResponse;
expect(quality.ok(), await quality.text()).toBe(true);
expect((await publishResponse).ok()).toBe(true);
await expect.poll(() => publishedVersions).toEqual([selectedVersion]);
expect(operationWrites).toEqual([]);
const agentPage = `/agents?onboarding=1&action=create&operationId=${encodeURIComponent(selectedOperationId)}&operationVersion=${selectedVersion}`;
await page.goto(agentPage);
await expect(page.locator('.drawer')).toHaveClass(/open/);
const identityInputs = page.locator('.drawer-section').first().locator('input.form-input');
await identityInputs.nth(0).fill('OpenAPI onboarding Agent');
await identityInputs.nth(1).fill(agentSlug);
await page.locator('.drawer-section').first().locator('textarea').fill('Agent created from an explicitly selected OpenAPI Draft.');
await expect(page.locator('.ops-picker-item.selected')).toContainText(/list.?rates/i);
const createAgentResponse = page.waitForResponse((r) => r.request().method() === 'POST' && /\/api\/admin\/workspaces\/[^/]+\/agents$/.test(r.url()));
const bindAgentResponse = page.waitForResponse((r) => r.request().method() === 'POST' && /\/agents\/[^/]+\/bindings$/.test(r.url()));
const publishAgentResponse = page.waitForResponse((r) => r.request().method() === 'POST' && /\/agents\/[^/]+\/publish$/.test(r.url()));
await page.locator('.drawer-footer .btn-primary-sm').click();
const agentResponse = await createAgentResponse;
expect(agentResponse.ok(), await agentResponse.text()).toBe(true);
expect((await bindAgentResponse).ok()).toBe(true);
expect((await publishAgentResponse).ok()).toBe(true);
const agentId = (await agentResponse.json()).agent_id;
await page.goto(`/api-keys?onboarding=1&action=create&agentId=${encodeURIComponent(agentId)}`);
await expect(page.locator('#agent-select')).toHaveValue(agentId);
await expect(page.locator('#modal-create')).toHaveClass(/open/);
await page.locator('#new-key-name').fill(uniqueName('openapi_onboarding_key'));
const keyResponsePromise = page.waitForResponse((r) => r.request().method() === 'POST' && /\/platform-api-keys$/.test(r.url()));
await page.locator('#modal-confirm-btn').click();
const keyResponse = await keyResponsePromise;
expect(keyResponse.ok(), await keyResponse.text()).toBe(true);
const keyBody = await keyResponse.json();
const rawKey = await page.locator('#reveal-key-value').textContent();
const keyId = keyBody.api_key.id || keyBody.api_key.api_key.id;
const endpoint = await page.locator('#onboarding-connection-clients > code').textContent();
expect(rawKey).toMatch(/^crk_/);
await expect(page.locator('body')).not.toContainText(SECRET_CANARY);
// An unauthorized public call must not advance the authoritative checklist.
const denied = await mcpPost(request, endpoint, SECRET_CANARY, {
jsonrpc: '2.0', id: 90, method: 'tools/call', params: { name: 'unavailable', arguments: {} },
});
expect([401, 403]).toContain(denied.status());
const beforeSuccessfulCall = await browserJson(page, 'GET', `/api/admin/workspaces/${encodeURIComponent(workspace.id)}/onboarding`);
expect(beforeSuccessfulCall.status).not.toBe('complete');
expect(beforeSuccessfulCall.first_call).toBeNull();
const initialize = await mcpPost(request, endpoint, rawKey, {
jsonrpc: '2.0', id: 1, method: 'initialize', params: {
protocolVersion: '2025-06-18', capabilities: {},
clientInfo: { name: 'crank-openapi-onboarding-playwright', version: '1.0.0' },
},
});
const initializeBody = await parseMcpResponse(initialize);
expect(initialize.ok(), JSON.stringify(initializeBody)).toBe(true);
const sessionId = initialize.headers()['mcp-session-id'];
expect(sessionId).toBeTruthy();
const initialized = await mcpPost(request, endpoint, rawKey, {
jsonrpc: '2.0', method: 'notifications/initialized', params: {},
}, sessionId);
expect([200, 202]).toContain(initialized.status());
const listed = await mcpPost(request, endpoint, rawKey, {
jsonrpc: '2.0', id: 2, method: 'tools/list', params: {},
}, sessionId);
expect(listed.ok()).toBe(true);
const listedBody = await parseMcpResponse(listed);
const selectedTool = listedBody.result.tools.find((tool) => /list.?rates/i.test(tool.name));
expect(selectedTool).toBeTruthy();
const toolName = selectedTool.name;
const called = await mcpPost(request, endpoint, rawKey, {
jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: toolName, arguments: {} },
}, sessionId);
expect(called.ok()).toBe(true);
const calledBody = await parseMcpResponse(called);
expect(calledBody.error).toBeUndefined();
expect(calledBody.result.isError).not.toBe(true);
const progress = await browserJson(page, 'GET', `/api/admin/workspaces/${encodeURIComponent(workspace.id)}/onboarding`);
expect(progress.status).toBe('complete');
expect(progress.operation_id).toBe(selectedOperationId);
expect(progress.operation_version).toBe(selectedVersion);
expect(progress.agent_id).toBe(agentId);
expect(progress.platform_api_key_id).toBe(keyId);
expect(progress.first_call.agent_id).toBe(agentId);
expect(progress.first_call.key_id).toBe(keyId);
expect(progress.first_call.operation_id).toBe(selectedOperationId);
expect(progress.first_call.operation_version).toBe(selectedVersion);
expect(progress.first_call.tool_name).toBe(toolName);
expect(progress.first_call.request_id).toBeTruthy();
expect(progress.first_call.trace_id).toMatch(/^[0-9a-f]{32}$/);
await page.goto('/');
await expect(page.getByTestId('onboarding-trigger')).toContainText(/7\s*\/\s*7/);
await page.getByTestId('onboarding-trigger').click();
await expect(page.getByTestId('onboarding-completion')).toContainText(toolName);
await expect(page.getByTestId('onboarding-completion')).toContainText(progress.first_call.request_id);
await page.evaluate((language) => window.setLang(language), locale);
await expect(page.getByTestId('onboarding-completion')).toBeVisible();
await page.reload();
await expect(page.getByTestId('onboarding-trigger')).toContainText(/7\s*\/\s*7/);
});
}
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,273 @@
// Operator-run AC-11 evidence against a Reference Deployment. This spec is
// intentionally separate from the local/mocked Playwright matrix.
const fs = require('node:fs');
const { test, expect } = require('@playwright/test');
const { localized, login } = require('./helpers');
// Remote operator credentials must not enter retry artifacts or failure captures.
test.use({ trace: 'off', video: 'off', screenshot: 'off' });
test.describe.configure({ retries: 0 });
const referenceBaseUrl = process.env.PLAYWRIGHT_BASE_URL;
const SAMPLE_COUNT = 20;
const OPERATION_COUNT = 2000;
const MAX_UPLOAD_BYTES = 256 * 1024;
const MAX_P95_MS = 2000;
function openApiDocument(operationCount) {
const lines = [
'openapi: 3.0.3',
'info:',
' title: Crank Reference Preview Benchmark',
' version: "1.0.0"',
'servers:',
' - url: https://api.example.test',
'paths:',
];
for (let index = 0; index < operationCount; index += 1) {
lines.push(` /op-${index}:`);
lines.push(' get:');
lines.push(' responses:');
lines.push(' "200":');
lines.push(' description: OK');
}
return Buffer.from(lines.join('\n') + '\n', 'utf8');
}
function percentile95(samples) {
const sorted = [...samples].sort((left, right) => left - right);
return sorted[Math.ceil(sorted.length * 0.95) - 1];
}
function safeReferenceOrigin(rawUrl) {
const url = new URL(rawUrl);
if (!['http:', 'https:'].includes(url.protocol)) {
throw new Error('PLAYWRIGHT_BASE_URL must use http or https');
}
if (url.username || url.password || url.search || url.hash) {
throw new Error('PLAYWRIGHT_BASE_URL must not contain credentials, query parameters, or fragments');
}
if (['localhost', '127.0.0.1', '::1'].includes(url.hostname)) {
throw new Error('AC-11 Reference benchmark requires a remote PLAYWRIGHT_BASE_URL');
}
return url.origin;
}
function readReferenceManifest(manifestPath) {
if (!manifestPath) {
throw new Error('CRANK_AC11_REFERENCE_ENV_JSON is required when PLAYWRIGHT_BASE_URL is set');
}
let manifest;
try {
manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
} catch (_error) {
throw new Error('CRANK_AC11_REFERENCE_ENV_JSON must point to a readable valid JSON manifest');
}
const deployment = manifest && manifest.deployment;
const loadGenerator = manifest && manifest.load_generator;
const browser = manifest && manifest.browser;
const nonempty = (value) => typeof value === 'string' && value.trim().length > 0;
const finiteNumber = (value) => typeof value === 'number' && Number.isFinite(value);
const versionHasMajor = (value, major) => nonempty(value) && new RegExp(`^${major}(?:\\.|$)`).test(value.trim());
if (!deployment || !loadGenerator || !browser) {
throw new Error('Reference manifest requires deployment, load_generator, and browser objects');
}
for (const [name, host] of [['deployment', deployment], ['load_generator', loadGenerator], ['browser', browser]]) {
if (!nonempty(host.host_id)) throw new Error(`Reference manifest ${name}.host_id is required`);
}
if (deployment.host_id.trim() === loadGenerator.host_id.trim()
|| deployment.host_id.trim() === browser.host_id.trim()) {
throw new Error('Reference manifest requires deployment and load generator/browser on separate hosts');
}
if (!nonempty(deployment.cpu_model) || !nonempty(deployment.storage_type)
|| deployment.storage_type.trim().toLowerCase() !== 'ssd'
|| !finiteNumber(deployment.cpu_cores)
|| !finiteNumber(deployment.ram_gib) || !finiteNumber(deployment.ssd_iops)
|| !finiteNumber(deployment.ssd_throughput_mb_s) || !finiteNumber(deployment.ssd_capacity_gb)
|| !finiteNumber(deployment.lan_mbps)
|| !versionHasMajor(deployment.postgres_version, 16)
|| !versionHasMajor(deployment.valkey_version, 8)) {
throw new Error('Reference manifest is missing valid CPU, RAM, database, SSD, or LAN fields');
}
if (deployment.cpu_cores !== 4 || deployment.ram_gib !== 8
|| deployment.ssd_capacity_gb < 100 || deployment.ssd_iops < 3000
|| deployment.ssd_throughput_mb_s < 100
|| deployment.lan_mbps < 1000) {
throw new Error('Reference deployment must meet 4 CPU / 8 GiB RAM, SSD 3000 IOPS / 100 MB/s, and 1 Gbit LAN');
}
if (!finiteNumber(loadGenerator.cpu_cores) || !finiteNumber(loadGenerator.ram_gib)
|| loadGenerator.cpu_cores !== 4 || loadGenerator.ram_gib !== 8) {
throw new Error('Reference load_generator must have 4 CPU and 8 GiB RAM');
}
// Emit only the fields needed for benchmark interpretation. Do not copy
// arbitrary manifest keys (which could contain credentials) into reports.
return {
provenance: 'operator_manifest',
deployment: {
cpu_model: deployment.cpu_model.trim(),
cpu_cores: deployment.cpu_cores,
ram_gib: deployment.ram_gib,
postgres_version: deployment.postgres_version.trim(),
valkey_version: deployment.valkey_version.trim(),
storage_type: 'SSD',
ssd_capacity_gb: deployment.ssd_capacity_gb,
ssd_iops: deployment.ssd_iops,
ssd_throughput_mb_s: deployment.ssd_throughput_mb_s,
lan_mbps: deployment.lan_mbps,
},
load_generator: { cpu_cores: loadGenerator.cpu_cores, ram_gib: loadGenerator.ram_gib },
browser_host_separate_from_deployment: true,
};
}
test('[P1][reference] AC-11 measures 20 real 2000-operation preview round trips', async ({ page }, testInfo) => {
test.skip(!referenceBaseUrl, 'Set PLAYWRIGHT_BASE_URL to a Reference Deployment to run AC-11 evidence');
test.setTimeout(300_000);
expect(process.env.PLAYWRIGHT_SKIP_WEB_SERVER).toBe('1');
const referenceOrigin = safeReferenceOrigin(referenceBaseUrl);
const referenceManifest = readReferenceManifest(process.env.CRANK_AC11_REFERENCE_ENV_JSON);
const yaml = openApiDocument(OPERATION_COUNT);
expect(yaml.byteLength).toBeLessThan(MAX_UPLOAD_BYTES);
await login(page);
await page.waitForFunction(() => Boolean(document.querySelector('[data-testid="onboarding-dismiss"]')));
await page.locator('[data-testid="onboarding-dismiss"]').click();
await expect(page.locator('#crank-onboarding-panel')).toBeHidden();
await page.evaluate(() => window.setLang('en'));
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await expect(page.locator('#openapi-import-modal')).toBeVisible();
await page.locator('#openapi-import-file').setInputFiles({
name: 'reference-preview-2000.yaml',
mimeType: 'application/yaml',
buffer: yaml,
});
const previewButton = page.locator('#openapi-import-preview');
const createButton = page.locator('#openapi-import-create');
const rows = page.locator('.openapi-import-operation');
const samplesMs = [];
let browserEnvironment;
// Warm the preview once before timing. Warm-up still uses the real remote
// preview API.
const warmupResponsePromise = page.waitForResponse((response) =>
response.request().method() === 'POST'
&& response.url().includes('/imports/openapi/preview'),
);
await previewButton.click();
const warmupResponse = await warmupResponsePromise;
expect(warmupResponse.status(), 'warm-up preview status').toBe(200);
expect(new URL(warmupResponse.url()).origin).toBe(referenceOrigin);
await expect(page.locator('[data-testid="openapi-import-page-status"]')).toContainText('2000');
await expect(createButton).toBeEnabled();
const previewResponses = [];
page.on('response', (response) => {
if (response.request().method() === 'POST' && response.url().includes('/imports/openapi/preview')) {
previewResponses.push({ status: response.status(), url: response.url() });
}
});
for (let sampleIndex = 0; sampleIndex < SAMPLE_COUNT; sampleIndex += 1) {
await expect(previewButton).toBeEnabled();
await page.evaluate((index) => {
const measurements = window.__ac11Measurements || (window.__ac11Measurements = []);
const sample = { start: null, elapsed: null };
measurements[index] = sample;
const ready = () => {
const panel = document.querySelector('#openapi-import-preview-panel');
const button = document.querySelector('#openapi-import-preview');
const status = document.querySelector('[data-testid="openapi-import-page-status"]');
const create = document.querySelector('#openapi-import-create');
const rowCount = document.querySelectorAll('.openapi-import-operation').length;
if (sample.start === null || !button || button.disabled || !panel || panel.hidden
|| !status || !status.textContent.includes('2000') || !create || create.disabled
|| rowCount < 1 || rowCount > 100) return;
sample.elapsed = Number((performance.now() - sample.start).toFixed(3));
observer.disconnect();
};
const observer = new MutationObserver(ready);
observer.observe(document.body, { childList: true, subtree: true, attributes: true, characterData: true });
document.addEventListener('click', (event) => {
if (event.target.closest('#openapi-import-preview')) sample.start = performance.now();
}, { capture: true, once: true });
}, sampleIndex);
const responsePromise = page.waitForResponse((response) =>
response.request().method() === 'POST'
&& response.url().includes('/imports/openapi/preview'),
);
await previewButton.click();
const previewResponse = await responsePromise;
expect(previewResponse.status(), `preview sample ${sampleIndex + 1} status`).toBe(200);
expect(new URL(previewResponse.url()).origin).toBe(referenceOrigin);
await page.waitForFunction((index) => {
const sample = window.__ac11Measurements && window.__ac11Measurements[index];
return sample && sample.elapsed !== null;
}, sampleIndex, { polling: 'raf' });
const elapsed = await page.evaluate((index) => window.__ac11Measurements[index].elapsed, sampleIndex);
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
await expect(page.locator('[data-testid="openapi-import-page-status"]')).toContainText('2000');
await expect(rows.first()).toBeVisible();
expect(await rows.count()).toBeGreaterThan(0);
expect(await rows.count()).toBeLessThanOrEqual(100);
await expect(createButton).toBeEnabled();
samplesMs.push(elapsed);
browserEnvironment = await page.evaluate(() => ({
user_agent: navigator.userAgent,
platform: navigator.platform,
language: navigator.language,
hardware_concurrency: navigator.hardwareConcurrency || null,
viewport: { width: innerWidth, height: innerHeight },
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
}));
}
expect(previewResponses).toHaveLength(SAMPLE_COUNT);
expect(previewResponses.every((item) => item.status === 200)).toBe(true);
const p95Ms = percentile95(samplesMs);
const report = {
benchmark: 'story-2.12-ac-11-reference-preview',
generated_at: new Date().toISOString(),
result: { sample_count: samplesMs.length, p95_ms: p95Ms, threshold_ms: MAX_P95_MS },
workload: {
operations: OPERATION_COUNT,
yaml_bytes: yaml.byteLength,
max_yaml_bytes: MAX_UPLOAD_BYTES,
preview_http_statuses: previewResponses.map((item) => item.status),
rendered_operation_rows: await rows.count(),
max_rendered_operation_rows: 100,
enabled_interaction: 'Create button enabled after preview',
interaction_enabled: true,
measurement_scope: 'click through real HTTP request, parsing, populated first page, and enabled Create button',
},
samples_ms: samplesMs,
environment: {
reference_origin: referenceOrigin,
playwright_base_url_configured: true,
playwright_skip_web_server: process.env.PLAYWRIGHT_SKIP_WEB_SERVER === '1',
node_version: process.version,
os_platform: process.platform,
os_arch: process.arch,
browser: browserEnvironment,
reference_manifest: referenceManifest,
},
};
const rawReport = JSON.stringify(report, null, 2);
await testInfo.attach('ac11-reference-preview-report.json', {
body: Buffer.from(rawReport),
contentType: 'application/json',
});
console.log('AC11_REFERENCE_PREVIEW_REPORT ' + JSON.stringify(report));
expect(p95Ms, 'Reference preview p95 must be at most 2 seconds').toBeLessThanOrEqual(MAX_P95_MS);
});
+229
View File
@@ -0,0 +1,229 @@
const fs = require('node:fs/promises');
const path = require('node:path');
const { test, expect } = require('@playwright/test');
const { getCurrentWorkspace, login, localized, uniqueName } = require('./helpers');
const controlDirectory = path.resolve(__dirname, '../../../../.tmp/ui-e2e');
async function dismissOnboardingIfOpen(page) {
await page.locator('#crank-onboarding-panel').waitFor({ state: 'attached' });
await page.locator('[data-testid="onboarding-dismiss"]').waitFor({ state: 'attached' });
await page.evaluate(() => document.querySelector('[data-testid="onboarding-dismiss"]').click());
await expect(page.locator('#crank-onboarding-panel')).toBeHidden();
}
function openApiDocument(operationId) {
return [
'openapi: 3.0.3',
`info: { title: '${operationId}', version: '1' }`,
'servers: [{ url: https://api.example.test }]',
'paths:',
` /${operationId}:`,
' get:',
` operationId: ${operationId}`,
' summary: Recovery test operation',
' responses:',
" '200': { description: OK }",
'',
].join('\n');
}
async function operationSnapshot(page, workspaceId) {
return page.evaluate(async (id) => {
const response = await window.CrankApi.listOperations(id);
if (!response || !Array.isArray(response.items)) throw new Error('Operations API returned no item list');
return response.items;
}, workspaceId);
}
async function requestAdminControl(command) {
const requestFile = path.join(controlDirectory, 'admin-control.request');
const ackFile = path.join(controlDirectory, 'admin-control.ack');
await fs.mkdir(controlDirectory, { recursive: true });
await fs.rm(ackFile, { force: true });
const temporaryFile = `${requestFile}.${process.pid}.${Date.now()}.tmp`;
await fs.writeFile(temporaryFile, `${command}\n`, { mode: 0o600 });
await fs.rename(temporaryFile, requestFile);
await expect.poll(async () => {
try {
return (await fs.readFile(ackFile, 'utf8')).trim();
} catch (_error) {
return '';
}
}, { timeout: 30_000, message: `Admin API did not acknowledge ${command}` }).toBe(command);
}
async function adminApiPid() {
return (await fs.readFile(path.join(controlDirectory, 'admin-api.pid'), 'utf8')).trim();
}
async function storageCounts(workspaceId) {
await requestAdminControl(`counts ${workspaceId}`);
return JSON.parse(await fs.readFile(path.join(controlDirectory, 'storage-counts.json'), 'utf8'));
}
async function openImport(page, operationId) {
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await page.locator('#openapi-import-file').setInputFiles({
name: `${operationId}.yaml`,
mimeType: 'application/yaml',
buffer: Buffer.from(openApiDocument(operationId)),
});
const previewResponse = page.waitForResponse((response) =>
response.request().method() === 'POST'
&& response.url().includes('/imports/openapi/preview'));
await page.locator('#openapi-import-preview').click();
const response = await previewResponse;
expect(response.ok()).toBe(true);
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
return response;
}
test('[P1] AC03 real invalid preview shows the exact canonical correlation headers', async ({ page }) => {
await login(page);
await dismissOnboardingIfOpen(page);
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await page.locator('#openapi-import-file').setInputFiles({
name: 'invalid-openapi.yaml',
mimeType: 'application/yaml',
buffer: Buffer.from('openapi: [\n'),
});
const rejectedPreview = page.waitForResponse((response) =>
response.request().method() === 'POST'
&& response.url().includes('/imports/openapi/preview'));
await page.locator('#openapi-import-preview').click();
const response = await rejectedPreview;
expect(response.status()).toBeGreaterThanOrEqual(400);
expect(response.status()).toBeLessThan(500);
const requestId = response.headers()['x-request-id'];
const traceId = response.headers()['x-trace-id'];
expect(requestId).toBeTruthy();
expect(traceId).toMatch(/^[a-f0-9]{32}$/i);
const status = page.locator('#openapi-import-status');
await expect(status).toBeFocused();
await expect(status).toHaveAttribute('role', 'status');
await expect(status).toHaveAttribute('aria-live', 'polite');
await expect(status).toHaveAttribute('aria-atomic', 'true');
await expect(status).toContainText(requestId);
await expect(status).toContainText(traceId);
await expect(status).toContainText('Request ID:');
await expect(status).toContainText('Trace ID:');
});
test('[P1] AC05 real preview and plan do not mutate Operations; reduced-motion Apply replay survives reload and API restart', async ({ page }) => {
// This journey includes bounded process stop/start and several database observations.
test.setTimeout(120_000);
await page.emulateMedia({ reducedMotion: 'reduce' });
await login(page);
await dismissOnboardingIfOpen(page);
expect(await page.evaluate(() => window.matchMedia('(prefers-reduced-motion: reduce)').matches)).toBe(true);
const workspace = await getCurrentWorkspace(page);
expect(workspace && workspace.id).toBeTruthy();
const initialOperations = await operationSnapshot(page, workspace.id);
const initialCounts = await storageCounts(workspace.id);
expect(initialCounts).toMatchObject({
sources: expect.any(Number),
operations: expect.any(Number),
versions: expect.any(Number),
});
const operationId = uniqueName('recovery_import').replace(/[^a-zA-Z0-9_]/g, '_');
const applyRequests = [];
const apiRequests = { preview: 0, createPlan: 0, apply: 0 };
page.on('request', (request) => {
if (request.method() !== 'POST') return;
const url = request.url();
if (url.includes('/imports/openapi/preview')) apiRequests.preview += 1;
if (/\/imports\/openapi\/[^/]+\/plans(?:\?|$)/.test(url)) apiRequests.createPlan += 1;
if (/\/imports\/openapi\/[^/]+\/apply(?:\?|$)/.test(url)) apiRequests.apply += 1;
});
await page.route('**/imports/openapi/*/apply', async (route) => {
applyRequests.push({
url: route.request().url(),
body: route.request().postData(),
});
if (applyRequests.length === 1) {
// Send the real request to Admin API, then lose only its browser response.
const response = await route.fetch();
expect(response.ok()).toBe(true);
await route.abort('connectionreset');
return;
}
await route.continue();
});
await openImport(page, operationId);
expect(await operationSnapshot(page, workspace.id)).toEqual(initialOperations);
expect(apiRequests.preview).toBe(1);
const afterPreviewCounts = await storageCounts(workspace.id);
expect(afterPreviewCounts).toEqual({
...initialCounts,
sources: initialCounts.sources + 1,
});
const dialogMotion = await page.locator('.openapi-import-dialog').evaluate((node) => getComputedStyle(node).transitionDuration);
expect(dialogMotion.split(',').every((duration) => Number.parseFloat(duration) === 0)).toBe(true);
await page.locator('#openapi-import-server-custom').fill('https://api.example.test');
await page.locator('#openapi-import-create').click();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
expect(await operationSnapshot(page, workspace.id)).toEqual(initialOperations);
expect(apiRequests.createPlan).toBe(1);
expect(await storageCounts(workspace.id)).toEqual(afterPreviewCounts);
await page.locator('#openapi-import-plan-apply').click();
await expect.poll(() => applyRequests.length).toBe(1);
expect(apiRequests.apply).toBe(1);
const applyStatus = page.locator('#openapi-import-status');
await expect(applyStatus).toBeFocused();
await expect(applyStatus).toHaveAttribute('role', 'status');
await expect(applyStatus).toHaveAttribute('aria-live', 'polite');
await expect(applyStatus).toHaveAttribute('aria-atomic', 'true');
await expect(applyStatus).toContainText(localized('Apply result is unknown', 'Результат применения неизвестен'));
await expect(page.locator('#openapi-import-retry')).toBeVisible();
const committedOperations = await operationSnapshot(page, workspace.id);
expect(committedOperations).toHaveLength(initialOperations.length + 1);
expect(committedOperations.some((operation) => operation.name === operationId
|| operation.operation_id === operationId)).toBe(true);
const committedCounts = await storageCounts(workspace.id);
expect(committedCounts).toEqual({
...afterPreviewCounts,
operations: afterPreviewCounts.operations + 1,
versions: afterPreviewCounts.versions + 1,
});
const pidBeforeRestart = await adminApiPid();
let adminMayBeStopped = true;
try {
await requestAdminControl('stop');
await requestAdminControl('start');
adminMayBeStopped = false;
} finally {
if (adminMayBeStopped) await requestAdminControl('start');
}
expect(await adminApiPid()).not.toBe(pidBeforeRestart);
expect(await storageCounts(workspace.id)).toEqual(committedCounts);
await page.reload();
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await expect(page.locator('#openapi-import-retry')).toBeVisible();
await expect(page.locator('#openapi-import-status')).toContainText(localized('Apply result is unknown', 'Результат применения неизвестен'));
const retryResponse = page.waitForResponse((response) =>
response.request().method() === 'POST'
&& response.url().includes('/imports/openapi/')
&& response.url().endsWith('/apply'));
await page.locator('#openapi-import-retry').click();
const response = await retryResponse;
expect(response.status()).toBe(200);
await expect(page.locator('#openapi-import-result')).toContainText(operationId);
await expect.poll(() => applyRequests.length).toBe(2);
expect(applyRequests[1].url).toBe(applyRequests[0].url);
expect(applyRequests[1].body).toBe(applyRequests[0].body);
expect(apiRequests).toEqual({ preview: 1, createPlan: 1, apply: 2 });
const finalOperations = await operationSnapshot(page, workspace.id);
expect(finalOperations).toHaveLength(initialOperations.length + 1);
expect(finalOperations.filter((operation) => operation.name === operationId
|| operation.operation_id === operationId)).toHaveLength(1);
expect(await storageCounts(workspace.id)).toEqual(committedCounts);
});
@@ -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) {}
}
});
+122 -40
View File
@@ -11,6 +11,48 @@ async function dismissOnboardingIfOpen(page) {
await expect(page.locator('#crank-onboarding-panel')).toBeHidden();
}
function planResponse(payload, planReference) {
const decisions = payload.decisions || [];
return {
plan_reference: planReference,
plan_digest: 'c'.repeat(64),
expires_at: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
selection_mode: payload.selection_mode,
counts: { selected: decisions.length, excluded: 0, actionable: decisions.length, blocked: 0 },
candidates: decisions.map((decision) => ({
key: decision.operation_key,
name: decision.confirmed_name || decision.operation_key,
state: 'actionable',
action: decision.action,
target_operation_id: decision.target_operation_id || null,
confirmed_name: decision.confirmed_name || null,
auth_profile_id: null,
reason: null,
})),
};
}
function applyResponse(payload, names) {
const outcomes = (payload.outcomes || []).map((outcome) => ({
key: outcome.key,
name: names && names[outcome.key] || outcome.name || outcome.key,
status: outcome.status || 'created',
}));
return {
counts: { created: outcomes.filter((outcome) => outcome.status === 'created').length },
outcomes,
};
}
async function mockEmptyOperationsList(page) {
await page.route('**/api/admin/workspaces/*/operations', async (route) => {
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({ items: [], page: 1, page_size: 0, total: 0 }),
});
});
}
test('operations page shows demo catalog and filter works', async ({ page }) => {
await login(page);
await expect(page.locator('.page-heading')).toHaveText(localized('Operations', 'Операции'));
@@ -100,7 +142,9 @@ paths:
const request = await previewRequest;
expect(request.headers()['content-type']).toMatch(/^multipart\/form-data; boundary=/i);
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
await expect(page.locator('.openapi-import-document-findings')).toContainText(/base URL/i);
const documentFindings = page.locator('.openapi-import-document-findings');
await documentFindings.locator('summary').click();
await expect(documentFindings).toContainText(/base URL/i);
await expect(page.locator('.openapi-import-group').filter({ hasText: 'currency' })).toBeVisible();
const importedOperation = page.locator('.openapi-import-operation').filter({ hasText: 'Получить курсы валют' });
await expect(importedOperation).toBeVisible();
@@ -112,12 +156,13 @@ paths:
await expect(importedOperation.locator('.openapi-import-mapping-preview')).toContainText('Header');
await expect(importedOperation.locator('.openapi-import-mapping-preview')).toContainText('X-API-Version');
await expect(importedOperation.locator('.openapi-import-mapping-preview')).toContainText('Body');
await expect(importedOperation.locator('.openapi-import-mapping-preview')).toContainText('symbols');
await expect(importedOperation.locator('.openapi-import-mapping-chip').filter({ hasText: /^body$/ })).toHaveCount(1);
await expect(importedOperation.locator('.openapi-import-mapping-preview')).toContainText(localized('Response', 'Ответ'));
await expect(page.locator('#openapi-import-selection')).toContainText(localized('Selected: 2', 'Выбрано: 2'));
await page.locator('#openapi-import-search').fill('status');
await expect(page.locator('.openapi-import-operation:visible')).toHaveCount(1);
await expect(page.locator('.openapi-import-operation:visible').filter({ hasText: 'Проверить статус' })).toBeVisible();
await page.locator('#openapi-import-partial-mode').check();
await page.locator('#openapi-import-clear-visible').click();
await expect(page.locator('#openapi-import-selection')).toContainText(localized('Selected: 1', 'Выбрано: 1'));
await page.locator('#openapi-import-search').fill('');
@@ -127,18 +172,21 @@ paths:
await page.locator('#openapi-import-method-filter').selectOption('');
await page.locator('#openapi-import-server-custom').fill('https://api.example.test');
await page.locator('#openapi-import-create').click();
await expect(page.locator('#openapi-import-result')).toContainText(localized('Import result', 'Результат импорта'));
await expect(page.locator('.openapi-import-result-table')).toBeVisible();
await expect(page.locator('.openapi-import-result-row').filter({ hasText: operationId })).toContainText('POST /v1/rates/{date}');
await expect(page.locator('.openapi-import-result-row').filter({ hasText: operationId })).toContainText(localized('tool description is too short', 'Описание инструмента слишком короткое'));
await expect(page.locator('.openapi-import-result-row').filter({ hasText: operationId })).toContainText(localized('Fix in wizard', 'Исправить в мастере'));
await expect(page.locator('.openapi-import-primary-result a')).toHaveAttribute(
'href',
/\/wizard\/\?mode=edit&operationId=op_/
);
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
await page.locator('#openapi-import-plan-apply').click();
await expect(page.locator('#openapi-import-result')).toBeVisible();
await expect(page.locator('#openapi-import-result')).toContainText(localized('Import plan result', 'Результат плана импорта'));
await expect(page.locator('.openapi-import-plan-outcomes')).toContainText(operationId);
await expect(page.locator('.openapi-import-plan-outcomes')).toContainText('POST /v1/rates/{date}');
const operationFindings = importedOperation.locator('.openapi-import-findings');
await operationFindings.locator('summary').click();
await expect(operationFindings).toContainText(localized('tool description is too short', 'Описание инструмента слишком короткое'));
await expect(page.locator('tbody')).toContainText(new RegExp(operationId, 'i'));
await expect(page.locator('tbody')).not.toContainText(new RegExp(statusOperationId, 'i'));
await expect(page.locator('body')).not.toContainText(sourceCanary);
await page.locator('[data-openapi-close]').last().click();
await page.locator('tbody tr').filter({ hasText: operationId }).locator('.row-btn-edit').click();
await expect(page).toHaveURL(/\/wizard\/\?mode=edit&operationId=op_/);
});
test('OpenAPI upload rejects invalid files locally and restores focus after Escape', async ({ page }) => {
@@ -230,7 +278,7 @@ test('OpenAPI upload recovers from pagehide and a preview server error', async (
buffer: Buffer.from('openapi: 3.0.3'),
});
await page.locator('#openapi-import-preview').click();
await expect(page.locator('#openapi-import-status')).toContainText(localized('Uploading and parsing', 'Загружаю и разбираю'));
await expect(page.locator('#openapi-import-status')).toContainText(localized('Uploading the document', 'Загружаю документ'));
await page.evaluate(() => window.dispatchEvent(new PageTransitionEvent('pagehide', { persisted: true })));
await expect(page.locator('#openapi-import-status')).toHaveText('');
@@ -246,6 +294,7 @@ test('OpenAPI apply cancellation preserves the import job for an idempotent retr
await login(page);
await dismissOnboardingIfOpen(page);
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await mockEmptyOperationsList(page);
await page.route('**/imports/openapi/preview', async (route) => {
await route.fulfill({
@@ -269,11 +318,18 @@ test('OpenAPI apply cancellation preserves the import job for an idempotent retr
});
const requests = [];
await page.route('**/imports/openapi/*/plans', async (route) => {
const payload = route.request().postDataJSON();
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify(planResponse(payload, 'plan_retry_same_authority')),
});
});
let releaseFirst;
const firstRequest = new Promise((resolve) => {
releaseFirst = resolve;
});
await page.route('**/imports/openapi/*/create', async (route) => {
await page.route('**/imports/openapi/*/apply', async (route) => {
requests.push({ url: route.request().url(), body: route.request().postData() });
if (requests.length === 1) await firstRequest;
if (requests.length === 3) {
@@ -287,12 +343,9 @@ test('OpenAPI apply cancellation preserves the import job for an idempotent retr
try {
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({
created: [{
operation_key: 'get:/retry', name: 'renamed_after_conflict', operation_id: 'op_retry', version: 1,
}],
skipped: [], findings: [],
}),
body: JSON.stringify(applyResponse({ outcomes: [{
key: 'get:/retry', name: 'renamed_after_conflict', status: 'created',
}] })),
});
} catch (_error) {
// The first request is deliberately aborted by the browser.
@@ -305,23 +358,25 @@ test('OpenAPI apply cancellation preserves the import job for an idempotent retr
await page.locator('#openapi-import-preview').click();
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
await page.locator('#openapi-import-create').click();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
await page.locator('#openapi-import-plan-apply').click();
await expect.poll(() => requests.length).toBe(1);
await page.locator('#openapi-import-cancel').click();
await expect(page.locator('#openapi-import-status')).toContainText(localized('may have completed', 'мог завершиться'));
await expect(page.locator('#openapi-import-status')).toContainText(localized('Apply result is unknown', 'Результат применения неизвестен'));
await expect(page.locator('#openapi-import-retry')).toBeVisible();
await page.locator('[data-openapi-close]').last().click();
await page.reload();
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await expect(page.locator('#openapi-import-retry')).toBeVisible();
await page.locator('#openapi-import-retry').click();
await expect(page.locator('#openapi-import-result')).toContainText('GET /retry');
await expect(page.locator('#openapi-import-result')).toContainText('get:/retry');
await expect.poll(() => requests.length).toBe(2);
// Let the cancelled first attempt answer after the retry. Its stale response
// must not overwrite or unlock the newer attempt's state.
releaseFirst();
await page.waitForTimeout(50);
await expect(page.locator('#openapi-import-result')).toContainText('GET /retry');
expect(requests[0].url).toContain('/imports/openapi/job_retry_same_authority/create');
await expect(page.locator('#openapi-import-result')).toContainText('get:/retry');
expect(requests[0].url).toContain('/imports/openapi/plan_retry_same_authority/apply');
expect(requests[1].url).toBe(requests[0].url);
expect(requests[1].body).toBe(requests[0].body);
@@ -334,17 +389,20 @@ test('OpenAPI apply cancellation preserves the import job for an idempotent retr
await page.locator('#openapi-import-preview').click();
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
await page.locator('#openapi-import-create').click();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
await page.locator('#openapi-import-plan-apply').click();
await expect.poll(() => requests.length).toBe(3);
await expect(page.locator('#openapi-import-file-select')).toBeEnabled();
await expect(page.locator('#openapi-import-reset')).toBeEnabled();
await expect(page.locator('#openapi-import-retry')).toBeVisible();
expect(await page.evaluate(() => sessionStorage.getItem('crank_openapi_apply_replay_v1'))).toBeNull();
expect(await page.evaluate(() => sessionStorage.getItem('crank_openapi_plan_apply_replay_v2'))).toBeNull();
});
test('OpenAPI apply preserves job authority after language or workspace changes', async ({ page }) => {
await login(page);
await dismissOnboardingIfOpen(page);
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await mockEmptyOperationsList(page);
await page.route('**/imports/openapi/preview', async (route) => {
await route.fulfill({
@@ -368,16 +426,21 @@ test('OpenAPI apply preserves job authority after language or workspace changes'
});
const releases = [];
const applyRequests = [];
await page.route('**/imports/openapi/*/create', async (route) => {
await page.route('**/imports/openapi/*/plans', async (route) => {
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify(planResponse(route.request().postDataJSON(), 'plan_active_apply')),
});
});
await page.route('**/imports/openapi/*/apply', async (route) => {
applyRequests.push({ url: route.request().url(), body: route.request().postData() });
await new Promise((resolve) => releases.push(resolve));
try {
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({
created: [{ operation_key: 'get:/active', name: 'active', operation_id: 'op_active', version: 1 }],
skipped: [], findings: [],
}),
body: JSON.stringify(applyResponse({ outcomes: [{
key: 'get:/active', name: 'active', status: 'created',
}] })),
});
} catch (_error) {
// The invalidation aborts a request that must not update the modal afterwards.
@@ -394,6 +457,8 @@ test('OpenAPI apply preserves job authority after language or workspace changes'
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
await page.locator('#openapi-import-server-custom').fill('https://api.example.test');
await page.locator('#openapi-import-create').click();
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
await page.locator('#openapi-import-plan-apply').click();
await expect(page.locator('#openapi-import-cancel')).toBeVisible();
await expect.poll(() => releases.length).toBeGreaterThan(0);
}
@@ -402,14 +467,14 @@ test('OpenAPI apply preserves job authority after language or workspace changes'
// Exercise the actual UI language switcher path: it updates storage,
// re-renders translations and dispatches crank:langchange in one action.
await page.evaluate(() => window.setLang('en'));
await expect(page.locator('#openapi-import-status')).toContainText('may have completed');
await expect(page.locator('#openapi-import-status')).toContainText('Apply result is unknown');
await expect(page.locator('#openapi-import-retry')).toBeVisible();
await expect(page.locator('#openapi-import-file-select')).toBeDisabled();
releases.shift()();
await page.locator('#openapi-import-retry').click();
await expect.poll(() => releases.length).toBeGreaterThan(0);
releases.shift()();
await expect(page.locator('#openapi-import-result')).toContainText('GET /active');
await expect(page.locator('#openapi-import-result')).toContainText('get:/active');
expect(applyRequests[1].url).toBe(applyRequests[0].url);
expect(applyRequests[1].body).toBe(applyRequests[0].body);
@@ -419,7 +484,7 @@ test('OpenAPI apply preserves job authority after language or workspace changes'
await page.evaluate(() => {
window.dispatchEvent(new CustomEvent('crank:workspacechange', { detail: { id: 'workspace-after-apply' } }));
});
await expect(page.locator('#openapi-import-status')).toContainText('may have completed');
await expect(page.locator('#openapi-import-status')).toContainText('Apply result is unknown');
await expect(page.locator('#openapi-import-retry')).toBeVisible();
await expect(page.locator('#openapi-import-file-select')).toBeDisabled();
releases.shift()();
@@ -516,6 +581,7 @@ test('OpenAPI upload ignores a stale failure and renders only correlation identi
await login(page);
await dismissOnboardingIfOpen(page);
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
await mockEmptyOperationsList(page);
const sourceCanary = 'do-not-render-openapi-source-canary';
await page.locator('#openapi-import-file').setInputFiles({
name: 'safe.yaml',
@@ -590,14 +656,30 @@ test('OpenAPI upload ignores a stale failure and renders only correlation identi
});
await page.locator('#openapi-import-retry').click();
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
let createRequests = 0;
await page.route('**/imports/openapi/*/create', async (route) => {
createRequests += 1;
await new Promise((resolve) => setTimeout(resolve, 100));
await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ created: [], skipped: [], findings: [] }) });
await page.route('**/imports/openapi/*/plans', async (route) => {
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify(planResponse(route.request().postDataJSON(), 'plan_ui_evidence')),
});
});
let applyRequests = 0;
let releaseApply;
const applyResponseHeld = new Promise((resolve) => { releaseApply = resolve; });
await page.route('**/imports/openapi/*/apply', async (route) => {
applyRequests += 1;
await applyResponseHeld;
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify(applyResponse({ outcomes: [{ key: 'get:/health', name: 'health', status: 'created' }] })),
});
});
await page.locator('#openapi-import-create').click();
await page.locator('#openapi-import-create').evaluate((button) => button.click());
await expect(page.locator('#openapi-import-status')).toContainText('Created: 0; skipped: 0.');
expect(createRequests).toBe(1);
await expect(page.locator('[data-testid="openapi-import-apply-confirmation"]')).toBeVisible();
const applyButton = page.locator('#openapi-import-plan-apply');
await applyButton.dblclick();
await expect.poll(() => applyRequests).toBe(1);
await expect(applyButton).toBeDisabled();
releaseApply();
await expect(page.locator('#openapi-import-status')).toContainText('Import plan applied.');
expect(applyRequests).toBe(1);
});
+41
View File
@@ -0,0 +1,41 @@
const { test, expect } = require('@playwright/test');
const { login } = require('./helpers');
test('delayed new-upstream autofocus must not steal focus from the URL field', async ({ page }) => {
await login(page);
await page.goto('/wizard/');
await page.waitForFunction(() => window.CrankWizardReady === true);
await page.locator('[data-testid="wizard-protocol-rest"]').click();
await page.locator('#btn-continue').click();
await expect(page.locator('#upstream-new-trigger')).toBeVisible();
// Take manual control of page time before the new-upstream form is opened so
// the deferred autofocus timer scheduled by startNewUpstream cannot fire on
// its own while Playwright fills the two fields.
const installTime = new Date('2026-05-01T12:00:00.000Z');
await page.clock.install({ time: installTime });
await page.clock.pauseAt(new Date(installTime.getTime() + 1000));
await page.locator('#upstream-new-trigger').click();
await page.locator('#new-upstream-name').fill('focus-red-upstream');
await page.locator('#new-upstream-url').fill('http://127.0.0.1:3310');
// Both values landed exactly and focus is explicitly on the URL field before
// the deferred autofocus runs.
await expect(page.locator('#new-upstream-name')).toHaveValue('focus-red-upstream');
await expect(page.locator('#new-upstream-url')).toHaveValue('http://127.0.0.1:3310');
await expect(page.locator('#new-upstream-url')).toBeFocused();
// Explicitly execute the old 50ms autofocus timer.
await page.clock.runFor(100);
// The delayed autofocus must not move focus back to the name field.
await expect(page.locator('#new-upstream-url')).toBeFocused();
// Correct field still receives text after the timer ran; no network mutation.
await page.keyboard.insertText('-probe');
await expect(page.locator('#new-upstream-url')).toHaveValue('http://127.0.0.1:3310-probe');
await expect(page.locator('#new-upstream-name')).toHaveValue('focus-red-upstream');
});
+165
View File
@@ -0,0 +1,165 @@
const { test, expect } = require('@playwright/test');
const { getCurrentWorkspace, login } = require('./helpers');
function draftSnapshot(operationId) {
return {
id: operationId,
name: operationId,
display_name: 'Imported rates',
category: 'general',
protocol: 'rest',
target: {
kind: 'rest',
base_url: 'https://api.example.test',
method: 'GET',
path_template: '/rates',
static_headers: {},
},
input_schema: {
type: 'object',
description: null,
required: false,
nullable: false,
default_value: null,
fields: {},
items: null,
enum_values: [],
variants: [],
},
output_schema: {
type: 'object',
description: null,
required: false,
nullable: false,
default_value: null,
fields: {},
items: null,
enum_values: [],
variants: [],
},
input_mapping: { rules: [] },
output_mapping: {
rules: [
{ source: '$.response.body', target: '$.output', required: true },
{ source: '$.response.body.rate', target: '$.output.rate', required: true },
],
},
execution_config: {
timeout_ms: 10000,
retry_policy: null,
auth_profile_ref: null,
headers: {},
approval_policy: null,
},
tool_description: { title: 'Imported rates', description: 'Get rates.', tags: [], examples: [] },
wizard_state: { input_sample: {}, output_sample: {}, test_input: {}, import_findings: [] },
};
}
test('edit wizard skips no-op saves and refreshes its baseline after a real edit', async ({ page }) => {
await login(page);
const workspace = await getCurrentWorkspace(page);
const operationId = 'imported_rates_noop';
const operationPath = `/api/admin/workspaces/${encodeURIComponent(workspace.id)}/operations/${operationId}`;
const versionPath = `${operationPath}/versions/*`;
let version = 4;
let updateCount = 0;
const testedVersions = [];
const publishedVersions = [];
const analyzedPayloads = [];
await page.route(operationPath, async (route) => {
if (route.request().method() === 'PATCH') {
updateCount += 1;
version += 1;
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({ operation_id: operationId, workspace_id: workspace.id, version, status: 'draft' }),
});
return;
}
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({
id: operationId,
workspace_id: workspace.id,
name: operationId,
display_name: 'Imported rates',
category: 'general',
protocol: 'rest',
status: 'draft',
current_draft_version: version,
draft_version_ref: { version, status: 'draft' },
published_version_ref: null,
agent_refs: [],
}),
});
});
await page.route(versionPath, async (route) => {
const requestedVersion = Number(new URL(route.request().url()).pathname.split('/').pop());
await route.fulfill({
contentType: 'application/json',
body: JSON.stringify({
operation_id: operationId,
workspace_id: workspace.id,
version: requestedVersion,
status: 'draft',
snapshot: draftSnapshot(operationId),
}),
});
});
await page.route(`**/operations/${operationId}/test-runs`, async (route) => {
testedVersions.push(route.request().postDataJSON().version);
await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ ok: true, errors: [] }) });
});
await page.route('**/operations/analyze-quality', async (route) => {
analyzedPayloads.push(route.request().postDataJSON());
await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ blocking: false, findings: [] }) });
});
await page.route(`**/operations/${operationId}/publish`, async (route) => {
const payload = route.request().postDataJSON();
publishedVersions.push(payload.version);
await route.fulfill({ contentType: 'application/json', body: JSON.stringify({ published_version: payload.version }) });
});
page.on('dialog', (dialog) => dialog.accept());
await page.goto(`/wizard/?mode=edit&operationId=${operationId}`);
await expect(page.locator('#tool-display-name')).toHaveValue('Imported rates');
const loadedOutputMapping = await page.evaluate(() => (
window.jsyaml.load(document.getElementById('tool-output-mapping').value)
));
expect(loadedOutputMapping['$.output']).toBe('$.response.body');
expect(loadedOutputMapping.rate).toBe('$.response.body.rate');
expect(JSON.stringify(loadedOutputMapping)).not.toContain('$.response.body.$.output');
await page.evaluate(() => window.CrankWizardShell.doGoToStep(5));
await page.locator('#wizard-run-test').click();
await expect.poll(() => testedVersions).toEqual([4]);
expect(updateCount).toBe(0);
await page.evaluate(() => window.CrankWizardShell.doGoToStep(4));
await page.locator('#tool-display-name').fill('Edited rates');
await page.locator('.btn-save-draft').click();
await expect.poll(() => updateCount).toBe(1);
await page.evaluate(() => window.CrankWizardShell.doGoToStep(5));
await page.locator('#wizard-run-test').click();
await expect.poll(() => testedVersions).toEqual([4, 5]);
expect(updateCount).toBe(1);
await page.locator('#wizard-publish-operation').click();
await expect.poll(() => publishedVersions).toEqual([5]);
expect(updateCount).toBe(1);
const publishedRules = analyzedPayloads[analyzedPayloads.length - 1].output_mapping.rules;
expect(publishedRules).toEqual(expect.arrayContaining([
expect.objectContaining({ source: '$.response.body', target: '$.output' }),
expect.objectContaining({ source: '$.response.body.rate', target: '$.output.rate' }),
]));
expect(JSON.stringify(publishedRules)).not.toContain('$.response.body.$.output');
});
+4 -2
View File
@@ -193,7 +193,7 @@ test('wizard builds visual request mappings from JSON sample and path params', a
await page.goto('/wizard/');
await page.locator('[data-testid="wizard-protocol-rest"]').click();
await page.evaluate(() => window.CrankWizardShell.goToStep(2));
await page.locator('#btn-continue').click();
await expect(page.locator('#step-panel-2')).toBeVisible();
await page.locator('#endpoint-path').fill('/rates/{date}');
await page.evaluate(() => window.CrankWizardShell.goToStep(3));
@@ -881,10 +881,12 @@ test('wizard edit mode preserves explicit request mapping targets on save', asyn
await expect(page.locator('#approval-risk-level')).toHaveCount(0);
await expect(page.locator('#approval-ttl-seconds')).toHaveValue('180');
await expect(page.locator('#approval-payload-preview-mode')).toHaveCount(0);
await page.evaluate(() => window.CrankWizardShell.doGoToStep(4));
await page.locator('#tool-display-name').fill('Frankfurter latest rate edited');
await page.locator('.btn-save-draft').click();
await expect.poll(() => updatePayload).not.toBeNull();
expect(updatePayload.display_name).toBe('Frankfurter latest rate');
expect(updatePayload.display_name).toBe('Frankfurter latest rate edited');
expect(updatePayload.target).toEqual({
kind: 'rest',
base_url: 'https://api.frankfurter.app',
+30 -4
View File
@@ -367,6 +367,8 @@ impl ExternalReferenceFetcher {
fn outbound_client(policy: &OutboundHttpPolicy) -> Result<Client, Arc<str>> {
let resolver = Arc::new(PolicyDnsResolver {
policy: policy.clone(),
#[cfg(test)]
lookup: None,
});
Client::builder()
.redirect(redirect::Policy::none())
@@ -611,23 +613,43 @@ impl OutboundHttpPolicy {
}
}
#[derive(Clone, Debug)]
#[derive(Clone)]
struct PolicyDnsResolver {
policy: OutboundHttpPolicy,
// Test-local DNS answers exercise the actual policy resolver and connector.
// Neither this field nor an injection API exists in production builds.
#[cfg(test)]
lookup: Option<Arc<dyn Resolve>>,
}
impl PolicyDnsResolver {
fn lookup(&self, name: Name) -> Resolving {
#[cfg(test)]
if let Some(lookup) = &self.lookup {
return lookup.resolve(name);
}
let host = normalize_host(name.as_str());
Box::pin(async move {
let addresses = tokio::net::lookup_host((host.as_str(), 0))
.await
.map_err(|error| Box::new(error) as Box<dyn std::error::Error + Send + Sync>)?;
let addresses: Vec<_> = addresses.collect();
Ok(Box::new(addresses.into_iter()) as Addrs)
})
}
}
impl Resolve for PolicyDnsResolver {
fn resolve(&self, name: Name) -> Resolving {
let host = normalize_host(name.as_str());
let policy = self.policy.clone();
let resolver = self.clone();
Box::pin(async move {
policy
.validate_host(&host)
.map_err(|error| boxed_io_error(error.to_string()))?;
let explicitly_allowed = policy.is_explicitly_allowed(&host);
let resolved = tokio::net::lookup_host((host.as_str(), 0))
.await
.map_err(|error| Box::new(error) as Box<dyn std::error::Error + Send + Sync>)?;
let resolved = resolver.lookup(name).await?;
let addresses = resolved
.filter(|address| {
!policy.is_denied_ip(address.ip())
@@ -969,3 +991,7 @@ fn to_reqwest_method(method: HttpMethod) -> reqwest::Method {
HttpMethod::Options => reqwest::Method::OPTIONS,
}
}
#[cfg(test)]
#[path = "client_dns_tests.rs"]
mod dns_tests;
@@ -0,0 +1,155 @@
//! Use the production policy resolver in reqwest's real connector. DNS can
//! change immediately after lookup; only the validated returned addresses may
//! be connected to, and a subsequent resolution must enforce policy again.
use super::*;
use axum::{Router, routing::get};
use std::sync::atomic::{AtomicUsize, Ordering};
struct ChangingLookup {
calls: AtomicUsize,
answers: Vec<Vec<SocketAddr>>,
}
impl Resolve for ChangingLookup {
fn resolve(&self, _: Name) -> Resolving {
// Advancing before the connector receives this iterator models a DNS
// answer changing between validation and the socket connection.
let call = self.calls.fetch_add(1, Ordering::SeqCst);
let addresses = self.answers[call.min(self.answers.len() - 1)].clone();
Box::pin(async move { Ok(Box::new(addresses.into_iter()) as Addrs) })
}
}
struct Listeners(Vec<tokio::task::JoinHandle<()>>);
impl Drop for Listeners {
fn drop(&mut self) {
for handle in &self.0 {
handle.abort();
}
}
}
async fn fixture() -> (u16, Arc<AtomicUsize>, Arc<AtomicUsize>, Listeners) {
let allowed = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = allowed.local_addr().unwrap().port();
let denied = tokio::net::TcpListener::bind((Ipv4Addr::new(127, 0, 0, 2), port))
.await
.unwrap();
let allowed_count = Arc::new(AtomicUsize::new(0));
let denied_count = Arc::new(AtomicUsize::new(0));
let mut handles = Vec::new();
for (listener, count) in [
(allowed, Arc::clone(&allowed_count)),
(denied, Arc::clone(&denied_count)),
] {
handles.push(tokio::spawn(async move {
let app = Router::new().route(
"/document",
get(move || {
let count = Arc::clone(&count);
async move {
count.fetch_add(1, Ordering::SeqCst);
"snapshot"
}
}),
);
axum::serve(listener, app).await.unwrap();
}));
}
(port, allowed_count, denied_count, Listeners(handles))
}
fn policy_client(lookup: Arc<ChangingLookup>) -> Client {
let policy = OutboundHttpPolicy::try_new(
vec!["reference.invalid".into()],
vec!["127.0.0.2".into()],
1024,
)
.unwrap();
Client::builder()
.no_proxy()
.redirect(redirect::Policy::none())
.pool_max_idle_per_host(0)
.timeout(Duration::from_secs(3))
.dns_resolver(Arc::new(PolicyDnsResolver {
policy,
lookup: Some(lookup),
}))
.build()
.unwrap()
}
#[tokio::test]
async fn dns_rebinding_pins_the_validated_connection_then_rejects_changed_denied_answer() {
let (port, allowed, denied, _listeners) = fixture().await;
let lookup = Arc::new(ChangingLookup {
calls: AtomicUsize::new(0),
answers: vec![
vec!["127.0.0.1:0".parse().unwrap()],
vec!["127.0.0.2:0".parse().unwrap()],
],
});
let client = policy_client(Arc::clone(&lookup));
let url = format!("http://reference.invalid:{port}/document");
let body = client
.get(&url)
.send()
.await
.unwrap()
.error_for_status()
.unwrap()
.text()
.await
.unwrap();
assert_eq!(body, "snapshot");
assert_eq!(
lookup.calls.load(Ordering::SeqCst),
1,
"one validated answer is pinned for this connection"
);
assert_eq!(allowed.load(Ordering::SeqCst), 1);
assert_eq!(denied.load(Ordering::SeqCst), 0);
// Disable idle pooling above so a new connection really asks for the new
// answer; no timing or external DNS configuration is involved.
let error = client.get(&url).send().await.unwrap_err();
assert!(error.is_connect());
assert!(
!error.is_timeout(),
"must reject the new DNS answer, not merely time out"
);
assert_eq!(lookup.calls.load(Ordering::SeqCst), 2);
assert_eq!(allowed.load(Ordering::SeqCst), 1);
assert_eq!(
denied.load(Ordering::SeqCst),
0,
"deny must win over hostname allowlist"
);
}
#[tokio::test]
async fn mixed_dns_answers_never_pass_denied_address_to_the_connector() {
let (port, allowed, denied, _listeners) = fixture().await;
let lookup = Arc::new(ChangingLookup {
calls: AtomicUsize::new(0),
answers: vec![vec![
"127.0.0.2:0".parse().unwrap(),
"127.0.0.1:0".parse().unwrap(),
]],
});
let client = policy_client(Arc::clone(&lookup));
assert_eq!(
client
.get(format!("http://reference.invalid:{port}/document"))
.send()
.await
.unwrap()
.text()
.await
.unwrap(),
"snapshot"
);
assert_eq!(lookup.calls.load(Ordering::SeqCst), 1);
assert_eq!(allowed.load(Ordering::SeqCst), 1);
assert_eq!(denied.load(Ordering::SeqCst), 0);
}
@@ -30,6 +30,18 @@ pub enum FaultAction {
Hold,
}
/// Terminates a debug test process at an explicitly armed transaction boundary.
/// Release builds contain neither this hook nor its callers. The checkpoint
/// is in-memory only; a request or environment variable cannot arm it.
#[cfg(debug_assertions)]
pub fn crash_if_checkpointed(stage: &str) {
if action(stage) == Some(FaultAction::Exit) {
// Deliberately skip destructors/atexit, as a lost process would. Test
// containers belong to the parent process, not this child.
unsafe { libc::_exit(86) }
}
}
struct State {
checkpoint: Option<(String, FaultAction, usize)>,
hits: BTreeMap<String, usize>,
Loaded 100 of 445 files, more files were not shown because too many files have changed in this diff. Show more