Compare commits

...
147 changed files with 34784 additions and 686 deletions

No files matched your search

+27
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: actions/upload-artifact@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
Generated
+14 -13
View File
@@ -221,9 +221,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 +231,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 +766,7 @@ dependencies = [
"serde",
"serde_json",
"serde_yaml",
"sha2 0.10.9",
"thiserror 2.0.18",
"url",
]
@@ -1142,7 +1143,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 +2672,7 @@ dependencies = [
"once_cell",
"socket2 0.5.10",
"tracing",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -3010,14 +3011,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 +3070,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
"windows-sys 0.52.0",
"windows-sys 0.59.0",
]
[[package]]
@@ -3080,9 +3081,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",
@@ -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]]
@@ -0,0 +1,164 @@
---
title: '3.6 — Сохранять typed static Resource Drafts'
type: feature
created: '2026-10-01'
status: blocked
review_loop_iteration: 0
followup_review_recommended: false
context:
- '{project-root}/_bmad-output/implementation-artifacts/epic-3-context.md'
warnings: [oversized]
deferred: []
---
<intent-contract>
## Intent
**Problem:** Администратору необходимо безопасно сохранять text, JSON и binary Resource Drafts с typed contract, bounded artifact и безопасным preview.
**Approach:** Создать отдельный typed Resource aggregate и persistence/API для Draft, сохраняя content bytes в существующем content-addressed artifact store. AC ниже уточнены решением пользователя: эта story ограничена Draft/Admin preview и безопасным download; MCP read и negotiated representation реализуются и проверяются в Story 3.8.
## Boundaries & Constraints
**Always:** Отдельные Resource ID/version/lifecycle, CapabilityKind::Resource и sensitivity; immutable Published contract; bounded bytes, exact digest и metadata; стабильные URI/name; UTF-8 и JSON validation без изменения semantics; безопасные preview/download и ошибки без content leakage. Следовать существующим Rust, registry, migration и API conventions.
**Never:** Untyped Operation subtype, универсальный JSON blob, filesystem paths/upload filenames/mutable external references в published contract; исполнение HTML/SVG в origin Crank; unbounded content в DOM/logs/errors. Не писать и не откатывать sprint-status.yaml. Не реализовывать соседние stories без разрешённой границы intent.
<frozen-after-approval>
### Согласованная граница Story 3.6
Решение пользователя от 2026-10-01 (вариант 1): Story 3.6 сохраняет typed static Resource Drafts и предоставляет Draft/Admin preview и безопасный download. Для binary проверяются MIME, точный byte size, bounded opaque bytes и безопасная выдача без text decoding, без unbounded bytes в DOM/telemetry и без content в logs/errors.
`resources/list`, `resources/read`, MCP version adapter, negotiated binary representation и их wire qualification относятся к Story 3.8. Publication и exact Agent binding остаются в Story 3.7; Story 3.6 задаёт typed domain/persistence contract, но не реализует эти lifecycle действия ради MCP read. Условие завершения Story 3.6 не требует MCP surface или будущей qualification. Эта граница определяет чтение AC ниже и исходной формулировки binary AC в epics.md.
</frozen-after-approval>
## I/O & Edge-Case Matrix
| Scenario | Input / State | Expected Output / Behavior | Error Handling |
|----------|--------------|---------------------------|----------------|
| Text | Bounded UTF-8 | Exact bytes и digest | Invalid UTF-8/oversize: stable finding, без truncation |
| JSON | Bounded valid JSON | Сохранение data semantics и exact artifact | Malformed/oversize отклоняются до publication |
| Binary Draft/Admin preview/download | Bounded opaque bytes + MIME | Точные MIME/byte size, inert metadata preview и безопасная binary выдача без text decoding; без unbounded bytes в DOM/telemetry | Safe finding, без content в logs/errors |
| MCP read / negotiated representation | Bound Published Resource Version | Реализация и wire qualification в Story 3.8 после Story 3.7; не критерий завершения 3.6 | Не добавлять MCP surface в 3.6 |
| Active content | HTML/SVG | Inert preview либо безопасный attachment | Safe Content-Type, nosniff, CSP/sandbox, sanitized filename |
| Integrity | Несовпадение digest/metadata | Fail closed | Safe error без filesystem/content leakage |
</intent-contract>
## Code Map
- `crates/crank-core/src/ids.rs` — существующий define_id! pattern; ResourceId/ResourceVersionId отсутствуют.
- `crates/crank-core/src/lib.rs`, `crates/crank-registry/src/model.rs` — domain exports и PublishedAgentTool; отдельного Resource aggregate и CapabilityKind нет.
- `crates/crank-artifacts/src/store.rs`, `model.rs` — ArtifactStore put/read API и ArtifactRef с digest; reuse для exact bytes.
- `crates/crank-registry/src/model/artifact_source.rs` — ArtifactSourceSensitivity относится к OpenAPI, не является готовым Resource sensitivity contract.
- `crates/crank-registry/src/migrations.rs`, `migrations/` — canonical authority, versioned SQL/Rust migrations; Resource tables отсутствуют.
- `apps/admin-api/src/routes/agents.rs`, `service/agents.rs`, `dto.rs` — Draft lifecycle и DTO conventions.
- `apps/admin-api/src/service/imports/verified_preview.rs` — существующий artifact preview pattern.
- `apps/ui/js/openapi-import.js`, `i18n.js` — vanilla JS preview и RU/EN conventions; Resource UI отсутствует.
- `crates/crank-community-mcp/src/jsonrpc.rs:3` — supported revisions 2025-03-26, 2025-06-18, 2025-11-25; negotiation есть, Resource version adapter отсутствует.
- `crates/crank-community-mcp/src/app.rs:827` — method dispatch без resources/list/read; `:1378` — capabilities только tools, listChanged=false.
- `apps/mcp-server/tests/integration/transport_protocol.rs`, `catalog_access.rs` — существующие wire integration surfaces; Resource evidence отсутствует.
- `justfile:59` — обязательный just verify.
- `_bmad-output/planning-artifacts/epics.md:2462` — read-only исходный intent 3.6; `:2520` — 3.7 publication/binding; `:2568` — 3.8 MCP read.
## Tasks & Acceptance
**Execution (предварительно; gate не пройден):**
- [ ] `crates/crank-core/src/ids.rs`, `lib.rs`, новый Resource domain module — typed identity/kinds/lifecycle/sensitivity и bounded validation.
- [ ] `crates/crank-registry/src/model.rs`, `repository.rs`, `postgres/`, `migrations/`, `docs/schemas/migration-sequence.json` — отдельная typed Draft persistence и canonical migration contract.
- [ ] `crates/crank-artifacts/src/`, `tests/` — reuse digest storage и проверить Resource artifact integrity.
- [ ] `apps/admin-api/src/routes/`, `service/`, `dto.rs` — authenticated Draft create/update/upload/preview с stable findings и safe download headers.
- [ ] `apps/ui/js/`, `apps/ui/css/`, `apps/ui/tests/` — безопасный Resource preview/download согласно согласованной границе.
- [ ] `crates/crank-core/tests/`, `crates/crank-registry/tests/`, `apps/admin-api/tests/` — domain/artifact/API edge cases; regression cases до fix.
MCP implementation и wire tests не входят в задачи 3.6: `crates/crank-community-mcp/src/` и `apps/mcp-server/tests/` для Resource read/version adapter относятся к 3.8.
**Acceptance Criteria (с уточнённой пользователем границей Draft/Admin):**
**Given** Resource domain model
**When** добавляется persistence и API contract
**Then** Resource является отдельным typed aggregate с собственными ID/version/lifecycle, `CapabilityKind::Resource`, sensitivity и immutable Published Version
**And** не хранится как untyped Operation subtype или универсальный JSON blob.
**Given** новый Resource Draft
**When** администратор выбирает static text, JSON или binary kind
**Then** задаются URI, name, description, MIME type, sensitivity и bounded content
**And** URI и name валидируются как стабильные capability identifiers.
**Given** static content
**When** оно сохраняется
**Then** bytes размещаются в content-addressed artifact store, а Resource Version хранит exact digest и metadata
**And** filesystem path, raw upload filename или mutable external reference не входит в published contract.
**Given** JSON Resource
**When** Draft сохраняется или preview-ится
**Then** content валидируется как JSON и возвращается без изменения data semantics
**And** malformed либо oversized JSON отклоняется до publication.
**Given** text Resource
**When** content принимается
**Then** он сохраняет валидный UTF-8 в пределах configured size
**And** invalid encoding или unsafe truncation отклоняются с stable finding.
**Given** binary Resource
**When** Draft preview-ится или скачивается через Admin API/UI
**Then** соблюдаются MIME, точный byte size и configured size limit; preview показывает inert metadata, а download безопасно возвращает exact binary bytes
**And** content не декодируется как text, unbounded bytes не попадают в DOM/telemetry, content не попадает в logs/errors.
MCP read, version adapter и negotiated binary representation реализуются и проверяются в Story 3.8; они не являются AC завершения Story 3.6.
**Given** Resource с active либо browser-renderable content type, включая HTML или SVG
**When** Admin UI показывает preview/download
**Then** untrusted bytes не исполняются в origin Crank: используется inert text/metadata, sandboxed isolated preview либо attachment download по explicit allowlist
**And** response применяет safe `Content-Type`, `nosniff`, CSP/sandbox и filename sanitization без content sniffing.
**Given** static Resource Draft suite
**When** выполняются domain, artifact и API tests
**Then** покрыты text/JSON/binary validation, MIME/size, active-content preview, malformed encoding и artifact integrity
**And** `just verify` проходит.
## Spec Change Log
- 2026-10-01 — пользователь выбрал вариант 1 в bmad-loop-resolve: 3.6 ограничена Draft/Admin preview/download; MCP read/version adapter/negotiated representation закреплены за 3.8. Уточнены frozen intent, binary AC, матрица и verification scope; статус оставлен оркестратору.
## Review Triage Log
## Design Notes
### Разрешённая граница intent
Исходный binary AC объединял Admin preview и MCP read, хотя цепочка зависимостей 3.6 → 3.7 → 3.8 относит publication/binding к 3.7, а MCP discovery/read и version adapter к 3.8. Пользователь выбрал вариант 1: в 3.6 проверяются только Draft/Admin preview/download, в 3.8 — exact published MCP read и negotiated representation. Frozen intent и AC выше фиксируют это решение; первоначальные результаты остановок ниже сохранены как история, а не актуальное требование MCP scope.
## Verification
Для повторного запуска 3.6: domain/artifact/registry/Admin API tests для text/JSON/binary Drafts, exact bytes/digest, MIME/size, encoding, safe preview/download и integrity; `just verify`, UI проверки при UI изменениях. MCP wire tests всех supported revisions, включая negotiated representation, выполняются в 3.8. В resolve-сессии код не реализовывался и тесты не запускались; исторические результаты предыдущих запусков приведены ниже.
## Auto Run Result
Status: blocked
Blocking condition: intent gap
- Workflow остановлен на step-02 Plan по правилу intent gaps; код не изменён, реализация/ревью/проверка AC не выполнены.
- Baseline получен напрямую через `git rev-parse HEAD`: `7ffde8885ddd7c0196134f6085330536911a72be`.
- Исходное рабочее дерево чистое, ветка соответствует story; `git add --refresh -- .` завершился успешно.
- Составлен Epic 3 context и read-only Code Map; ведущий проверил MCP dispatch, capabilities и negotiation непосредственно в коде.
- Нет действий AC, требующих покупки/настройки внешнего сервиса человеком. `awaiting-operator` неприменим: препятствие — противоречие границ спецификации внутри repo.
- `sprint-status.yaml` не изменён и не использован как доказательство верификации.
- Неразрешённый вопрос: должна ли 3.6 включать MCP binary read, или этот AC ограничивается Draft/Admin preview, а MCP проверяется в 3.8?
- Финальные проверки: `git diff --check` успешен, tracked working tree чистое. Документы `_bmad-output` игнорируются Git; commit кода не создавался.
- Read-only Pi завершил handoff; его tmux/Pi-сессия остановлена после завершения инструментов.
- `docker volume prune -f` завершён, освобождено 0B; активные контейнеры и именованные тома не удалялись. Повторные `docker system df`, `df -h /`, `btrfs filesystem usage /`: доступно около 110 ГБ, Metadata DUP 998.34 MiB / 7.01 GiB, global reserve used=0. Подробный per-device usage недоступен без root, общий запас metadata достаточен.
### Повторный запуск 2026-10-01
Status: blocked
Blocking condition: blocked spec supplied
- При маршрутизации story найдена существующая спецификация со статусом `blocked`; решение о границе Draft/Admin preview и MCP read не предоставлено. По HALT workflow реализация и ревью не запускались.
- Это нерешённая граница intent внутри репозитория, а не HUMAN-only operator action; статус `awaiting-operator` неприменим.
- Текущая ревизия: `7ffde8885ddd7c0196134f6085330536911a72be`. Код и `sprint-status.yaml` не изменялись; commit не создавался.
- `git diff --check` успешен, tracked working tree чистое. Тесты не запускались, фоновые исполнители не создавались.
- `docker volume prune -f` завершён (0B); последующие `docker system df`, `df -h /` и `btrfs filesystem usage /` успешны. Свободно около 110 ГБ, Metadata DUP использует 998.16 MiB из 7.01 GiB, global reserve used=0; подробный per-device usage недоступен без root.
+12 -1
View File
@@ -27,7 +27,10 @@ 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,
},
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,
@@ -58,6 +61,14 @@ 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),
)
.route(
"/imports/openapi/{plan_id}/apply",
post(apply_openapi_import_plan).layer(DefaultBodyLimit::max(16 * 1024)),
)
.route(
"/operations/analyze-quality",
post(analyze_operation_quality),
+67
View File
@@ -575,6 +575,73 @@ 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>,
}
#[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 reason: Option<String>,
}
#[derive(Clone, Debug, Serialize)]
pub struct OpenApiImportPlanCreateResponse {
pub plan_reference: String,
pub plan_digest: String,
pub expires_at: String,
pub selection_mode: String,
pub counts: OpenApiImportPlanCounts,
pub candidates: Vec<OpenApiImportPlanCandidateView>,
}
#[derive(Clone, Debug, Serialize)]
pub struct CreatedOperationResponse {
pub operation_id: String,
+88
View File
@@ -687,6 +687,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!({
+53 -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,49 @@ 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>,
Json(payload): Json<OpenApiImportPlanCreatePayload>,
) -> Result<Json<Value>, ApiError> {
let plan = state
.service
.create_openapi_import_plan(
&path.workspace_id.as_str().into(),
&path.job_id.as_str().into(),
payload,
)
.await?;
Ok(Json(json!(plan)))
}
pub async fn apply_openapi_import_plan(
Path(path): Path<WorkspacePlanPath>,
State(state): State<AppState>,
Json(payload): Json<OpenApiImportPlanApplyPayload>,
) -> Result<impl IntoResponse, ApiError> {
let report = state
.service
.apply_openapi_import_plan(
&path.workspace_id.as_str().into(),
&path.plan_id.as_str().into(),
payload,
)
.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};
+35 -359
View File
@@ -2,8 +2,8 @@ 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,
ToolQualityFinding, ToolQualitySeverity, WorkspaceId,
};
use crank_import::rest::{
ImportFinding, ImportFindingSeverity, ImportOperationCandidate, NORMALIZER_VERSION,
@@ -11,11 +11,12 @@ use crank_import::rest::{
};
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};
@@ -24,21 +25,38 @@ use crate::{
error::ApiError,
service::{
AdminService, OpenApiImportCreatePayload, OpenApiImportCreateResponse,
OpenApiImportCreatedOperation, OpenApiImportPreviewResponse, OpenApiImportSkippedOperation,
OpenApiUpload, OpenApiUploadLocale, OperationPayload, new_prefixed_id,
OpenApiImportCreatedOperation, OpenApiImportPlanApplyPayload,
OpenApiImportPlanCandidateView, OpenApiImportPlanCounts, OpenApiImportPlanCreatePayload,
OpenApiImportPlanCreateResponse, OpenApiImportPlanDecision, OpenApiImportPreviewResponse,
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 = 512;
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);
@@ -276,141 +294,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 +317,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);
}
@@ -599,227 +496,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
@@ -0,0 +1,779 @@
use super::*;
impl AdminService {
#[instrument(skip(self, payload), fields(workspace_id = %workspace_id.as_str(), job_id = %job_id.as_str()))]
pub async fn create_openapi_import_plan(
&self,
workspace_id: &WorkspaceId,
job_id: &ImportJobId,
payload: OpenApiImportPlanCreatePayload,
) -> 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 {
return Err(ApiError::validation("import preview has expired"));
}
if job.status != ImportJobStatus::Pending {
return Err(import_plan_repreview_error("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, OpenApiUploadLocale::En)
.await
.map_err(|resolution| match resolution {
ImportPreviewResolution::Fatal(error_code, _) => {
import_plan_repreview_error(error_code)
}
ImportPreviewResolution::NonFatal(error) => error,
})?;
let preview = &resolved.preview;
// 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,
OpenApiUploadLocale::En,
)
.await
.map_err(|_| import_plan_repreview_error("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();
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 decisions = 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(),
key,
candidate,
decisions.get(key).copied(),
blocker,
)
.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(),
};
// 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-v1",
"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,
"selection": {
"mode": payload.selection_mode,
"all": all_keys,
"selected": selected_keys,
"excluded": excluded,
},
"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(),
reason: candidate.reason.clone(),
})
.collect();
candidate_views.extend(excluded.iter().map(|key| {
let name = candidates
.get(key)
.map(|candidate| candidate.draft.name.clone())
.unwrap_or_default();
OpenApiImportPlanCandidateView {
key: key.clone(),
name,
state: "excluded".to_owned(),
action: None,
target_operation_id: None,
confirmed_name: None,
auth_profile_id: None,
reason: Some("not_selected".to_owned()),
}
}));
Ok(OpenApiImportPlanCreateResponse {
plan_reference: created.id.as_str().to_owned(),
plan_digest: created.digest,
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>,
key: &str,
candidate: &ImportOperationCandidate,
decision: Option<&OpenApiImportPlanDecision>,
blocker_reason: Option<String>,
) -> 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 candidate_name = candidate.draft.name.clone();
let 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: key.to_owned(),
name: candidate_name,
blocked: true,
reason: Some("operation_name_conflict".to_owned()),
action: action.to_owned(),
target_operation_id,
confirmed_name,
auth_profile_id,
auth_snapshot: None,
target: None,
operation: None,
});
}
return Err(ApiError::conflict_with_context(
format!("operation with name {final_name} already exists"),
json!({
"name": final_name,
"error_code": "import_plan_name_conflict",
"recovery": "confirm_skip_rename_or_new_version"
}),
));
}
}
// The final server-authored auth profile reference: the explicit
// decision, or the target's reference inherited for an actionable
// new_version. Only the reference (never a secret value) is stored.
let mut auth_profile_ref = auth_profile_id
.as_deref()
.map(|id| AuthProfileId::new(id.to_owned()));
if let Some(summary) = target_summary.as_ref()
&& !blocked
&& action == "new_version"
&& auth_profile_ref.is_none()
{
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;
}
let auth_profile_id = auth_profile_ref.as_ref().map(|id| id.as_str().to_owned());
if blocked {
return Ok(PlannedCandidate {
key: key.to_owned(),
name: candidate_name,
blocked: true,
reason: blocker_reason,
action: action.to_owned(),
target_operation_id,
confirmed_name,
auth_profile_id,
auth_snapshot: None,
target,
operation: None,
});
}
if action == "skip" {
return Ok(PlannedCandidate {
key: key.to_owned(),
name: candidate_name,
blocked: false,
reason: None,
action: action.to_owned(),
target_operation_id,
confirmed_name,
auth_profile_id,
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: key.to_owned(),
name: draft.name,
blocked: false,
reason: None,
action: action.to_owned(),
target_operation_id,
confirmed_name,
auth_profile_id,
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 = || import_plan_repreview_error("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>,
auth_snapshot: Option<Value>,
target: Option<Value>,
operation: Option<RegistryOperation>,
}
pub(super) fn import_plan_repreview_error(error_code: &'static str) -> ApiError {
ApiError::conflict_with_context(
"import plan revalidation failed; create a fresh preview",
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())
}
}
}
/// 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.
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");
}
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() {
return invalid("auth_profile_id 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(())
}
/// 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,
},
});
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(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,185 @@
use super::*;
use crank_registry::{ApplyImportPlanRequest, ImportPlanApplyReport};
const MAX_IMPORT_PLAN_IDEMPOTENCY_KEY_BYTES: usize = 128;
impl AdminService {
#[instrument(skip(self, payload), fields(workspace_id = %workspace_id.as_str(), plan_id = %plan_id.as_str()))]
pub async fn apply_openapi_import_plan(
&self,
workspace_id: &WorkspaceId,
plan_id: &ImportPlanId,
payload: OpenApiImportPlanApplyPayload,
) -> 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());
}
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("import_plan_digest_mismatch"));
}
let now = OffsetDateTime::now_utc();
if plan.expires_at <= now {
return Err(import_plan_repreview_error("import_plan_expired"));
}
let job = self
.registry
.get_import_job(workspace_id, &plan.job_id)
.await?
.ok_or_else(|| import_plan_repreview_error("import_plan_job_unavailable"))?;
if job.kind != ImportJobKind::OpenApi {
return Err(import_plan_repreview_error("import_plan_job_kind_mismatch"));
}
if job.status != ImportJobStatus::Pending || job.expires_at <= now {
return Err(import_plan_repreview_error("import_plan_job_terminal"));
}
let resolved = self
.resolve_verified_openapi_preview(workspace_id, &job, OpenApiUploadLocale::En)
.await
.map_err(|resolution| match resolution {
ImportPreviewResolution::Fatal(error_code, _) => {
import_plan_repreview_error(error_code)
}
ImportPreviewResolution::NonFatal(_) => {
import_plan_repreview_error("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)
{
return Err(import_plan_repreview_error("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,
OpenApiUploadLocale::En,
)
.await
.map_err(|_| import_plan_repreview_error("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(map_apply_registry_error)?;
Ok(result.report)
}
}
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(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("import_plan_expired")
}
RegistryError::ImportPlanPayloadCorrupt { .. } => {
import_plan_repreview_error("import_plan_payload_invalid")
}
RegistryError::ImportPlanFingerprintStale { .. } => {
import_plan_repreview_error("import_plan_fingerprint_stale")
}
RegistryError::ImportPlanKeyDigestConflict { .. } => key_digest_conflict(),
RegistryError::ImportPlanNameConflict { .. } => ApiError::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 { .. } => {
import_plan_repreview_error("import_plan_target_stale")
}
RegistryError::ImportPlanAuthUnavailable { .. } => {
import_plan_repreview_error("import_plan_auth_unavailable")
}
other => ApiError::from(other),
}
}
fn key_digest_conflict() -> ApiError {
ApiError::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
}),
)
}
@@ -0,0 +1,390 @@
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 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(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))
.flat_map(|operation| operation.findings.iter())
.any(|finding| finding.severity == ImportFindingSeverity::Error)
}
+1 -1
View File
@@ -111,7 +111,7 @@ async fn real_admin_startup_runs_immediate_import_maintenance() {
.fetch_one(&pool)
.await
.unwrap(),
Some(13),
Some(14),
"migration binary must install the current canonical ledger",
);
sqlx::query(
@@ -11,6 +11,8 @@ use super::common::{
mod external_references;
mod http_contract;
mod import_plan_apply;
mod import_plan_create;
const OPENAPI3: &str = r#"
openapi: 3.0.3
@@ -0,0 +1,846 @@
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::*;
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_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 } }
"#;
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_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,
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,
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 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;
@@ -0,0 +1,295 @@
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);
let secret = std::fs::read_to_string(root.join("hostile-secret.json")).unwrap();
let secret_plan = create_plan(&client, &base_url, &secret, full_plan()).await;
let exposed = format!("{}{}", secret_plan.preview, secret_plan.body);
assert!(
!exposed.contains("sk_test_corpus_secret_canary"),
"secret canary leaked into plan evidence"
);
assert_eq!(operation_list(&client, &base_url).await, before);
for file in ["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 block only the inherited one. No Apply mutation follows.
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("unsupported_security_requirement"),
"secured candidate must expose the exact security blocker: {}",
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"], "unsupported_security_requirement");
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,952 @@
use super::*;
#[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();
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.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());
// 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 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.reason.as_deref(), Some("not_selected"));
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-v1");
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");
}
#[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 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 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",
"create",
None,
None,
Some(auth_profile.id.as_str()),
)],
),
)
.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()
);
// 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())
);
// An unknown profile reference fails closed in the workspace scope check.
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,
Some("auth_missing_profile"),
)],
),
)
.await
.expect_err("an unknown auth profile reference must be rejected");
assert_error_code(&error, "operation_auth_profile_invalid");
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))
.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));
}
#[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,163 @@
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),
}
}
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 validation;
@@ -0,0 +1,275 @@
use super::*;
#[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()
);
}
+2 -2
View File
@@ -40,7 +40,7 @@ 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(), 14);
let checked = command(&["plan", "--check"], None);
assert!(
@@ -82,7 +82,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"], 14);
}
#[tokio::test]
+142 -4
View File
@@ -160,6 +160,103 @@
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-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 +282,6 @@
}
#openapi-import-server,
#openapi-import-conflict-mode,
#openapi-import-search,
#openapi-import-method-filter,
.openapi-import-server-custom {
@@ -266,12 +362,50 @@
}
.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-decision-controls {
display: flex;
flex-wrap: wrap;
gap: 10px 14px;
padding-left: 28px;
}
.openapi-import-decision-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 {
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-plan-blocked-help {
margin: 0;
color: var(--red);
font-weight: 700;
}
.openapi-import-operation:last-child {
@@ -304,6 +438,10 @@
font-size: 12px;
}
.openapi-import-operation .openapi-import-findings {
grid-column: auto;
}
.openapi-import-finding {
display: inline-flex;
align-items: baseline;
@@ -484,7 +622,7 @@
justify-content: flex-start;
}
.openapi-import-operation {
.openapi-import-operation-selection {
grid-template-columns: auto 1fr;
}
+14 -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>
@@ -443,9 +436,21 @@
<div class="openapi-import-groups" id="openapi-import-groups"></div>
<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-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>
<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-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 class="openapi-import-result" id="openapi-import-result" data-testid="openapi-import-apply-result" hidden></div>
</div>
</div>
</section>
+22
View File
@@ -436,6 +436,28 @@
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,
});
},
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');
},
+104
View File
@@ -611,6 +611,7 @@ 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.',
'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 +1659,7 @@ var TRANSLATIONS = {
'wizard.step2.auth_mode.none': 'Без авторизации',
'wizard.step2.auth_mode.existing': 'Использовать существующий профиль авторизации',
'wizard.step2.auth_mode.create': 'Создать профиль авторизации сейчас',
'openapi.error.plan_too_large': 'Выберите не более 512 операций и оставьте не более 512 исключённых операций.',
'wizard.step2.auth_profile': 'Профиль авторизации',
'wizard.step2.auth_profile_hint': 'Выбранный профиль применяется автоматически при каждом вызове инструмента.',
'wizard.step2.auth_profile_empty': 'Профилей авторизации пока нет. Создайте профиль ниже.',
@@ -2093,6 +2095,57 @@ Object.assign(TRANSLATIONS.en, {
'openapi.select_visible': 'Select visible',
'openapi.clear_visible': 'Clear visible',
'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.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}',
@@ -2209,6 +2262,57 @@ Object.assign(TRANSLATIONS.ru, {
'openapi.select_visible': 'Выбрать видимые',
'openapi.clear_visible': 'Снять видимые',
'openapi.create': 'Создать черновики',
'openapi.plan.create': 'Проверить план импорта',
'openapi.plan.confirm_title': 'Подтвердите план импорта',
'openapi.plan.confirm_intro': 'Перед применением проверьте точный план сервера.',
'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}',
+577 -61
View File
@@ -1,6 +1,6 @@
(function() {
var MAX_FILE_BYTES = 256 * 1024;
var APPLY_REPLAY_STORAGE_KEY = 'crank_openapi_apply_replay_v1';
var APPLY_REPLAY_STORAGE_KEY = 'crank_openapi_plan_apply_replay_v2';
var restoredApplyRequest = loadApplyReplay();
var state = {
workspaceId: null,
@@ -8,10 +8,15 @@
file: null,
jobId: null,
preview: null,
existingOperations: [],
operationsReady: false,
decisions: Object.create(null),
plan: null,
filterQuery: '',
filterMethod: '',
revision: 0,
previewController: null,
planController: null,
applyController: null,
applyInFlight: false,
applyRequest: restoredApplyRequest,
@@ -25,23 +30,9 @@
function validApplyReplay(request) {
return request
&& typeof request.workspaceId === 'string' && request.workspaceId.length > 0 && request.workspaceId.length <= 128
&& typeof request.jobId === 'string' && request.jobId.length > 0 && request.jobId.length <= 128
&& request.payload && Array.isArray(request.payload.selected_operation_keys)
&& request.payload.selected_operation_keys.length <= 1024
&& request.payload.selected_operation_keys.every(function(key) {
return typeof key === 'string' && key.length > 0 && key.length <= 512;
})
&& (request.payload.server_url === null
|| (typeof request.payload.server_url === 'string' && request.payload.server_url.length <= 2048))
&& (request.payload.conflict_mode === 'skip' || request.payload.conflict_mode === 'rename')
&& Array.isArray(request.operationMetadata)
&& request.operationMetadata.length <= 1024
&& request.operationMetadata.every(function(operation) {
return operation
&& typeof operation.key === 'string' && operation.key.length > 0 && operation.key.length <= 512
&& typeof operation.method === 'string' && operation.method.length > 0 && operation.method.length <= 16
&& typeof operation.path === 'string' && operation.path.length > 0 && operation.path.length <= 2048;
});
&& typeof request.planReference === 'string' && request.planReference.length > 0 && request.planReference.length <= 128
&& typeof request.planDigest === 'string' && /^[a-f0-9]{64}$/.test(request.planDigest)
&& typeof request.idempotencyKey === 'string' && request.idempotencyKey.length > 0 && request.idempotencyKey.length <= 128;
}
function loadApplyReplay() {
@@ -131,6 +122,116 @@
});
}
function importOperations() {
return (state.preview && state.preview.groups || []).flatMap(function(group) {
return group.operations || [];
});
}
function decisionFor(operationKey) {
if (!state.decisions[operationKey]) {
state.decisions[operationKey] = { action: 'create', targetOperationId: '', confirmedName: '' };
}
return state.decisions[operationKey];
}
function matchingOperations(operation) {
return state.existingOperations.filter(function(existing) {
return existing.name === operation.suggested_name;
});
}
function renderDecisionControls(operation, row) {
var previous = row.querySelector('.openapi-import-decision-controls');
if (previous) previous.remove();
var controls = document.createElement('div');
var actionLabel = document.createElement('label');
var actionSelect = document.createElement('select');
var candidateDecision = decisionFor(operation.key);
var matches = matchingOperations(operation);
var versionable = matches.filter(function(existing) {
return existing.protocol === 'rest' && existing.status !== 'archived';
});
var actions = [
['create', 'openapi.decision.create'],
['skip', 'openapi.decision.skip'],
['rename', 'openapi.decision.rename'],
['new_version', 'openapi.decision.new_version'],
];
controls.className = 'openapi-import-decision-controls';
actionLabel.textContent = tKey('openapi.decision.action_label');
actionLabel.htmlFor = 'openapi-import-decision-' + operation.key;
actionSelect.id = actionLabel.htmlFor;
actionSelect.dataset.openapiDecisionAction = operation.key;
actions.forEach(function(spec) {
var option = document.createElement('option');
option.value = spec[0];
option.textContent = tKey(spec[1]);
if ((spec[0] === 'skip' && !matches.length)
|| (spec[0] === 'new_version' && !versionable.length)) {
option.disabled = true;
}
actionSelect.appendChild(option);
});
actionSelect.value = candidateDecision.action;
actionSelect.addEventListener('change', function() {
candidateDecision.action = actionSelect.value;
if (candidateDecision.action === 'skip' || candidateDecision.action === 'new_version') {
var allowed = candidateDecision.action === 'new_version' ? versionable : matches;
if (!allowed.some(function(existing) { return existing.id === candidateDecision.targetOperationId; })) {
candidateDecision.targetOperationId = allowed.length === 1 ? allowed[0].id : '';
}
}
renderDecisionControls(operation, row);
});
actionLabel.appendChild(actionSelect);
controls.appendChild(actionLabel);
if (candidateDecision.action === 'skip' || candidateDecision.action === 'new_version') {
var targetLabel = document.createElement('label');
var targetSelect = document.createElement('select');
var allowedTargets = candidateDecision.action === 'new_version' ? versionable : matches;
var placeholder = document.createElement('option');
targetLabel.textContent = tKey('openapi.decision.target_label');
targetSelect.dataset.openapiDecisionTarget = operation.key;
placeholder.value = '';
placeholder.textContent = tKey('openapi.decision.target_placeholder');
targetSelect.appendChild(placeholder);
allowedTargets.forEach(function(existing) {
var option = document.createElement('option');
option.value = existing.id;
option.textContent = existing.name + ' · ' + existing.id;
targetSelect.appendChild(option);
});
targetSelect.value = candidateDecision.targetOperationId;
targetSelect.addEventListener('change', function() {
candidateDecision.targetOperationId = targetSelect.value;
});
targetLabel.appendChild(targetSelect);
controls.appendChild(targetLabel);
}
if (candidateDecision.action === 'rename') {
var renameLabel = document.createElement('label');
var renameInput = document.createElement('input');
renameLabel.textContent = tKey('openapi.decision.confirmed_name_label');
renameInput.type = 'text';
renameInput.maxLength = 128;
renameInput.value = candidateDecision.confirmedName;
renameInput.placeholder = tKey('openapi.decision.confirmed_name_placeholder');
renameInput.dataset.openapiDecisionName = operation.key;
renameInput.addEventListener('input', function() {
candidateDecision.confirmedName = renameInput.value;
});
renameLabel.appendChild(renameInput);
controls.appendChild(renameLabel);
}
row.appendChild(controls);
}
function operationRows() {
return Array.from(document.querySelectorAll('.openapi-import-operation'));
}
@@ -371,6 +472,10 @@
state.jobId = response.job_id;
state.preview = preview;
state.existingOperations = [];
state.operationsReady = false;
state.decisions = Object.create(null);
importOperations().forEach(function(operation) { decisionFor(operation.key); });
state.filterQuery = '';
state.filterMethod = '';
qs('openapi-import-preview-panel').hidden = false;
@@ -407,9 +512,11 @@
groupNode.appendChild(header);
group.operations.forEach(function(operation) {
var row = document.createElement('label');
var row = document.createElement('div');
var selectionLabel = document.createElement('label');
row.className = 'openapi-import-operation';
selectionLabel.className = 'openapi-import-operation-selection';
row.dataset.openapiMethod = operation.method;
row.dataset.openapiSearch = [
group.title,
@@ -419,12 +526,13 @@
operation.path,
operation.method,
].join(' ');
row.innerHTML = '<input type="checkbox" data-openapi-operation value="' + escapeHtml(operation.key) + '" checked>'
selectionLabel.innerHTML = '<input type="checkbox" data-openapi-operation value="' + escapeHtml(operation.key) + '" checked>'
+ '<div><div class="openapi-import-operation-title">' + escapeHtml(operation.suggested_display_name) + '</div>'
+ '<div class="openapi-import-operation-meta"><code>' + escapeHtml(operation.suggested_name) + '</code> · '
+ escapeHtml(operation.path) + ' · '
+ escapeHtml(tfKey('openapi.operation.fields', { input: operation.input_fields, output: operation.output_fields }))
+ '</div></div><span class="openapi-import-method">' + escapeHtml(operation.method) + '</span>';
row.appendChild(selectionLabel);
row.appendChild(renderOperationMappingPreview(operation));
if (operation.findings && operation.findings.length) {
@@ -434,6 +542,7 @@
row.appendChild(findings);
}
renderDecisionControls(operation, row);
groupNode.appendChild(row);
});
@@ -480,6 +589,10 @@
function clearPreview() {
state.jobId = null;
state.preview = null;
state.existingOperations = [];
state.operationsReady = false;
state.decisions = Object.create(null);
state.plan = null;
state.applyRequest = null;
state.applyMetadata = [];
state.applyResult = null;
@@ -488,6 +601,11 @@
state.filterQuery = '';
state.filterMethod = '';
qs('openapi-import-preview-panel').hidden = true;
qs('openapi-import-plan-confirmation').hidden = true;
qs('openapi-import-plan-counts').replaceChildren();
qs('openapi-import-plan-candidates').replaceChildren();
qs('openapi-import-versioning-consequences').hidden = true;
qs('openapi-import-plan-blocked-help').hidden = true;
qs('openapi-import-groups').replaceChildren();
qs('openapi-import-result').hidden = true;
qs('openapi-import-result').replaceChildren();
@@ -502,12 +620,16 @@
function invalidate(options) {
state.revision += 1;
abort(state.previewController);
abort(state.planController);
abort(state.applyController);
state.previewController = null;
state.planController = null;
state.applyController = null;
state.applyInFlight = false;
qs('openapi-import-preview').disabled = false;
qs('openapi-import-create').disabled = false;
qs('openapi-import-plan-apply').disabled = false;
qs('openapi-import-plan-back').disabled = false;
qs('openapi-import-file-select').disabled = false;
qs('openapi-import-reset').disabled = false;
qs('openapi-import-cancel').hidden = true;
@@ -529,6 +651,39 @@
qs('openapi-import-preview').disabled = locked;
qs('openapi-import-file-select').disabled = locked;
qs('openapi-import-reset').disabled = locked;
qs('openapi-import-plan-apply').disabled = locked;
qs('openapi-import-plan-back').disabled = locked;
qs('openapi-import-server').disabled = locked;
qs('openapi-import-server-custom').disabled = locked;
qs('openapi-import-search').disabled = locked;
qs('openapi-import-method-filter').disabled = locked;
qs('openapi-import-select-visible').disabled = locked;
qs('openapi-import-clear-visible').disabled = locked;
document.querySelectorAll('[data-openapi-operation], [data-openapi-group]').forEach(function(input) {
input.disabled = locked;
});
document.querySelectorAll('.openapi-import-decision-controls select, .openapi-import-decision-controls input').forEach(function(input) {
input.disabled = locked;
});
}
function lockPlanEditing(locked) {
qs('openapi-import-create').disabled = locked;
qs('openapi-import-preview').disabled = locked;
qs('openapi-import-file-select').disabled = locked;
qs('openapi-import-reset').disabled = locked;
qs('openapi-import-server').disabled = locked;
qs('openapi-import-server-custom').disabled = locked;
qs('openapi-import-search').disabled = locked;
qs('openapi-import-method-filter').disabled = locked;
qs('openapi-import-select-visible').disabled = locked;
qs('openapi-import-clear-visible').disabled = locked;
document.querySelectorAll('[data-openapi-operation], [data-openapi-group]').forEach(function(input) {
input.disabled = locked;
});
document.querySelectorAll('.openapi-import-decision-controls select, .openapi-import-decision-controls input').forEach(function(input) {
input.disabled = locked;
});
}
function markApplyOutcomeUnknown(options) {
@@ -539,14 +694,14 @@
state.applyInFlight = false;
state.applyOutcomeUnknown = true;
persistApplyReplay(state.applyRequest);
// Until the same job is replayed, starting another import could hide an
// Until the same plan is replayed, starting another import could hide an
// already committed server outcome and lead to duplicate drafts.
lockApplyInputs(true);
qs('openapi-import-cancel').hidden = true;
if (!options || options.render !== false) {
showRetry(true);
setStatus(tKey('openapi.status.apply_outcome_unknown'), true, true);
setStatus(tKey('openapi.plan.retry_unknown'), true, true);
}
return true;
@@ -557,6 +712,16 @@
markApplyOutcomeUnknown();
return;
}
if (state.planController) {
abort(state.planController);
state.planController = null;
state.revision += 1;
lockPlanEditing(false);
qs('openapi-import-cancel').hidden = true;
showRetry(false);
setStatus(tKey('openapi.status.cancelled'));
return;
}
if (!state.previewController) return;
invalidate();
@@ -621,6 +786,23 @@
if (!isCurrent(revision, workspaceId, language)) return;
renderPreview(response);
qs('openapi-import-create').disabled = true;
setStatus(tKey('openapi.status.loading_operations'));
var operationResponse = await window.CrankApi.listOperations(workspaceId);
if (!isCurrent(revision, workspaceId, language)) return;
if (!operationResponse || !Array.isArray(operationResponse.items)) {
throw new Error('Backend returned an invalid operations list response');
}
state.existingOperations = operationResponse.items;
state.operationsReady = true;
importOperations().forEach(function(operation) {
var row = Array.from(document.querySelectorAll('.openapi-import-operation')).find(function(candidateRow) {
var input = candidateRow.querySelector('[data-openapi-operation]');
return input && input.value === operation.key;
});
if (row) renderDecisionControls(operation, row);
});
qs('openapi-import-create').disabled = false;
setStatus(tKey('openapi.status.preview_ready'));
} catch (error) {
if (!isCurrent(revision, workspaceId, language)) return;
@@ -785,12 +967,176 @@
}
function createdStatus(response) {
if (response && response.counts) {
return tfKey('openapi.plan.summary', {
applied: (Number(response.counts.created) || 0)
+ (Number(response.counts.versioned) || 0)
+ (Number(response.counts.renamed) || 0),
skipped: Number(response.counts.skipped) || 0,
excluded: Number(response.counts.excluded) || 0,
rejected: Number(response.counts.rejected) || 0,
});
}
return tfKey('openapi.status.created', {
created: (response.created || []).length,
skipped: (response.skipped || []).length,
});
}
function planActionLabel(candidate) {
if (candidate.state === 'excluded') return tKey('openapi.plan.action.excluded');
if (candidate.state === 'blocked') return tKey('openapi.plan.action.blocked');
var action = String(candidate.action || 'create');
var key = 'openapi.plan.action.' + action;
return tKey(key) === key ? tKey('openapi.plan.action.create') : tKey(key);
}
function renderImportPlan(plan) {
var countsNode = qs('openapi-import-plan-counts');
var candidatesNode = qs('openapi-import-plan-candidates');
var versioningNode = qs('openapi-import-versioning-consequences');
var counts = plan.counts || {};
var hasBlocked = (Number(counts.blocked) || 0) > 0;
var countSpecs = [
['selected', 'openapi.plan.selected'],
['excluded', 'openapi.plan.excluded'],
['actionable', 'openapi.plan.actionable'],
['blocked', 'openapi.plan.blocked'],
];
countsNode.replaceChildren();
candidatesNode.replaceChildren();
countSpecs.forEach(function(spec) {
var item = document.createElement('span');
item.className = 'openapi-import-plan-count';
item.textContent = tfKey(spec[1], { count: Number(counts[spec[0]]) || 0 });
countsNode.appendChild(item);
});
var hasNewVersion = false;
(Array.isArray(plan.candidates) ? plan.candidates : []).forEach(function(candidate) {
var item = document.createElement('article');
var title = document.createElement('strong');
var key = document.createElement('code');
var action = document.createElement('p');
item.className = 'openapi-import-plan-candidate';
item.dataset.state = String(candidate.state || 'blocked');
title.textContent = String(candidate.name || candidate.key || tKey('openapi.result.unnamed'));
key.textContent = String(candidate.key || '');
action.textContent = planActionLabel(candidate);
item.append(title, key, action);
if (candidate.target_operation_id) {
var target = document.createElement('p');
target.textContent = tKey('openapi.plan.exact_target') + ': ' + candidate.target_operation_id;
item.appendChild(target);
}
if (candidate.confirmed_name) {
var confirmedName = document.createElement('p');
confirmedName.textContent = tKey('openapi.plan.confirmed_name') + ': ' + candidate.confirmed_name;
item.appendChild(confirmedName);
}
if (candidate.action === 'new_version' && candidate.state !== 'blocked' && candidate.state !== 'excluded') {
hasNewVersion = true;
}
if (candidate.reason) {
var reason = document.createElement('p');
reason.className = 'openapi-import-plan-reason';
reason.textContent = findingMessage({ code: candidate.reason });
item.appendChild(reason);
}
candidatesNode.appendChild(item);
});
versioningNode.textContent = tKey('openapi.plan.versioning_new');
versioningNode.hidden = !hasNewVersion;
qs('openapi-import-plan-confirmation').hidden = false;
qs('openapi-import-plan-blocked-help').hidden = !hasBlocked;
qs('openapi-import-result').hidden = true;
qs('openapi-import-plan-apply').disabled = hasBlocked;
qs('openapi-import-plan-back').textContent = tKey(hasBlocked ? 'openapi.plan.back_fix' : 'openapi.plan.back');
lockPlanEditing(true);
}
function reportOutcomeLabel(outcome) {
var value = String(outcome || 'rejected');
var key = 'openapi.plan.outcome.' + value;
return tKey(key) === key ? tKey('openapi.plan.outcome.rejected') : tKey(key);
}
function renderImportPlanReport(report) {
var node = qs('openapi-import-result');
var title = document.createElement('strong');
node.replaceChildren();
title.textContent = tKey('openapi.plan.result_title');
node.appendChild(title);
var counts = report.counts || {};
var applied = (Number(counts.created) || 0)
+ (Number(counts.versioned) || 0)
+ (Number(counts.renamed) || 0);
var summary = document.createElement('p');
summary.className = 'openapi-import-plan-summary';
summary.textContent = tfKey('openapi.plan.summary', {
applied: applied,
skipped: Number(counts.skipped) || 0,
excluded: Number(counts.excluded) || 0,
rejected: Number(counts.rejected) || 0,
});
node.appendChild(summary);
var outcomes = Array.isArray(report.outcomes) ? report.outcomes : [];
if (outcomes.length) {
var list = document.createElement('div');
list.className = 'openapi-import-plan-outcomes';
outcomes.forEach(function(outcome) {
var item = document.createElement('article');
var heading = document.createElement('strong');
var key = document.createElement('code');
var detail = document.createElement('p');
var outcomeStatus = outcome.status || outcome.outcome || 'rejected';
item.className = 'openapi-import-plan-outcome';
item.dataset.outcome = String(outcomeStatus);
heading.textContent = String(outcome.name || outcome.key || tKey('openapi.result.unnamed'));
key.textContent = String(outcome.key || '');
detail.textContent = reportOutcomeLabel(outcomeStatus);
if (Number.isInteger(outcome.version)) {
detail.textContent += ' · v' + outcome.version;
}
item.append(heading, key, detail);
if (outcome.reason) {
var reason = document.createElement('p');
reason.className = 'openapi-import-plan-reason';
reason.textContent = findingMessage({ code: outcome.reason });
item.appendChild(reason);
}
list.appendChild(item);
});
node.appendChild(list);
}
node.hidden = false;
qs('openapi-import-plan-confirmation').hidden = true;
}
function recoveryCode(payload) {
var value = payload && payload.error && typeof payload.error === 'object'
? payload.error
: payload;
var context = value && value.context && typeof value.context === 'object'
? value.context
: value;
return String((context && context.recovery) || (payload && payload.recovery) || '');
}
function reportFromPayload(payload) {
if (!payload || typeof payload !== 'object') return null;
var errorContext = payload.error && payload.error.context;
var report = payload.report || payload.apply_report
|| (errorContext && (errorContext.report || errorContext.apply_report || errorContext))
|| payload;
return report && Array.isArray(report.outcomes) ? report : null;
}
async function notifyImported(revision, workspaceId, language) {
if (typeof state.onImported !== 'function') return;
@@ -819,13 +1165,16 @@
lockApplyInputs(true);
qs('openapi-import-cancel').hidden = false;
showRetry(false);
setStatus(tKey('openapi.status.creating'));
setStatus(tKey('openapi.status.applying'));
try {
var response = await window.CrankApi.createOpenApiImport(
var response = await window.CrankApi.applyOpenApiImportPlan(
workspaceId,
request.jobId,
request.payload,
request.planReference,
{
plan_digest: request.planDigest,
idempotency_key: request.idempotencyKey,
},
{ signal: controller.signal }
);
// Abort is advisory: a superseded request can still deliver a response.
@@ -847,9 +1196,19 @@
}
state.applyResult = response;
state.applyRequest = null;
state.plan = null;
if (isCurrent(revision, workspaceId, language)) {
setStatus(createdStatus(response));
renderResult(response);
renderImportPlanReport(response);
if (response.recovery === 'repreview_required') {
setStatus(tKey('openapi.plan.repreview'), true, true);
showRetry(true);
} else if (response.status === 'rejected'
|| response.recovery === 'confirm_skip_rename_or_new_version') {
setStatus(tKey('openapi.plan.resolve_conflict'), true, true);
showRetry(true);
} else {
setStatus(tKey('openapi.status.applied'));
}
}
await notifyImported(revision, workspaceId, language);
} catch (error) {
@@ -859,9 +1218,10 @@
if (error && error.name === 'AbortError') {
state.applyOutcomeUnknown = true;
persistApplyReplay(state.applyRequest);
lockApplyInputs(true);
showRetry(true);
if (!qs('openapi-import-modal').hidden) {
setStatus(tKey('openapi.status.apply_outcome_unknown'), true, true);
setStatus(tKey('openapi.plan.retry_unknown'), true, true);
}
return;
}
@@ -872,19 +1232,35 @@
state.applyRequest = null;
clearApplyReplay();
showRetry(true);
var report = reportFromPayload(error.payload);
if (report && isCurrent(revision, workspaceId, language)) {
state.applyResult = report;
renderImportPlanReport(report);
}
var recovery = recoveryCode(error.payload);
state.plan = null;
qs('openapi-import-plan-confirmation').hidden = true;
lockPlanEditing(false);
if (!qs('openapi-import-modal').hidden) {
setStatus(errorStatus(error, 'openapi.error.create'), true, true);
if (recovery === 'repreview_required') {
setStatus(tKey('openapi.plan.repreview'), true, true);
} else if (recovery === 'confirm_skip_rename_or_new_version') {
setStatus(tKey('openapi.plan.resolve_conflict'), true, true);
} else {
setStatus(errorStatus(error, 'openapi.error.apply'), true, true);
}
}
return;
}
// A browser/network failure is not proof that the server rolled the
// transaction back. Replaying this exact job is idempotent server-side.
// transaction back. Replaying this exact plan is idempotent server-side.
state.applyOutcomeUnknown = true;
persistApplyReplay(state.applyRequest);
lockApplyInputs(true);
showRetry(true);
if (!qs('openapi-import-modal').hidden) {
setStatus(errorStatus(error, 'openapi.error.create') + ' ' + tKey('openapi.status.apply_outcome_unknown'), true, true);
setStatus(errorStatus(error, 'openapi.error.apply') + ' ' + tKey('openapi.plan.retry_unknown'), true, true);
}
} finally {
if (state.applyController === controller) {
@@ -896,14 +1272,18 @@
}
}
async function createDrafts() {
if (state.applyInFlight) return;
async function createImportPlan() {
if (state.applyInFlight || state.planController) return;
var keys = selectedKeys();
if (!keys.length) {
setStatus(tKey('openapi.error.selection'), true, true);
return;
}
if (keys.length > 512 || importOperations().length - keys.length > 512) {
setStatus(tKey('openapi.error.plan_too_large'), true, true);
return;
}
if (!state.jobId || !state.preview) {
setStatus(tKey('openapi.error.preview_required'), true, true);
return;
@@ -915,25 +1295,141 @@
return;
}
state.applyRequest = {
workspaceId: state.workspaceId,
jobId: state.jobId,
payload: {
selected_operation_keys: keys,
server_url: serverUrl,
conflict_mode: qs('openapi-import-conflict-mode').value || 'rename',
},
operationMetadata: (state.preview.groups || []).flatMap(function(group) {
return (group.operations || []).filter(function(operation) {
return keys.indexOf(operation.key) >= 0;
}).map(function(operation) {
return { key: operation.key, method: operation.method, path: operation.path };
if (!state.workspaceId) {
setStatus(tKey('openapi.error.workspace'), true, true);
return;
}
if (!state.operationsReady) {
setStatus(tKey('openapi.error.operations_unavailable'), true, true);
return;
}
var selectedSet = new Set(keys);
var decisions = [];
var invalidDecision = null;
importOperations().forEach(function(operation) {
if (!selectedSet.has(operation.key) || invalidDecision) return;
var decision = decisionFor(operation.key);
var output = { operation_key: operation.key, action: decision.action };
if (decision.action === 'skip' || decision.action === 'new_version') {
var allowedTargets = matchingOperations(operation).filter(function(existing) {
return decision.action !== 'new_version'
|| (existing.protocol === 'rest' && existing.status !== 'archived');
});
}),
if (!allowedTargets.some(function(existing) { return existing.id === decision.targetOperationId; })) {
invalidDecision = 'openapi.error.decision_target';
return;
}
output.target_operation_id = decision.targetOperationId;
} else if (decision.action === 'rename') {
if (!decision.confirmedName || !decision.confirmedName.trim()) {
invalidDecision = 'openapi.error.confirmed_name';
return;
}
output.confirmed_name = decision.confirmedName;
} else if (decision.action !== 'create') {
invalidDecision = 'openapi.error.decision_action';
return;
}
if (decision.action !== 'create') decisions.push(output);
});
if (invalidDecision) {
setStatus(tKey(invalidDecision), true, true);
return;
}
var total = (state.preview.groups || []).reduce(function(count, group) {
return count + (group.operations || []).length;
}, 0);
var selectionMode = keys.length === total ? 'full' : 'partial';
var payload = {
selection_mode: selectionMode,
selected_operation_keys: selectionMode === 'full' ? [] : keys,
server_url: serverUrl,
decisions: decisions,
};
state.applyMetadata = state.applyRequest.operationMetadata;
persistApplyReplay(state.applyRequest);
await submitApply(state.applyRequest);
var revision = state.revision;
var workspaceId = state.workspaceId;
var language = locale();
var controller = new AbortController();
state.planController = controller;
state.plan = null;
lockPlanEditing(true);
qs('openapi-import-cancel').hidden = false;
qs('openapi-import-plan-confirmation').hidden = true;
showRetry(false);
setStatus(tKey('openapi.status.planning'));
try {
var plan = await window.CrankApi.createOpenApiImportPlan(
workspaceId,
state.jobId,
payload,
{ signal: controller.signal }
);
if (state.planController !== controller) return;
if (!isCurrent(revision, workspaceId, language)) return;
if (!plan || typeof plan.plan_reference !== 'string'
|| !/^[a-f0-9]{64}$/.test(String(plan.plan_digest || ''))
|| !plan.counts || !Array.isArray(plan.candidates)) {
throw new Error('Backend returned an invalid ImportPlan response');
}
state.plan = plan;
renderImportPlan(plan);
setStatus(tKey('openapi.status.plan_ready'));
} catch (error) {
if (state.planController !== controller) return;
if (error && error.name === 'AbortError') {
setStatus(tKey('openapi.status.cancelled'));
return;
}
setStatus(errorStatus(error, 'openapi.error.plan'), true, true);
showRetry(true);
} finally {
if (state.planController === controller) {
state.planController = null;
lockPlanEditing(!!state.plan);
qs('openapi-import-cancel').hidden = true;
}
}
}
function newIdempotencyKey() {
if (window.crypto && typeof window.crypto.randomUUID === 'function') {
return 'openapi:' + window.crypto.randomUUID();
}
return 'openapi:' + Date.now().toString(36) + ':' + Math.random().toString(36).slice(2);
}
async function applyImportPlan() {
if (state.applyInFlight || !state.plan || state.applyOutcomeUnknown) return;
var request = {
workspaceId: state.workspaceId,
planReference: state.plan.plan_reference,
planDigest: state.plan.plan_digest,
idempotencyKey: newIdempotencyKey(),
};
if (!validApplyReplay(request)) {
setStatus(tKey('openapi.error.apply'), true, true);
return;
}
state.applyRequest = request;
persistApplyReplay(request);
await submitApply(request);
}
function backToImportSelection() {
if (state.applyInFlight || state.applyOutcomeUnknown) return;
state.plan = null;
qs('openapi-import-plan-confirmation').hidden = true;
qs('openapi-import-plan-counts').replaceChildren();
qs('openapi-import-plan-candidates').replaceChildren();
qs('openapi-import-versioning-consequences').hidden = true;
qs('openapi-import-plan-blocked-help').hidden = true;
qs('openapi-import-plan-back').textContent = tKey('openapi.plan.back');
lockPlanEditing(false);
setStatus(tKey('openapi.status.preview_ready'));
}
function retryCurrent() {
@@ -948,7 +1444,6 @@
showRetry(false);
setStatus('');
qs('openapi-import-server-custom').value = '';
qs('openapi-import-conflict-mode').value = 'rename';
}
function open(options) {
@@ -963,12 +1458,25 @@
qs('openapi-import-modal').hidden = false;
renderFileName();
if (state.applyResult) {
renderResult(state.applyResult);
setStatus(createdStatus(state.applyResult) + (state.applyRefreshFailed ? ' ' + tKey('openapi.status.refresh_failed') : ''));
if (Array.isArray(state.applyResult.outcomes)) {
renderImportPlanReport(state.applyResult);
} else {
renderResult(state.applyResult);
}
if (state.applyResult.recovery === 'repreview_required') {
showRetry(true);
setStatus(tKey('openapi.plan.repreview'), true, true);
} else if (state.applyResult.status === 'rejected'
|| state.applyResult.recovery === 'confirm_skip_rename_or_new_version') {
showRetry(true);
setStatus(tKey('openapi.plan.resolve_conflict'), true, true);
} else {
setStatus(createdStatus(state.applyResult) + (state.applyRefreshFailed ? ' ' + tKey('openapi.status.refresh_failed') : ''));
}
} else if (state.applyOutcomeUnknown && state.applyRequest) {
lockApplyInputs(true);
showRetry(true);
setStatus(tKey('openapi.status.apply_outcome_unknown'), true, true);
setStatus(tKey('openapi.plan.retry_unknown'), true, true);
qs('openapi-import-retry').focus();
return;
}
@@ -1031,7 +1539,9 @@
});
qs('openapi-import-preview').addEventListener('click', preview);
qs('openapi-import-retry').addEventListener('click', retryCurrent);
qs('openapi-import-create').addEventListener('click', createDrafts);
qs('openapi-import-create').addEventListener('click', createImportPlan);
qs('openapi-import-plan-apply').addEventListener('click', applyImportPlan);
qs('openapi-import-plan-back').addEventListener('click', backToImportSelection);
qs('openapi-import-cancel').addEventListener('click', cancelCurrent);
qs('openapi-import-reset').addEventListener('click', reset);
qs('openapi-import-search').addEventListener('input', function(event) {
@@ -1082,7 +1592,7 @@
}
if (state.applyOutcomeUnknown && state.applyRequest) {
showRetry(true);
setStatus(tKey('openapi.status.apply_outcome_unknown'), true, true);
setStatus(tKey('openapi.plan.retry_unknown'), true, true);
return;
}
invalidate(options);
@@ -1091,9 +1601,15 @@
setStatus(tKey('openapi.status.context_changed'));
}
}
window.addEventListener('crank:langchange', function() {
function handleLanguageChange() {
if (!qs('openapi-import-modal').hidden && state.plan && !state.applyInFlight && !state.applyOutcomeUnknown) {
renderImportPlan(state.plan);
setStatus(tKey('openapi.status.plan_ready'));
return;
}
invalidateForContext();
});
}
window.addEventListener('crank:langchange', handleLanguageChange);
window.addEventListener('crank:workspacechange', function(event) {
if (!qs('openapi-import-modal').hidden) {
state.workspaceId = event.detail && event.detail.id || null;
@@ -1101,7 +1617,7 @@
}
});
window.addEventListener('storage', function(event) {
if (event.key === 'crank_lang') invalidateForContext();
if (event.key === 'crank_lang') handleLanguageChange();
});
window.addEventListener('pagehide', function() {
if (state.applyInFlight || state.applyController) {
@@ -1124,7 +1640,7 @@
if (state.applyOutcomeUnknown && state.applyRequest) {
lockApplyInputs(true);
showRetry(true);
setStatus(tKey('openapi.status.apply_outcome_unknown'), true, true);
setStatus(tKey('openapi.plan.retry_unknown'), true, true);
} else {
invalidateForContext({ clearFile: true });
}
+1
View File
@@ -156,6 +156,7 @@ test('onboarding error exposes safe support correlation and retries without a cl
});
await page.goto('/');
await expect(page.getByTestId('onboarding-trigger')).toContainText(/3\s*\/\s*7/);
await page.getByTestId('onboarding-trigger').click();
fail = true;
await page.getByTestId('onboarding-refresh').click();
@@ -0,0 +1,278 @@
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) {
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({
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);
});
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();
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,
}]);
});
+114 -38
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', 'Операции'));
@@ -112,7 +154,6 @@ 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-preview')).toContainText(localized('Response', 'Ответ'));
await expect(page.locator('#openapi-import-selection')).toContainText(localized('Selected: 2', 'Выбрано: 2'));
await page.locator('#openapi-import-search').fill('status');
@@ -127,18 +168,19 @@ 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}');
await expect(importedOperation.locator('.openapi-import-findings')).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 }) => {
@@ -246,6 +288,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 +312,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 +337,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 +352,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 +383,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 +420,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 +451,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 +461,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 +478,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 +575,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 +650,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);
});
+1 -1
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));
+1
View File
@@ -13,5 +13,6 @@ crank-schema = { path = "../crank-schema" }
serde.workspace = true
serde_json.workspace = true
serde_yaml.workspace = true
sha2.workspace = true
thiserror.workspace = true
url.workspace = true
+1
View File
@@ -12,6 +12,7 @@ mod normalize_finding_validation;
mod normalize_limits;
mod normalize_projection;
mod normalize_schema;
mod normalize_security;
mod openapi3;
mod openapi3_findings;
mod payload;
@@ -146,6 +146,7 @@ pub fn normalize_verified_bundle(
}
None => return Err(ImportParseError::UnsupportedDocument),
};
super::normalize_security::append_security_requirement_findings(&mut parsed, &root);
super::metadata_findings::collect_secret_like_examples(
&root,
"",
@@ -238,6 +239,8 @@ fn preview_from_operations<'a>(
.push(candidate);
}
super::normalize_security::attach_operation_findings(&mut groups, &findings);
sort_findings(&mut findings);
ImportPreview {
source: source.clone(),
@@ -57,6 +57,10 @@ pub(super) fn matches_source(
pointer.contains("/example") && matches!(&node.value, CanonicalSourceValue::String(value) if secret_like(pointer, value))
}
"invalid_server" if is_error => invalid_server(pointer, node),
"unsupported_security_requirement" if is_error => {
matches!(&node.value, CanonicalSourceValue::Object(fields) if !fields.is_empty())
|| invalid_security_requirement(pointer, node)
}
_ => false,
}
}
@@ -201,6 +205,31 @@ fn secret_like(pointer: &str, value: &str) -> bool {
|| value.starts_with("sk-")
}
/// Accepts malformed `security` shapes at their scoped source location only:
/// the document `security` member, an operation `security` member, or a
/// non-object item of the corresponding security array. An object is valid
/// only as an array item, including the empty `{}` public alternative.
fn invalid_security_requirement(pointer: &str, node: &CanonicalSourceNode) -> bool {
const METHODS: &[&str] = &[
"get", "post", "put", "patch", "delete", "head", "options", "trace", "connect",
];
let is_index = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
let segments: Vec<&str> = pointer.split('/').collect();
match segments.as_slice() {
["", "security"] => true,
["", "security", index] => {
is_index(index) && !matches!(&node.value, CanonicalSourceValue::Object(_))
}
["", "paths", _, method, "security"] => METHODS.contains(method),
["", "paths", _, method, "security", index] => {
METHODS.contains(method)
&& is_index(index)
&& !matches!(&node.value, CanonicalSourceValue::Object(_))
}
_ => false,
}
}
fn invalid_server(pointer: &str, node: &CanonicalSourceNode) -> bool {
if pointer == "/host" {
return !matches!(&node.value, CanonicalSourceValue::String(host) if !host.is_empty() && !host.contains('@') && !host.chars().any(char::is_whitespace));
@@ -0,0 +1,166 @@
//! Effective per-operation security scopes for the OpenAPI importer.
use serde_json::Value;
use super::{
model::{
ImportFinding, ImportFindingSeverity, ImportGroupPreview, RestImportDocument,
RestImportOperation, SourceLocation,
},
normalize_coverage,
};
pub(super) fn attach_operation_findings(
groups: &mut std::collections::BTreeMap<String, ImportGroupPreview>,
findings: &[ImportFinding],
) {
for group in groups.values_mut() {
for candidate in &mut group.operations {
let additions = findings
.iter()
.filter(|finding| {
finding.severity == ImportFindingSeverity::Error
&& finding.operation_key.as_deref() == Some(candidate.key.as_str())
&& !candidate.findings.iter().any(|existing| {
existing.code == finding.code
&& existing.severity == finding.severity
&& existing.message == finding.message
})
})
.cloned()
.collect::<Vec<_>>();
candidate.findings.extend(additions);
}
}
}
/// Computes the effective security requirements for every candidate operation
/// and attaches source-located blockers to precisely the affected candidates.
///
/// Effective requirements follow the OpenAPI semantics: an operation that
/// declares its own `security` member wins over the document root; an empty
/// array (`security: []`) explicitly disables inheritance. Within a
/// requirement array the items are alternatives (OR): an empty requirement
/// object `{}` is the public alternative and makes the whole operation
/// public, so no blocker is produced for that operation.
///
/// A malformed security shape — a non-array `security` value or a non-object
/// array item — must never be discarded silently: the affected operation
/// receives one blocker with the exact source location. A supported non-empty
/// requirement remains a blocker until an administrator binds a compatible
/// Auth Profile.
pub(super) fn append_security_requirement_findings(parsed: &mut RestImportDocument, root: &Value) {
let operations = &parsed.operations;
let findings = &mut parsed.findings;
let locations = &mut parsed.internal_finding_locations;
let root_security = root.get("security");
for operation in operations {
let Some(path_item) = root
.pointer(&format!(
"/paths/{}",
normalize_coverage::escape_pointer(&operation.path)
))
.and_then(|item| item.get(method_as_lower(operation)))
else {
continue;
};
let Some(security) = path_item
.get("security")
.or_else(|| root_security.filter(|_| path_item.get("security").is_none()))
else {
continue;
};
let base_pointer = if path_item.get("security").is_some() {
format!(
"/paths/{}/{}/security",
normalize_coverage::escape_pointer(&operation.path),
method_as_lower(operation)
)
} else {
"/security".to_owned()
};
let alternatives = match security.as_array() {
Some(alternatives) => alternatives,
None => {
push_security_blocker(
findings,
locations,
operation,
&base_pointer,
"security имеет некорректный формат: ожидается массив требований; операции с незапакованным блоком безопасности не публикуются.",
);
continue;
}
};
// Validate the item shapes first: only a fully well-formed array may
// use the empty requirement object `{}` as its public OR alternative.
if !alternatives
.iter()
.all(|requirement| requirement.as_object().is_some())
{
for (index, requirement) in alternatives.iter().enumerate() {
let pointer = format!("{base_pointer}/{index}");
match requirement.as_object() {
Some(schemes) if schemes.is_empty() => {
// In a malformed array the empty alternative does
// not make the operation public, but it also cannot
// block on its own.
continue;
}
Some(_) => push_security_blocker(
findings,
locations,
operation,
&pointer,
"Требование безопасности должно быть привязано к настроенному Auth Profile перед публикацией этой операции; остальные операции не блокируются.",
),
None => push_security_blocker(
findings,
locations,
operation,
&pointer,
"security содержит альтернативу без объекта требований: формат не поддерживается, операция не публикуется.",
),
}
}
continue;
}
if alternatives.iter().any(|requirement| {
requirement
.as_object()
.is_some_and(serde_json::Map::is_empty)
}) {
continue;
}
for (index, _) in alternatives.iter().enumerate() {
push_security_blocker(
findings,
locations,
operation,
&format!("{base_pointer}/{index}"),
"Требование безопасности должно быть привязано к настроенному Auth Profile перед публикацией этой операции; остальные операции не блокируются.",
);
}
}
}
fn push_security_blocker(
findings: &mut Vec<ImportFinding>,
locations: &mut Vec<Option<SourceLocation>>,
operation: &RestImportOperation,
pointer: &str,
message: &str,
) {
findings.push(ImportFinding {
code: "unsupported_security_requirement".to_owned(),
severity: ImportFindingSeverity::Error,
message: message.to_owned(),
operation_key: Some(operation.key.clone()),
});
locations.push(Some(SourceLocation {
pointer: pointer.to_owned(),
}));
}
fn method_as_lower(operation: &RestImportOperation) -> String {
format!("{:?}", operation.method).to_ascii_lowercase()
}
@@ -0,0 +1,29 @@
{
"actionable_count": 50,
"content_digest": "296bb06a311615952c4688089515f514d417bf75b05645fb82ffaa41b92c73ad",
"content_digest_algorithm": "sha256",
"content_digest_definition": "SHA-256 of compact key-sorted JSON before the content_digest field is added.",
"corpus_version": "1.0.3",
"denominator": 50,
"evidence_identity": "be17fbf86429a8953acba4f3e8114d47c088305c0b1720678c4ffea8476f4f24",
"evidence_version": "1.0.0",
"exclusions": [],
"manifest_digest": "2abf220447fc73547583eab65370b84d1f3353a203909e16216d48b055919b47",
"matrix_contract": {
"construct_rows": 384,
"semantic_probes": "AC-1 runs a generated normalizer probe for every matrix row, including every 2xx status in all three formats."
},
"matrix_digest": "29f1e93850b057bb374895d60a8b2dacc8d01371b53d579f558c9dd2b85aa209",
"matrix_version": "1.0.2",
"method": "real normalize_verified_document + preview_from_ir; every NormalizedIr passed validate_normalized_ir",
"raw_counts": {
"covered_source_constructs": 1837,
"documents": 63,
"findings": 0,
"representative_operations": 50,
"semantic_coverage_entries": 514,
"source_constructs": 1837
},
"silent_loss_count": 0,
"uncovered_source_constructs": []
}
+973
View File
@@ -0,0 +1,973 @@
//! Offline regression gates for the versioned OpenAPI support matrix and corpus.
use crank_import::rest::model::CoverageDisposition;
use crank_import::rest::model::{CanonicalSourceNode, CanonicalSourceValue};
use crank_import::rest::{
ImportParseError, NormalizationConfig, SourceDigest, normalize_verified_document,
preview_from_ir, validate_normalized_ir,
};
use serde::Deserialize;
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use std::{
fs,
path::{Path, PathBuf},
};
#[path = "corpus/matrix.rs"]
mod matrix;
fn tests_root() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join("tests")
}
fn hex(bytes: impl AsRef<[u8]>) -> String {
Sha256::digest(bytes)
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
fn canonical_json(value: &Value) -> Vec<u8> {
serde_json::to_vec(value).expect("JSON values serialize")
}
fn escape_pointer(value: &str) -> String {
value.replace('~', "~0").replace('/', "~1")
}
fn source_ledger(
value: &Value,
pointer: &str,
ledger: &mut std::collections::BTreeMap<String, Value>,
) {
assert!(ledger.insert(pointer.to_owned(), value.clone()).is_none());
match value {
Value::Array(items) => {
for (index, item) in items.iter().enumerate() {
source_ledger(item, &format!("{pointer}/{index}"), ledger);
}
}
Value::Object(fields) => {
for (key, item) in fields {
source_ledger(item, &format!("{pointer}/{}", escape_pointer(key)), ledger);
}
}
_ => {}
}
}
fn canonical_source_ledger(
node: &CanonicalSourceNode,
ledger: &mut std::collections::BTreeMap<String, Value>,
) -> Value {
let value = match &node.value {
CanonicalSourceValue::Null => Value::Null,
CanonicalSourceValue::Boolean(value) => json!(value),
CanonicalSourceValue::Number(value) => {
serde_json::from_str(value).expect("canonical number")
}
CanonicalSourceValue::String(value) => json!(value),
CanonicalSourceValue::Array(items) => Value::Array(
items
.iter()
.map(|item| canonical_source_ledger(item, ledger))
.collect(),
),
CanonicalSourceValue::Object(items) => {
let mut fields = serde_json::Map::new();
for (key, item) in items {
fields.insert(key.clone(), canonical_source_ledger(item, ledger));
}
Value::Object(fields)
}
};
assert!(
ledger
.insert(node.location.pointer.clone(), value.clone())
.is_none()
);
value
}
#[derive(Debug, Deserialize)]
struct Manifest {
corpus_version: String,
matrix_version: String,
compatibility_impact: String,
documents: Vec<Document>,
}
#[derive(Debug, Deserialize)]
struct Document {
id: String,
file: String,
sha256: String,
canonical_digest: Option<String>,
origin: String,
license: String,
specification_version: String,
classification: String,
expected_preview: Value,
}
fn manifest() -> Manifest {
serde_json::from_slice(
&fs::read(tests_root().join("corpus/manifest.json")).expect("manifest exists"),
)
.expect("manifest JSON is valid")
}
fn normalize(source: &str) -> Result<crank_import::rest::NormalizedIr, ImportParseError> {
let source_digest = SourceDigest::parse(hex(source.as_bytes())).expect("sha256 is valid");
normalize_verified_document(source, source_digest, &NormalizationConfig::default())
}
#[test]
fn ac_2_manifest_covers_fifty_provenanced_specs_with_exact_expectations() {
let manifest = manifest();
assert_eq!(manifest.corpus_version, "1.0.3");
assert_eq!(manifest.matrix_version, "1.0.2");
assert!(!manifest.compatibility_impact.trim().is_empty());
assert!(manifest.documents.len() >= 50);
let root = tests_root().join("corpus");
let mut versions = std::collections::BTreeSet::new();
let mut representative_count = 0;
for document in &manifest.documents {
assert!(!document.id.is_empty());
assert!(
document.origin.starts_with("synthetic:"),
"{} lacks provenance",
document.id
);
assert!(
document.license.contains("CC0"),
"{} lacks license",
document.id
);
assert_eq!(document.sha256.len(), 64);
versions.insert(document.specification_version.as_str());
let source = fs::read(root.join(&document.file))
.unwrap_or_else(|e| panic!("{}: {e}", document.file));
assert_eq!(
hex(&source),
document.sha256,
"checksum mismatch for {}",
document.file
);
if let Ok(value) = serde_json::from_slice::<Value>(&source) {
let digest = hex(canonical_json(&value));
assert_eq!(
document.canonical_digest.as_deref(),
Some(digest.as_str()),
"canonical digest mismatch for {}",
document.file
);
} else {
assert!(
document.canonical_digest.is_none(),
"malformed JSON has no canonical digest"
);
}
if document.classification == "representative" {
representative_count += 1;
let text = std::str::from_utf8(&source).expect("fixtures are UTF-8");
let ir =
normalize(text).unwrap_or_else(|e| panic!("{} failed parser: {e}", document.file));
validate_normalized_ir(&ir).expect("normalized IR has explicit source coverage");
let preview = preview_from_ir(&ir);
let repeated_preview =
preview_from_ir(&normalize(text).expect("repeat normalization succeeds"));
assert_eq!(
serde_json::to_value(&preview).unwrap(),
serde_json::to_value(&repeated_preview).unwrap(),
"deterministic preview diff for {}:\nexpected={}\nactual={}",
document.file,
serde_json::to_string_pretty(&preview).unwrap(),
serde_json::to_string_pretty(&repeated_preview).unwrap(),
);
let candidates = preview
.groups
.iter()
.flat_map(|g| &g.operations)
.collect::<Vec<_>>();
assert_eq!(
candidates.len(),
document.expected_preview["operation_count"]
.as_u64()
.unwrap() as usize,
"operation count in {}",
document.file
);
assert_eq!(
candidates.len(),
1,
"corpus fixtures are single-operation exact oracles"
);
let expected = &document.expected_preview["operations"][0];
let actual_candidate = serde_json::to_value(candidates[0]).unwrap();
assert_eq!(
actual_candidate,
expected["candidate"],
"frozen candidate diff for {}:\nexpected={}\nactual={}",
document.file,
serde_json::to_string_pretty(&expected["candidate"]).unwrap(),
serde_json::to_string_pretty(&actual_candidate).unwrap(),
);
let blocking_codes = candidates[0]
.findings
.iter()
.filter(|finding| {
finding.severity == crank_import::rest::ImportFindingSeverity::Error
})
.map(|finding| finding.code.clone())
.collect::<Vec<_>>();
assert_eq!(json!(blocking_codes), expected["blocker_codes"]);
assert_eq!(
blocking_codes.is_empty(),
expected["actionable"].as_bool().unwrap()
);
assert_eq!(
hex(canonical_json(&actual_candidate)),
expected["candidate_digest"],
"candidate canonical digest in {}",
document.file
);
assert_eq!(
hex(canonical_json(&serde_json::to_value(&preview).unwrap())),
document.expected_preview["canonical_preview_digest"],
"preview canonical digest in {}",
document.file
);
let actual_preview = serde_json::to_value(&preview).unwrap();
assert_eq!(
actual_preview,
document.expected_preview["canonical_preview"],
"frozen readable preview diff for {}:\nexpected={}\nactual={}",
document.file,
serde_json::to_string_pretty(&document.expected_preview["canonical_preview"])
.unwrap(),
serde_json::to_string_pretty(&actual_preview).unwrap(),
);
assert_eq!(
serde_json::to_value(candidates[0].method).unwrap().as_str(),
expected["method"].as_str()
);
assert_eq!(candidates[0].path, expected["path"].as_str().unwrap());
assert_eq!(
candidates[0].operation_id.as_deref(),
expected["operation_id"].as_str()
);
assert!(
preview.findings.is_empty(),
"unexpected preview findings in {}: {:?}",
document.file,
preview.findings
);
let mut actual_findings = candidates[0]
.findings
.iter()
.map(|f| f.code.as_str())
.collect::<Vec<_>>();
let mut expected_findings = document.expected_preview["finding_codes"]
.as_array()
.unwrap()
.iter()
.map(|v| v.as_str().unwrap())
.collect::<Vec<_>>();
actual_findings.sort_unstable();
expected_findings.sort_unstable();
assert_eq!(
actual_findings, expected_findings,
"finding codes in {}",
document.file
);
} else {
assert_eq!(document.classification, "hostile");
let text = std::str::from_utf8(&source).unwrap();
let parsed = normalize(text);
assert_eq!(
parsed,
normalize(text),
"hostile parser result changed on deterministic rerun for {}",
document.file
);
if [
"hostile-empty.json",
"hostile-malformed.json",
"hostile-oversized.json",
"hostile-deep.json",
"hostile-aliases.yaml",
]
.contains(&document.file.as_str())
{
if [
"hostile-oversized.json",
"hostile-deep.json",
"hostile-aliases.yaml",
]
.contains(&document.file.as_str())
{
assert!(
matches!(parsed, Err(ImportParseError::LimitExceeded)),
"{} must fail within configured bounds: {parsed:?}",
document.file
);
} else {
assert!(parsed.is_err(), "{} must be rejected", document.file);
}
} else if document.file == "hostile-trace.json" {
let ir = parsed.expect("TRACE is reported instead of silently discarded");
assert!(
ir.findings
.iter()
.any(|f| f.code == "unsupported_http_method")
);
assert!(ir.coverage.iter().any(|c| c.construct_id.contains("trace")
&& c.disposition == CoverageDisposition::Finding));
} else if document.file == "hostile-xml.json" {
let ir = parsed.expect("XML is represented by an explicit finding");
let preview = preview_from_ir(&ir);
let codes = preview
.groups
.iter()
.flat_map(|g| &g.operations)
.flat_map(|o| &o.findings)
.map(|f| f.code.as_str())
.collect::<Vec<_>>();
assert!(
codes
.iter()
.any(|code| code.contains("xml") || code.contains("media")),
"XML findings: {codes:?}"
);
} else if document.file == "hostile-secret.json" {
let ir = parsed.expect("secret-like examples remain inspectable");
let evidence = serde_json::to_string(&preview_from_ir(&ir)).unwrap();
assert!(
!evidence.contains("sk_test_corpus_secret_canary"),
"secret canary leaked into preview evidence"
);
} else {
let ir = parsed.unwrap_or_else(|error| {
panic!(
"{} must have an explicit finding or bounded rejection: {error}",
document.file
)
});
validate_normalized_ir(&ir).expect("hostile construct coverage remains explicit");
assert!(
!ir.coverage.is_empty(),
"{} has no construct ledger",
document.file
);
let preview = preview_from_ir(&ir);
match document.file.as_str() {
"hostile-cycle.json" => {
assert_eq!(
ir.operations.len(),
1,
"recursive schema must not drop the source operation"
);
assert!(
ir.findings
.iter()
.chain(ir.operations.iter().flat_map(|op| &op.findings))
.all(|finding| {
finding.severity
!= crank_import::rest::ImportFindingSeverity::Error
}),
"bounded cycle policy must not yield an unexplained blocker: {:?} {:?}",
ir.findings,
ir.operations.iter().map(|op| &op.findings)
);
assert!(
ir.unresolved_references.is_empty(),
"resolved recursion must not be reported as unresolvable: {:?}",
ir.unresolved_references
);
let cycle_edge = |recursive: bool| {
ir.reference_graph.edges.iter().any(|edge| {
edge.recursive == recursive
&& edge.source.location.pointer
== "/components/schemas/Node/properties/next/$ref"
&& edge.target.location.pointer == "/components/schemas/Node"
})
};
assert!(
cycle_edge(false) && cycle_edge(true),
"Node.next must resolve through both bounded and recursive edges: {:?}",
ir.reference_graph.edges
);
let response = ir.operations[0]
.response_variants
.iter()
.find(|variant| variant.status_code == 200)
.expect("200 response is retained");
assert!(
matches!(
&response.schema,
Some(schema) if matches!(
&schema.kind,
crank_import::rest::NormalizedSchemaKind::Object {
properties, ..
} if properties.contains_key("next")
)
),
"recursive node schema must be projected: {:?}",
response.schema
);
assert!(
ir.coverage.iter().any(|entry| {
entry.location.pointer
== "/components/schemas/Node/properties/next/properties/next"
&& entry.disposition == CoverageDisposition::Mapped
}),
"bounded recursion must remain Mapped in the resolved source ledger: {:?}",
ir.coverage
);
assert_eq!(
document.expected_preview["mapped_recursive_pointer"].as_str(),
Some("/components/schemas/Node/properties/next/properties/next")
);
assert_eq!(
ir.findings
.iter()
.map(|f| (f.code.clone(), f.severity.clone()))
.collect::<Vec<_>>(),
vec![(
"missing_servers".to_owned(),
crank_import::rest::ImportFindingSeverity::Warning
)],
"cycle fixture must expose only the exact bounded warning set: {:?}",
ir.findings
);
assert_eq!(
document.expected_preview["operation_count"].as_u64(),
Some(1)
);
assert_eq!(
document.expected_preview["recursive_edge"]["source"].as_str(),
Some("/components/schemas/Node/properties/next/$ref")
);
assert_eq!(
document.expected_preview["recursive_edge"]["target"].as_str(),
Some("/components/schemas/Node")
);
assert_eq!(document.expected_preview["blocker_findings"], json!([]));
assert_eq!(
document.expected_preview["unresolved_references"],
json!([])
);
assert_eq!(
document.expected_preview["warning_findings"],
json!([{"code":"missing_servers","severity":"Warning","operation_key":null}])
);
}
"hostile-external-ref.json" => assert!(
ir.findings.iter()
.chain(ir.operations.iter().flat_map(|op| &op.findings))
.any(|finding| finding.code == "external_reference_disabled"
&& finding.location.pointer == "/paths/~1hostile/get/responses/200/content/application~1json/schema/$ref"),
"external ref must be denied at its source: {:?}",
ir.findings
),
"hostile-duplicate-ids.json" => assert_eq!(
ir.operations.len(),
2,
"duplicate IDs must not drop a source operation"
),
"hostile-composition-conflict.json" => {
assert_eq!(
ir.operations.len(),
1,
"conflicting allOf must keep the source operation explicit"
);
let conflict = ir.operations[0]
.findings
.iter()
.find(|finding| finding.code == "all_of_conflict")
.unwrap_or_else(|| {
panic!(
"allOf conflict must be named: {:?}",
ir.operations[0].findings
)
});
assert_eq!(
conflict.severity,
crank_import::rest::ImportFindingSeverity::Error,
"allOf conflict must block the candidate: {:?}",
conflict
);
assert_eq!(
conflict.operation_key.as_deref(),
Some("GET /hostile"),
"conflict must belong to the affected candidate: {:?}",
conflict
);
assert_eq!(
conflict.location.pointer,
"/paths/~1hostile/get/responses/200/content/application~1json/schema/allOf",
"conflict must point at the conflicting allOf: {:?}",
conflict
);
assert!(
ir.coverage
.iter()
.any(|entry| {
entry.location
.pointer
== "/paths/~1hostile/get/responses/200/content/application~1json/schema/allOf"
})
&& ir
.operations[0]
.findings
.iter()
.any(|finding| finding.code == "all_of_conflict"
&& finding.location.pointer
== "/paths/~1hostile/get/responses/200/content/application~1json/schema/allOf"),
"conflicting allOf must stay in the source ledger bound to the explicit finding: {:?}",
ir.coverage
);
let response = ir.operations[0]
.response_variants
.iter()
.find(|variant| variant.status_code == 200)
.expect("200 response is retained");
assert!(
matches!(
&response.schema,
Some(schema) if matches!(
&schema.kind,
crank_import::rest::NormalizedSchemaKind::Composition {
operator, variants
} if operator == "allOf" && variants.len() == 2
)
),
"conflict branches must be preserved verbatim: {:?}",
response.schema
);
assert_eq!(
ir.findings
.iter()
.map(|f| (f.code.clone(), f.severity.clone()))
.collect::<Vec<_>>(),
vec![(
"missing_servers".to_owned(),
crank_import::rest::ImportFindingSeverity::Warning
)],
"composition conflict fixture must keep the exact warning set: {:?}",
ir.findings
);
assert_eq!(
document.expected_preview["operation_count"].as_u64(),
Some(1)
);
assert_eq!(
document.expected_preview["blocker_findings"],
json!([{"code":"all_of_conflict","severity":"Error",
"operation_key":"GET /hostile",
"location":"/paths/~1hostile/get/responses/200/content/application~1json/schema/allOf"}])
);
assert_eq!(
document.expected_preview["composition"],
json!({"operator":"allOf","branch_count":2})
);
assert_eq!(
document.expected_preview["warning_findings"],
json!([{"code":"missing_servers","severity":"Warning","operation_key":null}])
);
}
"hostile-security-scope.json" => {
assert_eq!(
ir.operations.len(),
2,
"security-scope fixture must keep both candidates explicit: {:?}",
ir.operations.iter().map(|op| &op.key).collect::<Vec<_>>()
);
let requirements = ir
.findings
.iter()
.filter(|finding| finding.code == "unsupported_security_requirement")
.collect::<Vec<_>>();
assert_eq!(
requirements.len(),
1,
"exactly the inherited requirement must produce a blocker: {:?}",
ir.findings
);
let requirement = &requirements[0];
assert_eq!(
requirement.severity,
crank_import::rest::ImportFindingSeverity::Error,
"security requirement must block its candidate: {:?}",
requirement
);
assert_eq!(
requirement.operation_key.as_deref(),
Some("GET /secure"),
"blocker must belong only to the inherited secured candidate: {:?}",
requirement
);
assert_eq!(
requirement.location.pointer, "/security/0",
"inherited requirement must point at the document root requirement: {:?}",
requirement
);
let mut by_key = std::collections::BTreeMap::new();
for group in &preview.groups {
for candidate in &group.operations {
by_key.insert(candidate.key.clone(), candidate);
}
}
let public = by_key.get("GET /public").expect("public candidate present");
assert!(
public.findings.iter().all(|finding| finding.severity
!= crank_import::rest::ImportFindingSeverity::Error),
"public operation with security: [] must stay actionable: {:?}",
public.findings
);
assert!(
by_key
.get("GET /secure")
.expect("secured candidate present")
.findings
.iter()
.any(|finding| finding.code == "unsupported_security_requirement"
&& finding.severity
== crank_import::rest::ImportFindingSeverity::Error),
"inherited requirement must block the secured candidate: {:?}",
by_key.get("GET /secure").unwrap().findings
);
assert!(
preview
.findings
.iter()
.all(|finding| finding.operation_key.is_some()),
"no document-global blocker may be produced: {:?}",
preview.findings
);
assert!(
ir.coverage
.iter()
.any(|entry| entry.location.pointer == "/security/0"
&& entry.disposition == CoverageDisposition::Finding),
"inherited requirement must stay in the source ledger bound to the finding: {:?}",
ir.coverage
);
let mut actual_operation_keys = preview
.groups
.iter()
.flat_map(|group| &group.operations)
.map(|op| op.key.clone())
.collect::<Vec<_>>();
actual_operation_keys.sort();
assert_eq!(
json!(actual_operation_keys),
document.expected_preview["operation_keys"],
"security-scope operation oracle for {}",
document.file
);
let actual_blockers = requirements
.iter()
.map(|finding| {
json!({"code": finding.code.clone(), "severity": "Error",
"operation_key": finding.operation_key.clone(),
"location": finding.location.pointer.clone()})
})
.collect::<Vec<_>>();
assert_eq!(
actual_blockers,
document.expected_preview["blocker_findings"]
.as_array()
.unwrap()
.clone(),
"security-scope blocker oracle for {}: actual {actual_blockers:?}",
document.file
);
let actual_warnings = ir
.findings
.iter()
.filter(|finding| {
finding.severity
== crank_import::rest::ImportFindingSeverity::Warning
})
.map(|finding| {
json!({"code": finding.code.clone(), "severity": "Warning",
"operation_key": finding.operation_key.clone()})
})
.collect::<Vec<_>>();
assert_eq!(
actual_warnings,
document.expected_preview["warning_findings"]
.as_array()
.unwrap()
.clone(),
"security-scope warning oracle for {}: actual {actual_warnings:?}",
document.file
);
}
_ => unreachable!("hostile fixture must have a dedicated expectation"),
}
}
}
}
// Exact file set: manifest rows are unique and every corpus data file is
// accounted exactly once, so duplicates or orphan fixtures cannot inflate
// or hide coverage.
let mut ids = std::collections::BTreeSet::new();
let mut files = std::collections::BTreeSet::new();
for document in &manifest.documents {
assert!(
ids.insert(document.id.clone()),
"duplicate manifest document id {}",
document.id
);
assert!(
files.insert(document.file.clone()),
"duplicate manifest file {}",
document.file
);
}
let expected_files = files
.into_iter()
.chain(std::iter::once("manifest.json".to_owned()))
.chain(std::iter::once("matrix.rs".to_owned()))
.collect::<std::collections::BTreeSet<_>>();
let actual_files = fs::read_dir(&root)
.expect("corpus directory exists")
.map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
.collect::<std::collections::BTreeSet<_>>();
assert_eq!(
actual_files, expected_files,
"corpus directory must equal the manifest file set exactly"
);
assert_eq!(representative_count, 50);
assert!(
versions
.iter()
.any(|version| version.starts_with("OpenAPI 3.0"))
&& versions
.iter()
.any(|version| version.starts_with("OpenAPI 3.1"))
&& versions.contains("Swagger 2.0")
);
}
#[test]
fn ac_3_evidence_reports_actionable_denominator_exclusions_and_zero_silent_loss() {
let manifest = manifest();
let mut denominator = 0_u64;
let mut actionable_count = 0_u64;
let mut operation_count = 0_u64;
let mut source_construct_count = 0_u64;
let mut covered_source_construct_count = 0_u64;
let mut semantic_coverage_count = 0_u64;
let mut silent_loss = Vec::new();
let mut exclusions = Vec::new();
let mut finding_count = 0_u64;
for document in &manifest.documents {
if document.classification != "representative" {
continue;
}
let source_bytes = fs::read(tests_root().join("corpus").join(&document.file)).unwrap();
let source: Value =
serde_json::from_slice(&source_bytes).expect("representative corpus source is JSON");
let mut raw_ledger = std::collections::BTreeMap::new();
source_ledger(&source, "", &mut raw_ledger);
let source_text = std::str::from_utf8(&source_bytes).unwrap();
let ir = normalize(source_text).unwrap();
validate_normalized_ir(&ir).unwrap();
let mut normalized_ledger = std::collections::BTreeMap::new();
let _ = canonical_source_ledger(&ir.source_tree, &mut normalized_ledger);
assert_eq!(
normalized_ledger, raw_ledger,
"normalizer source-tree ledger differs from raw document for {}",
document.file
);
source_construct_count += raw_ledger.len() as u64;
let coverage_by_id = ir
.coverage
.iter()
.map(|entry| (entry.construct_id.as_str(), entry))
.collect::<std::collections::BTreeMap<_, _>>();
for pointer in raw_ledger.keys() {
let source_id = format!("source:{pointer}");
match coverage_by_id.get(source_id.as_str()) {
Some(entry)
if entry.location.pointer == *pointer
&& entry.disposition == CoverageDisposition::Mapped =>
{
covered_source_construct_count += 1;
}
_ => silent_loss.push(json!({"document":document.id,"source_pointer":pointer,"coverage_id":source_id})),
}
}
let findings = ir
.findings
.iter()
.chain(
ir.operations
.iter()
.flat_map(|operation| &operation.findings),
)
.collect::<Vec<_>>();
for entry in ir
.coverage
.iter()
.filter(|entry| !entry.construct_id.starts_with("source:"))
{
semantic_coverage_count += 1;
assert!(
raw_ledger.contains_key(&entry.location.pointer),
"coverage {} points outside raw source tree for {}",
entry.construct_id,
document.file
);
match entry.disposition {
CoverageDisposition::Mapped => {}
CoverageDisposition::Finding => assert!(
findings
.iter()
.any(|finding| finding.construct_id == entry.construct_id
&& finding.location == entry.location),
"finding coverage {} has no matching finding in {}",
entry.construct_id,
document.file
),
}
}
for operation in &ir.operations {
denominator += 1;
operation_count += 1;
if operation
.findings
.iter()
.all(|f| f.severity != crank_import::rest::ImportFindingSeverity::Error)
{
actionable_count += 1;
} else {
exclusions.push(json!({"document":document.id,"operation":operation.key,"reason":"blocking_finding","findings":operation.findings.iter().map(|f| &f.code).collect::<Vec<_>>()}));
}
}
finding_count += ir.findings.len() as u64;
}
assert!(denominator > 0);
assert!(
actionable_count * 100 >= denominator * 95,
"actionable {actionable_count}/{denominator}; exclusions={exclusions:?}"
);
let silent_loss_count = silent_loss.len() as u64;
assert_eq!(
source_construct_count, covered_source_construct_count,
"independently enumerated raw source constructs lack coverage: {silent_loss:?}"
);
let mut reversed_counts = (0_u64, 0_u64, 0_u64);
for document in manifest
.documents
.iter()
.rev()
.filter(|document| document.classification == "representative")
{
let source = fs::read_to_string(tests_root().join("corpus").join(&document.file)).unwrap();
let ir = normalize(&source).unwrap();
reversed_counts.0 += ir.operations.len() as u64;
reversed_counts.1 += ir
.operations
.iter()
.filter(|operation| {
operation.findings.iter().all(|finding| {
finding.severity != crank_import::rest::ImportFindingSeverity::Error
})
})
.count() as u64;
reversed_counts.2 += ir.findings.len() as u64;
}
assert_eq!(
reversed_counts,
(operation_count, actionable_count, finding_count),
"aggregate evidence must not depend on manifest order"
);
let manifest_bytes = fs::read(tests_root().join("corpus/manifest.json")).unwrap();
let manifest_digest = hex(&manifest_bytes);
let matrix_bytes = fs::read(tests_root().join("support-matrix.yaml")).unwrap();
let matrix_digest = hex(&matrix_bytes);
let matrix_value: serde_yaml::Value = serde_yaml::from_slice(&matrix_bytes).unwrap();
let matrix_row_count = matrix_value["constructs"].as_sequence().unwrap().len();
let evidence_identity = hex(format!(
"{}\n{}\n{}\n{}",
manifest.corpus_version, manifest.matrix_version, manifest_digest, matrix_digest
));
let mut evidence = json!({
"evidence_version":"1.0.0", "corpus_version":manifest.corpus_version, "matrix_version":manifest.matrix_version,
"evidence_identity":evidence_identity,
"content_digest_algorithm":"sha256",
"content_digest_definition":"SHA-256 of compact key-sorted JSON before the content_digest field is added.",
"manifest_digest":manifest_digest,
"matrix_digest":matrix_digest,
"denominator":denominator, "actionable_count":actionable_count, "exclusions":exclusions,
"raw_counts":{"documents":manifest.documents.len(),"representative_operations":operation_count,"findings":finding_count,"source_constructs":source_construct_count,"covered_source_constructs":covered_source_construct_count,"semantic_coverage_entries":semantic_coverage_count},
"matrix_contract":{"construct_rows":matrix_row_count,"semantic_probes":"AC-1 runs a generated normalizer probe for every matrix row, including every 2xx status in all three formats."},
"uncovered_source_constructs":silent_loss,
"silent_loss_count":silent_loss_count,
"method":"real normalize_verified_document + preview_from_ir; every NormalizedIr passed validate_normalized_ir"
});
let content_digest = hex(canonical_json(&evidence));
evidence["content_digest"] = json!(content_digest);
let artifact = Path::new(env!("CARGO_MANIFEST_DIR")).join(format!(
"target/openapi-corpus/evidence-{evidence_identity}.json"
));
let target_dir = artifact.parent().unwrap();
fs::create_dir_all(target_dir).unwrap();
let bytes = serde_json::to_vec_pretty(&evidence).unwrap();
// Each process needs its own temp file: concurrent corpus runs must not
// truncate each other's pending evidence before atomic publication.
let mut nonce = 0u32;
let (publish, mut file) = loop {
let path = target_dir.join(format!(
"evidence.json.tmp-{}-{}-{nonce}",
&evidence_identity[..16],
std::process::id()
));
match fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(&path)
{
Ok(file) => break (path, file),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists && nonce < 1024 => {
nonce += 1;
}
Err(error) => panic!(
"cannot create evidence temp file {}: {error}",
path.display()
),
}
};
{
use std::io::Write;
file.write_all(&bytes).unwrap();
file.sync_all().unwrap();
}
// hard_link fails atomically when the final identity already exists.
// Rename would silently overwrite after an exists-check race, while
// create_new on the final path would expose partial bytes after a crash.
let published = match fs::hard_link(&publish, &artifact) {
Ok(()) => true,
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => false,
Err(error) => panic!(
"cannot publish immutable evidence artifact {}: {error}",
artifact.display()
),
};
fs::remove_file(&publish).ok();
if !published {
let existing = fs::read(&artifact).unwrap();
assert_eq!(
existing,
bytes,
"immutable evidence identity {evidence_identity} already has conflicting contents at {}",
artifact.display()
);
}
if let Ok(directory) = fs::File::open(target_dir) {
let _ = directory.sync_all();
}
let reread: Value = serde_json::from_slice(&fs::read(artifact).unwrap()).unwrap();
assert_eq!(reread, evidence);
assert_eq!(reread["silent_loss_count"], 0);
assert_eq!(source_construct_count, covered_source_construct_count);
assert_eq!(reread["denominator"], denominator);
assert_eq!(reread["actionable_count"], actionable_count);
}
@@ -0,0 +1,5 @@
openapi: 3.1.0
info: {title: Aliases, version: 1}
paths: {}
x-anchor: &anchor {type: string}
x-aliases: [*anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor, *anchor]
@@ -0,0 +1,43 @@
{
"openapi": "3.1.0",
"info": {
"title": "Hostile generated",
"version": "1"
},
"paths": {
"/hostile": {
"get": {
"operationId": "hostileOperation",
"responses": {
"200": {
"description": "ok",
"content": {
"application/json": {
"schema": {
"allOf": [
{
"type": "object",
"properties": {
"id": {
"type": "string"
}
}
},
{
"type": "object",
"properties": {
"id": {
"type": "integer"
}
}
}
]
}
}
}
}
}
}
}
}
}
@@ -0,0 +1,38 @@
{
"openapi": "3.1.0",
"info": {
"title": "Hostile generated",
"version": "1"
},
"paths": {
"/hostile": {
"get": {
"operationId": "hostileOperation",
"responses": {
"200": {
"description": "ok",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Node"
}
}
}
}
}
}
}
},
"components": {
"schemas": {
"Node": {
"type": "object",
"properties": {
"next": {
"$ref": "#/components/schemas/Node"
}
}
}
}
}
}
@@ -0,0 +1 @@
{"openapi":"3.1.0","info":{"title":"Hostile generated","version":"1"},"paths":{"/hostile":{"get":{"operationId":"hostileOperation","responses":{"200":{"description":"ok","content":{"application/json":{"schema":{"type":"object"}}}}}}}},"components":{"schemas":{"Deep":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"array","items":{"type":"string"}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
@@ -0,0 +1,36 @@
{
"openapi": "3.1.0",
"info": {
"title": "Hostile generated",
"version": "1"
},
"paths": {
"/hostile": {
"get": {
"operationId": "hostileOperation",
"responses": {
"200": {
"description": "ok",
"content": {
"application/json": {
"schema": {
"$ref": "https://external.example.test/schema.json"
}
}
}
}
}
}
},
"/other": {
"post": {
"operationId": "hostileOperation",
"responses": {
"200": {
"description": "ok"
}
}
}
}
}
}
@@ -0,0 +1 @@
{}
@@ -0,0 +1,26 @@
{
"openapi": "3.1.0",
"info": {
"title": "Hostile generated",
"version": "1"
},
"paths": {
"/hostile": {
"get": {
"operationId": "hostileOperation",
"responses": {
"200": {
"description": "ok",
"content": {
"application/json": {
"schema": {
"$ref": "https://external.example.test/schema.json"
}
}
}
}
}
}
}
}
}
@@ -0,0 +1 @@
{"openapi":
@@ -0,0 +1,12 @@
{
"openapi": "3.1.0",
"info": {"title": "Hostile generated", "version": "1"},
"paths": {"/hostile": {"get": {"operationId": "hostileOperation", "responses": {"200": {"description": "ok", "content": {"application/json": {"schema": {"type": "string"}}}}}}}},
"x-padding-0": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa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aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaLine truncated
}
@@ -0,0 +1,32 @@
{
"openapi": "3.1.0",
"info": {
"title": "Secret hostile",
"version": "1"
},
"paths": {
"/secret": {
"get": {
"operationId": "secretOperation",
"responses": {
"200": {
"description": "ok",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
},
"x-example": "sk_test_corpus_secret_canary"
}
}
},
"servers": [
{
"url": "https://api.example.test"
}
]
}
@@ -0,0 +1,48 @@
{
"openapi": "3.0.3",
"info": {
"title": "Hostile security scope",
"version": "1"
},
"servers": [
{
"url": "https://corpus.example.test"
}
],
"security": [
{
"corpusProbe": []
}
],
"components": {
"securitySchemes": {
"corpusProbe": {
"type": "http",
"scheme": "basic"
}
}
},
"paths": {
"/public": {
"get": {
"operationId": "publicProbe",
"security": [],
"responses": {
"200": {
"description": "ok"
}
}
}
},
"/secure": {
"get": {
"operationId": "secureProbe",
"responses": {
"200": {
"description": "ok"
}
}
}
}
}
}
@@ -0,0 +1,18 @@
{
"openapi": "3.1.0",
"info": {
"title": "TRACE hostile",
"version": "1"
},
"paths": {
"/trace": {
"trace": {
"responses": {
"200": {
"description": "unsupported"
}
}
}
}
}
}
@@ -0,0 +1,31 @@
{
"openapi": "3.1.0",
"info": {
"title": "XML hostile",
"version": "1"
},
"paths": {
"/xml": {
"get": {
"operationId": "xmlOperation",
"responses": {
"200": {
"description": "ok",
"content": {
"application/xml": {
"schema": {
"type": "string"
}
}
}
}
}
}
}
},
"servers": [
{
"url": "https://api.example.test"
}
]
}
File diff suppressed because it is too large. Load diff
+822
View File
@@ -0,0 +1,822 @@
//! Executable normalizer probes for every normative support-matrix row.
use super::*;
use crank_import::rest::{NormalizedSchemaKind, normalize_verified_bundle};
fn assert_actionable(ir: &crank_import::rest::NormalizedIr, context: &str) {
let preview = preview_from_ir(ir);
assert!(
!preview.findings.iter().any(|finding| {
finding.severity == crank_import::rest::ImportFindingSeverity::Error
}),
"{context} has a document blocker: {:?}",
preview.findings
);
assert!(
preview
.groups
.iter()
.flat_map(|group| &group.operations)
.all(|candidate| {
!candidate.findings.iter().any(|finding| {
finding.severity == crank_import::rest::ImportFindingSeverity::Error
})
}),
"{context} unexpectedly blocked: {:?}",
preview.groups
);
}
#[test]
fn ac_1_support_matrix_rows_have_exact_construct_contracts() {
let matrix_text = fs::read_to_string(tests_root().join("support-matrix.yaml"))
.expect("support matrix exists");
let matrix: serde_yaml::Value = serde_yaml::from_str(&matrix_text).expect("valid YAML");
assert_eq!(matrix["matrix_version"].as_str(), Some("1.0.2"));
assert!(
matrix["compatibility_impact"]
.as_str()
.is_some_and(|s| !s.trim().is_empty())
);
let rows = matrix["constructs"].as_sequence().expect("construct rows");
assert!(rows.len() >= 375);
let mut construct_keys = std::collections::BTreeSet::new();
for row in rows {
assert!(
row["specification_version"].as_str().is_some_and(|s| [
"OpenAPI 3.0",
"OpenAPI 3.1",
"Swagger 2.0"
]
.contains(&s))
);
assert!(row["construct_id"].as_str().is_some_and(|s| !s.is_empty()));
assert!(matches!(
row["status"].as_str(),
Some("supported" | "unsupported")
));
assert!(
row["preserved_semantics"]
.as_str()
.is_some_and(|s| !s.trim().is_empty())
);
assert!(
row["expected_finding"]
.as_str()
.is_some_and(|s| !s.trim().is_empty())
);
let key = format!(
"{}:{}",
row["specification_version"].as_str().unwrap(),
row["construct_id"].as_str().unwrap()
);
assert!(
construct_keys.insert(key.clone()),
"duplicate normative construct row: {key}"
);
if row["status"] == "supported" {
assert_eq!(
row["expected_finding"], "none",
"supported construct has a finding: {key}"
);
} else {
assert_ne!(
row["expected_finding"], "none",
"unsupported construct has no finding: {key}"
);
}
}
for version in ["OpenAPI 3.0", "OpenAPI 3.1", "Swagger 2.0"] {
// Exhaustive accounting: every normative row of this format must be
// matched by an executed probe before the loop completes.
let mut unprobed = rows
.iter()
.filter(|row| row["specification_version"] == version)
.map(|row| {
(
version.to_owned(),
row["construct_id"].as_str().unwrap().to_owned(),
)
})
.collect::<std::collections::BTreeSet<_>>();
let mut probed = |construct: &str| {
let taken = unprobed.remove(&(version.to_owned(), construct.to_owned()));
assert!(taken, "{version} double-probes or misses {construct}");
};
let ids = rows
.iter()
.filter(|r| r["specification_version"] == version)
.filter_map(|r| r["construct_id"].as_str())
.collect::<Vec<_>>();
for id in [
"http.method.get",
"http.method.post",
"http.method.put",
"http.method.patch",
"http.method.delete",
"http.method.head",
"http.method.options",
"parameter.location.path",
"parameter.location.query",
"parameter.location.header",
"parameter.location.cookie",
"request_body.application/json",
"request_body.application/x-www-form-urlencoded",
"request_body.multipart/form-data",
"reference.local",
"reference.external_allowlisted",
"composition.allOf",
"composition.oneOf",
"composition.anyOf",
"security.bearer",
"security.basic",
"security.api_key",
"media_type.application_xml.request",
"media_type.application_xml.response",
"http.method.trace",
"http.method.connect",
] {
assert!(ids.contains(&id), "{version} matrix misses {id}");
}
for security_kind in ["bearer", "basic", "api_key"] {
let construct = format!("security.{security_kind}");
let row = rows
.iter()
.find(|row| {
row["specification_version"] == version && row["construct_id"] == construct
})
.unwrap();
let probe = if version == "Swagger 2.0" {
json!({
"swagger":"2.0", "info":{"title":"Security probe","version":"1"},
"securityDefinitions":{"probe": if security_kind == "bearer" {
json!({"type":"oauth2","flow":"implicit","authorizationUrl":"https://auth.example.test","scopes":{}})
} else if security_kind == "api_key" {
json!({"type":"apiKey","name":"X-Key","in":"header"})
} else {
json!({"type":"basic"})
}},
"paths":{"/probe":{"get":{"security":[{"probe":[]}],"operationId":"securityProbe","responses":{"200":{"description":"ok"}}}}}
})
} else {
let scheme = match security_kind {
"bearer" => json!({"type":"http","scheme":"bearer"}),
"basic" => json!({"type":"http","scheme":"basic"}),
"api_key" => json!({"type":"apiKey","name":"X-Key","in":"header"}),
_ => unreachable!(),
};
json!({
"openapi": if version == "OpenAPI 3.0" {"3.0.3"} else {"3.1.0"},
"info":{"title":"Security probe","version":"1"},
"servers":[{"url":"https://matrix.example.test"}],
"components":{"securitySchemes":{"probe":scheme}},
"paths":{"/probe":{"get":{"security":[{"probe":[]}],"operationId":"securityProbe","responses":{"200":{"description":"ok"}}}}}
})
};
assert_eq!(
row["status"], "unsupported",
"security is not yet persisted as Auth Profile semantics"
);
let source = serde_json::to_string(&probe).unwrap();
let ir = normalize(&source).unwrap();
validate_normalized_ir(&ir).unwrap();
let expected_finding = row["expected_finding"].as_str().unwrap();
let requirement = ir
.findings
.iter()
.find(|finding| {
finding.code == expected_finding
&& finding.severity == crank_import::rest::ImportFindingSeverity::Error
})
.unwrap_or_else(|| {
panic!(
"{version} {construct} must be explicitly blocked: {:?}",
ir.findings
)
});
assert_eq!(
requirement.operation_key.as_deref(),
Some("GET /probe"),
"{version} {construct} blocker must belong to the affected candidate"
);
assert_eq!(
requirement.location.pointer, "/paths/~1probe/get/security/0",
"{version} {construct} blocker must point at the local requirement"
);
let preview = preview_from_ir(&ir);
let candidate = &preview.groups[0].operations[0];
assert!(
candidate
.findings
.iter()
.any(|finding| finding.code == expected_finding
&& finding.severity == crank_import::rest::ImportFindingSeverity::Error),
"{version} {construct} candidate must be blocked: {:?}",
candidate.findings
);
assert!(
ir.coverage.iter().any(|entry| entry.location.pointer
== "/paths/~1probe/get/security/0"
&& entry.disposition == CoverageDisposition::Finding),
"{version} {construct} has no finding coverage"
);
probed(&construct);
}
{
let construct = "security.override_empty";
let override_probe = |path: &str| {
if version == "Swagger 2.0" {
json!({
"swagger":"2.0", "info":{"title":"Security override probe","version":"1"},
"securityDefinitions":{"probe":{"type":"basic"}},
"security":[{"probe":[]}],
"paths":{path:{"get":{"security":[],"operationId":"securityOverride","responses":{"200":{"description":"ok"}}}}}
})
} else {
json!({
"openapi": if version == "OpenAPI 3.0" {"3.0.3"} else {"3.1.0"},
"info":{"title":"Security override probe","version":"1"},
"servers":[{"url":"https://matrix.example.test"}],
"components":{"securitySchemes":{"probe":{"type":"http","scheme":"basic"}}},
"security":[{"probe":[]}],
"paths":{path:{"get":{"security":[],"operationId":"securityOverride","responses":{"200":{"description":"ok"}}}}}
})
}
};
let source = serde_json::to_string(&override_probe("/override")).unwrap();
let ir = normalize(&source).unwrap();
validate_normalized_ir(&ir).unwrap();
assert!(
ir.findings
.iter()
.all(|finding| finding.code != "unsupported_security_requirement"),
"explicit empty security override must disable inheritance: {:?}",
ir.findings
);
let preview = preview_from_ir(&ir);
let candidate = &preview.groups[0].operations[0];
assert!(
candidate
.findings
.iter()
.all(|finding| finding.severity
!= crank_import::rest::ImportFindingSeverity::Error),
"overridden operation must remain actionable: {:?}",
candidate.findings
);
probed(construct);
}
{
let construct = "security.mixed_operations";
let mixed_probe = if version == "Swagger 2.0" {
json!({
"swagger":"2.0", "info":{"title":"Mixed security probe","version":"1"},
"securityDefinitions":{"probe":{"type":"basic"}},
"security":[{"probe":[]}],
"paths":{
"/public":{"get":{"security":[],"operationId":"publicProbe","responses":{"200":{"description":"ok"}}}},
"/secured":{"get":{"operationId":"securedProbe","responses":{"200":{"description":"ok"}}}}
}
})
} else {
json!({
"openapi": if version == "OpenAPI 3.0" {"3.0.3"} else {"3.1.0"},
"info":{"title":"Mixed security probe","version":"1"},
"servers":[{"url":"https://matrix.example.test"}],
"components":{"securitySchemes":{"probe":{"type":"http","scheme":"basic"}}},
"security":[{"probe":[]}],
"paths":{
"/public":{"get":{"security":[],"operationId":"publicProbe","responses":{"200":{"description":"ok"}}}},
"/secured":{"get":{"operationId":"securedProbe","responses":{"200":{"description":"ok"}}}}
}
})
};
let source = serde_json::to_string(&mixed_probe).unwrap();
let ir = normalize(&source).unwrap();
validate_normalized_ir(&ir).unwrap();
let expected_finding = rows
.iter()
.find(|row| {
row["specification_version"] == version && row["construct_id"] == construct
})
.unwrap()["expected_finding"]
.as_str()
.unwrap();
let requirements = ir
.findings
.iter()
.filter(|finding| finding.code == expected_finding)
.collect::<Vec<_>>();
assert_eq!(
requirements.len(),
1,
"exactly the inherited operation must be blocked: {:?}",
requirements
);
assert_eq!(
requirements[0].operation_key.as_deref(),
Some("GET /secured"),
"blocker must belong only to the affected candidate"
);
assert_eq!(requirements[0].location.pointer, "/security/0");
let preview = preview_from_ir(&ir);
let mut by_key = std::collections::BTreeMap::new();
for group in &preview.groups {
for candidate in &group.operations {
by_key.insert(candidate.key.clone(), candidate);
}
}
let public = by_key.get("GET /public").expect("public candidate present");
assert!(
public
.findings
.iter()
.all(|finding| finding.severity
!= crank_import::rest::ImportFindingSeverity::Error),
"public operation must stay actionable: {:?}",
public.findings
);
let secured = by_key
.get("GET /secured")
.expect("secured candidate present");
assert!(
secured
.findings
.iter()
.any(|finding| finding.code == expected_finding
&& finding.severity == crank_import::rest::ImportFindingSeverity::Error),
"secured operation must be blocked: {:?}",
secured.findings
);
assert!(
ir.coverage
.iter()
.any(|entry| entry.location.pointer == "/security/0"
&& entry.disposition == CoverageDisposition::Finding),
"mixed probe has no finding coverage"
);
probed(construct);
}
for method in [
"get", "post", "put", "patch", "delete", "head", "options", "trace", "connect",
] {
let construct = format!("http.method.{method}");
let row = rows
.iter()
.find(|row| {
row["specification_version"] == version && row["construct_id"] == construct
})
.unwrap();
let mut path_item = serde_json::Map::new();
path_item.insert(
method.to_owned(),
json!({
"operationId":"methodProbe", "responses":{"200":{"description":"ok"}}
}),
);
let probe = if version == "Swagger 2.0" {
json!({"swagger":"2.0","info":{"title":"Method probe","version":"1"},"paths":{"/probe":path_item,"/normal":{"get":{"operationId":"normalProbe","responses":{"200":{"description":"ok"}}}}}})
} else {
json!({"openapi":if version == "OpenAPI 3.0" {"3.0.3"} else {"3.1.0"},
"info":{"title":"Method probe","version":"1"},"servers":[{"url":"https://matrix.example.test"}],"paths":{"/probe":path_item,"/normal":{"get":{"operationId":"normalProbe","responses":{"200":{"description":"ok"}}}}}})
};
let source = serde_json::to_string(&probe).unwrap();
let ir = normalize(&source).unwrap();
validate_normalized_ir(&ir).unwrap();
if row["status"] == "supported" {
assert!(
ir.operations
.iter()
.any(
|operation| serde_json::to_value(operation.method).unwrap().as_str()
== Some(&method.to_ascii_uppercase())
),
"{version} {construct} was not preserved"
);
assert_eq!(row["expected_finding"], "none");
assert_actionable(&ir, &format!("{version} {construct}"));
} else {
let expected_finding = row["expected_finding"].as_str().unwrap();
assert!(
ir.operations
.iter()
.any(|operation| operation.path == "/normal"),
"{version} {construct} must not discard a supported neighbour"
);
assert!(
ir.findings
.iter()
.any(|finding| finding.code == expected_finding
&& finding.severity
== crank_import::rest::ImportFindingSeverity::Error),
"{version} {construct} missing exact finding {expected_finding}: {:?}",
ir.findings
);
assert!(
ir.coverage
.iter()
.any(|entry| entry.construct_id.ends_with(&format!("/{method}"))
&& entry.disposition == CoverageDisposition::Finding),
"{version} {construct} has no finding coverage"
);
}
probed(&construct);
}
for location in ["path", "query", "header", "cookie"] {
let construct = format!("parameter.location.{location}");
let row = rows
.iter()
.find(|row| {
row["specification_version"] == version && row["construct_id"] == construct
})
.unwrap();
let parameter = if version == "Swagger 2.0" {
json!({"name":"probe","in":location,"required":location == "path","type":"string"})
} else {
json!({"name":"probe","in":location,"required":location == "path","schema":{"type":"string"}})
};
let path = if location == "path" {
"/probe/{probe}"
} else {
"/probe"
};
let operation = json!({"operationId":"parameterProbe","parameters":[parameter],"responses":{"200":{"description":"ok"}}});
let probe = if version == "Swagger 2.0" {
json!({"swagger":"2.0","info":{"title":"Parameter probe","version":"1"},"paths":{path:{"get":operation}}})
} else {
json!({"openapi":if version == "OpenAPI 3.0" {"3.0.3"} else {"3.1.0"},
"info":{"title":"Parameter probe","version":"1"},"servers":[{"url":"https://matrix.example.test"}],"paths":{path:{"get":operation}}})
};
let source = serde_json::to_string(&probe).unwrap();
let ir = normalize(&source).unwrap();
validate_normalized_ir(&ir).unwrap();
if row["status"] == "supported" {
let parameter = ir.operations[0]
.parameters
.iter()
.find(|parameter| parameter.name == "probe")
.unwrap();
assert_eq!(
serde_json::to_value(parameter.location).unwrap(),
location,
"{version} {construct} location was changed"
);
assert!(
parameter.schema.is_some(),
"{version} {construct} schema was lost"
);
assert_eq!(parameter.required, location == "path");
let preview = preview_from_ir(&ir);
let candidate = &preview.groups[0].operations[0];
let expected_root = match location {
"path" => "$.request.path.",
"query" => "$.request.query.",
"header" => "$.request.headers.",
"cookie" => "$.request.cookies.",
_ => unreachable!(),
};
assert!(
candidate
.draft
.input_mapping
.rules
.iter()
.any(|rule| rule.source == "$.mcp.probe"
&& rule.target.starts_with(expected_root)),
"{version} {construct} input mapping missing {expected_root}: {:?}",
candidate.draft.input_mapping
);
assert_actionable(&ir, &format!("{version} {construct}"));
} else {
let expected_finding = row["expected_finding"].as_str().unwrap();
assert!(
ir.operations[0].findings.iter().any(|finding| finding.code
== expected_finding
&& finding.severity == crank_import::rest::ImportFindingSeverity::Error
&& finding.location.pointer == "/paths/~1probe/get/parameters/0"),
"{version} {construct} missing exact finding {expected_finding}"
);
}
probed(&construct);
}
for media_type in [
"application/json",
"application/x-www-form-urlencoded",
"multipart/form-data",
] {
let construct = format!("request_body.{media_type}");
let row = rows
.iter()
.find(|row| {
row["specification_version"] == version && row["construct_id"] == construct
})
.unwrap();
let operation = if version == "Swagger 2.0" {
let mut operation =
json!({"operationId":"bodyProbe","responses":{"200":{"description":"ok"}}});
operation["consumes"] = json!([media_type]);
if media_type == "application/json" {
operation["parameters"] = json!([{"name":"body","in":"body","required":true,"schema":{"type":"object","properties":{"value":{"type":"string"}}}}]);
} else {
operation["parameters"] =
json!([{"name":"value","in":"formData","required":true,"type":"string"}]);
}
operation
} else {
json!({"operationId":"bodyProbe","requestBody":{"required":true,"content":{
(media_type):{"schema":{"type":"object","properties":{"value":{"type":"string"}}}}
}},"responses":{"200":{"description":"ok"}}})
};
let probe = if version == "Swagger 2.0" {
json!({"swagger":"2.0","info":{"title":"Body probe","version":"1"},"paths":{"/probe":{"post":operation}}})
} else {
json!({"openapi":if version == "OpenAPI 3.0" {"3.0.3"} else {"3.1.0"},
"info":{"title":"Body probe","version":"1"},"servers":[{"url":"https://matrix.example.test"}],"paths":{"/probe":{"post":operation}}})
};
let source = serde_json::to_string(&probe).unwrap();
let ir = normalize(&source).unwrap();
validate_normalized_ir(&ir).unwrap();
if row["status"] == "supported" {
let variant = ir.operations[0]
.request_body_variants
.iter()
.find(|variant| variant.content_type == media_type)
.expect("request body variant retained");
assert!(
variant.schema.is_some(),
"{version} {construct} schema was lost: {:?}",
variant
);
assert!(
variant.required,
"{version} {construct} required request body contract was lost: {variant:?}"
);
let preview = preview_from_ir(&ir);
let contract = preview.groups[0].operations[0]
.draft
.target
.request_contract
.as_ref()
.expect("draft request contract");
assert!(contract.body_required);
assert!(
contract
.variants
.iter()
.any(|variant| variant.media_type == media_type)
);
assert_actionable(&ir, &format!("{version} {construct}"));
} else {
let expected_finding = row["expected_finding"].as_str().unwrap();
assert!(
ir.operations[0].findings.iter().any(|finding| finding.code
== expected_finding
&& finding.severity == crank_import::rest::ImportFindingSeverity::Error)
);
}
probed(&construct);
}
for (construct, is_request) in [
("media_type.application_xml.request", true),
("media_type.application_xml.response", false),
] {
let row = rows
.iter()
.find(|row| {
row["specification_version"] == version && row["construct_id"] == construct
})
.unwrap();
let operation = if version == "Swagger 2.0" {
let mut operation = json!({"operationId":"xmlProbe","responses":{"200":{"description":"ok","schema":{"type":"string"}}}});
if is_request {
operation["consumes"] = json!(["application/xml"]);
operation["parameters"] = json!([{"name":"body","in":"body","required":true,"schema":{"type":"string"}}]);
} else {
operation["produces"] = json!(["application/xml"]);
}
operation
} else if is_request {
json!({"operationId":"xmlProbe","requestBody":{"content":{"application/xml":{"schema":{"type":"string"}}}},"responses":{"200":{"description":"ok"}}})
} else {
json!({"operationId":"xmlProbe","responses":{"200":{"description":"ok","content":{"application/xml":{"schema":{"type":"string"}}}}}})
};
let probe = if version == "Swagger 2.0" {
json!({"swagger":"2.0","info":{"title":"XML probe","version":"1"},"paths":{"/probe":{"post":operation}}})
} else {
json!({"openapi":if version == "OpenAPI 3.0" {"3.0.3"} else {"3.1.0"},
"info":{"title":"XML probe","version":"1"},"servers":[{"url":"https://matrix.example.test"}],"paths":{"/probe":{"post":operation}}})
};
let source = serde_json::to_string(&probe).unwrap();
let ir = normalize(&source).unwrap();
validate_normalized_ir(&ir).unwrap();
let expected_finding = row["expected_finding"].as_str().unwrap();
assert_eq!(row["status"], "unsupported");
let expected_pointer = if version == "Swagger 2.0" {
if is_request {
"/paths/~1probe/post/consumes/0"
} else {
"/paths/~1probe/post/produces/0"
}
} else if is_request {
"/paths/~1probe/post/requestBody/content/application~1xml"
} else {
"/paths/~1probe/post/responses/200/content/application~1xml"
};
assert!(
ir.operations[0]
.findings
.iter()
.any(|finding| finding.code == expected_finding
&& finding.severity == crank_import::rest::ImportFindingSeverity::Error
&& finding.location.pointer == expected_pointer),
"{version} {construct} missing exact blocker {expected_finding}: {:?}",
ir.operations[0].findings
);
probed(construct);
}
for composition in ["allOf", "oneOf", "anyOf"] {
let construct = format!("composition.{composition}");
let row = rows
.iter()
.find(|row| {
row["specification_version"] == version && row["construct_id"] == construct
})
.unwrap();
let schema = json!({(composition):[{"type":"object","properties":{"id":{"type":"string"}}},{"type":"object","properties":{"name":{"type":"string"}}}]});
let response = if version == "Swagger 2.0" {
json!({"description":"ok","schema":schema})
} else {
json!({"description":"ok","content":{"application/json":{"schema":schema}}})
};
let probe = if version == "Swagger 2.0" {
json!({"swagger":"2.0","info":{"title":"Composition probe","version":"1"},"paths":{"/probe":{"get":{"operationId":"compositionProbe","responses":{"200":response}}}}})
} else {
json!({"openapi":if version == "OpenAPI 3.0" {"3.0.3"} else {"3.1.0"},
"info":{"title":"Composition probe","version":"1"},"servers":[{"url":"https://matrix.example.test"}],"paths":{"/probe":{"get":{"operationId":"compositionProbe","responses":{"200":response}}}}})
};
let source = serde_json::to_string(&probe).unwrap();
let ir = normalize(&source).unwrap();
validate_normalized_ir(&ir).unwrap();
assert_eq!(row["status"], "supported");
assert!(ir.operations[0].response_variants[0].schema.as_ref().is_some_and(|schema|
if composition == "allOf" {
matches!(&schema.kind, NormalizedSchemaKind::Object { properties, .. }
if properties.contains_key("id") && properties.contains_key("name"))
} else {
matches!(&schema.kind, NormalizedSchemaKind::Composition { operator, variants }
if operator == composition && variants.len() == 2
&& matches!(&variants[0].kind, NormalizedSchemaKind::Object { properties, .. }
if properties.contains_key("id"))
&& matches!(&variants[1].kind, NormalizedSchemaKind::Object { properties, .. }
if properties.contains_key("name")))
}),
"{version} {construct} composition was not retained: {:?}", ir.operations[0].response_variants);
assert_eq!(row["expected_finding"], "none");
assert_actionable(&ir, &format!("{version} {construct}"));
probed(&construct);
}
for external in [false, true] {
let construct = if external {
"reference.external_allowlisted"
} else {
"reference.local"
};
let row = rows
.iter()
.find(|row| {
row["specification_version"] == version && row["construct_id"] == construct
})
.unwrap();
let reference = if external {
"https://schemas.example.test/root.yaml#/Item"
} else if version == "Swagger 2.0" {
"#/definitions/Item"
} else {
"#/components/schemas/Item"
};
let schema = json!({"$ref":reference});
let response = if version == "Swagger 2.0" {
json!({"description":"ok","schema":schema})
} else {
json!({"description":"ok","content":{"application/json":{"schema":schema}}})
};
let probe = if version == "Swagger 2.0" {
let mut root = json!({"swagger":"2.0","info":{"title":"Reference probe","version":"1"},"paths":{"/probe":{"get":{"operationId":"referenceProbe","responses":{"200":response}}}}});
if !external {
root["definitions"] =
json!({"Item":{"type":"object","properties":{"id":{"type":"string"}}}});
}
root
} else {
let mut root = json!({"openapi":if version == "OpenAPI 3.0" {"3.0.3"} else {"3.1.0"},
"info":{"title":"Reference probe","version":"1"},"servers":[{"url":"https://matrix.example.test"}],"paths":{"/probe":{"get":{"operationId":"referenceProbe","responses":{"200":response}}}}});
if !external {
root["components"] = json!({"schemas":{"Item":{"type":"object","properties":{"id":{"type":"string"}}}}});
}
root
};
let source = serde_json::to_string(&probe).unwrap();
let ir = if external {
let external_source =
"Item: { type: object, properties: { id: { type: string } } }";
let snapshot = crank_import::rest::ExternalDocumentSnapshot {
canonical_uri: "https://schemas.example.test/root.yaml".to_owned(),
digest: SourceDigest::parse(hex(external_source.as_bytes())).unwrap(),
document: external_source.to_owned(),
};
let digest = SourceDigest::parse(hex(source.as_bytes())).unwrap();
normalize_verified_bundle(
&source,
digest,
&[snapshot],
&NormalizationConfig::default(),
)
.unwrap()
} else {
normalize(&source).unwrap()
};
validate_normalized_ir(&ir).unwrap();
assert_eq!(row["status"], "supported");
assert!(
!ir.reference_graph.edges.is_empty(),
"{version} {construct} did not resolve through a source-backed edge"
);
assert!(
ir.unresolved_references.is_empty(),
"{version} {construct} remains unresolved"
);
assert!(
matches!(
ir.operations[0].response_variants[0].schema.as_ref().map(|schema| &schema.kind),
Some(NormalizedSchemaKind::Object { properties, .. }) if properties.contains_key("id")
),
"{version} {construct} resolved schema was not projected into the operation"
);
assert_actionable(&ir, &format!("{version} {construct}"));
assert_eq!(row["expected_finding"], "none");
probed(construct);
}
for code in 200..300 {
let construct = format!("response.{code}");
let response_row = rows
.iter()
.find(|row| {
row["specification_version"] == version && row["construct_id"] == construct
})
.unwrap_or_else(|| panic!("{version} matrix misses {construct}"));
assert!(
ids.contains(&construct.as_str()),
"{version} matrix misses {construct}"
);
assert_eq!(response_row["status"], "supported");
assert_eq!(response_row["expected_finding"], "none");
let has_body = !matches!(code, 204 | 205);
let source = if version == "Swagger 2.0" {
json!({
"swagger":"2.0", "info":{"title":"Matrix probe","version":"1"},
"paths":{"/probe":{"get":{"operationId":"matrixProbe","responses":{
code.to_string(): if has_body {json!({"description":"success","schema":{"type":"object","properties":{"id":{"type":"string"}}}})} else {json!({"description":"success"})}
}}}}
})
} else {
json!({
"openapi": if version == "OpenAPI 3.0" {"3.0.3"} else {"3.1.0"},
"info":{"title":"Matrix probe","version":"1"},
"servers":[{"url":"https://matrix.example.test"}],
"paths":{"/probe":{"get":{"operationId":"matrixProbe","responses":{
code.to_string(): if has_body {json!({"description":"success","content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string"}}}}}})} else {json!({"description":"success"})}
}}}}
})
};
let source = serde_json::to_string(&source).unwrap();
let ir = normalize(&source)
.unwrap_or_else(|error| panic!("{version} {construct} probe rejected: {error}"));
validate_normalized_ir(&ir).unwrap_or_else(|error| {
panic!("{version} {construct} probe has invalid ledger: {error}")
});
let response = ir.operations[0]
.response_variants
.iter()
.find(|variant| variant.status_code == code)
.unwrap_or_else(|| panic!("{version} {construct} was not preserved"));
assert_eq!(
response.schema.is_some(),
has_body,
"{version} {construct} body contract differs from 204/205 bodyless response semantics"
);
assert!(
!ir.operations[0]
.findings
.iter()
.any(|finding| finding.severity
== crank_import::rest::ImportFindingSeverity::Error),
"{version} {construct} unexpectedly blocked: {:?}",
ir.operations[0].findings
);
probed(&construct);
}
assert!(
unprobed.is_empty(),
"normative {version} rows lack an executed probe: {unprobed:?}"
);
}
}
@@ -0,0 +1,50 @@
{
"info": {
"title": "Synthetic corpus 00",
"version": "1.0"
},
"openapi": "3.0.3",
"paths": {
"/items/0": {
"get": {
"operationId": "corpusOperation00",
"parameters": [
{
"in": "query",
"name": "p00",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 00",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,65 @@
{
"info": {
"title": "Synthetic corpus 01",
"version": "1.0"
},
"openapi": "3.1.0",
"paths": {
"/items/{p01}": {
"post": {
"operationId": "corpusOperation01",
"parameters": [
{
"in": "path",
"name": "p01",
"required": true,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"properties": {
"name": {
"type": "string"
}
},
"type": "object"
}
}
},
"required": true
},
"responses": {
"201": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 01",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,67 @@
{
"basePath": "/v1",
"consumes": [
"application/json"
],
"host": "api.example.test",
"info": {
"title": "Synthetic corpus 02",
"version": "1.0"
},
"paths": {
"/items/2": {
"put": {
"operationId": "corpusOperation02",
"parameters": [
{
"in": "header",
"name": "p02",
"required": false,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"properties": {
"name": {
"type": "string"
}
},
"type": "object"
}
}
},
"required": true
},
"responses": {
"202": {
"description": "synthetic success",
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"summary": "Synthetic operation 02",
"tags": [
"corpus"
]
}
}
},
"produces": [
"application/json"
],
"schemes": [
"https"
],
"swagger": "2.0"
}
@@ -0,0 +1,65 @@
{
"info": {
"title": "Synthetic corpus 03",
"version": "1.0"
},
"openapi": "3.0.3",
"paths": {
"/items/3": {
"patch": {
"operationId": "corpusOperation03",
"parameters": [
{
"in": "cookie",
"name": "p03",
"required": false,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"properties": {
"name": {
"type": "string"
}
},
"type": "object"
}
}
},
"required": true
},
"responses": {
"204": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 03",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,50 @@
{
"info": {
"title": "Synthetic corpus 04",
"version": "1.0"
},
"openapi": "3.1.0",
"paths": {
"/items/4": {
"delete": {
"operationId": "corpusOperation04",
"parameters": [
{
"in": "query",
"name": "p04",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 04",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,52 @@
{
"basePath": "/v1",
"consumes": [
"application/json"
],
"host": "api.example.test",
"info": {
"title": "Synthetic corpus 05",
"version": "1.0"
},
"paths": {
"/items/{p05}": {
"head": {
"operationId": "corpusOperation05",
"parameters": [
{
"in": "path",
"name": "p05",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"201": {
"description": "synthetic success",
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"summary": "Synthetic operation 05",
"tags": [
"corpus"
]
}
}
},
"produces": [
"application/json"
],
"schemes": [
"https"
],
"swagger": "2.0"
}
@@ -0,0 +1,50 @@
{
"info": {
"title": "Synthetic corpus 06",
"version": "1.0"
},
"openapi": "3.0.3",
"paths": {
"/items/6": {
"options": {
"operationId": "corpusOperation06",
"parameters": [
{
"in": "header",
"name": "p06",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"202": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 06",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,50 @@
{
"info": {
"title": "Synthetic corpus 07",
"version": "1.0"
},
"openapi": "3.1.0",
"paths": {
"/items/7": {
"get": {
"operationId": "corpusOperation07",
"parameters": [
{
"in": "cookie",
"name": "p07",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"204": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 07",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,67 @@
{
"basePath": "/v1",
"consumes": [
"application/json"
],
"host": "api.example.test",
"info": {
"title": "Synthetic corpus 08",
"version": "1.0"
},
"paths": {
"/items/8": {
"post": {
"operationId": "corpusOperation08",
"parameters": [
{
"in": "query",
"name": "p08",
"required": false,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"properties": {
"name": {
"type": "string"
}
},
"type": "object"
}
}
},
"required": true
},
"responses": {
"200": {
"description": "synthetic success",
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"summary": "Synthetic operation 08",
"tags": [
"corpus"
]
}
}
},
"produces": [
"application/json"
],
"schemes": [
"https"
],
"swagger": "2.0"
}
@@ -0,0 +1,65 @@
{
"info": {
"title": "Synthetic corpus 09",
"version": "1.0"
},
"openapi": "3.0.3",
"paths": {
"/items/{p09}": {
"put": {
"operationId": "corpusOperation09",
"parameters": [
{
"in": "path",
"name": "p09",
"required": true,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"properties": {
"name": {
"type": "string"
}
},
"type": "object"
}
}
},
"required": true
},
"responses": {
"201": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 09",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,65 @@
{
"info": {
"title": "Synthetic corpus 10",
"version": "1.0"
},
"openapi": "3.1.0",
"paths": {
"/items/10": {
"patch": {
"operationId": "corpusOperation10",
"parameters": [
{
"in": "header",
"name": "p10",
"required": false,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"properties": {
"name": {
"type": "string"
}
},
"type": "object"
}
}
},
"required": true
},
"responses": {
"202": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 10",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,52 @@
{
"basePath": "/v1",
"consumes": [
"application/json"
],
"host": "api.example.test",
"info": {
"title": "Synthetic corpus 11",
"version": "1.0"
},
"paths": {
"/items/11": {
"delete": {
"operationId": "corpusOperation11",
"parameters": [
{
"in": "header",
"name": "p11",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"204": {
"description": "synthetic success",
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"summary": "Synthetic operation 11",
"tags": [
"corpus"
]
}
}
},
"produces": [
"application/json"
],
"schemes": [
"https"
],
"swagger": "2.0"
}
@@ -0,0 +1,50 @@
{
"info": {
"title": "Synthetic corpus 12",
"version": "1.0"
},
"openapi": "3.0.3",
"paths": {
"/items/12": {
"head": {
"operationId": "corpusOperation12",
"parameters": [
{
"in": "query",
"name": "p12",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 12",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,50 @@
{
"info": {
"title": "Synthetic corpus 13",
"version": "1.0"
},
"openapi": "3.1.0",
"paths": {
"/items/{p13}": {
"options": {
"operationId": "corpusOperation13",
"parameters": [
{
"in": "path",
"name": "p13",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"201": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 13",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,52 @@
{
"basePath": "/v1",
"consumes": [
"application/json"
],
"host": "api.example.test",
"info": {
"title": "Synthetic corpus 14",
"version": "1.0"
},
"paths": {
"/items/14": {
"get": {
"operationId": "corpusOperation14",
"parameters": [
{
"in": "header",
"name": "p14",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"202": {
"description": "synthetic success",
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"summary": "Synthetic operation 14",
"tags": [
"corpus"
]
}
}
},
"produces": [
"application/json"
],
"schemes": [
"https"
],
"swagger": "2.0"
}
@@ -0,0 +1,65 @@
{
"info": {
"title": "Synthetic corpus 15",
"version": "1.0"
},
"openapi": "3.0.3",
"paths": {
"/items/15": {
"post": {
"operationId": "corpusOperation15",
"parameters": [
{
"in": "cookie",
"name": "p15",
"required": false,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"properties": {
"name": {
"type": "string"
}
},
"type": "object"
}
}
},
"required": true
},
"responses": {
"204": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 15",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,65 @@
{
"info": {
"title": "Synthetic corpus 16",
"version": "1.0"
},
"openapi": "3.1.0",
"paths": {
"/items/16": {
"put": {
"operationId": "corpusOperation16",
"parameters": [
{
"in": "query",
"name": "p16",
"required": false,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"properties": {
"name": {
"type": "string"
}
},
"type": "object"
}
}
},
"required": true
},
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 16",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,67 @@
{
"basePath": "/v1",
"consumes": [
"application/json"
],
"host": "api.example.test",
"info": {
"title": "Synthetic corpus 17",
"version": "1.0"
},
"paths": {
"/items/{p17}": {
"patch": {
"operationId": "corpusOperation17",
"parameters": [
{
"in": "path",
"name": "p17",
"required": true,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"properties": {
"name": {
"type": "string"
}
},
"type": "object"
}
}
},
"required": true
},
"responses": {
"201": {
"description": "synthetic success",
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"summary": "Synthetic operation 17",
"tags": [
"corpus"
]
}
}
},
"produces": [
"application/json"
],
"schemes": [
"https"
],
"swagger": "2.0"
}
@@ -0,0 +1,50 @@
{
"info": {
"title": "Synthetic corpus 18",
"version": "1.0"
},
"openapi": "3.0.3",
"paths": {
"/items/18": {
"delete": {
"operationId": "corpusOperation18",
"parameters": [
{
"in": "header",
"name": "p18",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"202": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 18",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,50 @@
{
"info": {
"title": "Synthetic corpus 19",
"version": "1.0"
},
"openapi": "3.1.0",
"paths": {
"/items/19": {
"head": {
"operationId": "corpusOperation19",
"parameters": [
{
"in": "cookie",
"name": "p19",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"204": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 19",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,52 @@
{
"basePath": "/v1",
"consumes": [
"application/json"
],
"host": "api.example.test",
"info": {
"title": "Synthetic corpus 20",
"version": "1.0"
},
"paths": {
"/items/20": {
"options": {
"operationId": "corpusOperation20",
"parameters": [
{
"in": "query",
"name": "p20",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "synthetic success",
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"summary": "Synthetic operation 20",
"tags": [
"corpus"
]
}
}
},
"produces": [
"application/json"
],
"schemes": [
"https"
],
"swagger": "2.0"
}
@@ -0,0 +1,50 @@
{
"info": {
"title": "Synthetic corpus 21",
"version": "1.0"
},
"openapi": "3.0.3",
"paths": {
"/items/{p21}": {
"get": {
"operationId": "corpusOperation21",
"parameters": [
{
"in": "path",
"name": "p21",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"201": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 21",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,65 @@
{
"info": {
"title": "Synthetic corpus 22",
"version": "1.0"
},
"openapi": "3.1.0",
"paths": {
"/items/22": {
"post": {
"operationId": "corpusOperation22",
"parameters": [
{
"in": "header",
"name": "p22",
"required": false,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"properties": {
"name": {
"type": "string"
}
},
"type": "object"
}
}
},
"required": true
},
"responses": {
"202": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 22",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,67 @@
{
"basePath": "/v1",
"consumes": [
"application/json"
],
"host": "api.example.test",
"info": {
"title": "Synthetic corpus 23",
"version": "1.0"
},
"paths": {
"/items/23": {
"put": {
"operationId": "corpusOperation23",
"parameters": [
{
"in": "header",
"name": "p23",
"required": false,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"properties": {
"name": {
"type": "string"
}
},
"type": "object"
}
}
},
"required": true
},
"responses": {
"204": {
"description": "synthetic success",
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"summary": "Synthetic operation 23",
"tags": [
"corpus"
]
}
}
},
"produces": [
"application/json"
],
"schemes": [
"https"
],
"swagger": "2.0"
}
@@ -0,0 +1,65 @@
{
"info": {
"title": "Synthetic corpus 24",
"version": "1.0"
},
"openapi": "3.0.3",
"paths": {
"/items/24": {
"patch": {
"operationId": "corpusOperation24",
"parameters": [
{
"in": "query",
"name": "p24",
"required": false,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"properties": {
"name": {
"type": "string"
}
},
"type": "object"
}
}
},
"required": true
},
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 24",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,50 @@
{
"info": {
"title": "Synthetic corpus 25",
"version": "1.0"
},
"openapi": "3.1.0",
"paths": {
"/items/{p25}": {
"delete": {
"operationId": "corpusOperation25",
"parameters": [
{
"in": "path",
"name": "p25",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"201": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 25",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,52 @@
{
"basePath": "/v1",
"consumes": [
"application/json"
],
"host": "api.example.test",
"info": {
"title": "Synthetic corpus 26",
"version": "1.0"
},
"paths": {
"/items/26": {
"head": {
"operationId": "corpusOperation26",
"parameters": [
{
"in": "header",
"name": "p26",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"202": {
"description": "synthetic success",
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"summary": "Synthetic operation 26",
"tags": [
"corpus"
]
}
}
},
"produces": [
"application/json"
],
"schemes": [
"https"
],
"swagger": "2.0"
}
@@ -0,0 +1,50 @@
{
"info": {
"title": "Synthetic corpus 27",
"version": "1.0"
},
"openapi": "3.0.3",
"paths": {
"/items/27": {
"options": {
"operationId": "corpusOperation27",
"parameters": [
{
"in": "cookie",
"name": "p27",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"204": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 27",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,50 @@
{
"info": {
"title": "Synthetic corpus 28",
"version": "1.0"
},
"openapi": "3.1.0",
"paths": {
"/items/28": {
"get": {
"operationId": "corpusOperation28",
"parameters": [
{
"in": "query",
"name": "p28",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 28",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,67 @@
{
"basePath": "/v1",
"consumes": [
"application/json"
],
"host": "api.example.test",
"info": {
"title": "Synthetic corpus 29",
"version": "1.0"
},
"paths": {
"/items/{p29}": {
"post": {
"operationId": "corpusOperation29",
"parameters": [
{
"in": "path",
"name": "p29",
"required": true,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"properties": {
"name": {
"type": "string"
}
},
"type": "object"
}
}
},
"required": true
},
"responses": {
"201": {
"description": "synthetic success",
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"summary": "Synthetic operation 29",
"tags": [
"corpus"
]
}
}
},
"produces": [
"application/json"
],
"schemes": [
"https"
],
"swagger": "2.0"
}
@@ -0,0 +1,65 @@
{
"info": {
"title": "Synthetic corpus 30",
"version": "1.0"
},
"openapi": "3.0.3",
"paths": {
"/items/30": {
"put": {
"operationId": "corpusOperation30",
"parameters": [
{
"in": "header",
"name": "p30",
"required": false,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"properties": {
"name": {
"type": "string"
}
},
"type": "object"
}
}
},
"required": true
},
"responses": {
"202": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 30",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,65 @@
{
"info": {
"title": "Synthetic corpus 31",
"version": "1.0"
},
"openapi": "3.1.0",
"paths": {
"/items/31": {
"patch": {
"operationId": "corpusOperation31",
"parameters": [
{
"in": "cookie",
"name": "p31",
"required": false,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"properties": {
"name": {
"type": "string"
}
},
"type": "object"
}
}
},
"required": true
},
"responses": {
"204": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 31",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,52 @@
{
"basePath": "/v1",
"consumes": [
"application/json"
],
"host": "api.example.test",
"info": {
"title": "Synthetic corpus 32",
"version": "1.0"
},
"paths": {
"/items/32": {
"delete": {
"operationId": "corpusOperation32",
"parameters": [
{
"in": "query",
"name": "p32",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "synthetic success",
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"summary": "Synthetic operation 32",
"tags": [
"corpus"
]
}
}
},
"produces": [
"application/json"
],
"schemes": [
"https"
],
"swagger": "2.0"
}
@@ -0,0 +1,50 @@
{
"info": {
"title": "Synthetic corpus 33",
"version": "1.0"
},
"openapi": "3.0.3",
"paths": {
"/items/{p33}": {
"head": {
"operationId": "corpusOperation33",
"parameters": [
{
"in": "path",
"name": "p33",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"201": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 33",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,50 @@
{
"info": {
"title": "Synthetic corpus 34",
"version": "1.0"
},
"openapi": "3.1.0",
"paths": {
"/items/34": {
"options": {
"operationId": "corpusOperation34",
"parameters": [
{
"in": "header",
"name": "p34",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"202": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 34",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,52 @@
{
"basePath": "/v1",
"consumes": [
"application/json"
],
"host": "api.example.test",
"info": {
"title": "Synthetic corpus 35",
"version": "1.0"
},
"paths": {
"/items/35": {
"get": {
"operationId": "corpusOperation35",
"parameters": [
{
"in": "header",
"name": "p35",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"204": {
"description": "synthetic success",
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"summary": "Synthetic operation 35",
"tags": [
"corpus"
]
}
}
},
"produces": [
"application/json"
],
"schemes": [
"https"
],
"swagger": "2.0"
}
@@ -0,0 +1,65 @@
{
"info": {
"title": "Synthetic corpus 36",
"version": "1.0"
},
"openapi": "3.0.3",
"paths": {
"/items/36": {
"post": {
"operationId": "corpusOperation36",
"parameters": [
{
"in": "query",
"name": "p36",
"required": false,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"properties": {
"name": {
"type": "string"
}
},
"type": "object"
}
}
},
"required": true
},
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 36",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,65 @@
{
"info": {
"title": "Synthetic corpus 37",
"version": "1.0"
},
"openapi": "3.1.0",
"paths": {
"/items/{p37}": {
"put": {
"operationId": "corpusOperation37",
"parameters": [
{
"in": "path",
"name": "p37",
"required": true,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"properties": {
"name": {
"type": "string"
}
},
"type": "object"
}
}
},
"required": true
},
"responses": {
"201": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 37",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,67 @@
{
"basePath": "/v1",
"consumes": [
"application/json"
],
"host": "api.example.test",
"info": {
"title": "Synthetic corpus 38",
"version": "1.0"
},
"paths": {
"/items/38": {
"patch": {
"operationId": "corpusOperation38",
"parameters": [
{
"in": "header",
"name": "p38",
"required": false,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"properties": {
"name": {
"type": "string"
}
},
"type": "object"
}
}
},
"required": true
},
"responses": {
"202": {
"description": "synthetic success",
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"summary": "Synthetic operation 38",
"tags": [
"corpus"
]
}
}
},
"produces": [
"application/json"
],
"schemes": [
"https"
],
"swagger": "2.0"
}
@@ -0,0 +1,50 @@
{
"info": {
"title": "Synthetic corpus 39",
"version": "1.0"
},
"openapi": "3.0.3",
"paths": {
"/items/39": {
"delete": {
"operationId": "corpusOperation39",
"parameters": [
{
"in": "cookie",
"name": "p39",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"204": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 39",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,50 @@
{
"info": {
"title": "Synthetic corpus 40",
"version": "1.0"
},
"openapi": "3.1.0",
"paths": {
"/items/40": {
"head": {
"operationId": "corpusOperation40",
"parameters": [
{
"in": "query",
"name": "p40",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 40",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,52 @@
{
"basePath": "/v1",
"consumes": [
"application/json"
],
"host": "api.example.test",
"info": {
"title": "Synthetic corpus 41",
"version": "1.0"
},
"paths": {
"/items/{p41}": {
"options": {
"operationId": "corpusOperation41",
"parameters": [
{
"in": "path",
"name": "p41",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"201": {
"description": "synthetic success",
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"summary": "Synthetic operation 41",
"tags": [
"corpus"
]
}
}
},
"produces": [
"application/json"
],
"schemes": [
"https"
],
"swagger": "2.0"
}
@@ -0,0 +1,50 @@
{
"info": {
"title": "Synthetic corpus 42",
"version": "1.0"
},
"openapi": "3.0.3",
"paths": {
"/items/42": {
"get": {
"operationId": "corpusOperation42",
"parameters": [
{
"in": "header",
"name": "p42",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"202": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 42",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,65 @@
{
"info": {
"title": "Synthetic corpus 43",
"version": "1.0"
},
"openapi": "3.1.0",
"paths": {
"/items/43": {
"post": {
"operationId": "corpusOperation43",
"parameters": [
{
"in": "cookie",
"name": "p43",
"required": false,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"properties": {
"name": {
"type": "string"
}
},
"type": "object"
}
}
},
"required": true
},
"responses": {
"204": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 43",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,67 @@
{
"basePath": "/v1",
"consumes": [
"application/json"
],
"host": "api.example.test",
"info": {
"title": "Synthetic corpus 44",
"version": "1.0"
},
"paths": {
"/items/44": {
"put": {
"operationId": "corpusOperation44",
"parameters": [
{
"in": "query",
"name": "p44",
"required": false,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"properties": {
"name": {
"type": "string"
}
},
"type": "object"
}
}
},
"required": true
},
"responses": {
"200": {
"description": "synthetic success",
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"summary": "Synthetic operation 44",
"tags": [
"corpus"
]
}
}
},
"produces": [
"application/json"
],
"schemes": [
"https"
],
"swagger": "2.0"
}
@@ -0,0 +1,65 @@
{
"info": {
"title": "Synthetic corpus 45",
"version": "1.0"
},
"openapi": "3.0.3",
"paths": {
"/items/{p45}": {
"patch": {
"operationId": "corpusOperation45",
"parameters": [
{
"in": "path",
"name": "p45",
"required": true,
"schema": {
"type": "string"
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"properties": {
"name": {
"type": "string"
}
},
"type": "object"
}
}
},
"required": true
},
"responses": {
"201": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 45",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,50 @@
{
"info": {
"title": "Synthetic corpus 46",
"version": "1.0"
},
"openapi": "3.1.0",
"paths": {
"/items/46": {
"delete": {
"operationId": "corpusOperation46",
"parameters": [
{
"in": "header",
"name": "p46",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"202": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 46",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,52 @@
{
"basePath": "/v1",
"consumes": [
"application/json"
],
"host": "api.example.test",
"info": {
"title": "Synthetic corpus 47",
"version": "1.0"
},
"paths": {
"/items/47": {
"head": {
"operationId": "corpusOperation47",
"parameters": [
{
"in": "header",
"name": "p47",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"204": {
"description": "synthetic success",
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"summary": "Synthetic operation 47",
"tags": [
"corpus"
]
}
}
},
"produces": [
"application/json"
],
"schemes": [
"https"
],
"swagger": "2.0"
}
@@ -0,0 +1,50 @@
{
"info": {
"title": "Synthetic corpus 48",
"version": "1.0"
},
"openapi": "3.0.3",
"paths": {
"/items/48": {
"options": {
"operationId": "corpusOperation48",
"parameters": [
{
"in": "query",
"name": "p48",
"required": false,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 48",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
@@ -0,0 +1,50 @@
{
"info": {
"title": "Synthetic corpus 49",
"version": "1.0"
},
"openapi": "3.1.0",
"paths": {
"/items/{p49}": {
"get": {
"operationId": "corpusOperation49",
"parameters": [
{
"in": "path",
"name": "p49",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"201": {
"content": {
"application/json": {
"schema": {
"properties": {
"id": {
"type": "string"
}
},
"type": "object"
}
}
},
"description": "synthetic success"
}
},
"summary": "Synthetic operation 49",
"tags": [
"corpus"
]
}
}
},
"servers": [
{
"url": "https://api.example.test/v1"
}
]
}
Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff. Show more