diff --git a/Cargo.lock b/Cargo.lock
index b50df08..a51c073 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -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",
@@ -651,6 +651,7 @@ version = "0.3.1"
dependencies = [
"async-trait",
"axum",
+ "base64",
"crank-core",
"crank-metrics",
"crank-trace",
@@ -766,6 +767,7 @@ dependencies = [
"serde_json",
"serde_yaml",
"thiserror 2.0.18",
+ "url",
]
[[package]]
@@ -846,6 +848,7 @@ dependencies = [
"base64",
"crank-adapter-rest",
"crank-core",
+ "crank-import",
"crank-mapping",
"crank-metrics",
"crank-schema",
@@ -1139,7 +1142,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]]
@@ -2668,7 +2671,7 @@ dependencies = [
"once_cell",
"socket2 0.5.10",
"tracing",
- "windows-sys 0.52.0",
+ "windows-sys 0.59.0",
]
[[package]]
@@ -3007,14 +3010,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",
@@ -3066,7 +3069,7 @@ dependencies = [
"security-framework",
"security-framework-sys",
"webpki-root-certs",
- "windows-sys 0.52.0",
+ "windows-sys 0.59.0",
]
[[package]]
@@ -3077,9 +3080,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",
@@ -4470,7 +4473,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]]
diff --git a/_bmad-output/implementation-artifacts/spec-2-10-security-schemes-secrets.md b/_bmad-output/implementation-artifacts/spec-2-10-security-schemes-secrets.md
new file mode 100644
index 0000000..c7515ce
--- /dev/null
+++ b/_bmad-output/implementation-artifacts/spec-2-10-security-schemes-secrets.md
@@ -0,0 +1,227 @@
+---
+title: '2.10 — Привязать security schemes через безопасный import API'
+type: feature
+created: '2026-09-13'
+status: done
+baseline_revision: c562d5368d810d1730f5d392ae0c6c106143a97c
+review_loop_iteration: 0
+followup_review_recommended: true
+context:
+ - '_bmad-output/project-context.md'
+ - '_bmad-output/implementation-artifacts/epic-2-context.md'
+ - '_bmad-output/implementation-artifacts/1-10-lifecycle-auth-profiles-machine-keys.md'
+ - '_bmad-output/implementation-artifacts/spec-2-9-http-contract.md'
+warnings: [oversized]
+deferred: []
+---
+
+
+
+## Intent
+
+**Problem:** Importer не сохраняет security schemes и effective authentication requirements. Import API создаёт Operations с пустым auth binding, а raw upload сохраняется до security analysis.
+
+**Approach:** Сохранить typed security metadata и OR/AND semantics в IR/preview; предоставить workspace-scoped выбор совместимого Auth Profile и повторную проверку binding перед атомарным Apply. Сохранять только ссылки, исключая credential values из artifacts и результатов.
+
+## Boundaries & Constraints
+
+**Always:** Выполнить AC Story 2.10 для OpenAPI 3.0/3.1 и Swagger 2.0; сохранить детерминированность и исторический replay, workspace isolation, typed error/redaction и существующие architectural boundaries. `sprint-status.yaml` принадлежит оркестратору: не записывать и не откатывать его. Статусы спринта не являются доказательством проверки AC.
+
+**Never:** Raw credentials, ciphertext или secret hashes в source snapshot/IR/plan/export/diagnostics; silent collapse OR в AND или выбор первой alternative; создание actionable Draft при unresolved required auth; попутная реализация mapping UI Story 2.11 или полной qualification Story 2.14. Независимый отзыв/status/tombstone lifecycle Auth Profile остаётся вне scope Story 2.10; доступность binding определяется существованием и workspace профиля, а также существующим lifecycle связанных Secrets согласно решению ниже.
+
+
+
+### Решение пользователя: доступность Auth Profile (2026-09-13)
+
+Для Story 2.10 формулировка «отозванный Auth Profile» означает недоступный binding вследствие недоступности любого необходимого связанного Secret по существующим правилам active/current version. Это не независимый отзыв профиля. Preview проверяет существование профиля, его принадлежность текущему workspace, совместимость и доступность необходимых Secrets; Apply повторяет авторитетную проверку в registry transaction до создания Draft, включая изменение состояния после preview.
+
+При общем Secret профилей A и B отключение Secret отклоняет оба binding. При активном Secret с доступной текущей версией оба binding допустимы при выполнении остальных проверок. Независимое отключение только A при сохранении B не требуется и не реализуется в этой истории: status/tombstone и управление отзывом Auth Profile остаются отложенными. Negative test с disabled Secret доказывает только недоступность credential, а не независимый отзыв профиля. Отсутствующие/удалённые и foreign-workspace profile refs отклоняются без раскрытия foreign metadata.
+
+
+
+## I/O & Edge-Case Matrix
+
+| Scenario | Input / State | Expected Output / Behavior | Error Handling |
+|----------|---------------|---------------------------|----------------|
+| Schemes | Bearer/basic/API key header/query/cookie | Typed names, locations и format hints без credentials | Unsupported mapping явно отражён |
+| Effective security | Global rule, operation override, explicit no-auth | Сохраняется specification inheritance/override | Invalid requirement не становится actionable |
+| Alternatives | OR и AND requirements | Все OR alternatives сохраняются; unsupported AND блокирует affected candidate | Finding объясняет потерянную semantics |
+| Binding | Compatible current-workspace profile либо unresolved | Только typed reference; unresolved required auth блокирует Apply | Foreign/missing reference не раскрывает metadata |
+| Credential availability | Профиль отсутствует/удалён, принадлежит другому workspace либо любой необходимый связанный Secret недоступен по существующим правилам active/current version | Reference отклоняется при preview и повторно в transaction Apply до Draft | Ошибка не раскрывает metadata foreign profile |
+| Shared Secret | Профили A и B используют один Secret | При активном Secret с доступной текущей версией оба binding допустимы при выполнении остальных проверок; отключение общего Secret блокирует оба | Независимый отзыв только A не входит в scope и не заявляется как проверенный |
+| Secret source | Literal в example/default/extension/userinfo/header | Redacted finding; raw value отсутствует в persisted/observable output | Проверка до записи source artifact |
+| Stale source | Security source изменён после preview | Digest mismatch, новый preview и подтверждение mappings | Нет mutation |
+
+
+
+## Code Map
+
+- `crates/crank-import/src/rest/model.rs` — `NormalizedIr`, `NormalizedOperation`, `RestImportOperation`, `ImportOperationCandidate` пока не содержат security metadata. `NORMALIZER_VERSION` / `PROJECTION_VERSION` равны v4. `NormalizedIr.source_tree` сохраняет весь canonical document.
+- `crates/crank-import/src/rest/{openapi3.rs,swagger2.rs}` — `parse_document_v2` не читает security schemes/requirements; здесь начинается parser → IR путь.
+- `crates/crank-import/src/rest/{normalize.rs,normalize_projection.rs,payload.rs}` — `canonicalize`, `operation_from_normalized`, `candidate_from_operation` проводят semantics через IR к candidate.
+- `crates/crank-import/src/rest/metadata_findings.rs` — `collect_secret_like_examples` только добавляет warning для example/examples, не удаляя raw value. `normalize_finding_validation.rs` повторяет узкую эвристику.
+- `apps/admin-api/src/service/imports.rs:54` — после upload validation вызывается `put_registered` до parse; raw source записывается с sensitivity Internal. `preview_openapi_import` сохраняет job/digests; `create_openapi_import_with_locale` перепроверяет verified source/preview. При создании Operation `auth_profile_ref` задаётся `None`; `openapi_application_key` пока не включает mappings.
+- `apps/admin-api/src/service/imports/{job_contract.rs,external_references.rs}` — исторический replay и immutable external snapshots; защита source должна распространяться на external inputs.
+- `apps/admin-api/src/{app.rs,dto.rs}` — существующие `POST /imports/openapi/preview` и `POST /imports/openapi/{job_id}/create`, preview/create payloads; выбора auth alternative/profile пока нет.
+- `crates/crank-registry/src/postgres/import_job.rs` — `apply_import_job_transaction` является атомарной границей создания Operations; финальная auth revalidation нужна здесь, иначе service lookup оставляет race.
+- `crates/crank-core/src/auth.rs` — `AuthProfile` имеет identity/workspace/kind/config/timestamps, но не status. `AuthConfig` поддерживает Bearer/Basic/ApiKeyHeader/ApiKeyQuery, без cookie.
+- `crates/crank-core/src/operation.rs` — `ExecutionConfig.auth_profile_ref` допускает один `AuthProfileId`; AND из нескольких schemes не поддержан текущим runtime.
+- `crates/crank-runtime/src/auth.rs` — `ResolvedAuth::{from_profile,apply}`; существующие trusted credential injection rules необходимо сохранить.
+- `apps/admin-api/src/service.rs` — `validate_registry_operation_in_workspace` и `resolve_operation_auth`; `crates/crank-registry/src/postgres/auth.rs` — workspace-scoped profile lookup.
+- `_bmad-output/implementation-artifacts/1-10-lifecycle-auth-profiles-machine-keys.md:223` и `_bmad-output/implementation-artifacts/deferred-work.md:17` — отдельный status/tombstone lifecycle Auth Profile явно отложен; существующая проверка active Secret не равна отзыву отдельного профиля.
+
+## Tasks & Acceptance
+
+**Execution (intent gap разрешён пользователем 2026-09-13; реализация выполняется при повторном запуске оркестратора):**
+
+- [x] `crates/crank-import/src/rest/{model.rs,openapi3.rs,swagger2.rs,normalize.rs,normalize_projection.rs,payload.rs}` — добавить typed schemes и effective requirements, deterministic OR/AND projection, source coverage и blockers без credentials.
+- [x] `crates/crank-import/src/rest/{metadata_findings.rs,normalize_finding_validation.rs}`, `apps/admin-api/src/service/imports.rs`, `apps/admin-api/src/service/imports/external_references.rs` — проверять secret-bearing inputs до persistence и исключить raw values из IR/diagnostics.
+- [x] `apps/admin-api/src/{app.rs,dto.rs,service/imports.rs}` — предоставить выбор/revalidation alternative и совместимых workspace profiles, включить mappings в application digest, сохранять только profile reference.
+- [x] `crates/crank-registry/src/postgres/import_job.rs` — проверять существование и workspace профиля, совместимость binding и доступность всех необходимых связанных Secrets по существующим правилам active/current version в transaction перед mutation; независимый lifecycle профиля не добавлять.
+- [x] `apps/admin-api/src/service/imports/job_contract.rs` — сохранить исторический v4 replay при изменении normalizer/projection contract.
+- [x] `crates/crank-import/tests/`, `apps/admin-api/tests/integration/openapi_import/`, `crates/crank-runtime/tests/` — покрыть все строки матрицы и AC fixtures/negative tests, в том числе race, foreign refs, redaction canaries и digest mismatch.
+- [x] `docs/openapi-import.md` — описать security API, поддерживаемые mappings, blockers и revalidation; не обещать непроверенные semantics.
+
+**Acceptance Criteria (из Story 2.10; семантика доступности binding уточнена решением пользователя 2026-09-13):**
+
+**Given** OpenAPI 3.x `components.securitySchemes` или Swagger 2.0 `securityDefinitions`
+**When** importer анализирует schemes
+**Then** bearer HTTP, basic HTTP и API key в header/query/cookie преобразуются в typed security metadata
+**And** source names, locations и применимые format hints сохраняются без credential values.
+
+**Given** global security requirement
+**When** Operation не задаёт собственный override
+**Then** candidate наследует global requirement согласно specification semantics
+**And** operation-level requirement или explicit no-auth корректно заменяет global rule.
+
+**Given** security requirement с несколькими alternatives
+**When** source определяет OR-семантику
+**Then** preview сохраняет все допустимые alternatives и позволяет выбрать поддерживаемый вариант
+**And** importer не объединяет alternatives в ложное обязательное AND.
+
+**Given** security requirement, требующий несколько schemes одновременно
+**When** source определяет AND-семантику
+**Then** candidate сохраняет составное требование, если runtime contract его поддерживает
+**And** иначе affected Operation получает blocker finding с перечислением несохраняемой semantics.
+
+**Given** bearer, basic или API-key requirement
+**When** формируется preview
+**Then** администратору предлагается выбрать совместимый Auth Profile из текущего workspace либо оставить явный unresolved binding
+**And** unresolved required authentication блокирует actionable Draft/Apply для affected Operation.
+
+**Given** выбранный Auth Profile
+**When** создаётся candidate или ImportPlan
+**Then** сохраняется только typed `AuthProfileRef` и scheme metadata
+**And** raw secret, password, token, API key, hash или encrypted ciphertext не копируется в source snapshot, IR, findings, plan или Operation export.
+
+**Given** OAuth2, OpenID Connect, mutual TLS или неизвестная scheme
+**When** release scope не поддерживает автоматическое mapping
+**Then** importer создаёт explicit manual-configuration/unsupported finding
+**And** не извлекает client secret, token URL credential, example token или vendor-extension secret.
+
+**Given** OpenAPI document содержит literal credential в example, default, extension, URL userinfo или header example
+**When** security analysis выполняется
+**Then** значение не используется как credential и создаёт redacted secret finding
+**And** raw value не появляется в preview UI, logs, traces, metrics или diagnostics.
+
+**Given** Auth Profile отсутствует/удалён, принадлежит другому workspace либо любой необходимый связанный Secret недоступен по существующим правилам active/current version
+**When** preview либо Apply проверяет binding
+**Then** reference отклоняется до создания Draft
+**And** ошибка не раскрывает metadata foreign profile.
+
+**Given** профили A и B используют один активный Secret с доступной текущей версией
+**When** проверяются binding этих профилей
+**Then** оба binding допустимы при выполнении остальных проверок
+**And** после отключения общего Secret оба binding отклоняются до создания Draft; тест с disabled Secret не является доказательством независимого отзыва Auth Profile, который остаётся вне scope.
+
+**Given** исходная security scheme изменилась после preview
+**When** старый ImportPlan пытаются применить к новому source
+**Then** plan digest mismatch блокирует Apply
+**And** требуется новый preview и явное подтверждение Auth Profile mappings.
+
+**Given** security scheme test suite
+**When** выполняются fixtures и negative tests
+**Then** покрыты global/operation overrides, no-auth, bearer/basic/API-key locations, OR/AND requirements, OAuth/OpenID/unknown schemes, secret-like examples, missing/deleted и cross-workspace profile refs, недоступные Secrets по правилам active/current version и блокировка обоих профилей при отключении общего Secret
+**And** redaction tests и `just verify` проходят.
+
+## Spec Change Log
+
+- 2026-09-13 — Пользователь выбрал вариант 1: сохранить существующий lifecycle Secrets; независимый отзыв Auth Profile остаётся отложенным. Уточнены intent, AC, матрица и transaction predicate. Запись Auto Run Result ниже сохранена как историческое свидетельство остановки; требуемое в ней решение принято. Статус переустанавливает оркестратор.
+
+## Review Triage Log
+
+### 2026-09-27 — Review pass
+- verdicts: 13 findings — high 9, medium 1, low 2, false 1, maybe-false 0
+- findings:
+ - `[high]` `[patch]` camelCase `clientSecret`/`accessToken` не распознаются — `sensitive_key` приводит регистр, но сравнивает только целые слова или `_`-границы; literal может остаться в source. Исправить распознавание и покрыть canary. В `security_literals.rs` добавлена проверка camelCase; canary-тест проходит.
+ - `[high]` `[patch]` числовые/boolean credential values пропускаются — `walk` обрабатывает лишь строки, хотя значения под чувствительным ключом тоже являются literal; заменить их безопасным redaction marker и покрыть тестом. В `walk` скаляры под sensitive context заменяются `[REDACTED]`; null оставлен без finding, тест проходит.
+ - `[high]` `[patch]` JWT в generic example пропускается — путь и значение могут не содержать текстовых маркеров; добавить строгую JWT-эвристику и canary-тест. `is_jwt` проверяет форму и длины сегментов; JWT canary и benign `1.2.3` проверены.
+ - `[high]` `[patch]` secret в query URL пропускается — проверяется userinfo, но не ключи query вроде `access_token`; отклонять такой source до persistence и проверять отсутствие canary в IR. Добавлена проверка чувствительных query keys с redaction; OAuth URL fixture проверяет и безопасный, и секретный вариант.
+ - `[high]` `[patch]` Cookie/Set-Cookie example пропускается — response header example без слова `token` не получает sensitive context; покрыть header/cookie примеры. Добавлен контекст Cookie/Set-Cookie и canary-тест.
+ - `[medium]` `[patch]` credential как ключ объекта example остаётся в pointer/source tree — для распознаваемого token-shaped ключа значение редактируется, а имя ключа нет; редактировать весь example object и указывать безопасный parent pointer. JWT-shaped key приводит к redaction всего example object с parent pointer; canary-тест проходит.
+ - `[low]` `[patch]` transaction-level auth error не локализуется — `From` всегда выдаёт английский текст, хотя `create_openapi_import` знает locale; преобразовать этот вариант на границе import API. В import Apply вариант RegistryError преобразуется с locale; Ru integration test проходит.
+ - `[low]` `[patch]` документация не уточняет zero-based `alternative_index` — код индексирует `Vec` напрямую; добавить одну фразу. В `docs/openapi-import.md` добавлено явное правило нулевой индексации.
+ - `[high]` `[patch]` AC-12 не проверяет перечисленные literal paths — тесты не содержат camelCase/JWT/query URL/Cookie; добавить canary-fixtures к исправлению сканера. `scanner_redacts_contextual_credentials_non_strings_jwts_and_cookie_examples` и OAuth URL fixture добавлены и прошли.
+ - `[high]` `[patch]` тест redacted bearer hint не проверяет safe finding — сейчас проверяется только отсутствие canary в IR; добавить проверку source location и сериализованного finding. Проверяются точный safe pointer, код finding и сериализованный report без canary.
+ - `[high]` `[patch]` edge-case слой подтвердил camelCase/JWT пропуски — тот же `sensitive_key` и `looks_secret_value`, что в строках 1 и 3; покрывается тем же исправлением. Закрыто общей scanner patch и canary-тестами строк 1 и 3.
+ - `[high]` `[patch]` query API-key parameter с произвольным example пропускается — имя параметра и example обходятся отдельно, `in: query` не включает sensitive context; связать context с именем `api_key` и добавить тест. Сканер использует sibling `name`/`in` для example context; canary-тест проходит.
+ - `[false]` `[reject]` API rejection вместо redacted preview finding не означает отсутствия finding — `normalize.rs` создаёт `secret_literal_redacted` в IR, а admin API до persistence отклоняет опасный upload с безопасной ошибкой; контракт не требует сохранять небезопасный source ради preview.
+
+## Design Notes
+
+Pure importer хранит schemes/requirements, но не читает Auth Profiles или Secrets. Workspace-safe lookup принадлежит admin service, authoritative проверка непосредственно перед созданием Draft — registry transaction. Текущий единичный profile reference позволяет выдавать blocker для unsupported AND: это прямо предусмотрено AC и не требует расширения runtime до составного auth.
+
+Проверка literal credentials до `put_registered` позволяет отвергать небезопасный source без изменения bytes принятого immutable snapshot; AC не требует успешного preview для документа с literal secret. Новые формы import API и внутреннее представление alternatives сами по себе являются инженерными решениями, не основанием для остановки.
+
+## Verification
+
+- `cargo test -p crank-import --all-targets` — PASS: 99 tests; security metadata, inheritance, OR/AND, Swagger 2.0, redaction, JWT/cookie/query credential canaries.
+- `cargo test -p admin-api --test integration -- --test-threads=1` — PASS: 88 integration tests; upload, mappings, workspace isolation, Secret availability, replay и digest drift.
+- `cargo test -p crank-runtime --all-targets` — PASS: 83 tests; существующий trusted auth path не менялся.
+- `cargo test -p crank-registry --test integration import_auth_binding -- --test-threads=1` — PASS: 5 tests; transaction revalidation и no-partial-Draft race.
+- `just rust-code-health`, `just dependencies`, `just fmt-check`, `just clippy` — PASS после разнесения oversized модулей, обновления `rustls` в `Cargo.lock` до 0.23.45 и исправления формата теста.
+- `just verify` — PASS: полный workspace gate завершился с exit 0 (через pipe/`tee`). Первый прогон остановился на file-size gate, второй — на устаревшей advisory `RUSTSEC-2026-0285`, третий — на `clippy`, четвёртый — на `rustfmt`, пятый и шестой запуск упали в `crank-artifacts::real_process_write_limit_leaves_no_partial_final_blob` из-за перенаправления stdout в обычный файл: дочерний тест ставит `RLIMIT_FSIZE=1`, и его собственный вывод попал под лимит. Это воспроизведено отдельной командой с редиректом; без него scoped target прошёл 7/7. Финальный полный прогон через pipe/`tee` прошёл; код теста не менялся.
+- После review patch повторный `just verify` — PASS (exit 0): все workspace tests, fmt, clippy, code health и dependency gate. Включены новые scanner canaries и исправленная локализация ошибки binding.
+
+**Matrix test audit:** Schemes, Effective security и Alternatives покрыты `crates/crank-import/tests/security_schemes.rs`; Binding, Credential availability, Shared Secret и Stale source — `apps/admin-api/tests/integration/openapi_import/security.rs` и `crates/crank-registry/tests/integration/import_auth_binding.rs`; Secret source — importer scanner tests, primary/external upload integration и telemetry canary tests. Все указанные story tests и полный workspace gate запускались и прошли.
+
+## Auto Run Result
+
+Status: blocked
+Blocking condition: intent gap
+
+Планирование остановлено до ATDD и реализации. Код, migration, API и tests не изменены. Обновлён локальный epic context и подготовлен этот spec; прохождение AC не заявляется. `sprint-status.yaml` не изменялся и не откатывался.
+
+### Требуемое решение
+
+Определить, что означает «Auth Profile был отозван» в AC Story 2.10:
+
+- Проверять только существующий lifecycle связанных Secrets (active/current version), считая профиль недоступным при отключении credential, а отдельный lifecycle профиля оставить отложенным.
+- Ввести в этой истории независимый отзыв Auth Profile (status/tombstone и соответствующее управление), который запрещает только этот profile ref, сохраняя работоспособность другого профиля с тем же Secret.
+
+Наблюдаемое различие: профили A и B с одним активным Secret. Независимый отзыв A должен отклонить binding A и сохранить binding B; отключение общего Secret отклоняет оба. `AuthProfile` сейчас не имеет status, а отдельный lifecycle явно отложен в Story 1.10 и deferred-work. Поэтому нельзя считать negative test с disabled Secret доказательством независимого отзыва Auth Profile, либо расширить lifecycle/domain/storage scope молча.
+
+Основание остановки: правило `step-02-plan.md`, INSTRUCTIONS 5: “Multiple defensible readings of the intent that lead to observably different outcomes, with nothing in the intent to select between them, are an intent gap — do not resolve one by picking a reading.”
+
+Это пробел нормативного scope, а не внешнее действие оператора. AC не требуют покупки домена, выдачи реального API key или действий в vendor console; `awaiting-operator` к данной остановке не применяется.
+
+### 2026-09-27 — повторный Auto Run Result
+
+Status: done
+
+Реализованы typed security schemes и OR/AND requirements в IR/preview, безопасный выбор Auth Profile при import, повторная проверка Secret/profile в транзакции перед созданием Draft, redaction credential literals и совместимость исторического replay. Небезопасный source отклоняется до сохранения artifacts. Документирован API contract; ATDD сценарии и матрица AC покрыты тестами.
+
+Изменённые файлы:
+
+- `crates/crank-import/src/rest/{model,security,security_literals,normalize*,openapi3*,swagger2*,payload,legacy_payload,mod}.rs` — typed security metadata, effective requirements, безопасный scan/redaction и совместимый replay.
+- `apps/admin-api/src/{dto,error,service/imports*}.rs` — API выбора Auth Profile, проверка mapping и безопасная локализованная ошибка.
+- `crates/crank-registry/src/{model,error,lib,postgres/import_job}.rs` — повторная transaction-level проверка binding до создания Draft.
+- `crates/crank-import/tests/security_schemes.rs`, `apps/admin-api/tests/integration/openapi_import*`, `apps/admin-api/tests/integration/openapi_source*`, `crates/crank-registry/tests/integration*` — acceptance и regression tests, включая race, replay и credential canaries.
+- `docs/openapi-import.md` — контракт import API и индексация alternatives.
+- `_bmad-output/test-artifacts/atdd-{checklist,summary}-2-10-security-schemes-secrets.*` — RED/GREEN и результаты проверок.
+- `Cargo.lock` — обновление `rustls` для dependency gate.
+- Этот spec — матрица AC, Review Triage Log, Verification и итоговый статус.
+
+Review: 13 findings; 12 исправлены (9 high, 1 medium, 2 low), отложенных нет. Один finding отклонён как false: он утверждал, что API rejection не показывает redacted preview finding, но pure importer формирует `secret_literal_redacted`, а Admin API намеренно отклоняет опасный upload до сохранения source; AC не требует сохранять небезопасный source ради preview. Открытых intent gaps нет. Повторный `just verify` прошёл с exit 0 после всех review patches; importer 99/99, Admin API integration 88/88, registry auth-binding 5/5, runtime 83/83.
+
+Остаточный риск: распознавание произвольных секретов без явного контекста остаётся эвристическим. Рекомендована независимая follow-up проверка scanner coverage при дальнейшем расширении форматов. Внешних действий оператора для AC этой истории нет.
diff --git a/_bmad-output/test-artifacts/atdd-checklist-2-10-security-schemes-secrets.md b/_bmad-output/test-artifacts/atdd-checklist-2-10-security-schemes-secrets.md
new file mode 100644
index 0000000..73fc078
--- /dev/null
+++ b/_bmad-output/test-artifacts/atdd-checklist-2-10-security-schemes-secrets.md
@@ -0,0 +1,137 @@
+---
+stepsCompleted: ['step-01-preflight-and-context', 'step-02-generation-mode', 'step-03-test-strategy', 'step-04c-aggregate', 'step-05-validate-and-complete']
+lastStep: 'step-05-validate-and-complete'
+lastSaved: '2026-09-27'
+storyId: '2.10'
+storyKey: '2-10-security-schemes-secrets'
+storyFile: '_bmad-output/implementation-artifacts/spec-2-10-security-schemes-secrets.md'
+atddChecklistPath: '_bmad-output/test-artifacts/atdd-checklist-2-10-security-schemes-secrets.md'
+generatedTestFiles:
+ - 'crates/crank-import/tests/security_schemes.rs'
+ - 'apps/admin-api/tests/integration/openapi_import/security.rs'
+ - 'apps/admin-api/tests/integration/openapi_import/external_references.rs'
+ - 'crates/crank-registry/tests/integration/import_auth_binding.rs'
+inputDocuments:
+ - '_bmad-output/implementation-artifacts/spec-2-10-security-schemes-secrets.md'
+ - '_bmad-output/implementation-artifacts/epic-2-context.md'
+ - '_bmad-output/implementation-artifacts/1-10-lifecycle-auth-profiles-machine-keys.md'
+ - '_bmad-output/implementation-artifacts/spec-2-9-http-contract.md'
+ - '_bmad-output/test-artifacts/test-design-epic-2.md'
+ - '_bmad-output/test-artifacts/test-design-qa.md'
+ - '_bmad/tea/config.yaml'
+ - 'Cargo.toml'
+ - 'apps/admin-api/Cargo.toml'
+ - 'crates/crank-import/Cargo.toml'
+ - 'crates/crank-runtime/Cargo.toml'
+acceptanceCriteria:
+ - id: AC-1
+ idSource: generated
+ text: 'Given OpenAPI 3.x components.securitySchemes или Swagger 2.0 securityDefinitions; When importer анализирует schemes; Then bearer HTTP, basic HTTP и API key в header/query/cookie преобразуются в typed security metadata; And source names, locations и применимые format hints сохраняются без credential values.'
+ - id: AC-2
+ idSource: generated
+ text: 'Given global security requirement; When Operation не задаёт собственный override; Then candidate наследует global requirement согласно specification semantics; And operation-level requirement или explicit no-auth корректно заменяет global rule.'
+ - id: AC-3
+ idSource: generated
+ text: 'Given security requirement с несколькими alternatives; When source определяет OR-семантику; Then preview сохраняет все допустимые alternatives и позволяет выбрать поддерживаемый вариант; And importer не объединяет alternatives в ложное обязательное AND.'
+ - id: AC-4
+ idSource: generated
+ text: 'Given security requirement, требующий несколько schemes одновременно; When source определяет AND-семантику; Then candidate сохраняет составное требование, если runtime contract его поддерживает; And иначе affected Operation получает blocker finding с перечислением несохраняемой semantics.'
+ - id: AC-5
+ idSource: generated
+ text: 'Given bearer, basic или API-key requirement; When формируется preview; Then администратору предлагается выбрать совместимый Auth Profile из текущего workspace либо оставить явный unresolved binding; And unresolved required authentication блокирует actionable Draft/Apply для affected Operation.'
+ - id: AC-6
+ idSource: generated
+ text: 'Given выбранный Auth Profile; When создаётся candidate или ImportPlan; Then сохраняется только typed AuthProfileRef и scheme metadata; And raw secret, password, token, API key, hash или encrypted ciphertext не копируется в source snapshot, IR, findings, plan или Operation export.'
+ - id: AC-7
+ idSource: generated
+ text: 'Given OAuth2, OpenID Connect, mutual TLS или неизвестная scheme; When release scope не поддерживает автоматическое mapping; Then importer создаёт explicit manual-configuration/unsupported finding; And не извлекает client secret, token URL credential, example token или vendor-extension secret.'
+ - id: AC-8
+ idSource: generated
+ text: 'Given OpenAPI document содержит literal credential в example, default, extension, URL userinfo или header example; When security analysis выполняется; Then значение не используется как credential и создаёт redacted secret finding; And raw value не появляется в preview UI, logs, traces, metrics или diagnostics.'
+ - id: AC-9
+ idSource: generated
+ text: 'Given Auth Profile отсутствует/удалён, принадлежит другому workspace либо любой необходимый связанный Secret недоступен по существующим правилам active/current version; When preview либо Apply проверяет binding; Then reference отклоняется до создания Draft; And ошибка не раскрывает metadata foreign profile.'
+ - id: AC-10
+ idSource: generated
+ text: 'Given профили A и B используют один активный Secret с доступной текущей версией; When проверяются binding этих профилей; Then оба binding допустимы при выполнении остальных проверок; And после отключения общего Secret оба binding отклоняются до создания Draft; тест с disabled Secret не является доказательством независимого отзыва Auth Profile, который остаётся вне scope.'
+ - id: AC-11
+ idSource: generated
+ text: 'Given исходная security scheme изменилась после preview; When старый ImportPlan пытаются применить к новому source; Then plan digest mismatch блокирует Apply; And требуется новый preview и явное подтверждение Auth Profile mappings.'
+ - id: AC-12
+ idSource: generated
+ text: 'Given security scheme test suite; When выполняются fixtures и negative tests; Then покрыты global/operation overrides, no-auth, bearer/basic/API-key locations, OR/AND requirements, OAuth/OpenID/unknown schemes, secret-like examples, missing/deleted и cross-workspace profile refs, недоступные Secrets по правилам active/current version и блокировка обоих профилей при отключении общего Secret; And redaction tests и `just verify` проходят.'
+---
+
+# ATDD Checklist — Story 2.10: Security Schemes and Secrets
+
+## Preflight
+
+- **Approval/source:** the approved, frozen acceptance contract is the Story 2.10 spec. Its recorded 2026-09-13 decision defines binding availability through the existing active/current Secret rules; it does not add independent Auth Profile revocation.
+- **Story identity:** ID `2.10`; canonical key `2-10-security-schemes-secrets` from the spec filename.
+- **Stack and harness:** repository is Rust backend plus an existing UI. This story's approved scope is API/parser/runtime, so primary level is Rust unit/integration/API contract; UI/E2E belongs to Story 2.11. `cargo test` and `just verify` are configured.
+- **Risk and design:** P0, FR-10, E2-R2 (score 9), seed scenarios `2.10-API-A` and `2.10-API-B`. The epic test design calls for preserving security semantics and rejecting unsupported/foreign bindings, with secret canaries absent from API/IR/plan/export surfaces.
+- **Implementation observation:** security metadata now flows through typed IR/preview; Admin API accepts profile mappings, rejects unsafe literals before persistence, and validates binding availability within Apply. Current verification evidence is recorded below and is scoped to the commands actually run.
+- **Generation mode:** backend/API source analysis. No browser recording; no Story 2.11 UI scaffolds.
+- **Contract boundary:** implementation added focused tests in the existing importer, Admin API and registry harnesses. No skipped or placeholder tests are used as evidence.
+
+## Acceptance Criteria Snapshot and Scenario Mapping
+
+AC IDs below are deterministic IDs assigned in source order because the spec does not declare `AC-` IDs. The exact snapshot is also stored in frontmatter.
+
+| Scenario | AC | Test level / priority | Primary reusable test path | Required scenario and current status |
+|---|---|---|---|---|
+| 2.10-API-A1 | AC-1 | Importer unit / P0 | `security_alternatives_preserve_or_and_and_preview_exposes_typed_schemes`; `swagger2_security_definitions_project_basic_and_api_key_header_and_query` in `crates/crank-import/tests/security_schemes.rs` | **PASS** in importer suite: OpenAPI typed scheme metadata and Swagger 2.0 basic/API-key locations are projected. |
+| 2.10-API-A2 | AC-2 | Importer unit / P0 | `security_requirements_inherit_and_operation_empty_array_disables_auth` in `crates/crank-import/tests/security_schemes.rs` | **PASS** in importer suite: global inheritance, multi-scheme operation requirement, explicit empty override. |
+| 2.10-API-A3 | AC-3 | Importer + preview API / P0 | `security_alternatives_preserve_or_and_and_preview_exposes_typed_schemes`; `selected_supported_or_and_explicit_no_auth_alternatives_apply_without_collapsing_semantics` in `apps/admin-api/tests/integration/openapi_import/security.rs` | **PASS** in importer and Admin API integration suites: OR alternatives remain distinct and selected supported option applies. |
+| 2.10-API-A4 | AC-4 | Importer unit + preview API / P0 | `security_requirements_inherit_and_operation_empty_array_disables_auth`; `security_alternatives_preserve_or_and_and_preview_exposes_typed_schemes` in `crates/crank-import/tests/security_schemes.rs` | **PASS** in importer suite: AND composition is retained and unsupported composition becomes a blocker. |
+| 2.10-API-B1 | AC-5 | Admin API integration / P0 | `auth_profiles_are_workspace_scoped_revalidated_and_shared_secret_availability_is_current`; `selected_supported_or_and_explicit_no_auth_alternatives_apply_without_collapsing_semantics` in `apps/admin-api/tests/integration/openapi_import/security.rs` | **PASS** in Admin API integration suite: choices are workspace-scoped, supported mapping applies, unresolved required auth is blocked. |
+| 2.10-API-B2 | AC-6 | Importer + API/registry integration / P0 | `ac_6_never_copies_literal_secret_canaries_into_normalized_ir` in `crates/crank-import/tests/security_schemes.rs`; `auth_profiles_are_workspace_scoped_revalidated_and_shared_secret_availability_is_current` in `apps/admin-api/tests/integration/openapi_import/security.rs`; `no_auth_requires_no_profile_reference` in `crates/crank-registry/tests/integration/import_auth_binding.rs` | **PASS** in importer, Admin API and registry suites. Tests assert canary/ciphertext/hash absence from IR/serialized Operation and no profile ref for no-auth. |
+| 2.10-API-A5 | AC-7 | Importer unit / P0 | `unsupported_security_schemes_create_blockers_without_copying_credentials` in `crates/crank-import/tests/security_schemes.rs` | **PASS** in importer suite: OAuth/OIDC/mTLS/unknown produce explicit unsupported/blocker findings without credential extraction. |
+| 2.10-API-A6 | AC-8 | Importer + Admin API integration / P0 | `scanner_finds_examples_defaults_extensions_and_url_userinfo_without_values`; `scanner_redacts_contextual_credentials_non_strings_jwts_and_cookie_examples`; `scanner_keeps_version_examples_and_null_credential_defaults`; `unsafe_bearer_format_canary_is_redacted_and_not_projected` in `crates/crank-import/tests/security_schemes.rs`; `literal_credential_is_rejected_before_any_import_artifact_or_job_is_created` in Admin API `security.rs`; `external_literal_credential_is_rejected_before_snapshot_persistence` in `external_references.rs` | **PASS** in importer/Admin API suites: canaries redact from findings and literal credentials are rejected before primary or external source persistence. |
+| 2.10-API-B3 | AC-9 | Admin API + registry integration / P0 | `auth_profiles_are_workspace_scoped_revalidated_and_shared_secret_availability_is_current` in Admin API `security.rs`; `missing_and_foreign_profiles_have_the_same_safe_error_and_insert_no_operation`; `apply_rejects_kind_parameter_and_missing_current_version_before_mutation` in `crates/crank-registry/tests/integration/import_auth_binding.rs` | **PASS** in Admin API and registry suites. Foreign/missing errors are indistinguishable and no Draft mutation occurs. |
+| 2.10-API-B4 | AC-10 | Admin API + registry integration / P0 | `auth_profiles_are_workspace_scoped_revalidated_and_shared_secret_availability_is_current` in Admin API `security.rs`; `apply_accepts_current_compatible_profile_and_shared_secret_then_rejects_disabled_secret` in `crates/crank-registry/tests/integration/import_auth_binding.rs` | **PASS** in Admin API and registry suites. Shared Secret permits both profiles while active and rejects them when disabled; independent profile revocation is not asserted. |
+| 2.10-API-B5 | AC-11 | Admin API integration / P0 | `changed_security_scheme_after_preview_fails_digest_check_without_draft_mutation` in `apps/admin-api/tests/integration/openapi_import/security.rs` | **PASS** in Admin API integration suite: stale digest blocks Apply without creating Draft. |
+| 2.10-API-GATE | AC-12 | Suite / P0 | `cargo test -p crank-import --all-targets`; `cargo test -p admin-api --test integration openapi_import -- --test-threads=1`; `cargo test -p crank-registry --test integration import_auth_binding -- --test-threads=1`; `just verify` | Importer, Admin API and registry suites **PASS**; final `just verify` **PASS**. Earlier failed attempts were repaired; the unrelated artifact subprocess failure was caused by redirecting stdout to a regular file and disappeared when the gate ran through a pipe. |
+
+### Reuse inventory (not a claim of AC coverage)
+
+- Importer behavior patterns: `crates/crank-import/tests/security_schemes.rs`, `swagger2_contract.rs`, `unit.rs`, `preview.rs`, and `http_replay.rs`.
+- API/import persistence patterns: `apps/admin-api/tests/integration/openapi_import/http_contract.rs` and `external_references.rs`.
+- Runtime auth injection patterns: `crates/crank-runtime/tests/stages.rs` and `integration/confirmation.rs`.
+- The AC rows point to the actual tests observed in the current implementation. Importer, Admin API and registry test runs are complete; broad `just verify` has now passed.
+
+## Test Strategy and TDD State
+
+- **Primary level:** importer unit tests for pure OpenAPI semantics; Admin API + registry integration for profile scope, secret availability, transaction revalidation, and no-Draft guarantees; runtime tests only for unchanged trusted credential injection behavior.
+- **Duplicate coverage:** do not duplicate existing general reference, source digest, redaction, or runtime-auth tests. Add assertions only for the Story 2.10 security contract and its import boundary.
+- **Fixture requirements:** OAS 3.0, OAS 3.1, and Swagger 2.0 docs; deterministic secret canaries in example/default/extension/userinfo/header-example positions; workspace A/B profiles sharing one Secret; active/current and disabled Secret states; source mutation after preview. Never use customer credentials.
+- **Assertion order:** primary assertion checks the exact promised value/state (typed scheme/effective requirement, blocker, absence of Draft, or digest rejection) before broad serialized-object checks. Setup results from an unimplemented endpoint remain opaque until the criterion assertion.
+- **TDD record:** the initial two active tests genuinely failed before implementation (historical RED below); after implementation both now pass. No skipped tests are counted as RED or GREEN evidence.
+
+## Handoff
+
+- Story-level importer, Admin API and registry evidence is recorded above; all scenarios mapped to AC-1..AC-11 passed in those suites.
+- AC-12 is satisfied: full `just verify` completed successfully. Earlier gate failures were fixed or traced to the output-redirection harness.
+- Runtime suite: root reports `cargo test -p crank-runtime --all-targets` passed (83 tests).
+
+## Historical RED Evidence (Before Implementation)
+
+`cargo test -p crank-import --test normalization_details -- --nocapture` failed as intended: 11 passed, 2 failed, 0 ignored. AC-1 failed because `WorkspaceBearer` was absent from operation projection; AC-6 failed because `atdd-secret-canary-2-10` appeared in normalized IR. These failures were fixed by implementation and the tests now pass.
+
+## Verification Results (Current Worktree)
+
+| Command | Result | Interpretation |
+|---|---|---|
+| `cargo test -p crank-import --all-targets` | **PASS** — 99 tests passed, 0 failed, 0 ignored. | Includes security normalization, OpenAPI/Swagger mapping and redaction cases after review fixes. |
+| `cargo test -p admin-api --test integration openapi_import -- --test-threads=1` | **PASS** — 24 passed, 0 failed, 0 ignored; 64 filtered out. | Includes mapping choices, literal-credential rejection, workspace/profile revalidation, shared Secret availability and digest drift. |
+| `cargo test -p crank-registry --test integration import_auth_binding -- --test-threads=1` | **PASS** — 5 passed, 0 failed, 0 ignored; 95 filtered out. | Includes transaction-level profile, Secret state, no-auth and no-partial-mutation checks. |
+| `cargo test -p crank-runtime --all-targets` | **PASS** — 83 passed, 0 failed, 0 ignored (result reported by root). | Runtime regression suite is green; no security scheme behavior is implemented in the runtime crate. |
+| `just verify` | **PASS** — full workspace gate finished with exit 0, including fmt, clippy, dependencies and all workspace tests. | Earlier failures were corrected; artifact subprocess needed a pipe instead of regular-file stdout. |
+| `git diff --check` | **PASS**. | No whitespace errors in current diff. |
+
+## Completion Summary
+
+- Story ID/key: `2.10` / `2-10-security-schemes-secrets`.
+- AC snapshot: 12 source criteria mapped one-to-one to scenario IDs.
+- Tests: security-specific tests were added to existing importer, Admin API and registry suites. The scenario table maps each AC to exact test names and package-level evidence.
+- Current evidence after review fixes: importer 99/99, Admin API integration 88/88, registry auth-binding integration 5/5. Historical RED is retained separately; repeat full `just verify` passed.
diff --git a/_bmad-output/test-artifacts/atdd-summary-2-10-security-schemes-secrets.json b/_bmad-output/test-artifacts/atdd-summary-2-10-security-schemes-secrets.json
new file mode 100644
index 0000000..8847b1b
--- /dev/null
+++ b/_bmad-output/test-artifacts/atdd-summary-2-10-security-schemes-secrets.json
@@ -0,0 +1,81 @@
+{
+ "story_id": "2.10",
+ "story_key": "2-10-security-schemes-secrets",
+ "story_file": "_bmad-output/implementation-artifacts/spec-2-10-security-schemes-secrets.md",
+ "checklist": "_bmad-output/test-artifacts/atdd-checklist-2-10-security-schemes-secrets.md",
+ "tdd_phase": "GREEN",
+ "acceptance_criteria_total": 12,
+ "active_red_tests": 0,
+ "historical_red_tests": [
+ {
+ "scenario": "2.10-API-A1",
+ "acceptance_criterion": "AC-1",
+ "test": "security_schemes::ac_1_projects_openapi_security_scheme_identity_onto_operation_metadata",
+ "result": "FAIL_BEFORE_IMPLEMENTATION_THEN_PASS",
+ "observed": "operation projection does not contain WorkspaceBearer"
+ },
+ {
+ "scenario": "2.10-API-B2",
+ "acceptance_criterion": "AC-6",
+ "test": "security_schemes::ac_6_never_copies_literal_secret_canaries_into_normalized_ir",
+ "result": "FAIL_BEFORE_IMPLEMENTATION_THEN_PASS",
+ "observed": "normalized IR contains atdd-secret-canary-2-10"
+ }
+ ],
+ "pending_acceptance_criteria": [],
+ "generated_test_files": [
+ "crates/crank-import/tests/security_schemes.rs",
+ "apps/admin-api/tests/integration/openapi_import/security.rs",
+ "apps/admin-api/tests/integration/openapi_import/external_references.rs",
+ "crates/crank-registry/tests/integration/import_auth_binding.rs"
+ ],
+ "existing_suite_baseline": {
+ "command": "cargo test -p crank-import --all-targets",
+ "result": "PASS",
+ "passed": 99,
+ "failed": 0,
+ "ignored": 0,
+ "timing": "current implementation"
+ },
+ "other_passed_suites": [
+ {
+ "command": "cargo test -p admin-api --test integration openapi_import -- --test-threads=1",
+ "result": "PASS",
+ "passed": 24,
+ "failed": 0,
+ "ignored": 0,
+ "filtered_out": 64
+ },
+ {
+ "command": "cargo test -p crank-registry --test integration import_auth_binding -- --test-threads=1",
+ "result": "PASS",
+ "passed": 5,
+ "failed": 0,
+ "ignored": 0,
+ "filtered_out": 95
+ },
+ {
+ "command": "cargo test -p crank-runtime --all-targets",
+ "result": "PASS",
+ "passed": 83,
+ "failed": 0,
+ "ignored": 0,
+ "reported_by": "root"
+ }
+ ],
+ "other_checks": [
+ {
+ "command": "just verify",
+ "result": "PASS",
+ "detail": "Repeat full workspace gate after review fixes exited 0; earlier file-size, advisory, fmt/clippy and stdout-redirection failures were resolved."
+ },
+ {
+ "command": "git diff --check",
+ "result": "PASS"
+ }
+ ],
+ "all_tests_skipped": false,
+ "expected_to_fail": false,
+ "e2e_tests": 0,
+ "note": "Historical RED evidence is preserved; all active acceptance tests and the final just verify gate pass. No skipped scaffold is counted as RED."
+}
diff --git a/apps/admin-api/src/dto.rs b/apps/admin-api/src/dto.rs
index 4f22489..7237796 100644
--- a/apps/admin-api/src/dto.rs
+++ b/apps/admin-api/src/dto.rs
@@ -542,17 +542,48 @@ pub struct OpenApiImportPreviewResponse {
pub job_id: String,
pub expires_at: String,
pub preview: crank_import::rest::ImportPreview,
+ /// Compatible Auth Profiles visible to the current workspace, grouped by
+ /// operation and security alternative. Profile credentials are never
+ /// included.
+ pub auth_profile_choices: Vec,
+}
+
+#[derive(Clone, Debug, Serialize)]
+pub struct OpenApiAuthProfileChoice {
+ pub operation_key: String,
+ pub alternative_index: usize,
+ pub scheme_names: Vec,
+ pub supported: bool,
+ pub profiles: Vec,
+}
+
+#[derive(Clone, Debug, Serialize)]
+pub struct OpenApiAuthProfileOption {
+ pub id: String,
+ pub name: String,
+ pub kind: AuthKind,
}
#[derive(Clone, Debug, Deserialize)]
pub struct OpenApiImportCreatePayload {
pub selected_operation_keys: Vec,
#[serde(default)]
+ pub auth_mappings: Vec,
+ #[serde(default)]
pub server_url: Option,
#[serde(default = "default_openapi_conflict_mode")]
pub conflict_mode: String,
}
+#[derive(Clone, Debug, Deserialize, Serialize)]
+pub struct OpenApiAuthMapping {
+ pub operation_key: String,
+ pub alternative_index: usize,
+ /// `None` is an explicit unresolved mapping. It is never actionable for a
+ /// required authentication alternative.
+ pub auth_profile_id: Option,
+}
+
#[derive(Clone, Debug, Serialize)]
pub struct OpenApiImportCreateResponse {
pub created: Vec,
diff --git a/apps/admin-api/src/error.rs b/apps/admin-api/src/error.rs
index cbc4bc1..12e3b32 100644
--- a/apps/admin-api/src/error.rs
+++ b/apps/admin-api/src/error.rs
@@ -135,6 +135,41 @@ impl ApiError {
"OpenAPI document is invalid or unsupported"
}
}
+ (_, "literal_credentials_rejected") => {
+ if russian {
+ "документ OpenAPI содержит literal credential и отклонён"
+ } else {
+ "OpenAPI document contains literal credential material and was rejected"
+ }
+ }
+ (_, "auth_mapping_required") => {
+ if russian {
+ "для требования аутентификации выберите доступный профиль"
+ } else {
+ "an available Auth Profile mapping is required for this authentication requirement"
+ }
+ }
+ (_, "auth_mapping_unsupported") => {
+ if russian {
+ "это требование аутентификации не поддерживается импортом"
+ } else {
+ "this authentication requirement is not supported by import"
+ }
+ }
+ (_, "auth_mapping_invalid") => {
+ if russian {
+ "привязка аутентификации в запросе импорта некорректна"
+ } else {
+ "OpenAPI import authentication mapping is invalid"
+ }
+ }
+ (_, "auth_binding_unavailable") => {
+ if russian {
+ "выбранный профиль аутентификации недоступен для этого импорта"
+ } else {
+ "selected Auth Profile is unavailable for this import"
+ }
+ }
(_, "no_methods") => {
if russian {
"документ OpenAPI не содержит поддерживаемых методов"
@@ -195,6 +230,18 @@ impl ApiError {
}
}
+ pub(crate) fn openapi_auth_binding_unavailable(locale: OpenApiUploadLocale) -> Self {
+ let message = if locale == OpenApiUploadLocale::Ru {
+ "выбранный профиль аутентификации недоступен для этого импорта"
+ } else {
+ "selected Auth Profile is unavailable for this import"
+ };
+ Self::unprocessable_with_context(
+ message,
+ json!({ "error_code": "openapi_auth_binding_unavailable" }),
+ )
+ }
+
pub(crate) fn rate_limited_with_context(message: impl Into, context: Value) -> Self {
Self::RateLimited {
message: message.into(),
@@ -675,6 +722,10 @@ impl From for ApiError {
"value": value,
}),
),
+ RegistryError::ImportAuthBindingUnavailable => Self::unprocessable_with_context(
+ "selected Auth Profile is unavailable for this import",
+ json!({ "error_code": "openapi_auth_binding_unavailable" }),
+ ),
RegistryError::YamlImportJobNotFound { job_id } => Self::validation_with_context(
format!("yaml import job {job_id} was not found"),
json!({ "job_id": job_id }),
diff --git a/apps/admin-api/src/import_guidance.rs b/apps/admin-api/src/import_guidance.rs
index 65949bc..5b0a948 100644
--- a/apps/admin-api/src/import_guidance.rs
+++ b/apps/admin-api/src/import_guidance.rs
@@ -134,9 +134,13 @@ mod tests {
method: HttpMethod::Delete,
path_template: "/items/{id}".to_owned(),
static_headers: BTreeMap::new(),
+ request_contract: None,
+ response_contract: Vec::new(),
+ multipart_field_mime_types: BTreeMap::new(),
}),
input_schema: Schema {
kind: SchemaKind::Object,
+ format: None,
description: None,
required: true,
nullable: false,
@@ -148,6 +152,7 @@ mod tests {
},
output_schema: Schema {
kind: SchemaKind::Object,
+ format: None,
description: None,
required: false,
nullable: false,
@@ -198,6 +203,7 @@ mod tests {
fn string_schema() -> Schema {
Schema {
kind: SchemaKind::String,
+ format: None,
description: None,
required: true,
nullable: false,
diff --git a/apps/admin-api/src/service/demo.rs b/apps/admin-api/src/service/demo.rs
index 8d12fa3..3b71562 100644
--- a/apps/admin-api/src/service/demo.rs
+++ b/apps/admin-api/src/service/demo.rs
@@ -421,6 +421,9 @@ fn demo_rest_operation_payload() -> OperationPayload {
method: crank_core::HttpMethod::Get,
path_template: "/v1/latest".to_owned(),
static_headers: BTreeMap::from([("Accept".to_owned(), "application/json".to_owned())]),
+ request_contract: None,
+ response_contract: Vec::new(),
+ multipart_field_mime_types: BTreeMap::new(),
}),
input_schema: Schema::from_json_sample(&input),
output_schema: Schema::from_json_sample(&output),
diff --git a/apps/admin-api/src/service/imports.rs b/apps/admin-api/src/service/imports.rs
index 36be097..95e33d2 100644
--- a/apps/admin-api/src/service/imports.rs
+++ b/apps/admin-api/src/service/imports.rs
@@ -12,8 +12,8 @@ use crank_import::rest::{
use crank_registry::{
ApplyImportJobRequest, ArtifactSourceId, ArtifactSourceSensitivity,
CreateArtifactSourceRequest, CreateImportJobRequest, FinishImportJobRequest,
- ImportConflictMode, ImportJobApplyResult, ImportJobId, ImportJobKind, ImportJobSourceEnvelope,
- ImportJobStatus, ImportOperationDraft, RegistryError,
+ ImportAuthRequirement, ImportConflictMode, ImportJobApplyResult, ImportJobId, ImportJobKind,
+ ImportJobSourceEnvelope, ImportJobStatus, ImportOperationDraft, RegistryError,
};
use serde_json::json;
use sha2::{Digest, Sha256};
@@ -23,7 +23,7 @@ use tracing::{info, instrument};
use crate::{
error::ApiError,
service::{
- AdminService, OpenApiImportCreatePayload, OpenApiImportCreateResponse,
+ AdminService, OpenApiAuthMapping, OpenApiImportCreatePayload, OpenApiImportCreateResponse,
OpenApiImportCreatedOperation, OpenApiImportPreviewResponse, OpenApiImportSkippedOperation,
OpenApiUpload, OpenApiUploadLocale, OperationPayload, new_prefixed_id,
},
@@ -31,6 +31,7 @@ use crate::{
mod external_references;
mod job_contract;
+mod security;
use external_references::ImportReplayContext;
use job_contract::{
SourceDetachGuard, import_job_dependencies, import_job_normalization_config, import_job_source,
@@ -52,6 +53,14 @@ impl AdminService {
self.ensure_workspace_exists(workspace_id).await?;
validate_openapi_upload(&upload)?;
+ let literal_findings = crank_import::rest::scan_secret_literals(&upload.bytes)
+ .map_err(|_| ApiError::openapi_upload(upload.locale, "invalid_document"))?;
+ if !literal_findings.is_empty() {
+ return Err(ApiError::openapi_upload(
+ upload.locale,
+ "literal_credentials_rejected",
+ ));
+ }
let OpenApiUpload {
bytes,
mime_type,
@@ -105,6 +114,14 @@ impl AdminService {
let mut dependencies = self
.materialize_external_reference_snapshots(workspace_id, &verified.bytes, now)
.await;
+ if dependencies.secret_literal_rejected {
+ dependencies.detach_all().await;
+ detach_guard.detach_now().await;
+ return Err(ApiError::openapi_upload(
+ locale,
+ "literal_credentials_rejected",
+ ));
+ }
let parsed = match parse_verified_preview(
verified.bytes,
artifact.artifact_ref().digest_hex().to_owned(),
@@ -132,6 +149,17 @@ impl AdminService {
detach_guard.detach_now().await;
return Err(ApiError::openapi_upload(locale, "no_methods"));
}
+ let auth_profile_choices = match self
+ .openapi_auth_profile_choices(workspace_id, &parsed.preview)
+ .await
+ {
+ Ok(choices) => choices,
+ Err(error) => {
+ dependencies.detach_all().await;
+ detach_guard.detach_now().await;
+ return Err(error);
+ }
+ };
let source_envelope = ImportJobSourceEnvelope {
source_id,
digest: artifact.artifact_ref().clone(),
@@ -184,6 +212,7 @@ impl AdminService {
expires_at: expires_at
.format(&Rfc3339)
.map_err(|error| ApiError::internal(error.to_string()))?,
+ auth_profile_choices,
preview: parsed.preview,
})
}
@@ -247,6 +276,15 @@ impl AdminService {
));
}
let finished_at = OffsetDateTime::now_utc();
+ let mut auth_mappings = BTreeMap::new();
+ for mapping in &payload.auth_mappings {
+ if auth_mappings
+ .insert(mapping.operation_key.clone(), mapping)
+ .is_some()
+ {
+ return Err(ApiError::openapi_upload(locale, "auth_mapping_invalid"));
+ }
+ }
let application_key = openapi_application_key(&payload)?;
let conflict_mode = if payload.conflict_mode == "skip" {
ImportConflictMode::Skip
@@ -425,6 +463,20 @@ impl AdminService {
candidates.insert(operation.key.clone(), operation);
}
}
+ if auth_mappings.iter().any(|(operation_key, mapping)| {
+ !selected.contains(operation_key)
+ || candidates.get(operation_key).is_none_or(|candidate| {
+ mapping.alternative_index >= candidate.security_requirements.alternatives.len()
+ })
+ }) {
+ return self
+ .fail_openapi_import_or_replay(
+ &replay_context,
+ "auth_mapping_invalid",
+ ApiError::openapi_upload(locale, "auth_mapping_invalid"),
+ )
+ .await;
+ }
let mut skipped = Vec::new();
let mut operations = Vec::new();
@@ -438,6 +490,26 @@ impl AdminService {
});
continue;
};
+ let (auth_profile_ref, auth_requirement) = match self
+ .resolve_openapi_auth_binding(
+ workspace_id,
+ candidate,
+ auth_mappings.get(&operation_key).copied(),
+ locale,
+ )
+ .await
+ {
+ Ok(binding) => binding,
+ Err(error) => {
+ return self
+ .fail_openapi_import_or_replay(
+ &replay_context,
+ "auth_binding_unavailable",
+ error,
+ )
+ .await;
+ }
+ };
let mut draft =
operation_draft_from_candidate(candidate, payload.server_url.as_deref());
attach_import_findings(&mut draft, candidate);
@@ -459,7 +531,7 @@ impl AdminService {
idempotency: None,
safety: None,
approval_policy: None,
- auth_profile_ref: None,
+ auth_profile_ref,
headers: BTreeMap::new(),
},
tool_description: draft.tool_description,
@@ -468,6 +540,7 @@ impl AdminService {
operations.push(ImportOperationDraft {
operation_key: candidate.key.clone(),
operation,
+ auth_requirement,
});
}
@@ -482,7 +555,13 @@ impl AdminService {
pre_skipped: &skipped,
finished_at: &finished_at,
})
- .await?;
+ .await
+ .map_err(|error| match error {
+ RegistryError::ImportAuthBindingUnavailable => {
+ ApiError::openapi_auth_binding_unavailable(locale)
+ }
+ error => error.into(),
+ })?;
Ok(openapi_import_response(applied))
}
@@ -639,7 +718,14 @@ fn import_replay_contract(
if normalizer == NORMALIZER_VERSION && projection == PROJECTION_VERSION {
return Ok(ImportReplayContract::Current);
}
- if normalizer != "normalized-ir-v2" || projection != "preview-v2" {
+ // Historical v2-v4 preview payloads are replayed as their persisted
+ // projection. They must never be parsed again with current v5 semantics.
+ if !matches!(
+ (normalizer, projection),
+ ("normalized-ir-v2", "preview-v2")
+ | ("normalized-ir-v3", "preview-v3")
+ | ("normalized-ir-v4", "preview-v4")
+ ) {
return Err(ApiError::openapi_upload(locale, "source_integrity"));
}
@@ -812,7 +898,15 @@ fn preview_has_blocker(
.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)
+ .any(|finding| {
+ finding.severity == ImportFindingSeverity::Error
+ && !matches!(
+ finding.code.as_str(),
+ "unsupported_security_and_requirement"
+ | "unsupported_security_scheme"
+ | "unresolved_security_scheme"
+ )
+ })
}
fn openapi_application_key(payload: &OpenApiImportCreatePayload) -> Result {
@@ -821,8 +915,15 @@ fn openapi_application_key(payload: &OpenApiImportCreatePayload) -> Result>();
+ let mut auth_mappings = payload.auth_mappings.clone();
+ auth_mappings.sort_by(|left, right| {
+ left.operation_key
+ .cmp(&right.operation_key)
+ .then(left.alternative_index.cmp(&right.alternative_index))
+ });
let canonical = serde_json::to_vec(&json!({
"selected_operation_keys": selected_operation_keys,
+ "auth_mappings": auth_mappings,
"server_url": payload.server_url.as_deref(),
"conflict_mode": payload.conflict_mode.as_str(),
}))
diff --git a/apps/admin-api/src/service/imports/external_references.rs b/apps/admin-api/src/service/imports/external_references.rs
index b12c37b..c2b6260 100644
--- a/apps/admin-api/src/service/imports/external_references.rs
+++ b/apps/admin-api/src/service/imports/external_references.rs
@@ -4,6 +4,7 @@ use tracing::warn;
pub(super) struct MaterializedDependencies {
pub(super) snapshots: Vec,
+ pub(super) secret_literal_rejected: bool,
envelopes: Vec,
canonical_uris: Vec,
guards: Vec,
@@ -21,6 +22,7 @@ impl MaterializedDependencies {
fn empty() -> Self {
Self {
snapshots: Vec::new(),
+ secret_literal_rejected: false,
envelopes: Vec::new(),
canonical_uris: Vec::new(),
guards: Vec::new(),
@@ -207,6 +209,26 @@ impl AdminService {
);
continue;
};
+ match crank_import::rest::scan_secret_literals(&bytes) {
+ Ok(findings) if !findings.is_empty() => {
+ materialization_failure(
+ "security_scan",
+ "literal_credentials_rejected",
+ result.snapshots.len(),
+ );
+ result.secret_literal_rejected = true;
+ break;
+ }
+ Ok(_) => {}
+ Err(_) => {
+ materialization_failure(
+ "security_scan",
+ "invalid_document",
+ result.snapshots.len(),
+ );
+ continue;
+ }
+ }
let Ok(references) = crank_import::rest::external_reference_uris(
&document,
&self.external_reference_normalization,
@@ -368,6 +390,14 @@ impl AdminService {
}
let document = String::from_utf8(verified.bytes)
.map_err(|_| ApiError::openapi_upload(locale, "source_integrity"))?;
+ let findings = crank_import::rest::scan_secret_literals(document.as_bytes())
+ .map_err(|_| ApiError::openapi_upload(locale, "source_integrity"))?;
+ if !findings.is_empty() {
+ return Err(ApiError::openapi_upload(
+ locale,
+ "literal_credentials_rejected",
+ ));
+ }
let digest =
crank_import::rest::SourceDigest::parse(dependency.digest.digest_hex().to_owned())
.map_err(|_| ApiError::openapi_upload(locale, "source_integrity"))?;
diff --git a/apps/admin-api/src/service/imports/security.rs b/apps/admin-api/src/service/imports/security.rs
new file mode 100644
index 0000000..5220b3f
--- /dev/null
+++ b/apps/admin-api/src/service/imports/security.rs
@@ -0,0 +1,195 @@
+use super::*;
+use crate::service::{OpenApiAuthProfileChoice, OpenApiAuthProfileOption};
+use crank_core::{AuthConfig, AuthProfile, AuthProfileId};
+
+impl AdminService {
+ pub(super) async fn openapi_auth_profile_choices(
+ &self,
+ workspace_id: &WorkspaceId,
+ preview: &crank_import::rest::ImportPreview,
+ ) -> Result, ApiError> {
+ let mut profiles = self
+ .registry
+ .list_auth_profiles(workspace_id)
+ .await?
+ .into_iter()
+ .filter(|profile| profile.kind == profile.config.kind())
+ .collect::>();
+ let mut available_profiles = Vec::with_capacity(profiles.len());
+ for profile in profiles.drain(..) {
+ if auth_profile_is_available(&self.registry, workspace_id, &profile).await? {
+ available_profiles.push(profile);
+ }
+ }
+ let mut choices = Vec::new();
+ for operation in preview
+ .groups
+ .iter()
+ .flat_map(|group| group.operations.iter())
+ {
+ for (alternative_index, alternative) in operation
+ .security_requirements
+ .alternatives
+ .iter()
+ .enumerate()
+ {
+ let scheme = (alternative.schemes.len() == 1)
+ .then(|| operation.security_schemes.get(&alternative.schemes[0]))
+ .flatten();
+ let requirement = scheme.and_then(import_auth_requirement);
+ let supported = alternative.supported
+ && (alternative.schemes.is_empty() || requirement.is_some());
+ let options = requirement
+ .as_ref()
+ .map(|requirement| {
+ available_profiles
+ .iter()
+ .filter(|profile| auth_profile_matches(profile, requirement))
+ .map(|profile| OpenApiAuthProfileOption {
+ id: profile.id.as_str().to_owned(),
+ name: profile.name.clone(),
+ kind: profile.kind,
+ })
+ .collect()
+ })
+ .unwrap_or_default();
+ choices.push(OpenApiAuthProfileChoice {
+ operation_key: operation.key.clone(),
+ alternative_index,
+ scheme_names: alternative.schemes.clone(),
+ supported,
+ profiles: options,
+ });
+ }
+ }
+ Ok(choices)
+ }
+
+ pub(super) async fn resolve_openapi_auth_binding(
+ &self,
+ workspace_id: &WorkspaceId,
+ candidate: &ImportOperationCandidate,
+ mapping: Option<&OpenApiAuthMapping>,
+ locale: OpenApiUploadLocale,
+ ) -> Result<(Option, Option), ApiError> {
+ let alternatives = &candidate.security_requirements.alternatives;
+ if alternatives.is_empty() {
+ return if mapping.is_none() {
+ Ok((None, None))
+ } else {
+ Err(ApiError::openapi_upload(locale, "auth_mapping_invalid"))
+ };
+ }
+ let mapping =
+ mapping.ok_or_else(|| ApiError::openapi_upload(locale, "auth_mapping_required"))?;
+ let alternative = alternatives
+ .get(mapping.alternative_index)
+ .ok_or_else(|| ApiError::openapi_upload(locale, "auth_mapping_invalid"))?;
+ if !alternative.supported {
+ return Err(ApiError::openapi_upload(locale, "auth_mapping_unsupported"));
+ }
+ if alternative.schemes.is_empty() {
+ return if mapping.auth_profile_id.is_none() {
+ Ok((None, None))
+ } else {
+ Err(ApiError::openapi_upload(locale, "auth_mapping_invalid"))
+ };
+ }
+ if alternative.schemes.len() != 1 {
+ return Err(ApiError::openapi_upload(locale, "auth_mapping_unsupported"));
+ }
+ let scheme = candidate
+ .security_schemes
+ .get(&alternative.schemes[0])
+ .ok_or_else(|| ApiError::openapi_upload(locale, "auth_mapping_unsupported"))?;
+ let requirement = import_auth_requirement(scheme)
+ .ok_or_else(|| ApiError::openapi_upload(locale, "auth_mapping_unsupported"))?;
+ let profile_id = mapping
+ .auth_profile_id
+ .as_deref()
+ .filter(|value| !value.is_empty())
+ .ok_or_else(|| ApiError::openapi_upload(locale, "auth_mapping_required"))?;
+ let profile_id = AuthProfileId::new(profile_id.to_owned());
+ let profile = self
+ .registry
+ .get_auth_profile(workspace_id, &profile_id)
+ .await?
+ .ok_or_else(|| ApiError::openapi_auth_binding_unavailable(locale))?;
+ if !auth_profile_matches(&profile, &requirement)
+ || !auth_profile_is_available(&self.registry, workspace_id, &profile).await?
+ {
+ return Err(ApiError::openapi_auth_binding_unavailable(locale));
+ }
+ Ok((Some(profile_id), Some(requirement)))
+ }
+}
+
+fn import_auth_requirement(
+ scheme: &crank_import::rest::NormalizedSecurityScheme,
+) -> Option {
+ use crank_import::rest::{NormalizedSecuritySchemeKind, SecurityParameterLocation};
+
+ match &scheme.kind {
+ NormalizedSecuritySchemeKind::Http { scheme, .. }
+ if scheme.eq_ignore_ascii_case("bearer") =>
+ {
+ Some(ImportAuthRequirement::Bearer)
+ }
+ NormalizedSecuritySchemeKind::Http { scheme, .. }
+ if scheme.eq_ignore_ascii_case("basic") =>
+ {
+ Some(ImportAuthRequirement::Basic)
+ }
+ NormalizedSecuritySchemeKind::ApiKey {
+ location: SecurityParameterLocation::Header,
+ parameter_name,
+ ..
+ } => Some(ImportAuthRequirement::ApiKeyHeader {
+ parameter_name: parameter_name.clone(),
+ }),
+ NormalizedSecuritySchemeKind::ApiKey {
+ location: SecurityParameterLocation::Query,
+ parameter_name,
+ ..
+ } => Some(ImportAuthRequirement::ApiKeyQuery {
+ parameter_name: parameter_name.clone(),
+ }),
+ _ => None,
+ }
+}
+
+fn auth_profile_matches(profile: &AuthProfile, requirement: &ImportAuthRequirement) -> bool {
+ if profile.kind != profile.config.kind() {
+ return false;
+ }
+ match (requirement, &profile.config) {
+ (ImportAuthRequirement::Bearer, AuthConfig::Bearer(_))
+ | (ImportAuthRequirement::Basic, AuthConfig::Basic(_)) => true,
+ (
+ ImportAuthRequirement::ApiKeyHeader { parameter_name },
+ AuthConfig::ApiKeyHeader(config),
+ ) => config.header_name.eq_ignore_ascii_case(parameter_name),
+ (
+ ImportAuthRequirement::ApiKeyQuery { parameter_name },
+ AuthConfig::ApiKeyQuery(config),
+ ) => config.param_name == *parameter_name,
+ _ => false,
+ }
+}
+
+async fn auth_profile_is_available(
+ registry: &crank_registry::PostgresRegistry,
+ workspace_id: &WorkspaceId,
+ profile: &AuthProfile,
+) -> Result {
+ for secret_id in profile.config.secret_ids() {
+ if registry
+ .get_current_secret_version(workspace_id, secret_id)
+ .await?
+ .is_none()
+ {
+ return Ok(false);
+ }
+ }
+ Ok(true)
+}
diff --git a/apps/admin-api/src/service/operation_validation.rs b/apps/admin-api/src/service/operation_validation.rs
index 8f7de41..a535186 100644
--- a/apps/admin-api/src/service/operation_validation.rs
+++ b/apps/admin-api/src/service/operation_validation.rs
@@ -93,7 +93,14 @@ pub(super) fn validate_idempotency_policy(
}
match target {
- Target::Rest(rest_target) if rest_target.method != crank_core::HttpMethod::Get => {}
+ Target::Rest(rest_target)
+ if matches!(
+ rest_target.method,
+ crank_core::HttpMethod::Post
+ | crank_core::HttpMethod::Put
+ | crank_core::HttpMethod::Patch
+ | crank_core::HttpMethod::Delete
+ ) => {}
_ => {
return Err(ApiError::validation_with_context(
"idempotency is supported only for mutating REST operations".to_owned(),
@@ -206,6 +213,9 @@ mod tests {
method: HttpMethod::Get,
path_template: "/catalog".to_owned(),
static_headers: BTreeMap::new(),
+ request_contract: None,
+ response_contract: Vec::new(),
+ multipart_field_mime_types: BTreeMap::new(),
});
let result = validate_response_cache_policy(&target, &cacheable_execution_config());
@@ -233,6 +243,9 @@ mod tests {
method: HttpMethod::Post,
path_template: "/catalog".to_owned(),
static_headers: BTreeMap::new(),
+ request_contract: None,
+ response_contract: Vec::new(),
+ multipart_field_mime_types: BTreeMap::new(),
});
let error =
@@ -252,6 +265,9 @@ mod tests {
method: HttpMethod::Post,
path_template: "/orders".to_owned(),
static_headers: BTreeMap::new(),
+ request_contract: None,
+ response_contract: Vec::new(),
+ multipart_field_mime_types: BTreeMap::new(),
});
let result = validate_idempotency_policy(
@@ -269,6 +285,9 @@ mod tests {
method: HttpMethod::Get,
path_template: "/orders".to_owned(),
static_headers: BTreeMap::new(),
+ request_contract: None,
+ response_contract: Vec::new(),
+ multipart_field_mime_types: BTreeMap::new(),
});
let error = validate_idempotency_policy(
@@ -291,6 +310,9 @@ mod tests {
method: HttpMethod::Post,
path_template: "/orders".to_owned(),
static_headers: BTreeMap::new(),
+ request_contract: None,
+ response_contract: Vec::new(),
+ multipart_field_mime_types: BTreeMap::new(),
});
let mut config = idempotent_execution_config(IdempotencyMode::Required);
let policy = config.idempotency.as_mut().unwrap();
diff --git a/apps/admin-api/tests/integration/common.rs b/apps/admin-api/tests/integration/common.rs
index bf59278..06f450f 100644
--- a/apps/admin-api/tests/integration/common.rs
+++ b/apps/admin-api/tests/integration/common.rs
@@ -435,6 +435,9 @@ pub(super) fn test_operation_payload(base_url: &str, name: &str) -> OperationPay
method: HttpMethod::Post,
path_template: "/crm/leads".to_owned(),
static_headers: BTreeMap::new(),
+ request_contract: None,
+ response_contract: Vec::new(),
+ multipart_field_mime_types: BTreeMap::new(),
}),
input_schema: object_schema("email"),
output_schema: object_schema("id"),
@@ -483,6 +486,7 @@ pub(super) fn test_operation_payload(base_url: &str, name: &str) -> OperationPay
pub(super) fn object_schema(field_name: &str) -> Schema {
Schema {
kind: SchemaKind::Object,
+ format: None,
description: None,
required: true,
nullable: false,
@@ -491,6 +495,7 @@ pub(super) fn object_schema(field_name: &str) -> Schema {
field_name.to_owned(),
Schema {
kind: SchemaKind::String,
+ format: None,
description: None,
required: true,
nullable: false,
diff --git a/apps/admin-api/tests/integration/community_access_usage.rs b/apps/admin-api/tests/integration/community_access_usage.rs
index 8475e1e..acd1f2b 100644
--- a/apps/admin-api/tests/integration/community_access_usage.rs
+++ b/apps/admin-api/tests/integration/community_access_usage.rs
@@ -323,6 +323,9 @@ async fn rejects_response_cache_for_operation_with_auth_profile() {
method: HttpMethod::Get,
path_template: "/crm/leads".to_owned(),
static_headers: BTreeMap::new(),
+ request_contract: None,
+ response_contract: Vec::new(),
+ multipart_field_mime_types: BTreeMap::new(),
});
payload.execution_config.response_cache = Some(ResponseCachePolicy { ttl_ms: 5_000 });
payload.execution_config.auth_profile_ref = Some("auth_profile_01".into());
diff --git a/apps/admin-api/tests/integration/openapi_import.rs b/apps/admin-api/tests/integration/openapi_import.rs
index 650c6b3..d0a4f96 100644
--- a/apps/admin-api/tests/integration/openapi_import.rs
+++ b/apps/admin-api/tests/integration/openapi_import.rs
@@ -1,15 +1,23 @@
use admin_api::service::{
- AdminServiceBuilder, OpenApiImportCreatePayload, OpenApiUpload, OpenApiUploadLocale,
+ AdminServiceBuilder, AuthProfilePayload, OpenApiAuthMapping, OpenApiImportCreatePayload,
+ OpenApiImportCreateResponse, OpenApiUpload, OpenApiUploadLocale, SecretPayload,
};
-use crank_core::WorkspaceId;
-use crank_registry::ImportJobStatus;
+use crank_core::{
+ AuthConfig, AuthKind, BearerAuthConfig, SecretId, SecretKind, Workspace, WorkspaceId,
+ WorkspaceStatus,
+};
+use crank_registry::{CreateWorkspaceRequest, ImportJobStatus};
+use serde_json::json;
use serial_test::serial;
+use sha2::Digest;
use super::common::{
test_auth_settings, test_registry, test_secret_crypto, test_service, test_storage_root,
};
mod external_references;
+mod http_contract;
+mod security;
const OPENAPI3: &str = r#"
openapi: 3.0.3
@@ -77,11 +85,11 @@ async fn previews_openapi_and_creates_draft_operations() {
assert_eq!(preview_job.status, ImportJobStatus::Pending);
assert_eq!(
preview_job.preview_payload["normalization"]["normalizer_version"],
- "normalized-ir-v3"
+ "normalized-ir-v5"
);
assert_eq!(
preview_job.preview_payload["normalization"]["projection_version"],
- "preview-v3"
+ "preview-v5"
);
assert!(preview_job.preview_payload["normalization"]["ir_fingerprint"].is_string());
@@ -91,6 +99,7 @@ async fn previews_openapi_and_creates_draft_operations() {
&preview.job_id.as_str().into(),
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
+ auth_mappings: vec![],
server_url: Some("https://api.frankfurter.dev".to_owned()),
conflict_mode: "skip".to_owned(),
},
@@ -109,6 +118,7 @@ async fn previews_openapi_and_creates_draft_operations() {
&preview.job_id.as_str().into(),
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
+ auth_mappings: vec![],
server_url: Some("https://api.frankfurter.dev".to_owned()),
conflict_mode: "skip".to_owned(),
},
@@ -161,6 +171,7 @@ async fn previews_openapi_and_creates_draft_operations() {
&skip_preview.job_id.as_str().into(),
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
+ auth_mappings: vec![],
server_url: Some("https://api.frankfurter.dev".to_owned()),
conflict_mode: "skip".to_owned(),
},
@@ -183,6 +194,7 @@ async fn previews_openapi_and_creates_draft_operations() {
&rename_preview.job_id.as_str().into(),
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
+ auth_mappings: vec![],
server_url: Some("https://api.frankfurter.dev".to_owned()),
conflict_mode: "rename".to_owned(),
},
@@ -212,6 +224,7 @@ async fn unknown_selected_operations_are_persisted_in_the_canonical_replay() {
.unwrap();
let payload = OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /v2/latest".to_owned(), "GET /missing".to_owned()],
+ auth_mappings: vec![],
server_url: Some("https://api.frankfurter.dev".to_owned()),
conflict_mode: "skip".to_owned(),
};
@@ -253,6 +266,7 @@ async fn concurrent_openapi_import_replays_the_same_atomic_result() {
let job_id = preview.job_id.as_str().into();
let payload = OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
+ auth_mappings: vec![],
server_url: Some("https://api.frankfurter.dev".to_owned()),
conflict_mode: "rename".to_owned(),
};
@@ -307,6 +321,7 @@ async fn concurrent_openapi_import_replays_the_same_atomic_result() {
&job_id,
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
+ auth_mappings: vec![],
server_url: Some("https://api.frankfurter.dev".to_owned()),
conflict_mode: "skip".to_owned(),
},
@@ -348,6 +363,7 @@ async fn apply_fails_closed_when_the_preview_parser_contract_drifts() {
&job_id,
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
+ auth_mappings: vec![],
server_url: Some("https://api.frankfurter.dev".to_owned()),
conflict_mode: "rename".to_owned(),
},
@@ -424,6 +440,7 @@ async fn apply_fails_closed_for_each_normalization_contract_field_and_digest_sha
&job_id,
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
+ auth_mappings: vec![],
server_url: Some("https://api.frankfurter.dev".to_owned()),
conflict_mode: "rename".to_owned(),
}
@@ -451,6 +468,8 @@ async fn apply_fails_closed_for_each_normalization_contract_field_and_digest_sha
#[tokio::test]
#[serial]
async fn legacy_job_without_normalization_contract_replays_until_expiry() {
+ use sha2::{Digest, Sha256};
+
let registry = test_registry().await;
let service = test_service(
registry.clone(),
@@ -464,10 +483,22 @@ async fn legacy_job_without_normalization_contract_replays_until_expiry() {
.await
.unwrap();
let job_id: crank_registry::ImportJobId = preview.job_id.as_str().into();
+ // A legacy job stores the legacy projection and its matching fingerprint,
+ // not a current projection with only the version metadata removed.
+ let legacy_preview =
+ serde_json::to_value(crank_import::rest::preview_document_legacy_v1(OPENAPI3).unwrap())
+ .unwrap();
+ let legacy_digest = format!(
+ "{:x}",
+ Sha256::digest(serde_json::to_vec(&legacy_preview).unwrap())
+ );
sqlx::query(
- "update import_jobs set preview_payload = preview_payload - 'normalization' where id = $1",
+ "update import_jobs set preview_payload = (preview_payload - 'normalization') || \
+ jsonb_build_object('preview', $2::jsonb, 'preview_digest', $3::text) where id = $1",
)
.bind(job_id.as_str())
+ .bind(legacy_preview)
+ .bind(legacy_digest)
.execute(registry.pool())
.await
.unwrap();
@@ -478,6 +509,7 @@ async fn legacy_job_without_normalization_contract_replays_until_expiry() {
&job_id,
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
+ auth_mappings: vec![],
server_url: Some("https://api.frankfurter.dev".to_owned()),
conflict_mode: "skip".to_owned(),
},
@@ -532,6 +564,7 @@ paths:
&preview.job_id.as_str().into(),
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /valid".to_owned()],
+ auth_mappings: vec![],
server_url: None,
conflict_mode: "skip".to_owned(),
},
@@ -619,6 +652,7 @@ paths:
&valid_preview.job_id.as_str().into(),
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /valid".to_owned()],
+ auth_mappings: vec![],
server_url: None,
conflict_mode: "skip".to_owned(),
},
@@ -637,6 +671,7 @@ paths:
&full_preview.job_id.as_str().into(),
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /valid".to_owned(), "GET /broken".to_owned()],
+ auth_mappings: vec![],
server_url: None,
conflict_mode: "rename".to_owned(),
},
@@ -718,6 +753,7 @@ components:
&preview.job_id.as_str().into(),
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /referenced".to_owned()],
+ auth_mappings: vec![],
server_url: None,
conflict_mode: "skip".to_owned(),
},
diff --git a/apps/admin-api/tests/integration/openapi_import/external_references.rs b/apps/admin-api/tests/integration/openapi_import/external_references.rs
index 24d0e5b..e9a6e88 100644
--- a/apps/admin-api/tests/integration/openapi_import/external_references.rs
+++ b/apps/admin-api/tests/integration/openapi_import/external_references.rs
@@ -99,6 +99,7 @@ paths:
&preview.job_id.as_str().into(),
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /items".to_owned()],
+ auth_mappings: vec![],
server_url: None,
conflict_mode: "skip".to_owned(),
},
@@ -117,6 +118,73 @@ paths:
assert_eq!(active_sources, 0);
}
+#[tokio::test]
+#[serial]
+async fn external_literal_credential_is_rejected_before_snapshot_persistence() {
+ let canary = "external-atdd-secret-canary-2-10";
+ let app = Router::new().route(
+ "/schemas.yaml",
+ get(move || async move {
+ format!(
+ "Item: {{ type: object, properties: {{ token: {{ type: string, example: '{canary}' }} }} }}"
+ )
+ }),
+ );
+ 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_external_literal_credential"),
+ vec![format!("{origin}/")],
+ );
+ let workspace_id = WorkspaceId::new("ws_default");
+ let upload = OpenApiUpload {
+ bytes: format!(
+ r#"
+openapi: 3.1.0
+info: {{ title: External secret canary }}
+paths:
+ /items:
+ get:
+ responses:
+ '200':
+ description: ok
+ content:
+ application/json:
+ schema: {{ $ref: '{origin}/schemas.yaml#/Item' }}
+"#
+ )
+ .into_bytes(),
+ mime_type: "application/yaml".to_owned(),
+ locale: OpenApiUploadLocale::En,
+ };
+
+ let error = service
+ .preview_openapi_import(&workspace_id, upload)
+ .await
+ .unwrap_err();
+ assert!(!format!("{error:?}").contains(canary));
+ let dependency_sources: i64 = sqlx::query_scalar(
+ "select count(*) from artifact_sources
+ where workspace_id = $1 and source_id like 'src_openapi_dep_%'",
+ )
+ .bind(workspace_id.as_str())
+ .fetch_one(registry.pool())
+ .await
+ .unwrap();
+ let import_jobs: i64 =
+ sqlx::query_scalar("select count(*) from import_jobs where workspace_id = $1")
+ .bind(workspace_id.as_str())
+ .fetch_one(registry.pool())
+ .await
+ .unwrap();
+ assert_eq!(dependency_sources, 0);
+ assert_eq!(import_jobs, 0);
+}
+
#[tokio::test]
#[serial]
async fn missing_external_snapshot_fails_closed_before_draft_mutation() {
@@ -188,6 +256,7 @@ paths:
&preview.job_id.as_str().into(),
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /items".to_owned()],
+ auth_mappings: vec![],
server_url: None,
conflict_mode: "skip".to_owned(),
},
@@ -270,6 +339,7 @@ paths:
&corrupt_preview.job_id.as_str().into(),
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /items".to_owned()],
+ auth_mappings: vec![],
server_url: None,
conflict_mode: "skip".to_owned(),
},
@@ -522,6 +592,155 @@ async fn exact_v2_contract_replays_persisted_preview_without_v3_or_dependency_re
&job_id,
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
+ auth_mappings: vec![],
+ server_url: Some("https://api.frankfurter.dev".to_owned()),
+ conflict_mode: "skip".to_owned(),
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(result.created.len(), 1);
+ let completed = registry
+ .get_import_job(&workspace_id, &job_id)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(completed.status, ImportJobStatus::Completed);
+}
+
+#[tokio::test]
+#[serial]
+async fn exact_v3_contract_replays_persisted_preview_without_v4_or_dependency_reads() {
+ let registry = test_registry().await;
+ let service = test_service(
+ registry.clone(),
+ test_storage_root("openapi_import_v3_compatibility"),
+ test_auth_settings(),
+ test_secret_crypto(),
+ );
+ let workspace_id = WorkspaceId::new("ws_default");
+ let preview = service
+ .preview_openapi_import(&workspace_id, openapi_upload())
+ .await
+ .unwrap();
+ let job_id: crank_registry::ImportJobId = preview.job_id.as_str().into();
+ let missing_dependency = serde_json::json!([{
+ "source_id": "src_openapi_dep_v3_must_not_be_read",
+ "digest": format!("sha256:{}", "0".repeat(64)),
+ "canonical_uri": "https://schemas.example.test/v3.yaml"
+ }]);
+ sqlx::query(
+ "update import_jobs
+ set preview_payload = jsonb_set(
+ jsonb_set(
+ jsonb_set(
+ jsonb_set(
+ preview_payload,
+ '{normalization,normalizer_version}',
+ to_jsonb('normalized-ir-v3'::text)
+ ),
+ '{normalization,projection_version}',
+ to_jsonb('preview-v3'::text)
+ ),
+ '{normalization,ir_fingerprint}',
+ to_jsonb($1::text)
+ ),
+ '{dependency_snapshots}',
+ $2::jsonb
+ )
+ where id = $3",
+ )
+ .bind("a".repeat(64))
+ .bind(missing_dependency)
+ .bind(job_id.as_str())
+ .execute(registry.pool())
+ .await
+ .unwrap();
+
+ let result = service
+ .create_openapi_import(
+ &workspace_id,
+ &job_id,
+ OpenApiImportCreatePayload {
+ selected_operation_keys: vec!["GET /v2/latest".to_owned()],
+ auth_mappings: vec![],
+ server_url: Some("https://api.frankfurter.dev".to_owned()),
+ conflict_mode: "skip".to_owned(),
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(result.created.len(), 1);
+ let completed = registry
+ .get_import_job(&workspace_id, &job_id)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(completed.status, ImportJobStatus::Completed);
+}
+
+#[tokio::test]
+#[serial]
+async fn exact_v4_contract_replays_legacy_preview_without_v5_reparse_or_dependency_reads() {
+ use sha2::Digest;
+
+ let registry = test_registry().await;
+ let service = test_service(
+ registry.clone(),
+ test_storage_root("openapi_import_v4_compatibility"),
+ test_auth_settings(),
+ test_secret_crypto(),
+ );
+ let workspace_id = WorkspaceId::new("ws_default");
+ let preview = service
+ .preview_openapi_import(&workspace_id, openapi_upload())
+ .await
+ .unwrap();
+ let job_id: crank_registry::ImportJobId = preview.job_id.as_str().into();
+ let mut job = registry
+ .get_import_job(&workspace_id, &job_id)
+ .await
+ .unwrap()
+ .unwrap();
+ let missing_dependency = serde_json::json!([{
+ "source_id": "src_openapi_dep_v4_must_not_be_read",
+ "digest": format!("sha256:{}", "0".repeat(64)),
+ "canonical_uri": "https://schemas.example.test/v4.yaml"
+ }]);
+ let mut persisted_preview = job.preview_payload["preview"].clone();
+ for group in persisted_preview["groups"].as_array_mut().unwrap() {
+ for operation in group["operations"].as_array_mut().unwrap() {
+ let object = operation.as_object_mut().unwrap();
+ object.remove("security_requirements");
+ object.remove("security_schemes");
+ }
+ }
+ let expected_preview_digest = format!(
+ "{:x}",
+ sha2::Sha256::digest(serde_json::to_vec(&persisted_preview).unwrap())
+ );
+ job.preview_payload["preview"] = persisted_preview;
+ job.preview_payload["preview_digest"] = serde_json::json!(expected_preview_digest);
+ job.preview_payload["normalization"]["normalizer_version"] =
+ serde_json::json!("normalized-ir-v4");
+ job.preview_payload["normalization"]["projection_version"] = serde_json::json!("preview-v4");
+ job.preview_payload["normalization"]["ir_fingerprint"] = serde_json::json!("a".repeat(64));
+ job.preview_payload["dependency_snapshots"] = missing_dependency;
+ sqlx::query("update import_jobs set preview_payload = $1 where workspace_id = $2 and id = $3")
+ .bind(&job.preview_payload)
+ .bind(workspace_id.as_str())
+ .bind(job_id.as_str())
+ .execute(registry.pool())
+ .await
+ .unwrap();
+
+ let result = service
+ .create_openapi_import(
+ &workspace_id,
+ &job_id,
+ OpenApiImportCreatePayload {
+ selected_operation_keys: vec!["GET /v2/latest".to_owned()],
+ auth_mappings: vec![],
server_url: Some("https://api.frankfurter.dev".to_owned()),
conflict_mode: "skip".to_owned(),
},
diff --git a/apps/admin-api/tests/integration/openapi_import/http_contract.rs b/apps/admin-api/tests/integration/openapi_import/http_contract.rs
new file mode 100644
index 0000000..34ee401
--- /dev/null
+++ b/apps/admin-api/tests/integration/openapi_import/http_contract.rs
@@ -0,0 +1,298 @@
+use super::*;
+
+use crank_core::Target;
+use serde_json::json;
+
+#[tokio::test]
+#[serial]
+async fn http_contract_preview_apply_and_replay_preserve_json_multipart_schemas_mapping_and_mime() {
+ let registry = test_registry().await;
+ let service = test_service(
+ registry.clone(),
+ test_storage_root("openapi_import_http_contract_replay"),
+ test_auth_settings(),
+ test_secret_crypto(),
+ );
+ let workspace_id = WorkspaceId::new("ws_default");
+ let preview = service
+ .preview_openapi_import(&workspace_id, rich_http_contract_upload())
+ .await
+ .unwrap();
+ let job_id: crank_registry::ImportJobId = preview.job_id.as_str().into();
+ let persisted_preview_before_apply = registry
+ .get_import_job(&workspace_id, &job_id)
+ .await
+ .unwrap()
+ .unwrap()
+ .preview_payload["preview"]
+ .clone();
+ assert_eq!(
+ persisted_preview_before_apply,
+ serde_json::to_value(&preview.preview).unwrap()
+ );
+
+ let operations = preview
+ .preview
+ .groups
+ .iter()
+ .flat_map(|group| group.operations.iter())
+ .collect::>();
+ assert_eq!(operations.len(), 1, "media variants must not split a Tool");
+ let candidate = operations[0];
+ assert_eq!(candidate.key, "POST /documents");
+ assert!(
+ candidate.findings.iter().all(|finding| {
+ finding.severity != crank_import::rest::ImportFindingSeverity::Error
+ })
+ );
+
+ let json_arguments = json!({
+ "content_type": "application/json",
+ "body": {"title": "Quarterly report"}
+ });
+ let multipart_arguments = json!({
+ "content_type": "multipart/form-data",
+ "body": {
+ "file": {
+ "data_base64": "AA==",
+ "filename": "report.png",
+ "content_type": "image/png"
+ },
+ "caption": "Quarterly report"
+ }
+ });
+ candidate
+ .draft
+ .input_schema
+ .validate_shape(&json_arguments)
+ .unwrap();
+ candidate
+ .draft
+ .input_schema
+ .validate_shape(&multipart_arguments)
+ .unwrap();
+ assert!(
+ candidate
+ .draft
+ .input_schema
+ .validate_shape(&json!({
+ "content_type": "multipart/form-data",
+ "body": {"title": "wrong branch"}
+ }))
+ .is_err()
+ );
+
+ let mapped = candidate
+ .draft
+ .input_mapping
+ .apply(&json!({"mcp": multipart_arguments}))
+ .unwrap();
+ assert_eq!(
+ mapped["request"]["body_content_type"],
+ "multipart/form-data"
+ );
+ assert_eq!(mapped["request"]["body"]["file"]["data_base64"], "AA==");
+
+ let preview_target = &candidate.draft.target;
+ let preview_contract = preview_target.request_contract.as_ref().unwrap();
+ assert_eq!(preview_contract.body_field, "body");
+ assert_eq!(
+ preview_contract.selector_field.as_deref(),
+ Some("content_type")
+ );
+ assert_eq!(preview_contract.variants.len(), 2);
+ assert_eq!(
+ preview_target.multipart_field_mime_types["multipart/form-data"]["file"],
+ ["image/png", "image/jpeg"]
+ );
+
+ let payload = OpenApiImportCreatePayload {
+ selected_operation_keys: vec![candidate.key.clone()],
+ auth_mappings: vec![],
+ server_url: None,
+ conflict_mode: "skip".to_owned(),
+ };
+ let created = service
+ .create_openapi_import(&workspace_id, &job_id, payload.clone())
+ .await
+ .unwrap();
+ assert_eq!(created.created.len(), 1);
+
+ let replayed = service
+ .create_openapi_import(&workspace_id, &job_id, payload)
+ .await
+ .unwrap();
+ assert_eq!(replayed.created, created.created);
+ let persisted_preview_after_replay = registry
+ .get_import_job(&workspace_id, &job_id)
+ .await
+ .unwrap()
+ .unwrap()
+ .preview_payload["preview"]
+ .clone();
+ assert_eq!(
+ persisted_preview_after_replay,
+ persisted_preview_before_apply
+ );
+
+ let version = service
+ .get_operation_version(
+ &workspace_id,
+ &created.created[0].operation_id.as_str().into(),
+ created.created[0].version,
+ )
+ .await
+ .unwrap();
+ assert_eq!(version.snapshot.input_schema, candidate.draft.input_schema);
+ assert_eq!(
+ version.snapshot.output_schema,
+ candidate.draft.output_schema
+ );
+ assert_eq!(
+ version.snapshot.input_mapping,
+ candidate.draft.input_mapping
+ );
+ assert_eq!(
+ version.snapshot.output_mapping,
+ candidate.draft.output_mapping
+ );
+ assert_eq!(
+ version.snapshot.target,
+ Target::Rest(candidate.draft.target.clone())
+ );
+}
+
+#[tokio::test]
+#[serial]
+async fn xml_and_unsupported_media_block_apply_without_registry_mutation() {
+ let registry = test_registry().await;
+ let service = test_service(
+ registry.clone(),
+ test_storage_root("openapi_import_http_contract_blockers"),
+ test_auth_settings(),
+ test_secret_crypto(),
+ );
+ let workspace_id = WorkspaceId::new("ws_default");
+ let preview = service
+ .preview_openapi_import(&workspace_id, unsupported_media_upload())
+ .await
+ .unwrap();
+ let candidate = preview
+ .preview
+ .groups
+ .iter()
+ .flat_map(|group| group.operations.iter())
+ .find(|operation| operation.key == "POST /blocked")
+ .unwrap();
+ assert!(candidate.findings.iter().any(|finding| {
+ finding.code == "unsupported_xml_request_media_type"
+ && finding.severity == crank_import::rest::ImportFindingSeverity::Error
+ }));
+ assert!(candidate.findings.iter().any(|finding| {
+ finding.code == "unsupported_request_media_type"
+ && finding.severity == crank_import::rest::ImportFindingSeverity::Error
+ }));
+
+ assert!(
+ service
+ .create_openapi_import(
+ &workspace_id,
+ &preview.job_id.as_str().into(),
+ OpenApiImportCreatePayload {
+ selected_operation_keys: vec![candidate.key.clone()],
+ auth_mappings: vec![],
+ server_url: None,
+ conflict_mode: "skip".to_owned(),
+ },
+ )
+ .await
+ .is_err()
+ );
+ assert!(
+ service
+ .list_operations(&workspace_id)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+
+ let job = registry
+ .get_import_job(&workspace_id, &preview.job_id.as_str().into())
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(job.status, ImportJobStatus::Failed);
+ assert_eq!(
+ job.error_text.as_deref(),
+ Some("reference_resolution_blocked")
+ );
+}
+
+fn rich_http_contract_upload() -> OpenApiUpload {
+ OpenApiUpload {
+ bytes: br#"
+openapi: 3.0.3
+info: { title: Document import }
+servers: [{ url: https://api.example.test/v1 }]
+paths:
+ /documents:
+ post:
+ operationId: importDocument
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ type: object
+ required: [title]
+ properties:
+ title: { type: string }
+ multipart/form-data:
+ schema:
+ type: object
+ required: [file]
+ properties:
+ file: { type: string, format: binary }
+ caption: { type: string }
+ encoding:
+ file: { contentType: 'image/png, image/jpeg' }
+ responses:
+ '201':
+ description: Created
+ content:
+ application/json:
+ schema: { type: object, properties: { id: { type: string } } }
+"#
+ .to_vec(),
+ mime_type: "application/yaml".to_owned(),
+ locale: OpenApiUploadLocale::En,
+ }
+}
+
+fn unsupported_media_upload() -> OpenApiUpload {
+ OpenApiUpload {
+ bytes: br#"
+openapi: 3.0.3
+info: { title: Unsupported request media }
+servers: [{ url: https://api.example.test/v1 }]
+paths:
+ /blocked:
+ post:
+ operationId: blockedMedia
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema: { type: object, properties: { name: { type: string } } }
+ application/xml:
+ schema: { type: string }
+ application/pdf:
+ schema: { type: string, format: binary }
+ responses:
+ '200': { description: OK }
+"#
+ .to_vec(),
+ mime_type: "application/yaml".to_owned(),
+ locale: OpenApiUploadLocale::En,
+ }
+}
diff --git a/apps/admin-api/tests/integration/openapi_import/security.rs b/apps/admin-api/tests/integration/openapi_import/security.rs
new file mode 100644
index 0000000..afb2b86
--- /dev/null
+++ b/apps/admin-api/tests/integration/openapi_import/security.rs
@@ -0,0 +1,659 @@
+use super::*;
+
+#[tokio::test]
+#[serial]
+async fn literal_credential_is_rejected_before_any_import_artifact_or_job_is_created() {
+ let registry = test_registry().await;
+ let service = test_service(
+ registry.clone(),
+ test_storage_root("openapi_import_literal_credential_rejected"),
+ test_auth_settings(),
+ test_secret_crypto(),
+ );
+ let workspace_id = WorkspaceId::new("ws_default");
+ let canary = "atdd-secret-canary-2-10-api";
+ let upload = OpenApiUpload {
+ bytes: format!(
+ r#"
+openapi: 3.0.3
+info: {{ title: Secret canary }}
+paths:
+ /items:
+ get:
+ responses:
+ '200': {{ description: ok }}
+x-api-key: {canary}
+"#
+ )
+ .into_bytes(),
+ mime_type: "application/yaml".to_owned(),
+ locale: OpenApiUploadLocale::En,
+ };
+
+ let error = service
+ .preview_openapi_import(&workspace_id, upload)
+ .await
+ .unwrap_err();
+ assert!(!format!("{error:?}").contains(canary));
+ let import_jobs: i64 =
+ sqlx::query_scalar("select count(*) from import_jobs where workspace_id = $1")
+ .bind(workspace_id.as_str())
+ .fetch_one(registry.pool())
+ .await
+ .unwrap();
+ let artifact_sources: i64 =
+ sqlx::query_scalar("select count(*) from artifact_sources where workspace_id = $1")
+ .bind(workspace_id.as_str())
+ .fetch_one(registry.pool())
+ .await
+ .unwrap();
+ assert_eq!(import_jobs, 0);
+ assert_eq!(artifact_sources, 0);
+}
+
+#[tokio::test]
+#[serial]
+async fn auth_profiles_are_workspace_scoped_revalidated_and_shared_secret_availability_is_current()
+{
+ let registry = test_registry().await;
+ let service = test_service(
+ registry.clone(),
+ test_storage_root("openapi_import_auth_profile_binding"),
+ test_auth_settings(),
+ test_secret_crypto(),
+ );
+ let workspace_id = WorkspaceId::new("ws_default");
+ let secret = service
+ .create_secret(
+ &workspace_id,
+ None,
+ SecretPayload {
+ name: "shared-openapi-token".to_owned(),
+ kind: SecretKind::Token,
+ value: json!("integration-secret-canary"),
+ },
+ None,
+ )
+ .await
+ .unwrap();
+ let ciphertext = registry
+ .get_current_secret_version(&workspace_id, &secret.id)
+ .await
+ .unwrap()
+ .unwrap()
+ .secret_version
+ .ciphertext;
+ let secret_hash = format!("{:x}", sha2::Sha256::digest(b"integration-secret-canary"));
+ let profile_a = create_bearer_profile(&service, &workspace_id, "profile-a", &secret.id).await;
+ let profile_b = create_bearer_profile(&service, &workspace_id, "profile-b", &secret.id).await;
+
+ let preview = service
+ .preview_openapi_import(&workspace_id, two_protected_operations_upload())
+ .await
+ .unwrap();
+ assert_eq!(preview.auth_profile_choices.len(), 2);
+ for choice in &preview.auth_profile_choices {
+ assert!(choice.supported);
+ assert_eq!(choice.profiles.len(), 2);
+ }
+ let response = serde_json::to_string(&preview).unwrap();
+ assert!(!response.contains("integration-secret-canary"));
+
+ let applied = service
+ .create_openapi_import(
+ &workspace_id,
+ &preview.job_id.as_str().into(),
+ OpenApiImportCreatePayload {
+ selected_operation_keys: vec!["GET /a".to_owned(), "GET /b".to_owned()],
+ auth_mappings: vec![
+ OpenApiAuthMapping {
+ operation_key: "GET /a".to_owned(),
+ alternative_index: 0,
+ auth_profile_id: Some(profile_a.id.as_str().to_owned()),
+ },
+ OpenApiAuthMapping {
+ operation_key: "GET /b".to_owned(),
+ alternative_index: 0,
+ auth_profile_id: Some(profile_b.id.as_str().to_owned()),
+ },
+ ],
+ server_url: None,
+ conflict_mode: "skip".to_owned(),
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(applied.created.len(), 2);
+ for created in &applied.created {
+ let version = service
+ .get_operation_version(
+ &workspace_id,
+ &created.operation_id.as_str().into(),
+ created.version,
+ )
+ .await
+ .unwrap();
+ let profile_ref = version
+ .snapshot
+ .execution_config
+ .auth_profile_ref
+ .as_ref()
+ .unwrap();
+ let serialized_operation = serde_json::to_string(&version.snapshot).unwrap();
+ assert!(serialized_operation.contains(profile_ref.as_str()));
+ assert!(!serialized_operation.contains("integration-secret-canary"));
+ assert!(!serialized_operation.contains(&ciphertext));
+ assert!(!serialized_operation.contains(&secret_hash));
+ }
+ let changed_mapping_replay = service
+ .create_openapi_import(
+ &workspace_id,
+ &preview.job_id.as_str().into(),
+ OpenApiImportCreatePayload {
+ selected_operation_keys: vec!["GET /a".to_owned(), "GET /b".to_owned()],
+ auth_mappings: vec![
+ OpenApiAuthMapping {
+ operation_key: "GET /a".to_owned(),
+ alternative_index: 0,
+ auth_profile_id: Some(profile_b.id.as_str().to_owned()),
+ },
+ OpenApiAuthMapping {
+ operation_key: "GET /b".to_owned(),
+ alternative_index: 0,
+ auth_profile_id: Some(profile_a.id.as_str().to_owned()),
+ },
+ ],
+ server_url: None,
+ conflict_mode: "skip".to_owned(),
+ },
+ )
+ .await;
+ assert!(changed_mapping_replay.is_err());
+ assert_eq!(
+ service.list_operations(&workspace_id).await.unwrap().len(),
+ 2
+ );
+
+ let now = time::OffsetDateTime::now_utc();
+ let foreign_workspace_id = WorkspaceId::new("ws_openapi_auth_foreign");
+ let foreign_workspace = Workspace {
+ id: foreign_workspace_id.clone(),
+ slug: "openapi-auth-foreign".to_owned(),
+ display_name: "OpenAPI Auth Foreign".to_owned(),
+ status: WorkspaceStatus::Active,
+ settings: json!({}),
+ created_at: now,
+ updated_at: now,
+ };
+ registry
+ .create_workspace(CreateWorkspaceRequest {
+ workspace: &foreign_workspace,
+ })
+ .await
+ .unwrap();
+ let foreign_secret = service
+ .create_secret(
+ &foreign_workspace_id,
+ None,
+ SecretPayload {
+ name: "foreign-token".to_owned(),
+ kind: SecretKind::Token,
+ value: json!("foreign-secret-canary"),
+ },
+ None,
+ )
+ .await
+ .unwrap();
+ let foreign_profile = create_bearer_profile(
+ &service,
+ &foreign_workspace_id,
+ "foreign-profile",
+ &foreign_secret.id,
+ )
+ .await;
+ let choices_preview = service
+ .preview_openapi_import(&workspace_id, two_protected_operations_upload())
+ .await
+ .unwrap();
+ assert!(
+ choices_preview
+ .auth_profile_choices
+ .iter()
+ .flat_map(|choice| &choice.profiles)
+ .all(|profile| profile.id != foreign_profile.id.as_str())
+ );
+
+ let missing_error =
+ apply_first_protected_mapping(&service, &workspace_id, "auth_missing_profile")
+ .await
+ .unwrap_err();
+ let foreign_error =
+ apply_first_protected_mapping(&service, &workspace_id, foreign_profile.id.as_str())
+ .await
+ .unwrap_err();
+ assert_eq!(format!("{missing_error:?}"), format!("{foreign_error:?}"));
+ assert!(!format!("{foreign_error:?}").contains(foreign_profile.id.as_str()));
+
+ sqlx::query("update secrets set status = 'disabled' where workspace_id = $1 and id = $2")
+ .bind(workspace_id.as_str())
+ .bind(secret.id.as_str())
+ .execute(registry.pool())
+ .await
+ .unwrap();
+ let disabled_preview = service
+ .preview_openapi_import(&workspace_id, two_protected_operations_upload())
+ .await
+ .unwrap();
+ assert!(
+ disabled_preview
+ .auth_profile_choices
+ .iter()
+ .all(|choice| choice.profiles.is_empty())
+ );
+ let before_disabled_apply = service.list_operations(&workspace_id).await.unwrap().len();
+ let disabled_error = service
+ .create_openapi_import_with_locale(
+ &workspace_id,
+ &disabled_preview.job_id.as_str().into(),
+ OpenApiImportCreatePayload {
+ selected_operation_keys: vec!["GET /a".to_owned()],
+ auth_mappings: vec![OpenApiAuthMapping {
+ operation_key: "GET /a".to_owned(),
+ alternative_index: 0,
+ auth_profile_id: Some(profile_a.id.as_str().to_owned()),
+ }],
+ server_url: None,
+ conflict_mode: "skip".to_owned(),
+ },
+ OpenApiUploadLocale::Ru,
+ )
+ .await
+ .unwrap_err();
+ match &disabled_error {
+ admin_api::error::ApiError::Unprocessable { message, context } => {
+ assert_eq!(
+ message,
+ "выбранный профиль аутентификации недоступен для этого импорта"
+ );
+ assert_eq!(
+ context.as_ref().unwrap()["error_code"],
+ "openapi_auth_binding_unavailable"
+ );
+ }
+ other => panic!("expected localized auth binding error, got {other:?}"),
+ }
+ let disabled_shared_profile_error =
+ apply_first_protected_mapping(&service, &workspace_id, profile_b.id.as_str())
+ .await
+ .unwrap_err();
+ assert_eq!(
+ format!("{disabled_shared_profile_error:?}"),
+ format!("{missing_error:?}")
+ );
+ assert_eq!(
+ service.list_operations(&workspace_id).await.unwrap().len(),
+ before_disabled_apply
+ );
+}
+
+#[tokio::test]
+#[serial]
+async fn selected_supported_or_and_explicit_no_auth_alternatives_apply_without_collapsing_semantics()
+ {
+ let registry = test_registry().await;
+ let service = test_service(
+ registry,
+ test_storage_root("openapi_import_auth_alternatives"),
+ test_auth_settings(),
+ test_secret_crypto(),
+ );
+ let workspace_id = WorkspaceId::new("ws_default");
+ let secret = service
+ .create_secret(
+ &workspace_id,
+ None,
+ SecretPayload {
+ name: "or-token".to_owned(),
+ kind: SecretKind::Token,
+ value: json!("or-profile-secret"),
+ },
+ None,
+ )
+ .await
+ .unwrap();
+ let profile = create_bearer_profile(&service, &workspace_id, "or-bearer", &secret.id).await;
+ let preview = service
+ .preview_openapi_import(&workspace_id, security_alternatives_upload())
+ .await
+ .unwrap();
+ let choices = preview
+ .auth_profile_choices
+ .iter()
+ .filter(|choice| choice.operation_key == "GET /choice")
+ .collect::>();
+ assert_eq!(choices.len(), 2);
+ assert!(choices[0].supported);
+ assert_eq!(choices[0].profiles.len(), 1);
+ assert!(!choices[1].supported);
+ let either = preview
+ .auth_profile_choices
+ .iter()
+ .filter(|choice| choice.operation_key == "GET /either")
+ .collect::>();
+ assert_eq!(either.len(), 2);
+ assert!(either[1].supported);
+
+ let applied = service
+ .create_openapi_import(
+ &workspace_id,
+ &preview.job_id.as_str().into(),
+ OpenApiImportCreatePayload {
+ selected_operation_keys: vec![
+ "GET /choice".to_owned(),
+ "GET /either".to_owned(),
+ "GET /public".to_owned(),
+ ],
+ auth_mappings: vec![
+ OpenApiAuthMapping {
+ operation_key: "GET /choice".to_owned(),
+ alternative_index: 0,
+ auth_profile_id: Some(profile.id.as_str().to_owned()),
+ },
+ OpenApiAuthMapping {
+ operation_key: "GET /either".to_owned(),
+ alternative_index: 1,
+ auth_profile_id: None,
+ },
+ ],
+ server_url: None,
+ conflict_mode: "skip".to_owned(),
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(applied.created.len(), 3);
+ for created in &applied.created {
+ let version = service
+ .get_operation_version(
+ &workspace_id,
+ &created.operation_id.as_str().into(),
+ created.version,
+ )
+ .await
+ .unwrap();
+ let auth_profile_ref = version.snapshot.execution_config.auth_profile_ref;
+ match created.operation_key.as_str() {
+ "GET /choice" => assert_eq!(auth_profile_ref, Some(profile.id.clone())),
+ "GET /either" | "GET /public" => assert!(auth_profile_ref.is_none()),
+ other => panic!("unexpected operation {other}"),
+ }
+ }
+}
+
+#[tokio::test]
+#[serial]
+async fn changed_security_scheme_after_preview_fails_digest_check_without_draft_mutation() {
+ let registry = test_registry().await;
+ let service = test_service(
+ registry.clone(),
+ test_storage_root("openapi_import_security_scheme_drift"),
+ test_auth_settings(),
+ test_secret_crypto(),
+ );
+ let workspace_id = WorkspaceId::new("ws_default");
+ let secret = service
+ .create_secret(
+ &workspace_id,
+ None,
+ SecretPayload {
+ name: "drift-test-token".to_owned(),
+ kind: SecretKind::Token,
+ value: json!("scheme-drift-profile-secret"),
+ },
+ None,
+ )
+ .await
+ .unwrap();
+ let profile =
+ create_bearer_profile(&service, &workspace_id, "drift-test-profile", &secret.id).await;
+ let bearer_preview = service
+ .preview_openapi_import(&workspace_id, security_scheme_upload(false))
+ .await
+ .unwrap();
+ let api_key_preview = service
+ .preview_openapi_import(&workspace_id, security_scheme_upload(true))
+ .await
+ .unwrap();
+ let bearer_job: crank_registry::ImportJobId = bearer_preview.job_id.as_str().into();
+ let api_key_job: crank_registry::ImportJobId = api_key_preview.job_id.as_str().into();
+ let api_key_source = registry
+ .get_import_job(&workspace_id, &api_key_job)
+ .await
+ .unwrap()
+ .unwrap()
+ .preview_payload["source"]
+ .clone();
+ sqlx::query(
+ "update import_jobs
+ set preview_payload = jsonb_set(
+ jsonb_set(preview_payload, '{source,source_id}', $1, false),
+ '{source,digest}', $2, false
+ )
+ where workspace_id = $3 and id = $4",
+ )
+ .bind(&api_key_source["source_id"])
+ .bind(&api_key_source["digest"])
+ .bind(workspace_id.as_str())
+ .bind(bearer_job.as_str())
+ .execute(registry.pool())
+ .await
+ .unwrap();
+
+ let error = service
+ .create_openapi_import(
+ &workspace_id,
+ &bearer_job,
+ OpenApiImportCreatePayload {
+ selected_operation_keys: vec!["GET /secure".to_owned()],
+ auth_mappings: vec![OpenApiAuthMapping {
+ operation_key: "GET /secure".to_owned(),
+ alternative_index: 0,
+ auth_profile_id: Some(profile.id.as_str().to_owned()),
+ }],
+ server_url: None,
+ conflict_mode: "skip".to_owned(),
+ },
+ )
+ .await
+ .unwrap_err();
+ match error {
+ admin_api::error::ApiError::Unprocessable { context, .. } => assert_eq!(
+ context.unwrap()["error_code"],
+ "openapi_upload.source_integrity"
+ ),
+ other => panic!("expected source integrity error, got {other:?}"),
+ }
+ let job = registry
+ .get_import_job(&workspace_id, &bearer_job)
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(
+ job.error_text.as_deref(),
+ Some("import_replay_verification_failed")
+ );
+ assert!(
+ service
+ .list_operations(&workspace_id)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+}
+
+#[tokio::test]
+#[serial]
+async fn auth_mapping_for_unselected_operation_is_rejected_without_draft_mutation() {
+ let registry = test_registry().await;
+ let service = test_service(
+ registry,
+ test_storage_root("openapi_import_unselected_auth_mapping"),
+ test_auth_settings(),
+ test_secret_crypto(),
+ );
+ let workspace_id = WorkspaceId::new("ws_default");
+ let preview = service
+ .preview_openapi_import(&workspace_id, two_protected_operations_upload())
+ .await
+ .unwrap();
+ assert!(
+ service
+ .create_openapi_import(
+ &workspace_id,
+ &preview.job_id.as_str().into(),
+ OpenApiImportCreatePayload {
+ selected_operation_keys: vec!["GET /a".to_owned()],
+ auth_mappings: vec![OpenApiAuthMapping {
+ operation_key: "GET /b".to_owned(),
+ alternative_index: 0,
+ auth_profile_id: None,
+ }],
+ server_url: None,
+ conflict_mode: "skip".to_owned(),
+ },
+ )
+ .await
+ .is_err()
+ );
+ assert!(
+ service
+ .list_operations(&workspace_id)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+}
+
+fn two_protected_operations_upload() -> OpenApiUpload {
+ OpenApiUpload {
+ bytes: br#"
+openapi: 3.0.3
+info: { title: Protected API }
+servers: [{ url: https://api.example.test }]
+components:
+ securitySchemes:
+ bearerAuth: { type: http, scheme: bearer }
+security:
+ - bearerAuth: []
+paths:
+ /a:
+ get:
+ responses: { '200': { description: ok } }
+ /b:
+ get:
+ responses: { '200': { description: ok } }
+"#
+ .to_vec(),
+ mime_type: "application/yaml".to_owned(),
+ locale: OpenApiUploadLocale::En,
+ }
+}
+
+fn security_alternatives_upload() -> OpenApiUpload {
+ OpenApiUpload {
+ bytes: br#"
+openapi: 3.0.3
+info: { title: Security alternatives }
+servers: [{ url: https://api.example.test }]
+components:
+ securitySchemes:
+ bearerAuth: { type: http, scheme: bearer }
+ oauth: { type: oauth2, flows: { implicit: { authorizationUrl: https://auth.example.test, scopes: {} } } }
+security:
+ - bearerAuth: []
+ - oauth: []
+paths:
+ /choice:
+ get:
+ responses: { '200': { description: ok } }
+ /either:
+ get:
+ security:
+ - bearerAuth: []
+ - {}
+ responses: { '200': { description: ok } }
+ /public:
+ get:
+ security: []
+ responses: { '200': { description: ok } }
+"#
+ .to_vec(),
+ mime_type: "application/yaml".to_owned(),
+ locale: OpenApiUploadLocale::En,
+ }
+}
+
+fn security_scheme_upload(api_key: bool) -> OpenApiUpload {
+ let security_scheme = if api_key {
+ "auth: { type: apiKey, in: header, name: X-Token }"
+ } else {
+ "auth: { type: http, scheme: bearer }"
+ };
+ OpenApiUpload {
+ bytes: format!(
+ "openapi: 3.0.3\ninfo: {{ title: Scheme drift }}\nservers: [{{ url: https://api.example.test }}]\ncomponents:\n securitySchemes:\n {security_scheme}\nsecurity:\n - auth: []\npaths:\n /secure:\n get:\n responses: {{ '200': {{ description: ok }} }}\n"
+ )
+ .into_bytes(),
+ mime_type: "application/yaml".to_owned(),
+ locale: OpenApiUploadLocale::En,
+ }
+}
+
+async fn create_bearer_profile(
+ service: &admin_api::service::AdminService,
+ workspace_id: &WorkspaceId,
+ name: &str,
+ secret_id: &SecretId,
+) -> crank_core::AuthProfile {
+ service
+ .create_auth_profile(
+ workspace_id,
+ AuthProfilePayload {
+ name: name.to_owned(),
+ kind: AuthKind::Bearer,
+ config: AuthConfig::Bearer(BearerAuthConfig {
+ header_name: "Authorization".to_owned(),
+ secret_id: secret_id.clone(),
+ }),
+ },
+ None,
+ )
+ .await
+ .unwrap()
+}
+
+async fn apply_first_protected_mapping(
+ service: &admin_api::service::AdminService,
+ workspace_id: &WorkspaceId,
+ auth_profile_id: &str,
+) -> Result {
+ let preview = service
+ .preview_openapi_import(workspace_id, two_protected_operations_upload())
+ .await?;
+ service
+ .create_openapi_import(
+ workspace_id,
+ &preview.job_id.as_str().into(),
+ OpenApiImportCreatePayload {
+ selected_operation_keys: vec!["GET /a".to_owned()],
+ auth_mappings: vec![OpenApiAuthMapping {
+ operation_key: "GET /a".to_owned(),
+ alternative_index: 0,
+ auth_profile_id: Some(auth_profile_id.to_owned()),
+ }],
+ server_url: None,
+ conflict_mode: "skip".to_owned(),
+ },
+ )
+ .await
+}
diff --git a/apps/admin-api/tests/integration/openapi_source.rs b/apps/admin-api/tests/integration/openapi_source.rs
index 47d32cb..e0ef434 100644
--- a/apps/admin-api/tests/integration/openapi_source.rs
+++ b/apps/admin-api/tests/integration/openapi_source.rs
@@ -512,6 +512,7 @@ async fn apply_rereads_the_scoped_verified_source_and_expiry_detaches_it() {
&job_id,
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /health".to_owned()],
+ auth_mappings: vec![],
server_url: None,
conflict_mode: "skip".to_owned(),
},
diff --git a/apps/admin-api/tests/integration/openapi_source/apply_failures.rs b/apps/admin-api/tests/integration/openapi_source/apply_failures.rs
index 589fe5a..b994662 100644
--- a/apps/admin-api/tests/integration/openapi_source/apply_failures.rs
+++ b/apps/admin-api/tests/integration/openapi_source/apply_failures.rs
@@ -245,6 +245,7 @@ async fn apply_health_operation(
job_id,
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /health".to_owned()],
+ auth_mappings: vec![],
server_url: None,
conflict_mode: "skip".to_owned(),
},
diff --git a/apps/mcp-server/tests/integration/common.rs b/apps/mcp-server/tests/integration/common.rs
index e7f44b8..fbe3b5d 100644
--- a/apps/mcp-server/tests/integration/common.rs
+++ b/apps/mcp-server/tests/integration/common.rs
@@ -489,6 +489,9 @@ pub(super) fn test_operation(base_url: &str, name: &str) -> Operation Operation Schema {
Schema {
kind: SchemaKind::Object,
+ format: None,
description: None,
required: true,
nullable: false,
@@ -551,6 +555,7 @@ pub(super) fn object_schema(field_name: &str) -> Schema {
field_name.to_owned(),
Schema {
kind: SchemaKind::String,
+ format: None,
description: None,
required: true,
nullable: false,
diff --git a/crates/crank-adapter-rest/Cargo.toml b/crates/crank-adapter-rest/Cargo.toml
index e94a956..b63dda1 100644
--- a/crates/crank-adapter-rest/Cargo.toml
+++ b/crates/crank-adapter-rest/Cargo.toml
@@ -8,6 +8,7 @@ version.workspace = true
[dependencies]
async-trait = "0.1"
+base64.workspace = true
crank-core = { path = "../crank-core" }
crank-metrics = { path = "../crank-metrics" }
crank-trace = { path = "../crank-trace" }
diff --git a/crates/crank-adapter-rest/src/body.rs b/crates/crank-adapter-rest/src/body.rs
new file mode 100644
index 0000000..b4fbbac
--- /dev/null
+++ b/crates/crank-adapter-rest/src/body.rs
@@ -0,0 +1,488 @@
+use std::{collections::BTreeMap, io};
+
+use base64::{Engine as _, engine::general_purpose::STANDARD};
+use crank_core::RestTarget;
+use futures_util::StreamExt;
+use serde_json::Value;
+
+use crate::RestAdapterError;
+
+pub(crate) async fn apply_body(
+ builder: reqwest::RequestBuilder,
+ body: &Value,
+ content_type: &str,
+ multipart_mime_types: Option<&BTreeMap>>,
+ max_request_bytes: usize,
+) -> Result {
+ match content_type {
+ "application/x-www-form-urlencoded" => {
+ let encoded = form_urlencoded(body, max_request_bytes)?;
+ Ok(builder.header("content-type", content_type).body(encoded))
+ }
+ "multipart/form-data" => {
+ let form = multipart_form(body, multipart_mime_types, max_request_bytes)?;
+ let boundary = form.boundary().to_owned();
+ let mut encoded = BoundedBuffer::new(max_request_bytes);
+ let mut stream = Box::pin(form.into_stream());
+ while let Some(chunk) = stream.next().await {
+ let chunk = chunk?;
+ encoded.append(&chunk)?;
+ }
+ Ok(builder
+ .header(
+ "content-type",
+ format!("multipart/form-data; boundary={boundary}"),
+ )
+ .body(encoded.into_bytes()))
+ }
+ content_type if content_type == "application/json" || content_type.ends_with("+json") => {
+ let encoded = json_bytes(body, max_request_bytes)?;
+ Ok(builder.header("content-type", content_type).body(encoded))
+ }
+ _ => Err(RestAdapterError::InvalidBodyContract {
+ reason: "unsupported request content type".to_owned(),
+ }),
+ }
+}
+
+pub(crate) fn apply_legacy_json_body(
+ builder: reqwest::RequestBuilder,
+ body: &Value,
+ has_content_type: bool,
+ limit_bytes: usize,
+) -> Result {
+ let builder = if has_content_type {
+ builder
+ } else {
+ builder.header("content-type", "application/json")
+ };
+ Ok(builder.body(json_bytes(body, limit_bytes)?))
+}
+
+pub(crate) fn selected_request_content_type(
+ target: &RestTarget,
+ request: &crate::RestRequest,
+) -> Result