Merge pull request 'Bmad loop/20260927 234647 43b3/2 10 security schemes secrets' (#5) from bmad-loop/20260927-234647-43b3/2-10-security-schemes-secrets into main
Reviewed-on: #5
This commit was merged in pull request #5.
This commit is contained in:
commit
82b215dd74
109 files changed
+12267
-1048
No files matched your search
Generated
+16
-13
@@ -221,9 +221,9 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "aws-lc-rs"
|
name = "aws-lc-rs"
|
||||||
version = "1.17.3"
|
version = "1.18.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "00bdb5da18dac48ca2cc7cd4a98e533e8635a58e2361d13a1a4ee3888e0d72f1"
|
checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aws-lc-sys",
|
"aws-lc-sys",
|
||||||
"zeroize",
|
"zeroize",
|
||||||
@@ -231,9 +231,9 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "aws-lc-sys"
|
name = "aws-lc-sys"
|
||||||
version = "0.43.0"
|
version = "0.45.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "43103168cc76fe62678a375e722fc9cb3a0146159ac5828bc4f0dfd755c2224c"
|
checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"cc",
|
"cc",
|
||||||
"cmake",
|
"cmake",
|
||||||
@@ -651,6 +651,7 @@ version = "0.3.1"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"async-trait",
|
"async-trait",
|
||||||
"axum",
|
"axum",
|
||||||
|
"base64",
|
||||||
"crank-core",
|
"crank-core",
|
||||||
"crank-metrics",
|
"crank-metrics",
|
||||||
"crank-trace",
|
"crank-trace",
|
||||||
@@ -766,6 +767,7 @@ dependencies = [
|
|||||||
"serde_json",
|
"serde_json",
|
||||||
"serde_yaml",
|
"serde_yaml",
|
||||||
"thiserror 2.0.18",
|
"thiserror 2.0.18",
|
||||||
|
"url",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -846,6 +848,7 @@ dependencies = [
|
|||||||
"base64",
|
"base64",
|
||||||
"crank-adapter-rest",
|
"crank-adapter-rest",
|
||||||
"crank-core",
|
"crank-core",
|
||||||
|
"crank-import",
|
||||||
"crank-mapping",
|
"crank-mapping",
|
||||||
"crank-metrics",
|
"crank-metrics",
|
||||||
"crank-schema",
|
"crank-schema",
|
||||||
@@ -1139,7 +1142,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"libc",
|
"libc",
|
||||||
"windows-sys 0.52.0",
|
"windows-sys 0.59.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -2668,7 +2671,7 @@ dependencies = [
|
|||||||
"once_cell",
|
"once_cell",
|
||||||
"socket2 0.5.10",
|
"socket2 0.5.10",
|
||||||
"tracing",
|
"tracing",
|
||||||
"windows-sys 0.52.0",
|
"windows-sys 0.59.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -3007,14 +3010,14 @@ dependencies = [
|
|||||||
"errno",
|
"errno",
|
||||||
"libc",
|
"libc",
|
||||||
"linux-raw-sys 0.12.1",
|
"linux-raw-sys 0.12.1",
|
||||||
"windows-sys 0.52.0",
|
"windows-sys 0.59.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rustls"
|
name = "rustls"
|
||||||
version = "0.23.41"
|
version = "0.23.45"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "6b92b125634d9b795e7beca796cc790df15a7fb38323bf3196fda83292d06b1f"
|
checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aws-lc-rs",
|
"aws-lc-rs",
|
||||||
"log",
|
"log",
|
||||||
@@ -3066,7 +3069,7 @@ dependencies = [
|
|||||||
"security-framework",
|
"security-framework",
|
||||||
"security-framework-sys",
|
"security-framework-sys",
|
||||||
"webpki-root-certs",
|
"webpki-root-certs",
|
||||||
"windows-sys 0.52.0",
|
"windows-sys 0.59.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -3077,9 +3080,9 @@ checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rustls-webpki"
|
name = "rustls-webpki"
|
||||||
version = "0.103.13"
|
version = "0.103.15"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"
|
checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aws-lc-rs",
|
"aws-lc-rs",
|
||||||
"ring",
|
"ring",
|
||||||
@@ -4470,7 +4473,7 @@ version = "0.1.11"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"windows-sys 0.52.0",
|
"windows-sys 0.59.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
|||||||
@@ -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-contract>
|
||||||
|
|
||||||
|
## 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 согласно решению ниже.
|
||||||
|
|
||||||
|
<frozen-after-approval>
|
||||||
|
|
||||||
|
### Решение пользователя: доступность 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.
|
||||||
|
|
||||||
|
</frozen-after-approval>
|
||||||
|
|
||||||
|
## 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 |
|
||||||
|
|
||||||
|
</intent-contract>
|
||||||
|
|
||||||
|
## 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<RegistryError>` всегда выдаёт английский текст, хотя `create_openapi_import` знает locale; преобразовать этот вариант на границе import API. В import Apply вариант RegistryError преобразуется с locale; Ru integration test проходит.
|
||||||
|
- `[low]` `[patch]` документация не уточняет zero-based `alternative_index` — код индексирует `Vec` напрямую; добавить одну фразу. В `docs/openapi-import.md` добавлено явное правило нулевой индексации.
|
||||||
|
- `[high]` `[patch]` AC-12 не проверяет перечисленные literal paths — тесты не содержат camelCase/JWT/query URL/Cookie; добавить canary-fixtures к исправлению сканера. `scanner_redacts_contextual_credentials_non_strings_jwts_and_cookie_examples` и OAuth URL fixture добавлены и прошли.
|
||||||
|
- `[high]` `[patch]` тест redacted bearer hint не проверяет safe finding — сейчас проверяется только отсутствие canary в IR; добавить проверку source location и сериализованного finding. Проверяются точный safe pointer, код finding и сериализованный report без canary.
|
||||||
|
- `[high]` `[patch]` edge-case слой подтвердил camelCase/JWT пропуски — тот же `sensitive_key` и `looks_secret_value`, что в строках 1 и 3; покрывается тем же исправлением. Закрыто общей scanner patch и canary-тестами строк 1 и 3.
|
||||||
|
- `[high]` `[patch]` query API-key parameter с произвольным example пропускается — имя параметра и example обходятся отдельно, `in: query` не включает sensitive context; связать context с именем `api_key` и добавить тест. Сканер использует sibling `name`/`in` для example context; canary-тест проходит.
|
||||||
|
- `[false]` `[reject]` API rejection вместо redacted preview finding не означает отсутствия finding — `normalize.rs` создаёт `secret_literal_redacted` в IR, а admin API до persistence отклоняет опасный upload с безопасной ошибкой; контракт не требует сохранять небезопасный source ради preview.
|
||||||
|
|
||||||
|
## Design Notes
|
||||||
|
|
||||||
|
Pure importer хранит schemes/requirements, но не читает Auth Profiles или Secrets. Workspace-safe lookup принадлежит admin service, authoritative проверка непосредственно перед созданием Draft — registry transaction. Текущий единичный profile reference позволяет выдавать blocker для unsupported AND: это прямо предусмотрено AC и не требует расширения runtime до составного auth.
|
||||||
|
|
||||||
|
Проверка 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 этой истории нет.
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
---
|
||||||
|
stepsCompleted: ['step-01-preflight-and-context', 'step-02-generation-mode', 'step-03-test-strategy', 'step-04c-aggregate', 'step-05-validate-and-complete']
|
||||||
|
lastStep: 'step-05-validate-and-complete'
|
||||||
|
lastSaved: '2026-09-27'
|
||||||
|
storyId: '2.10'
|
||||||
|
storyKey: '2-10-security-schemes-secrets'
|
||||||
|
storyFile: '_bmad-output/implementation-artifacts/spec-2-10-security-schemes-secrets.md'
|
||||||
|
atddChecklistPath: '_bmad-output/test-artifacts/atdd-checklist-2-10-security-schemes-secrets.md'
|
||||||
|
generatedTestFiles:
|
||||||
|
- 'crates/crank-import/tests/security_schemes.rs'
|
||||||
|
- 'apps/admin-api/tests/integration/openapi_import/security.rs'
|
||||||
|
- 'apps/admin-api/tests/integration/openapi_import/external_references.rs'
|
||||||
|
- 'crates/crank-registry/tests/integration/import_auth_binding.rs'
|
||||||
|
inputDocuments:
|
||||||
|
- '_bmad-output/implementation-artifacts/spec-2-10-security-schemes-secrets.md'
|
||||||
|
- '_bmad-output/implementation-artifacts/epic-2-context.md'
|
||||||
|
- '_bmad-output/implementation-artifacts/1-10-lifecycle-auth-profiles-machine-keys.md'
|
||||||
|
- '_bmad-output/implementation-artifacts/spec-2-9-http-contract.md'
|
||||||
|
- '_bmad-output/test-artifacts/test-design-epic-2.md'
|
||||||
|
- '_bmad-output/test-artifacts/test-design-qa.md'
|
||||||
|
- '_bmad/tea/config.yaml'
|
||||||
|
- 'Cargo.toml'
|
||||||
|
- 'apps/admin-api/Cargo.toml'
|
||||||
|
- 'crates/crank-import/Cargo.toml'
|
||||||
|
- 'crates/crank-runtime/Cargo.toml'
|
||||||
|
acceptanceCriteria:
|
||||||
|
- id: AC-1
|
||||||
|
idSource: generated
|
||||||
|
text: 'Given OpenAPI 3.x components.securitySchemes или Swagger 2.0 securityDefinitions; When importer анализирует schemes; Then bearer HTTP, basic HTTP и API key в header/query/cookie преобразуются в typed security metadata; And source names, locations и применимые format hints сохраняются без credential values.'
|
||||||
|
- id: AC-2
|
||||||
|
idSource: generated
|
||||||
|
text: 'Given global security requirement; When Operation не задаёт собственный override; Then candidate наследует global requirement согласно specification semantics; And operation-level requirement или explicit no-auth корректно заменяет global rule.'
|
||||||
|
- id: AC-3
|
||||||
|
idSource: generated
|
||||||
|
text: 'Given security requirement с несколькими alternatives; When source определяет OR-семантику; Then preview сохраняет все допустимые alternatives и позволяет выбрать поддерживаемый вариант; And importer не объединяет alternatives в ложное обязательное AND.'
|
||||||
|
- id: AC-4
|
||||||
|
idSource: generated
|
||||||
|
text: 'Given security requirement, требующий несколько schemes одновременно; When source определяет AND-семантику; Then candidate сохраняет составное требование, если runtime contract его поддерживает; And иначе affected Operation получает blocker finding с перечислением несохраняемой semantics.'
|
||||||
|
- id: AC-5
|
||||||
|
idSource: generated
|
||||||
|
text: 'Given bearer, basic или API-key requirement; When формируется preview; Then администратору предлагается выбрать совместимый Auth Profile из текущего workspace либо оставить явный unresolved binding; And unresolved required authentication блокирует actionable Draft/Apply для affected Operation.'
|
||||||
|
- id: AC-6
|
||||||
|
idSource: generated
|
||||||
|
text: 'Given выбранный Auth Profile; When создаётся candidate или ImportPlan; Then сохраняется только typed AuthProfileRef и scheme metadata; And raw secret, password, token, API key, hash или encrypted ciphertext не копируется в source snapshot, IR, findings, plan или Operation export.'
|
||||||
|
- id: AC-7
|
||||||
|
idSource: generated
|
||||||
|
text: 'Given OAuth2, OpenID Connect, mutual TLS или неизвестная scheme; When release scope не поддерживает автоматическое mapping; Then importer создаёт explicit manual-configuration/unsupported finding; And не извлекает client secret, token URL credential, example token или vendor-extension secret.'
|
||||||
|
- id: AC-8
|
||||||
|
idSource: generated
|
||||||
|
text: 'Given OpenAPI document содержит literal credential в example, default, extension, URL userinfo или header example; When security analysis выполняется; Then значение не используется как credential и создаёт redacted secret finding; And raw value не появляется в preview UI, logs, traces, metrics или diagnostics.'
|
||||||
|
- id: AC-9
|
||||||
|
idSource: generated
|
||||||
|
text: 'Given Auth Profile отсутствует/удалён, принадлежит другому workspace либо любой необходимый связанный Secret недоступен по существующим правилам active/current version; When preview либо Apply проверяет binding; Then reference отклоняется до создания Draft; And ошибка не раскрывает metadata foreign profile.'
|
||||||
|
- id: AC-10
|
||||||
|
idSource: generated
|
||||||
|
text: 'Given профили A и B используют один активный Secret с доступной текущей версией; When проверяются binding этих профилей; Then оба binding допустимы при выполнении остальных проверок; And после отключения общего Secret оба binding отклоняются до создания Draft; тест с disabled Secret не является доказательством независимого отзыва Auth Profile, который остаётся вне scope.'
|
||||||
|
- id: AC-11
|
||||||
|
idSource: generated
|
||||||
|
text: 'Given исходная security scheme изменилась после preview; When старый ImportPlan пытаются применить к новому source; Then plan digest mismatch блокирует Apply; And требуется новый preview и явное подтверждение Auth Profile mappings.'
|
||||||
|
- id: AC-12
|
||||||
|
idSource: generated
|
||||||
|
text: 'Given security scheme test suite; When выполняются fixtures и negative tests; Then покрыты global/operation overrides, no-auth, bearer/basic/API-key locations, OR/AND requirements, OAuth/OpenID/unknown schemes, secret-like examples, missing/deleted и cross-workspace profile refs, недоступные Secrets по правилам active/current version и блокировка обоих профилей при отключении общего Secret; And redaction tests и `just verify` проходят.'
|
||||||
|
---
|
||||||
|
|
||||||
|
# ATDD Checklist — Story 2.10: Security Schemes and Secrets
|
||||||
|
|
||||||
|
## Preflight
|
||||||
|
|
||||||
|
- **Approval/source:** the approved, frozen acceptance contract is the Story 2.10 spec. Its recorded 2026-09-13 decision defines binding availability through the existing active/current Secret rules; it does not add independent Auth Profile revocation.
|
||||||
|
- **Story identity:** ID `2.10`; canonical key `2-10-security-schemes-secrets` from the spec filename.
|
||||||
|
- **Stack and harness:** repository is Rust backend plus an existing UI. This story's approved scope is API/parser/runtime, so primary level is Rust unit/integration/API contract; UI/E2E belongs to Story 2.11. `cargo test` and `just verify` are configured.
|
||||||
|
- **Risk and design:** P0, FR-10, E2-R2 (score 9), seed scenarios `2.10-API-A` and `2.10-API-B`. The epic test design calls for preserving security semantics and rejecting unsupported/foreign bindings, with secret canaries absent from API/IR/plan/export surfaces.
|
||||||
|
- **Implementation observation:** security metadata now flows through typed IR/preview; Admin API accepts profile mappings, rejects unsafe literals before persistence, and validates binding availability within Apply. Current verification evidence is recorded below and is scoped to the commands actually run.
|
||||||
|
- **Generation mode:** backend/API source analysis. No browser recording; no Story 2.11 UI scaffolds.
|
||||||
|
- **Contract boundary:** implementation added focused tests in the existing importer, Admin API and registry harnesses. No skipped or placeholder tests are used as evidence.
|
||||||
|
|
||||||
|
## Acceptance Criteria Snapshot and Scenario Mapping
|
||||||
|
|
||||||
|
AC IDs below are deterministic IDs assigned in source order because the spec does not declare `AC-<n>` IDs. The exact snapshot is also stored in frontmatter.
|
||||||
|
|
||||||
|
| Scenario | AC | Test level / priority | Primary reusable test path | Required scenario and current status |
|
||||||
|
|---|---|---|---|---|
|
||||||
|
| 2.10-API-A1 | AC-1 | Importer unit / P0 | `security_alternatives_preserve_or_and_and_preview_exposes_typed_schemes`; `swagger2_security_definitions_project_basic_and_api_key_header_and_query` in `crates/crank-import/tests/security_schemes.rs` | **PASS** in importer suite: OpenAPI typed scheme metadata and Swagger 2.0 basic/API-key locations are projected. |
|
||||||
|
| 2.10-API-A2 | AC-2 | Importer unit / P0 | `security_requirements_inherit_and_operation_empty_array_disables_auth` in `crates/crank-import/tests/security_schemes.rs` | **PASS** in importer suite: global inheritance, multi-scheme operation requirement, explicit empty override. |
|
||||||
|
| 2.10-API-A3 | AC-3 | Importer + preview API / P0 | `security_alternatives_preserve_or_and_and_preview_exposes_typed_schemes`; `selected_supported_or_and_explicit_no_auth_alternatives_apply_without_collapsing_semantics` in `apps/admin-api/tests/integration/openapi_import/security.rs` | **PASS** in importer and Admin API integration suites: OR alternatives remain distinct and selected supported option applies. |
|
||||||
|
| 2.10-API-A4 | AC-4 | Importer unit + preview API / P0 | `security_requirements_inherit_and_operation_empty_array_disables_auth`; `security_alternatives_preserve_or_and_and_preview_exposes_typed_schemes` in `crates/crank-import/tests/security_schemes.rs` | **PASS** in importer suite: AND composition is retained and unsupported composition becomes a blocker. |
|
||||||
|
| 2.10-API-B1 | AC-5 | Admin API integration / P0 | `auth_profiles_are_workspace_scoped_revalidated_and_shared_secret_availability_is_current`; `selected_supported_or_and_explicit_no_auth_alternatives_apply_without_collapsing_semantics` in `apps/admin-api/tests/integration/openapi_import/security.rs` | **PASS** in Admin API integration suite: choices are workspace-scoped, supported mapping applies, unresolved required auth is blocked. |
|
||||||
|
| 2.10-API-B2 | AC-6 | Importer + API/registry integration / P0 | `ac_6_never_copies_literal_secret_canaries_into_normalized_ir` in `crates/crank-import/tests/security_schemes.rs`; `auth_profiles_are_workspace_scoped_revalidated_and_shared_secret_availability_is_current` in `apps/admin-api/tests/integration/openapi_import/security.rs`; `no_auth_requires_no_profile_reference` in `crates/crank-registry/tests/integration/import_auth_binding.rs` | **PASS** in importer, Admin API and registry suites. Tests assert canary/ciphertext/hash absence from IR/serialized Operation and no profile ref for no-auth. |
|
||||||
|
| 2.10-API-A5 | AC-7 | Importer unit / P0 | `unsupported_security_schemes_create_blockers_without_copying_credentials` in `crates/crank-import/tests/security_schemes.rs` | **PASS** in importer suite: OAuth/OIDC/mTLS/unknown produce explicit unsupported/blocker findings without credential extraction. |
|
||||||
|
| 2.10-API-A6 | AC-8 | Importer + Admin API integration / P0 | `scanner_finds_examples_defaults_extensions_and_url_userinfo_without_values`; `scanner_redacts_contextual_credentials_non_strings_jwts_and_cookie_examples`; `scanner_keeps_version_examples_and_null_credential_defaults`; `unsafe_bearer_format_canary_is_redacted_and_not_projected` in `crates/crank-import/tests/security_schemes.rs`; `literal_credential_is_rejected_before_any_import_artifact_or_job_is_created` in Admin API `security.rs`; `external_literal_credential_is_rejected_before_snapshot_persistence` in `external_references.rs` | **PASS** in importer/Admin API suites: canaries redact from findings and literal credentials are rejected before primary or external source persistence. |
|
||||||
|
| 2.10-API-B3 | AC-9 | Admin API + registry integration / P0 | `auth_profiles_are_workspace_scoped_revalidated_and_shared_secret_availability_is_current` in Admin API `security.rs`; `missing_and_foreign_profiles_have_the_same_safe_error_and_insert_no_operation`; `apply_rejects_kind_parameter_and_missing_current_version_before_mutation` in `crates/crank-registry/tests/integration/import_auth_binding.rs` | **PASS** in Admin API and registry suites. Foreign/missing errors are indistinguishable and no Draft mutation occurs. |
|
||||||
|
| 2.10-API-B4 | AC-10 | Admin API + registry integration / P0 | `auth_profiles_are_workspace_scoped_revalidated_and_shared_secret_availability_is_current` in Admin API `security.rs`; `apply_accepts_current_compatible_profile_and_shared_secret_then_rejects_disabled_secret` in `crates/crank-registry/tests/integration/import_auth_binding.rs` | **PASS** in Admin API and registry suites. Shared Secret permits both profiles while active and rejects them when disabled; independent profile revocation is not asserted. |
|
||||||
|
| 2.10-API-B5 | AC-11 | Admin API integration / P0 | `changed_security_scheme_after_preview_fails_digest_check_without_draft_mutation` in `apps/admin-api/tests/integration/openapi_import/security.rs` | **PASS** in Admin API integration suite: stale digest blocks Apply without creating Draft. |
|
||||||
|
| 2.10-API-GATE | AC-12 | Suite / P0 | `cargo test -p crank-import --all-targets`; `cargo test -p admin-api --test integration openapi_import -- --test-threads=1`; `cargo test -p crank-registry --test integration import_auth_binding -- --test-threads=1`; `just verify` | Importer, Admin API and registry suites **PASS**; final `just verify` **PASS**. Earlier failed attempts were repaired; the unrelated artifact subprocess failure was caused by redirecting stdout to a regular file and disappeared when the gate ran through a pipe. |
|
||||||
|
|
||||||
|
### Reuse inventory (not a claim of AC coverage)
|
||||||
|
|
||||||
|
- Importer behavior patterns: `crates/crank-import/tests/security_schemes.rs`, `swagger2_contract.rs`, `unit.rs`, `preview.rs`, and `http_replay.rs`.
|
||||||
|
- API/import persistence patterns: `apps/admin-api/tests/integration/openapi_import/http_contract.rs` and `external_references.rs`.
|
||||||
|
- Runtime auth injection patterns: `crates/crank-runtime/tests/stages.rs` and `integration/confirmation.rs`.
|
||||||
|
- The AC rows point to the actual tests observed in the current implementation. Importer, Admin API and registry test runs are complete; broad `just verify` has now passed.
|
||||||
|
|
||||||
|
## Test Strategy and TDD State
|
||||||
|
|
||||||
|
- **Primary level:** importer unit tests for pure OpenAPI semantics; Admin API + registry integration for profile scope, secret availability, transaction revalidation, and no-Draft guarantees; runtime tests only for unchanged trusted credential injection behavior.
|
||||||
|
- **Duplicate coverage:** do not duplicate existing general reference, source digest, redaction, or runtime-auth tests. Add assertions only for the Story 2.10 security contract and its import boundary.
|
||||||
|
- **Fixture requirements:** OAS 3.0, OAS 3.1, and Swagger 2.0 docs; deterministic secret canaries in example/default/extension/userinfo/header-example positions; workspace A/B profiles sharing one Secret; active/current and disabled Secret states; source mutation after preview. Never use customer credentials.
|
||||||
|
- **Assertion order:** primary assertion checks the exact promised value/state (typed scheme/effective requirement, blocker, absence of Draft, or digest rejection) before broad serialized-object checks. Setup results from an unimplemented endpoint remain opaque until the criterion assertion.
|
||||||
|
- **TDD record:** the initial two active tests genuinely failed before implementation (historical RED below); after implementation both now pass. No skipped tests are counted as RED or GREEN evidence.
|
||||||
|
|
||||||
|
## Handoff
|
||||||
|
|
||||||
|
- Story-level importer, Admin API and registry evidence is recorded above; all scenarios mapped to AC-1..AC-11 passed in those suites.
|
||||||
|
- AC-12 is satisfied: full `just verify` completed successfully. Earlier gate failures were fixed or traced to the output-redirection harness.
|
||||||
|
- Runtime suite: root reports `cargo test -p crank-runtime --all-targets` passed (83 tests).
|
||||||
|
|
||||||
|
## Historical RED Evidence (Before Implementation)
|
||||||
|
|
||||||
|
`cargo test -p crank-import --test normalization_details -- --nocapture` failed as intended: 11 passed, 2 failed, 0 ignored. AC-1 failed because `WorkspaceBearer` was absent from operation projection; AC-6 failed because `atdd-secret-canary-2-10` appeared in normalized IR. These failures were fixed by implementation and the tests now pass.
|
||||||
|
|
||||||
|
## Verification Results (Current Worktree)
|
||||||
|
|
||||||
|
| Command | Result | Interpretation |
|
||||||
|
|---|---|---|
|
||||||
|
| `cargo test -p crank-import --all-targets` | **PASS** — 99 tests passed, 0 failed, 0 ignored. | Includes security normalization, OpenAPI/Swagger mapping and redaction cases after review fixes. |
|
||||||
|
| `cargo test -p admin-api --test integration openapi_import -- --test-threads=1` | **PASS** — 24 passed, 0 failed, 0 ignored; 64 filtered out. | Includes mapping choices, literal-credential rejection, workspace/profile revalidation, shared Secret availability and digest drift. |
|
||||||
|
| `cargo test -p crank-registry --test integration import_auth_binding -- --test-threads=1` | **PASS** — 5 passed, 0 failed, 0 ignored; 95 filtered out. | Includes transaction-level profile, Secret state, no-auth and no-partial-mutation checks. |
|
||||||
|
| `cargo test -p crank-runtime --all-targets` | **PASS** — 83 passed, 0 failed, 0 ignored (result reported by root). | Runtime regression suite is green; no security scheme behavior is implemented in the runtime crate. |
|
||||||
|
| `just verify` | **PASS** — full workspace gate finished with exit 0, including fmt, clippy, dependencies and all workspace tests. | Earlier failures were corrected; artifact subprocess needed a pipe instead of regular-file stdout. |
|
||||||
|
| `git diff --check` | **PASS**. | No whitespace errors in current diff. |
|
||||||
|
|
||||||
|
## Completion Summary
|
||||||
|
|
||||||
|
- Story ID/key: `2.10` / `2-10-security-schemes-secrets`.
|
||||||
|
- AC snapshot: 12 source criteria mapped one-to-one to scenario IDs.
|
||||||
|
- Tests: security-specific tests were added to existing importer, Admin API and registry suites. The scenario table maps each AC to exact test names and package-level evidence.
|
||||||
|
- Current evidence after review fixes: importer 99/99, Admin API integration 88/88, registry auth-binding integration 5/5. Historical RED is retained separately; repeat full `just verify` passed.
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
{
|
||||||
|
"story_id": "2.10",
|
||||||
|
"story_key": "2-10-security-schemes-secrets",
|
||||||
|
"story_file": "_bmad-output/implementation-artifacts/spec-2-10-security-schemes-secrets.md",
|
||||||
|
"checklist": "_bmad-output/test-artifacts/atdd-checklist-2-10-security-schemes-secrets.md",
|
||||||
|
"tdd_phase": "GREEN",
|
||||||
|
"acceptance_criteria_total": 12,
|
||||||
|
"active_red_tests": 0,
|
||||||
|
"historical_red_tests": [
|
||||||
|
{
|
||||||
|
"scenario": "2.10-API-A1",
|
||||||
|
"acceptance_criterion": "AC-1",
|
||||||
|
"test": "security_schemes::ac_1_projects_openapi_security_scheme_identity_onto_operation_metadata",
|
||||||
|
"result": "FAIL_BEFORE_IMPLEMENTATION_THEN_PASS",
|
||||||
|
"observed": "operation projection does not contain WorkspaceBearer"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"scenario": "2.10-API-B2",
|
||||||
|
"acceptance_criterion": "AC-6",
|
||||||
|
"test": "security_schemes::ac_6_never_copies_literal_secret_canaries_into_normalized_ir",
|
||||||
|
"result": "FAIL_BEFORE_IMPLEMENTATION_THEN_PASS",
|
||||||
|
"observed": "normalized IR contains atdd-secret-canary-2-10"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"pending_acceptance_criteria": [],
|
||||||
|
"generated_test_files": [
|
||||||
|
"crates/crank-import/tests/security_schemes.rs",
|
||||||
|
"apps/admin-api/tests/integration/openapi_import/security.rs",
|
||||||
|
"apps/admin-api/tests/integration/openapi_import/external_references.rs",
|
||||||
|
"crates/crank-registry/tests/integration/import_auth_binding.rs"
|
||||||
|
],
|
||||||
|
"existing_suite_baseline": {
|
||||||
|
"command": "cargo test -p crank-import --all-targets",
|
||||||
|
"result": "PASS",
|
||||||
|
"passed": 99,
|
||||||
|
"failed": 0,
|
||||||
|
"ignored": 0,
|
||||||
|
"timing": "current implementation"
|
||||||
|
},
|
||||||
|
"other_passed_suites": [
|
||||||
|
{
|
||||||
|
"command": "cargo test -p admin-api --test integration openapi_import -- --test-threads=1",
|
||||||
|
"result": "PASS",
|
||||||
|
"passed": 24,
|
||||||
|
"failed": 0,
|
||||||
|
"ignored": 0,
|
||||||
|
"filtered_out": 64
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "cargo test -p crank-registry --test integration import_auth_binding -- --test-threads=1",
|
||||||
|
"result": "PASS",
|
||||||
|
"passed": 5,
|
||||||
|
"failed": 0,
|
||||||
|
"ignored": 0,
|
||||||
|
"filtered_out": 95
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "cargo test -p crank-runtime --all-targets",
|
||||||
|
"result": "PASS",
|
||||||
|
"passed": 83,
|
||||||
|
"failed": 0,
|
||||||
|
"ignored": 0,
|
||||||
|
"reported_by": "root"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"other_checks": [
|
||||||
|
{
|
||||||
|
"command": "just verify",
|
||||||
|
"result": "PASS",
|
||||||
|
"detail": "Repeat full workspace gate after review fixes exited 0; earlier file-size, advisory, fmt/clippy and stdout-redirection failures were resolved."
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"command": "git diff --check",
|
||||||
|
"result": "PASS"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"all_tests_skipped": false,
|
||||||
|
"expected_to_fail": false,
|
||||||
|
"e2e_tests": 0,
|
||||||
|
"note": "Historical RED evidence is preserved; all active acceptance tests and the final just verify gate pass. No skipped scaffold is counted as RED."
|
||||||
|
}
|
||||||
@@ -542,17 +542,48 @@ pub struct OpenApiImportPreviewResponse {
|
|||||||
pub job_id: String,
|
pub job_id: String,
|
||||||
pub expires_at: String,
|
pub expires_at: String,
|
||||||
pub preview: crank_import::rest::ImportPreview,
|
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<OpenApiAuthProfileChoice>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize)]
|
||||||
|
pub struct OpenApiAuthProfileChoice {
|
||||||
|
pub operation_key: String,
|
||||||
|
pub alternative_index: usize,
|
||||||
|
pub scheme_names: Vec<String>,
|
||||||
|
pub supported: bool,
|
||||||
|
pub profiles: Vec<OpenApiAuthProfileOption>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Serialize)]
|
||||||
|
pub struct OpenApiAuthProfileOption {
|
||||||
|
pub id: String,
|
||||||
|
pub name: String,
|
||||||
|
pub kind: AuthKind,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Deserialize)]
|
#[derive(Clone, Debug, Deserialize)]
|
||||||
pub struct OpenApiImportCreatePayload {
|
pub struct OpenApiImportCreatePayload {
|
||||||
pub selected_operation_keys: Vec<String>,
|
pub selected_operation_keys: Vec<String>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
pub auth_mappings: Vec<OpenApiAuthMapping>,
|
||||||
|
#[serde(default)]
|
||||||
pub server_url: Option<String>,
|
pub server_url: Option<String>,
|
||||||
#[serde(default = "default_openapi_conflict_mode")]
|
#[serde(default = "default_openapi_conflict_mode")]
|
||||||
pub conflict_mode: String,
|
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<String>,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Serialize)]
|
#[derive(Clone, Debug, Serialize)]
|
||||||
pub struct OpenApiImportCreateResponse {
|
pub struct OpenApiImportCreateResponse {
|
||||||
pub created: Vec<OpenApiImportCreatedOperation>,
|
pub created: Vec<OpenApiImportCreatedOperation>,
|
||||||
|
|||||||
@@ -135,6 +135,41 @@ impl ApiError {
|
|||||||
"OpenAPI document is invalid or unsupported"
|
"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") => {
|
(_, "no_methods") => {
|
||||||
if russian {
|
if russian {
|
||||||
"документ OpenAPI не содержит поддерживаемых методов"
|
"документ 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<String>, context: Value) -> Self {
|
pub(crate) fn rate_limited_with_context(message: impl Into<String>, context: Value) -> Self {
|
||||||
Self::RateLimited {
|
Self::RateLimited {
|
||||||
message: message.into(),
|
message: message.into(),
|
||||||
@@ -675,6 +722,10 @@ impl From<RegistryError> for ApiError {
|
|||||||
"value": value,
|
"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(
|
RegistryError::YamlImportJobNotFound { job_id } => Self::validation_with_context(
|
||||||
format!("yaml import job {job_id} was not found"),
|
format!("yaml import job {job_id} was not found"),
|
||||||
json!({ "job_id": job_id }),
|
json!({ "job_id": job_id }),
|
||||||
|
|||||||
@@ -134,9 +134,13 @@ mod tests {
|
|||||||
method: HttpMethod::Delete,
|
method: HttpMethod::Delete,
|
||||||
path_template: "/items/{id}".to_owned(),
|
path_template: "/items/{id}".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
}),
|
}),
|
||||||
input_schema: Schema {
|
input_schema: Schema {
|
||||||
kind: SchemaKind::Object,
|
kind: SchemaKind::Object,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
@@ -148,6 +152,7 @@ mod tests {
|
|||||||
},
|
},
|
||||||
output_schema: Schema {
|
output_schema: Schema {
|
||||||
kind: SchemaKind::Object,
|
kind: SchemaKind::Object,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: false,
|
required: false,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
@@ -198,6 +203,7 @@ mod tests {
|
|||||||
fn string_schema() -> Schema {
|
fn string_schema() -> Schema {
|
||||||
Schema {
|
Schema {
|
||||||
kind: SchemaKind::String,
|
kind: SchemaKind::String,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
|
|||||||
@@ -421,6 +421,9 @@ fn demo_rest_operation_payload() -> OperationPayload {
|
|||||||
method: crank_core::HttpMethod::Get,
|
method: crank_core::HttpMethod::Get,
|
||||||
path_template: "/v1/latest".to_owned(),
|
path_template: "/v1/latest".to_owned(),
|
||||||
static_headers: BTreeMap::from([("Accept".to_owned(), "application/json".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),
|
input_schema: Schema::from_json_sample(&input),
|
||||||
output_schema: Schema::from_json_sample(&output),
|
output_schema: Schema::from_json_sample(&output),
|
||||||
|
|||||||
@@ -12,8 +12,8 @@ use crank_import::rest::{
|
|||||||
use crank_registry::{
|
use crank_registry::{
|
||||||
ApplyImportJobRequest, ArtifactSourceId, ArtifactSourceSensitivity,
|
ApplyImportJobRequest, ArtifactSourceId, ArtifactSourceSensitivity,
|
||||||
CreateArtifactSourceRequest, CreateImportJobRequest, FinishImportJobRequest,
|
CreateArtifactSourceRequest, CreateImportJobRequest, FinishImportJobRequest,
|
||||||
ImportConflictMode, ImportJobApplyResult, ImportJobId, ImportJobKind, ImportJobSourceEnvelope,
|
ImportAuthRequirement, ImportConflictMode, ImportJobApplyResult, ImportJobId, ImportJobKind,
|
||||||
ImportJobStatus, ImportOperationDraft, RegistryError,
|
ImportJobSourceEnvelope, ImportJobStatus, ImportOperationDraft, RegistryError,
|
||||||
};
|
};
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
@@ -23,7 +23,7 @@ use tracing::{info, instrument};
|
|||||||
use crate::{
|
use crate::{
|
||||||
error::ApiError,
|
error::ApiError,
|
||||||
service::{
|
service::{
|
||||||
AdminService, OpenApiImportCreatePayload, OpenApiImportCreateResponse,
|
AdminService, OpenApiAuthMapping, OpenApiImportCreatePayload, OpenApiImportCreateResponse,
|
||||||
OpenApiImportCreatedOperation, OpenApiImportPreviewResponse, OpenApiImportSkippedOperation,
|
OpenApiImportCreatedOperation, OpenApiImportPreviewResponse, OpenApiImportSkippedOperation,
|
||||||
OpenApiUpload, OpenApiUploadLocale, OperationPayload, new_prefixed_id,
|
OpenApiUpload, OpenApiUploadLocale, OperationPayload, new_prefixed_id,
|
||||||
},
|
},
|
||||||
@@ -31,6 +31,7 @@ use crate::{
|
|||||||
|
|
||||||
mod external_references;
|
mod external_references;
|
||||||
mod job_contract;
|
mod job_contract;
|
||||||
|
mod security;
|
||||||
use external_references::ImportReplayContext;
|
use external_references::ImportReplayContext;
|
||||||
use job_contract::{
|
use job_contract::{
|
||||||
SourceDetachGuard, import_job_dependencies, import_job_normalization_config, import_job_source,
|
SourceDetachGuard, import_job_dependencies, import_job_normalization_config, import_job_source,
|
||||||
@@ -52,6 +53,14 @@ impl AdminService {
|
|||||||
self.ensure_workspace_exists(workspace_id).await?;
|
self.ensure_workspace_exists(workspace_id).await?;
|
||||||
|
|
||||||
validate_openapi_upload(&upload)?;
|
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 {
|
let OpenApiUpload {
|
||||||
bytes,
|
bytes,
|
||||||
mime_type,
|
mime_type,
|
||||||
@@ -105,6 +114,14 @@ impl AdminService {
|
|||||||
let mut dependencies = self
|
let mut dependencies = self
|
||||||
.materialize_external_reference_snapshots(workspace_id, &verified.bytes, now)
|
.materialize_external_reference_snapshots(workspace_id, &verified.bytes, now)
|
||||||
.await;
|
.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(
|
let parsed = match parse_verified_preview(
|
||||||
verified.bytes,
|
verified.bytes,
|
||||||
artifact.artifact_ref().digest_hex().to_owned(),
|
artifact.artifact_ref().digest_hex().to_owned(),
|
||||||
@@ -132,6 +149,17 @@ impl AdminService {
|
|||||||
detach_guard.detach_now().await;
|
detach_guard.detach_now().await;
|
||||||
return Err(ApiError::openapi_upload(locale, "no_methods"));
|
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 {
|
let source_envelope = ImportJobSourceEnvelope {
|
||||||
source_id,
|
source_id,
|
||||||
digest: artifact.artifact_ref().clone(),
|
digest: artifact.artifact_ref().clone(),
|
||||||
@@ -184,6 +212,7 @@ impl AdminService {
|
|||||||
expires_at: expires_at
|
expires_at: expires_at
|
||||||
.format(&Rfc3339)
|
.format(&Rfc3339)
|
||||||
.map_err(|error| ApiError::internal(error.to_string()))?,
|
.map_err(|error| ApiError::internal(error.to_string()))?,
|
||||||
|
auth_profile_choices,
|
||||||
preview: parsed.preview,
|
preview: parsed.preview,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -247,6 +276,15 @@ impl AdminService {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
let finished_at = OffsetDateTime::now_utc();
|
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 application_key = openapi_application_key(&payload)?;
|
||||||
let conflict_mode = if payload.conflict_mode == "skip" {
|
let conflict_mode = if payload.conflict_mode == "skip" {
|
||||||
ImportConflictMode::Skip
|
ImportConflictMode::Skip
|
||||||
@@ -425,6 +463,20 @@ impl AdminService {
|
|||||||
candidates.insert(operation.key.clone(), operation);
|
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 skipped = Vec::new();
|
||||||
let mut operations = Vec::new();
|
let mut operations = Vec::new();
|
||||||
@@ -438,6 +490,26 @@ impl AdminService {
|
|||||||
});
|
});
|
||||||
continue;
|
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 =
|
let mut draft =
|
||||||
operation_draft_from_candidate(candidate, payload.server_url.as_deref());
|
operation_draft_from_candidate(candidate, payload.server_url.as_deref());
|
||||||
attach_import_findings(&mut draft, candidate);
|
attach_import_findings(&mut draft, candidate);
|
||||||
@@ -459,7 +531,7 @@ impl AdminService {
|
|||||||
idempotency: None,
|
idempotency: None,
|
||||||
safety: None,
|
safety: None,
|
||||||
approval_policy: None,
|
approval_policy: None,
|
||||||
auth_profile_ref: None,
|
auth_profile_ref,
|
||||||
headers: BTreeMap::new(),
|
headers: BTreeMap::new(),
|
||||||
},
|
},
|
||||||
tool_description: draft.tool_description,
|
tool_description: draft.tool_description,
|
||||||
@@ -468,6 +540,7 @@ impl AdminService {
|
|||||||
operations.push(ImportOperationDraft {
|
operations.push(ImportOperationDraft {
|
||||||
operation_key: candidate.key.clone(),
|
operation_key: candidate.key.clone(),
|
||||||
operation,
|
operation,
|
||||||
|
auth_requirement,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -482,7 +555,13 @@ impl AdminService {
|
|||||||
pre_skipped: &skipped,
|
pre_skipped: &skipped,
|
||||||
finished_at: &finished_at,
|
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))
|
Ok(openapi_import_response(applied))
|
||||||
}
|
}
|
||||||
@@ -639,7 +718,14 @@ fn import_replay_contract(
|
|||||||
if normalizer == NORMALIZER_VERSION && projection == PROJECTION_VERSION {
|
if normalizer == NORMALIZER_VERSION && projection == PROJECTION_VERSION {
|
||||||
return Ok(ImportReplayContract::Current);
|
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"));
|
return Err(ApiError::openapi_upload(locale, "source_integrity"));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -812,7 +898,15 @@ fn preview_has_blocker(
|
|||||||
.flat_map(|group| group.operations.iter())
|
.flat_map(|group| group.operations.iter())
|
||||||
.filter(|operation| selected_operation_keys.contains(&operation.key))
|
.filter(|operation| selected_operation_keys.contains(&operation.key))
|
||||||
.flat_map(|operation| operation.findings.iter())
|
.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<String, ApiError> {
|
fn openapi_application_key(payload: &OpenApiImportCreatePayload) -> Result<String, ApiError> {
|
||||||
@@ -821,8 +915,15 @@ fn openapi_application_key(payload: &OpenApiImportCreatePayload) -> Result<Strin
|
|||||||
.iter()
|
.iter()
|
||||||
.cloned()
|
.cloned()
|
||||||
.collect::<BTreeSet<_>>();
|
.collect::<BTreeSet<_>>();
|
||||||
|
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!({
|
let canonical = serde_json::to_vec(&json!({
|
||||||
"selected_operation_keys": selected_operation_keys,
|
"selected_operation_keys": selected_operation_keys,
|
||||||
|
"auth_mappings": auth_mappings,
|
||||||
"server_url": payload.server_url.as_deref(),
|
"server_url": payload.server_url.as_deref(),
|
||||||
"conflict_mode": payload.conflict_mode.as_str(),
|
"conflict_mode": payload.conflict_mode.as_str(),
|
||||||
}))
|
}))
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ use tracing::warn;
|
|||||||
|
|
||||||
pub(super) struct MaterializedDependencies {
|
pub(super) struct MaterializedDependencies {
|
||||||
pub(super) snapshots: Vec<crank_import::rest::ExternalDocumentSnapshot>,
|
pub(super) snapshots: Vec<crank_import::rest::ExternalDocumentSnapshot>,
|
||||||
|
pub(super) secret_literal_rejected: bool,
|
||||||
envelopes: Vec<ImportJobSourceEnvelope>,
|
envelopes: Vec<ImportJobSourceEnvelope>,
|
||||||
canonical_uris: Vec<String>,
|
canonical_uris: Vec<String>,
|
||||||
guards: Vec<SourceDetachGuard>,
|
guards: Vec<SourceDetachGuard>,
|
||||||
@@ -21,6 +22,7 @@ impl MaterializedDependencies {
|
|||||||
fn empty() -> Self {
|
fn empty() -> Self {
|
||||||
Self {
|
Self {
|
||||||
snapshots: Vec::new(),
|
snapshots: Vec::new(),
|
||||||
|
secret_literal_rejected: false,
|
||||||
envelopes: Vec::new(),
|
envelopes: Vec::new(),
|
||||||
canonical_uris: Vec::new(),
|
canonical_uris: Vec::new(),
|
||||||
guards: Vec::new(),
|
guards: Vec::new(),
|
||||||
@@ -207,6 +209,26 @@ impl AdminService {
|
|||||||
);
|
);
|
||||||
continue;
|
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(
|
let Ok(references) = crank_import::rest::external_reference_uris(
|
||||||
&document,
|
&document,
|
||||||
&self.external_reference_normalization,
|
&self.external_reference_normalization,
|
||||||
@@ -368,6 +390,14 @@ impl AdminService {
|
|||||||
}
|
}
|
||||||
let document = String::from_utf8(verified.bytes)
|
let document = String::from_utf8(verified.bytes)
|
||||||
.map_err(|_| ApiError::openapi_upload(locale, "source_integrity"))?;
|
.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 =
|
let digest =
|
||||||
crank_import::rest::SourceDigest::parse(dependency.digest.digest_hex().to_owned())
|
crank_import::rest::SourceDigest::parse(dependency.digest.digest_hex().to_owned())
|
||||||
.map_err(|_| ApiError::openapi_upload(locale, "source_integrity"))?;
|
.map_err(|_| ApiError::openapi_upload(locale, "source_integrity"))?;
|
||||||
|
|||||||
@@ -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<Vec<OpenApiAuthProfileChoice>, ApiError> {
|
||||||
|
let mut profiles = self
|
||||||
|
.registry
|
||||||
|
.list_auth_profiles(workspace_id)
|
||||||
|
.await?
|
||||||
|
.into_iter()
|
||||||
|
.filter(|profile| profile.kind == profile.config.kind())
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
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<AuthProfileId>, Option<ImportAuthRequirement>), 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<ImportAuthRequirement> {
|
||||||
|
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<bool, ApiError> {
|
||||||
|
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)
|
||||||
|
}
|
||||||
@@ -93,7 +93,14 @@ pub(super) fn validate_idempotency_policy(
|
|||||||
}
|
}
|
||||||
|
|
||||||
match target {
|
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(
|
return Err(ApiError::validation_with_context(
|
||||||
"idempotency is supported only for mutating REST operations".to_owned(),
|
"idempotency is supported only for mutating REST operations".to_owned(),
|
||||||
@@ -206,6 +213,9 @@ mod tests {
|
|||||||
method: HttpMethod::Get,
|
method: HttpMethod::Get,
|
||||||
path_template: "/catalog".to_owned(),
|
path_template: "/catalog".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
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());
|
let result = validate_response_cache_policy(&target, &cacheable_execution_config());
|
||||||
@@ -233,6 +243,9 @@ mod tests {
|
|||||||
method: HttpMethod::Post,
|
method: HttpMethod::Post,
|
||||||
path_template: "/catalog".to_owned(),
|
path_template: "/catalog".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
});
|
});
|
||||||
|
|
||||||
let error =
|
let error =
|
||||||
@@ -252,6 +265,9 @@ mod tests {
|
|||||||
method: HttpMethod::Post,
|
method: HttpMethod::Post,
|
||||||
path_template: "/orders".to_owned(),
|
path_template: "/orders".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
});
|
});
|
||||||
|
|
||||||
let result = validate_idempotency_policy(
|
let result = validate_idempotency_policy(
|
||||||
@@ -269,6 +285,9 @@ mod tests {
|
|||||||
method: HttpMethod::Get,
|
method: HttpMethod::Get,
|
||||||
path_template: "/orders".to_owned(),
|
path_template: "/orders".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
});
|
});
|
||||||
|
|
||||||
let error = validate_idempotency_policy(
|
let error = validate_idempotency_policy(
|
||||||
@@ -291,6 +310,9 @@ mod tests {
|
|||||||
method: HttpMethod::Post,
|
method: HttpMethod::Post,
|
||||||
path_template: "/orders".to_owned(),
|
path_template: "/orders".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
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 mut config = idempotent_execution_config(IdempotencyMode::Required);
|
||||||
let policy = config.idempotency.as_mut().unwrap();
|
let policy = config.idempotency.as_mut().unwrap();
|
||||||
|
|||||||
@@ -435,6 +435,9 @@ pub(super) fn test_operation_payload(base_url: &str, name: &str) -> OperationPay
|
|||||||
method: HttpMethod::Post,
|
method: HttpMethod::Post,
|
||||||
path_template: "/crm/leads".to_owned(),
|
path_template: "/crm/leads".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
}),
|
}),
|
||||||
input_schema: object_schema("email"),
|
input_schema: object_schema("email"),
|
||||||
output_schema: object_schema("id"),
|
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 {
|
pub(super) fn object_schema(field_name: &str) -> Schema {
|
||||||
Schema {
|
Schema {
|
||||||
kind: SchemaKind::Object,
|
kind: SchemaKind::Object,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
@@ -491,6 +495,7 @@ pub(super) fn object_schema(field_name: &str) -> Schema {
|
|||||||
field_name.to_owned(),
|
field_name.to_owned(),
|
||||||
Schema {
|
Schema {
|
||||||
kind: SchemaKind::String,
|
kind: SchemaKind::String,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
|
|||||||
@@ -323,6 +323,9 @@ async fn rejects_response_cache_for_operation_with_auth_profile() {
|
|||||||
method: HttpMethod::Get,
|
method: HttpMethod::Get,
|
||||||
path_template: "/crm/leads".to_owned(),
|
path_template: "/crm/leads".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
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.response_cache = Some(ResponseCachePolicy { ttl_ms: 5_000 });
|
||||||
payload.execution_config.auth_profile_ref = Some("auth_profile_01".into());
|
payload.execution_config.auth_profile_ref = Some("auth_profile_01".into());
|
||||||
|
|||||||
@@ -1,15 +1,23 @@
|
|||||||
use admin_api::service::{
|
use admin_api::service::{
|
||||||
AdminServiceBuilder, OpenApiImportCreatePayload, OpenApiUpload, OpenApiUploadLocale,
|
AdminServiceBuilder, AuthProfilePayload, OpenApiAuthMapping, OpenApiImportCreatePayload,
|
||||||
|
OpenApiImportCreateResponse, OpenApiUpload, OpenApiUploadLocale, SecretPayload,
|
||||||
};
|
};
|
||||||
use crank_core::WorkspaceId;
|
use crank_core::{
|
||||||
use crank_registry::ImportJobStatus;
|
AuthConfig, AuthKind, BearerAuthConfig, SecretId, SecretKind, Workspace, WorkspaceId,
|
||||||
|
WorkspaceStatus,
|
||||||
|
};
|
||||||
|
use crank_registry::{CreateWorkspaceRequest, ImportJobStatus};
|
||||||
|
use serde_json::json;
|
||||||
use serial_test::serial;
|
use serial_test::serial;
|
||||||
|
use sha2::Digest;
|
||||||
|
|
||||||
use super::common::{
|
use super::common::{
|
||||||
test_auth_settings, test_registry, test_secret_crypto, test_service, test_storage_root,
|
test_auth_settings, test_registry, test_secret_crypto, test_service, test_storage_root,
|
||||||
};
|
};
|
||||||
|
|
||||||
mod external_references;
|
mod external_references;
|
||||||
|
mod http_contract;
|
||||||
|
mod security;
|
||||||
|
|
||||||
const OPENAPI3: &str = r#"
|
const OPENAPI3: &str = r#"
|
||||||
openapi: 3.0.3
|
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.status, ImportJobStatus::Pending);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
preview_job.preview_payload["normalization"]["normalizer_version"],
|
preview_job.preview_payload["normalization"]["normalizer_version"],
|
||||||
"normalized-ir-v3"
|
"normalized-ir-v5"
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
preview_job.preview_payload["normalization"]["projection_version"],
|
preview_job.preview_payload["normalization"]["projection_version"],
|
||||||
"preview-v3"
|
"preview-v5"
|
||||||
);
|
);
|
||||||
assert!(preview_job.preview_payload["normalization"]["ir_fingerprint"].is_string());
|
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(),
|
&preview.job_id.as_str().into(),
|
||||||
OpenApiImportCreatePayload {
|
OpenApiImportCreatePayload {
|
||||||
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
||||||
|
auth_mappings: vec![],
|
||||||
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||||
conflict_mode: "skip".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(),
|
&preview.job_id.as_str().into(),
|
||||||
OpenApiImportCreatePayload {
|
OpenApiImportCreatePayload {
|
||||||
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
||||||
|
auth_mappings: vec![],
|
||||||
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||||
conflict_mode: "skip".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(),
|
&skip_preview.job_id.as_str().into(),
|
||||||
OpenApiImportCreatePayload {
|
OpenApiImportCreatePayload {
|
||||||
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
||||||
|
auth_mappings: vec![],
|
||||||
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||||
conflict_mode: "skip".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(),
|
&rename_preview.job_id.as_str().into(),
|
||||||
OpenApiImportCreatePayload {
|
OpenApiImportCreatePayload {
|
||||||
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
||||||
|
auth_mappings: vec![],
|
||||||
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||||
conflict_mode: "rename".to_owned(),
|
conflict_mode: "rename".to_owned(),
|
||||||
},
|
},
|
||||||
@@ -212,6 +224,7 @@ async fn unknown_selected_operations_are_persisted_in_the_canonical_replay() {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
let payload = OpenApiImportCreatePayload {
|
let payload = OpenApiImportCreatePayload {
|
||||||
selected_operation_keys: vec!["GET /v2/latest".to_owned(), "GET /missing".to_owned()],
|
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()),
|
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||||
conflict_mode: "skip".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 job_id = preview.job_id.as_str().into();
|
||||||
let payload = OpenApiImportCreatePayload {
|
let payload = OpenApiImportCreatePayload {
|
||||||
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
||||||
|
auth_mappings: vec![],
|
||||||
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||||
conflict_mode: "rename".to_owned(),
|
conflict_mode: "rename".to_owned(),
|
||||||
};
|
};
|
||||||
@@ -307,6 +321,7 @@ async fn concurrent_openapi_import_replays_the_same_atomic_result() {
|
|||||||
&job_id,
|
&job_id,
|
||||||
OpenApiImportCreatePayload {
|
OpenApiImportCreatePayload {
|
||||||
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
||||||
|
auth_mappings: vec![],
|
||||||
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||||
conflict_mode: "skip".to_owned(),
|
conflict_mode: "skip".to_owned(),
|
||||||
},
|
},
|
||||||
@@ -348,6 +363,7 @@ async fn apply_fails_closed_when_the_preview_parser_contract_drifts() {
|
|||||||
&job_id,
|
&job_id,
|
||||||
OpenApiImportCreatePayload {
|
OpenApiImportCreatePayload {
|
||||||
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
||||||
|
auth_mappings: vec![],
|
||||||
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||||
conflict_mode: "rename".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,
|
&job_id,
|
||||||
OpenApiImportCreatePayload {
|
OpenApiImportCreatePayload {
|
||||||
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
||||||
|
auth_mappings: vec![],
|
||||||
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||||
conflict_mode: "rename".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]
|
#[tokio::test]
|
||||||
#[serial]
|
#[serial]
|
||||||
async fn legacy_job_without_normalization_contract_replays_until_expiry() {
|
async fn legacy_job_without_normalization_contract_replays_until_expiry() {
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
let registry = test_registry().await;
|
let registry = test_registry().await;
|
||||||
let service = test_service(
|
let service = test_service(
|
||||||
registry.clone(),
|
registry.clone(),
|
||||||
@@ -464,10 +483,22 @@ async fn legacy_job_without_normalization_contract_replays_until_expiry() {
|
|||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let job_id: crank_registry::ImportJobId = preview.job_id.as_str().into();
|
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(
|
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(job_id.as_str())
|
||||||
|
.bind(legacy_preview)
|
||||||
|
.bind(legacy_digest)
|
||||||
.execute(registry.pool())
|
.execute(registry.pool())
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -478,6 +509,7 @@ async fn legacy_job_without_normalization_contract_replays_until_expiry() {
|
|||||||
&job_id,
|
&job_id,
|
||||||
OpenApiImportCreatePayload {
|
OpenApiImportCreatePayload {
|
||||||
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
||||||
|
auth_mappings: vec![],
|
||||||
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||||
conflict_mode: "skip".to_owned(),
|
conflict_mode: "skip".to_owned(),
|
||||||
},
|
},
|
||||||
@@ -532,6 +564,7 @@ paths:
|
|||||||
&preview.job_id.as_str().into(),
|
&preview.job_id.as_str().into(),
|
||||||
OpenApiImportCreatePayload {
|
OpenApiImportCreatePayload {
|
||||||
selected_operation_keys: vec!["GET /valid".to_owned()],
|
selected_operation_keys: vec!["GET /valid".to_owned()],
|
||||||
|
auth_mappings: vec![],
|
||||||
server_url: None,
|
server_url: None,
|
||||||
conflict_mode: "skip".to_owned(),
|
conflict_mode: "skip".to_owned(),
|
||||||
},
|
},
|
||||||
@@ -619,6 +652,7 @@ paths:
|
|||||||
&valid_preview.job_id.as_str().into(),
|
&valid_preview.job_id.as_str().into(),
|
||||||
OpenApiImportCreatePayload {
|
OpenApiImportCreatePayload {
|
||||||
selected_operation_keys: vec!["GET /valid".to_owned()],
|
selected_operation_keys: vec!["GET /valid".to_owned()],
|
||||||
|
auth_mappings: vec![],
|
||||||
server_url: None,
|
server_url: None,
|
||||||
conflict_mode: "skip".to_owned(),
|
conflict_mode: "skip".to_owned(),
|
||||||
},
|
},
|
||||||
@@ -637,6 +671,7 @@ paths:
|
|||||||
&full_preview.job_id.as_str().into(),
|
&full_preview.job_id.as_str().into(),
|
||||||
OpenApiImportCreatePayload {
|
OpenApiImportCreatePayload {
|
||||||
selected_operation_keys: vec!["GET /valid".to_owned(), "GET /broken".to_owned()],
|
selected_operation_keys: vec!["GET /valid".to_owned(), "GET /broken".to_owned()],
|
||||||
|
auth_mappings: vec![],
|
||||||
server_url: None,
|
server_url: None,
|
||||||
conflict_mode: "rename".to_owned(),
|
conflict_mode: "rename".to_owned(),
|
||||||
},
|
},
|
||||||
@@ -718,6 +753,7 @@ components:
|
|||||||
&preview.job_id.as_str().into(),
|
&preview.job_id.as_str().into(),
|
||||||
OpenApiImportCreatePayload {
|
OpenApiImportCreatePayload {
|
||||||
selected_operation_keys: vec!["GET /referenced".to_owned()],
|
selected_operation_keys: vec!["GET /referenced".to_owned()],
|
||||||
|
auth_mappings: vec![],
|
||||||
server_url: None,
|
server_url: None,
|
||||||
conflict_mode: "skip".to_owned(),
|
conflict_mode: "skip".to_owned(),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -99,6 +99,7 @@ paths:
|
|||||||
&preview.job_id.as_str().into(),
|
&preview.job_id.as_str().into(),
|
||||||
OpenApiImportCreatePayload {
|
OpenApiImportCreatePayload {
|
||||||
selected_operation_keys: vec!["GET /items".to_owned()],
|
selected_operation_keys: vec!["GET /items".to_owned()],
|
||||||
|
auth_mappings: vec![],
|
||||||
server_url: None,
|
server_url: None,
|
||||||
conflict_mode: "skip".to_owned(),
|
conflict_mode: "skip".to_owned(),
|
||||||
},
|
},
|
||||||
@@ -117,6 +118,73 @@ paths:
|
|||||||
assert_eq!(active_sources, 0);
|
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]
|
#[tokio::test]
|
||||||
#[serial]
|
#[serial]
|
||||||
async fn missing_external_snapshot_fails_closed_before_draft_mutation() {
|
async fn missing_external_snapshot_fails_closed_before_draft_mutation() {
|
||||||
@@ -188,6 +256,7 @@ paths:
|
|||||||
&preview.job_id.as_str().into(),
|
&preview.job_id.as_str().into(),
|
||||||
OpenApiImportCreatePayload {
|
OpenApiImportCreatePayload {
|
||||||
selected_operation_keys: vec!["GET /items".to_owned()],
|
selected_operation_keys: vec!["GET /items".to_owned()],
|
||||||
|
auth_mappings: vec![],
|
||||||
server_url: None,
|
server_url: None,
|
||||||
conflict_mode: "skip".to_owned(),
|
conflict_mode: "skip".to_owned(),
|
||||||
},
|
},
|
||||||
@@ -270,6 +339,7 @@ paths:
|
|||||||
&corrupt_preview.job_id.as_str().into(),
|
&corrupt_preview.job_id.as_str().into(),
|
||||||
OpenApiImportCreatePayload {
|
OpenApiImportCreatePayload {
|
||||||
selected_operation_keys: vec!["GET /items".to_owned()],
|
selected_operation_keys: vec!["GET /items".to_owned()],
|
||||||
|
auth_mappings: vec![],
|
||||||
server_url: None,
|
server_url: None,
|
||||||
conflict_mode: "skip".to_owned(),
|
conflict_mode: "skip".to_owned(),
|
||||||
},
|
},
|
||||||
@@ -522,6 +592,155 @@ async fn exact_v2_contract_replays_persisted_preview_without_v3_or_dependency_re
|
|||||||
&job_id,
|
&job_id,
|
||||||
OpenApiImportCreatePayload {
|
OpenApiImportCreatePayload {
|
||||||
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
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()),
|
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||||
conflict_mode: "skip".to_owned(),
|
conflict_mode: "skip".to_owned(),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -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::<Vec<_>>();
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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::<Vec<_>>();
|
||||||
|
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::<Vec<_>>();
|
||||||
|
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<OpenApiImportCreateResponse, admin_api::error::ApiError> {
|
||||||
|
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
|
||||||
|
}
|
||||||
@@ -512,6 +512,7 @@ async fn apply_rereads_the_scoped_verified_source_and_expiry_detaches_it() {
|
|||||||
&job_id,
|
&job_id,
|
||||||
OpenApiImportCreatePayload {
|
OpenApiImportCreatePayload {
|
||||||
selected_operation_keys: vec!["GET /health".to_owned()],
|
selected_operation_keys: vec!["GET /health".to_owned()],
|
||||||
|
auth_mappings: vec![],
|
||||||
server_url: None,
|
server_url: None,
|
||||||
conflict_mode: "skip".to_owned(),
|
conflict_mode: "skip".to_owned(),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -245,6 +245,7 @@ async fn apply_health_operation(
|
|||||||
job_id,
|
job_id,
|
||||||
OpenApiImportCreatePayload {
|
OpenApiImportCreatePayload {
|
||||||
selected_operation_keys: vec!["GET /health".to_owned()],
|
selected_operation_keys: vec!["GET /health".to_owned()],
|
||||||
|
auth_mappings: vec![],
|
||||||
server_url: None,
|
server_url: None,
|
||||||
conflict_mode: "skip".to_owned(),
|
conflict_mode: "skip".to_owned(),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -489,6 +489,9 @@ pub(super) fn test_operation(base_url: &str, name: &str) -> Operation<Schema, Ma
|
|||||||
method: HttpMethod::Post,
|
method: HttpMethod::Post,
|
||||||
path_template: "/crm/leads".to_owned(),
|
path_template: "/crm/leads".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
}),
|
}),
|
||||||
input_schema: object_schema("email"),
|
input_schema: object_schema("email"),
|
||||||
output_schema: object_schema("id"),
|
output_schema: object_schema("id"),
|
||||||
@@ -543,6 +546,7 @@ pub(super) fn test_operation(base_url: &str, name: &str) -> Operation<Schema, Ma
|
|||||||
pub(super) fn object_schema(field_name: &str) -> Schema {
|
pub(super) fn object_schema(field_name: &str) -> Schema {
|
||||||
Schema {
|
Schema {
|
||||||
kind: SchemaKind::Object,
|
kind: SchemaKind::Object,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
@@ -551,6 +555,7 @@ pub(super) fn object_schema(field_name: &str) -> Schema {
|
|||||||
field_name.to_owned(),
|
field_name.to_owned(),
|
||||||
Schema {
|
Schema {
|
||||||
kind: SchemaKind::String,
|
kind: SchemaKind::String,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ version.workspace = true
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
async-trait = "0.1"
|
async-trait = "0.1"
|
||||||
|
base64.workspace = true
|
||||||
crank-core = { path = "../crank-core" }
|
crank-core = { path = "../crank-core" }
|
||||||
crank-metrics = { path = "../crank-metrics" }
|
crank-metrics = { path = "../crank-metrics" }
|
||||||
crank-trace = { path = "../crank-trace" }
|
crank-trace = { path = "../crank-trace" }
|
||||||
|
|||||||
@@ -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<String, Vec<String>>>,
|
||||||
|
max_request_bytes: usize,
|
||||||
|
) -> Result<reqwest::RequestBuilder, RestAdapterError> {
|
||||||
|
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<reqwest::RequestBuilder, RestAdapterError> {
|
||||||
|
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<Option<String>, RestAdapterError> {
|
||||||
|
let Some(contract) = &target.request_contract else {
|
||||||
|
if request.body_content_type.is_some() {
|
||||||
|
return Err(RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "body content type requires a typed request contract".to_owned(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let selected = match (&contract.selector_field, &request.body_content_type) {
|
||||||
|
(Some(_), Some(selected)) => selected,
|
||||||
|
(Some(_), None) => {
|
||||||
|
return Err(RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "content_type selector is required".to_owned(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
(None, Some(_)) => {
|
||||||
|
return Err(RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "single-variant request does not accept a selector".to_owned(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
(None, None) => contract
|
||||||
|
.variants
|
||||||
|
.as_slice()
|
||||||
|
.first()
|
||||||
|
.filter(|_| contract.variants.len() == 1)
|
||||||
|
.map(|variant| &variant.media_type)
|
||||||
|
.ok_or_else(|| RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "request contract without selector must have one media variant".to_owned(),
|
||||||
|
})?,
|
||||||
|
};
|
||||||
|
contract
|
||||||
|
.variants
|
||||||
|
.iter()
|
||||||
|
.any(|variant| variant.media_type == *selected)
|
||||||
|
.then(|| selected.clone())
|
||||||
|
.map(Some)
|
||||||
|
.ok_or_else(|| RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "content_type selector is not declared by request contract".to_owned(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn json_bytes(body: &Value, limit_bytes: usize) -> Result<Vec<u8>, RestAdapterError> {
|
||||||
|
let mut encoded = BoundedBuffer::new(limit_bytes);
|
||||||
|
let result = serde_json::to_writer(&mut encoded, body);
|
||||||
|
if encoded.exceeded {
|
||||||
|
return Err(RestAdapterError::RequestTooLarge { limit_bytes });
|
||||||
|
}
|
||||||
|
result.map_err(|_| RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "body cannot be serialized as JSON".to_owned(),
|
||||||
|
})?;
|
||||||
|
Ok(encoded.into_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn form_urlencoded(body: &Value, limit_bytes: usize) -> Result<Vec<u8>, RestAdapterError> {
|
||||||
|
let object = body
|
||||||
|
.as_object()
|
||||||
|
.ok_or_else(|| RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "form body must be an object".to_owned(),
|
||||||
|
})?;
|
||||||
|
let mut encoded = BoundedBuffer::new(limit_bytes);
|
||||||
|
let mut first = true;
|
||||||
|
for (name, value) in object {
|
||||||
|
match value {
|
||||||
|
Value::Array(values) => {
|
||||||
|
for value in values {
|
||||||
|
append_form_pair(&mut encoded, &mut first, name, &form_scalar(value)?)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
value => {
|
||||||
|
append_form_pair(&mut encoded, &mut first, name, &form_scalar(value)?)?;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
Ok(encoded.into_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn append_form_pair(
|
||||||
|
encoded: &mut BoundedBuffer,
|
||||||
|
first: &mut bool,
|
||||||
|
name: &str,
|
||||||
|
value: &str,
|
||||||
|
) -> Result<(), RestAdapterError> {
|
||||||
|
if !*first {
|
||||||
|
encoded.append(b"&")?;
|
||||||
|
}
|
||||||
|
*first = false;
|
||||||
|
append_form_component(encoded, name.as_bytes())?;
|
||||||
|
encoded.append(b"=")?;
|
||||||
|
append_form_component(encoded, value.as_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn append_form_component(
|
||||||
|
encoded: &mut BoundedBuffer,
|
||||||
|
value: &[u8],
|
||||||
|
) -> Result<(), RestAdapterError> {
|
||||||
|
const HEX: &[u8; 16] = b"0123456789ABCDEF";
|
||||||
|
for byte in value {
|
||||||
|
match byte {
|
||||||
|
b'*' | b'-' | b'.' | b'0'..=b'9' | b'A'..=b'Z' | b'_' | b'a'..=b'z' => {
|
||||||
|
encoded.append(&[*byte])?;
|
||||||
|
}
|
||||||
|
b' ' => encoded.append(b"+")?,
|
||||||
|
_ => encoded.append(&[b'%', HEX[(byte >> 4) as usize], HEX[(byte & 0x0f) as usize]])?,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn form_scalar(value: &Value) -> Result<String, RestAdapterError> {
|
||||||
|
match value {
|
||||||
|
Value::Null => Ok("null".to_owned()),
|
||||||
|
Value::Bool(value) => Ok(value.to_string()),
|
||||||
|
Value::Number(value) => Ok(value.to_string()),
|
||||||
|
Value::String(value) => Ok(value.clone()),
|
||||||
|
Value::Array(_) | Value::Object(_) => Err(RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "form fields must be scalar or arrays of scalars".to_owned(),
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn multipart_form(
|
||||||
|
body: &Value,
|
||||||
|
source_mime_types: Option<&BTreeMap<String, Vec<String>>>,
|
||||||
|
max_request_bytes: usize,
|
||||||
|
) -> Result<reqwest::multipart::Form, RestAdapterError> {
|
||||||
|
let object = body
|
||||||
|
.as_object()
|
||||||
|
.ok_or_else(|| RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "multipart body must be an object".to_owned(),
|
||||||
|
})?;
|
||||||
|
let mut form = reqwest::multipart::Form::new();
|
||||||
|
let mut payload_budget = MultipartPayloadBudget::new(max_request_bytes);
|
||||||
|
for (name, value) in object {
|
||||||
|
let values = value
|
||||||
|
.as_array()
|
||||||
|
.map_or_else(|| vec![value], |values| values.iter().collect());
|
||||||
|
for value in values {
|
||||||
|
if let Some(file) = value
|
||||||
|
.as_object()
|
||||||
|
.filter(|file| file.contains_key("data_base64"))
|
||||||
|
{
|
||||||
|
form = form.part(
|
||||||
|
name.clone(),
|
||||||
|
multipart_file(name, file, source_mime_types, &mut payload_budget)?,
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
let value = form_scalar(value)?;
|
||||||
|
payload_budget.reserve(value.len())?;
|
||||||
|
form = form.text(name.clone(), value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(form)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn multipart_file(
|
||||||
|
field_name: &str,
|
||||||
|
file: &serde_json::Map<String, Value>,
|
||||||
|
source_mime_types: Option<&BTreeMap<String, Vec<String>>>,
|
||||||
|
payload_budget: &mut MultipartPayloadBudget,
|
||||||
|
) -> Result<reqwest::multipart::Part, RestAdapterError> {
|
||||||
|
if file
|
||||||
|
.keys()
|
||||||
|
.any(|key| !matches!(key.as_str(), "data_base64" | "filename" | "content_type"))
|
||||||
|
{
|
||||||
|
return Err(RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "file object contains unsupported field".to_owned(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let encoded = file
|
||||||
|
.get("data_base64")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.ok_or_else(|| RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "file data_base64 must be a string".to_owned(),
|
||||||
|
})?;
|
||||||
|
if encoded.chars().any(char::is_whitespace)
|
||||||
|
|| encoded.contains('-')
|
||||||
|
|| encoded.contains('_')
|
||||||
|
|| encoded.starts_with("data:")
|
||||||
|
{
|
||||||
|
return Err(RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "file data_base64 is not standard base64".to_owned(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
payload_budget.reserve(decoded_base64_len(encoded)?)?;
|
||||||
|
let bytes = STANDARD
|
||||||
|
.decode(encoded)
|
||||||
|
.map_err(|_| RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "file data_base64 is invalid".to_owned(),
|
||||||
|
})?;
|
||||||
|
let mut part = reqwest::multipart::Part::bytes(bytes);
|
||||||
|
if let Some(filename) = file.get("filename") {
|
||||||
|
let filename = filename
|
||||||
|
.as_str()
|
||||||
|
.filter(|value| !value.chars().any(char::is_control))
|
||||||
|
.ok_or_else(|| RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "filename is invalid".to_owned(),
|
||||||
|
})?;
|
||||||
|
part = part.file_name(filename.to_owned());
|
||||||
|
}
|
||||||
|
let allowed_mime_types = source_mime_types.and_then(|fields| fields.get(field_name));
|
||||||
|
if let Some(mime) = file.get("content_type") {
|
||||||
|
let mime = mime
|
||||||
|
.as_str()
|
||||||
|
.filter(|value| !value.chars().any(char::is_control))
|
||||||
|
.ok_or_else(|| RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "content_type is invalid".to_owned(),
|
||||||
|
})?;
|
||||||
|
validate_part_mime_type(mime, allowed_mime_types)?;
|
||||||
|
part = part
|
||||||
|
.mime_str(mime)
|
||||||
|
.map_err(|_| RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "content_type is invalid".to_owned(),
|
||||||
|
})?;
|
||||||
|
} else if let Some(allowed) = allowed_mime_types {
|
||||||
|
match allowed.as_slice() {
|
||||||
|
[mime] => {
|
||||||
|
validate_part_mime_type(mime, Some(allowed))?;
|
||||||
|
part = part
|
||||||
|
.mime_str(mime)
|
||||||
|
.map_err(|_| RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "source content_type is invalid".to_owned(),
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
[] => {}
|
||||||
|
_ => {
|
||||||
|
return Err(RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "content_type is required for this file field".to_owned(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
part = part.mime_str("application/octet-stream").map_err(|_| {
|
||||||
|
RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "default content_type is invalid".to_owned(),
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
Ok(part)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decoded_base64_len(encoded: &str) -> Result<usize, RestAdapterError> {
|
||||||
|
let padding = if encoded.ends_with("==") {
|
||||||
|
2
|
||||||
|
} else if encoded.ends_with('=') {
|
||||||
|
1
|
||||||
|
} else {
|
||||||
|
0
|
||||||
|
};
|
||||||
|
encoded
|
||||||
|
.len()
|
||||||
|
.checked_div(4)
|
||||||
|
.and_then(|groups| groups.checked_mul(3))
|
||||||
|
.and_then(|bytes| bytes.checked_sub(padding))
|
||||||
|
.ok_or_else(|| RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "file data_base64 is invalid".to_owned(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
struct MultipartPayloadBudget {
|
||||||
|
bytes: usize,
|
||||||
|
limit_bytes: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MultipartPayloadBudget {
|
||||||
|
fn new(limit_bytes: usize) -> Self {
|
||||||
|
Self {
|
||||||
|
bytes: 0,
|
||||||
|
limit_bytes,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reserve(&mut self, bytes: usize) -> Result<(), RestAdapterError> {
|
||||||
|
if self.bytes.saturating_add(bytes) > self.limit_bytes {
|
||||||
|
return Err(RestAdapterError::RequestTooLarge {
|
||||||
|
limit_bytes: self.limit_bytes,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
self.bytes += bytes;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct BoundedBuffer {
|
||||||
|
bytes: Vec<u8>,
|
||||||
|
limit_bytes: usize,
|
||||||
|
exceeded: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BoundedBuffer {
|
||||||
|
fn new(limit_bytes: usize) -> Self {
|
||||||
|
Self {
|
||||||
|
bytes: Vec::new(),
|
||||||
|
limit_bytes,
|
||||||
|
exceeded: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn append(&mut self, bytes: &[u8]) -> Result<(), RestAdapterError> {
|
||||||
|
if self.bytes.len().saturating_add(bytes.len()) > self.limit_bytes {
|
||||||
|
self.exceeded = true;
|
||||||
|
return Err(RestAdapterError::RequestTooLarge {
|
||||||
|
limit_bytes: self.limit_bytes,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
self.bytes.extend_from_slice(bytes);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn into_bytes(self) -> Vec<u8> {
|
||||||
|
self.bytes
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl io::Write for BoundedBuffer {
|
||||||
|
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
|
||||||
|
if self.bytes.len().saturating_add(bytes.len()) > self.limit_bytes {
|
||||||
|
self.exceeded = true;
|
||||||
|
return Err(io::Error::other("request body exceeds configured limit"));
|
||||||
|
}
|
||||||
|
self.bytes.extend_from_slice(bytes);
|
||||||
|
Ok(bytes.len())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flush(&mut self) -> io::Result<()> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn validate_part_mime_type(
|
||||||
|
value: &str,
|
||||||
|
allowed: Option<&Vec<String>>,
|
||||||
|
) -> Result<(), RestAdapterError> {
|
||||||
|
let normalized = mime_essence(value).ok_or_else(|| RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "content_type is invalid".to_owned(),
|
||||||
|
})?;
|
||||||
|
if let Some(allowed) = allowed
|
||||||
|
&& !allowed.iter().any(|candidate| {
|
||||||
|
mime_essence(candidate)
|
||||||
|
.map(|candidate| candidate.eq_ignore_ascii_case(normalized))
|
||||||
|
.unwrap_or(false)
|
||||||
|
})
|
||||||
|
{
|
||||||
|
return Err(RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "content_type is not allowed by the source contract".to_owned(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mime_essence(value: &str) -> Option<&str> {
|
||||||
|
let essence = value.split(';').next()?.trim();
|
||||||
|
(essence.contains('/')
|
||||||
|
&& !essence.starts_with('/')
|
||||||
|
&& !essence.ends_with('/')
|
||||||
|
&& essence
|
||||||
|
.chars()
|
||||||
|
.all(|character| character.is_ascii_graphic() && !character.is_control()))
|
||||||
|
.then_some(essence)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
use super::{RestAdapterError, form_urlencoded, multipart_form};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn form_and_multipart_reject_invalid_contract_before_dispatch() {
|
||||||
|
assert_eq!(
|
||||||
|
String::from_utf8(form_urlencoded(&json!({"tag": ["a", "b"]}), 1024).unwrap()).unwrap(),
|
||||||
|
"tag=a&tag=b"
|
||||||
|
);
|
||||||
|
for invalid in [
|
||||||
|
"not base64!",
|
||||||
|
"SGVs bG8=",
|
||||||
|
"SGVsbG8_",
|
||||||
|
"data:text/plain,SGVsbG8=",
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
multipart_form(
|
||||||
|
&json!({"file": {"data_base64": invalid}}),
|
||||||
|
None,
|
||||||
|
4 * 1024 * 1024,
|
||||||
|
)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
multipart_form(
|
||||||
|
&json!({"file": {"data_base64": "SGVsbG8=", "path": "/tmp/secret"}}),
|
||||||
|
None,
|
||||||
|
4 * 1024 * 1024,
|
||||||
|
)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn form_encoding_escapes_incrementally_and_respects_the_limit() {
|
||||||
|
assert_eq!(
|
||||||
|
String::from_utf8(form_urlencoded(&json!({"sp ace": "a+b&/ёж"}), 1024).unwrap())
|
||||||
|
.unwrap(),
|
||||||
|
"sp+ace=a%2Bb%26%2F%D1%91%D0%B6"
|
||||||
|
);
|
||||||
|
assert!(matches!(
|
||||||
|
form_urlencoded(&json!({"field": "abcdef"}), 8),
|
||||||
|
Err(RestAdapterError::RequestTooLarge { limit_bytes: 8 })
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn multipart_payload_limit_counts_multiple_decoded_files() {
|
||||||
|
assert!(matches!(
|
||||||
|
multipart_form(
|
||||||
|
&json!({"files": [{"data_base64": "AA=="}, {"data_base64": "AQ=="}]}),
|
||||||
|
None,
|
||||||
|
1,
|
||||||
|
),
|
||||||
|
Err(RestAdapterError::RequestTooLarge { limit_bytes: 1 })
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,11 +21,14 @@ use reqwest::{
|
|||||||
header::{HeaderMap, HeaderName, HeaderValue},
|
header::{HeaderMap, HeaderName, HeaderValue},
|
||||||
redirect,
|
redirect,
|
||||||
};
|
};
|
||||||
use serde_json::Value;
|
|
||||||
use tracing::{Instrument, Span};
|
use tracing::{Instrument, Span};
|
||||||
use tracing_opentelemetry::OpenTelemetrySpanExt;
|
use tracing_opentelemetry::OpenTelemetrySpanExt;
|
||||||
|
|
||||||
use crate::{ExternalReferenceFetchError, RestAdapterError, RestRequest, RestResponse};
|
use crate::{
|
||||||
|
ExternalReferenceFetchError, RestAdapterError, RestRequest, RestResponse,
|
||||||
|
body::{apply_body, apply_legacy_json_body, selected_request_content_type},
|
||||||
|
response::{decode_body, normalize_headers, validate_response_contract},
|
||||||
|
};
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct RestAdapter {
|
pub struct RestAdapter {
|
||||||
@@ -128,7 +131,22 @@ impl RestAdapter {
|
|||||||
let result = async {
|
let result = async {
|
||||||
let url = build_url(target, request)?;
|
let url = build_url(target, request)?;
|
||||||
self.policy.validate_url(&url)?;
|
self.policy.validate_url(&url)?;
|
||||||
let mut headers = build_headers(target, request)?;
|
let mut header_request = request.clone();
|
||||||
|
let cookie_header = extract_mapped_cookies(&mut header_request.headers)?;
|
||||||
|
let mut headers = build_headers(target, &header_request)?;
|
||||||
|
if let Some(cookie_header) = cookie_header {
|
||||||
|
if headers.contains_key("cookie") {
|
||||||
|
return Err(RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "mapped cookie conflicts with an existing cookie header".to_owned(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let value = HeaderValue::try_from(cookie_header).map_err(|_| {
|
||||||
|
RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "cookie parameter is invalid".to_owned(),
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
headers.insert("cookie", value);
|
||||||
|
}
|
||||||
if let Some(context) = trusted_context {
|
if let Some(context) = trusted_context {
|
||||||
for (name, value) in context.outbound_headers() {
|
for (name, value) in context.outbound_headers() {
|
||||||
let (Ok(name), Ok(value)) =
|
let (Ok(name), Ok(value)) =
|
||||||
@@ -152,14 +170,55 @@ impl RestAdapter {
|
|||||||
.map_err(|details| RestAdapterError::InvalidConfiguration {
|
.map_err(|details| RestAdapterError::InvalidConfiguration {
|
||||||
details: details.to_string(),
|
details: details.to_string(),
|
||||||
})?;
|
})?;
|
||||||
|
if request.body.is_none()
|
||||||
|
&& (request.body_content_type.is_some()
|
||||||
|
|| target
|
||||||
|
.request_contract
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|contract| contract.body_required))
|
||||||
|
{
|
||||||
|
return Err(RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "request body contract requires a body".to_owned(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let typed_content_type = if request.body.is_some() && target.request_contract.is_some()
|
||||||
|
{
|
||||||
|
selected_request_content_type(target, request)?
|
||||||
|
} else {
|
||||||
|
if request.body.is_some() && request.body_content_type.is_some() {
|
||||||
|
selected_request_content_type(target, request)?;
|
||||||
|
}
|
||||||
|
None
|
||||||
|
};
|
||||||
|
if typed_content_type.is_some() {
|
||||||
|
headers.remove("content-type");
|
||||||
|
}
|
||||||
|
let legacy_has_content_type = headers.contains_key("content-type");
|
||||||
|
|
||||||
let mut builder = client
|
let mut builder = client
|
||||||
.request(to_reqwest_method(target.method), url)
|
.request(to_reqwest_method(target.method), url)
|
||||||
.headers(headers)
|
.headers(headers)
|
||||||
.timeout(Duration::from_millis(request.timeout_ms));
|
.timeout(Duration::from_millis(request.timeout_ms));
|
||||||
|
|
||||||
if let Some(body) = &request.body {
|
if let Some(body) = &request.body {
|
||||||
enforce_request_body_limit(body, self.policy.max_request_bytes)?;
|
if let Some(content_type) = typed_content_type {
|
||||||
builder = builder.json(body);
|
builder = apply_body(
|
||||||
|
builder,
|
||||||
|
body,
|
||||||
|
&content_type,
|
||||||
|
target.multipart_field_mime_types.get(&content_type),
|
||||||
|
self.policy.max_request_bytes,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
} else {
|
||||||
|
builder = apply_legacy_json_body(
|
||||||
|
builder,
|
||||||
|
body,
|
||||||
|
legacy_has_content_type,
|
||||||
|
self.policy.max_request_bytes,
|
||||||
|
)?;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(context) = trusted_context {
|
if let Some(context) = trusted_context {
|
||||||
@@ -171,7 +230,8 @@ impl RestAdapter {
|
|||||||
if status.is_redirection() {
|
if status.is_redirection() {
|
||||||
return Err(RestAdapterError::RedirectNotAllowed);
|
return Err(RestAdapterError::RedirectNotAllowed);
|
||||||
}
|
}
|
||||||
let body = decode_body(response, self.policy.max_response_bytes).await?;
|
let (body, has_body, valid_json) =
|
||||||
|
decode_body(response, self.policy.max_response_bytes).await?;
|
||||||
|
|
||||||
if !status.is_success() {
|
if !status.is_success() {
|
||||||
return Err(RestAdapterError::UnexpectedStatus {
|
return Err(RestAdapterError::UnexpectedStatus {
|
||||||
@@ -179,6 +239,7 @@ impl RestAdapter {
|
|||||||
body,
|
body,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
validate_response_contract(target, status.as_u16(), &headers, has_body, valid_json)?;
|
||||||
|
|
||||||
Ok(RestResponse {
|
Ok(RestResponse {
|
||||||
status_code: status.as_u16(),
|
status_code: status.as_u16(),
|
||||||
@@ -199,6 +260,43 @@ impl RestAdapter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn extract_mapped_cookies(
|
||||||
|
headers: &mut BTreeMap<String, String>,
|
||||||
|
) -> Result<Option<String>, RestAdapterError> {
|
||||||
|
let internal = headers
|
||||||
|
.keys()
|
||||||
|
.filter(|name| name.starts_with("x-crank-internal-cookie-"))
|
||||||
|
.cloned()
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
if internal.is_empty() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
let mut cookies = Vec::with_capacity(internal.len());
|
||||||
|
for key in internal {
|
||||||
|
let value = headers.remove(&key).unwrap_or_default();
|
||||||
|
let (name, value) =
|
||||||
|
value
|
||||||
|
.split_once('\t')
|
||||||
|
.ok_or_else(|| RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "cookie parameter is malformed".to_owned(),
|
||||||
|
})?;
|
||||||
|
if name.is_empty()
|
||||||
|
|| name
|
||||||
|
.chars()
|
||||||
|
.any(|character| character.is_control() || matches!(character, ';' | '='))
|
||||||
|
|| value
|
||||||
|
.chars()
|
||||||
|
.any(|character| character.is_control() || character == ';')
|
||||||
|
{
|
||||||
|
return Err(RestAdapterError::InvalidBodyContract {
|
||||||
|
reason: "cookie parameter is invalid".to_owned(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
cookies.push(format!("{name}={value}"));
|
||||||
|
}
|
||||||
|
Ok(Some(cookies.join("; ")))
|
||||||
|
}
|
||||||
|
|
||||||
impl ExternalReferenceFetcher {
|
impl ExternalReferenceFetcher {
|
||||||
pub fn try_new(
|
pub fn try_new(
|
||||||
policy: OutboundHttpPolicy,
|
policy: OutboundHttpPolicy,
|
||||||
@@ -363,12 +461,15 @@ fn upstream_outcome(error: &RestAdapterError) -> UpstreamOutcome {
|
|||||||
UpstreamOutcome::Rejected
|
UpstreamOutcome::Rejected
|
||||||
}
|
}
|
||||||
RestAdapterError::WindowExpired => UpstreamOutcome::WindowExpired,
|
RestAdapterError::WindowExpired => UpstreamOutcome::WindowExpired,
|
||||||
RestAdapterError::InvalidSseEvent => UpstreamOutcome::InvalidResponse,
|
RestAdapterError::InvalidSseEvent | RestAdapterError::InvalidResponseContract { .. } => {
|
||||||
|
UpstreamOutcome::InvalidResponse
|
||||||
|
}
|
||||||
RestAdapterError::InvalidBaseUrl { .. }
|
RestAdapterError::InvalidBaseUrl { .. }
|
||||||
| RestAdapterError::InvalidPathParameter { .. }
|
| RestAdapterError::InvalidPathParameter { .. }
|
||||||
| RestAdapterError::InvalidQueryParameter { .. }
|
| RestAdapterError::InvalidQueryParameter { .. }
|
||||||
| RestAdapterError::InvalidHeaderName { .. }
|
| RestAdapterError::InvalidHeaderName { .. }
|
||||||
| RestAdapterError::InvalidHeaderValue { .. } => UpstreamOutcome::InvalidRequest,
|
| RestAdapterError::InvalidHeaderValue { .. }
|
||||||
|
| RestAdapterError::InvalidBodyContract { .. } => UpstreamOutcome::InvalidRequest,
|
||||||
RestAdapterError::InvalidConfiguration { .. } => UpstreamOutcome::Configuration,
|
RestAdapterError::InvalidConfiguration { .. } => UpstreamOutcome::Configuration,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -494,7 +595,7 @@ impl OutboundHttpPolicy {
|
|||||||
.any(|pattern| host_matches(pattern, &host))
|
.any(|pattern| host_matches(pattern, &host))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_denied_ip(&self, address: IpAddr) -> bool {
|
pub(crate) fn is_denied_ip(&self, address: IpAddr) -> bool {
|
||||||
ip_match_hosts(address).iter().any(|host| {
|
ip_match_hosts(address).iter().any(|host| {
|
||||||
self.denied_hosts
|
self.denied_hosts
|
||||||
.iter()
|
.iter()
|
||||||
@@ -502,7 +603,7 @@ impl OutboundHttpPolicy {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_explicitly_allowed(&self, host: &str) -> bool {
|
pub(crate) fn is_explicitly_allowed(&self, host: &str) -> bool {
|
||||||
let host = normalize_host(host);
|
let host = normalize_host(host);
|
||||||
self.allowed_hosts
|
self.allowed_hosts
|
||||||
.iter()
|
.iter()
|
||||||
@@ -601,7 +702,7 @@ fn is_public_ip(address: IpAddr) -> bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn ip_match_hosts(address: IpAddr) -> Vec<String> {
|
pub(crate) fn ip_match_hosts(address: IpAddr) -> Vec<String> {
|
||||||
match address {
|
match address {
|
||||||
IpAddr::V4(address) => vec![address.to_string()],
|
IpAddr::V4(address) => vec![address.to_string()],
|
||||||
IpAddr::V6(address) => {
|
IpAddr::V6(address) => {
|
||||||
@@ -667,11 +768,26 @@ fn build_url(target: &RestTarget, request: &RestRequest) -> Result<reqwest::Url,
|
|||||||
url: "url".to_owned(),
|
url: "url".to_owned(),
|
||||||
})?;
|
})?;
|
||||||
let path = substitute_path_params(&target.path_template, &request.path_params);
|
let path = substitute_path_params(&target.path_template, &request.path_params);
|
||||||
let mut url = base_url.join(path.trim_start_matches('/')).map_err(|_| {
|
let mut url = if target.request_contract.is_some() || !target.response_contract.is_empty() {
|
||||||
|
let base_path = base_url.path().trim_end_matches('/');
|
||||||
|
let target_path = path.trim_start_matches('/');
|
||||||
|
let combined_path = if target_path.is_empty() {
|
||||||
|
base_path.to_owned()
|
||||||
|
} else if base_path.is_empty() {
|
||||||
|
format!("/{target_path}")
|
||||||
|
} else {
|
||||||
|
format!("{base_path}/{target_path}")
|
||||||
|
};
|
||||||
|
let mut url = base_url;
|
||||||
|
url.set_path(&combined_path);
|
||||||
|
url
|
||||||
|
} else {
|
||||||
|
base_url.join(path.trim_start_matches('/')).map_err(|_| {
|
||||||
RestAdapterError::InvalidBaseUrl {
|
RestAdapterError::InvalidBaseUrl {
|
||||||
url: "url".to_owned(),
|
url: "url".to_owned(),
|
||||||
}
|
}
|
||||||
})?;
|
})?
|
||||||
|
};
|
||||||
|
|
||||||
{
|
{
|
||||||
let mut query = url.query_pairs_mut();
|
let mut query = url.query_pairs_mut();
|
||||||
@@ -842,107 +958,6 @@ impl Injector for ReqwestHeaderInjector<'_> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn decode_body(
|
|
||||||
response: reqwest::Response,
|
|
||||||
max_response_bytes: usize,
|
|
||||||
) -> Result<Value, RestAdapterError> {
|
|
||||||
if response
|
|
||||||
.content_length()
|
|
||||||
.is_some_and(|length| length > max_response_bytes as u64)
|
|
||||||
{
|
|
||||||
return Err(RestAdapterError::ResponseTooLarge {
|
|
||||||
limit_bytes: max_response_bytes,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
let mut stream = response.bytes_stream();
|
|
||||||
let mut bytes = Vec::new();
|
|
||||||
while let Some(chunk) = stream.next().await {
|
|
||||||
let chunk = chunk?;
|
|
||||||
if bytes.len().saturating_add(chunk.len()) > max_response_bytes {
|
|
||||||
return Err(RestAdapterError::ResponseTooLarge {
|
|
||||||
limit_bytes: max_response_bytes,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
bytes.extend_from_slice(&chunk);
|
|
||||||
}
|
|
||||||
|
|
||||||
if bytes.is_empty() {
|
|
||||||
return Ok(Value::Null);
|
|
||||||
}
|
|
||||||
|
|
||||||
match serde_json::from_slice::<Value>(&bytes) {
|
|
||||||
Ok(value) => Ok(value),
|
|
||||||
Err(_) => Ok(Value::String(
|
|
||||||
String::from_utf8_lossy(&bytes).trim().to_owned(),
|
|
||||||
)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn enforce_request_body_limit(
|
|
||||||
body: &Value,
|
|
||||||
max_request_bytes: usize,
|
|
||||||
) -> Result<(), RestAdapterError> {
|
|
||||||
if max_request_bytes == 0 {
|
|
||||||
return Err(RestAdapterError::InvalidConfiguration {
|
|
||||||
details: "outbound request limit must be greater than zero".to_owned(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
let mut writer = LimitWriter::new(max_request_bytes);
|
|
||||||
let result = serde_json::to_writer(&mut writer, body);
|
|
||||||
if writer.exceeded {
|
|
||||||
return Err(RestAdapterError::RequestTooLarge {
|
|
||||||
limit_bytes: max_request_bytes,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
result.map_err(|_| RestAdapterError::InvalidHeaderValue {
|
|
||||||
header: "body".to_owned(),
|
|
||||||
})?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
struct LimitWriter {
|
|
||||||
written: usize,
|
|
||||||
limit: usize,
|
|
||||||
exceeded: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl LimitWriter {
|
|
||||||
fn new(limit: usize) -> Self {
|
|
||||||
Self {
|
|
||||||
written: 0,
|
|
||||||
limit,
|
|
||||||
exceeded: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl io::Write for LimitWriter {
|
|
||||||
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
|
|
||||||
if self.written.saturating_add(buf.len()) > self.limit {
|
|
||||||
self.exceeded = true;
|
|
||||||
return Err(io::Error::other("request body exceeds configured limit"));
|
|
||||||
}
|
|
||||||
self.written += buf.len();
|
|
||||||
Ok(buf.len())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn flush(&mut self) -> io::Result<()> {
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn normalize_headers(headers: &HeaderMap) -> BTreeMap<String, String> {
|
|
||||||
headers
|
|
||||||
.iter()
|
|
||||||
.filter_map(|(name, value)| {
|
|
||||||
value
|
|
||||||
.to_str()
|
|
||||||
.ok()
|
|
||||||
.map(|value| (name.as_str().to_owned(), value.to_owned()))
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn to_reqwest_method(method: HttpMethod) -> reqwest::Method {
|
fn to_reqwest_method(method: HttpMethod) -> reqwest::Method {
|
||||||
match method {
|
match method {
|
||||||
HttpMethod::Get => reqwest::Method::GET,
|
HttpMethod::Get => reqwest::Method::GET,
|
||||||
@@ -950,40 +965,7 @@ fn to_reqwest_method(method: HttpMethod) -> reqwest::Method {
|
|||||||
HttpMethod::Put => reqwest::Method::PUT,
|
HttpMethod::Put => reqwest::Method::PUT,
|
||||||
HttpMethod::Patch => reqwest::Method::PATCH,
|
HttpMethod::Patch => reqwest::Method::PATCH,
|
||||||
HttpMethod::Delete => reqwest::Method::DELETE,
|
HttpMethod::Delete => reqwest::Method::DELETE,
|
||||||
}
|
HttpMethod::Head => reqwest::Method::HEAD,
|
||||||
}
|
HttpMethod::Options => reqwest::Method::OPTIONS,
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::{OutboundHttpPolicy, ip_match_hosts};
|
|
||||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn denied_resolved_ip_overrides_explicitly_allowed_hostname() {
|
|
||||||
let policy = OutboundHttpPolicy::try_new_with_limits(
|
|
||||||
vec!["api.example.test".to_owned()],
|
|
||||||
vec!["169.254.169.254".to_owned()],
|
|
||||||
4 * 1024 * 1024,
|
|
||||||
4 * 1024 * 1024,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
assert!(policy.is_explicitly_allowed("api.example.test"));
|
|
||||||
assert!(policy.is_denied_ip(IpAddr::V4(Ipv4Addr::new(169, 254, 169, 254))));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn denied_resolved_ip_checks_ipv4_mapped_ipv6_alias() {
|
|
||||||
let policy = OutboundHttpPolicy::try_new_with_limits(
|
|
||||||
vec!["api.example.test".to_owned()],
|
|
||||||
vec!["127.0.0.1".to_owned()],
|
|
||||||
4 * 1024 * 1024,
|
|
||||||
4 * 1024 * 1024,
|
|
||||||
)
|
|
||||||
.unwrap();
|
|
||||||
let mapped = IpAddr::V6(Ipv6Addr::from(0xffff_7f00_0001u128));
|
|
||||||
|
|
||||||
assert!(ip_match_hosts(mapped).contains(&"127.0.0.1".to_owned()));
|
|
||||||
assert!(policy.is_denied_ip(mapped));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
|
||||||
|
|
||||||
|
use crate::client::{OutboundHttpPolicy, ip_match_hosts};
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn denied_resolved_ip_overrides_explicitly_allowed_hostname() {
|
||||||
|
let policy = OutboundHttpPolicy::try_new_with_limits(
|
||||||
|
vec!["api.example.test".to_owned()],
|
||||||
|
vec!["169.254.169.254".to_owned()],
|
||||||
|
4 * 1024 * 1024,
|
||||||
|
4 * 1024 * 1024,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert!(policy.is_explicitly_allowed("api.example.test"));
|
||||||
|
assert!(policy.is_denied_ip(IpAddr::V4(Ipv4Addr::new(169, 254, 169, 254))));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn denied_resolved_ip_checks_ipv4_mapped_ipv6_alias() {
|
||||||
|
let policy = OutboundHttpPolicy::try_new_with_limits(
|
||||||
|
vec!["api.example.test".to_owned()],
|
||||||
|
vec!["127.0.0.1".to_owned()],
|
||||||
|
4 * 1024 * 1024,
|
||||||
|
4 * 1024 * 1024,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let mapped = IpAddr::V6(Ipv6Addr::from(0xffff_7f00_0001u128));
|
||||||
|
|
||||||
|
assert!(ip_match_hosts(mapped).contains(&"127.0.0.1".to_owned()));
|
||||||
|
assert!(policy.is_denied_ip(mapped));
|
||||||
|
}
|
||||||
@@ -33,6 +33,8 @@ pub enum RestAdapterError {
|
|||||||
InvalidHeaderName { header: String },
|
InvalidHeaderName { header: String },
|
||||||
#[error("invalid header value for {header}")]
|
#[error("invalid header value for {header}")]
|
||||||
InvalidHeaderValue { header: String },
|
InvalidHeaderValue { header: String },
|
||||||
|
#[error("invalid REST request body contract")]
|
||||||
|
InvalidBodyContract { reason: String },
|
||||||
#[error("outbound target is not allowed")]
|
#[error("outbound target is not allowed")]
|
||||||
TargetNotAllowed { target: String },
|
TargetNotAllowed { target: String },
|
||||||
#[error("outbound redirects are not allowed")]
|
#[error("outbound redirects are not allowed")]
|
||||||
@@ -49,6 +51,8 @@ pub enum RestAdapterError {
|
|||||||
WindowExpired,
|
WindowExpired,
|
||||||
#[error("rest endpoint returned status {status}")]
|
#[error("rest endpoint returned status {status}")]
|
||||||
UnexpectedStatus { status: u16, body: Value },
|
UnexpectedStatus { status: u16, body: Value },
|
||||||
|
#[error("rest endpoint response does not match the Operation contract: {reason}")]
|
||||||
|
InvalidResponseContract { reason: String },
|
||||||
#[error("sse stream produced malformed event payload")]
|
#[error("sse stream produced malformed event payload")]
|
||||||
InvalidSseEvent,
|
InvalidSseEvent,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,10 @@
|
|||||||
|
mod body;
|
||||||
mod client;
|
mod client;
|
||||||
|
#[cfg(test)]
|
||||||
|
mod client_tests;
|
||||||
mod error;
|
mod error;
|
||||||
mod model;
|
mod model;
|
||||||
|
mod response;
|
||||||
|
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use crank_core::{
|
use crank_core::{
|
||||||
@@ -35,6 +39,7 @@ impl ProtocolAdapter for RestAdapter {
|
|||||||
headers: prepared.headers.clone(),
|
headers: prepared.headers.clone(),
|
||||||
trusted_header_names: prepared.trusted_header_names.clone(),
|
trusted_header_names: prepared.trusted_header_names.clone(),
|
||||||
body: prepared.body.clone(),
|
body: prepared.body.clone(),
|
||||||
|
body_content_type: prepared.body_content_type.clone(),
|
||||||
timeout_ms: prepared.timeout_ms,
|
timeout_ms: prepared.timeout_ms,
|
||||||
};
|
};
|
||||||
let response = self.execute_with_context(target, &request, context).await?;
|
let response = self.execute_with_context(target, &request, context).await?;
|
||||||
@@ -62,7 +67,8 @@ impl From<RestAdapterError> for ProtocolAdapterError {
|
|||||||
RestAdapterError::InvalidPathParameter { .. }
|
RestAdapterError::InvalidPathParameter { .. }
|
||||||
| RestAdapterError::InvalidQueryParameter { .. }
|
| RestAdapterError::InvalidQueryParameter { .. }
|
||||||
| RestAdapterError::InvalidHeaderName { .. }
|
| RestAdapterError::InvalidHeaderName { .. }
|
||||||
| RestAdapterError::InvalidHeaderValue { .. } => Self::InvalidPreparedRequest,
|
| RestAdapterError::InvalidHeaderValue { .. }
|
||||||
|
| RestAdapterError::InvalidBodyContract { .. } => Self::InvalidPreparedRequest,
|
||||||
RestAdapterError::RedirectNotAllowed => Self::TargetRejected,
|
RestAdapterError::RedirectNotAllowed => Self::TargetRejected,
|
||||||
RestAdapterError::TargetNotAllowed { .. } => Self::TargetRejected,
|
RestAdapterError::TargetNotAllowed { .. } => Self::TargetRejected,
|
||||||
RestAdapterError::RequestTooLarge { .. } => Self::RequestTooLarge,
|
RestAdapterError::RequestTooLarge { .. } => Self::RequestTooLarge,
|
||||||
@@ -93,6 +99,9 @@ impl From<RestAdapterError> for ProtocolAdapterError {
|
|||||||
RestAdapterError::InvalidSseEvent => Self::InvalidResponse {
|
RestAdapterError::InvalidSseEvent => Self::InvalidResponse {
|
||||||
dispatch: DispatchEvidence::MayHaveDispatched,
|
dispatch: DispatchEvidence::MayHaveDispatched,
|
||||||
},
|
},
|
||||||
|
RestAdapterError::InvalidResponseContract { .. } => Self::InvalidResponse {
|
||||||
|
dispatch: DispatchEvidence::MayHaveDispatched,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -15,6 +15,8 @@ pub struct RestRequest {
|
|||||||
pub trusted_header_names: BTreeSet<String>,
|
pub trusted_header_names: BTreeSet<String>,
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub body: Option<Value>,
|
pub body: Option<Value>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub body_content_type: Option<String>,
|
||||||
pub timeout_ms: u64,
|
pub timeout_ms: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,127 @@
|
|||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use crank_core::RestTarget;
|
||||||
|
use futures_util::StreamExt;
|
||||||
|
use reqwest::header::HeaderMap;
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
use crate::RestAdapterError;
|
||||||
|
|
||||||
|
pub(crate) async fn decode_body(
|
||||||
|
response: reqwest::Response,
|
||||||
|
max_response_bytes: usize,
|
||||||
|
) -> Result<(Value, bool, bool), RestAdapterError> {
|
||||||
|
if response
|
||||||
|
.content_length()
|
||||||
|
.is_some_and(|length| length > max_response_bytes as u64)
|
||||||
|
{
|
||||||
|
return Err(RestAdapterError::ResponseTooLarge {
|
||||||
|
limit_bytes: max_response_bytes,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let mut stream = response.bytes_stream();
|
||||||
|
let mut bytes = Vec::new();
|
||||||
|
while let Some(chunk) = stream.next().await {
|
||||||
|
let chunk = chunk?;
|
||||||
|
if bytes.len().saturating_add(chunk.len()) > max_response_bytes {
|
||||||
|
return Err(RestAdapterError::ResponseTooLarge {
|
||||||
|
limit_bytes: max_response_bytes,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
bytes.extend_from_slice(&chunk);
|
||||||
|
}
|
||||||
|
|
||||||
|
if bytes.is_empty() {
|
||||||
|
return Ok((Value::Null, false, false));
|
||||||
|
}
|
||||||
|
|
||||||
|
match serde_json::from_slice::<Value>(&bytes) {
|
||||||
|
Ok(value) => Ok((value, true, true)),
|
||||||
|
Err(_) => Ok((
|
||||||
|
Value::String(String::from_utf8_lossy(&bytes).trim().to_owned()),
|
||||||
|
true,
|
||||||
|
false,
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn validate_response_contract(
|
||||||
|
target: &RestTarget,
|
||||||
|
status_code: u16,
|
||||||
|
headers: &BTreeMap<String, String>,
|
||||||
|
has_body: bool,
|
||||||
|
valid_json: bool,
|
||||||
|
) -> Result<(), RestAdapterError> {
|
||||||
|
if target.response_contract.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
let matching_status = target
|
||||||
|
.response_contract
|
||||||
|
.iter()
|
||||||
|
.filter(|descriptor| descriptor.status_code == status_code)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
if matching_status.is_empty() {
|
||||||
|
return Err(RestAdapterError::UnexpectedStatus {
|
||||||
|
status: status_code,
|
||||||
|
body: Value::Null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if !has_body {
|
||||||
|
return matching_status
|
||||||
|
.iter()
|
||||||
|
.any(|descriptor| descriptor.media_type.is_none())
|
||||||
|
.then_some(())
|
||||||
|
.ok_or_else(|| RestAdapterError::InvalidResponseContract {
|
||||||
|
reason: format!("status {status_code} requires a response body"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let content_type = headers
|
||||||
|
.get("content-type")
|
||||||
|
.map(|value| normalized_media_type(value));
|
||||||
|
let Some(content_type) = content_type else {
|
||||||
|
return Err(RestAdapterError::InvalidResponseContract {
|
||||||
|
reason: format!("status {status_code} has a body without a content-type"),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
if matching_status.iter().any(|descriptor| {
|
||||||
|
descriptor
|
||||||
|
.media_type
|
||||||
|
.as_deref()
|
||||||
|
.is_some_and(|expected| normalized_media_type(expected) == content_type)
|
||||||
|
}) {
|
||||||
|
if (content_type == "application/json" || content_type.ends_with("+json")) && !valid_json {
|
||||||
|
return Err(RestAdapterError::InvalidResponseContract {
|
||||||
|
reason: format!("status {status_code} has invalid JSON response body"),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
Err(RestAdapterError::InvalidResponseContract {
|
||||||
|
reason: format!("status {status_code} with content-type {content_type} is not declared"),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn normalized_media_type(value: &str) -> String {
|
||||||
|
value
|
||||||
|
.split(';')
|
||||||
|
.next()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.trim()
|
||||||
|
.to_ascii_lowercase()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn normalize_headers(headers: &HeaderMap) -> BTreeMap<String, String> {
|
||||||
|
headers
|
||||||
|
.iter()
|
||||||
|
.filter_map(|(name, value)| {
|
||||||
|
value
|
||||||
|
.to_str()
|
||||||
|
.ok()
|
||||||
|
.map(|value| (name.as_str().to_owned(), value.to_owned()))
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
mod integration {
|
mod integration {
|
||||||
mod client;
|
mod client;
|
||||||
mod external_reference_fetcher;
|
mod external_reference_fetcher;
|
||||||
|
mod multipart;
|
||||||
mod outbound_security;
|
mod outbound_security;
|
||||||
}
|
}
|
||||||
@@ -10,7 +10,7 @@ use axum::{
|
|||||||
use crank_adapter_rest::{OutboundHttpPolicy, RestAdapter, RestAdapterError, RestRequest};
|
use crank_adapter_rest::{OutboundHttpPolicy, RestAdapter, RestAdapterError, RestRequest};
|
||||||
use crank_core::{
|
use crank_core::{
|
||||||
DispatchEvidence, HttpMethod, PreparedRequest, ProtocolAdapter, ProtocolAdapterError,
|
DispatchEvidence, HttpMethod, PreparedRequest, ProtocolAdapter, ProtocolAdapterError,
|
||||||
RestTarget, RuntimeRequestContext, Target,
|
RestResponseDescriptor, RestTarget, RuntimeRequestContext, Target,
|
||||||
};
|
};
|
||||||
use opentelemetry::{
|
use opentelemetry::{
|
||||||
global,
|
global,
|
||||||
@@ -32,6 +32,9 @@ async fn executes_rest_request_and_normalizes_json_response() {
|
|||||||
method: HttpMethod::Post,
|
method: HttpMethod::Post,
|
||||||
path_template: "/users/{user_id}".to_owned(),
|
path_template: "/users/{user_id}".to_owned(),
|
||||||
static_headers: BTreeMap::from([("x-static".to_owned(), "static".to_owned())]),
|
static_headers: BTreeMap::from([("x-static".to_owned(), "static".to_owned())]),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
};
|
};
|
||||||
let request = RestRequest {
|
let request = RestRequest {
|
||||||
path_params: BTreeMap::from([("user_id".to_owned(), "42".to_owned())]),
|
path_params: BTreeMap::from([("user_id".to_owned(), "42".to_owned())]),
|
||||||
@@ -57,6 +60,29 @@ async fn executes_rest_request_and_normalizes_json_response() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn legacy_json_field_named_content_type_is_sent_unchanged() {
|
||||||
|
let base_url = spawn_test_server().await;
|
||||||
|
let target = RestTarget {
|
||||||
|
base_url,
|
||||||
|
method: HttpMethod::Post,
|
||||||
|
path_template: "/users/{user_id}".to_owned(),
|
||||||
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
|
};
|
||||||
|
let request = RestRequest {
|
||||||
|
path_params: BTreeMap::from([("user_id".to_owned(), "42".to_owned())]),
|
||||||
|
body: Some(json!({"__content_type": "legacy-value", "name": "Ada"})),
|
||||||
|
timeout_ms: 1_000,
|
||||||
|
..RestRequest::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
let response = test_adapter().execute(&target, &request).await.unwrap();
|
||||||
|
assert_eq!(response.body["payload"]["__content_type"], "legacy-value");
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn prepared_auth_profile_header_is_allowed_after_runtime_resolution() {
|
async fn prepared_auth_profile_header_is_allowed_after_runtime_resolution() {
|
||||||
let base_url = spawn_test_server().await;
|
let base_url = spawn_test_server().await;
|
||||||
@@ -66,6 +92,9 @@ async fn prepared_auth_profile_header_is_allowed_after_runtime_resolution() {
|
|||||||
method: HttpMethod::Post,
|
method: HttpMethod::Post,
|
||||||
path_template: "/users/{user_id}".to_owned(),
|
path_template: "/users/{user_id}".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
};
|
};
|
||||||
let request = RestRequest {
|
let request = RestRequest {
|
||||||
path_params: BTreeMap::from([("user_id".to_owned(), "42".to_owned())]),
|
path_params: BTreeMap::from([("user_id".to_owned(), "42".to_owned())]),
|
||||||
@@ -76,6 +105,7 @@ async fn prepared_auth_profile_header_is_allowed_after_runtime_resolution() {
|
|||||||
)]),
|
)]),
|
||||||
trusted_header_names: BTreeSet::from(["authorization".to_owned()]),
|
trusted_header_names: BTreeSet::from(["authorization".to_owned()]),
|
||||||
body: Some(json!({ "name": "Ada" })),
|
body: Some(json!({ "name": "Ada" })),
|
||||||
|
body_content_type: None,
|
||||||
timeout_ms: 1_000,
|
timeout_ms: 1_000,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -96,6 +126,9 @@ async fn untrusted_prepared_credential_header_is_rejected_before_dispatch() {
|
|||||||
method: HttpMethod::Post,
|
method: HttpMethod::Post,
|
||||||
path_template: "/users/{user_id}".to_owned(),
|
path_template: "/users/{user_id}".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
};
|
};
|
||||||
let request = RestRequest {
|
let request = RestRequest {
|
||||||
path_params: BTreeMap::from([("user_id".to_owned(), "42".to_owned())]),
|
path_params: BTreeMap::from([("user_id".to_owned(), "42".to_owned())]),
|
||||||
@@ -144,6 +177,9 @@ async fn protocol_context_overrides_mapped_correlation_headers() {
|
|||||||
),
|
),
|
||||||
("x-trace-id".to_owned(), "static-trace".to_owned()),
|
("x-trace-id".to_owned(), "static-trace".to_owned()),
|
||||||
]),
|
]),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
});
|
});
|
||||||
let prepared = PreparedRequest {
|
let prepared = PreparedRequest {
|
||||||
path_params: BTreeMap::from([("user_id".to_owned(), "42".to_owned())]),
|
path_params: BTreeMap::from([("user_id".to_owned(), "42".to_owned())]),
|
||||||
@@ -197,6 +233,9 @@ async fn current_trace_context_overrides_mapped_traceparent() {
|
|||||||
method: HttpMethod::Post,
|
method: HttpMethod::Post,
|
||||||
path_template: "/users/{user_id}".to_owned(),
|
path_template: "/users/{user_id}".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
};
|
};
|
||||||
let request = RestRequest {
|
let request = RestRequest {
|
||||||
path_params: BTreeMap::from([("user_id".to_owned(), "42".to_owned())]),
|
path_params: BTreeMap::from([("user_id".to_owned(), "42".to_owned())]),
|
||||||
@@ -238,6 +277,9 @@ async fn user_configured_propagation_headers_are_removed_without_trusted_context
|
|||||||
("tracestate".to_owned(), "vendor=value".to_owned()),
|
("tracestate".to_owned(), "vendor=value".to_owned()),
|
||||||
("baggage".to_owned(), "secret=must-not-leave".to_owned()),
|
("baggage".to_owned(), "secret=must-not-leave".to_owned()),
|
||||||
]),
|
]),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
};
|
};
|
||||||
let request = RestRequest {
|
let request = RestRequest {
|
||||||
path_params: BTreeMap::from([("user_id".to_owned(), "42".to_owned())]),
|
path_params: BTreeMap::from([("user_id".to_owned(), "42".to_owned())]),
|
||||||
@@ -264,6 +306,9 @@ async fn returns_unexpected_status_with_normalized_body() {
|
|||||||
method: HttpMethod::Get,
|
method: HttpMethod::Get,
|
||||||
path_template: "/fail".to_owned(),
|
path_template: "/fail".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
};
|
};
|
||||||
let request = RestRequest {
|
let request = RestRequest {
|
||||||
path_params: BTreeMap::new(),
|
path_params: BTreeMap::new(),
|
||||||
@@ -292,6 +337,116 @@ async fn returns_unexpected_status_with_normalized_body() {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn enforces_declared_success_status_and_media_type() {
|
||||||
|
let base_url = spawn_test_server().await;
|
||||||
|
let request = RestRequest {
|
||||||
|
path_params: BTreeMap::from([("user_id".to_owned(), "42".to_owned())]),
|
||||||
|
body: Some(json!({"name": "Ada"})),
|
||||||
|
timeout_ms: 1_000,
|
||||||
|
..RestRequest::default()
|
||||||
|
};
|
||||||
|
let target = RestTarget {
|
||||||
|
base_url: base_url.clone(),
|
||||||
|
method: HttpMethod::Post,
|
||||||
|
path_template: "/users/{user_id}".to_owned(),
|
||||||
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: vec![RestResponseDescriptor {
|
||||||
|
status_code: 200,
|
||||||
|
media_type: Some("application/json".to_owned()),
|
||||||
|
schema_variant: 0,
|
||||||
|
}],
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
|
};
|
||||||
|
assert!(test_adapter().execute(&target, &request).await.is_ok());
|
||||||
|
|
||||||
|
let unexpected_status = RestTarget {
|
||||||
|
response_contract: vec![RestResponseDescriptor {
|
||||||
|
status_code: 201,
|
||||||
|
media_type: Some("application/json".to_owned()),
|
||||||
|
schema_variant: 0,
|
||||||
|
}],
|
||||||
|
..target.clone()
|
||||||
|
};
|
||||||
|
assert!(matches!(
|
||||||
|
test_adapter().execute(&unexpected_status, &request).await,
|
||||||
|
Err(RestAdapterError::UnexpectedStatus { status: 200, .. })
|
||||||
|
));
|
||||||
|
|
||||||
|
let unexpected_media_type = RestTarget {
|
||||||
|
response_contract: vec![RestResponseDescriptor {
|
||||||
|
status_code: 200,
|
||||||
|
media_type: Some("application/problem+json".to_owned()),
|
||||||
|
schema_variant: 0,
|
||||||
|
}],
|
||||||
|
..target
|
||||||
|
};
|
||||||
|
assert!(matches!(
|
||||||
|
test_adapter()
|
||||||
|
.execute(&unexpected_media_type, &request)
|
||||||
|
.await,
|
||||||
|
Err(RestAdapterError::InvalidResponseContract { .. })
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn accepts_declared_no_content_response() {
|
||||||
|
let base_url = spawn_test_server().await;
|
||||||
|
let target = RestTarget {
|
||||||
|
base_url,
|
||||||
|
method: HttpMethod::Get,
|
||||||
|
path_template: "/no-content".to_owned(),
|
||||||
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: vec![RestResponseDescriptor {
|
||||||
|
status_code: 204,
|
||||||
|
media_type: None,
|
||||||
|
schema_variant: 0,
|
||||||
|
}],
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let response = test_adapter()
|
||||||
|
.execute(&target, &empty_request())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(response.status_code, 204);
|
||||||
|
assert_eq!(response.body, Value::Null);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn typed_json_response_rejects_invalid_json_while_legacy_keeps_text_fallback() {
|
||||||
|
let base_url = spawn_test_server().await;
|
||||||
|
let typed = RestTarget {
|
||||||
|
base_url: base_url.clone(),
|
||||||
|
method: HttpMethod::Get,
|
||||||
|
path_template: "/invalid-json".to_owned(),
|
||||||
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: vec![RestResponseDescriptor {
|
||||||
|
status_code: 200,
|
||||||
|
media_type: Some("application/json".to_owned()),
|
||||||
|
schema_variant: 0,
|
||||||
|
}],
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
|
};
|
||||||
|
assert!(matches!(
|
||||||
|
test_adapter().execute(&typed, &empty_request()).await,
|
||||||
|
Err(RestAdapterError::InvalidResponseContract { .. })
|
||||||
|
));
|
||||||
|
|
||||||
|
let legacy = RestTarget {
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
..typed
|
||||||
|
};
|
||||||
|
let response = test_adapter()
|
||||||
|
.execute(&legacy, &empty_request())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(response.body, "not-json");
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn connect_failure_is_known_not_dispatched() {
|
async fn connect_failure_is_known_not_dispatched() {
|
||||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
@@ -302,6 +457,9 @@ async fn connect_failure_is_known_not_dispatched() {
|
|||||||
method: HttpMethod::Post,
|
method: HttpMethod::Post,
|
||||||
path_template: "/write".to_owned(),
|
path_template: "/write".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
};
|
};
|
||||||
let request = RestRequest {
|
let request = RestRequest {
|
||||||
path_params: BTreeMap::new(),
|
path_params: BTreeMap::new(),
|
||||||
@@ -349,6 +507,9 @@ async fn does_not_follow_redirects() {
|
|||||||
method: HttpMethod::Get,
|
method: HttpMethod::Get,
|
||||||
path_template: "/redirect".to_owned(),
|
path_template: "/redirect".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
};
|
};
|
||||||
|
|
||||||
let error = adapter
|
let error = adapter
|
||||||
@@ -370,6 +531,9 @@ async fn rejects_responses_over_the_configured_limit() {
|
|||||||
method: HttpMethod::Get,
|
method: HttpMethod::Get,
|
||||||
path_template: "/large".to_owned(),
|
path_template: "/large".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
};
|
};
|
||||||
|
|
||||||
let error = adapter
|
let error = adapter
|
||||||
@@ -402,6 +566,11 @@ async fn spawn_test_server() -> String {
|
|||||||
let app = Router::new()
|
let app = Router::new()
|
||||||
.route("/users/{user_id}", post(create_user))
|
.route("/users/{user_id}", post(create_user))
|
||||||
.route("/fail", get(fail))
|
.route("/fail", get(fail))
|
||||||
|
.route("/no-content", get(|| async { StatusCode::NO_CONTENT }))
|
||||||
|
.route(
|
||||||
|
"/invalid-json",
|
||||||
|
get(|| async { ([("content-type", "application/json")], "not-json") }),
|
||||||
|
)
|
||||||
.route("/redirect", get(|| async { Redirect::to("/large") }))
|
.route("/redirect", get(|| async { Redirect::to("/large") }))
|
||||||
.route(
|
.route(
|
||||||
"/large",
|
"/large",
|
||||||
|
|||||||
@@ -0,0 +1,554 @@
|
|||||||
|
use std::{
|
||||||
|
collections::{BTreeMap, BTreeSet},
|
||||||
|
sync::{Arc, Mutex},
|
||||||
|
};
|
||||||
|
|
||||||
|
use axum::{
|
||||||
|
Json, Router,
|
||||||
|
body::Bytes,
|
||||||
|
extract::{Multipart, State},
|
||||||
|
http::{HeaderMap, StatusCode},
|
||||||
|
routing::{get, post},
|
||||||
|
};
|
||||||
|
use crank_adapter_rest::{OutboundHttpPolicy, RestAdapter, RestAdapterError, RestRequest};
|
||||||
|
use crank_core::{
|
||||||
|
HttpMethod, RestRequestContract, RestRequestContractVersion, RestRequestDescriptor,
|
||||||
|
RestResponseDescriptor, RestTarget,
|
||||||
|
};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use tokio::net::TcpListener;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
struct MultipartPart {
|
||||||
|
name: String,
|
||||||
|
filename: Option<String>,
|
||||||
|
content_type: Option<String>,
|
||||||
|
bytes: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
struct WireRequest {
|
||||||
|
content_types: Vec<String>,
|
||||||
|
cookie: Option<String>,
|
||||||
|
body: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
struct CaptureState {
|
||||||
|
multipart: Mutex<Vec<MultipartPart>>,
|
||||||
|
wire: Mutex<Vec<WireRequest>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn multipart_decodes_base64_and_preserves_filename_and_mime() {
|
||||||
|
let (base_url, state) = spawn_capture_server().await;
|
||||||
|
let target = target(&base_url, "/multipart");
|
||||||
|
let request = RestRequest {
|
||||||
|
body: Some(json!({
|
||||||
|
"title": "report",
|
||||||
|
"file": {
|
||||||
|
"data_base64": "AAEC/w==",
|
||||||
|
"filename": "report.bin",
|
||||||
|
"content_type": "application/octet-stream"
|
||||||
|
}
|
||||||
|
})),
|
||||||
|
body_content_type: Some("multipart/form-data".to_owned()),
|
||||||
|
timeout_ms: 1_000,
|
||||||
|
..RestRequest::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
let response = test_adapter().execute(&target, &request).await.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(response.status_code, 200);
|
||||||
|
let parts = state.multipart.lock().unwrap().clone();
|
||||||
|
assert_eq!(parts.len(), 2);
|
||||||
|
let file = parts.iter().find(|part| part.name == "file").unwrap();
|
||||||
|
assert_eq!(file.filename.as_deref(), Some("report.bin"));
|
||||||
|
assert_eq!(
|
||||||
|
file.content_type.as_deref(),
|
||||||
|
Some("application/octet-stream")
|
||||||
|
);
|
||||||
|
assert_eq!(file.bytes, vec![0, 1, 2, 255]);
|
||||||
|
let title = parts.iter().find(|part| part.name == "title").unwrap();
|
||||||
|
assert_eq!(title.filename, None);
|
||||||
|
assert_eq!(title.content_type, None);
|
||||||
|
assert_eq!(title.bytes, b"report");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn typed_contract_preserves_server_base_path_on_wire() {
|
||||||
|
let (base_url, state) = spawn_capture_server().await;
|
||||||
|
let target = target(&format!("{base_url}/api/v2"), "/multipart");
|
||||||
|
let request = RestRequest {
|
||||||
|
body: Some(json!({"file": {"data_base64": ""}})),
|
||||||
|
body_content_type: Some("multipart/form-data".to_owned()),
|
||||||
|
timeout_ms: 1_000,
|
||||||
|
..RestRequest::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
test_adapter().execute(&target, &request).await.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(state.multipart.lock().unwrap().len(), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn typed_response_only_contract_preserves_server_base_path_on_wire() {
|
||||||
|
let (base_url, _) = spawn_capture_server().await;
|
||||||
|
let target = RestTarget {
|
||||||
|
base_url: format!("{base_url}/api/v2"),
|
||||||
|
method: HttpMethod::Head,
|
||||||
|
path_template: "/no-content".to_owned(),
|
||||||
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: vec![RestResponseDescriptor {
|
||||||
|
status_code: 204,
|
||||||
|
media_type: None,
|
||||||
|
schema_variant: 0,
|
||||||
|
}],
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
|
};
|
||||||
|
let response = test_adapter()
|
||||||
|
.execute(
|
||||||
|
&target,
|
||||||
|
&RestRequest {
|
||||||
|
timeout_ms: 1_000,
|
||||||
|
..RestRequest::default()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(response.status_code, 204);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn invalid_multipart_base64_is_rejected_before_dispatch() {
|
||||||
|
let (base_url, state) = spawn_capture_server().await;
|
||||||
|
let target = target(&base_url, "/multipart");
|
||||||
|
let request = RestRequest {
|
||||||
|
body: Some(json!({
|
||||||
|
"file": { "data_base64": "definitely not base64" }
|
||||||
|
})),
|
||||||
|
body_content_type: Some("multipart/form-data".to_owned()),
|
||||||
|
timeout_ms: 1_000,
|
||||||
|
..RestRequest::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
let error = test_adapter().execute(&target, &request).await.unwrap_err();
|
||||||
|
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
RestAdapterError::InvalidBodyContract { .. }
|
||||||
|
));
|
||||||
|
assert!(state.multipart.lock().unwrap().is_empty());
|
||||||
|
assert!(state.wire.lock().unwrap().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn multipart_uses_source_mime_default_or_requires_a_choice() {
|
||||||
|
let (base_url, state) = spawn_capture_server().await;
|
||||||
|
let adapter = test_adapter();
|
||||||
|
let single = target_with_mime(&base_url, vec!["image/png"]);
|
||||||
|
adapter
|
||||||
|
.execute(
|
||||||
|
&single,
|
||||||
|
&RestRequest {
|
||||||
|
body: Some(json!({
|
||||||
|
"file": { "data_base64": "" }
|
||||||
|
})),
|
||||||
|
body_content_type: Some("multipart/form-data".to_owned()),
|
||||||
|
timeout_ms: 1_000,
|
||||||
|
..RestRequest::default()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let default = target(&base_url, "/multipart");
|
||||||
|
adapter
|
||||||
|
.execute(
|
||||||
|
&default,
|
||||||
|
&RestRequest {
|
||||||
|
body: Some(json!({
|
||||||
|
"file": { "data_base64": "" }
|
||||||
|
})),
|
||||||
|
body_content_type: Some("multipart/form-data".to_owned()),
|
||||||
|
timeout_ms: 1_000,
|
||||||
|
..RestRequest::default()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let parts = state.multipart.lock().unwrap().clone();
|
||||||
|
assert_eq!(parts[0].bytes, Vec::<u8>::new());
|
||||||
|
assert_eq!(parts[0].filename, None);
|
||||||
|
assert_eq!(parts[0].content_type.as_deref(), Some("image/png"));
|
||||||
|
assert_eq!(
|
||||||
|
parts[1].content_type.as_deref(),
|
||||||
|
Some("application/octet-stream")
|
||||||
|
);
|
||||||
|
|
||||||
|
let multiple = target_with_mime(&base_url, vec!["image/png", "image/jpeg"]);
|
||||||
|
let error = adapter
|
||||||
|
.execute(
|
||||||
|
&multiple,
|
||||||
|
&RestRequest {
|
||||||
|
body: Some(json!({
|
||||||
|
"file": { "data_base64": "AA==" }
|
||||||
|
})),
|
||||||
|
body_content_type: Some("multipart/form-data".to_owned()),
|
||||||
|
timeout_ms: 1_000,
|
||||||
|
..RestRequest::default()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
RestAdapterError::InvalidBodyContract { .. }
|
||||||
|
));
|
||||||
|
|
||||||
|
let mismatch = target_with_mime(&base_url, vec!["image/png"]);
|
||||||
|
let error = adapter
|
||||||
|
.execute(
|
||||||
|
&mismatch,
|
||||||
|
&RestRequest {
|
||||||
|
body: Some(json!({
|
||||||
|
"file": { "data_base64": "AA==", "content_type": "image/jpeg" }
|
||||||
|
})),
|
||||||
|
body_content_type: Some("multipart/form-data".to_owned()),
|
||||||
|
timeout_ms: 1_000,
|
||||||
|
..RestRequest::default()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
RestAdapterError::InvalidBodyContract { .. }
|
||||||
|
));
|
||||||
|
assert_eq!(state.multipart.lock().unwrap().len(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn multipart_sends_each_file_array_item_as_decoded_part() {
|
||||||
|
let (base_url, state) = spawn_capture_server().await;
|
||||||
|
test_adapter()
|
||||||
|
.execute(
|
||||||
|
&target(&base_url, "/multipart"),
|
||||||
|
&RestRequest {
|
||||||
|
body: Some(json!({
|
||||||
|
"files": [
|
||||||
|
{"data_base64": ""},
|
||||||
|
{"data_base64": "SGk=", "filename": "two.txt"}
|
||||||
|
]
|
||||||
|
})),
|
||||||
|
body_content_type: Some("multipart/form-data".to_owned()),
|
||||||
|
timeout_ms: 1_000,
|
||||||
|
..RestRequest::default()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let parts = state.multipart.lock().unwrap().clone();
|
||||||
|
assert_eq!(parts.len(), 2);
|
||||||
|
assert_eq!(parts[0].name, "files");
|
||||||
|
assert_eq!(parts[0].bytes, Vec::<u8>::new());
|
||||||
|
assert_eq!(parts[1].bytes, b"Hi");
|
||||||
|
assert_eq!(parts[1].filename.as_deref(), Some("two.txt"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn multipart_limit_includes_serialized_overhead_before_dispatch() {
|
||||||
|
let (base_url, state) = spawn_capture_server().await;
|
||||||
|
let error = RestAdapter::with_policy(
|
||||||
|
OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]).with_max_request_bytes(32),
|
||||||
|
)
|
||||||
|
.execute(
|
||||||
|
&target(&base_url, "/multipart"),
|
||||||
|
&RestRequest {
|
||||||
|
body: Some(json!({
|
||||||
|
"file": { "data_base64": "AA==" }
|
||||||
|
})),
|
||||||
|
body_content_type: Some("multipart/form-data".to_owned()),
|
||||||
|
timeout_ms: 1_000,
|
||||||
|
..RestRequest::default()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap_err();
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
RestAdapterError::RequestTooLarge { limit_bytes: 32 }
|
||||||
|
));
|
||||||
|
assert!(state.multipart.lock().unwrap().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn content_type_selector_controls_json_and_form_wire_serialization() {
|
||||||
|
let (base_url, state) = spawn_capture_server().await;
|
||||||
|
let adapter = test_adapter();
|
||||||
|
|
||||||
|
let json_target = target(&base_url, "/wire");
|
||||||
|
adapter
|
||||||
|
.execute(
|
||||||
|
&json_target,
|
||||||
|
&RestRequest {
|
||||||
|
body: Some(json!({
|
||||||
|
"name": "Ada",
|
||||||
|
"enabled": true
|
||||||
|
})),
|
||||||
|
body_content_type: Some("application/json".to_owned()),
|
||||||
|
timeout_ms: 1_000,
|
||||||
|
..RestRequest::default()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let form_target = target(&base_url, "/wire");
|
||||||
|
adapter
|
||||||
|
.execute(
|
||||||
|
&form_target,
|
||||||
|
&RestRequest {
|
||||||
|
body: Some(json!({
|
||||||
|
"name": "Ada Lovelace",
|
||||||
|
"tag": ["math", "programming"]
|
||||||
|
})),
|
||||||
|
body_content_type: Some("application/x-www-form-urlencoded".to_owned()),
|
||||||
|
timeout_ms: 1_000,
|
||||||
|
..RestRequest::default()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
adapter
|
||||||
|
.execute(
|
||||||
|
&target(&base_url, "/wire"),
|
||||||
|
&RestRequest {
|
||||||
|
body: Some(json!({"file": {"data_base64": "AA=="}})),
|
||||||
|
body_content_type: Some("multipart/form-data".to_owned()),
|
||||||
|
timeout_ms: 1_000,
|
||||||
|
..RestRequest::default()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let requests = state.wire.lock().unwrap().clone();
|
||||||
|
assert_eq!(requests.len(), 3);
|
||||||
|
assert_eq!(requests[0].content_types, vec!["application/json"]);
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::from_slice::<Value>(&requests[0].body).unwrap(),
|
||||||
|
json!({"enabled": true, "name": "Ada"})
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
requests[1].content_types,
|
||||||
|
vec!["application/x-www-form-urlencoded"]
|
||||||
|
);
|
||||||
|
let query = reqwest::Url::parse(&format!(
|
||||||
|
"https://wire.invalid/?{}",
|
||||||
|
String::from_utf8(requests[1].body.clone()).unwrap()
|
||||||
|
))
|
||||||
|
.unwrap()
|
||||||
|
.query_pairs()
|
||||||
|
.into_owned()
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
assert_eq!(
|
||||||
|
query,
|
||||||
|
vec![
|
||||||
|
("name".to_owned(), "Ada Lovelace".to_owned()),
|
||||||
|
("tag".to_owned(), "math".to_owned()),
|
||||||
|
("tag".to_owned(), "programming".to_owned()),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert_eq!(requests[2].content_types.len(), 1);
|
||||||
|
assert!(requests[2].content_types[0].starts_with("multipart/form-data; boundary="));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn legacy_configured_content_type_keeps_json_wire_serialization() {
|
||||||
|
let (base_url, state) = spawn_capture_server().await;
|
||||||
|
for content_type in [
|
||||||
|
"application/json; charset=utf-8",
|
||||||
|
"application/x-www-form-urlencoded; charset=utf-8",
|
||||||
|
] {
|
||||||
|
let target = RestTarget {
|
||||||
|
static_headers: BTreeMap::from([("content-type".to_owned(), content_type.to_owned())]),
|
||||||
|
request_contract: None,
|
||||||
|
..target(&base_url, "/wire")
|
||||||
|
};
|
||||||
|
test_adapter()
|
||||||
|
.execute(
|
||||||
|
&target,
|
||||||
|
&RestRequest {
|
||||||
|
body: Some(json!({"name": "Ada", "tag": ["math", "programming"]})),
|
||||||
|
timeout_ms: 1_000,
|
||||||
|
..RestRequest::default()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
let requests = state.wire.lock().unwrap().clone();
|
||||||
|
assert_eq!(requests.len(), 2);
|
||||||
|
for (request, content_type) in requests.iter().zip([
|
||||||
|
"application/json; charset=utf-8",
|
||||||
|
"application/x-www-form-urlencoded; charset=utf-8",
|
||||||
|
]) {
|
||||||
|
assert_eq!(request.content_types, vec![content_type]);
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::from_slice::<Value>(&request.body).unwrap(),
|
||||||
|
json!({"name": "Ada", "tag": ["math", "programming"]})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn mapped_cookie_conflicting_with_trusted_cookie_is_rejected_before_dispatch() {
|
||||||
|
let (base_url, state) = spawn_capture_server().await;
|
||||||
|
let legacy_target = RestTarget {
|
||||||
|
request_contract: None,
|
||||||
|
..target(&base_url, "/wire")
|
||||||
|
};
|
||||||
|
let conflict = RestRequest {
|
||||||
|
headers: BTreeMap::from([
|
||||||
|
("cookie".to_owned(), "auth=trusted".to_owned()),
|
||||||
|
(
|
||||||
|
"x-crank-internal-cookie-session".to_owned(),
|
||||||
|
"session\tmapped".to_owned(),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
trusted_header_names: BTreeSet::from(["cookie".to_owned()]),
|
||||||
|
timeout_ms: 1_000,
|
||||||
|
..RestRequest::default()
|
||||||
|
};
|
||||||
|
assert!(matches!(
|
||||||
|
test_adapter().execute(&legacy_target, &conflict).await,
|
||||||
|
Err(RestAdapterError::InvalidBodyContract { .. })
|
||||||
|
));
|
||||||
|
assert!(state.wire.lock().unwrap().is_empty());
|
||||||
|
|
||||||
|
test_adapter()
|
||||||
|
.execute(
|
||||||
|
&legacy_target,
|
||||||
|
&RestRequest {
|
||||||
|
headers: BTreeMap::from([("cookie".to_owned(), "auth=trusted".to_owned())]),
|
||||||
|
trusted_header_names: BTreeSet::from(["cookie".to_owned()]),
|
||||||
|
timeout_ms: 1_000,
|
||||||
|
..RestRequest::default()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
state.wire.lock().unwrap()[0].cookie.as_deref(),
|
||||||
|
Some("auth=trusted")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn target(base_url: &str, path: &str) -> RestTarget {
|
||||||
|
RestTarget {
|
||||||
|
base_url: base_url.to_owned(),
|
||||||
|
method: HttpMethod::Post,
|
||||||
|
path_template: path.to_owned(),
|
||||||
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: Some(RestRequestContract {
|
||||||
|
version: RestRequestContractVersion::V1,
|
||||||
|
body_field: "body".to_owned(),
|
||||||
|
selector_field: Some("content_type".to_owned()),
|
||||||
|
body_required: true,
|
||||||
|
variants: [
|
||||||
|
"application/json",
|
||||||
|
"application/x-www-form-urlencoded",
|
||||||
|
"multipart/form-data",
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(schema_variant, media_type)| RestRequestDescriptor {
|
||||||
|
media_type: media_type.to_owned(),
|
||||||
|
schema_variant,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
}),
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn target_with_mime(base_url: &str, allowed_mime_types: Vec<&str>) -> RestTarget {
|
||||||
|
RestTarget {
|
||||||
|
multipart_field_mime_types: BTreeMap::from([(
|
||||||
|
"multipart/form-data".to_owned(),
|
||||||
|
BTreeMap::from([(
|
||||||
|
"file".to_owned(),
|
||||||
|
allowed_mime_types
|
||||||
|
.into_iter()
|
||||||
|
.map(ToOwned::to_owned)
|
||||||
|
.collect(),
|
||||||
|
)]),
|
||||||
|
)]),
|
||||||
|
..target(base_url, "/multipart")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn test_adapter() -> RestAdapter {
|
||||||
|
RestAdapter::with_policy(OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn spawn_capture_server() -> (String, Arc<CaptureState>) {
|
||||||
|
let state = Arc::new(CaptureState::default());
|
||||||
|
let app = Router::new()
|
||||||
|
.route("/multipart", post(capture_multipart))
|
||||||
|
.route("/api/v2/multipart", post(capture_multipart))
|
||||||
|
.route(
|
||||||
|
"/api/v2/no-content",
|
||||||
|
get(|| async { StatusCode::NO_CONTENT }),
|
||||||
|
)
|
||||||
|
.route("/wire", post(capture_wire))
|
||||||
|
.with_state(Arc::clone(&state));
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let address = listener.local_addr().unwrap();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
axum::serve(listener, app).await.unwrap();
|
||||||
|
});
|
||||||
|
(format!("http://{address}"), state)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn capture_multipart(
|
||||||
|
State(state): State<Arc<CaptureState>>,
|
||||||
|
mut multipart: Multipart,
|
||||||
|
) -> (StatusCode, Json<Value>) {
|
||||||
|
while let Some(field) = multipart.next_field().await.unwrap() {
|
||||||
|
let part = MultipartPart {
|
||||||
|
name: field.name().unwrap_or_default().to_owned(),
|
||||||
|
filename: field.file_name().map(ToOwned::to_owned),
|
||||||
|
content_type: field.content_type().map(ToOwned::to_owned),
|
||||||
|
bytes: field.bytes().await.unwrap().to_vec(),
|
||||||
|
};
|
||||||
|
state.multipart.lock().unwrap().push(part);
|
||||||
|
}
|
||||||
|
(StatusCode::OK, Json(json!({"ok": true})))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn capture_wire(
|
||||||
|
State(state): State<Arc<CaptureState>>,
|
||||||
|
headers: HeaderMap,
|
||||||
|
body: Bytes,
|
||||||
|
) -> (StatusCode, Json<Value>) {
|
||||||
|
state.wire.lock().unwrap().push(WireRequest {
|
||||||
|
content_types: headers
|
||||||
|
.get_all("content-type")
|
||||||
|
.iter()
|
||||||
|
.filter_map(|value| value.to_str().ok().map(ToOwned::to_owned))
|
||||||
|
.collect(),
|
||||||
|
cookie: headers
|
||||||
|
.get("cookie")
|
||||||
|
.and_then(|value| value.to_str().ok())
|
||||||
|
.map(ToOwned::to_owned),
|
||||||
|
body: body.to_vec(),
|
||||||
|
});
|
||||||
|
(StatusCode::OK, Json(json!({"ok": true})))
|
||||||
|
}
|
||||||
@@ -38,6 +38,9 @@ async fn forbidden_credential_and_framing_headers_fail_before_bytes_leave() {
|
|||||||
),
|
),
|
||||||
("host".to_owned(), "metadata.internal".to_owned()),
|
("host".to_owned(), "metadata.internal".to_owned()),
|
||||||
]),
|
]),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
};
|
};
|
||||||
|
|
||||||
let error = adapter
|
let error = adapter
|
||||||
@@ -64,6 +67,9 @@ async fn request_body_limit_fails_before_bytes_leave() {
|
|||||||
method: HttpMethod::Post,
|
method: HttpMethod::Post,
|
||||||
path_template: "/capture".to_owned(),
|
path_template: "/capture".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
};
|
};
|
||||||
|
|
||||||
let error = adapter
|
let error = adapter
|
||||||
@@ -101,6 +107,9 @@ async fn proxy_environment_is_ignored_by_default() {
|
|||||||
method: HttpMethod::Post,
|
method: HttpMethod::Post,
|
||||||
path_template: "/capture".to_owned(),
|
path_template: "/capture".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
};
|
};
|
||||||
let _ = adapter.execute(&rest_target, &request).await.expect_err(
|
let _ = adapter.execute(&rest_target, &request).await.expect_err(
|
||||||
"unresolvable target should fail locally instead of being sent through proxy env",
|
"unresolvable target should fail locally instead of being sent through proxy env",
|
||||||
|
|||||||
@@ -108,8 +108,9 @@ fn search_mode_tool_definitions(policy: &ToolSelectionPolicy) -> Vec<Value> {
|
|||||||
pub fn tool_definitions(tool: &PublishedAgentTool) -> Vec<Value> {
|
pub fn tool_definitions(tool: &PublishedAgentTool) -> Vec<Value> {
|
||||||
let safety = effective_safety_policy(tool);
|
let safety = effective_safety_policy(tool);
|
||||||
let requires_confirmation = safety.class.requires_confirmation();
|
let requires_confirmation = safety.class.requires_confirmation();
|
||||||
|
let input_schema = operation_input_json_schema(tool);
|
||||||
let input_schema = if requires_confirmation {
|
let input_schema = if requires_confirmation {
|
||||||
add_confirmation_token(schema_to_json_schema(&tool.operation.input_schema))
|
add_confirmation_token(input_schema)
|
||||||
} else {
|
} else {
|
||||||
schema_to_json_schema(&tool.operation.input_schema)
|
schema_to_json_schema(&tool.operation.input_schema)
|
||||||
};
|
};
|
||||||
@@ -130,6 +131,26 @@ pub fn tool_definitions(tool: &PublishedAgentTool) -> Vec<Value> {
|
|||||||
)]
|
)]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn operation_input_json_schema(tool: &PublishedAgentTool) -> Value {
|
||||||
|
let mut projected = schema_to_json_schema(&tool.operation.input_schema);
|
||||||
|
if matches!(&tool.operation.target, Target::Rest(target) if target.request_contract.is_some()) {
|
||||||
|
close_request_objects(&mut projected);
|
||||||
|
}
|
||||||
|
projected
|
||||||
|
}
|
||||||
|
|
||||||
|
fn close_request_objects(schema: &mut Value) {
|
||||||
|
if let Some(variants) = schema.get_mut("anyOf").and_then(Value::as_array_mut) {
|
||||||
|
for variant in variants {
|
||||||
|
close_request_objects(variant);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if schema.get("type").and_then(Value::as_str) == Some("object") {
|
||||||
|
schema["additionalProperties"] = Value::Bool(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn analyze_published_tool_catalog(
|
pub fn analyze_published_tool_catalog(
|
||||||
tools: &[PublishedAgentTool],
|
tools: &[PublishedAgentTool],
|
||||||
) -> Result<ToolCatalogAnalysis, ToolCatalogAnalysisError> {
|
) -> Result<ToolCatalogAnalysis, ToolCatalogAnalysisError> {
|
||||||
@@ -187,13 +208,25 @@ fn infer_safety_class(tool: &PublishedAgentTool) -> OperationSafetyClass {
|
|||||||
HttpMethod::Get => OperationSafetyClass::Read,
|
HttpMethod::Get => OperationSafetyClass::Read,
|
||||||
HttpMethod::Delete => OperationSafetyClass::Destructive,
|
HttpMethod::Delete => OperationSafetyClass::Destructive,
|
||||||
HttpMethod::Post | HttpMethod::Put | HttpMethod::Patch => OperationSafetyClass::Write,
|
HttpMethod::Post | HttpMethod::Put | HttpMethod::Patch => OperationSafetyClass::Write,
|
||||||
|
HttpMethod::Head | HttpMethod::Options => OperationSafetyClass::Read,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn add_confirmation_token(mut schema: Value) -> Value {
|
fn add_confirmation_token(mut schema: Value) -> Value {
|
||||||
let Some(object) = schema.as_object_mut() else {
|
if let Some(variants) = schema.get_mut("anyOf").and_then(Value::as_array_mut) {
|
||||||
|
for variant in variants {
|
||||||
|
add_confirmation_token_to_object(variant);
|
||||||
|
}
|
||||||
return schema;
|
return schema;
|
||||||
|
}
|
||||||
|
add_confirmation_token_to_object(&mut schema);
|
||||||
|
schema
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add_confirmation_token_to_object(schema: &mut Value) {
|
||||||
|
let Some(object) = schema.as_object_mut() else {
|
||||||
|
return;
|
||||||
};
|
};
|
||||||
let properties = object.entry("properties").or_insert_with(|| json!({}));
|
let properties = object.entry("properties").or_insert_with(|| json!({}));
|
||||||
if let Some(properties) = properties.as_object_mut() {
|
if let Some(properties) = properties.as_object_mut() {
|
||||||
@@ -205,11 +238,10 @@ fn add_confirmation_token(mut schema: Value) -> Value {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
schema
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn schema_to_json_schema(schema: &crank_schema::Schema) -> Value {
|
pub fn schema_to_json_schema(schema: &crank_schema::Schema) -> Value {
|
||||||
match schema.kind {
|
let mut projected = match schema.kind {
|
||||||
crank_schema::SchemaKind::Object => {
|
crank_schema::SchemaKind::Object => {
|
||||||
let mut properties = serde_json::Map::new();
|
let mut properties = serde_json::Map::new();
|
||||||
let mut required = Vec::new();
|
let mut required = Vec::new();
|
||||||
@@ -242,11 +274,55 @@ pub fn schema_to_json_schema(schema: &crank_schema::Schema) -> Value {
|
|||||||
crank_schema::SchemaKind::Boolean => json!({ "type": "boolean" }),
|
crank_schema::SchemaKind::Boolean => json!({ "type": "boolean" }),
|
||||||
crank_schema::SchemaKind::Enum => json!({
|
crank_schema::SchemaKind::Enum => json!({
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"enum": schema.enum_values
|
"enum": schema.enum_values.clone()
|
||||||
}),
|
}),
|
||||||
crank_schema::SchemaKind::Null => json!({ "type": "null" }),
|
crank_schema::SchemaKind::Null => json!({ "type": "null" }),
|
||||||
crank_schema::SchemaKind::Oneof => json!({
|
crank_schema::SchemaKind::Oneof => json!({
|
||||||
"anyOf": schema.variants.iter().map(schema_to_json_schema).collect::<Vec<_>>()
|
"anyOf": schema.variants.iter().map(schema_to_json_schema).collect::<Vec<_>>()
|
||||||
}),
|
}),
|
||||||
|
};
|
||||||
|
if schema.kind == crank_schema::SchemaKind::Object
|
||||||
|
&& matches!(
|
||||||
|
schema.format.as_deref(),
|
||||||
|
Some("binary" | crank_schema::CLOSED_OBJECT_SCHEMA_FORMAT)
|
||||||
|
)
|
||||||
|
{
|
||||||
|
projected["additionalProperties"] = Value::Bool(false);
|
||||||
}
|
}
|
||||||
|
if let Some(format) = &schema.format
|
||||||
|
&& format != crank_schema::CLOSED_OBJECT_SCHEMA_FORMAT
|
||||||
|
{
|
||||||
|
projected["format"] = Value::String(format.clone());
|
||||||
|
}
|
||||||
|
if schema.nullable {
|
||||||
|
if schema.kind == crank_schema::SchemaKind::Enum
|
||||||
|
&& let Some(values) = projected.get_mut("enum").and_then(Value::as_array_mut)
|
||||||
|
&& !values.iter().any(Value::is_null)
|
||||||
|
{
|
||||||
|
values.push(Value::Null);
|
||||||
|
}
|
||||||
|
if let Some(kind) = projected.get_mut("type") {
|
||||||
|
match kind {
|
||||||
|
Value::String(name) => {
|
||||||
|
*kind = Value::Array(vec![
|
||||||
|
Value::String(name.clone()),
|
||||||
|
Value::String("null".to_owned()),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
Value::Array(kinds) if !kinds.iter().any(|kind| kind.as_str() == Some("null")) => {
|
||||||
|
kinds.push(Value::String("null".to_owned()));
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
} else if let Some(variants) = projected.get_mut("anyOf").and_then(Value::as_array_mut) {
|
||||||
|
variants.push(json!({"type": "null"}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(default) = &schema.default_value {
|
||||||
|
projected["default"] = default.clone();
|
||||||
|
}
|
||||||
|
if let Some(description) = &schema.description {
|
||||||
|
projected["description"] = Value::String(description.clone());
|
||||||
|
}
|
||||||
|
projected
|
||||||
}
|
}
|
||||||
@@ -2,12 +2,13 @@ use std::collections::BTreeMap;
|
|||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
|
|
||||||
use crank_community_mcp::manifest::{
|
use crank_community_mcp::manifest::{
|
||||||
analyze_published_tool_catalog, catalog_tool_definitions, tool_definitions,
|
analyze_published_tool_catalog, catalog_tool_definitions, schema_to_json_schema,
|
||||||
|
tool_definitions,
|
||||||
};
|
};
|
||||||
use crank_core::{
|
use crank_core::{
|
||||||
ExecutionConfig, HttpMethod, Operation, OperationId, OperationSecurityLevel, OperationStatus,
|
ExecutionConfig, HttpMethod, Operation, OperationId, OperationSecurityLevel, OperationStatus,
|
||||||
Protocol, RestTarget, Target, ToolAccessMode, ToolDescription, ToolSelectionPolicy,
|
Protocol, RestRequestContract, RestRequestContractVersion, RestRequestDescriptor, RestTarget,
|
||||||
WorkspaceId,
|
Target, ToolAccessMode, ToolDescription, ToolSelectionPolicy, WorkspaceId,
|
||||||
};
|
};
|
||||||
use crank_mapping::MappingSet;
|
use crank_mapping::MappingSet;
|
||||||
use crank_registry::{PublishedAgentCatalog, PublishedAgentTool, RegistryOperation};
|
use crank_registry::{PublishedAgentCatalog, PublishedAgentTool, RegistryOperation};
|
||||||
@@ -61,6 +62,107 @@ fn marks_destructive_tools_as_two_step_confirmation_calls() {
|
|||||||
assert_eq!(definition["inputSchema"]["required"], json!(["base"]));
|
assert_eq!(definition["inputSchema"]["required"], json!(["base"]));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn projects_nullable_and_binary_as_valid_closed_json_schema() {
|
||||||
|
let nullable = Schema {
|
||||||
|
kind: SchemaKind::String,
|
||||||
|
nullable: true,
|
||||||
|
..empty_schema(SchemaKind::String)
|
||||||
|
};
|
||||||
|
let projected = schema_to_json_schema(&nullable);
|
||||||
|
assert_eq!(projected["type"], json!(["string", "null"]));
|
||||||
|
assert!(projected.get("nullable").is_none());
|
||||||
|
|
||||||
|
let nullable_enum = Schema {
|
||||||
|
kind: SchemaKind::Enum,
|
||||||
|
nullable: true,
|
||||||
|
enum_values: vec!["draft".to_owned()],
|
||||||
|
..empty_schema(SchemaKind::Enum)
|
||||||
|
};
|
||||||
|
let projected = schema_to_json_schema(&nullable_enum);
|
||||||
|
assert_eq!(projected["type"], json!(["string", "null"]));
|
||||||
|
assert_eq!(projected["enum"], json!(["draft", null]));
|
||||||
|
|
||||||
|
let binary = Schema {
|
||||||
|
kind: SchemaKind::Object,
|
||||||
|
format: Some("binary".to_owned()),
|
||||||
|
fields: BTreeMap::from([(
|
||||||
|
"data_base64".to_owned(),
|
||||||
|
Schema {
|
||||||
|
required: true,
|
||||||
|
..empty_schema(SchemaKind::String)
|
||||||
|
},
|
||||||
|
)]),
|
||||||
|
..empty_schema(SchemaKind::Object)
|
||||||
|
};
|
||||||
|
let projected = schema_to_json_schema(&binary);
|
||||||
|
assert_eq!(projected["additionalProperties"], false);
|
||||||
|
assert_eq!(projected["format"], "binary");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn optional_request_pair_uses_closed_presence_and_absence_branches() {
|
||||||
|
let mut tool = published_tool();
|
||||||
|
let selected = Schema {
|
||||||
|
kind: SchemaKind::Object,
|
||||||
|
format: Some(crank_schema::CLOSED_OBJECT_SCHEMA_FORMAT.to_owned()),
|
||||||
|
fields: BTreeMap::from([
|
||||||
|
(
|
||||||
|
"body".to_owned(),
|
||||||
|
Schema {
|
||||||
|
required: true,
|
||||||
|
..empty_schema(SchemaKind::Object)
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"content_type".to_owned(),
|
||||||
|
Schema {
|
||||||
|
kind: SchemaKind::Enum,
|
||||||
|
required: true,
|
||||||
|
enum_values: vec!["application/json".to_owned()],
|
||||||
|
..empty_schema(SchemaKind::Enum)
|
||||||
|
},
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
..empty_schema(SchemaKind::Object)
|
||||||
|
};
|
||||||
|
let absent = Schema {
|
||||||
|
kind: SchemaKind::Object,
|
||||||
|
format: Some(crank_schema::CLOSED_OBJECT_SCHEMA_FORMAT.to_owned()),
|
||||||
|
..empty_schema(SchemaKind::Object)
|
||||||
|
};
|
||||||
|
tool.operation.input_schema = Schema {
|
||||||
|
kind: SchemaKind::Oneof,
|
||||||
|
variants: vec![selected, absent],
|
||||||
|
..empty_schema(SchemaKind::Oneof)
|
||||||
|
};
|
||||||
|
let Target::Rest(target) = &mut tool.operation.target;
|
||||||
|
target.request_contract = Some(RestRequestContract {
|
||||||
|
version: RestRequestContractVersion::V1,
|
||||||
|
body_field: "body".to_owned(),
|
||||||
|
selector_field: Some("content_type".to_owned()),
|
||||||
|
body_required: false,
|
||||||
|
variants: vec![RestRequestDescriptor {
|
||||||
|
media_type: "application/json".to_owned(),
|
||||||
|
schema_variant: 0,
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
|
||||||
|
let schema = &tool_definitions(&tool)[0]["inputSchema"];
|
||||||
|
assert_eq!(schema["anyOf"][0]["additionalProperties"], false);
|
||||||
|
assert_eq!(
|
||||||
|
schema["anyOf"][0]["required"],
|
||||||
|
json!(["body", "content_type"])
|
||||||
|
);
|
||||||
|
assert_eq!(schema["anyOf"][1]["additionalProperties"], false);
|
||||||
|
assert!(
|
||||||
|
schema["anyOf"][1]["properties"]
|
||||||
|
.as_object()
|
||||||
|
.unwrap()
|
||||||
|
.is_empty()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn catalog_budget_uses_the_same_definitions_as_tools_list() {
|
fn catalog_budget_uses_the_same_definitions_as_tools_list() {
|
||||||
let tool = published_tool();
|
let tool = published_tool();
|
||||||
@@ -154,10 +256,14 @@ fn operation() -> RegistryOperation {
|
|||||||
method: HttpMethod::Get,
|
method: HttpMethod::Get,
|
||||||
path_template: "/v2/rates".to_owned(),
|
path_template: "/v2/rates".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
}),
|
}),
|
||||||
input_schema: input_schema(),
|
input_schema: input_schema(),
|
||||||
output_schema: Schema {
|
output_schema: Schema {
|
||||||
kind: SchemaKind::Object,
|
kind: SchemaKind::Object,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: false,
|
required: false,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
@@ -201,6 +307,7 @@ fn input_schema() -> Schema {
|
|||||||
"base".to_owned(),
|
"base".to_owned(),
|
||||||
Schema {
|
Schema {
|
||||||
kind: SchemaKind::String,
|
kind: SchemaKind::String,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
@@ -215,6 +322,7 @@ fn input_schema() -> Schema {
|
|||||||
"mode".to_owned(),
|
"mode".to_owned(),
|
||||||
Schema {
|
Schema {
|
||||||
kind: SchemaKind::Enum,
|
kind: SchemaKind::Enum,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: false,
|
required: false,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
@@ -228,6 +336,7 @@ fn input_schema() -> Schema {
|
|||||||
|
|
||||||
Schema {
|
Schema {
|
||||||
kind: SchemaKind::Object,
|
kind: SchemaKind::Object,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: false,
|
required: false,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
@@ -239,6 +348,21 @@ fn input_schema() -> Schema {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn empty_schema(kind: SchemaKind) -> Schema {
|
||||||
|
Schema {
|
||||||
|
kind,
|
||||||
|
format: None,
|
||||||
|
description: None,
|
||||||
|
required: false,
|
||||||
|
nullable: false,
|
||||||
|
default_value: None,
|
||||||
|
fields: BTreeMap::new(),
|
||||||
|
items: None,
|
||||||
|
enum_values: Vec::new(),
|
||||||
|
variants: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn timestamp(value: &str) -> OffsetDateTime {
|
fn timestamp(value: &str) -> OffsetDateTime {
|
||||||
OffsetDateTime::parse(value, &Rfc3339).unwrap()
|
OffsetDateTime::parse(value, &Rfc3339).unwrap()
|
||||||
}
|
}
|
||||||
@@ -150,6 +150,7 @@ pub struct PreparedRequest {
|
|||||||
pub headers: BTreeMap<String, String>,
|
pub headers: BTreeMap<String, String>,
|
||||||
pub trusted_header_names: BTreeSet<String>,
|
pub trusted_header_names: BTreeSet<String>,
|
||||||
pub body: Option<Value>,
|
pub body: Option<Value>,
|
||||||
|
pub body_content_type: Option<String>,
|
||||||
pub timeout_ms: u64,
|
pub timeout_ms: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -162,6 +163,10 @@ impl std::fmt::Debug for PreparedRequest {
|
|||||||
.field("header_count", &self.headers.len())
|
.field("header_count", &self.headers.len())
|
||||||
.field("trusted_header_count", &self.trusted_header_names.len())
|
.field("trusted_header_count", &self.trusted_header_names.len())
|
||||||
.field("body_configured", &self.body.is_some())
|
.field("body_configured", &self.body.is_some())
|
||||||
|
.field(
|
||||||
|
"body_content_type_configured",
|
||||||
|
&self.body_content_type.is_some(),
|
||||||
|
)
|
||||||
.field("timeout_ms", &self.timeout_ms)
|
.field("timeout_ms", &self.timeout_ms)
|
||||||
.finish()
|
.finish()
|
||||||
}
|
}
|
||||||
@@ -333,6 +338,9 @@ mod tests {
|
|||||||
method: crate::HttpMethod::Get,
|
method: crate::HttpMethod::Get,
|
||||||
path_template: "/health".to_owned(),
|
path_template: "/health".to_owned(),
|
||||||
static_headers: Default::default(),
|
static_headers: Default::default(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: Default::default(),
|
||||||
});
|
});
|
||||||
|
|
||||||
let response = adapter
|
let response = adapter
|
||||||
|
|||||||
@@ -169,7 +169,8 @@ pub use operation::{
|
|||||||
OperationApprovalPayloadPreviewMode, OperationApprovalPolicy, OperationApprovalRiskLevel,
|
OperationApprovalPayloadPreviewMode, OperationApprovalPolicy, OperationApprovalRiskLevel,
|
||||||
OperationAvailability, OperationLifecycle, OperationLifecycleAction, OperationLifecycleError,
|
OperationAvailability, OperationLifecycle, OperationLifecycleAction, OperationLifecycleError,
|
||||||
OperationSafetyClass, OperationSafetyPolicy, OperationStatus, OperationVersionState,
|
OperationSafetyClass, OperationSafetyPolicy, OperationStatus, OperationVersionState,
|
||||||
ResponseCachePolicy, RestTarget, RetryPolicy, Samples, Target, ToolDescription, ToolExample,
|
ResponseCachePolicy, RestRequestContract, RestRequestContractVersion, RestRequestDescriptor,
|
||||||
|
RestResponseDescriptor, RestTarget, RetryPolicy, Samples, Target, ToolDescription, ToolExample,
|
||||||
WizardState,
|
WizardState,
|
||||||
};
|
};
|
||||||
pub use product_event::{
|
pub use product_event::{
|
||||||
|
|||||||
@@ -101,6 +101,62 @@ pub struct RestTarget {
|
|||||||
pub path_template: String,
|
pub path_template: String,
|
||||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||||
pub static_headers: BTreeMap<String, String>,
|
pub static_headers: BTreeMap<String, String>,
|
||||||
|
/// Typed request-body metadata used by Operations generated by the HTTP
|
||||||
|
/// contract importer. `None` preserves the preparation and JSON wire
|
||||||
|
/// behavior of Operations persisted before this contract existed.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub request_contract: Option<RestRequestContract>,
|
||||||
|
/// The successful HTTP responses accepted by this Operation. An empty
|
||||||
|
/// contract retains the permissive behavior of Operations persisted
|
||||||
|
/// before response variants were made explicit.
|
||||||
|
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||||
|
pub response_contract: Vec<RestResponseDescriptor>,
|
||||||
|
/// Source-declared MIME choices for multipart file fields, keyed first by
|
||||||
|
/// request media type and then by field name. Empty retains the behavior
|
||||||
|
/// of Operations persisted before multipart contracts were explicit.
|
||||||
|
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||||
|
pub multipart_field_mime_types: BTreeMap<String, BTreeMap<String, Vec<String>>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A single successful REST response branch.
|
||||||
|
///
|
||||||
|
/// `media_type: None` represents the explicit no-content branch. A response
|
||||||
|
/// with a body must select a branch with the exact status and media type.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct RestResponseDescriptor {
|
||||||
|
pub status_code: u16,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub media_type: Option<String>,
|
||||||
|
/// Index of the matching branch in `Operation.output_schema`. A scalar
|
||||||
|
/// output schema uses index zero.
|
||||||
|
pub schema_variant: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub enum RestRequestContractVersion {
|
||||||
|
#[serde(rename = "1")]
|
||||||
|
V1,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct RestRequestContract {
|
||||||
|
pub version: RestRequestContractVersion,
|
||||||
|
pub body_field: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub selector_field: Option<String>,
|
||||||
|
pub body_required: bool,
|
||||||
|
pub variants: Vec<RestRequestDescriptor>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(deny_unknown_fields)]
|
||||||
|
pub struct RestRequestDescriptor {
|
||||||
|
pub media_type: String,
|
||||||
|
/// Index of the matching top-level `Operation.input_schema` branch. A
|
||||||
|
/// request contract without a top-level union uses index zero.
|
||||||
|
pub schema_variant: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
@@ -406,6 +462,9 @@ mod tests {
|
|||||||
method: HttpMethod::Post,
|
method: HttpMethod::Post,
|
||||||
path_template: "/v1/leads".to_owned(),
|
path_template: "/v1/leads".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
});
|
});
|
||||||
|
|
||||||
let value = serde_json::to_value(target).unwrap();
|
let value = serde_json::to_value(target).unwrap();
|
||||||
@@ -571,6 +630,8 @@ updated_at: 2026-03-25T08:10:00Z
|
|||||||
|
|
||||||
assert_eq!(restored.security_level, OperationSecurityLevel::Standard);
|
assert_eq!(restored.security_level, OperationSecurityLevel::Standard);
|
||||||
assert_eq!(restored.published_at, None);
|
assert_eq!(restored.published_at, None);
|
||||||
|
let Target::Rest(target) = restored.target;
|
||||||
|
assert!(target.response_contract.is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
fn test_operation(status: OperationStatus) -> Operation<serde_json::Value, serde_json::Value> {
|
fn test_operation(status: OperationStatus) -> Operation<serde_json::Value, serde_json::Value> {
|
||||||
@@ -588,6 +649,9 @@ updated_at: 2026-03-25T08:10:00Z
|
|||||||
method: HttpMethod::Post,
|
method: HttpMethod::Post,
|
||||||
path_template: "/v1/leads".to_owned(),
|
path_template: "/v1/leads".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
}),
|
}),
|
||||||
input_schema: json!({"type":"object","fields":{"email":{"type":"string","required":true}}}),
|
input_schema: json!({"type":"object","fields":{"email":{"type":"string","required":true}}}),
|
||||||
output_schema: json!({"type":"object","fields":{"id":{"type":"string","required":true}}}),
|
output_schema: json!({"type":"object","fields":{"id":{"type":"string","required":true}}}),
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ pub enum HttpMethod {
|
|||||||
Put,
|
Put,
|
||||||
Patch,
|
Patch,
|
||||||
Delete,
|
Delete,
|
||||||
|
Head,
|
||||||
|
Options,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
|||||||
@@ -14,4 +14,4 @@ serde.workspace = true
|
|||||||
serde_json.workspace = true
|
serde_json.workspace = true
|
||||||
serde_yaml.workspace = true
|
serde_yaml.workspace = true
|
||||||
thiserror.workspace = true
|
thiserror.workspace = true
|
||||||
|
url.workspace = true
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
use crank_core::HttpMethod;
|
||||||
|
|
||||||
|
use crate::rest::model::{ImportFinding, ImportFindingSeverity};
|
||||||
|
|
||||||
|
pub(super) fn from_lower(value: &str) -> Option<HttpMethod> {
|
||||||
|
match value {
|
||||||
|
"get" => Some(HttpMethod::Get),
|
||||||
|
"post" => Some(HttpMethod::Post),
|
||||||
|
"put" => Some(HttpMethod::Put),
|
||||||
|
"patch" => Some(HttpMethod::Patch),
|
||||||
|
"delete" => Some(HttpMethod::Delete),
|
||||||
|
"head" => Some(HttpMethod::Head),
|
||||||
|
"options" => Some(HttpMethod::Options),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn invalid_path_item() -> ImportFinding {
|
||||||
|
ImportFinding {
|
||||||
|
code: "invalid_path_item".to_owned(),
|
||||||
|
severity: ImportFindingSeverity::Error,
|
||||||
|
message: "Path Item имеет неверную структуру и не был интерпретирован.".to_owned(),
|
||||||
|
operation_key: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
// Frozen pre-v4 projection for historical legacy-v1 jobs.
|
||||||
|
use crank_mapping::{MappingRule, MappingSet};
|
||||||
|
use crank_schema::{Schema, SchemaKind};
|
||||||
|
|
||||||
|
use crate::rest::model::{RestImportParameter, RestParameterLocation};
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct BodyFieldMapping {
|
||||||
|
pub input_name: String,
|
||||||
|
pub body_path: String,
|
||||||
|
pub required: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn input_mapping(
|
||||||
|
parameters: &[RestImportParameter],
|
||||||
|
body_fields: &[BodyFieldMapping],
|
||||||
|
) -> MappingSet {
|
||||||
|
let mut rules = Vec::new();
|
||||||
|
for parameter in parameters {
|
||||||
|
let target_root = match parameter.location {
|
||||||
|
RestParameterLocation::Path => "$.request.path",
|
||||||
|
RestParameterLocation::Query => "$.request.query",
|
||||||
|
RestParameterLocation::Header => "$.request.headers",
|
||||||
|
RestParameterLocation::Cookie => "$.request.cookies",
|
||||||
|
};
|
||||||
|
rules.push(MappingRule {
|
||||||
|
source: format!("$.mcp.{}", parameter.name),
|
||||||
|
target: format!("{target_root}.{}", parameter.name),
|
||||||
|
required: parameter.required,
|
||||||
|
default_value: None,
|
||||||
|
transform: None,
|
||||||
|
condition: None,
|
||||||
|
notes: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
for field in body_fields {
|
||||||
|
let target = if field.body_path.is_empty() {
|
||||||
|
"$.request.body".to_owned()
|
||||||
|
} else {
|
||||||
|
format!("$.request.body.{}", field.body_path)
|
||||||
|
};
|
||||||
|
rules.push(MappingRule {
|
||||||
|
source: format!("$.mcp.{}", field.input_name),
|
||||||
|
target,
|
||||||
|
required: field.required,
|
||||||
|
default_value: None,
|
||||||
|
transform: None,
|
||||||
|
condition: None,
|
||||||
|
notes: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
MappingSet { rules }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn output_mapping(output_schema: &Schema) -> MappingSet {
|
||||||
|
let mut rules = Vec::new();
|
||||||
|
if output_schema.kind == SchemaKind::Object && !output_schema.fields.is_empty() {
|
||||||
|
for (name, field) in &output_schema.fields {
|
||||||
|
rules.push(MappingRule {
|
||||||
|
source: format!("$.response.body.{name}"),
|
||||||
|
target: format!("$.output.{name}"),
|
||||||
|
required: field.required,
|
||||||
|
default_value: None,
|
||||||
|
transform: None,
|
||||||
|
condition: None,
|
||||||
|
notes: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
rules.push(MappingRule {
|
||||||
|
source: "$.response.body".to_owned(),
|
||||||
|
target: "$.output".to_owned(),
|
||||||
|
required: true,
|
||||||
|
default_value: None,
|
||||||
|
transform: None,
|
||||||
|
condition: None,
|
||||||
|
notes: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
MappingSet { rules }
|
||||||
|
}
|
||||||
@@ -0,0 +1,240 @@
|
|||||||
|
// Frozen pre-v4 projection for historical legacy-v1 jobs.
|
||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
|
use crank_core::{
|
||||||
|
ExecutionConfig, HttpMethod, OperationSafetyClass, OperationSafetyPolicy, Protocol, RestTarget,
|
||||||
|
ToolDescription, ToolExample, WizardState,
|
||||||
|
};
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
use crate::rest::{
|
||||||
|
legacy_mapping::{BodyFieldMapping, input_mapping, output_mapping},
|
||||||
|
legacy_schema::{any_object, field_count, object_with_fields, schema_from_openapi},
|
||||||
|
model::{
|
||||||
|
ImportOperationCandidate, RestImportCandidate, RestImportOperation, RestParameterLocation,
|
||||||
|
},
|
||||||
|
naming::{fallback_operation_seed, title_from_name, unique_name},
|
||||||
|
recommendations::{candidate_recommendations, operation_recommendations},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub fn candidate_from_operation(
|
||||||
|
operation: &RestImportOperation,
|
||||||
|
document_servers: &[String],
|
||||||
|
used_names: &mut BTreeSet<String>,
|
||||||
|
) -> ImportOperationCandidate {
|
||||||
|
let method_name = method_as_str(operation.method);
|
||||||
|
let seed = operation
|
||||||
|
.operation_id
|
||||||
|
.as_deref()
|
||||||
|
.filter(|value| !value.trim().is_empty())
|
||||||
|
.map(ToOwned::to_owned)
|
||||||
|
.unwrap_or_else(|| fallback_operation_seed(method_name, &operation.path));
|
||||||
|
let name = unique_name(&seed, used_names);
|
||||||
|
let display_name = operation
|
||||||
|
.summary
|
||||||
|
.as_deref()
|
||||||
|
.filter(|value| !value.trim().is_empty())
|
||||||
|
.map(ToOwned::to_owned)
|
||||||
|
.unwrap_or_else(|| title_from_name(&name));
|
||||||
|
let description = operation
|
||||||
|
.description
|
||||||
|
.as_deref()
|
||||||
|
.or(operation.summary.as_deref())
|
||||||
|
.filter(|value| !value.trim().is_empty())
|
||||||
|
.map(ToOwned::to_owned)
|
||||||
|
.unwrap_or_else(|| format!("Выполняет {method_name} {}", operation.path));
|
||||||
|
let category = operation
|
||||||
|
.tags
|
||||||
|
.first()
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_else(|| "imported".to_owned());
|
||||||
|
let server_urls = if operation.servers.is_empty() {
|
||||||
|
document_servers.to_vec()
|
||||||
|
} else {
|
||||||
|
operation.servers.clone()
|
||||||
|
};
|
||||||
|
let base_url = server_urls.first().cloned().unwrap_or_default();
|
||||||
|
let mut input_fields = BTreeMap::new();
|
||||||
|
let mut used_input_field_names = BTreeSet::new();
|
||||||
|
for parameter in &operation.parameters {
|
||||||
|
used_input_field_names.insert(parameter.name.clone());
|
||||||
|
input_fields.insert(
|
||||||
|
parameter.name.clone(),
|
||||||
|
schema_from_openapi(
|
||||||
|
parameter.schema.as_ref(),
|
||||||
|
parameter.required || parameter.location == RestParameterLocation::Path,
|
||||||
|
parameter.description.clone(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let body_fields = body_input_fields(
|
||||||
|
operation.request_body_schema.as_ref(),
|
||||||
|
&mut used_input_field_names,
|
||||||
|
&mut input_fields,
|
||||||
|
);
|
||||||
|
let input_schema = object_with_fields(
|
||||||
|
Some("Входные параметры MCP-инструмента".to_owned()),
|
||||||
|
input_fields,
|
||||||
|
);
|
||||||
|
let output_schema = operation
|
||||||
|
.response_schema
|
||||||
|
.as_ref()
|
||||||
|
.map(|schema| schema_from_openapi(Some(schema), true, Some("Ответ API".to_owned())))
|
||||||
|
.unwrap_or_else(|| any_object(Some("Ответ API".to_owned())));
|
||||||
|
let input_mapping = input_mapping(&operation.parameters, &body_fields);
|
||||||
|
let output_mapping = output_mapping(&output_schema);
|
||||||
|
let mut findings = operation_recommendations(operation);
|
||||||
|
findings.extend(candidate_recommendations(
|
||||||
|
operation,
|
||||||
|
&name,
|
||||||
|
&description,
|
||||||
|
&input_schema,
|
||||||
|
&output_schema,
|
||||||
|
));
|
||||||
|
|
||||||
|
let draft = RestImportCandidate {
|
||||||
|
name: name.clone(),
|
||||||
|
display_name: display_name.clone(),
|
||||||
|
category: category.clone(),
|
||||||
|
target: RestTarget {
|
||||||
|
base_url,
|
||||||
|
method: operation.method,
|
||||||
|
path_template: operation.path.clone(),
|
||||||
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
|
},
|
||||||
|
input_schema: input_schema.clone(),
|
||||||
|
output_schema: output_schema.clone(),
|
||||||
|
input_mapping,
|
||||||
|
output_mapping,
|
||||||
|
tool_description: ToolDescription {
|
||||||
|
title: display_name.clone(),
|
||||||
|
description: description.clone(),
|
||||||
|
tags: operation.tags.clone(),
|
||||||
|
examples: vec![ToolExample { input: json!({}) }],
|
||||||
|
},
|
||||||
|
wizard_state: Some(WizardState {
|
||||||
|
input_sample: None,
|
||||||
|
output_sample: None,
|
||||||
|
test_input: None,
|
||||||
|
import_findings: Vec::new(),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
ImportOperationCandidate {
|
||||||
|
key: operation.key.clone(),
|
||||||
|
method: operation.method,
|
||||||
|
path: operation.path.clone(),
|
||||||
|
security_requirements: Default::default(),
|
||||||
|
security_schemes: Default::default(),
|
||||||
|
operation_id: operation.operation_id.clone(),
|
||||||
|
suggested_name: name,
|
||||||
|
suggested_display_name: display_name,
|
||||||
|
description,
|
||||||
|
category,
|
||||||
|
input_fields: field_count(&input_schema),
|
||||||
|
output_fields: field_count(&output_schema),
|
||||||
|
server_urls,
|
||||||
|
findings,
|
||||||
|
draft,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn body_input_fields(
|
||||||
|
request_body_schema: Option<&serde_json::Value>,
|
||||||
|
used_names: &mut BTreeSet<String>,
|
||||||
|
input_fields: &mut BTreeMap<String, crank_schema::Schema>,
|
||||||
|
) -> Vec<BodyFieldMapping> {
|
||||||
|
let Some(request_body_schema) = request_body_schema else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let body_schema = schema_from_openapi(
|
||||||
|
Some(request_body_schema),
|
||||||
|
true,
|
||||||
|
Some("Тело запроса".to_owned()),
|
||||||
|
);
|
||||||
|
if body_schema.kind != crank_schema::SchemaKind::Object || body_schema.fields.is_empty() {
|
||||||
|
let input_name = unique_body_input_name("body", used_names);
|
||||||
|
input_fields.insert(input_name.clone(), body_schema);
|
||||||
|
return vec![BodyFieldMapping {
|
||||||
|
input_name,
|
||||||
|
body_path: String::new(),
|
||||||
|
required: true,
|
||||||
|
}];
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut mappings = Vec::new();
|
||||||
|
for (field_name, field_schema) in body_schema.fields {
|
||||||
|
let input_name = unique_body_input_name(&field_name, used_names);
|
||||||
|
mappings.push(BodyFieldMapping {
|
||||||
|
input_name: input_name.clone(),
|
||||||
|
body_path: field_name,
|
||||||
|
required: field_schema.required,
|
||||||
|
});
|
||||||
|
input_fields.insert(input_name, field_schema);
|
||||||
|
}
|
||||||
|
mappings
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unique_body_input_name(name: &str, used_names: &mut BTreeSet<String>) -> String {
|
||||||
|
if used_names.insert(name.to_owned()) {
|
||||||
|
return name.to_owned();
|
||||||
|
}
|
||||||
|
let prefixed = format!("body_{name}");
|
||||||
|
if used_names.insert(prefixed.clone()) {
|
||||||
|
return prefixed;
|
||||||
|
}
|
||||||
|
for index in 2.. {
|
||||||
|
let candidate = format!("body_{name}_{index}");
|
||||||
|
if used_names.insert(candidate.clone()) {
|
||||||
|
return candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
unreachable!()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn method_as_str(method: HttpMethod) -> &'static str {
|
||||||
|
match method {
|
||||||
|
HttpMethod::Get => "GET",
|
||||||
|
HttpMethod::Head => "HEAD",
|
||||||
|
HttpMethod::Options => "OPTIONS",
|
||||||
|
HttpMethod::Post => "POST",
|
||||||
|
HttpMethod::Put => "PUT",
|
||||||
|
HttpMethod::Patch => "PATCH",
|
||||||
|
HttpMethod::Delete => "DELETE",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
fn safety_for_method(method: HttpMethod) -> OperationSafetyPolicy {
|
||||||
|
let class = match method {
|
||||||
|
HttpMethod::Get | HttpMethod::Head | HttpMethod::Options => OperationSafetyClass::Read,
|
||||||
|
HttpMethod::Post | HttpMethod::Put | HttpMethod::Patch => OperationSafetyClass::Write,
|
||||||
|
HttpMethod::Delete => OperationSafetyClass::Destructive,
|
||||||
|
};
|
||||||
|
OperationSafetyPolicy {
|
||||||
|
class,
|
||||||
|
confirmation: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
fn default_execution_config() -> ExecutionConfig {
|
||||||
|
ExecutionConfig {
|
||||||
|
timeout_ms: 10_000,
|
||||||
|
retry_policy: None,
|
||||||
|
response_cache: None,
|
||||||
|
idempotency: None,
|
||||||
|
safety: None,
|
||||||
|
approval_policy: None,
|
||||||
|
auth_profile_ref: None,
|
||||||
|
headers: BTreeMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
fn _protocol() -> Protocol {
|
||||||
|
Protocol::Rest
|
||||||
|
}
|
||||||
@@ -0,0 +1,238 @@
|
|||||||
|
// Frozen pre-v4 projection for historical legacy-v1 jobs.
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use crank_schema::{Schema, SchemaKind};
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
pub fn any_object(description: Option<String>) -> Schema {
|
||||||
|
Schema {
|
||||||
|
format: None,
|
||||||
|
kind: SchemaKind::Object,
|
||||||
|
description,
|
||||||
|
required: true,
|
||||||
|
nullable: false,
|
||||||
|
default_value: None,
|
||||||
|
fields: BTreeMap::new(),
|
||||||
|
items: None,
|
||||||
|
enum_values: Vec::new(),
|
||||||
|
variants: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn field_count(schema: &Schema) -> usize {
|
||||||
|
match schema.kind {
|
||||||
|
SchemaKind::Object => schema.fields.len(),
|
||||||
|
_ => 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn schema_from_openapi(
|
||||||
|
value: Option<&Value>,
|
||||||
|
required: bool,
|
||||||
|
description: Option<String>,
|
||||||
|
) -> Schema {
|
||||||
|
let Some(value) = value else {
|
||||||
|
return primitive(SchemaKind::String, required, description);
|
||||||
|
};
|
||||||
|
// Only v3 NormalizedIR emits the private marker. Pending legacy-v1 jobs
|
||||||
|
// retain their historical first-branch behavior, while modern oneOf/anyOf
|
||||||
|
// is projected losslessly through crank-schema's existing Oneof shape.
|
||||||
|
if value
|
||||||
|
.get("x-crank-lossless-composition")
|
||||||
|
.and_then(Value::as_bool)
|
||||||
|
== Some(true)
|
||||||
|
&& let Some(items) = value
|
||||||
|
.get("oneOf")
|
||||||
|
.or_else(|| value.get("anyOf"))
|
||||||
|
.and_then(Value::as_array)
|
||||||
|
{
|
||||||
|
return Schema {
|
||||||
|
format: None,
|
||||||
|
kind: SchemaKind::Oneof,
|
||||||
|
description: description.or_else(|| text(value, "description")),
|
||||||
|
required,
|
||||||
|
nullable: nullable(value),
|
||||||
|
default_value: value.get("default").cloned(),
|
||||||
|
fields: BTreeMap::new(),
|
||||||
|
items: None,
|
||||||
|
enum_values: Vec::new(),
|
||||||
|
variants: items
|
||||||
|
.iter()
|
||||||
|
.map(|item| schema_from_openapi(Some(item), true, None))
|
||||||
|
.collect(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
let resolved = collapse_composition(value);
|
||||||
|
|
||||||
|
if let Some(values) = resolved.get("enum").and_then(Value::as_array) {
|
||||||
|
let enum_values = values
|
||||||
|
.iter()
|
||||||
|
.filter_map(Value::as_str)
|
||||||
|
.map(ToOwned::to_owned)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
if !enum_values.is_empty() {
|
||||||
|
return Schema {
|
||||||
|
format: None,
|
||||||
|
kind: SchemaKind::Enum,
|
||||||
|
description: description.or_else(|| text(&resolved, "description")),
|
||||||
|
required,
|
||||||
|
nullable: nullable(&resolved),
|
||||||
|
default_value: resolved.get("default").cloned(),
|
||||||
|
fields: BTreeMap::new(),
|
||||||
|
items: None,
|
||||||
|
enum_values,
|
||||||
|
variants: Vec::new(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
match type_name(&resolved).unwrap_or("object") {
|
||||||
|
"object" => object_schema(&resolved, required, description),
|
||||||
|
"array" => Schema {
|
||||||
|
format: None,
|
||||||
|
kind: SchemaKind::Array,
|
||||||
|
description: description.or_else(|| text(&resolved, "description")),
|
||||||
|
required,
|
||||||
|
nullable: nullable(&resolved),
|
||||||
|
default_value: resolved.get("default").cloned(),
|
||||||
|
fields: BTreeMap::new(),
|
||||||
|
items: Some(Box::new(schema_from_openapi(
|
||||||
|
resolved.get("items"),
|
||||||
|
true,
|
||||||
|
None,
|
||||||
|
))),
|
||||||
|
enum_values: Vec::new(),
|
||||||
|
variants: Vec::new(),
|
||||||
|
},
|
||||||
|
"integer" => primitive(
|
||||||
|
SchemaKind::Integer,
|
||||||
|
required,
|
||||||
|
description.or_else(|| text(&resolved, "description")),
|
||||||
|
),
|
||||||
|
"number" => primitive(
|
||||||
|
SchemaKind::Number,
|
||||||
|
required,
|
||||||
|
description.or_else(|| text(&resolved, "description")),
|
||||||
|
),
|
||||||
|
"boolean" => primitive(
|
||||||
|
SchemaKind::Boolean,
|
||||||
|
required,
|
||||||
|
description.or_else(|| text(&resolved, "description")),
|
||||||
|
),
|
||||||
|
"null" => primitive(
|
||||||
|
SchemaKind::Null,
|
||||||
|
required,
|
||||||
|
description.or_else(|| text(&resolved, "description")),
|
||||||
|
),
|
||||||
|
_ => primitive(
|
||||||
|
SchemaKind::String,
|
||||||
|
required,
|
||||||
|
description.or_else(|| text(&resolved, "description")),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn collapse_composition(value: &Value) -> Value {
|
||||||
|
for key in ["allOf", "oneOf", "anyOf"] {
|
||||||
|
if let Some(items) = value.get(key).and_then(Value::as_array)
|
||||||
|
&& let Some(first) = items.first()
|
||||||
|
{
|
||||||
|
return first.clone();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
value.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn object_with_fields(description: Option<String>, fields: BTreeMap<String, Schema>) -> Schema {
|
||||||
|
Schema {
|
||||||
|
format: None,
|
||||||
|
kind: SchemaKind::Object,
|
||||||
|
description,
|
||||||
|
required: true,
|
||||||
|
nullable: false,
|
||||||
|
default_value: None,
|
||||||
|
fields,
|
||||||
|
items: None,
|
||||||
|
enum_values: Vec::new(),
|
||||||
|
variants: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn object_schema(value: &Value, required: bool, description: Option<String>) -> Schema {
|
||||||
|
let required_fields = value
|
||||||
|
.get("required")
|
||||||
|
.and_then(Value::as_array)
|
||||||
|
.map(|items| {
|
||||||
|
items
|
||||||
|
.iter()
|
||||||
|
.filter_map(Value::as_str)
|
||||||
|
.collect::<std::collections::BTreeSet<_>>()
|
||||||
|
})
|
||||||
|
.unwrap_or_default();
|
||||||
|
let mut fields = BTreeMap::new();
|
||||||
|
|
||||||
|
if let Some(properties) = value.get("properties").and_then(Value::as_object) {
|
||||||
|
for (name, schema) in properties {
|
||||||
|
fields.insert(
|
||||||
|
name.clone(),
|
||||||
|
schema_from_openapi(
|
||||||
|
Some(schema),
|
||||||
|
required_fields.contains(name.as_str()),
|
||||||
|
text(schema, "description"),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Schema {
|
||||||
|
format: None,
|
||||||
|
kind: SchemaKind::Object,
|
||||||
|
description: description.or_else(|| text(value, "description")),
|
||||||
|
required,
|
||||||
|
nullable: nullable(value),
|
||||||
|
default_value: value.get("default").cloned(),
|
||||||
|
fields,
|
||||||
|
items: None,
|
||||||
|
enum_values: Vec::new(),
|
||||||
|
variants: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn primitive(kind: SchemaKind, required: bool, description: Option<String>) -> Schema {
|
||||||
|
Schema {
|
||||||
|
format: None,
|
||||||
|
kind,
|
||||||
|
description,
|
||||||
|
required,
|
||||||
|
nullable: false,
|
||||||
|
default_value: None,
|
||||||
|
fields: BTreeMap::new(),
|
||||||
|
items: None,
|
||||||
|
enum_values: Vec::new(),
|
||||||
|
variants: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn type_name(value: &Value) -> Option<&str> {
|
||||||
|
match value.get("type") {
|
||||||
|
Some(Value::String(value)) => Some(value.as_str()),
|
||||||
|
Some(Value::Array(values)) => values.iter().find_map(Value::as_str),
|
||||||
|
_ if value.get("properties").is_some() => Some("object"),
|
||||||
|
_ if value.get("items").is_some() => Some("array"),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn nullable(value: &Value) -> bool {
|
||||||
|
value
|
||||||
|
.get("nullable")
|
||||||
|
.and_then(Value::as_bool)
|
||||||
|
.unwrap_or(false)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn text(value: &Value, key: &str) -> Option<String> {
|
||||||
|
value
|
||||||
|
.get(key)
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.map(ToOwned::to_owned)
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
use crank_mapping::{MappingRule, MappingSet};
|
use crank_mapping::{MappingRule, MappingSet};
|
||||||
use crank_schema::{Schema, SchemaKind};
|
use crank_schema::{Schema, SchemaKind};
|
||||||
|
|
||||||
use crate::rest::model::{RestImportParameter, RestParameterLocation};
|
use crate::rest::model::RestParameterLocation;
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub struct BodyFieldMapping {
|
pub struct BodyFieldMapping {
|
||||||
@@ -10,8 +10,17 @@ pub struct BodyFieldMapping {
|
|||||||
pub required: bool,
|
pub required: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct ParameterFieldMapping {
|
||||||
|
pub input_name: String,
|
||||||
|
pub wire_name: String,
|
||||||
|
pub location: RestParameterLocation,
|
||||||
|
pub required: bool,
|
||||||
|
pub default_value: Option<serde_json::Value>,
|
||||||
|
}
|
||||||
|
|
||||||
pub fn input_mapping(
|
pub fn input_mapping(
|
||||||
parameters: &[RestImportParameter],
|
parameters: &[ParameterFieldMapping],
|
||||||
body_fields: &[BodyFieldMapping],
|
body_fields: &[BodyFieldMapping],
|
||||||
) -> MappingSet {
|
) -> MappingSet {
|
||||||
let mut rules = Vec::new();
|
let mut rules = Vec::new();
|
||||||
@@ -20,19 +29,25 @@ pub fn input_mapping(
|
|||||||
RestParameterLocation::Path => "$.request.path",
|
RestParameterLocation::Path => "$.request.path",
|
||||||
RestParameterLocation::Query => "$.request.query",
|
RestParameterLocation::Query => "$.request.query",
|
||||||
RestParameterLocation::Header => "$.request.headers",
|
RestParameterLocation::Header => "$.request.headers",
|
||||||
|
// Cookies travel through a distinct mapping root. Runtime turns
|
||||||
|
// this object into the single wire `Cookie` header at the adapter
|
||||||
|
// boundary; source values cannot inject an arbitrary header.
|
||||||
|
RestParameterLocation::Cookie => "$.request.cookies",
|
||||||
};
|
};
|
||||||
rules.push(MappingRule {
|
rules.push(MappingRule {
|
||||||
source: format!("$.mcp.{}", parameter.name),
|
source: format!("$.mcp.{}", parameter.input_name),
|
||||||
target: format!("{target_root}.{}", parameter.name),
|
target: format!("{target_root}.{}", parameter.wire_name),
|
||||||
required: parameter.required,
|
required: parameter.required,
|
||||||
default_value: None,
|
default_value: parameter.default_value.clone(),
|
||||||
transform: None,
|
transform: None,
|
||||||
condition: None,
|
condition: None,
|
||||||
notes: None,
|
notes: None,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
for field in body_fields {
|
for field in body_fields {
|
||||||
let target = if field.body_path.is_empty() {
|
let target = if field.body_path == "__content_type" {
|
||||||
|
"$.request.body_content_type".to_owned()
|
||||||
|
} else if field.body_path.is_empty() || field.body_path == "__body" {
|
||||||
"$.request.body".to_owned()
|
"$.request.body".to_owned()
|
||||||
} else {
|
} else {
|
||||||
format!("$.request.body.{}", field.body_path)
|
format!("$.request.body.{}", field.body_path)
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
use crate::rest::{
|
||||||
|
model::{ImportFinding, SourceLocation},
|
||||||
|
recommendations::document_finding,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub(super) fn collect_secret_like_examples(
|
||||||
|
value: &Value,
|
||||||
|
pointer: &str,
|
||||||
|
inside_example: bool,
|
||||||
|
findings: &mut Vec<ImportFinding>,
|
||||||
|
locations: &mut Vec<Option<SourceLocation>>,
|
||||||
|
) {
|
||||||
|
match value {
|
||||||
|
Value::Object(fields) => {
|
||||||
|
for (key, child) in fields {
|
||||||
|
let child_pointer = format!(
|
||||||
|
"{pointer}/{}",
|
||||||
|
super::normalize_coverage::escape_pointer(key)
|
||||||
|
);
|
||||||
|
collect_secret_like_examples(
|
||||||
|
child,
|
||||||
|
&child_pointer,
|
||||||
|
inside_example || matches!(key.as_str(), "example" | "examples"),
|
||||||
|
findings,
|
||||||
|
locations,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Value::Array(items) => {
|
||||||
|
for (index, child) in items.iter().enumerate() {
|
||||||
|
collect_secret_like_examples(
|
||||||
|
child,
|
||||||
|
&format!("{pointer}/{index}"),
|
||||||
|
inside_example,
|
||||||
|
findings,
|
||||||
|
locations,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Value::String(value) if inside_example && looks_secret_like(pointer, value) => {
|
||||||
|
findings.push(document_finding(
|
||||||
|
"secret_like_example",
|
||||||
|
"Example содержит значение, похожее на секрет, и не включается в executable contract.",
|
||||||
|
));
|
||||||
|
locations.push(Some(SourceLocation {
|
||||||
|
pointer: pointer.to_owned(),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn looks_secret_like(pointer: &str, value: &str) -> bool {
|
||||||
|
let pointer = pointer.to_ascii_lowercase();
|
||||||
|
let value = value.to_ascii_lowercase();
|
||||||
|
[
|
||||||
|
"token",
|
||||||
|
"secret",
|
||||||
|
"password",
|
||||||
|
"api_key",
|
||||||
|
"apikey",
|
||||||
|
"authorization",
|
||||||
|
]
|
||||||
|
.iter()
|
||||||
|
.any(|marker| pointer.contains(marker) || value.contains(marker))
|
||||||
|
|| value.starts_with("bearer ")
|
||||||
|
|| value.starts_with("sk-")
|
||||||
|
}
|
||||||
@@ -1,25 +1,43 @@
|
|||||||
|
mod http_methods;
|
||||||
|
mod legacy_mapping;
|
||||||
|
mod legacy_payload;
|
||||||
|
mod legacy_schema;
|
||||||
mod mapping;
|
mod mapping;
|
||||||
pub mod model;
|
pub mod model;
|
||||||
mod naming;
|
mod naming;
|
||||||
mod normalize;
|
mod normalize;
|
||||||
mod normalize_coverage;
|
mod normalize_coverage;
|
||||||
|
mod normalize_finding_validation;
|
||||||
mod normalize_limits;
|
mod normalize_limits;
|
||||||
|
mod normalize_preview;
|
||||||
|
mod normalize_projection;
|
||||||
mod normalize_schema;
|
mod normalize_schema;
|
||||||
mod openapi3;
|
mod openapi3;
|
||||||
|
mod openapi3_findings;
|
||||||
|
mod openapi3_legacy;
|
||||||
mod payload;
|
mod payload;
|
||||||
mod recommendations;
|
mod recommendations;
|
||||||
mod reference;
|
mod reference;
|
||||||
mod schema;
|
mod schema;
|
||||||
|
mod security;
|
||||||
|
mod security_literals;
|
||||||
mod swagger2;
|
mod swagger2;
|
||||||
|
mod swagger2_findings;
|
||||||
|
mod swagger2_legacy;
|
||||||
|
|
||||||
pub use model::{
|
pub use model::{
|
||||||
ExternalDocumentSnapshot, ImportFinding, ImportFindingSeverity, ImportGroupPreview,
|
ExternalDocumentSnapshot, HISTORICAL_NORMALIZER_VERSION, HISTORICAL_PROJECTION_VERSION,
|
||||||
ImportOperationCandidate, ImportPreview, ImportSourcePreview, NORMALIZER_VERSION,
|
ImportFinding, ImportFindingSeverity, ImportGroupPreview, ImportOperationCandidate,
|
||||||
NormalizationConfig, NormalizedFinding, NormalizedIr, NormalizedOperation, NormalizedParameter,
|
ImportPreview, ImportSourcePreview, NORMALIZER_VERSION, NormalizationConfig, NormalizedFinding,
|
||||||
NormalizedReference, NormalizedSchema, NormalizedSchemaConstraints, NormalizedSchemaKind,
|
NormalizedIr, NormalizedOperation, NormalizedParameter, NormalizedReference,
|
||||||
PROJECTION_VERSION, ResolvedReferenceEdge, ResolvedReferenceGraph, ResolvedReferenceNode,
|
NormalizedRequestBodyVariant, NormalizedResponseVariant, NormalizedSchema,
|
||||||
RestImportCandidate, RestImportDocument, RestImportOperation, RestImportParameter,
|
NormalizedSchemaConstraints, NormalizedSchemaKind, NormalizedSecurityRequirements,
|
||||||
RestParameterLocation, SourceDigest, SourceIdentity, SourceLocation, UnresolvedReference,
|
NormalizedSecurityScheme, NormalizedSecuritySchemeKind, PROJECTION_VERSION,
|
||||||
|
ResolvedReferenceEdge, ResolvedReferenceGraph, ResolvedReferenceNode, RestImportCandidate,
|
||||||
|
RestImportDocument, RestImportOperation, RestImportParameter, RestParameterLocation,
|
||||||
|
RestRequestBodyVariant, RestResponseVariant, SecurityParameterLocation,
|
||||||
|
SecurityRequirementAlternative, SecurityRequirementsSource, SourceDigest, SourceIdentity,
|
||||||
|
SourceLocation, UnresolvedReference,
|
||||||
};
|
};
|
||||||
pub use normalize::{
|
pub use normalize::{
|
||||||
ImportParseError, external_reference_uris, normalize_verified_bundle,
|
ImportParseError, external_reference_uris, normalize_verified_bundle,
|
||||||
@@ -27,3 +45,4 @@ pub use normalize::{
|
|||||||
reference_uris, validate_normalized_ir,
|
reference_uris, validate_normalized_ir,
|
||||||
};
|
};
|
||||||
pub use payload::operation_draft_from_candidate;
|
pub use payload::operation_draft_from_candidate;
|
||||||
|
pub use security_literals::{SecretLiteralFinding, scan_secret_literals};
|
||||||
@@ -9,8 +9,10 @@ use serde_json::Value;
|
|||||||
/// The immutable contract used to normalize an OpenAPI source. These names
|
/// The immutable contract used to normalize an OpenAPI source. These names
|
||||||
/// deliberately travel with an import job: changing either contract must not
|
/// deliberately travel with an import job: changing either contract must not
|
||||||
/// silently reinterpret a pending preview.
|
/// silently reinterpret a pending preview.
|
||||||
pub const NORMALIZER_VERSION: &str = "normalized-ir-v3";
|
pub const NORMALIZER_VERSION: &str = "normalized-ir-v5";
|
||||||
pub const PROJECTION_VERSION: &str = "preview-v3";
|
pub const PROJECTION_VERSION: &str = "preview-v5";
|
||||||
|
pub const HISTORICAL_NORMALIZER_VERSION: &str = "normalized-ir-v4";
|
||||||
|
pub const HISTORICAL_PROJECTION_VERSION: &str = "preview-v4";
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
|
||||||
pub struct SourceDigest(String);
|
pub struct SourceDigest(String);
|
||||||
@@ -232,6 +234,13 @@ pub struct NormalizedOperation {
|
|||||||
pub key: String,
|
pub key: String,
|
||||||
pub method: HttpMethod,
|
pub method: HttpMethod,
|
||||||
pub path: String,
|
pub path: String,
|
||||||
|
#[serde(
|
||||||
|
default,
|
||||||
|
skip_serializing_if = "NormalizedSecurityRequirements::is_empty"
|
||||||
|
)]
|
||||||
|
pub security_requirements: NormalizedSecurityRequirements,
|
||||||
|
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||||
|
pub security_schemes: BTreeMap<String, NormalizedSecurityScheme>,
|
||||||
pub operation_id: Option<String>,
|
pub operation_id: Option<String>,
|
||||||
pub summary: Option<String>,
|
pub summary: Option<String>,
|
||||||
pub description: Option<String>,
|
pub description: Option<String>,
|
||||||
@@ -242,11 +251,110 @@ pub struct NormalizedOperation {
|
|||||||
pub request_body_schema: Option<NormalizedSchema>,
|
pub request_body_schema: Option<NormalizedSchema>,
|
||||||
pub response_schema: Option<NormalizedSchema>,
|
pub response_schema: Option<NormalizedSchema>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
|
pub request_body_variants: Vec<NormalizedRequestBodyVariant>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub response_variants: Vec<NormalizedResponseVariant>,
|
||||||
|
#[serde(default)]
|
||||||
pub servers: Vec<String>,
|
pub servers: Vec<String>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub findings: Vec<NormalizedFinding>,
|
pub findings: Vec<NormalizedFinding>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A supported OpenAPI/Swagger authentication scheme, without credential values.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct NormalizedSecurityScheme {
|
||||||
|
pub name: String,
|
||||||
|
pub kind: NormalizedSecuritySchemeKind,
|
||||||
|
pub source_location: SourceLocation,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case", tag = "kind")]
|
||||||
|
pub enum NormalizedSecuritySchemeKind {
|
||||||
|
Http {
|
||||||
|
scheme: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
format_hint: Option<String>,
|
||||||
|
},
|
||||||
|
ApiKey {
|
||||||
|
location: SecurityParameterLocation,
|
||||||
|
parameter_name: String,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
format_hint: Option<String>,
|
||||||
|
},
|
||||||
|
Unsupported {
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
scheme_type: Option<String>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum SecurityParameterLocation {
|
||||||
|
Header,
|
||||||
|
Query,
|
||||||
|
Cookie,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||||
|
pub struct NormalizedSecurityRequirements {
|
||||||
|
pub source: SecurityRequirementsSource,
|
||||||
|
/// Each item is one OR alternative; names within an alternative are ANDed.
|
||||||
|
#[serde(default)]
|
||||||
|
pub alternatives: Vec<SecurityRequirementAlternative>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NormalizedSecurityRequirements {
|
||||||
|
fn is_empty(&self) -> bool {
|
||||||
|
self.source == SecurityRequirementsSource::None && self.alternatives.is_empty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum SecurityRequirementsSource {
|
||||||
|
#[default]
|
||||||
|
None,
|
||||||
|
Document,
|
||||||
|
Operation,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||||
|
pub struct SecurityRequirementAlternative {
|
||||||
|
#[serde(default)]
|
||||||
|
pub schemes: Vec<String>,
|
||||||
|
#[serde(default = "default_supported_security_alternative")]
|
||||||
|
pub supported: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub findings: Vec<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub source_location: Option<SourceLocation>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_supported_security_alternative() -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct NormalizedRequestBodyVariant {
|
||||||
|
pub content_type: String,
|
||||||
|
pub required: bool,
|
||||||
|
pub schema: Option<NormalizedSchema>,
|
||||||
|
/// MIME types allowed for individual multipart fields, keyed by source
|
||||||
|
/// property name. Empty when the source does not constrain a field.
|
||||||
|
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||||
|
pub multipart_field_mime_types: BTreeMap<String, Vec<String>>,
|
||||||
|
pub source_location: SourceLocation,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct NormalizedResponseVariant {
|
||||||
|
pub status_code: u16,
|
||||||
|
pub content_type: Option<String>,
|
||||||
|
pub schema: Option<NormalizedSchema>,
|
||||||
|
pub source_location: SourceLocation,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
pub struct NormalizedParameter {
|
pub struct NormalizedParameter {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
@@ -306,9 +414,13 @@ pub enum NormalizedSchemaKind {
|
|||||||
Object {
|
Object {
|
||||||
properties: BTreeMap<String, NormalizedSchema>,
|
properties: BTreeMap<String, NormalizedSchema>,
|
||||||
required: Vec<String>,
|
required: Vec<String>,
|
||||||
|
nullable: bool,
|
||||||
|
default_value: Option<NormalizedLiteral>,
|
||||||
},
|
},
|
||||||
Array {
|
Array {
|
||||||
items: Option<Box<NormalizedSchema>>,
|
items: Option<Box<NormalizedSchema>>,
|
||||||
|
nullable: bool,
|
||||||
|
default_value: Option<NormalizedLiteral>,
|
||||||
},
|
},
|
||||||
Reference {
|
Reference {
|
||||||
reference: UnresolvedReference,
|
reference: UnresolvedReference,
|
||||||
@@ -359,6 +471,8 @@ pub struct NormalizedIr {
|
|||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub reference_graph: ResolvedReferenceGraph,
|
pub reference_graph: ResolvedReferenceGraph,
|
||||||
pub source: ImportSourcePreview,
|
pub source: ImportSourcePreview,
|
||||||
|
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||||
|
pub security_schemes: BTreeMap<String, NormalizedSecurityScheme>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub operations: Vec<NormalizedOperation>,
|
pub operations: Vec<NormalizedOperation>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
@@ -414,6 +528,13 @@ pub struct ImportOperationCandidate {
|
|||||||
pub key: String,
|
pub key: String,
|
||||||
pub method: HttpMethod,
|
pub method: HttpMethod,
|
||||||
pub path: String,
|
pub path: String,
|
||||||
|
#[serde(
|
||||||
|
default,
|
||||||
|
skip_serializing_if = "NormalizedSecurityRequirements::is_empty"
|
||||||
|
)]
|
||||||
|
pub security_requirements: NormalizedSecurityRequirements,
|
||||||
|
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||||
|
pub security_schemes: BTreeMap<String, NormalizedSecurityScheme>,
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
pub operation_id: Option<String>,
|
pub operation_id: Option<String>,
|
||||||
pub suggested_name: String,
|
pub suggested_name: String,
|
||||||
@@ -449,6 +570,8 @@ pub struct RestImportDocument {
|
|||||||
pub version: Option<String>,
|
pub version: Option<String>,
|
||||||
pub title: String,
|
pub title: String,
|
||||||
pub servers: Vec<String>,
|
pub servers: Vec<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||||
|
pub security_schemes: BTreeMap<String, NormalizedSecurityScheme>,
|
||||||
pub operations: Vec<RestImportOperation>,
|
pub operations: Vec<RestImportOperation>,
|
||||||
pub findings: Vec<ImportFinding>,
|
pub findings: Vec<ImportFinding>,
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
@@ -460,6 +583,11 @@ pub struct RestImportOperation {
|
|||||||
pub key: String,
|
pub key: String,
|
||||||
pub method: HttpMethod,
|
pub method: HttpMethod,
|
||||||
pub path: String,
|
pub path: String,
|
||||||
|
#[serde(
|
||||||
|
default,
|
||||||
|
skip_serializing_if = "NormalizedSecurityRequirements::is_empty"
|
||||||
|
)]
|
||||||
|
pub security_requirements: NormalizedSecurityRequirements,
|
||||||
pub operation_id: Option<String>,
|
pub operation_id: Option<String>,
|
||||||
pub summary: Option<String>,
|
pub summary: Option<String>,
|
||||||
pub description: Option<String>,
|
pub description: Option<String>,
|
||||||
@@ -468,11 +596,21 @@ pub struct RestImportOperation {
|
|||||||
pub request_body_schema: Option<Value>,
|
pub request_body_schema: Option<Value>,
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
pub request_body_schema_location: Option<SourceLocation>,
|
pub request_body_schema_location: Option<SourceLocation>,
|
||||||
|
/// Every executable request variant. `request_body_schema` remains for
|
||||||
|
/// legacy replay only; modern projection must use this complete list.
|
||||||
|
#[serde(default)]
|
||||||
|
pub request_body_variants: Vec<RestRequestBodyVariant>,
|
||||||
pub response_schema: Option<Value>,
|
pub response_schema: Option<Value>,
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
pub response_schema_location: Option<SourceLocation>,
|
pub response_schema_location: Option<SourceLocation>,
|
||||||
|
/// All successful response branches, including explicit no-content
|
||||||
|
/// outcomes. The old singular field is retained for legacy-v1 jobs.
|
||||||
|
#[serde(default)]
|
||||||
|
pub response_variants: Vec<RestResponseVariant>,
|
||||||
pub servers: Vec<String>,
|
pub servers: Vec<String>,
|
||||||
pub findings: Vec<ImportFinding>,
|
pub findings: Vec<ImportFinding>,
|
||||||
|
#[serde(skip)]
|
||||||
|
pub internal_finding_locations: Vec<SourceLocation>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
@@ -488,6 +626,37 @@ pub struct RestImportParameter {
|
|||||||
pub schema_source_location: Option<SourceLocation>,
|
pub schema_source_location: Option<SourceLocation>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct RestRequestBodyVariant {
|
||||||
|
pub content_type: String,
|
||||||
|
pub required: bool,
|
||||||
|
pub schema: Option<Value>,
|
||||||
|
/// MIME types from OpenAPI's multipart `encoding.*.contentType`.
|
||||||
|
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||||
|
pub multipart_field_mime_types: BTreeMap<String, Vec<String>>,
|
||||||
|
#[serde(skip, default = "empty_source_location")]
|
||||||
|
pub source_location: SourceLocation,
|
||||||
|
#[serde(skip, default)]
|
||||||
|
pub schema_source_location: Option<SourceLocation>,
|
||||||
|
/// Swagger 2 formData schemas are assembled from independent parameters.
|
||||||
|
/// This keeps each generated property tied to its original parameter.
|
||||||
|
#[serde(skip, default)]
|
||||||
|
pub schema_property_source_locations: BTreeMap<String, SourceLocation>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
pub struct RestResponseVariant {
|
||||||
|
pub status_code: u16,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub content_type: Option<String>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub schema: Option<Value>,
|
||||||
|
#[serde(skip, default = "empty_source_location")]
|
||||||
|
pub source_location: SourceLocation,
|
||||||
|
#[serde(skip, default)]
|
||||||
|
pub schema_source_location: Option<SourceLocation>,
|
||||||
|
}
|
||||||
|
|
||||||
fn empty_source_location() -> SourceLocation {
|
fn empty_source_location() -> SourceLocation {
|
||||||
SourceLocation {
|
SourceLocation {
|
||||||
pointer: String::new(),
|
pointer: String::new(),
|
||||||
@@ -500,4 +669,5 @@ pub enum RestParameterLocation {
|
|||||||
Path,
|
Path,
|
||||||
Query,
|
Query,
|
||||||
Header,
|
Header,
|
||||||
|
Cookie,
|
||||||
}
|
}
|
||||||
@@ -6,16 +6,13 @@ use thiserror::Error;
|
|||||||
use crate::rest::{
|
use crate::rest::{
|
||||||
model::{
|
model::{
|
||||||
CoverageDisposition, CoverageEntry, ExternalDocumentSnapshot, ImportFinding,
|
CoverageDisposition, CoverageEntry, ExternalDocumentSnapshot, ImportFinding,
|
||||||
ImportFindingSeverity, ImportGroupPreview, ImportPreview, ImportSourcePreview,
|
ImportFindingSeverity, ImportPreview, ImportSourcePreview, NORMALIZER_VERSION,
|
||||||
NORMALIZER_VERSION, NormalizationConfig, NormalizedApiMetadata, NormalizedFinding,
|
NormalizationConfig, NormalizedApiMetadata, NormalizedFinding, NormalizedIr,
|
||||||
NormalizedIr, NormalizedLiteral, NormalizedOperation, NormalizedParameter,
|
NormalizedOperation, NormalizedParameter, NormalizedRequestBodyVariant,
|
||||||
NormalizedScalarKind, NormalizedSchema, NormalizedSchemaKind, PROJECTION_VERSION,
|
NormalizedResponseVariant, NormalizedSchema, NormalizedSchemaKind, PROJECTION_VERSION,
|
||||||
RestImportDocument, RestImportOperation, RestImportParameter, SourceDigest, SourceIdentity,
|
RestImportDocument, SourceDigest, SourceIdentity, SourceLocation, SourceSyntax,
|
||||||
SourceLocation, SourceSyntax,
|
|
||||||
},
|
},
|
||||||
openapi3,
|
openapi3, swagger2,
|
||||||
payload::candidate_from_operation,
|
|
||||||
swagger2,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
use super::normalize_coverage;
|
use super::normalize_coverage;
|
||||||
@@ -64,9 +61,9 @@ pub fn external_reference_uris(
|
|||||||
pub fn preview_document_legacy_v1(document: &str) -> Result<ImportPreview, ImportParseError> {
|
pub fn preview_document_legacy_v1(document: &str) -> Result<ImportPreview, ImportParseError> {
|
||||||
let root = decode_legacy_v1(document)?;
|
let root = decode_legacy_v1(document)?;
|
||||||
let mut parsed = match root.get("openapi") {
|
let mut parsed = match root.get("openapi") {
|
||||||
Some(_) => openapi3::parse_document_legacy_v1(&root)?,
|
Some(_) => super::openapi3_legacy::parse_document_legacy_v1(&root)?,
|
||||||
None if root.get("swagger").and_then(Value::as_str) == Some("2.0") => {
|
None if root.get("swagger").and_then(Value::as_str) == Some("2.0") => {
|
||||||
swagger2::parse_document_legacy_v1(&root)?
|
super::swagger2_legacy::parse_document_legacy_v1(&root)?
|
||||||
}
|
}
|
||||||
None => return Err(ImportParseError::UnsupportedDocument),
|
None => return Err(ImportParseError::UnsupportedDocument),
|
||||||
};
|
};
|
||||||
@@ -83,7 +80,7 @@ pub fn preview_document_legacy_v1(document: &str) -> Result<ImportPreview, Impor
|
|||||||
operation.response_schema = Some(resolve_local_ref(&root, &schema, 0));
|
operation.response_schema = Some(resolve_local_ref(&root, &schema, 0));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(preview_from_document(parsed))
|
Ok(super::normalize_preview::preview_from_document(parsed))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn decode_legacy_v1(document: &str) -> Result<Value, ImportParseError> {
|
fn decode_legacy_v1(document: &str) -> Result<Value, ImportParseError> {
|
||||||
@@ -136,10 +133,12 @@ pub fn normalize_verified_bundle(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
let resolution = super::reference::resolve(root, digest.clone(), snapshots, config)?;
|
let resolution = super::reference::resolve(root, digest.clone(), snapshots, config)?;
|
||||||
let root = resolution.root;
|
let mut root = resolution.root;
|
||||||
validate_value_limits(&root, config)?;
|
validate_value_limits(&root, config)?;
|
||||||
|
|
||||||
let parsed = match root.get("openapi").and_then(Value::as_str) {
|
let redacted_literals = super::security_literals::inspect_and_redact(&mut root);
|
||||||
|
|
||||||
|
let mut parsed = match root.get("openapi").and_then(Value::as_str) {
|
||||||
Some(version) if supported_oas_version(version) => openapi3::parse_document(&root)?,
|
Some(version) if supported_oas_version(version) => openapi3::parse_document(&root)?,
|
||||||
Some(_) => return Err(ImportParseError::UnsupportedDocument),
|
Some(_) => return Err(ImportParseError::UnsupportedDocument),
|
||||||
None if root.get("swagger").and_then(Value::as_str) == Some("2.0") => {
|
None if root.get("swagger").and_then(Value::as_str) == Some("2.0") => {
|
||||||
@@ -147,8 +146,22 @@ pub fn normalize_verified_bundle(
|
|||||||
}
|
}
|
||||||
None => return Err(ImportParseError::UnsupportedDocument),
|
None => return Err(ImportParseError::UnsupportedDocument),
|
||||||
};
|
};
|
||||||
|
for literal in redacted_literals {
|
||||||
|
parsed.findings.push(super::recommendations::document_finding(
|
||||||
|
"secret_literal_redacted",
|
||||||
|
"Документ содержит literal credential; значение удалено из normalized representation.",
|
||||||
|
));
|
||||||
|
parsed
|
||||||
|
.internal_finding_locations
|
||||||
|
.push(Some(literal.location));
|
||||||
|
}
|
||||||
|
|
||||||
if parsed.operations.is_empty() {
|
if parsed.operations.is_empty()
|
||||||
|
&& !parsed
|
||||||
|
.findings
|
||||||
|
.iter()
|
||||||
|
.any(|finding| finding.code == "unsupported_http_method")
|
||||||
|
{
|
||||||
return Err(ImportParseError::NoMethods);
|
return Err(ImportParseError::NoMethods);
|
||||||
}
|
}
|
||||||
canonicalize(
|
canonicalize(
|
||||||
@@ -163,70 +176,10 @@ pub fn normalize_verified_bundle(
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn preview_from_ir(ir: &NormalizedIr) -> ImportPreview {
|
pub fn preview_from_ir(ir: &NormalizedIr) -> ImportPreview {
|
||||||
let operations = ir
|
super::normalize_preview::preview_from_ir(ir)
|
||||||
.operations
|
|
||||||
.iter()
|
|
||||||
.map(legacy_operation_from_normalized)
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let findings = ir
|
|
||||||
.findings
|
|
||||||
.iter()
|
|
||||||
.map(|finding| ImportFinding {
|
|
||||||
code: finding.code.clone(),
|
|
||||||
severity: finding.severity.clone(),
|
|
||||||
message: finding.message.clone(),
|
|
||||||
operation_key: finding.operation_key.clone(),
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
preview_from_operations(&ir.source, operations.iter(), findings)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn preview_from_document(document: RestImportDocument) -> ImportPreview {
|
pub(super) fn decode(document: &str) -> Result<Value, ImportParseError> {
|
||||||
let source = ImportSourcePreview {
|
|
||||||
format: document.format,
|
|
||||||
version: document.version,
|
|
||||||
title: document.title,
|
|
||||||
servers: document.servers,
|
|
||||||
};
|
|
||||||
preview_from_operations(&source, document.operations.iter(), document.findings)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn preview_from_operations<'a>(
|
|
||||||
source: &ImportSourcePreview,
|
|
||||||
operations: impl Iterator<Item = &'a crate::rest::model::RestImportOperation>,
|
|
||||||
mut findings: Vec<ImportFinding>,
|
|
||||||
) -> ImportPreview {
|
|
||||||
let mut groups: BTreeMap<String, ImportGroupPreview> = BTreeMap::new();
|
|
||||||
let mut used_names = BTreeSet::new();
|
|
||||||
|
|
||||||
for operation in operations {
|
|
||||||
let candidate = candidate_from_operation(operation, &source.servers, &mut used_names);
|
|
||||||
let group_title = operation
|
|
||||||
.tags
|
|
||||||
.first()
|
|
||||||
.cloned()
|
|
||||||
.unwrap_or_else(|| "Без группы".to_owned());
|
|
||||||
let group_key = crate::rest::naming::snake_name(&group_title);
|
|
||||||
groups
|
|
||||||
.entry(group_key.clone())
|
|
||||||
.or_insert_with(|| ImportGroupPreview {
|
|
||||||
key: group_key,
|
|
||||||
title: group_title,
|
|
||||||
operations: Vec::new(),
|
|
||||||
})
|
|
||||||
.operations
|
|
||||||
.push(candidate);
|
|
||||||
}
|
|
||||||
|
|
||||||
sort_findings(&mut findings);
|
|
||||||
ImportPreview {
|
|
||||||
source: source.clone(),
|
|
||||||
groups: groups.into_values().collect(),
|
|
||||||
findings,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn decode(document: &str) -> Result<Value, ImportParseError> {
|
|
||||||
if let Ok(json) = serde_json::from_str(document) {
|
if let Ok(json) = serde_json::from_str(document) {
|
||||||
return Ok(json);
|
return Ok(json);
|
||||||
}
|
}
|
||||||
@@ -252,6 +205,7 @@ fn canonicalize(
|
|||||||
reference_graph: crate::rest::model::ResolvedReferenceGraph,
|
reference_graph: crate::rest::model::ResolvedReferenceGraph,
|
||||||
resolution_findings: Vec<NormalizedFinding>,
|
resolution_findings: Vec<NormalizedFinding>,
|
||||||
) -> Result<NormalizedIr, ImportParseError> {
|
) -> Result<NormalizedIr, ImportParseError> {
|
||||||
|
let security_schemes = document.security_schemes.clone();
|
||||||
let source = ImportSourcePreview {
|
let source = ImportSourcePreview {
|
||||||
format: document.format,
|
format: document.format,
|
||||||
version: document.version,
|
version: document.version,
|
||||||
@@ -379,14 +333,27 @@ fn canonicalize(
|
|||||||
disposition: CoverageDisposition::Mapped,
|
disposition: CoverageDisposition::Mapped,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
operation_findings.extend(operation.findings.iter().map(|finding| NormalizedFinding {
|
operation_findings.extend(operation.findings.iter().enumerate().map(
|
||||||
|
|(index, finding)| {
|
||||||
|
let finding_location = operation
|
||||||
|
.internal_finding_locations
|
||||||
|
.get(index)
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_else(|| location.clone());
|
||||||
|
NormalizedFinding {
|
||||||
code: finding.code.clone(),
|
code: finding.code.clone(),
|
||||||
severity: finding.severity.clone(),
|
severity: finding.severity.clone(),
|
||||||
message: finding.message.clone(),
|
message: finding.message.clone(),
|
||||||
construct_id: stable_id.clone(),
|
construct_id: if finding_location == location {
|
||||||
location: location.clone(),
|
stable_id.clone()
|
||||||
|
} else {
|
||||||
|
format!("{version}:{}", finding_location.pointer)
|
||||||
|
},
|
||||||
|
location: finding_location,
|
||||||
operation_key: Some(operation.key.clone()),
|
operation_key: Some(operation.key.clone()),
|
||||||
}));
|
}
|
||||||
|
},
|
||||||
|
));
|
||||||
let parameters = operation
|
let parameters = operation
|
||||||
.parameters
|
.parameters
|
||||||
.into_iter()
|
.into_iter()
|
||||||
@@ -465,6 +432,52 @@ fn canonicalize(
|
|||||||
&mut coverage,
|
&mut coverage,
|
||||||
)
|
)
|
||||||
});
|
});
|
||||||
|
let request_body_variants = operation
|
||||||
|
.request_body_variants
|
||||||
|
.iter()
|
||||||
|
.map(|variant| NormalizedRequestBodyVariant {
|
||||||
|
content_type: variant.content_type.clone(),
|
||||||
|
required: variant.required,
|
||||||
|
schema: variant.schema.as_ref().map(|schema| {
|
||||||
|
let schema_location = variant
|
||||||
|
.schema_source_location
|
||||||
|
.as_ref()
|
||||||
|
.unwrap_or(&variant.source_location);
|
||||||
|
normalize_coverage::typed_schema_with_property_locations(
|
||||||
|
schema,
|
||||||
|
&schema_location.pointer,
|
||||||
|
&variant.schema_property_source_locations,
|
||||||
|
&mut coverage,
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
multipart_field_mime_types: variant.multipart_field_mime_types.clone(),
|
||||||
|
source_location: variant.source_location.clone(),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let response_variants = operation
|
||||||
|
.response_variants
|
||||||
|
.iter()
|
||||||
|
.map(|variant| NormalizedResponseVariant {
|
||||||
|
status_code: variant.status_code,
|
||||||
|
content_type: variant.content_type.clone(),
|
||||||
|
schema: variant.schema.as_ref().map(|schema| {
|
||||||
|
let schema_location = variant
|
||||||
|
.schema_source_location
|
||||||
|
.as_ref()
|
||||||
|
.unwrap_or(&variant.source_location);
|
||||||
|
normalize_coverage::typed_schema(
|
||||||
|
schema,
|
||||||
|
&schema_location.pointer,
|
||||||
|
&format!(
|
||||||
|
"{stable_id}:response_variant:{}",
|
||||||
|
normalize_coverage::escape_pointer(&schema_location.pointer)
|
||||||
|
),
|
||||||
|
&mut coverage,
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
source_location: variant.source_location.clone(),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
if normalize_coverage::has_reference_schema(request_body_schema.as_ref())
|
if normalize_coverage::has_reference_schema(request_body_schema.as_ref())
|
||||||
|| normalize_coverage::has_reference_schema(response_schema.as_ref())
|
|| normalize_coverage::has_reference_schema(response_schema.as_ref())
|
||||||
|| parameters.iter().any(|parameter| {
|
|| parameters.iter().any(|parameter| {
|
||||||
@@ -492,6 +505,8 @@ fn canonicalize(
|
|||||||
key: operation.key,
|
key: operation.key,
|
||||||
method: operation.method,
|
method: operation.method,
|
||||||
path: operation.path,
|
path: operation.path,
|
||||||
|
security_requirements: operation.security_requirements,
|
||||||
|
security_schemes: security_schemes.clone(),
|
||||||
operation_id: operation.operation_id,
|
operation_id: operation.operation_id,
|
||||||
summary: operation.summary,
|
summary: operation.summary,
|
||||||
description: operation.description,
|
description: operation.description,
|
||||||
@@ -499,6 +514,8 @@ fn canonicalize(
|
|||||||
parameters,
|
parameters,
|
||||||
request_body_schema,
|
request_body_schema,
|
||||||
response_schema,
|
response_schema,
|
||||||
|
request_body_variants,
|
||||||
|
response_variants,
|
||||||
servers: operation.servers,
|
servers: operation.servers,
|
||||||
findings: operation_findings,
|
findings: operation_findings,
|
||||||
})
|
})
|
||||||
@@ -599,6 +616,18 @@ fn canonicalize(
|
|||||||
.filter_map(|parameter| parameter.schema.as_ref())
|
.filter_map(|parameter| parameter.schema.as_ref())
|
||||||
.chain(operation.request_body_schema.iter())
|
.chain(operation.request_body_schema.iter())
|
||||||
.chain(operation.response_schema.iter())
|
.chain(operation.response_schema.iter())
|
||||||
|
.chain(
|
||||||
|
operation
|
||||||
|
.request_body_variants
|
||||||
|
.iter()
|
||||||
|
.filter_map(|variant| variant.schema.as_ref()),
|
||||||
|
)
|
||||||
|
.chain(
|
||||||
|
operation
|
||||||
|
.response_variants
|
||||||
|
.iter()
|
||||||
|
.filter_map(|variant| variant.schema.as_ref()),
|
||||||
|
)
|
||||||
.any(|schema| schema_contains_reference(schema, &reference.location))
|
.any(|schema| schema_contains_reference(schema, &reference.location))
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -669,6 +698,7 @@ fn canonicalize(
|
|||||||
unresolved_references,
|
unresolved_references,
|
||||||
reference_graph,
|
reference_graph,
|
||||||
source,
|
source,
|
||||||
|
security_schemes: document.security_schemes,
|
||||||
operations,
|
operations,
|
||||||
findings,
|
findings,
|
||||||
coverage,
|
coverage,
|
||||||
@@ -678,7 +708,11 @@ fn canonicalize(
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn validate_normalized_ir(ir: &NormalizedIr) -> Result<(), ImportParseError> {
|
pub fn validate_normalized_ir(ir: &NormalizedIr) -> Result<(), ImportParseError> {
|
||||||
if ir.normalizer_version != NORMALIZER_VERSION || ir.projection_version != PROJECTION_VERSION {
|
let current =
|
||||||
|
ir.normalizer_version == NORMALIZER_VERSION && ir.projection_version == PROJECTION_VERSION;
|
||||||
|
let historical_v4 = ir.normalizer_version == super::model::HISTORICAL_NORMALIZER_VERSION
|
||||||
|
&& ir.projection_version == super::model::HISTORICAL_PROJECTION_VERSION;
|
||||||
|
if !current && !historical_v4 {
|
||||||
return Err(ImportParseError::InvalidDocument);
|
return Err(ImportParseError::InvalidDocument);
|
||||||
}
|
}
|
||||||
validate_reference_graph(ir)?;
|
validate_reference_graph(ir)?;
|
||||||
@@ -738,115 +772,13 @@ fn coverage_disposition_rank(disposition: &CoverageDisposition) -> u8 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn legacy_operation_from_normalized(operation: &NormalizedOperation) -> RestImportOperation {
|
|
||||||
RestImportOperation {
|
|
||||||
key: operation.key.clone(),
|
|
||||||
method: operation.method,
|
|
||||||
path: operation.path.clone(),
|
|
||||||
operation_id: operation.operation_id.clone(),
|
|
||||||
summary: operation.summary.clone(),
|
|
||||||
description: operation.description.clone(),
|
|
||||||
tags: operation.tags.clone(),
|
|
||||||
parameters: operation
|
|
||||||
.parameters
|
|
||||||
.iter()
|
|
||||||
.map(|parameter| RestImportParameter {
|
|
||||||
name: parameter.name.clone(),
|
|
||||||
location: parameter.location,
|
|
||||||
required: parameter.required,
|
|
||||||
description: parameter.description.clone(),
|
|
||||||
schema: parameter.schema.as_ref().map(legacy_schema_value),
|
|
||||||
source_location: parameter.source_location.clone(),
|
|
||||||
schema_source_location: None,
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
request_body_schema: operation
|
|
||||||
.request_body_schema
|
|
||||||
.as_ref()
|
|
||||||
.map(legacy_schema_value),
|
|
||||||
request_body_schema_location: None,
|
|
||||||
response_schema: operation.response_schema.as_ref().map(legacy_schema_value),
|
|
||||||
response_schema_location: None,
|
|
||||||
servers: operation.servers.clone(),
|
|
||||||
findings: operation
|
|
||||||
.findings
|
|
||||||
.iter()
|
|
||||||
.map(|finding| ImportFinding {
|
|
||||||
code: finding.code.clone(),
|
|
||||||
severity: finding.severity.clone(),
|
|
||||||
message: finding.message.clone(),
|
|
||||||
operation_key: finding.operation_key.clone(),
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn legacy_schema_value(schema: &NormalizedSchema) -> Value {
|
|
||||||
let mut value = match &schema.kind {
|
|
||||||
NormalizedSchemaKind::Reference { reference } => serde_json::json!({"$ref": reference.uri}),
|
|
||||||
NormalizedSchemaKind::Composition { operator, variants } => {
|
|
||||||
serde_json::json!({
|
|
||||||
operator: variants.iter().map(legacy_schema_value).collect::<Vec<_>>(),
|
|
||||||
"x-crank-lossless-composition": true,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
NormalizedSchemaKind::Object {
|
|
||||||
properties,
|
|
||||||
required,
|
|
||||||
} => {
|
|
||||||
serde_json::json!({"type":"object", "properties": properties.iter().map(|(name, schema)| (name.clone(), legacy_schema_value(schema))).collect::<serde_json::Map<_, _>>(), "required": required})
|
|
||||||
}
|
|
||||||
NormalizedSchemaKind::Array { items } => {
|
|
||||||
let mut value = serde_json::json!({"type":"array"});
|
|
||||||
if let Some(items) = items {
|
|
||||||
value["items"] = legacy_schema_value(items);
|
|
||||||
}
|
|
||||||
value
|
|
||||||
}
|
|
||||||
NormalizedSchemaKind::Scalar {
|
|
||||||
scalar_type,
|
|
||||||
format,
|
|
||||||
nullable,
|
|
||||||
default_value,
|
|
||||||
enum_values,
|
|
||||||
} => {
|
|
||||||
let scalar_type = match scalar_type {
|
|
||||||
NormalizedScalarKind::String => "string",
|
|
||||||
NormalizedScalarKind::Integer => "integer",
|
|
||||||
NormalizedScalarKind::Number => "number",
|
|
||||||
NormalizedScalarKind::Boolean => "boolean",
|
|
||||||
NormalizedScalarKind::Null => "null",
|
|
||||||
};
|
|
||||||
serde_json::json!({"type":scalar_type, "format":format, "nullable":nullable, "default":default_value.as_ref().map(legacy_literal_value), "enum":enum_values.iter().map(legacy_literal_value).collect::<Vec<_>>()})
|
|
||||||
}
|
|
||||||
NormalizedSchemaKind::Unknown => serde_json::json!({}),
|
|
||||||
};
|
|
||||||
if let Some(description) = &schema.description {
|
|
||||||
value["description"] = Value::String(description.clone());
|
|
||||||
}
|
|
||||||
value
|
|
||||||
}
|
|
||||||
|
|
||||||
fn legacy_literal_value(value: &NormalizedLiteral) -> Value {
|
|
||||||
match value {
|
|
||||||
NormalizedLiteral::String(value) => Value::String(value.clone()),
|
|
||||||
NormalizedLiteral::Integer(value) => Value::Number((*value).into()),
|
|
||||||
NormalizedLiteral::Unsigned(value) => Value::Number((*value).into()),
|
|
||||||
NormalizedLiteral::Number(value) => serde_json::Number::from_f64(*value)
|
|
||||||
.map(Value::Number)
|
|
||||||
.unwrap_or(Value::Null),
|
|
||||||
NormalizedLiteral::Boolean(value) => Value::Bool(*value),
|
|
||||||
NormalizedLiteral::Null => Value::Null,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn schema_contains_reference(schema: &NormalizedSchema, location: &SourceLocation) -> bool {
|
fn schema_contains_reference(schema: &NormalizedSchema, location: &SourceLocation) -> bool {
|
||||||
match &schema.kind {
|
match &schema.kind {
|
||||||
NormalizedSchemaKind::Reference { reference } => reference.location == *location,
|
NormalizedSchemaKind::Reference { reference } => reference.location == *location,
|
||||||
NormalizedSchemaKind::Object { properties, .. } => properties
|
NormalizedSchemaKind::Object { properties, .. } => properties
|
||||||
.values()
|
.values()
|
||||||
.any(|schema| schema_contains_reference(schema, location)),
|
.any(|schema| schema_contains_reference(schema, location)),
|
||||||
NormalizedSchemaKind::Array { items } => items
|
NormalizedSchemaKind::Array { items, .. } => items
|
||||||
.as_deref()
|
.as_deref()
|
||||||
.is_some_and(|schema| schema_contains_reference(schema, location)),
|
.is_some_and(|schema| schema_contains_reference(schema, location)),
|
||||||
NormalizedSchemaKind::Composition { variants, .. } => variants
|
NormalizedSchemaKind::Composition { variants, .. } => variants
|
||||||
@@ -908,6 +840,8 @@ fn method_name(method: crank_core::HttpMethod) -> &'static str {
|
|||||||
crank_core::HttpMethod::Put => "PUT",
|
crank_core::HttpMethod::Put => "PUT",
|
||||||
crank_core::HttpMethod::Patch => "PATCH",
|
crank_core::HttpMethod::Patch => "PATCH",
|
||||||
crank_core::HttpMethod::Delete => "DELETE",
|
crank_core::HttpMethod::Delete => "DELETE",
|
||||||
|
crank_core::HttpMethod::Head => "HEAD",
|
||||||
|
crank_core::HttpMethod::Options => "OPTIONS",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -918,6 +852,8 @@ fn method_rank(method: crank_core::HttpMethod) -> u8 {
|
|||||||
crank_core::HttpMethod::Put => 2,
|
crank_core::HttpMethod::Put => 2,
|
||||||
crank_core::HttpMethod::Patch => 3,
|
crank_core::HttpMethod::Patch => 3,
|
||||||
crank_core::HttpMethod::Delete => 4,
|
crank_core::HttpMethod::Delete => 4,
|
||||||
|
crank_core::HttpMethod::Head => 5,
|
||||||
|
crank_core::HttpMethod::Options => 6,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -929,7 +865,7 @@ fn severity_rank(severity: &ImportFindingSeverity) -> u8 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn sort_findings(findings: &mut [ImportFinding]) {
|
pub(super) fn sort_findings(findings: &mut [ImportFinding]) {
|
||||||
findings.sort_by(|left, right| {
|
findings.sort_by(|left, right| {
|
||||||
(
|
(
|
||||||
severity_rank(&left.severity),
|
severity_rank(&left.severity),
|
||||||
|
|||||||
@@ -11,10 +11,16 @@ use crate::rest::model::{
|
|||||||
|
|
||||||
use super::ImportParseError;
|
use super::ImportParseError;
|
||||||
|
|
||||||
pub(super) use super::normalize_schema::{has_reference_schema, typed_schema};
|
pub(super) use super::normalize_schema::{
|
||||||
|
has_reference_schema, typed_schema, typed_schema_with_property_locations,
|
||||||
|
};
|
||||||
|
|
||||||
pub(super) fn validate_coverage(ir: &NormalizedIr) -> Result<(), ImportParseError> {
|
pub(super) fn validate_coverage(ir: &NormalizedIr) -> Result<(), ImportParseError> {
|
||||||
if ir.normalizer_version != NORMALIZER_VERSION || ir.projection_version != PROJECTION_VERSION {
|
let current =
|
||||||
|
ir.normalizer_version == NORMALIZER_VERSION && ir.projection_version == PROJECTION_VERSION;
|
||||||
|
let historical_v4 = ir.normalizer_version == super::model::HISTORICAL_NORMALIZER_VERSION
|
||||||
|
&& ir.projection_version == super::model::HISTORICAL_PROJECTION_VERSION;
|
||||||
|
if !current && !historical_v4 {
|
||||||
return Err(ImportParseError::InvalidDocument);
|
return Err(ImportParseError::InvalidDocument);
|
||||||
}
|
}
|
||||||
let mut source_nodes = BTreeMap::new();
|
let mut source_nodes = BTreeMap::new();
|
||||||
@@ -92,6 +98,25 @@ pub(super) fn validate_coverage(ir: &NormalizedIr) -> Result<(), ImportParseErro
|
|||||||
.flat_map(|operation| &operation.findings),
|
.flat_map(|operation| &operation.findings),
|
||||||
)
|
)
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
|
if findings.iter().any(|finding| {
|
||||||
|
is_security_finding_code(&finding.code)
|
||||||
|
&& !super::normalize_finding_validation::matches_source(finding, ir, &source_nodes)
|
||||||
|
}) {
|
||||||
|
return Err(ImportParseError::InvalidDocument);
|
||||||
|
}
|
||||||
|
for finding in &findings {
|
||||||
|
if super::normalize_finding_validation::matches_source(finding, ir, &source_nodes)
|
||||||
|
&& finding.construct_id == format!("{version}:{}", finding.location.pointer)
|
||||||
|
{
|
||||||
|
insert_real_expected(
|
||||||
|
&mut expected,
|
||||||
|
&source_nodes,
|
||||||
|
finding.construct_id.clone(),
|
||||||
|
finding.location.clone(),
|
||||||
|
CoverageDisposition::Finding,
|
||||||
|
)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
for finding in &findings {
|
for finding in &findings {
|
||||||
let Some(target) = expected.get(&finding.construct_id) else {
|
let Some(target) = expected.get(&finding.construct_id) else {
|
||||||
return Err(ImportParseError::InvalidDocument);
|
return Err(ImportParseError::InvalidDocument);
|
||||||
@@ -130,6 +155,20 @@ pub(super) fn validate_coverage(ir: &NormalizedIr) -> Result<(), ImportParseErro
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn is_security_finding_code(code: &str) -> bool {
|
||||||
|
matches!(
|
||||||
|
code,
|
||||||
|
"invalid_security_requirements"
|
||||||
|
| "invalid_security_requirement"
|
||||||
|
| "unresolved_security_scheme"
|
||||||
|
| "unsupported_security_and_requirement"
|
||||||
|
| "unsupported_security_scheme"
|
||||||
|
| "unsupported_security_requirements"
|
||||||
|
| "invalid_security_scopes"
|
||||||
|
| "unexpected_security_scopes"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
struct ExpectedCoverage {
|
struct ExpectedCoverage {
|
||||||
location: SourceLocation,
|
location: SourceLocation,
|
||||||
@@ -342,6 +381,9 @@ fn openapi_servers(
|
|||||||
let CanonicalSourceValue::String(url) = &fields.get("url")?.value else {
|
let CanonicalSourceValue::String(url) = &fields.get("url")?.value else {
|
||||||
return None;
|
return None;
|
||||||
};
|
};
|
||||||
|
if !super::openapi3_findings::valid_http_server_url(url) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
Some((url.trim_end_matches('/').to_owned(), item.location.clone()))
|
Some((url.trim_end_matches('/').to_owned(), item.location.clone()))
|
||||||
})
|
})
|
||||||
.unzip()
|
.unzip()
|
||||||
@@ -413,6 +455,8 @@ fn method_rank(method: crank_core::HttpMethod) -> u8 {
|
|||||||
crank_core::HttpMethod::Put => 2,
|
crank_core::HttpMethod::Put => 2,
|
||||||
crank_core::HttpMethod::Patch => 3,
|
crank_core::HttpMethod::Patch => 3,
|
||||||
crank_core::HttpMethod::Delete => 4,
|
crank_core::HttpMethod::Delete => 4,
|
||||||
|
crank_core::HttpMethod::Head => 5,
|
||||||
|
crank_core::HttpMethod::Options => 6,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -423,6 +467,8 @@ fn method_name(method: crank_core::HttpMethod) -> &'static str {
|
|||||||
crank_core::HttpMethod::Put => "put",
|
crank_core::HttpMethod::Put => "put",
|
||||||
crank_core::HttpMethod::Patch => "patch",
|
crank_core::HttpMethod::Patch => "patch",
|
||||||
crank_core::HttpMethod::Delete => "delete",
|
crank_core::HttpMethod::Delete => "delete",
|
||||||
|
crank_core::HttpMethod::Head => "head",
|
||||||
|
crank_core::HttpMethod::Options => "options",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -518,6 +564,16 @@ fn collect_operation_expectations(
|
|||||||
if let Some(schema) = &operation.response_schema {
|
if let Some(schema) = &operation.response_schema {
|
||||||
collect_schema_expectations(schema, source_nodes, expected)?;
|
collect_schema_expectations(schema, source_nodes, expected)?;
|
||||||
}
|
}
|
||||||
|
for variant in &operation.request_body_variants {
|
||||||
|
if let Some(schema) = &variant.schema {
|
||||||
|
collect_schema_expectations(schema, source_nodes, expected)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for variant in &operation.response_variants {
|
||||||
|
if let Some(schema) = &variant.schema {
|
||||||
|
collect_schema_expectations(schema, source_nodes, expected)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -578,7 +634,9 @@ fn collect_schema_expectations(
|
|||||||
collect_schema_expectations(child, source_nodes, expected)?;
|
collect_schema_expectations(child, source_nodes, expected)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
NormalizedSchemaKind::Array { items: Some(child) } => {
|
NormalizedSchemaKind::Array {
|
||||||
|
items: Some(child), ..
|
||||||
|
} => {
|
||||||
collect_schema_expectations(child, source_nodes, expected)?;
|
collect_schema_expectations(child, source_nodes, expected)?;
|
||||||
}
|
}
|
||||||
NormalizedSchemaKind::Composition { variants, .. } => {
|
NormalizedSchemaKind::Composition { variants, .. } => {
|
||||||
@@ -639,12 +697,27 @@ fn collect_finding_only_expectations(
|
|||||||
expected,
|
expected,
|
||||||
)?;
|
)?;
|
||||||
}
|
}
|
||||||
for method in ["head", "options", "trace", "connect"] {
|
for method in methods.keys().filter(|method| {
|
||||||
|
let non_method = if ir.source.format == "openapi" {
|
||||||
|
matches!(
|
||||||
|
method.as_str(),
|
||||||
|
"$ref" | "summary" | "description" | "servers" | "parameters"
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
matches!(method.as_str(), "$ref" | "parameters")
|
||||||
|
};
|
||||||
|
!method.starts_with("x-")
|
||||||
|
&& !non_method
|
||||||
|
&& !matches!(
|
||||||
|
method.as_str(),
|
||||||
|
"get" | "post" | "put" | "patch" | "delete" | "head" | "options"
|
||||||
|
)
|
||||||
|
}) {
|
||||||
if let Some(node) = methods.get(method) {
|
if let Some(node) = methods.get(method) {
|
||||||
insert_finding_pointer(version, node, expected)?;
|
insert_finding_pointer(version, node, expected)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for method in ["get", "post", "put", "patch", "delete"] {
|
for method in ["get", "post", "put", "patch", "delete", "head", "options"] {
|
||||||
if let Some(node) = methods.get(method) {
|
if let Some(node) = methods.get(method) {
|
||||||
match &node.value {
|
match &node.value {
|
||||||
CanonicalSourceValue::Object(operation) => {
|
CanonicalSourceValue::Object(operation) => {
|
||||||
@@ -682,13 +755,16 @@ fn collect_invalid_openapi_server_findings(
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
};
|
};
|
||||||
for server in items {
|
for server in items {
|
||||||
let valid = matches!(
|
match &server.value {
|
||||||
&server.value,
|
CanonicalSourceValue::Object(fields) => match fields.get("url") {
|
||||||
CanonicalSourceValue::Object(fields)
|
Some(url) if matches!(&url.value, CanonicalSourceValue::String(value) if !super::openapi3_findings::valid_http_server_url(value)) =>
|
||||||
if matches!(fields.get("url").map(|node| &node.value), Some(CanonicalSourceValue::String(_)))
|
{
|
||||||
);
|
insert_finding_pointer(version, url, expected)?;
|
||||||
if !valid {
|
}
|
||||||
insert_finding_pointer(version, server, expected)?;
|
Some(url) if matches!(url.value, CanonicalSourceValue::String(_)) => {}
|
||||||
|
_ => insert_finding_pointer(version, server, expected)?,
|
||||||
|
},
|
||||||
|
_ => insert_finding_pointer(version, server, expected)?,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -746,8 +822,11 @@ fn collect_dropped_parameter_findings(
|
|||||||
return Err(ImportParseError::InvalidDocument);
|
return Err(ImportParseError::InvalidDocument);
|
||||||
};
|
};
|
||||||
let supported = match format {
|
let supported = match format {
|
||||||
"openapi" => matches!(location.as_str(), "path" | "query" | "header"),
|
"openapi" => matches!(location.as_str(), "path" | "query" | "header" | "cookie"),
|
||||||
"swagger" => matches!(location.as_str(), "path" | "query" | "header" | "body"),
|
"swagger" => matches!(
|
||||||
|
location.as_str(),
|
||||||
|
"path" | "query" | "header" | "body" | "formData"
|
||||||
|
),
|
||||||
_ => false,
|
_ => false,
|
||||||
};
|
};
|
||||||
if !supported {
|
if !supported {
|
||||||
|
|||||||
@@ -0,0 +1,365 @@
|
|||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use crate::rest::model::{
|
||||||
|
CanonicalSourceNode, CanonicalSourceValue, ImportFindingSeverity, NormalizedFinding,
|
||||||
|
NormalizedIr, NormalizedOperation, NormalizedSecuritySchemeKind, SecurityRequirementsSource,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub(super) fn matches_source(
|
||||||
|
finding: &NormalizedFinding,
|
||||||
|
ir: &NormalizedIr,
|
||||||
|
nodes: &BTreeMap<String, &CanonicalSourceNode>,
|
||||||
|
) -> bool {
|
||||||
|
let pointer = finding.location.pointer.as_str();
|
||||||
|
let Some(node) = nodes.get(pointer).copied() else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let is_error = finding.severity == ImportFindingSeverity::Error;
|
||||||
|
match finding.code.as_str() {
|
||||||
|
"unsupported_parameter_style" if is_error => parameter_style(pointer, node, nodes),
|
||||||
|
"unsupported_parameter_content" if is_error => pointer.ends_with("/content"),
|
||||||
|
"missing_parameter_schema" if is_error => {
|
||||||
|
matches!(&node.value, CanonicalSourceValue::Object(fields) if !fields.contains_key("schema") && !fields.contains_key("content"))
|
||||||
|
}
|
||||||
|
"unsupported_request_body" if is_error => pointer.ends_with("/requestBody"),
|
||||||
|
"unsupported_request_media_type" | "unsupported_xml_request_media_type" if is_error => {
|
||||||
|
media_from_pointer(pointer).is_some_and(|media| !supported_request_media(&media))
|
||||||
|
}
|
||||||
|
"unsupported_response_media_type" | "unsupported_xml_response_media_type" if is_error => {
|
||||||
|
media_from_pointer(pointer).is_some_and(|media| !supported_response_media(&media))
|
||||||
|
}
|
||||||
|
"unsupported_multipart_encoding" | "unsupported_form_encoding" if is_error => {
|
||||||
|
pointer.contains("/encoding")
|
||||||
|
}
|
||||||
|
"unsupported_form_schema" if is_error => form_schema_shape(pointer, node),
|
||||||
|
"missing_request_media_schema" | "missing_response_media_schema" if is_error => {
|
||||||
|
matches!(&node.value, CanonicalSourceValue::Object(fields) if !fields.contains_key("schema"))
|
||||||
|
}
|
||||||
|
"unsupported_consumes" if is_error => {
|
||||||
|
matches!(&node.value, CanonicalSourceValue::String(media) if !supported_request_media(media))
|
||||||
|
}
|
||||||
|
"unsupported_produces" if is_error => {
|
||||||
|
matches!(&node.value, CanonicalSourceValue::String(media) if !supported_response_media(media))
|
||||||
|
}
|
||||||
|
"path_parameter_not_required" if is_error => {
|
||||||
|
matches!(&node.value, CanonicalSourceValue::Object(fields) if !matches!(fields.get("required").map(|node| &node.value), Some(CanonicalSourceValue::Boolean(true))))
|
||||||
|
}
|
||||||
|
"path_parameter_placeholder_missing" if is_error => ir.operations.iter().any(|operation| {
|
||||||
|
finding.operation_key.as_deref() == Some(operation.key.as_str())
|
||||||
|
&& matches!(&node.value, CanonicalSourceValue::Object(fields) if matches!(fields.get("name").map(|node| &node.value), Some(CanonicalSourceValue::String(name)) if !operation.path.contains(&format!("{{{name}}}"))))
|
||||||
|
}),
|
||||||
|
"unsupported_schema_keyword" if is_error => schema_keyword(pointer, node),
|
||||||
|
"unsupported_schema_enum" if is_error => {
|
||||||
|
pointer.ends_with("/enum")
|
||||||
|
&& matches!(&node.value, CanonicalSourceValue::Array(items) if items.iter().any(|item| !matches!(item.value, CanonicalSourceValue::String(_))))
|
||||||
|
}
|
||||||
|
"secret_like_example" if finding.severity == ImportFindingSeverity::Warning => {
|
||||||
|
pointer.contains("/example") && matches!(&node.value, CanonicalSourceValue::String(value) if secret_like(pointer, value))
|
||||||
|
}
|
||||||
|
"secret_literal_redacted" if finding.severity == ImportFindingSeverity::Warning => {
|
||||||
|
matches!(&node.value, CanonicalSourceValue::String(value) if value == "[REDACTED]")
|
||||||
|
}
|
||||||
|
"invalid_security_requirements"
|
||||||
|
| "invalid_security_requirement"
|
||||||
|
| "unresolved_security_scheme"
|
||||||
|
| "unsupported_security_and_requirement"
|
||||||
|
| "unsupported_security_scheme"
|
||||||
|
| "unsupported_security_requirements"
|
||||||
|
| "invalid_security_scopes"
|
||||||
|
| "unexpected_security_scopes" => security_finding(finding, ir, nodes),
|
||||||
|
"invalid_server" if is_error => invalid_server(pointer, node),
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn security_finding(
|
||||||
|
finding: &NormalizedFinding,
|
||||||
|
ir: &NormalizedIr,
|
||||||
|
nodes: &BTreeMap<String, &CanonicalSourceNode>,
|
||||||
|
) -> bool {
|
||||||
|
let Some(operation) = ir
|
||||||
|
.operations
|
||||||
|
.iter()
|
||||||
|
.find(|operation| finding.operation_key.as_deref() == Some(operation.key.as_str()))
|
||||||
|
else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let Some(requirements_pointer) = requirements_pointer(operation) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let pointer = finding.location.pointer.as_str();
|
||||||
|
let node = nodes.get(pointer).copied();
|
||||||
|
|
||||||
|
match finding.code.as_str() {
|
||||||
|
"invalid_security_requirements" => {
|
||||||
|
finding.severity == ImportFindingSeverity::Error
|
||||||
|
&& pointer == requirements_pointer
|
||||||
|
&& node.is_some_and(|node| !matches!(&node.value, CanonicalSourceValue::Array(_)))
|
||||||
|
}
|
||||||
|
"invalid_security_requirement" => {
|
||||||
|
finding.severity == ImportFindingSeverity::Warning
|
||||||
|
&& alternative_at(operation, pointer).is_some_and(|_| {
|
||||||
|
node.is_some_and(|node| !matches!(&node.value, CanonicalSourceValue::Object(_)))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
"unresolved_security_scheme" => {
|
||||||
|
finding.severity == ImportFindingSeverity::Warning
|
||||||
|
&& scheme_at(operation, pointer)
|
||||||
|
.is_some_and(|name| node.is_some() && !ir.security_schemes.contains_key(name))
|
||||||
|
}
|
||||||
|
"unsupported_security_and_requirement" => {
|
||||||
|
finding.severity == ImportFindingSeverity::Warning
|
||||||
|
&& alternative_at(operation, pointer)
|
||||||
|
.is_some_and(|alternative| alternative.schemes.len() > 1)
|
||||||
|
&& node.is_some_and(|node| matches!(&node.value, CanonicalSourceValue::Object(_)))
|
||||||
|
}
|
||||||
|
"unsupported_security_scheme" => {
|
||||||
|
finding.severity == ImportFindingSeverity::Warning
|
||||||
|
&& scheme_at(operation, pointer).is_some_and(|name| {
|
||||||
|
let Some(scheme) = ir.security_schemes.get(name) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
node.is_some()
|
||||||
|
&& matches!(
|
||||||
|
&scheme.kind,
|
||||||
|
NormalizedSecuritySchemeKind::Unsupported { .. }
|
||||||
|
| NormalizedSecuritySchemeKind::ApiKey {
|
||||||
|
location: crate::rest::model::SecurityParameterLocation::Cookie,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
"unsupported_security_requirements" => {
|
||||||
|
finding.severity == ImportFindingSeverity::Error
|
||||||
|
&& pointer == requirements_pointer
|
||||||
|
&& !operation.security_requirements.alternatives.is_empty()
|
||||||
|
&& operation
|
||||||
|
.security_requirements
|
||||||
|
.alternatives
|
||||||
|
.iter()
|
||||||
|
.all(|alternative| !alternative.supported)
|
||||||
|
&& node.is_some_and(|node| matches!(&node.value, CanonicalSourceValue::Array(_)))
|
||||||
|
}
|
||||||
|
"invalid_security_scopes" | "unexpected_security_scopes" => {
|
||||||
|
if finding.severity != ImportFindingSeverity::Warning {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let Some(name) = scheme_at(operation, pointer) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let Some(node) = node else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let valid_scopes = matches!(&node.value, CanonicalSourceValue::Array(items) if items.iter().all(|item| matches!(item.value, CanonicalSourceValue::String(_))));
|
||||||
|
if finding.code == "invalid_security_scopes" {
|
||||||
|
!valid_scopes
|
||||||
|
} else {
|
||||||
|
let nonempty = matches!(&node.value, CanonicalSourceValue::Array(items) if !items.is_empty() && items.iter().all(|item| matches!(item.value, CanonicalSourceValue::String(_))));
|
||||||
|
let oauth_scoped = ir.security_schemes.get(name).is_some_and(|scheme| {
|
||||||
|
matches!(
|
||||||
|
&scheme.kind,
|
||||||
|
NormalizedSecuritySchemeKind::Unsupported {
|
||||||
|
scheme_type: Some(scheme_type)
|
||||||
|
} if matches!(scheme_type.as_str(), "oauth2" | "openIdConnect")
|
||||||
|
)
|
||||||
|
});
|
||||||
|
nonempty && !oauth_scoped
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn requirements_pointer(operation: &NormalizedOperation) -> Option<String> {
|
||||||
|
match operation.security_requirements.source {
|
||||||
|
SecurityRequirementsSource::Document => Some("/security".to_owned()),
|
||||||
|
SecurityRequirementsSource::Operation => {
|
||||||
|
Some(format!("{}/security", operation.location.pointer))
|
||||||
|
}
|
||||||
|
SecurityRequirementsSource::None => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn alternative_at<'a>(
|
||||||
|
operation: &'a NormalizedOperation,
|
||||||
|
pointer: &str,
|
||||||
|
) -> Option<&'a crate::rest::model::SecurityRequirementAlternative> {
|
||||||
|
operation
|
||||||
|
.security_requirements
|
||||||
|
.alternatives
|
||||||
|
.iter()
|
||||||
|
.find(|alternative| {
|
||||||
|
alternative
|
||||||
|
.source_location
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|location| location.pointer == pointer)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scheme_at<'a>(operation: &'a NormalizedOperation, pointer: &str) -> Option<&'a str> {
|
||||||
|
let (alternative_pointer, scheme) = pointer.rsplit_once('/')?;
|
||||||
|
let alternative = alternative_at(operation, alternative_pointer)?;
|
||||||
|
let name = scheme.replace("~1", "/").replace("~0", "~");
|
||||||
|
alternative
|
||||||
|
.schemes
|
||||||
|
.iter()
|
||||||
|
.find(|candidate| **candidate == name)
|
||||||
|
.map(String::as_str)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parameter_style(
|
||||||
|
pointer: &str,
|
||||||
|
node: &CanonicalSourceNode,
|
||||||
|
nodes: &BTreeMap<String, &CanonicalSourceNode>,
|
||||||
|
) -> bool {
|
||||||
|
if pointer.ends_with("/schema") {
|
||||||
|
return compound_parameter(node);
|
||||||
|
}
|
||||||
|
if pointer.ends_with("/collectionFormat") {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if compound_parameter(node) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
let Some((parameter_pointer, field)) = pointer.rsplit_once('/') else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let location = nodes
|
||||||
|
.get(&format!("{parameter_pointer}/in"))
|
||||||
|
.and_then(|node| match &node.value {
|
||||||
|
CanonicalSourceValue::String(value) => Some(value.as_str()),
|
||||||
|
_ => None,
|
||||||
|
});
|
||||||
|
match (field, &node.value, location) {
|
||||||
|
("style", CanonicalSourceValue::String(style), Some("path" | "header")) => {
|
||||||
|
style != "simple"
|
||||||
|
}
|
||||||
|
("style", CanonicalSourceValue::String(style), Some("query" | "cookie")) => style != "form",
|
||||||
|
("style", _, Some(_)) => true,
|
||||||
|
("explode", CanonicalSourceValue::Boolean(value), Some("path" | "header")) => *value,
|
||||||
|
("explode", CanonicalSourceValue::Boolean(value), Some("query" | "cookie")) => !*value,
|
||||||
|
("explode", _, Some(_)) => true,
|
||||||
|
("allowReserved", value, _) => !matches!(value, CanonicalSourceValue::Boolean(false)),
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn compound_parameter(node: &CanonicalSourceNode) -> bool {
|
||||||
|
matches!(&node.value, CanonicalSourceValue::Object(fields) if matches!(fields.get("type").map(|node| &node.value), Some(CanonicalSourceValue::String(value)) if matches!(value.as_str(), "array" | "object")))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn schema_keyword(pointer: &str, node: &CanonicalSourceNode) -> bool {
|
||||||
|
const UNSUPPORTED: &[&str] = &[
|
||||||
|
"additionalProperties",
|
||||||
|
"unevaluatedProperties",
|
||||||
|
"prefixItems",
|
||||||
|
"contains",
|
||||||
|
"dependentSchemas",
|
||||||
|
"if",
|
||||||
|
"then",
|
||||||
|
"else",
|
||||||
|
"not",
|
||||||
|
"propertyNames",
|
||||||
|
"minimum",
|
||||||
|
"maximum",
|
||||||
|
"exclusiveMinimum",
|
||||||
|
"exclusiveMaximum",
|
||||||
|
"minLength",
|
||||||
|
"maxLength",
|
||||||
|
"pattern",
|
||||||
|
"minItems",
|
||||||
|
"maxItems",
|
||||||
|
"uniqueItems",
|
||||||
|
"const",
|
||||||
|
"multipleOf",
|
||||||
|
"minProperties",
|
||||||
|
"maxProperties",
|
||||||
|
"dependentRequired",
|
||||||
|
];
|
||||||
|
let field = pointer.rsplit('/').next().unwrap_or_default();
|
||||||
|
if UNSUPPORTED.contains(&field) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
field == "type"
|
||||||
|
&& matches!(&node.value, CanonicalSourceValue::Array(items) if {
|
||||||
|
let concrete = items.iter().filter(|item| matches!(&item.value, CanonicalSourceValue::String(value) if value != "null")).count();
|
||||||
|
items.len() != 2 || concrete != 1 || !items.iter().any(|item| matches!(&item.value, CanonicalSourceValue::String(value) if value == "null"))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn form_schema_shape(pointer: &str, node: &CanonicalSourceNode) -> bool {
|
||||||
|
if !pointer.contains("/requestBody/content/application~1x-www-form-urlencoded/schema")
|
||||||
|
&& !pointer.contains("/requestBody/content/multipart~1form-data/schema")
|
||||||
|
&& !pointer.contains("/parameters/")
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let object = matches!(
|
||||||
|
&node.value,
|
||||||
|
CanonicalSourceValue::Object(fields)
|
||||||
|
if fields.contains_key("properties")
|
||||||
|
|| matches!(fields.get("type").map(|field| &field.value), Some(CanonicalSourceValue::String(value)) if value == "object")
|
||||||
|
);
|
||||||
|
let nested_array = pointer.ends_with("/items")
|
||||||
|
&& matches!(
|
||||||
|
&node.value,
|
||||||
|
CanonicalSourceValue::Object(fields)
|
||||||
|
if matches!(fields.get("type").map(|field| &field.value), Some(CanonicalSourceValue::String(value)) if value == "array")
|
||||||
|
);
|
||||||
|
pointer.ends_with("/schema") || object || nested_array
|
||||||
|
}
|
||||||
|
|
||||||
|
fn media_from_pointer(pointer: &str) -> Option<String> {
|
||||||
|
Some(
|
||||||
|
pointer
|
||||||
|
.rsplit('/')
|
||||||
|
.next()?
|
||||||
|
.replace("~1", "/")
|
||||||
|
.replace("~0", "~"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn supported_request_media(media: &str) -> bool {
|
||||||
|
matches!(
|
||||||
|
media,
|
||||||
|
"application/json" | "application/x-www-form-urlencoded" | "multipart/form-data"
|
||||||
|
) || media.ends_with("+json")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn supported_response_media(media: &str) -> bool {
|
||||||
|
media == "application/json" || media.ends_with("+json")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn secret_like(pointer: &str, value: &str) -> bool {
|
||||||
|
let pointer = pointer.to_ascii_lowercase();
|
||||||
|
let value = value.to_ascii_lowercase();
|
||||||
|
[
|
||||||
|
"token",
|
||||||
|
"secret",
|
||||||
|
"password",
|
||||||
|
"api_key",
|
||||||
|
"apikey",
|
||||||
|
"authorization",
|
||||||
|
]
|
||||||
|
.iter()
|
||||||
|
.any(|marker| pointer.contains(marker) || value.contains(marker))
|
||||||
|
|| value.starts_with("bearer ")
|
||||||
|
|| value.starts_with("sk-")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn invalid_server(pointer: &str, node: &CanonicalSourceNode) -> bool {
|
||||||
|
if pointer == "/host" {
|
||||||
|
return !matches!(&node.value, CanonicalSourceValue::String(host) if !host.is_empty() && !host.contains('@') && !host.chars().any(char::is_whitespace));
|
||||||
|
}
|
||||||
|
if pointer == "/basePath" {
|
||||||
|
return !matches!(&node.value, CanonicalSourceValue::String(path) if (path.is_empty() || path.starts_with('/')) && !path.chars().any(char::is_control));
|
||||||
|
}
|
||||||
|
if pointer.starts_with("/schemes/") {
|
||||||
|
return !matches!(&node.value, CanonicalSourceValue::String(scheme) if matches!(scheme.as_str(), "http" | "https"));
|
||||||
|
}
|
||||||
|
if pointer.ends_with("/url") {
|
||||||
|
return matches!(&node.value, CanonicalSourceValue::String(url) if !super::openapi3_findings::valid_http_server_url(url));
|
||||||
|
}
|
||||||
|
!matches!(&node.value, CanonicalSourceValue::Object(fields) if matches!(fields.get("url").map(|node| &node.value), Some(CanonicalSourceValue::String(_))))
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
|
use crate::rest::model::{
|
||||||
|
ImportFinding, ImportGroupPreview, ImportPreview, ImportSourcePreview, NormalizedIr,
|
||||||
|
NormalizedSecurityScheme, RestImportDocument,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub(super) fn preview_from_ir(ir: &NormalizedIr) -> ImportPreview {
|
||||||
|
let operations = ir
|
||||||
|
.operations
|
||||||
|
.iter()
|
||||||
|
.map(super::normalize_projection::operation_from_normalized)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let findings = ir
|
||||||
|
.findings
|
||||||
|
.iter()
|
||||||
|
.map(|finding| ImportFinding {
|
||||||
|
code: finding.code.clone(),
|
||||||
|
severity: finding.severity.clone(),
|
||||||
|
message: finding.message.clone(),
|
||||||
|
operation_key: finding.operation_key.clone(),
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
preview_from_operations(
|
||||||
|
&ir.source,
|
||||||
|
&ir.security_schemes,
|
||||||
|
operations.iter(),
|
||||||
|
findings,
|
||||||
|
false,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn preview_from_document(document: RestImportDocument) -> ImportPreview {
|
||||||
|
let source = ImportSourcePreview {
|
||||||
|
format: document.format,
|
||||||
|
version: document.version,
|
||||||
|
title: document.title,
|
||||||
|
servers: document.servers,
|
||||||
|
};
|
||||||
|
preview_from_operations(
|
||||||
|
&source,
|
||||||
|
&document.security_schemes,
|
||||||
|
document.operations.iter(),
|
||||||
|
document.findings,
|
||||||
|
true,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn preview_from_operations<'a>(
|
||||||
|
source: &ImportSourcePreview,
|
||||||
|
security_schemes: &BTreeMap<String, NormalizedSecurityScheme>,
|
||||||
|
operations: impl Iterator<Item = &'a crate::rest::model::RestImportOperation>,
|
||||||
|
mut findings: Vec<ImportFinding>,
|
||||||
|
legacy: bool,
|
||||||
|
) -> ImportPreview {
|
||||||
|
let mut groups: BTreeMap<String, ImportGroupPreview> = BTreeMap::new();
|
||||||
|
let mut used_names = BTreeSet::new();
|
||||||
|
|
||||||
|
for operation in operations {
|
||||||
|
let candidate = if legacy {
|
||||||
|
super::legacy_payload::candidate_from_operation(
|
||||||
|
operation,
|
||||||
|
&source.servers,
|
||||||
|
&mut used_names,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
super::payload::candidate_from_operation(
|
||||||
|
operation,
|
||||||
|
security_schemes,
|
||||||
|
&source.servers,
|
||||||
|
&mut used_names,
|
||||||
|
)
|
||||||
|
};
|
||||||
|
let group_title = operation
|
||||||
|
.tags
|
||||||
|
.first()
|
||||||
|
.cloned()
|
||||||
|
.unwrap_or_else(|| "Без группы".to_owned());
|
||||||
|
let group_key = crate::rest::naming::snake_name(&group_title);
|
||||||
|
groups
|
||||||
|
.entry(group_key.clone())
|
||||||
|
.or_insert_with(|| ImportGroupPreview {
|
||||||
|
key: group_key,
|
||||||
|
title: group_title,
|
||||||
|
operations: Vec::new(),
|
||||||
|
})
|
||||||
|
.operations
|
||||||
|
.push(candidate);
|
||||||
|
}
|
||||||
|
|
||||||
|
super::normalize::sort_findings(&mut findings);
|
||||||
|
ImportPreview {
|
||||||
|
source: source.clone(),
|
||||||
|
groups: groups.into_values().collect(),
|
||||||
|
findings,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
use crate::rest::model::{
|
||||||
|
ImportFinding, NormalizedLiteral, NormalizedOperation, NormalizedScalarKind, NormalizedSchema,
|
||||||
|
NormalizedSchemaKind, RestImportOperation, RestImportParameter, RestRequestBodyVariant,
|
||||||
|
RestResponseVariant,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub(super) fn operation_from_normalized(operation: &NormalizedOperation) -> RestImportOperation {
|
||||||
|
RestImportOperation {
|
||||||
|
key: operation.key.clone(),
|
||||||
|
method: operation.method,
|
||||||
|
path: operation.path.clone(),
|
||||||
|
security_requirements: operation.security_requirements.clone(),
|
||||||
|
operation_id: operation.operation_id.clone(),
|
||||||
|
summary: operation.summary.clone(),
|
||||||
|
description: operation.description.clone(),
|
||||||
|
tags: operation.tags.clone(),
|
||||||
|
parameters: operation
|
||||||
|
.parameters
|
||||||
|
.iter()
|
||||||
|
.map(|parameter| RestImportParameter {
|
||||||
|
name: parameter.name.clone(),
|
||||||
|
location: parameter.location,
|
||||||
|
required: parameter.required,
|
||||||
|
description: parameter.description.clone(),
|
||||||
|
schema: parameter.schema.as_ref().map(schema_value),
|
||||||
|
source_location: parameter.source_location.clone(),
|
||||||
|
schema_source_location: None,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
request_body_schema: operation.request_body_schema.as_ref().map(schema_value),
|
||||||
|
request_body_schema_location: None,
|
||||||
|
request_body_variants: operation
|
||||||
|
.request_body_variants
|
||||||
|
.iter()
|
||||||
|
.map(|variant| RestRequestBodyVariant {
|
||||||
|
content_type: variant.content_type.clone(),
|
||||||
|
required: variant.required,
|
||||||
|
schema: variant.schema.as_ref().map(schema_value),
|
||||||
|
multipart_field_mime_types: variant.multipart_field_mime_types.clone(),
|
||||||
|
source_location: variant.source_location.clone(),
|
||||||
|
schema_source_location: None,
|
||||||
|
schema_property_source_locations: BTreeMap::new(),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
response_schema: operation.response_schema.as_ref().map(schema_value),
|
||||||
|
response_schema_location: None,
|
||||||
|
response_variants: operation
|
||||||
|
.response_variants
|
||||||
|
.iter()
|
||||||
|
.map(|variant| RestResponseVariant {
|
||||||
|
status_code: variant.status_code,
|
||||||
|
content_type: variant.content_type.clone(),
|
||||||
|
schema: variant.schema.as_ref().map(schema_value),
|
||||||
|
source_location: variant.source_location.clone(),
|
||||||
|
schema_source_location: None,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
servers: operation.servers.clone(),
|
||||||
|
findings: operation
|
||||||
|
.findings
|
||||||
|
.iter()
|
||||||
|
.map(|finding| ImportFinding {
|
||||||
|
code: finding.code.clone(),
|
||||||
|
severity: finding.severity.clone(),
|
||||||
|
message: finding.message.clone(),
|
||||||
|
operation_key: finding.operation_key.clone(),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
internal_finding_locations: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn schema_value(schema: &NormalizedSchema) -> Value {
|
||||||
|
let mut value = match &schema.kind {
|
||||||
|
NormalizedSchemaKind::Reference { reference } => serde_json::json!({"$ref": reference.uri}),
|
||||||
|
NormalizedSchemaKind::Composition { operator, variants } => serde_json::json!({
|
||||||
|
operator: variants.iter().map(schema_value).collect::<Vec<_>>(),
|
||||||
|
"x-crank-lossless-composition": true,
|
||||||
|
}),
|
||||||
|
NormalizedSchemaKind::Object {
|
||||||
|
properties,
|
||||||
|
required,
|
||||||
|
nullable,
|
||||||
|
default_value,
|
||||||
|
} => {
|
||||||
|
let mut value = serde_json::json!({
|
||||||
|
"type": "object",
|
||||||
|
"properties": properties.iter().map(|(name, schema)| (name.clone(), schema_value(schema))).collect::<serde_json::Map<_, _>>(),
|
||||||
|
"required": required,
|
||||||
|
"nullable": nullable,
|
||||||
|
});
|
||||||
|
insert_default(&mut value, default_value.as_ref());
|
||||||
|
value
|
||||||
|
}
|
||||||
|
NormalizedSchemaKind::Array {
|
||||||
|
items,
|
||||||
|
nullable,
|
||||||
|
default_value,
|
||||||
|
} => {
|
||||||
|
let mut value = serde_json::json!({"type": "array", "nullable": nullable});
|
||||||
|
if let Some(items) = items {
|
||||||
|
value["items"] = schema_value(items);
|
||||||
|
}
|
||||||
|
insert_default(&mut value, default_value.as_ref());
|
||||||
|
value
|
||||||
|
}
|
||||||
|
NormalizedSchemaKind::Scalar {
|
||||||
|
scalar_type,
|
||||||
|
format,
|
||||||
|
nullable,
|
||||||
|
default_value,
|
||||||
|
enum_values,
|
||||||
|
} => {
|
||||||
|
let scalar_type = match scalar_type {
|
||||||
|
NormalizedScalarKind::String => "string",
|
||||||
|
NormalizedScalarKind::Integer => "integer",
|
||||||
|
NormalizedScalarKind::Number => "number",
|
||||||
|
NormalizedScalarKind::Boolean => "boolean",
|
||||||
|
NormalizedScalarKind::Null => "null",
|
||||||
|
};
|
||||||
|
let mut value = serde_json::json!({"type": scalar_type, "nullable": nullable});
|
||||||
|
if let Some(format) = format {
|
||||||
|
value["format"] = Value::String(format.clone());
|
||||||
|
}
|
||||||
|
if !enum_values.is_empty() {
|
||||||
|
value["enum"] = Value::Array(enum_values.iter().map(literal_value).collect());
|
||||||
|
}
|
||||||
|
insert_default(&mut value, default_value.as_ref());
|
||||||
|
value
|
||||||
|
}
|
||||||
|
NormalizedSchemaKind::Unknown => serde_json::json!({}),
|
||||||
|
};
|
||||||
|
if let Some(description) = &schema.description {
|
||||||
|
value["description"] = Value::String(description.clone());
|
||||||
|
}
|
||||||
|
value
|
||||||
|
}
|
||||||
|
|
||||||
|
fn insert_default(value: &mut Value, default: Option<&NormalizedLiteral>) {
|
||||||
|
if let Some(default) = default {
|
||||||
|
value["default"] = literal_value(default);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn literal_value(value: &NormalizedLiteral) -> Value {
|
||||||
|
match value {
|
||||||
|
NormalizedLiteral::String(value) => Value::String(value.clone()),
|
||||||
|
NormalizedLiteral::Integer(value) => Value::Number((*value).into()),
|
||||||
|
NormalizedLiteral::Unsigned(value) => Value::Number((*value).into()),
|
||||||
|
NormalizedLiteral::Number(value) => serde_json::Number::from_f64(*value)
|
||||||
|
.map(Value::Number)
|
||||||
|
.unwrap_or(Value::Null),
|
||||||
|
NormalizedLiteral::Boolean(value) => Value::Bool(*value),
|
||||||
|
NormalizedLiteral::Null => Value::Null,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,12 +8,71 @@ use crate::rest::model::{
|
|||||||
|
|
||||||
use super::normalize_coverage::escape_pointer;
|
use super::normalize_coverage::escape_pointer;
|
||||||
|
|
||||||
|
pub(super) fn typed_schema_with_property_locations(
|
||||||
|
value: &Value,
|
||||||
|
pointer: &str,
|
||||||
|
property_locations: &std::collections::BTreeMap<String, SourceLocation>,
|
||||||
|
coverage: &mut Vec<CoverageEntry>,
|
||||||
|
) -> NormalizedSchema {
|
||||||
|
if property_locations.is_empty() {
|
||||||
|
return typed_schema(value, pointer, "", coverage);
|
||||||
|
}
|
||||||
|
let mut root_value = value.clone();
|
||||||
|
if let Some(object) = root_value.as_object_mut() {
|
||||||
|
object.remove("properties");
|
||||||
|
}
|
||||||
|
let mut normalized = typed_schema(&root_value, pointer, "", coverage);
|
||||||
|
let Some(properties) = value.get("properties").and_then(Value::as_object) else {
|
||||||
|
return normalized;
|
||||||
|
};
|
||||||
|
let NormalizedSchemaKind::Object {
|
||||||
|
properties: normalized_properties,
|
||||||
|
..
|
||||||
|
} = &mut normalized.kind
|
||||||
|
else {
|
||||||
|
return normalized;
|
||||||
|
};
|
||||||
|
for (name, schema) in properties {
|
||||||
|
let Some(location) = property_locations.get(name) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
normalized_properties.insert(
|
||||||
|
name.clone(),
|
||||||
|
typed_schema(schema, &location.pointer, "", coverage),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
normalized
|
||||||
|
}
|
||||||
|
|
||||||
pub(super) fn typed_schema(
|
pub(super) fn typed_schema(
|
||||||
value: &Value,
|
value: &Value,
|
||||||
pointer: &str,
|
pointer: &str,
|
||||||
_id: &str,
|
_id: &str,
|
||||||
coverage: &mut Vec<CoverageEntry>,
|
coverage: &mut Vec<CoverageEntry>,
|
||||||
) -> NormalizedSchema {
|
) -> NormalizedSchema {
|
||||||
|
let normalized_type_value;
|
||||||
|
let value = if let Some(types) = value.get("type").and_then(Value::as_array) {
|
||||||
|
let concrete = types
|
||||||
|
.iter()
|
||||||
|
.filter_map(Value::as_str)
|
||||||
|
.filter(|value| *value != "null")
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
if types.iter().any(|value| value.as_str() == Some("null")) && concrete.len() == 1 {
|
||||||
|
normalized_type_value = {
|
||||||
|
let mut normalized = value.clone();
|
||||||
|
if let Some(object) = normalized.as_object_mut() {
|
||||||
|
object.insert("type".to_owned(), Value::String(concrete[0].to_owned()));
|
||||||
|
object.insert("nullable".to_owned(), Value::Bool(true));
|
||||||
|
}
|
||||||
|
normalized
|
||||||
|
};
|
||||||
|
&normalized_type_value
|
||||||
|
} else {
|
||||||
|
value
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
value
|
||||||
|
};
|
||||||
// IDs are derived from RFC 6901 locations rather than user-controlled
|
// IDs are derived from RFC 6901 locations rather than user-controlled
|
||||||
// property names, so escaped keys cannot collide with one another.
|
// property names, so escaped keys cannot collide with one another.
|
||||||
let id = format!("schema:{}", escape_pointer(pointer));
|
let id = format!("schema:{}", escape_pointer(pointer));
|
||||||
@@ -105,6 +164,11 @@ pub(super) fn typed_schema(
|
|||||||
NormalizedSchemaKind::Object {
|
NormalizedSchemaKind::Object {
|
||||||
properties,
|
properties,
|
||||||
required,
|
required,
|
||||||
|
nullable: value
|
||||||
|
.get("nullable")
|
||||||
|
.and_then(Value::as_bool)
|
||||||
|
.unwrap_or(false),
|
||||||
|
default_value: value.get("default").and_then(normalized_literal),
|
||||||
}
|
}
|
||||||
} else if value.get("type").and_then(Value::as_str) == Some("array") {
|
} else if value.get("type").and_then(Value::as_str) == Some("array") {
|
||||||
NormalizedSchemaKind::Array {
|
NormalizedSchemaKind::Array {
|
||||||
@@ -116,6 +180,11 @@ pub(super) fn typed_schema(
|
|||||||
coverage,
|
coverage,
|
||||||
))
|
))
|
||||||
}),
|
}),
|
||||||
|
nullable: value
|
||||||
|
.get("nullable")
|
||||||
|
.and_then(Value::as_bool)
|
||||||
|
.unwrap_or(false),
|
||||||
|
default_value: value.get("default").and_then(normalized_literal),
|
||||||
}
|
}
|
||||||
} else if let Some(raw_type) = value.get("type").and_then(Value::as_str) {
|
} else if let Some(raw_type) = value.get("type").and_then(Value::as_str) {
|
||||||
NormalizedSchemaKind::Scalar {
|
NormalizedSchemaKind::Scalar {
|
||||||
@@ -190,7 +259,7 @@ pub(super) fn has_reference_schema(schema: Option<&NormalizedSchema>) -> bool {
|
|||||||
Some(NormalizedSchemaKind::Object { properties, .. }) => properties
|
Some(NormalizedSchemaKind::Object { properties, .. }) => properties
|
||||||
.values()
|
.values()
|
||||||
.any(|schema| has_reference_schema(Some(schema))),
|
.any(|schema| has_reference_schema(Some(schema))),
|
||||||
Some(NormalizedSchemaKind::Array { items }) => has_reference_schema(items.as_deref()),
|
Some(NormalizedSchemaKind::Array { items, .. }) => has_reference_schema(items.as_deref()),
|
||||||
Some(NormalizedSchemaKind::Composition { variants, .. }) => variants
|
Some(NormalizedSchemaKind::Composition { variants, .. }) => variants
|
||||||
.iter()
|
.iter()
|
||||||
.any(|schema| has_reference_schema(Some(schema))),
|
.any(|schema| has_reference_schema(Some(schema))),
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ use serde_json::Value;
|
|||||||
|
|
||||||
use crate::rest::{
|
use crate::rest::{
|
||||||
model::{
|
model::{
|
||||||
ImportFinding, ImportFindingSeverity, RestImportDocument, RestImportOperation,
|
ImportFinding, RestImportDocument, RestImportOperation, RestImportParameter,
|
||||||
RestImportParameter, RestParameterLocation,
|
RestParameterLocation, RestRequestBodyVariant, RestResponseVariant,
|
||||||
},
|
},
|
||||||
normalize::ImportParseError,
|
normalize::ImportParseError,
|
||||||
recommendations::{document_blocker, document_finding},
|
recommendations::{document_blocker, document_finding},
|
||||||
@@ -27,6 +27,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
|||||||
let mut findings = Vec::new();
|
let mut findings = Vec::new();
|
||||||
let mut internal_finding_locations = Vec::new();
|
let mut internal_finding_locations = Vec::new();
|
||||||
let servers = parse_servers(root.get("servers"), "/servers");
|
let servers = parse_servers(root.get("servers"), "/servers");
|
||||||
|
let security_schemes = super::security::schemes(root, false);
|
||||||
append_findings_with_locations(
|
append_findings_with_locations(
|
||||||
&mut findings,
|
&mut findings,
|
||||||
&mut internal_finding_locations,
|
&mut internal_finding_locations,
|
||||||
@@ -59,13 +60,13 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
|||||||
|
|
||||||
for (path, path_item) in paths {
|
for (path, path_item) in paths {
|
||||||
if !path_item.is_object() {
|
if !path_item.is_object() {
|
||||||
findings.push(path_item_blocker(path));
|
findings.push(super::http_methods::invalid_path_item());
|
||||||
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
|
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
|
||||||
pointer: format!("/paths/{}", path.replace('~', "~0").replace('/', "~1")),
|
pointer: format!("/paths/{}", path.replace('~', "~0").replace('/', "~1")),
|
||||||
}));
|
}));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
for method_name in ["head", "options", "trace", "connect"] {
|
for method_name in super::openapi3_findings::unsupported_methods(path_item) {
|
||||||
if path_item.get(method_name).is_some() {
|
if path_item.get(method_name).is_some() {
|
||||||
findings.push(document_blocker(
|
findings.push(document_blocker(
|
||||||
"unsupported_http_method",
|
"unsupported_http_method",
|
||||||
@@ -99,7 +100,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
|||||||
path_servers.findings,
|
path_servers.findings,
|
||||||
);
|
);
|
||||||
let path_servers = path_servers.servers;
|
let path_servers = path_servers.servers;
|
||||||
for method_name in ["get", "post", "put", "patch", "delete"] {
|
for method_name in ["get", "post", "put", "patch", "delete", "head", "options"] {
|
||||||
let Some(operation_value) = path_item.get(method_name) else {
|
let Some(operation_value) = path_item.get(method_name) else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
@@ -117,7 +118,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
|||||||
}));
|
}));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let Some(method) = method_from_lower(method_name) else {
|
let Some(method) = super::http_methods::from_lower(method_name) else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
let operation_pointer = format!("{path_pointer}/{method_name}");
|
let operation_pointer = format!("{path_pointer}/{method_name}");
|
||||||
@@ -154,10 +155,29 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
|||||||
tags.findings,
|
tags.findings,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
let mut located_operation_findings =
|
||||||
|
super::openapi3_findings::operation(operation_value, &operation_pointer);
|
||||||
|
let security_requirements = super::security::collect_operation_requirements(
|
||||||
|
root,
|
||||||
|
operation_value,
|
||||||
|
&operation_pointer,
|
||||||
|
&security_schemes,
|
||||||
|
&mut located_operation_findings,
|
||||||
|
);
|
||||||
|
located_operation_findings.extend(super::openapi3_findings::path_parameters(
|
||||||
|
path,
|
||||||
|
&operation_parameters,
|
||||||
|
));
|
||||||
|
let (operation_findings, internal_finding_locations) =
|
||||||
|
located_operation_findings.into_iter().unzip();
|
||||||
|
let response_schema = (method != HttpMethod::Head)
|
||||||
|
.then(|| response_schema(operation_value, &operation_pointer))
|
||||||
|
.flatten();
|
||||||
operations.push(RestImportOperation {
|
operations.push(RestImportOperation {
|
||||||
key: format!("{} {}", method_name.to_uppercase(), path),
|
key: format!("{} {}", method_name.to_uppercase(), path),
|
||||||
method,
|
method,
|
||||||
path: path.clone(),
|
path: path.clone(),
|
||||||
|
security_requirements,
|
||||||
operation_id: operation_value
|
operation_id: operation_value
|
||||||
.get("operationId")
|
.get("operationId")
|
||||||
.and_then(Value::as_str)
|
.and_then(Value::as_str)
|
||||||
@@ -179,16 +199,17 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
|||||||
&operation_pointer,
|
&operation_pointer,
|
||||||
)
|
)
|
||||||
.map(|(_, location)| location),
|
.map(|(_, location)| location),
|
||||||
response_schema: response_schema(operation_value, &operation_pointer)
|
request_body_variants: request_body_variants(operation_value, &operation_pointer),
|
||||||
.map(|(schema, _)| schema),
|
response_schema: response_schema.as_ref().map(|(schema, _)| schema.clone()),
|
||||||
response_schema_location: response_schema(operation_value, &operation_pointer)
|
response_schema_location: response_schema.map(|(_, location)| location),
|
||||||
.map(|(_, location)| location),
|
response_variants: response_variants(operation_value, &operation_pointer, method),
|
||||||
servers: if operation_servers.is_empty() {
|
servers: if operation_servers.is_empty() {
|
||||||
path_servers.clone()
|
path_servers.clone()
|
||||||
} else {
|
} else {
|
||||||
operation_servers
|
operation_servers
|
||||||
},
|
},
|
||||||
findings: operation_findings(operation_value),
|
findings: operation_findings,
|
||||||
|
internal_finding_locations,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -198,6 +219,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
|||||||
version,
|
version,
|
||||||
title,
|
title,
|
||||||
servers,
|
servers,
|
||||||
|
security_schemes,
|
||||||
operations,
|
operations,
|
||||||
findings,
|
findings,
|
||||||
internal_finding_locations,
|
internal_finding_locations,
|
||||||
@@ -211,225 +233,6 @@ fn deduplicate_parameters(parameters: &mut Vec<RestImportParameter>) {
|
|||||||
parameters.reverse();
|
parameters.reverse();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn parse_document_legacy_v1(root: &Value) -> Result<RestImportDocument, ImportParseError> {
|
|
||||||
let version = root
|
|
||||||
.get("openapi")
|
|
||||||
.and_then(Value::as_str)
|
|
||||||
.map(ToOwned::to_owned);
|
|
||||||
let title = root
|
|
||||||
.pointer("/info/title")
|
|
||||||
.and_then(Value::as_str)
|
|
||||||
.unwrap_or("Imported API")
|
|
||||||
.to_owned();
|
|
||||||
let servers = legacy_servers(root.get("servers"));
|
|
||||||
let mut findings = Vec::new();
|
|
||||||
if servers.is_empty() {
|
|
||||||
findings.push(document_finding(
|
|
||||||
"missing_servers",
|
|
||||||
"В документе не указаны servers, base URL нужно будет выбрать вручную.",
|
|
||||||
));
|
|
||||||
} else if servers.len() > 1 {
|
|
||||||
findings.push(document_finding(
|
|
||||||
"multiple_servers",
|
|
||||||
"В документе несколько servers, при импорте нужно выбрать нужный base URL.",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut operations = Vec::new();
|
|
||||||
let paths = root
|
|
||||||
.get("paths")
|
|
||||||
.and_then(Value::as_object)
|
|
||||||
.ok_or(ImportParseError::UnsupportedDocument)?;
|
|
||||||
for (path, path_item) in paths {
|
|
||||||
let path_pointer = format!("/paths/{}", path.replace('~', "~0").replace('/', "~1"));
|
|
||||||
let path_parameters = legacy_parameters(
|
|
||||||
root,
|
|
||||||
path_item.get("parameters"),
|
|
||||||
&format!("{path_pointer}/parameters"),
|
|
||||||
);
|
|
||||||
for method_name in ["get", "post", "put", "patch", "delete"] {
|
|
||||||
let Some(operation) = path_item.get(method_name) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let Some(method) = method_from_lower(method_name) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let operation_pointer = format!("{path_pointer}/{method_name}");
|
|
||||||
let mut parameters = path_parameters.clone();
|
|
||||||
parameters.extend(legacy_parameters(
|
|
||||||
root,
|
|
||||||
operation.get("parameters"),
|
|
||||||
&format!("{operation_pointer}/parameters"),
|
|
||||||
));
|
|
||||||
operations.push(RestImportOperation {
|
|
||||||
key: format!("{} {}", method_name.to_uppercase(), path),
|
|
||||||
method,
|
|
||||||
path: path.clone(),
|
|
||||||
operation_id: operation
|
|
||||||
.get("operationId")
|
|
||||||
.and_then(Value::as_str)
|
|
||||||
.map(ToOwned::to_owned),
|
|
||||||
summary: operation
|
|
||||||
.get("summary")
|
|
||||||
.and_then(Value::as_str)
|
|
||||||
.map(ToOwned::to_owned),
|
|
||||||
description: operation
|
|
||||||
.get("description")
|
|
||||||
.and_then(Value::as_str)
|
|
||||||
.map(ToOwned::to_owned),
|
|
||||||
tags: legacy_tags(operation.get("tags")),
|
|
||||||
parameters,
|
|
||||||
request_body_schema: legacy_request_body_schema(root, operation),
|
|
||||||
request_body_schema_location: None,
|
|
||||||
response_schema: legacy_response_schema(root, operation),
|
|
||||||
response_schema_location: None,
|
|
||||||
servers: legacy_servers(operation.get("servers")),
|
|
||||||
findings: legacy_operation_findings(operation),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(RestImportDocument {
|
|
||||||
format: "openapi".to_owned(),
|
|
||||||
version,
|
|
||||||
title,
|
|
||||||
servers,
|
|
||||||
operations,
|
|
||||||
findings,
|
|
||||||
internal_finding_locations: Vec::new(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn legacy_servers(value: Option<&Value>) -> Vec<String> {
|
|
||||||
value
|
|
||||||
.and_then(Value::as_array)
|
|
||||||
.map(|items| {
|
|
||||||
items
|
|
||||||
.iter()
|
|
||||||
.filter_map(|item| item.get("url").and_then(Value::as_str))
|
|
||||||
.map(|url| url.trim_end_matches('/').to_owned())
|
|
||||||
.collect()
|
|
||||||
})
|
|
||||||
.unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn legacy_tags(value: Option<&Value>) -> Vec<String> {
|
|
||||||
value
|
|
||||||
.and_then(Value::as_array)
|
|
||||||
.map(|items| {
|
|
||||||
items
|
|
||||||
.iter()
|
|
||||||
.filter_map(Value::as_str)
|
|
||||||
.map(ToOwned::to_owned)
|
|
||||||
.collect()
|
|
||||||
})
|
|
||||||
.unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn legacy_parameters(
|
|
||||||
root: &Value,
|
|
||||||
value: Option<&Value>,
|
|
||||||
base_pointer: &str,
|
|
||||||
) -> Vec<RestImportParameter> {
|
|
||||||
value
|
|
||||||
.and_then(Value::as_array)
|
|
||||||
.map(|items| {
|
|
||||||
items
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.filter_map(|(index, item)| {
|
|
||||||
let item = crate::rest::normalize::resolve_local_ref(root, item, 0);
|
|
||||||
let location = match item.get("in").and_then(Value::as_str)? {
|
|
||||||
"path" => RestParameterLocation::Path,
|
|
||||||
"query" => RestParameterLocation::Query,
|
|
||||||
"header" => RestParameterLocation::Header,
|
|
||||||
_ => return None,
|
|
||||||
};
|
|
||||||
Some(RestImportParameter {
|
|
||||||
name: item.get("name").and_then(Value::as_str)?.to_owned(),
|
|
||||||
location,
|
|
||||||
required: item
|
|
||||||
.get("required")
|
|
||||||
.and_then(Value::as_bool)
|
|
||||||
.unwrap_or(false)
|
|
||||||
|| location == RestParameterLocation::Path,
|
|
||||||
description: item
|
|
||||||
.get("description")
|
|
||||||
.and_then(Value::as_str)
|
|
||||||
.map(ToOwned::to_owned),
|
|
||||||
schema: item.get("schema").map(|schema| {
|
|
||||||
crate::rest::normalize::resolve_local_ref(root, schema, 0)
|
|
||||||
}),
|
|
||||||
source_location: crate::rest::model::SourceLocation {
|
|
||||||
pointer: format!("{base_pointer}/{index}"),
|
|
||||||
},
|
|
||||||
schema_source_location: None,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
})
|
|
||||||
.unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn legacy_request_body_schema(root: &Value, operation: &Value) -> Option<Value> {
|
|
||||||
let body = crate::rest::normalize::resolve_local_ref(root, operation.get("requestBody")?, 0);
|
|
||||||
let content = body.get("content")?.as_object()?;
|
|
||||||
for content_type in ["application/json", "application/*+json"] {
|
|
||||||
if let Some(schema) = content
|
|
||||||
.get(content_type)
|
|
||||||
.and_then(|media| media.get("schema"))
|
|
||||||
{
|
|
||||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
content
|
|
||||||
.iter()
|
|
||||||
.find(|(content_type, _)| content_type.contains("json"))
|
|
||||||
.and_then(|(_, media)| media.get("schema"))
|
|
||||||
.map(|schema| crate::rest::normalize::resolve_local_ref(root, schema, 0))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn legacy_response_schema(root: &Value, operation: &Value) -> Option<Value> {
|
|
||||||
let responses = operation.get("responses")?.as_object()?;
|
|
||||||
for code in ["200", "201", "202", "default"] {
|
|
||||||
let Some(response) = responses.get(code) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let response = crate::rest::normalize::resolve_local_ref(root, response, 0);
|
|
||||||
let Some(content) = response.get("content").and_then(Value::as_object) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
for content_type in ["application/json", "application/*+json"] {
|
|
||||||
if let Some(schema) = content
|
|
||||||
.get(content_type)
|
|
||||||
.and_then(|media| media.get("schema"))
|
|
||||||
{
|
|
||||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if let Some(schema) = content
|
|
||||||
.iter()
|
|
||||||
.find(|(content_type, _)| content_type.contains("json"))
|
|
||||||
.and_then(|(_, media)| media.get("schema"))
|
|
||||||
{
|
|
||||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
fn legacy_operation_findings(operation: &Value) -> Vec<ImportFinding> {
|
|
||||||
if operation.get("requestBody").is_some()
|
|
||||||
&& legacy_request_body_schema(&Value::Null, operation).is_none()
|
|
||||||
{
|
|
||||||
vec![document_finding(
|
|
||||||
"unsupported_request_body",
|
|
||||||
"У метода есть requestBody, но JSON schema не найдена.",
|
|
||||||
)]
|
|
||||||
} else {
|
|
||||||
Vec::new()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct ParsedParameters {
|
struct ParsedParameters {
|
||||||
parameters: Vec<RestImportParameter>,
|
parameters: Vec<RestImportParameter>,
|
||||||
findings: Vec<(ImportFinding, crate::rest::model::SourceLocation)>,
|
findings: Vec<(ImportFinding, crate::rest::model::SourceLocation)>,
|
||||||
@@ -458,6 +261,10 @@ fn parse_servers(value: Option<&Value>, base_pointer: &str) -> ParsedServers {
|
|||||||
findings.push(server_blocker(&pointer));
|
findings.push(server_blocker(&pointer));
|
||||||
return None;
|
return None;
|
||||||
};
|
};
|
||||||
|
if !super::openapi3_findings::valid_http_server_url(url) {
|
||||||
|
findings.push(server_blocker(&format!("{pointer}/url")));
|
||||||
|
return None;
|
||||||
|
}
|
||||||
Some(url.trim_end_matches('/').to_owned())
|
Some(url.trim_end_matches('/').to_owned())
|
||||||
})
|
})
|
||||||
.collect()
|
.collect()
|
||||||
@@ -559,14 +366,7 @@ fn parameters(value: Option<&Value>, base_pointer: &str) -> ParsedParameters {
|
|||||||
"path" => RestParameterLocation::Path,
|
"path" => RestParameterLocation::Path,
|
||||||
"query" => RestParameterLocation::Query,
|
"query" => RestParameterLocation::Query,
|
||||||
"header" => RestParameterLocation::Header,
|
"header" => RestParameterLocation::Header,
|
||||||
"cookie" => {
|
"cookie" => RestParameterLocation::Cookie,
|
||||||
findings.push(parameter_blocker(
|
|
||||||
"unsupported_cookie_parameter",
|
|
||||||
"Cookie parameter пока не поддерживается и не был импортирован.",
|
|
||||||
&pointer,
|
|
||||||
));
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
_ => {
|
_ => {
|
||||||
findings.push(parameter_blocker(
|
findings.push(parameter_blocker(
|
||||||
"unsupported_parameter_location",
|
"unsupported_parameter_location",
|
||||||
@@ -576,14 +376,81 @@ fn parameters(value: Option<&Value>, base_pointer: &str) -> ParsedParameters {
|
|||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
let expected_style = match location {
|
||||||
|
RestParameterLocation::Path | RestParameterLocation::Header => "simple",
|
||||||
|
RestParameterLocation::Query | RestParameterLocation::Cookie => "form",
|
||||||
|
};
|
||||||
|
if item
|
||||||
|
.get("style")
|
||||||
|
.is_some_and(|style| style.as_str() != Some(expected_style))
|
||||||
|
{
|
||||||
|
findings.push(parameter_blocker(
|
||||||
|
"unsupported_parameter_style",
|
||||||
|
"Параметр использует style, который текущий REST mapping не сериализует без потерь.",
|
||||||
|
&format!("{pointer}/style"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let default_explode = matches!(
|
||||||
|
location,
|
||||||
|
RestParameterLocation::Query | RestParameterLocation::Cookie
|
||||||
|
);
|
||||||
|
if item
|
||||||
|
.get("explode")
|
||||||
|
.is_some_and(|explode| explode.as_bool() != Some(default_explode))
|
||||||
|
{
|
||||||
|
findings.push(parameter_blocker(
|
||||||
|
"unsupported_parameter_style",
|
||||||
|
"Параметр использует explode, который текущий REST mapping не сериализует без потерь.",
|
||||||
|
&format!("{pointer}/explode"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if item
|
||||||
|
.get("allowReserved")
|
||||||
|
.is_some_and(|value| value.as_bool() != Some(false))
|
||||||
|
{
|
||||||
|
findings.push(parameter_blocker(
|
||||||
|
"unsupported_parameter_style",
|
||||||
|
"allowReserved=true не поддерживается текущим REST mapping.",
|
||||||
|
&format!("{pointer}/allowReserved"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if item.get("content").is_some() {
|
||||||
|
findings.push(parameter_blocker(
|
||||||
|
"unsupported_parameter_content",
|
||||||
|
"Parameter content не поддерживается текущим REST mapping.",
|
||||||
|
&format!("{pointer}/content"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if item.get("schema").is_none() && item.get("content").is_none() {
|
||||||
|
findings.push(parameter_blocker(
|
||||||
|
"missing_parameter_schema",
|
||||||
|
"Параметр не содержит schema.",
|
||||||
|
&pointer,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if item.get("schema").is_some_and(|schema| {
|
||||||
|
matches!(schema.get("type").and_then(Value::as_str), Some("array" | "object"))
|
||||||
|
}) {
|
||||||
|
findings.push(parameter_blocker(
|
||||||
|
"unsupported_parameter_style",
|
||||||
|
"Array/object parameter serialization не поддерживается текущим REST mapping.",
|
||||||
|
&format!("{pointer}/schema"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if let Some(schema) = item.get("schema") {
|
||||||
|
super::openapi3_findings::schema_findings(
|
||||||
|
schema,
|
||||||
|
&format!("{pointer}/schema"),
|
||||||
|
&mut findings,
|
||||||
|
);
|
||||||
|
}
|
||||||
Some(RestImportParameter {
|
Some(RestImportParameter {
|
||||||
name: item.get("name").and_then(Value::as_str)?.to_owned(),
|
name: item.get("name").and_then(Value::as_str)?.to_owned(),
|
||||||
location,
|
location,
|
||||||
required: item
|
required: item
|
||||||
.get("required")
|
.get("required")
|
||||||
.and_then(Value::as_bool)
|
.and_then(Value::as_bool)
|
||||||
.unwrap_or(false)
|
.unwrap_or(false),
|
||||||
|| location == RestParameterLocation::Path,
|
|
||||||
description: item
|
description: item
|
||||||
.get("description")
|
.get("description")
|
||||||
.and_then(Value::as_str)
|
.and_then(Value::as_str)
|
||||||
@@ -672,6 +539,87 @@ fn request_body_schema(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn request_body_variants(
|
||||||
|
operation: &Value,
|
||||||
|
operation_pointer: &str,
|
||||||
|
) -> Vec<RestRequestBodyVariant> {
|
||||||
|
let Some(body) = operation.get("requestBody") else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let required = body
|
||||||
|
.get("required")
|
||||||
|
.and_then(Value::as_bool)
|
||||||
|
.unwrap_or(false);
|
||||||
|
let Some(content) = body.get("content").and_then(Value::as_object) else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
content
|
||||||
|
.iter()
|
||||||
|
.filter(|(content_type, media)| {
|
||||||
|
supported_request_content_type(content_type) && media.get("schema").is_some()
|
||||||
|
})
|
||||||
|
.map(|(content_type, media)| RestRequestBodyVariant {
|
||||||
|
content_type: content_type.clone(),
|
||||||
|
required,
|
||||||
|
schema: media.get("schema").cloned(),
|
||||||
|
multipart_field_mime_types: if content_type == "multipart/form-data" {
|
||||||
|
multipart_field_mime_types(media)
|
||||||
|
} else {
|
||||||
|
Default::default()
|
||||||
|
},
|
||||||
|
source_location: crate::rest::model::SourceLocation {
|
||||||
|
pointer: format!(
|
||||||
|
"{operation_pointer}/requestBody/content/{}",
|
||||||
|
content_type.replace('~', "~0").replace('/', "~1")
|
||||||
|
),
|
||||||
|
},
|
||||||
|
schema_source_location: media.get("schema").map(|_| {
|
||||||
|
crate::rest::model::SourceLocation {
|
||||||
|
pointer: format!(
|
||||||
|
"{operation_pointer}/requestBody/content/{}/schema",
|
||||||
|
content_type.replace('~', "~0").replace('/', "~1")
|
||||||
|
),
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
schema_property_source_locations: Default::default(),
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn multipart_field_mime_types(media: &Value) -> std::collections::BTreeMap<String, Vec<String>> {
|
||||||
|
media
|
||||||
|
.get("encoding")
|
||||||
|
.and_then(Value::as_object)
|
||||||
|
.map(|encoding| {
|
||||||
|
encoding
|
||||||
|
.iter()
|
||||||
|
.filter_map(|(field, value)| {
|
||||||
|
let mime_types = value
|
||||||
|
.get("contentType")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.map(|value| {
|
||||||
|
value
|
||||||
|
.split(',')
|
||||||
|
.map(str::trim)
|
||||||
|
.filter(|value| !value.is_empty())
|
||||||
|
.map(ToOwned::to_owned)
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
})
|
||||||
|
.unwrap_or_default();
|
||||||
|
(!mime_types.is_empty()).then(|| (field.clone(), mime_types))
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn supported_request_content_type(content_type: &str) -> bool {
|
||||||
|
content_type == "application/x-www-form-urlencoded"
|
||||||
|
|| content_type == "multipart/form-data"
|
||||||
|
|| content_type == "application/json"
|
||||||
|
|| content_type.ends_with("+json")
|
||||||
|
}
|
||||||
|
|
||||||
fn response_schema(
|
fn response_schema(
|
||||||
operation: &Value,
|
operation: &Value,
|
||||||
operation_pointer: &str,
|
operation_pointer: &str,
|
||||||
@@ -752,33 +700,85 @@ fn response_json_schema(
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn operation_findings(operation: &Value) -> Vec<ImportFinding> {
|
fn response_variants(
|
||||||
let mut findings = Vec::new();
|
operation: &Value,
|
||||||
if operation.get("requestBody").is_some() && request_body_schema(operation, "").is_none() {
|
operation_pointer: &str,
|
||||||
findings.push(document_finding(
|
method: HttpMethod,
|
||||||
"unsupported_request_body",
|
) -> Vec<RestResponseVariant> {
|
||||||
"У метода есть requestBody, но JSON schema не найдена.",
|
let Some(responses) = operation.get("responses").and_then(Value::as_object) else {
|
||||||
));
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let mut variants = responses
|
||||||
|
.iter()
|
||||||
|
.filter_map(|(code, response)| {
|
||||||
|
let status_code = code
|
||||||
|
.parse::<u16>()
|
||||||
|
.ok()
|
||||||
|
.filter(|code| (200..300).contains(code))?;
|
||||||
|
let base = format!(
|
||||||
|
"{operation_pointer}/responses/{}",
|
||||||
|
code.replace('~', "~0").replace('/', "~1")
|
||||||
|
);
|
||||||
|
if method == HttpMethod::Head {
|
||||||
|
return Some(vec![RestResponseVariant {
|
||||||
|
status_code,
|
||||||
|
content_type: None,
|
||||||
|
schema: None,
|
||||||
|
source_location: crate::rest::model::SourceLocation { pointer: base },
|
||||||
|
schema_source_location: None,
|
||||||
|
}]);
|
||||||
}
|
}
|
||||||
findings
|
let content = response.get("content").and_then(Value::as_object);
|
||||||
}
|
Some(match content {
|
||||||
|
None => vec![RestResponseVariant {
|
||||||
fn method_from_lower(value: &str) -> Option<HttpMethod> {
|
status_code,
|
||||||
match value {
|
content_type: None,
|
||||||
"get" => Some(HttpMethod::Get),
|
schema: None,
|
||||||
"post" => Some(HttpMethod::Post),
|
source_location: crate::rest::model::SourceLocation { pointer: base },
|
||||||
"put" => Some(HttpMethod::Put),
|
schema_source_location: None,
|
||||||
"patch" => Some(HttpMethod::Patch),
|
}],
|
||||||
"delete" => Some(HttpMethod::Delete),
|
Some(content) if content.is_empty() => vec![RestResponseVariant {
|
||||||
_ => None,
|
status_code,
|
||||||
}
|
content_type: None,
|
||||||
}
|
schema: None,
|
||||||
|
source_location: crate::rest::model::SourceLocation { pointer: base },
|
||||||
fn path_item_blocker(_path: &str) -> ImportFinding {
|
schema_source_location: None,
|
||||||
ImportFinding {
|
}],
|
||||||
code: "invalid_path_item".to_owned(),
|
Some(content) => content
|
||||||
severity: ImportFindingSeverity::Error,
|
.iter()
|
||||||
message: "Path Item имеет неверную структуру и не был интерпретирован.".to_owned(),
|
.filter(|(content_type, _)| {
|
||||||
operation_key: None,
|
*content_type == "application/json" || content_type.ends_with("+json")
|
||||||
|
})
|
||||||
|
.filter(|(_, media)| media.get("schema").is_some())
|
||||||
|
.map(|(content_type, media)| RestResponseVariant {
|
||||||
|
status_code,
|
||||||
|
content_type: Some(content_type.clone()),
|
||||||
|
schema: media.get("schema").cloned(),
|
||||||
|
source_location: crate::rest::model::SourceLocation {
|
||||||
|
pointer: format!(
|
||||||
|
"{base}/content/{}",
|
||||||
|
content_type.replace('~', "~0").replace('/', "~1")
|
||||||
|
),
|
||||||
|
},
|
||||||
|
schema_source_location: media.get("schema").map(|_| {
|
||||||
|
crate::rest::model::SourceLocation {
|
||||||
|
pointer: format!(
|
||||||
|
"{base}/content/{}/schema",
|
||||||
|
content_type.replace('~', "~0").replace('/', "~1")
|
||||||
|
),
|
||||||
}
|
}
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.flatten()
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
variants.sort_by(|left, right| {
|
||||||
|
(left.status_code, left.content_type.as_deref().unwrap_or("")).cmp(&(
|
||||||
|
right.status_code,
|
||||||
|
right.content_type.as_deref().unwrap_or(""),
|
||||||
|
))
|
||||||
|
});
|
||||||
|
variants
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,485 @@
|
|||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
use crate::rest::{
|
||||||
|
model::{ImportFinding, RestImportParameter, RestParameterLocation, SourceLocation},
|
||||||
|
recommendations::document_blocker,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub(super) fn operation(
|
||||||
|
operation: &Value,
|
||||||
|
operation_pointer: &str,
|
||||||
|
) -> Vec<(ImportFinding, SourceLocation)> {
|
||||||
|
let mut findings = Vec::new();
|
||||||
|
if operation.get("requestBody").is_some() && supported_request_variants(operation) == 0 {
|
||||||
|
push(
|
||||||
|
&mut findings,
|
||||||
|
"unsupported_request_body",
|
||||||
|
"У requestBody нет поддерживаемой schema.",
|
||||||
|
&format!("{operation_pointer}/requestBody"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if let Some(content) = operation
|
||||||
|
.pointer("/requestBody/content")
|
||||||
|
.and_then(Value::as_object)
|
||||||
|
{
|
||||||
|
for (content_type, media) in content {
|
||||||
|
let media_pointer = format!(
|
||||||
|
"{operation_pointer}/requestBody/content/{}",
|
||||||
|
escape(content_type)
|
||||||
|
);
|
||||||
|
if !supported_request_media(content_type) {
|
||||||
|
let code = if content_type.contains("xml") {
|
||||||
|
"unsupported_xml_request_media_type"
|
||||||
|
} else {
|
||||||
|
"unsupported_request_media_type"
|
||||||
|
};
|
||||||
|
push(
|
||||||
|
&mut findings,
|
||||||
|
code,
|
||||||
|
"Request media type не поддерживается без fallback.",
|
||||||
|
&media_pointer,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if supported_request_media(content_type) && media.get("schema").is_none() {
|
||||||
|
push(
|
||||||
|
&mut findings,
|
||||||
|
"missing_request_media_schema",
|
||||||
|
"Request media type не содержит schema.",
|
||||||
|
&media_pointer,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if let Some(schema) = media.get("schema") {
|
||||||
|
schema_findings(schema, &format!("{media_pointer}/schema"), &mut findings);
|
||||||
|
}
|
||||||
|
if matches!(
|
||||||
|
content_type.as_str(),
|
||||||
|
"application/x-www-form-urlencoded" | "multipart/form-data"
|
||||||
|
) && let Some(schema) = media.get("schema")
|
||||||
|
{
|
||||||
|
form_schema_findings(schema, &format!("{media_pointer}/schema"), &mut findings);
|
||||||
|
}
|
||||||
|
if content_type == "application/x-www-form-urlencoded" {
|
||||||
|
form_encoding_findings(media, &media_pointer, &mut findings);
|
||||||
|
}
|
||||||
|
if content_type == "multipart/form-data" {
|
||||||
|
multipart_encoding_findings(media, &media_pointer, &mut findings);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(responses) = operation.get("responses").and_then(Value::as_object) {
|
||||||
|
for (status, response) in responses {
|
||||||
|
let Some(content) = response.get("content").and_then(Value::as_object) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
for (content_type, media) in content {
|
||||||
|
let media_pointer = format!(
|
||||||
|
"{operation_pointer}/responses/{}/content/{}",
|
||||||
|
escape(status),
|
||||||
|
escape(content_type)
|
||||||
|
);
|
||||||
|
if !supported_response_media(content_type) {
|
||||||
|
let code = if content_type.contains("xml") {
|
||||||
|
"unsupported_xml_response_media_type"
|
||||||
|
} else {
|
||||||
|
"unsupported_response_media_type"
|
||||||
|
};
|
||||||
|
push(
|
||||||
|
&mut findings,
|
||||||
|
code,
|
||||||
|
"Response media type не поддерживается без fallback.",
|
||||||
|
&media_pointer,
|
||||||
|
);
|
||||||
|
} else if let Some(schema) = media.get("schema") {
|
||||||
|
schema_findings(schema, &format!("{media_pointer}/schema"), &mut findings);
|
||||||
|
} else {
|
||||||
|
push(
|
||||||
|
&mut findings,
|
||||||
|
"missing_response_media_schema",
|
||||||
|
"Response media type не содержит schema.",
|
||||||
|
&media_pointer,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
findings
|
||||||
|
}
|
||||||
|
|
||||||
|
fn form_encoding_findings(
|
||||||
|
media: &Value,
|
||||||
|
media_pointer: &str,
|
||||||
|
findings: &mut Vec<(ImportFinding, SourceLocation)>,
|
||||||
|
) {
|
||||||
|
let Some(encoding_value) = media.get("encoding") else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let Some(encoding) = encoding_value.as_object() else {
|
||||||
|
push(
|
||||||
|
findings,
|
||||||
|
"unsupported_form_encoding",
|
||||||
|
"Form encoding должен быть объектом.",
|
||||||
|
&format!("{media_pointer}/encoding"),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
for (field, settings) in encoding {
|
||||||
|
let field_pointer = format!("{media_pointer}/encoding/{}", escape(field));
|
||||||
|
let Some(settings) = settings.as_object() else {
|
||||||
|
push(
|
||||||
|
findings,
|
||||||
|
"unsupported_form_encoding",
|
||||||
|
"Form encoding имеет неподдерживаемую структуру.",
|
||||||
|
&field_pointer,
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
for (key, value) in settings {
|
||||||
|
let supported = match key.as_str() {
|
||||||
|
"style" => value.as_str() == Some("form"),
|
||||||
|
"explode" => value.as_bool() == Some(true),
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
if !supported {
|
||||||
|
push(
|
||||||
|
findings,
|
||||||
|
"unsupported_form_encoding",
|
||||||
|
"Form encoding metadata не поддерживается wire contract.",
|
||||||
|
&format!("{field_pointer}/{}", escape(key)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn form_schema_findings(
|
||||||
|
schema: &Value,
|
||||||
|
pointer: &str,
|
||||||
|
findings: &mut Vec<(ImportFinding, SourceLocation)>,
|
||||||
|
) {
|
||||||
|
if !object_schema(schema) {
|
||||||
|
push(
|
||||||
|
findings,
|
||||||
|
"unsupported_form_schema",
|
||||||
|
"Form body должен быть object со scalar, file или array полями.",
|
||||||
|
pointer,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if let Some(properties) = schema.get("properties").and_then(Value::as_object) {
|
||||||
|
for (name, property) in properties {
|
||||||
|
form_field_schema_findings(
|
||||||
|
property,
|
||||||
|
&format!("{pointer}/properties/{}", escape(name)),
|
||||||
|
findings,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn form_field_schema_findings(
|
||||||
|
schema: &Value,
|
||||||
|
pointer: &str,
|
||||||
|
findings: &mut Vec<(ImportFinding, SourceLocation)>,
|
||||||
|
) {
|
||||||
|
form_field_schema_findings_inner(schema, pointer, true, findings);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn form_field_schema_findings_inner(
|
||||||
|
schema: &Value,
|
||||||
|
pointer: &str,
|
||||||
|
array_allowed: bool,
|
||||||
|
findings: &mut Vec<(ImportFinding, SourceLocation)>,
|
||||||
|
) {
|
||||||
|
if object_schema(schema) {
|
||||||
|
push(
|
||||||
|
findings,
|
||||||
|
"unsupported_form_schema",
|
||||||
|
"Вложенный object field не поддерживается form wire contract.",
|
||||||
|
pointer,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if schema.get("type").and_then(Value::as_str) == Some("array") {
|
||||||
|
if !array_allowed {
|
||||||
|
push(
|
||||||
|
findings,
|
||||||
|
"unsupported_form_schema",
|
||||||
|
"Вложенные arrays не поддерживаются form wire contract.",
|
||||||
|
pointer,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if let Some(items) = schema.get("items") {
|
||||||
|
form_field_schema_findings_inner(items, &format!("{pointer}/items"), false, findings);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for operator in ["allOf", "oneOf", "anyOf"] {
|
||||||
|
if let Some(variants) = schema.get(operator).and_then(Value::as_array) {
|
||||||
|
for (index, variant) in variants.iter().enumerate() {
|
||||||
|
form_field_schema_findings_inner(
|
||||||
|
variant,
|
||||||
|
&format!("{pointer}/{operator}/{index}"),
|
||||||
|
array_allowed,
|
||||||
|
findings,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn object_schema(schema: &Value) -> bool {
|
||||||
|
schema.get("properties").is_some()
|
||||||
|
|| schema.get("type").and_then(Value::as_str) == Some("object")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn multipart_encoding_findings(
|
||||||
|
media: &Value,
|
||||||
|
media_pointer: &str,
|
||||||
|
findings: &mut Vec<(ImportFinding, SourceLocation)>,
|
||||||
|
) {
|
||||||
|
let Some(encoding_value) = media.get("encoding") else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let Some(encoding) = encoding_value.as_object() else {
|
||||||
|
push(
|
||||||
|
findings,
|
||||||
|
"unsupported_multipart_encoding",
|
||||||
|
"Multipart encoding должен быть объектом.",
|
||||||
|
&format!("{media_pointer}/encoding"),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
for (field, settings) in encoding {
|
||||||
|
let field_pointer = format!("{media_pointer}/encoding/{}", escape(field));
|
||||||
|
let Some(settings) = settings.as_object() else {
|
||||||
|
push(
|
||||||
|
findings,
|
||||||
|
"unsupported_multipart_encoding",
|
||||||
|
"Multipart encoding имеет неподдерживаемую структуру.",
|
||||||
|
&field_pointer,
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
for key in settings.keys().filter(|key| key.as_str() != "contentType") {
|
||||||
|
push(
|
||||||
|
findings,
|
||||||
|
"unsupported_multipart_encoding",
|
||||||
|
"Multipart encoding metadata не поддерживается wire contract.",
|
||||||
|
&format!("{field_pointer}/{}", escape(key)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if let Some(content_type) = settings.get("contentType") {
|
||||||
|
let source_field = media.pointer(&format!("/schema/properties/{}", escape(field)));
|
||||||
|
let invalid_mime = content_type.as_str().is_none_or(|value| {
|
||||||
|
value.split(',').map(str::trim).any(|mime| {
|
||||||
|
mime.is_empty() || !mime.contains('/') || mime.chars().any(char::is_control)
|
||||||
|
})
|
||||||
|
});
|
||||||
|
if invalid_mime || !source_field.is_some_and(binary_schema) {
|
||||||
|
push(
|
||||||
|
findings,
|
||||||
|
"unsupported_multipart_encoding",
|
||||||
|
"Multipart contentType поддерживается только для binary/file field с валидным MIME.",
|
||||||
|
&format!("{field_pointer}/contentType"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn binary_schema(schema: &Value) -> bool {
|
||||||
|
schema.get("type").and_then(Value::as_str) == Some("string")
|
||||||
|
&& schema.get("format").and_then(Value::as_str) == Some("binary")
|
||||||
|
|| schema.get("type").and_then(Value::as_str) == Some("array")
|
||||||
|
&& schema.get("items").is_some_and(binary_schema)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn schema_findings(
|
||||||
|
schema: &Value,
|
||||||
|
pointer: &str,
|
||||||
|
findings: &mut Vec<(ImportFinding, SourceLocation)>,
|
||||||
|
) {
|
||||||
|
if let Some(types) = schema.get("type").and_then(Value::as_array) {
|
||||||
|
let concrete = types
|
||||||
|
.iter()
|
||||||
|
.filter_map(Value::as_str)
|
||||||
|
.filter(|value| *value != "null")
|
||||||
|
.count();
|
||||||
|
let supported = types.len() == 2
|
||||||
|
&& concrete == 1
|
||||||
|
&& types.iter().any(|value| value.as_str() == Some("null"));
|
||||||
|
if !supported {
|
||||||
|
push(
|
||||||
|
findings,
|
||||||
|
"unsupported_schema_keyword",
|
||||||
|
"Schema type array содержит неподдерживаемую комбинацию.",
|
||||||
|
&format!("{pointer}/type"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if schema
|
||||||
|
.get("enum")
|
||||||
|
.and_then(Value::as_array)
|
||||||
|
.is_some_and(|values| values.iter().any(|value| !value.is_string()))
|
||||||
|
{
|
||||||
|
push(
|
||||||
|
findings,
|
||||||
|
"unsupported_schema_enum",
|
||||||
|
"Non-string enum не поддерживается executable schema.",
|
||||||
|
&format!("{pointer}/enum"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for keyword in [
|
||||||
|
"additionalProperties",
|
||||||
|
"unevaluatedProperties",
|
||||||
|
"prefixItems",
|
||||||
|
"contains",
|
||||||
|
"dependentSchemas",
|
||||||
|
"if",
|
||||||
|
"then",
|
||||||
|
"else",
|
||||||
|
"not",
|
||||||
|
"propertyNames",
|
||||||
|
"minimum",
|
||||||
|
"maximum",
|
||||||
|
"exclusiveMinimum",
|
||||||
|
"exclusiveMaximum",
|
||||||
|
"minLength",
|
||||||
|
"maxLength",
|
||||||
|
"pattern",
|
||||||
|
"minItems",
|
||||||
|
"maxItems",
|
||||||
|
"uniqueItems",
|
||||||
|
"const",
|
||||||
|
"multipleOf",
|
||||||
|
"minProperties",
|
||||||
|
"maxProperties",
|
||||||
|
"dependentRequired",
|
||||||
|
] {
|
||||||
|
if schema.get(keyword).is_some() {
|
||||||
|
push(
|
||||||
|
findings,
|
||||||
|
"unsupported_schema_keyword",
|
||||||
|
"Schema keyword не поддерживается executable schema.",
|
||||||
|
&format!("{pointer}/{keyword}"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(properties) = schema.get("properties").and_then(Value::as_object) {
|
||||||
|
for (name, child) in properties {
|
||||||
|
schema_findings(
|
||||||
|
child,
|
||||||
|
&format!("{pointer}/properties/{}", escape(name)),
|
||||||
|
findings,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(items) = schema.get("items") {
|
||||||
|
schema_findings(items, &format!("{pointer}/items"), findings);
|
||||||
|
}
|
||||||
|
for operator in ["allOf", "oneOf", "anyOf"] {
|
||||||
|
if let Some(variants) = schema.get(operator).and_then(Value::as_array) {
|
||||||
|
for (index, variant) in variants.iter().enumerate() {
|
||||||
|
schema_findings(variant, &format!("{pointer}/{operator}/{index}"), findings);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn path_parameters(
|
||||||
|
path: &str,
|
||||||
|
parameters: &[RestImportParameter],
|
||||||
|
) -> Vec<(ImportFinding, SourceLocation)> {
|
||||||
|
parameters
|
||||||
|
.iter()
|
||||||
|
.filter(|parameter| parameter.location == RestParameterLocation::Path)
|
||||||
|
.filter_map(|parameter| {
|
||||||
|
let finding = if !parameter.required {
|
||||||
|
Some((
|
||||||
|
"path_parameter_not_required",
|
||||||
|
format!("Path parameter {} должен быть required.", parameter.name),
|
||||||
|
))
|
||||||
|
} else if !path.contains(&format!("{{{}}}", parameter.name)) {
|
||||||
|
Some((
|
||||||
|
"path_parameter_placeholder_missing",
|
||||||
|
format!(
|
||||||
|
"Path parameter {} не имеет placeholder в пути.",
|
||||||
|
parameter.name
|
||||||
|
),
|
||||||
|
))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}?;
|
||||||
|
Some((
|
||||||
|
document_blocker(finding.0, finding.1),
|
||||||
|
parameter.source_location.clone(),
|
||||||
|
))
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn unsupported_methods(path_item: &Value) -> Vec<&str> {
|
||||||
|
const NON_METHOD: &[&str] = &["$ref", "summary", "description", "servers", "parameters"];
|
||||||
|
const SUPPORTED: &[&str] = &["get", "post", "put", "patch", "delete", "head", "options"];
|
||||||
|
path_item
|
||||||
|
.as_object()
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(|item| item.keys())
|
||||||
|
.map(String::as_str)
|
||||||
|
.filter(|name| {
|
||||||
|
!name.starts_with("x-") && !NON_METHOD.contains(name) && !SUPPORTED.contains(name)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn supported_request_variants(operation: &Value) -> usize {
|
||||||
|
operation
|
||||||
|
.pointer("/requestBody/content")
|
||||||
|
.and_then(Value::as_object)
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(|content| content.iter())
|
||||||
|
.filter(|(media, value)| supported_request_media(media) && value.get("schema").is_some())
|
||||||
|
.count()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn supported_request_media(media: &str) -> bool {
|
||||||
|
matches!(
|
||||||
|
media,
|
||||||
|
"application/json" | "application/x-www-form-urlencoded" | "multipart/form-data"
|
||||||
|
) || media.ends_with("+json")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn supported_response_media(media: &str) -> bool {
|
||||||
|
media == "application/json" || media.ends_with("+json")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn valid_http_server_url(url: &str) -> bool {
|
||||||
|
if url.chars().any(char::is_control) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let Ok(parsed) = url::Url::parse(url) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
matches!(parsed.scheme(), "http" | "https")
|
||||||
|
&& parsed.host().is_some()
|
||||||
|
&& parsed.username().is_empty()
|
||||||
|
&& parsed.password().is_none()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push(
|
||||||
|
findings: &mut Vec<(ImportFinding, SourceLocation)>,
|
||||||
|
code: &str,
|
||||||
|
message: impl Into<String>,
|
||||||
|
pointer: &str,
|
||||||
|
) {
|
||||||
|
findings.push((
|
||||||
|
document_blocker(code, message),
|
||||||
|
SourceLocation {
|
||||||
|
pointer: pointer.to_owned(),
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn escape(value: &str) -> String {
|
||||||
|
value.replace('~', "~0").replace('/', "~1")
|
||||||
|
}
|
||||||
@@ -0,0 +1,236 @@
|
|||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
use crate::rest::{
|
||||||
|
model::{
|
||||||
|
ImportFinding, RestImportDocument, RestImportOperation, RestImportParameter,
|
||||||
|
RestParameterLocation,
|
||||||
|
},
|
||||||
|
normalize::ImportParseError,
|
||||||
|
recommendations::document_finding,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub(super) fn parse_document_legacy_v1(
|
||||||
|
root: &Value,
|
||||||
|
) -> Result<RestImportDocument, ImportParseError> {
|
||||||
|
let version = root
|
||||||
|
.get("openapi")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.map(ToOwned::to_owned);
|
||||||
|
let title = root
|
||||||
|
.pointer("/info/title")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.unwrap_or("Imported API")
|
||||||
|
.to_owned();
|
||||||
|
let servers = legacy_servers(root.get("servers"));
|
||||||
|
let mut findings = Vec::new();
|
||||||
|
if servers.is_empty() {
|
||||||
|
findings.push(document_finding(
|
||||||
|
"missing_servers",
|
||||||
|
"В документе не указаны servers, base URL нужно будет выбрать вручную.",
|
||||||
|
));
|
||||||
|
} else if servers.len() > 1 {
|
||||||
|
findings.push(document_finding(
|
||||||
|
"multiple_servers",
|
||||||
|
"В документе несколько servers, при импорте нужно выбрать нужный base URL.",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut operations = Vec::new();
|
||||||
|
let paths = root
|
||||||
|
.get("paths")
|
||||||
|
.and_then(Value::as_object)
|
||||||
|
.ok_or(ImportParseError::UnsupportedDocument)?;
|
||||||
|
for (path, path_item) in paths {
|
||||||
|
let path_pointer = format!("/paths/{}", path.replace('~', "~0").replace('/', "~1"));
|
||||||
|
let path_parameters = legacy_parameters(
|
||||||
|
root,
|
||||||
|
path_item.get("parameters"),
|
||||||
|
&format!("{path_pointer}/parameters"),
|
||||||
|
);
|
||||||
|
for method_name in ["get", "post", "put", "patch", "delete"] {
|
||||||
|
let Some(operation) = path_item.get(method_name) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some(method) = super::http_methods::from_lower(method_name) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let operation_pointer = format!("{path_pointer}/{method_name}");
|
||||||
|
let mut parameters = path_parameters.clone();
|
||||||
|
parameters.extend(legacy_parameters(
|
||||||
|
root,
|
||||||
|
operation.get("parameters"),
|
||||||
|
&format!("{operation_pointer}/parameters"),
|
||||||
|
));
|
||||||
|
operations.push(RestImportOperation {
|
||||||
|
key: format!("{} {}", method_name.to_uppercase(), path),
|
||||||
|
method,
|
||||||
|
path: path.clone(),
|
||||||
|
security_requirements: Default::default(),
|
||||||
|
operation_id: operation
|
||||||
|
.get("operationId")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.map(ToOwned::to_owned),
|
||||||
|
summary: operation
|
||||||
|
.get("summary")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.map(ToOwned::to_owned),
|
||||||
|
description: operation
|
||||||
|
.get("description")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.map(ToOwned::to_owned),
|
||||||
|
tags: legacy_tags(operation.get("tags")),
|
||||||
|
parameters,
|
||||||
|
request_body_schema: legacy_request_body_schema(root, operation),
|
||||||
|
request_body_schema_location: None,
|
||||||
|
request_body_variants: Vec::new(),
|
||||||
|
response_schema: legacy_response_schema(root, operation),
|
||||||
|
response_schema_location: None,
|
||||||
|
response_variants: Vec::new(),
|
||||||
|
servers: legacy_servers(operation.get("servers")),
|
||||||
|
findings: legacy_operation_findings(operation),
|
||||||
|
internal_finding_locations: Vec::new(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(RestImportDocument {
|
||||||
|
format: "openapi".to_owned(),
|
||||||
|
version,
|
||||||
|
title,
|
||||||
|
servers,
|
||||||
|
security_schemes: Default::default(),
|
||||||
|
operations,
|
||||||
|
findings,
|
||||||
|
internal_finding_locations: Vec::new(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn legacy_servers(value: Option<&Value>) -> Vec<String> {
|
||||||
|
value
|
||||||
|
.and_then(Value::as_array)
|
||||||
|
.map(|items| {
|
||||||
|
items
|
||||||
|
.iter()
|
||||||
|
.filter_map(|item| item.get("url").and_then(Value::as_str))
|
||||||
|
.map(|url| url.trim_end_matches('/').to_owned())
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn legacy_tags(value: Option<&Value>) -> Vec<String> {
|
||||||
|
value
|
||||||
|
.and_then(Value::as_array)
|
||||||
|
.map(|items| {
|
||||||
|
items
|
||||||
|
.iter()
|
||||||
|
.filter_map(Value::as_str)
|
||||||
|
.map(ToOwned::to_owned)
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn legacy_parameters(
|
||||||
|
root: &Value,
|
||||||
|
value: Option<&Value>,
|
||||||
|
base_pointer: &str,
|
||||||
|
) -> Vec<RestImportParameter> {
|
||||||
|
value
|
||||||
|
.and_then(Value::as_array)
|
||||||
|
.map(|items| {
|
||||||
|
items
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.filter_map(|(index, item)| {
|
||||||
|
let item = crate::rest::normalize::resolve_local_ref(root, item, 0);
|
||||||
|
let location = match item.get("in").and_then(Value::as_str)? {
|
||||||
|
"path" => RestParameterLocation::Path,
|
||||||
|
"query" => RestParameterLocation::Query,
|
||||||
|
"header" => RestParameterLocation::Header,
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
Some(RestImportParameter {
|
||||||
|
name: item.get("name").and_then(Value::as_str)?.to_owned(),
|
||||||
|
location,
|
||||||
|
required: item
|
||||||
|
.get("required")
|
||||||
|
.and_then(Value::as_bool)
|
||||||
|
.unwrap_or(false)
|
||||||
|
|| location == RestParameterLocation::Path,
|
||||||
|
description: item
|
||||||
|
.get("description")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.map(ToOwned::to_owned),
|
||||||
|
schema: item.get("schema").map(|schema| {
|
||||||
|
crate::rest::normalize::resolve_local_ref(root, schema, 0)
|
||||||
|
}),
|
||||||
|
source_location: crate::rest::model::SourceLocation {
|
||||||
|
pointer: format!("{base_pointer}/{index}"),
|
||||||
|
},
|
||||||
|
schema_source_location: None,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn legacy_request_body_schema(root: &Value, operation: &Value) -> Option<Value> {
|
||||||
|
let body = crate::rest::normalize::resolve_local_ref(root, operation.get("requestBody")?, 0);
|
||||||
|
let content = body.get("content")?.as_object()?;
|
||||||
|
for content_type in ["application/json", "application/*+json"] {
|
||||||
|
if let Some(schema) = content
|
||||||
|
.get(content_type)
|
||||||
|
.and_then(|media| media.get("schema"))
|
||||||
|
{
|
||||||
|
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
content
|
||||||
|
.iter()
|
||||||
|
.find(|(content_type, _)| content_type.contains("json"))
|
||||||
|
.and_then(|(_, media)| media.get("schema"))
|
||||||
|
.map(|schema| crate::rest::normalize::resolve_local_ref(root, schema, 0))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn legacy_response_schema(root: &Value, operation: &Value) -> Option<Value> {
|
||||||
|
let responses = operation.get("responses")?.as_object()?;
|
||||||
|
for code in ["200", "201", "202", "default"] {
|
||||||
|
let Some(response) = responses.get(code) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let response = crate::rest::normalize::resolve_local_ref(root, response, 0);
|
||||||
|
let Some(content) = response.get("content").and_then(Value::as_object) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
for content_type in ["application/json", "application/*+json"] {
|
||||||
|
if let Some(schema) = content
|
||||||
|
.get(content_type)
|
||||||
|
.and_then(|media| media.get("schema"))
|
||||||
|
{
|
||||||
|
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(schema) = content
|
||||||
|
.iter()
|
||||||
|
.find(|(content_type, _)| content_type.contains("json"))
|
||||||
|
.and_then(|(_, media)| media.get("schema"))
|
||||||
|
{
|
||||||
|
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
fn legacy_operation_findings(operation: &Value) -> Vec<ImportFinding> {
|
||||||
|
if operation.get("requestBody").is_some()
|
||||||
|
&& legacy_request_body_schema(&Value::Null, operation).is_none()
|
||||||
|
{
|
||||||
|
vec![document_finding(
|
||||||
|
"unsupported_request_body",
|
||||||
|
"У метода есть requestBody, но JSON schema не найдена.",
|
||||||
|
)]
|
||||||
|
} else {
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,23 +1,28 @@
|
|||||||
use std::collections::{BTreeMap, BTreeSet};
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
use crank_core::{
|
use crank_core::{
|
||||||
ExecutionConfig, HttpMethod, OperationSafetyClass, OperationSafetyPolicy, Protocol, RestTarget,
|
ExecutionConfig, HttpMethod, OperationSafetyClass, OperationSafetyPolicy, Protocol,
|
||||||
ToolDescription, ToolExample, WizardState,
|
RestRequestContract, RestRequestContractVersion, RestRequestDescriptor, RestResponseDescriptor,
|
||||||
|
RestTarget, ToolDescription, ToolExample, WizardState,
|
||||||
};
|
};
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
|
|
||||||
use crate::rest::{
|
use crate::rest::{
|
||||||
mapping::{BodyFieldMapping, input_mapping, output_mapping},
|
mapping::{BodyFieldMapping, ParameterFieldMapping, input_mapping, output_mapping},
|
||||||
model::{
|
model::{
|
||||||
ImportOperationCandidate, RestImportCandidate, RestImportOperation, RestParameterLocation,
|
ImportOperationCandidate, NormalizedSecurityScheme, RestImportCandidate,
|
||||||
|
RestImportOperation, RestParameterLocation,
|
||||||
},
|
},
|
||||||
naming::{fallback_operation_seed, title_from_name, unique_name},
|
naming::{fallback_operation_seed, title_from_name, unique_name},
|
||||||
recommendations::{candidate_recommendations, operation_recommendations},
|
recommendations::{candidate_recommendations, operation_recommendations},
|
||||||
schema::{any_object, field_count, object_with_fields, schema_from_openapi},
|
schema::{
|
||||||
|
any_object, field_count, object_with_fields, schema_from_multipart, schema_from_openapi,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn candidate_from_operation(
|
pub fn candidate_from_operation(
|
||||||
operation: &RestImportOperation,
|
operation: &RestImportOperation,
|
||||||
|
security_schemes: &BTreeMap<String, NormalizedSecurityScheme>,
|
||||||
document_servers: &[String],
|
document_servers: &[String],
|
||||||
used_names: &mut BTreeSet<String>,
|
used_names: &mut BTreeSet<String>,
|
||||||
) -> ImportOperationCandidate {
|
) -> ImportOperationCandidate {
|
||||||
@@ -55,32 +60,37 @@ pub fn candidate_from_operation(
|
|||||||
let base_url = server_urls.first().cloned().unwrap_or_default();
|
let base_url = server_urls.first().cloned().unwrap_or_default();
|
||||||
let mut input_fields = BTreeMap::new();
|
let mut input_fields = BTreeMap::new();
|
||||||
let mut used_input_field_names = BTreeSet::new();
|
let mut used_input_field_names = BTreeSet::new();
|
||||||
for parameter in &operation.parameters {
|
let parameter_mappings = operation
|
||||||
used_input_field_names.insert(parameter.name.clone());
|
.parameters
|
||||||
|
.iter()
|
||||||
|
.map(|parameter| {
|
||||||
|
let input_name = unique_parameter_input_name(parameter, &mut used_input_field_names);
|
||||||
|
let default_value = parameter
|
||||||
|
.schema
|
||||||
|
.as_ref()
|
||||||
|
.and_then(|schema| schema.get("default"))
|
||||||
|
.cloned();
|
||||||
input_fields.insert(
|
input_fields.insert(
|
||||||
parameter.name.clone(),
|
input_name.clone(),
|
||||||
schema_from_openapi(
|
schema_from_openapi(
|
||||||
parameter.schema.as_ref(),
|
parameter.schema.as_ref(),
|
||||||
parameter.required || parameter.location == RestParameterLocation::Path,
|
parameter.required || parameter.location == RestParameterLocation::Path,
|
||||||
parameter.description.clone(),
|
parameter.description.clone(),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
ParameterFieldMapping {
|
||||||
|
input_name,
|
||||||
|
wire_name: parameter.name.clone(),
|
||||||
|
location: parameter.location,
|
||||||
|
required: parameter.required || parameter.location == RestParameterLocation::Path,
|
||||||
|
default_value,
|
||||||
}
|
}
|
||||||
let body_fields = body_input_fields(
|
})
|
||||||
operation.request_body_schema.as_ref(),
|
.collect::<Vec<_>>();
|
||||||
&mut used_input_field_names,
|
let body_fields = body_input_fields(operation, &mut used_input_field_names, &mut input_fields);
|
||||||
&mut input_fields,
|
let input_schema = input_schema_for_body_variants(operation, input_fields, &body_fields);
|
||||||
);
|
let output_schema = output_schema_from_operation(operation);
|
||||||
let input_schema = object_with_fields(
|
let input_mapping = input_mapping(¶meter_mappings, &body_fields);
|
||||||
Some("Входные параметры MCP-инструмента".to_owned()),
|
|
||||||
input_fields,
|
|
||||||
);
|
|
||||||
let output_schema = operation
|
|
||||||
.response_schema
|
|
||||||
.as_ref()
|
|
||||||
.map(|schema| schema_from_openapi(Some(schema), true, Some("Ответ API".to_owned())))
|
|
||||||
.unwrap_or_else(|| any_object(Some("Ответ API".to_owned())));
|
|
||||||
let input_mapping = input_mapping(&operation.parameters, &body_fields);
|
|
||||||
let output_mapping = output_mapping(&output_schema);
|
let output_mapping = output_mapping(&output_schema);
|
||||||
let mut findings = operation_recommendations(operation);
|
let mut findings = operation_recommendations(operation);
|
||||||
findings.extend(candidate_recommendations(
|
findings.extend(candidate_recommendations(
|
||||||
@@ -100,6 +110,29 @@ pub fn candidate_from_operation(
|
|||||||
method: operation.method,
|
method: operation.method,
|
||||||
path_template: operation.path.clone(),
|
path_template: operation.path.clone(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: request_contract(operation, &body_fields),
|
||||||
|
response_contract: operation
|
||||||
|
.response_variants
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(schema_variant, variant)| RestResponseDescriptor {
|
||||||
|
status_code: variant.status_code,
|
||||||
|
media_type: variant.content_type.clone(),
|
||||||
|
schema_variant,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
multipart_field_mime_types: operation
|
||||||
|
.request_body_variants
|
||||||
|
.iter()
|
||||||
|
.filter(|variant| variant.content_type == "multipart/form-data")
|
||||||
|
.filter(|variant| !variant.multipart_field_mime_types.is_empty())
|
||||||
|
.map(|variant| {
|
||||||
|
(
|
||||||
|
variant.content_type.clone(),
|
||||||
|
variant.multipart_field_mime_types.clone(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
},
|
},
|
||||||
input_schema: input_schema.clone(),
|
input_schema: input_schema.clone(),
|
||||||
output_schema: output_schema.clone(),
|
output_schema: output_schema.clone(),
|
||||||
@@ -123,6 +156,8 @@ pub fn candidate_from_operation(
|
|||||||
key: operation.key.clone(),
|
key: operation.key.clone(),
|
||||||
method: operation.method,
|
method: operation.method,
|
||||||
path: operation.path.clone(),
|
path: operation.path.clone(),
|
||||||
|
security_requirements: operation.security_requirements.clone(),
|
||||||
|
security_schemes: security_schemes.clone(),
|
||||||
operation_id: operation.operation_id.clone(),
|
operation_id: operation.operation_id.clone(),
|
||||||
suggested_name: name,
|
suggested_name: name,
|
||||||
suggested_display_name: display_name,
|
suggested_display_name: display_name,
|
||||||
@@ -136,7 +171,274 @@ pub fn candidate_from_operation(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn output_schema_from_operation(operation: &RestImportOperation) -> crank_schema::Schema {
|
||||||
|
if operation.response_variants.is_empty() {
|
||||||
|
return operation
|
||||||
|
.response_schema
|
||||||
|
.as_ref()
|
||||||
|
.map(|schema| schema_from_openapi(Some(schema), true, Some("Ответ API".to_owned())))
|
||||||
|
.unwrap_or_else(|| any_object(Some("Ответ API".to_owned())));
|
||||||
|
}
|
||||||
|
let mut variants = operation
|
||||||
|
.response_variants
|
||||||
|
.iter()
|
||||||
|
.map(|variant| match &variant.schema {
|
||||||
|
Some(schema) => schema_from_openapi(Some(schema), true, Some("Ответ API".to_owned())),
|
||||||
|
None => crank_schema::Schema {
|
||||||
|
kind: crank_schema::SchemaKind::Null,
|
||||||
|
format: None,
|
||||||
|
description: Some("Успешный ответ без тела".to_owned()),
|
||||||
|
required: true,
|
||||||
|
nullable: false,
|
||||||
|
default_value: None,
|
||||||
|
fields: BTreeMap::new(),
|
||||||
|
items: None,
|
||||||
|
enum_values: Vec::new(),
|
||||||
|
variants: Vec::new(),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
if variants.len() == 1 {
|
||||||
|
return variants
|
||||||
|
.pop()
|
||||||
|
.unwrap_or_else(|| any_object(Some("Ответ API".to_owned())));
|
||||||
|
}
|
||||||
|
crank_schema::Schema {
|
||||||
|
kind: crank_schema::SchemaKind::Oneof,
|
||||||
|
format: None,
|
||||||
|
description: Some("Варианты успешного ответа API".to_owned()),
|
||||||
|
required: true,
|
||||||
|
nullable: false,
|
||||||
|
default_value: None,
|
||||||
|
fields: BTreeMap::new(),
|
||||||
|
items: None,
|
||||||
|
enum_values: Vec::new(),
|
||||||
|
variants,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn body_input_fields(
|
fn body_input_fields(
|
||||||
|
operation: &RestImportOperation,
|
||||||
|
used_names: &mut BTreeSet<String>,
|
||||||
|
input_fields: &mut BTreeMap<String, crank_schema::Schema>,
|
||||||
|
) -> Vec<BodyFieldMapping> {
|
||||||
|
let variants = &operation.request_body_variants;
|
||||||
|
if variants.is_empty() {
|
||||||
|
return legacy_body_input_fields(
|
||||||
|
operation.request_body_schema.as_ref(),
|
||||||
|
used_names,
|
||||||
|
input_fields,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let required = variants.iter().any(|variant| variant.required);
|
||||||
|
let body_variants = variants
|
||||||
|
.iter()
|
||||||
|
.map(|variant| {
|
||||||
|
let description = Some(format!("Тело запроса ({})", variant.content_type));
|
||||||
|
if variant.content_type == "multipart/form-data" {
|
||||||
|
schema_from_multipart(variant.schema.as_ref(), required, description)
|
||||||
|
} else {
|
||||||
|
schema_from_openapi(variant.schema.as_ref(), required, description)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let body_schema = if body_variants.len() == 1 {
|
||||||
|
body_variants
|
||||||
|
.into_iter()
|
||||||
|
.next()
|
||||||
|
.expect("single body variant exists")
|
||||||
|
} else {
|
||||||
|
crank_schema::Schema {
|
||||||
|
kind: crank_schema::SchemaKind::Oneof,
|
||||||
|
format: None,
|
||||||
|
description: Some("Тело запроса для выбранного формата".to_owned()),
|
||||||
|
required,
|
||||||
|
nullable: body_variants.iter().any(|variant| variant.nullable),
|
||||||
|
default_value: None,
|
||||||
|
fields: BTreeMap::new(),
|
||||||
|
items: None,
|
||||||
|
enum_values: Vec::new(),
|
||||||
|
variants: body_variants,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let body_name = unique_body_input_name("body", used_names);
|
||||||
|
input_fields.insert(body_name.clone(), body_schema);
|
||||||
|
if variants.len() > 1 {
|
||||||
|
let selector = unique_body_input_name("content_type", used_names);
|
||||||
|
input_fields.insert(
|
||||||
|
selector.clone(),
|
||||||
|
crank_schema::Schema {
|
||||||
|
kind: crank_schema::SchemaKind::Enum,
|
||||||
|
format: None,
|
||||||
|
description: Some("Выбирает формат тела запроса".to_owned()),
|
||||||
|
required,
|
||||||
|
nullable: false,
|
||||||
|
default_value: None,
|
||||||
|
fields: BTreeMap::new(),
|
||||||
|
items: None,
|
||||||
|
enum_values: variants
|
||||||
|
.iter()
|
||||||
|
.map(|variant| variant.content_type.clone())
|
||||||
|
.collect(),
|
||||||
|
variants: Vec::new(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
// The adapter obtains the selector from the mapped body envelope.
|
||||||
|
return vec![
|
||||||
|
BodyFieldMapping {
|
||||||
|
input_name: body_name,
|
||||||
|
// Keep selector and value in an internal envelope so that a
|
||||||
|
// selected nullable body can remain JSON null on the wire.
|
||||||
|
body_path: "__body".to_owned(),
|
||||||
|
required,
|
||||||
|
},
|
||||||
|
BodyFieldMapping {
|
||||||
|
input_name: selector,
|
||||||
|
body_path: "__content_type".to_owned(),
|
||||||
|
required,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
vec![BodyFieldMapping {
|
||||||
|
input_name: body_name,
|
||||||
|
body_path: String::new(),
|
||||||
|
required,
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn input_schema_for_body_variants(
|
||||||
|
operation: &RestImportOperation,
|
||||||
|
input_fields: BTreeMap<String, crank_schema::Schema>,
|
||||||
|
body_fields: &[BodyFieldMapping],
|
||||||
|
) -> crank_schema::Schema {
|
||||||
|
if operation.request_body_variants.len() <= 1 {
|
||||||
|
return object_with_fields(
|
||||||
|
Some("Входные параметры MCP-инструмента".to_owned()),
|
||||||
|
input_fields,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let Some(body_name) = body_fields
|
||||||
|
.iter()
|
||||||
|
.find(|field| field.body_path == "__body")
|
||||||
|
.map(|field| field.input_name.as_str())
|
||||||
|
else {
|
||||||
|
return object_with_fields(
|
||||||
|
Some("Входные параметры MCP-инструмента".to_owned()),
|
||||||
|
input_fields,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
let Some(selector_name) = body_fields
|
||||||
|
.iter()
|
||||||
|
.find(|field| field.body_path == "__content_type")
|
||||||
|
.map(|field| field.input_name.as_str())
|
||||||
|
else {
|
||||||
|
return object_with_fields(
|
||||||
|
Some("Входные параметры MCP-инструмента".to_owned()),
|
||||||
|
input_fields,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
let Some(body_schema) = input_fields.get(body_name) else {
|
||||||
|
return object_with_fields(
|
||||||
|
Some("Входные параметры MCP-инструмента".to_owned()),
|
||||||
|
input_fields,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
let Some(selector_schema) = input_fields.get(selector_name) else {
|
||||||
|
return object_with_fields(
|
||||||
|
Some("Входные параметры MCP-инструмента".to_owned()),
|
||||||
|
input_fields,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
let variants = operation
|
||||||
|
.request_body_variants
|
||||||
|
.iter()
|
||||||
|
.zip(&body_schema.variants)
|
||||||
|
.map(|(request_variant, body_schema)| {
|
||||||
|
let mut fields = input_fields.clone();
|
||||||
|
let mut body_schema = body_schema.clone();
|
||||||
|
body_schema.required = true;
|
||||||
|
fields.insert(body_name.to_owned(), body_schema);
|
||||||
|
let mut selector = selector_schema.clone();
|
||||||
|
selector.required = true;
|
||||||
|
selector.enum_values = vec![request_variant.content_type.clone()];
|
||||||
|
fields.insert(selector_name.to_owned(), selector);
|
||||||
|
closed_object_with_fields(Some("Входные параметры MCP-инструмента".to_owned()), fields)
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let mut variants = variants;
|
||||||
|
if !operation
|
||||||
|
.request_body_variants
|
||||||
|
.iter()
|
||||||
|
.any(|variant| variant.required)
|
||||||
|
{
|
||||||
|
let mut absent_fields = input_fields;
|
||||||
|
absent_fields.remove(body_name);
|
||||||
|
absent_fields.remove(selector_name);
|
||||||
|
variants.push(closed_object_with_fields(
|
||||||
|
Some("Входные параметры без HTTP body".to_owned()),
|
||||||
|
absent_fields,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
crank_schema::Schema {
|
||||||
|
kind: crank_schema::SchemaKind::Oneof,
|
||||||
|
format: None,
|
||||||
|
description: Some("Входные параметры для выбранного формата тела запроса".to_owned()),
|
||||||
|
required: true,
|
||||||
|
nullable: false,
|
||||||
|
default_value: None,
|
||||||
|
fields: BTreeMap::new(),
|
||||||
|
items: None,
|
||||||
|
enum_values: Vec::new(),
|
||||||
|
variants,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn closed_object_with_fields(
|
||||||
|
description: Option<String>,
|
||||||
|
fields: BTreeMap<String, crank_schema::Schema>,
|
||||||
|
) -> crank_schema::Schema {
|
||||||
|
let mut schema = object_with_fields(description, fields);
|
||||||
|
schema.format = Some(crank_schema::CLOSED_OBJECT_SCHEMA_FORMAT.to_owned());
|
||||||
|
schema
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request_contract(
|
||||||
|
operation: &RestImportOperation,
|
||||||
|
body_fields: &[BodyFieldMapping],
|
||||||
|
) -> Option<RestRequestContract> {
|
||||||
|
if operation.request_body_variants.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let body_field = body_fields
|
||||||
|
.iter()
|
||||||
|
.find(|field| field.body_path.is_empty() || field.body_path == "__body")?
|
||||||
|
.input_name
|
||||||
|
.clone();
|
||||||
|
let selector_field = body_fields
|
||||||
|
.iter()
|
||||||
|
.find(|field| field.body_path == "__content_type")
|
||||||
|
.map(|field| field.input_name.clone());
|
||||||
|
Some(RestRequestContract {
|
||||||
|
version: RestRequestContractVersion::V1,
|
||||||
|
body_field,
|
||||||
|
selector_field,
|
||||||
|
body_required: operation
|
||||||
|
.request_body_variants
|
||||||
|
.iter()
|
||||||
|
.any(|variant| variant.required),
|
||||||
|
variants: operation
|
||||||
|
.request_body_variants
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(schema_variant, variant)| RestRequestDescriptor {
|
||||||
|
media_type: variant.content_type.clone(),
|
||||||
|
schema_variant,
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn legacy_body_input_fields(
|
||||||
request_body_schema: Option<&serde_json::Value>,
|
request_body_schema: Option<&serde_json::Value>,
|
||||||
used_names: &mut BTreeSet<String>,
|
used_names: &mut BTreeSet<String>,
|
||||||
input_fields: &mut BTreeMap<String, crank_schema::Schema>,
|
input_fields: &mut BTreeMap<String, crank_schema::Schema>,
|
||||||
@@ -158,7 +460,6 @@ fn body_input_fields(
|
|||||||
required: true,
|
required: true,
|
||||||
}];
|
}];
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut mappings = Vec::new();
|
let mut mappings = Vec::new();
|
||||||
for (field_name, field_schema) in body_schema.fields {
|
for (field_name, field_schema) in body_schema.fields {
|
||||||
let input_name = unique_body_input_name(&field_name, used_names);
|
let input_name = unique_body_input_name(&field_name, used_names);
|
||||||
@@ -172,6 +473,33 @@ fn body_input_fields(
|
|||||||
mappings
|
mappings
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn unique_parameter_input_name(
|
||||||
|
parameter: &crate::rest::model::RestImportParameter,
|
||||||
|
used_names: &mut BTreeSet<String>,
|
||||||
|
) -> String {
|
||||||
|
let reserved = matches!(parameter.name.as_str(), "body" | "content_type");
|
||||||
|
if !reserved && used_names.insert(parameter.name.clone()) {
|
||||||
|
return parameter.name.clone();
|
||||||
|
}
|
||||||
|
unique_body_input_name(
|
||||||
|
&format!(
|
||||||
|
"{}_{}",
|
||||||
|
parameter_location_name(parameter.location),
|
||||||
|
parameter.name
|
||||||
|
),
|
||||||
|
used_names,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parameter_location_name(location: RestParameterLocation) -> &'static str {
|
||||||
|
match location {
|
||||||
|
RestParameterLocation::Path => "path",
|
||||||
|
RestParameterLocation::Query => "query",
|
||||||
|
RestParameterLocation::Header => "header",
|
||||||
|
RestParameterLocation::Cookie => "cookie",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn unique_body_input_name(name: &str, used_names: &mut BTreeSet<String>) -> String {
|
fn unique_body_input_name(name: &str, used_names: &mut BTreeSet<String>) -> String {
|
||||||
if used_names.insert(name.to_owned()) {
|
if used_names.insert(name.to_owned()) {
|
||||||
return name.to_owned();
|
return name.to_owned();
|
||||||
@@ -207,6 +535,8 @@ fn method_as_str(method: HttpMethod) -> &'static str {
|
|||||||
HttpMethod::Put => "PUT",
|
HttpMethod::Put => "PUT",
|
||||||
HttpMethod::Patch => "PATCH",
|
HttpMethod::Patch => "PATCH",
|
||||||
HttpMethod::Delete => "DELETE",
|
HttpMethod::Delete => "DELETE",
|
||||||
|
HttpMethod::Head => "HEAD",
|
||||||
|
HttpMethod::Options => "OPTIONS",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -216,6 +546,7 @@ fn safety_for_method(method: HttpMethod) -> OperationSafetyPolicy {
|
|||||||
HttpMethod::Get => OperationSafetyClass::Read,
|
HttpMethod::Get => OperationSafetyClass::Read,
|
||||||
HttpMethod::Post | HttpMethod::Put | HttpMethod::Patch => OperationSafetyClass::Write,
|
HttpMethod::Post | HttpMethod::Put | HttpMethod::Patch => OperationSafetyClass::Write,
|
||||||
HttpMethod::Delete => OperationSafetyClass::Destructive,
|
HttpMethod::Delete => OperationSafetyClass::Destructive,
|
||||||
|
HttpMethod::Head | HttpMethod::Options => OperationSafetyClass::Read,
|
||||||
};
|
};
|
||||||
OperationSafetyPolicy {
|
OperationSafetyPolicy {
|
||||||
class,
|
class,
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ use serde_json::Value;
|
|||||||
pub fn any_object(description: Option<String>) -> Schema {
|
pub fn any_object(description: Option<String>) -> Schema {
|
||||||
Schema {
|
Schema {
|
||||||
kind: SchemaKind::Object,
|
kind: SchemaKind::Object,
|
||||||
|
format: None,
|
||||||
description,
|
description,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
@@ -28,9 +29,26 @@ pub fn schema_from_openapi(
|
|||||||
value: Option<&Value>,
|
value: Option<&Value>,
|
||||||
required: bool,
|
required: bool,
|
||||||
description: Option<String>,
|
description: Option<String>,
|
||||||
|
) -> Schema {
|
||||||
|
schema_from_openapi_context(value, required, description, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn schema_from_multipart(
|
||||||
|
value: Option<&Value>,
|
||||||
|
required: bool,
|
||||||
|
description: Option<String>,
|
||||||
|
) -> Schema {
|
||||||
|
schema_from_openapi_context(value, required, description, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn schema_from_openapi_context(
|
||||||
|
value: Option<&Value>,
|
||||||
|
required: bool,
|
||||||
|
description: Option<String>,
|
||||||
|
binary_envelopes: bool,
|
||||||
) -> Schema {
|
) -> Schema {
|
||||||
let Some(value) = value else {
|
let Some(value) = value else {
|
||||||
return primitive(SchemaKind::String, required, description);
|
return primitive(SchemaKind::String, required, description, None);
|
||||||
};
|
};
|
||||||
// Only v3 NormalizedIR emits the private marker. Pending legacy-v1 jobs
|
// Only v3 NormalizedIR emits the private marker. Pending legacy-v1 jobs
|
||||||
// retain their historical first-branch behavior, while modern oneOf/anyOf
|
// retain their historical first-branch behavior, while modern oneOf/anyOf
|
||||||
@@ -46,6 +64,7 @@ pub fn schema_from_openapi(
|
|||||||
{
|
{
|
||||||
return Schema {
|
return Schema {
|
||||||
kind: SchemaKind::Oneof,
|
kind: SchemaKind::Oneof,
|
||||||
|
format: text(value, "format"),
|
||||||
description: description.or_else(|| text(value, "description")),
|
description: description.or_else(|| text(value, "description")),
|
||||||
required,
|
required,
|
||||||
nullable: nullable(value),
|
nullable: nullable(value),
|
||||||
@@ -55,7 +74,7 @@ pub fn schema_from_openapi(
|
|||||||
enum_values: Vec::new(),
|
enum_values: Vec::new(),
|
||||||
variants: items
|
variants: items
|
||||||
.iter()
|
.iter()
|
||||||
.map(|item| schema_from_openapi(Some(item), true, None))
|
.map(|item| schema_from_openapi_context(Some(item), true, None, binary_envelopes))
|
||||||
.collect(),
|
.collect(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -70,6 +89,7 @@ pub fn schema_from_openapi(
|
|||||||
if !enum_values.is_empty() {
|
if !enum_values.is_empty() {
|
||||||
return Schema {
|
return Schema {
|
||||||
kind: SchemaKind::Enum,
|
kind: SchemaKind::Enum,
|
||||||
|
format: text(&resolved, "format"),
|
||||||
description: description.or_else(|| text(&resolved, "description")),
|
description: description.or_else(|| text(&resolved, "description")),
|
||||||
required,
|
required,
|
||||||
nullable: nullable(&resolved),
|
nullable: nullable(&resolved),
|
||||||
@@ -82,19 +102,31 @@ pub fn schema_from_openapi(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// OpenAPI binary/file fields use the frozen multipart envelope rather
|
||||||
|
// than a path, URL, or base64 string. Arrays recurse through this branch
|
||||||
|
// for each item and therefore expose the same object contract.
|
||||||
|
if binary_envelopes && is_binary_file(&resolved) {
|
||||||
|
return file_schema(
|
||||||
|
required,
|
||||||
|
description.or_else(|| text(&resolved, "description")),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
match type_name(&resolved).unwrap_or("object") {
|
match type_name(&resolved).unwrap_or("object") {
|
||||||
"object" => object_schema(&resolved, required, description),
|
"object" => object_schema(&resolved, required, description, binary_envelopes),
|
||||||
"array" => Schema {
|
"array" => Schema {
|
||||||
kind: SchemaKind::Array,
|
kind: SchemaKind::Array,
|
||||||
|
format: text(&resolved, "format"),
|
||||||
description: description.or_else(|| text(&resolved, "description")),
|
description: description.or_else(|| text(&resolved, "description")),
|
||||||
required,
|
required,
|
||||||
nullable: nullable(&resolved),
|
nullable: nullable(&resolved),
|
||||||
default_value: resolved.get("default").cloned(),
|
default_value: resolved.get("default").cloned(),
|
||||||
fields: BTreeMap::new(),
|
fields: BTreeMap::new(),
|
||||||
items: Some(Box::new(schema_from_openapi(
|
items: Some(Box::new(schema_from_openapi_context(
|
||||||
resolved.get("items"),
|
resolved.get("items"),
|
||||||
true,
|
true,
|
||||||
None,
|
None,
|
||||||
|
binary_envelopes,
|
||||||
))),
|
))),
|
||||||
enum_values: Vec::new(),
|
enum_values: Vec::new(),
|
||||||
variants: Vec::new(),
|
variants: Vec::new(),
|
||||||
@@ -103,26 +135,31 @@ pub fn schema_from_openapi(
|
|||||||
SchemaKind::Integer,
|
SchemaKind::Integer,
|
||||||
required,
|
required,
|
||||||
description.or_else(|| text(&resolved, "description")),
|
description.or_else(|| text(&resolved, "description")),
|
||||||
|
Some(&resolved),
|
||||||
),
|
),
|
||||||
"number" => primitive(
|
"number" => primitive(
|
||||||
SchemaKind::Number,
|
SchemaKind::Number,
|
||||||
required,
|
required,
|
||||||
description.or_else(|| text(&resolved, "description")),
|
description.or_else(|| text(&resolved, "description")),
|
||||||
|
Some(&resolved),
|
||||||
),
|
),
|
||||||
"boolean" => primitive(
|
"boolean" => primitive(
|
||||||
SchemaKind::Boolean,
|
SchemaKind::Boolean,
|
||||||
required,
|
required,
|
||||||
description.or_else(|| text(&resolved, "description")),
|
description.or_else(|| text(&resolved, "description")),
|
||||||
|
Some(&resolved),
|
||||||
),
|
),
|
||||||
"null" => primitive(
|
"null" => primitive(
|
||||||
SchemaKind::Null,
|
SchemaKind::Null,
|
||||||
required,
|
required,
|
||||||
description.or_else(|| text(&resolved, "description")),
|
description.or_else(|| text(&resolved, "description")),
|
||||||
|
Some(&resolved),
|
||||||
),
|
),
|
||||||
_ => primitive(
|
_ => primitive(
|
||||||
SchemaKind::String,
|
SchemaKind::String,
|
||||||
required,
|
required,
|
||||||
description.or_else(|| text(&resolved, "description")),
|
description.or_else(|| text(&resolved, "description")),
|
||||||
|
Some(&resolved),
|
||||||
),
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -141,6 +178,7 @@ fn collapse_composition(value: &Value) -> Value {
|
|||||||
pub fn object_with_fields(description: Option<String>, fields: BTreeMap<String, Schema>) -> Schema {
|
pub fn object_with_fields(description: Option<String>, fields: BTreeMap<String, Schema>) -> Schema {
|
||||||
Schema {
|
Schema {
|
||||||
kind: SchemaKind::Object,
|
kind: SchemaKind::Object,
|
||||||
|
format: None,
|
||||||
description,
|
description,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
@@ -152,7 +190,12 @@ pub fn object_with_fields(description: Option<String>, fields: BTreeMap<String,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn object_schema(value: &Value, required: bool, description: Option<String>) -> Schema {
|
fn object_schema(
|
||||||
|
value: &Value,
|
||||||
|
required: bool,
|
||||||
|
description: Option<String>,
|
||||||
|
binary_envelopes: bool,
|
||||||
|
) -> Schema {
|
||||||
let required_fields = value
|
let required_fields = value
|
||||||
.get("required")
|
.get("required")
|
||||||
.and_then(Value::as_array)
|
.and_then(Value::as_array)
|
||||||
@@ -169,10 +212,11 @@ fn object_schema(value: &Value, required: bool, description: Option<String>) ->
|
|||||||
for (name, schema) in properties {
|
for (name, schema) in properties {
|
||||||
fields.insert(
|
fields.insert(
|
||||||
name.clone(),
|
name.clone(),
|
||||||
schema_from_openapi(
|
schema_from_openapi_context(
|
||||||
Some(schema),
|
Some(schema),
|
||||||
required_fields.contains(name.as_str()),
|
required_fields.contains(name.as_str()),
|
||||||
text(schema, "description"),
|
text(schema, "description"),
|
||||||
|
binary_envelopes,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -180,6 +224,7 @@ fn object_schema(value: &Value, required: bool, description: Option<String>) ->
|
|||||||
|
|
||||||
Schema {
|
Schema {
|
||||||
kind: SchemaKind::Object,
|
kind: SchemaKind::Object,
|
||||||
|
format: text(value, "format"),
|
||||||
description: description.or_else(|| text(value, "description")),
|
description: description.or_else(|| text(value, "description")),
|
||||||
required,
|
required,
|
||||||
nullable: nullable(value),
|
nullable: nullable(value),
|
||||||
@@ -191,14 +236,54 @@ fn object_schema(value: &Value, required: bool, description: Option<String>) ->
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn primitive(kind: SchemaKind, required: bool, description: Option<String>) -> Schema {
|
fn primitive(
|
||||||
|
kind: SchemaKind,
|
||||||
|
required: bool,
|
||||||
|
description: Option<String>,
|
||||||
|
value: Option<&Value>,
|
||||||
|
) -> Schema {
|
||||||
Schema {
|
Schema {
|
||||||
kind,
|
kind,
|
||||||
|
format: value.and_then(|value| text(value, "format")),
|
||||||
|
description,
|
||||||
|
required,
|
||||||
|
nullable: value.is_some_and(nullable),
|
||||||
|
default_value: value.and_then(|value| value.get("default").cloned()),
|
||||||
|
fields: BTreeMap::new(),
|
||||||
|
items: None,
|
||||||
|
enum_values: Vec::new(),
|
||||||
|
variants: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_binary_file(value: &Value) -> bool {
|
||||||
|
matches!(type_name(value), Some("file"))
|
||||||
|
|| matches!(type_name(value), Some("string"))
|
||||||
|
&& matches!(text(value, "format").as_deref(), Some("binary" | "file"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn file_schema(required: bool, description: Option<String>) -> Schema {
|
||||||
|
let mut fields = BTreeMap::new();
|
||||||
|
fields.insert(
|
||||||
|
"data_base64".to_owned(),
|
||||||
|
primitive(SchemaKind::String, true, None, None),
|
||||||
|
);
|
||||||
|
fields.insert(
|
||||||
|
"filename".to_owned(),
|
||||||
|
primitive(SchemaKind::String, false, None, None),
|
||||||
|
);
|
||||||
|
fields.insert(
|
||||||
|
"content_type".to_owned(),
|
||||||
|
primitive(SchemaKind::String, false, None, None),
|
||||||
|
);
|
||||||
|
Schema {
|
||||||
|
kind: SchemaKind::Object,
|
||||||
|
format: Some("binary".to_owned()),
|
||||||
description,
|
description,
|
||||||
required,
|
required,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
default_value: None,
|
default_value: None,
|
||||||
fields: BTreeMap::new(),
|
fields,
|
||||||
items: None,
|
items: None,
|
||||||
enum_values: Vec::new(),
|
enum_values: Vec::new(),
|
||||||
variants: Vec::new(),
|
variants: Vec::new(),
|
||||||
|
|||||||
@@ -0,0 +1,340 @@
|
|||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
use super::model::{
|
||||||
|
NormalizedSecurityRequirements, NormalizedSecurityScheme, NormalizedSecuritySchemeKind,
|
||||||
|
SecurityParameterLocation, SecurityRequirementAlternative, SecurityRequirementsSource,
|
||||||
|
SourceLocation,
|
||||||
|
};
|
||||||
|
use super::recommendations::{document_blocker, document_finding};
|
||||||
|
|
||||||
|
pub(super) fn schemes(root: &Value, swagger: bool) -> BTreeMap<String, NormalizedSecurityScheme> {
|
||||||
|
let (container, prefix) = if swagger {
|
||||||
|
(root.get("securityDefinitions"), "/securityDefinitions")
|
||||||
|
} else {
|
||||||
|
(
|
||||||
|
root.pointer("/components/securitySchemes"),
|
||||||
|
"/components/securitySchemes",
|
||||||
|
)
|
||||||
|
};
|
||||||
|
let Some(definitions) = container.and_then(Value::as_object) else {
|
||||||
|
return BTreeMap::new();
|
||||||
|
};
|
||||||
|
definitions
|
||||||
|
.iter()
|
||||||
|
.map(|(name, definition)| {
|
||||||
|
let location = SourceLocation {
|
||||||
|
pointer: format!(
|
||||||
|
"{prefix}/{}",
|
||||||
|
super::normalize_coverage::escape_pointer(name)
|
||||||
|
),
|
||||||
|
};
|
||||||
|
let kind = if swagger {
|
||||||
|
match definition.get("type").and_then(Value::as_str) {
|
||||||
|
Some("basic") => NormalizedSecuritySchemeKind::Http {
|
||||||
|
scheme: "basic".to_owned(),
|
||||||
|
format_hint: None,
|
||||||
|
},
|
||||||
|
Some("apiKey") => api_key(definition, false),
|
||||||
|
other => NormalizedSecuritySchemeKind::Unsupported {
|
||||||
|
scheme_type: other.map(ToOwned::to_owned),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
match definition.get("type").and_then(Value::as_str) {
|
||||||
|
Some("http") => {
|
||||||
|
let scheme = definition
|
||||||
|
.get("scheme")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.unwrap_or("")
|
||||||
|
.to_owned();
|
||||||
|
if matches!(scheme.to_ascii_lowercase().as_str(), "basic" | "bearer") {
|
||||||
|
NormalizedSecuritySchemeKind::Http {
|
||||||
|
scheme,
|
||||||
|
format_hint: definition
|
||||||
|
.get("bearerFormat")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.filter(|value| {
|
||||||
|
safe_format_hint(value) && !looks_secret_hint(value)
|
||||||
|
})
|
||||||
|
.map(ToOwned::to_owned),
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
NormalizedSecuritySchemeKind::Unsupported {
|
||||||
|
scheme_type: Some(format!("http:{}", scheme)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some("apiKey") => api_key(definition, true),
|
||||||
|
other => NormalizedSecuritySchemeKind::Unsupported {
|
||||||
|
scheme_type: other.map(ToOwned::to_owned),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
};
|
||||||
|
(
|
||||||
|
name.clone(),
|
||||||
|
NormalizedSecurityScheme {
|
||||||
|
name: name.clone(),
|
||||||
|
kind,
|
||||||
|
source_location: location,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn api_key(definition: &Value, allow_cookie: bool) -> NormalizedSecuritySchemeKind {
|
||||||
|
let location = match definition.get("in").and_then(Value::as_str) {
|
||||||
|
Some("header") => Some(SecurityParameterLocation::Header),
|
||||||
|
Some("query") => Some(SecurityParameterLocation::Query),
|
||||||
|
Some("cookie") if allow_cookie => Some(SecurityParameterLocation::Cookie),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
match (location, definition.get("name").and_then(Value::as_str)) {
|
||||||
|
(Some(location), Some(parameter_name)) => NormalizedSecuritySchemeKind::ApiKey {
|
||||||
|
location,
|
||||||
|
parameter_name: parameter_name.to_owned(),
|
||||||
|
format_hint: definition
|
||||||
|
.get("x-format-hint")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.filter(|value| safe_format_hint(value) && !looks_secret_hint(value))
|
||||||
|
.map(ToOwned::to_owned),
|
||||||
|
},
|
||||||
|
_ => NormalizedSecuritySchemeKind::Unsupported {
|
||||||
|
scheme_type: Some("apiKey".to_owned()),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn safe_format_hint(value: &str) -> bool {
|
||||||
|
!value.is_empty()
|
||||||
|
&& value.len() <= 64
|
||||||
|
&& value
|
||||||
|
.bytes()
|
||||||
|
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'+'))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn looks_secret_hint(value: &str) -> bool {
|
||||||
|
let value = value.to_ascii_lowercase();
|
||||||
|
["token", "secret", "password", "credential", "authorization"]
|
||||||
|
.iter()
|
||||||
|
.any(|marker| value.contains(marker))
|
||||||
|
|| value.starts_with("sk-")
|
||||||
|
|| value.starts_with("bearer ")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn effective_requirements(
|
||||||
|
root: &Value,
|
||||||
|
operation: &Value,
|
||||||
|
operation_pointer: &str,
|
||||||
|
schemes: &BTreeMap<String, NormalizedSecurityScheme>,
|
||||||
|
) -> (
|
||||||
|
NormalizedSecurityRequirements,
|
||||||
|
Vec<(super::model::ImportFinding, SourceLocation)>,
|
||||||
|
) {
|
||||||
|
let (value, source, pointer) = if let Some(value) = operation.get("security") {
|
||||||
|
(
|
||||||
|
Some(value),
|
||||||
|
SecurityRequirementsSource::Operation,
|
||||||
|
format!("{operation_pointer}/security"),
|
||||||
|
)
|
||||||
|
} else if let Some(value) = root.get("security") {
|
||||||
|
(
|
||||||
|
Some(value),
|
||||||
|
SecurityRequirementsSource::Document,
|
||||||
|
"/security".to_owned(),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
(None, SecurityRequirementsSource::None, String::new())
|
||||||
|
};
|
||||||
|
let mut findings = Vec::new();
|
||||||
|
let Some(value) = value else {
|
||||||
|
return (
|
||||||
|
NormalizedSecurityRequirements {
|
||||||
|
source,
|
||||||
|
alternatives: Vec::new(),
|
||||||
|
},
|
||||||
|
findings,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
let Some(alternatives) = value.as_array() else {
|
||||||
|
findings.push((
|
||||||
|
document_blocker(
|
||||||
|
"invalid_security_requirements",
|
||||||
|
"Security requirements имеют неверную структуру и блокируют импорт операции.",
|
||||||
|
),
|
||||||
|
SourceLocation { pointer },
|
||||||
|
));
|
||||||
|
return (
|
||||||
|
NormalizedSecurityRequirements {
|
||||||
|
source,
|
||||||
|
alternatives: Vec::new(),
|
||||||
|
},
|
||||||
|
findings,
|
||||||
|
);
|
||||||
|
};
|
||||||
|
let mut projected = Vec::new();
|
||||||
|
let mut supported_alternatives = 0usize;
|
||||||
|
for (alternative_index, alternative) in alternatives.iter().enumerate() {
|
||||||
|
let alternative_pointer = format!("{pointer}/{alternative_index}");
|
||||||
|
let Some(requirement) = alternative.as_object() else {
|
||||||
|
let source_location = SourceLocation {
|
||||||
|
pointer: alternative_pointer,
|
||||||
|
};
|
||||||
|
findings.push((
|
||||||
|
document_finding(
|
||||||
|
"invalid_security_requirement",
|
||||||
|
"Security alternative имеет неверную структуру и недоступна для выбора.",
|
||||||
|
),
|
||||||
|
source_location.clone(),
|
||||||
|
));
|
||||||
|
projected.push(SecurityRequirementAlternative {
|
||||||
|
schemes: Vec::new(),
|
||||||
|
supported: false,
|
||||||
|
findings: vec!["invalid_security_requirement".to_owned()],
|
||||||
|
source_location: Some(source_location),
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let mut names = requirement.keys().cloned().collect::<Vec<_>>();
|
||||||
|
names.sort();
|
||||||
|
let mut alternative_findings = Vec::new();
|
||||||
|
for name in &names {
|
||||||
|
let scopes = requirement.get(name).and_then(Value::as_array);
|
||||||
|
let valid_scope_array =
|
||||||
|
scopes.is_some_and(|scopes| scopes.iter().all(Value::is_string));
|
||||||
|
if !valid_scope_array {
|
||||||
|
alternative_findings.push("invalid_security_scopes".to_owned());
|
||||||
|
findings.push((
|
||||||
|
document_finding(
|
||||||
|
"invalid_security_scopes",
|
||||||
|
"Security scopes должны быть массивом строк; эта альтернатива недоступна для выбора.",
|
||||||
|
),
|
||||||
|
SourceLocation {
|
||||||
|
pointer: format!("{alternative_pointer}/{}", super::normalize_coverage::escape_pointer(name)),
|
||||||
|
},
|
||||||
|
));
|
||||||
|
} else if scopes.is_some_and(|scopes| !scopes.is_empty())
|
||||||
|
&& !schemes.get(name).is_some_and(supports_named_scopes)
|
||||||
|
{
|
||||||
|
alternative_findings.push("unexpected_security_scopes".to_owned());
|
||||||
|
findings.push((
|
||||||
|
document_finding(
|
||||||
|
"unexpected_security_scopes",
|
||||||
|
format!("Схема {name} не поддерживает OAuth scopes; непустой список блокирует эту alternative."),
|
||||||
|
),
|
||||||
|
SourceLocation {
|
||||||
|
pointer: format!("{alternative_pointer}/{}", super::normalize_coverage::escape_pointer(name)),
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if !schemes.contains_key(name) {
|
||||||
|
alternative_findings.push("unresolved_security_scheme".to_owned());
|
||||||
|
findings.push((
|
||||||
|
document_finding(
|
||||||
|
"unresolved_security_scheme",
|
||||||
|
format!(
|
||||||
|
"Альтернатива требует неизвестную схему {name} и недоступна для выбора."
|
||||||
|
),
|
||||||
|
),
|
||||||
|
SourceLocation {
|
||||||
|
pointer: format!(
|
||||||
|
"{alternative_pointer}/{}",
|
||||||
|
super::normalize_coverage::escape_pointer(name)
|
||||||
|
),
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if names.len() > 1 {
|
||||||
|
alternative_findings.push("unsupported_security_and_requirement".to_owned());
|
||||||
|
findings.push((
|
||||||
|
document_finding(
|
||||||
|
"unsupported_security_and_requirement",
|
||||||
|
format!("Альтернатива требует AND-сочетание схем {}; текущий импорт поддерживает только одну Auth Profile и не сохраняет это сочетание.", names.join(", ")),
|
||||||
|
),
|
||||||
|
SourceLocation {
|
||||||
|
pointer: alternative_pointer.clone(),
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if let Some((_unsupported, message)) = names.iter().find_map(|name| {
|
||||||
|
schemes.get(name).and_then(|scheme| match &scheme.kind {
|
||||||
|
NormalizedSecuritySchemeKind::Unsupported { .. } => Some((
|
||||||
|
name,
|
||||||
|
format!("Альтернатива использует неподдерживаемую схему {name} и недоступна для выбора."),
|
||||||
|
)),
|
||||||
|
NormalizedSecuritySchemeKind::ApiKey {
|
||||||
|
location: SecurityParameterLocation::Cookie,
|
||||||
|
..
|
||||||
|
} => Some((
|
||||||
|
name,
|
||||||
|
format!("Схема {name} передаёт ключ через cookie, чего текущий Auth Profile runtime не поддерживает; настройте authentication вручную."),
|
||||||
|
)),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
}) {
|
||||||
|
alternative_findings.push("unsupported_security_scheme".to_owned());
|
||||||
|
findings.push((
|
||||||
|
document_finding(
|
||||||
|
"unsupported_security_scheme",
|
||||||
|
message,
|
||||||
|
),
|
||||||
|
SourceLocation {
|
||||||
|
pointer: format!("{alternative_pointer}/{}", super::normalize_coverage::escape_pointer(_unsupported)),
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
alternative_findings.sort();
|
||||||
|
alternative_findings.dedup();
|
||||||
|
let supported = alternative_findings.is_empty();
|
||||||
|
supported_alternatives += usize::from(supported);
|
||||||
|
projected.push(SecurityRequirementAlternative {
|
||||||
|
schemes: names,
|
||||||
|
supported,
|
||||||
|
findings: alternative_findings,
|
||||||
|
source_location: Some(SourceLocation {
|
||||||
|
pointer: alternative_pointer,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if !projected.is_empty() && supported_alternatives == 0 {
|
||||||
|
findings.push((
|
||||||
|
document_blocker(
|
||||||
|
"unsupported_security_requirements",
|
||||||
|
"Ни одну authentication alternative нельзя безопасно выбрать; импорт операции заблокирован.",
|
||||||
|
),
|
||||||
|
SourceLocation { pointer },
|
||||||
|
));
|
||||||
|
}
|
||||||
|
(
|
||||||
|
NormalizedSecurityRequirements {
|
||||||
|
source,
|
||||||
|
alternatives: projected,
|
||||||
|
},
|
||||||
|
findings,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn collect_operation_requirements(
|
||||||
|
root: &Value,
|
||||||
|
operation: &Value,
|
||||||
|
pointer: &str,
|
||||||
|
schemes: &BTreeMap<String, NormalizedSecurityScheme>,
|
||||||
|
findings: &mut Vec<(super::model::ImportFinding, SourceLocation)>,
|
||||||
|
) -> NormalizedSecurityRequirements {
|
||||||
|
let (requirements, security_findings) =
|
||||||
|
effective_requirements(root, operation, pointer, schemes);
|
||||||
|
findings.extend(security_findings);
|
||||||
|
requirements
|
||||||
|
}
|
||||||
|
|
||||||
|
fn supports_named_scopes(scheme: &NormalizedSecurityScheme) -> bool {
|
||||||
|
matches!(
|
||||||
|
&scheme.kind,
|
||||||
|
NormalizedSecuritySchemeKind::Unsupported {
|
||||||
|
scheme_type: Some(scheme_type)
|
||||||
|
} if matches!(scheme_type.as_str(), "oauth2" | "openIdConnect")
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,287 @@
|
|||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
use super::model::SourceLocation;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||||
|
pub struct SecretLiteralFinding {
|
||||||
|
pub location: SourceLocation,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Scans UTF-8 JSON or YAML and returns source locations without literal values.
|
||||||
|
pub fn scan_secret_literals(
|
||||||
|
bytes: &[u8],
|
||||||
|
) -> Result<Vec<SecretLiteralFinding>, super::normalize::ImportParseError> {
|
||||||
|
let document = std::str::from_utf8(bytes)
|
||||||
|
.map_err(|_| super::normalize::ImportParseError::InvalidDocument)?;
|
||||||
|
let mut root = super::normalize::decode(document)?;
|
||||||
|
Ok(inspect_and_redact(&mut root))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn inspect_and_redact(root: &mut Value) -> Vec<SecretLiteralFinding> {
|
||||||
|
let mut findings = Vec::new();
|
||||||
|
walk(root, "", false, false, &mut findings, true, false);
|
||||||
|
findings
|
||||||
|
}
|
||||||
|
|
||||||
|
fn walk(
|
||||||
|
value: &mut Value,
|
||||||
|
pointer: &str,
|
||||||
|
sensitive_context: bool,
|
||||||
|
example_context: bool,
|
||||||
|
findings: &mut Vec<SecretLiteralFinding>,
|
||||||
|
redact: bool,
|
||||||
|
cookie_context: bool,
|
||||||
|
) {
|
||||||
|
if example_context
|
||||||
|
&& value
|
||||||
|
.as_object()
|
||||||
|
.is_some_and(|fields| fields.keys().any(|key| is_jwt(key)))
|
||||||
|
{
|
||||||
|
findings.push(SecretLiteralFinding {
|
||||||
|
location: SourceLocation {
|
||||||
|
pointer: pointer.to_owned(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if redact {
|
||||||
|
*value = Value::String("[REDACTED]".to_owned());
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
match value {
|
||||||
|
Value::Object(fields) => {
|
||||||
|
let header_parameter = fields
|
||||||
|
.get("in")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.is_some_and(|location| location.eq_ignore_ascii_case("header"));
|
||||||
|
let parameter_name = fields.get("name").and_then(Value::as_str).unwrap_or("");
|
||||||
|
let named_sensitive_parameter =
|
||||||
|
sensitive_key(parameter_name) && fields.get("in").and_then(Value::as_str).is_some();
|
||||||
|
let named_cookie_header = is_cookie_header(parameter_name);
|
||||||
|
for (key, child) in fields {
|
||||||
|
let child_pointer = format!(
|
||||||
|
"{pointer}/{}",
|
||||||
|
super::normalize_coverage::escape_pointer(key)
|
||||||
|
);
|
||||||
|
let property_definition = (pointer.contains("/properties/")
|
||||||
|
|| pointer.ends_with("/properties"))
|
||||||
|
&& !key.to_ascii_lowercase().starts_with("x-");
|
||||||
|
let sensitive = sensitive_context
|
||||||
|
|| (sensitive_key(key)
|
||||||
|
&& !property_definition
|
||||||
|
&& !is_oauth_flow_name(pointer, key));
|
||||||
|
let example = example_context
|
||||||
|
|| matches!(
|
||||||
|
key.to_ascii_lowercase().as_str(),
|
||||||
|
"example" | "examples" | "default"
|
||||||
|
);
|
||||||
|
let header_example = header_parameter
|
||||||
|
&& matches!(
|
||||||
|
key.to_ascii_lowercase().as_str(),
|
||||||
|
"example" | "examples" | "default"
|
||||||
|
);
|
||||||
|
let named_header = is_cookie_header(key);
|
||||||
|
let credential_example = matches!(
|
||||||
|
key.to_ascii_lowercase().as_str(),
|
||||||
|
"example" | "examples" | "default"
|
||||||
|
) && (named_sensitive_parameter
|
||||||
|
|| (cookie_context && !property_definition)
|
||||||
|
|| (named_cookie_header && !property_definition));
|
||||||
|
walk(
|
||||||
|
child,
|
||||||
|
&child_pointer,
|
||||||
|
sensitive || header_example || credential_example,
|
||||||
|
example,
|
||||||
|
findings,
|
||||||
|
redact,
|
||||||
|
cookie_context || named_cookie_header || named_header,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Value::Array(items) => {
|
||||||
|
for (index, child) in items.iter_mut().enumerate() {
|
||||||
|
walk(
|
||||||
|
child,
|
||||||
|
&format!("{pointer}/{index}"),
|
||||||
|
sensitive_context,
|
||||||
|
example_context,
|
||||||
|
findings,
|
||||||
|
redact,
|
||||||
|
cookie_context,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Value::String(string) => {
|
||||||
|
let userinfo = url_userinfo_range(string);
|
||||||
|
let query_secret = sensitive_query_value(string);
|
||||||
|
let likely_example_secret = (example_context
|
||||||
|
&& (looks_secret_like(pointer, string) || is_jwt(string)))
|
||||||
|
|| looks_secret_value(string)
|
||||||
|
|| ((pointer.ends_with("/bearerFormat") || pointer.ends_with("/x-format-hint"))
|
||||||
|
&& looks_secret_like(pointer, string));
|
||||||
|
if sensitive_context || likely_example_secret || userinfo.is_some() || query_secret {
|
||||||
|
findings.push(SecretLiteralFinding {
|
||||||
|
location: SourceLocation {
|
||||||
|
pointer: pointer.to_owned(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if redact {
|
||||||
|
if query_secret {
|
||||||
|
*string = "[REDACTED]".to_owned();
|
||||||
|
} else if let Some((start, end)) = userinfo {
|
||||||
|
string.replace_range(start..end, "[REDACTED]");
|
||||||
|
} else {
|
||||||
|
*string = "[REDACTED]".to_owned();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Value::Number(_) | Value::Bool(_) if sensitive_context => {
|
||||||
|
findings.push(SecretLiteralFinding {
|
||||||
|
location: SourceLocation {
|
||||||
|
pointer: pointer.to_owned(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
if redact {
|
||||||
|
*value = Value::String("[REDACTED]".to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sensitive_key(key: &str) -> bool {
|
||||||
|
let mut normalized = String::new();
|
||||||
|
let mut previous_lower = false;
|
||||||
|
for ch in key.chars() {
|
||||||
|
if ch.is_ascii_uppercase() && previous_lower {
|
||||||
|
normalized.push('_');
|
||||||
|
}
|
||||||
|
if ch == '-' || ch == ' ' {
|
||||||
|
normalized.push('_');
|
||||||
|
} else {
|
||||||
|
normalized.push(ch.to_ascii_lowercase());
|
||||||
|
}
|
||||||
|
previous_lower = ch.is_ascii_lowercase() || ch.is_ascii_digit();
|
||||||
|
}
|
||||||
|
let key = normalized;
|
||||||
|
if matches!(key.as_str(), "authorization_url" | "token_url") {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
[
|
||||||
|
"token",
|
||||||
|
"secret",
|
||||||
|
"secret_hash",
|
||||||
|
"secrethash",
|
||||||
|
"password",
|
||||||
|
"password_hash",
|
||||||
|
"passwordhash",
|
||||||
|
"passwd",
|
||||||
|
"api_key",
|
||||||
|
"apikey",
|
||||||
|
"authorization",
|
||||||
|
"credential",
|
||||||
|
"credentials",
|
||||||
|
"access_key",
|
||||||
|
"private_key",
|
||||||
|
"privatekey",
|
||||||
|
"ciphertext",
|
||||||
|
]
|
||||||
|
.iter()
|
||||||
|
.any(|marker| {
|
||||||
|
key == *marker
|
||||||
|
|| key.ends_with(&format!("_{marker}"))
|
||||||
|
|| key.starts_with(&format!("{marker}_"))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_oauth_flow_name(parent_pointer: &str, key: &str) -> bool {
|
||||||
|
if !parent_pointer.ends_with("/flows") {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let compact_key: String = key
|
||||||
|
.chars()
|
||||||
|
.filter(|character| character.is_ascii_alphanumeric())
|
||||||
|
.map(|character| character.to_ascii_lowercase())
|
||||||
|
.collect();
|
||||||
|
matches!(
|
||||||
|
compact_key.as_str(),
|
||||||
|
"implicit" | "password" | "clientcredentials" | "authorizationcode"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_cookie_header(value: &str) -> bool {
|
||||||
|
value.eq_ignore_ascii_case("cookie") || value.eq_ignore_ascii_case("set-cookie")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_jwt(value: &str) -> bool {
|
||||||
|
let mut parts = value.split('.');
|
||||||
|
let Some(header) = parts.next() else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let Some(payload) = parts.next() else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let Some(signature) = parts.next() else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
parts.next().is_none()
|
||||||
|
&& header.starts_with("eyJ")
|
||||||
|
&& payload.starts_with("eyJ")
|
||||||
|
&& header.len() >= 8
|
||||||
|
&& payload.len() >= 16
|
||||||
|
&& signature.len() >= 12
|
||||||
|
&& [header, payload, signature].iter().all(|part| {
|
||||||
|
!part.is_empty()
|
||||||
|
&& part
|
||||||
|
.bytes()
|
||||||
|
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sensitive_query_value(value: &str) -> bool {
|
||||||
|
let Some(query_start) = value.find('?') else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
value[query_start + 1..]
|
||||||
|
.split('#')
|
||||||
|
.next()
|
||||||
|
.unwrap_or_default()
|
||||||
|
.split(['&', ';'])
|
||||||
|
.any(|pair| {
|
||||||
|
let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
|
||||||
|
!value.is_empty() && sensitive_key(key)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn looks_secret_like(pointer: &str, value: &str) -> bool {
|
||||||
|
let pointer = pointer.to_ascii_lowercase();
|
||||||
|
let value = value.to_ascii_lowercase();
|
||||||
|
[
|
||||||
|
"token",
|
||||||
|
"secret",
|
||||||
|
"password",
|
||||||
|
"api_key",
|
||||||
|
"apikey",
|
||||||
|
"authorization",
|
||||||
|
]
|
||||||
|
.iter()
|
||||||
|
.any(|marker| pointer.contains(marker) || value.contains(marker))
|
||||||
|
|| value.starts_with("bearer ")
|
||||||
|
|| value.starts_with("sk-")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn looks_secret_value(value: &str) -> bool {
|
||||||
|
let value = value.to_ascii_lowercase();
|
||||||
|
value.starts_with("bearer ") || value.starts_with("sk-")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn url_userinfo_range(value: &str) -> Option<(usize, usize)> {
|
||||||
|
let scheme_end = value.find("://")? + 3;
|
||||||
|
let authority_end = value[scheme_end..]
|
||||||
|
.find('/')
|
||||||
|
.map(|index| scheme_end + index)
|
||||||
|
.unwrap_or(value.len());
|
||||||
|
let authority = &value[scheme_end..authority_end];
|
||||||
|
let at = authority.find('@')?;
|
||||||
|
(at > 0).then_some((scheme_end, scheme_end + at))
|
||||||
|
}
|
||||||
@@ -3,11 +3,11 @@ use serde_json::Value;
|
|||||||
|
|
||||||
use crate::rest::{
|
use crate::rest::{
|
||||||
model::{
|
model::{
|
||||||
ImportFinding, ImportFindingSeverity, RestImportDocument, RestImportOperation,
|
ImportFinding, RestImportDocument, RestImportOperation, RestImportParameter,
|
||||||
RestImportParameter, RestParameterLocation,
|
RestParameterLocation, RestRequestBodyVariant, RestResponseVariant,
|
||||||
},
|
},
|
||||||
normalize::ImportParseError,
|
normalize::ImportParseError,
|
||||||
recommendations::{document_blocker, document_finding, operation_finding},
|
recommendations::{document_blocker, document_finding},
|
||||||
};
|
};
|
||||||
|
|
||||||
pub fn parse_document(root: &Value) -> Result<RestImportDocument, ImportParseError> {
|
pub fn parse_document(root: &Value) -> Result<RestImportDocument, ImportParseError> {
|
||||||
@@ -21,8 +21,14 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
|||||||
.unwrap_or("Imported API")
|
.unwrap_or("Imported API")
|
||||||
.to_owned();
|
.to_owned();
|
||||||
let servers = swagger_servers(root);
|
let servers = swagger_servers(root);
|
||||||
|
let security_schemes = super::security::schemes(root, true);
|
||||||
let mut findings = Vec::new();
|
let mut findings = Vec::new();
|
||||||
let mut internal_finding_locations = Vec::new();
|
let mut internal_finding_locations = Vec::new();
|
||||||
|
append_parameter_findings(
|
||||||
|
&mut findings,
|
||||||
|
&mut internal_finding_locations,
|
||||||
|
super::swagger2_findings::servers(root),
|
||||||
|
);
|
||||||
if servers.is_empty() {
|
if servers.is_empty() {
|
||||||
findings.push(document_finding(
|
findings.push(document_finding(
|
||||||
"missing_servers",
|
"missing_servers",
|
||||||
@@ -41,13 +47,13 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
|||||||
|
|
||||||
for (path, path_item) in paths {
|
for (path, path_item) in paths {
|
||||||
if !path_item.is_object() {
|
if !path_item.is_object() {
|
||||||
findings.push(path_item_blocker(path));
|
findings.push(super::http_methods::invalid_path_item());
|
||||||
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
|
internal_finding_locations.push(Some(crate::rest::model::SourceLocation {
|
||||||
pointer: format!("/paths/{}", path.replace('~', "~0").replace('/', "~1")),
|
pointer: format!("/paths/{}", path.replace('~', "~0").replace('/', "~1")),
|
||||||
}));
|
}));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
for method_name in ["head", "options", "trace", "connect"] {
|
for method_name in super::swagger2_findings::unsupported_methods(path_item) {
|
||||||
if path_item.get(method_name).is_some() {
|
if path_item.get(method_name).is_some() {
|
||||||
findings.push(document_blocker(
|
findings.push(document_blocker(
|
||||||
"unsupported_http_method",
|
"unsupported_http_method",
|
||||||
@@ -74,7 +80,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
|||||||
path_parameters.findings,
|
path_parameters.findings,
|
||||||
);
|
);
|
||||||
let path_parameters = path_parameters.parameters;
|
let path_parameters = path_parameters.parameters;
|
||||||
for method_name in ["get", "post", "put", "patch", "delete"] {
|
for method_name in ["get", "post", "put", "patch", "delete", "head", "options"] {
|
||||||
let Some(operation_value) = path_item.get(method_name) else {
|
let Some(operation_value) = path_item.get(method_name) else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
@@ -92,7 +98,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
|||||||
}));
|
}));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let Some(method) = method_from_lower(method_name) else {
|
let Some(method) = super::http_methods::from_lower(method_name) else {
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
let mut operation_parameters = path_parameters.clone();
|
let mut operation_parameters = path_parameters.clone();
|
||||||
@@ -101,11 +107,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
|||||||
operation_value.get("parameters"),
|
operation_value.get("parameters"),
|
||||||
&format!("{path_pointer}/{method_name}/parameters"),
|
&format!("{path_pointer}/{method_name}/parameters"),
|
||||||
);
|
);
|
||||||
append_parameter_findings(
|
let parsed_parameter_findings = parsed_parameters.findings;
|
||||||
&mut findings,
|
|
||||||
&mut internal_finding_locations,
|
|
||||||
parsed_parameters.findings,
|
|
||||||
);
|
|
||||||
operation_parameters.extend(parsed_parameters.parameters);
|
operation_parameters.extend(parsed_parameters.parameters);
|
||||||
deduplicate_parameters(&mut operation_parameters);
|
deduplicate_parameters(&mut operation_parameters);
|
||||||
let tags = tags(
|
let tags = tags(
|
||||||
@@ -117,6 +119,13 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
|||||||
&mut internal_finding_locations,
|
&mut internal_finding_locations,
|
||||||
tags.findings,
|
tags.findings,
|
||||||
);
|
);
|
||||||
|
let request_body_variants = swagger_request_body_variants(
|
||||||
|
root,
|
||||||
|
path_item,
|
||||||
|
operation_value,
|
||||||
|
&path_pointer,
|
||||||
|
&format!("{path_pointer}/{method_name}"),
|
||||||
|
);
|
||||||
let request_body_schema = operation_parameters
|
let request_body_schema = operation_parameters
|
||||||
.iter()
|
.iter()
|
||||||
.find(|parameter| parameter.name == "body")
|
.find(|parameter| parameter.name == "body")
|
||||||
@@ -135,10 +144,31 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
|||||||
.filter(|parameter| parameter.name != "body")
|
.filter(|parameter| parameter.name != "body")
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
|
let operation_pointer = format!("{path_pointer}/{method_name}");
|
||||||
|
let mut located_operation_findings =
|
||||||
|
super::swagger2_findings::operation(root, operation_value, &operation_pointer);
|
||||||
|
let security_requirements = super::security::collect_operation_requirements(
|
||||||
|
root,
|
||||||
|
operation_value,
|
||||||
|
&operation_pointer,
|
||||||
|
&security_schemes,
|
||||||
|
&mut located_operation_findings,
|
||||||
|
);
|
||||||
|
located_operation_findings.extend(parsed_parameter_findings);
|
||||||
|
located_operation_findings.extend(super::swagger2_findings::path_parameters(
|
||||||
|
path,
|
||||||
|
&operation_parameters,
|
||||||
|
));
|
||||||
|
let (operation_findings, internal_finding_locations) =
|
||||||
|
located_operation_findings.into_iter().unzip();
|
||||||
|
let response_schema = (method != HttpMethod::Head)
|
||||||
|
.then(|| response_schema(operation_value, &operation_pointer))
|
||||||
|
.flatten();
|
||||||
operations.push(RestImportOperation {
|
operations.push(RestImportOperation {
|
||||||
key: format!("{} {}", method_name.to_uppercase(), path),
|
key: format!("{} {}", method_name.to_uppercase(), path),
|
||||||
method,
|
method,
|
||||||
path: path.clone(),
|
path: path.clone(),
|
||||||
|
security_requirements,
|
||||||
operation_id: operation_value
|
operation_id: operation_value
|
||||||
.get("operationId")
|
.get("operationId")
|
||||||
.and_then(Value::as_str)
|
.and_then(Value::as_str)
|
||||||
@@ -157,18 +187,18 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
|||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|(schema, _)| schema.clone()),
|
.map(|(schema, _)| schema.clone()),
|
||||||
request_body_schema_location: request_body_schema.map(|(_, location)| location),
|
request_body_schema_location: request_body_schema.map(|(_, location)| location),
|
||||||
response_schema: response_schema(
|
request_body_variants,
|
||||||
|
response_schema: response_schema.as_ref().map(|(schema, _)| schema.clone()),
|
||||||
|
response_schema_location: response_schema.map(|(_, location)| location),
|
||||||
|
response_variants: swagger_response_variants(
|
||||||
|
root,
|
||||||
operation_value,
|
operation_value,
|
||||||
&format!("{path_pointer}/{method_name}"),
|
&operation_pointer,
|
||||||
)
|
method,
|
||||||
.map(|(schema, _)| schema),
|
),
|
||||||
response_schema_location: response_schema(
|
|
||||||
operation_value,
|
|
||||||
&format!("{path_pointer}/{method_name}"),
|
|
||||||
)
|
|
||||||
.map(|(_, location)| location),
|
|
||||||
servers: Vec::new(),
|
servers: Vec::new(),
|
||||||
findings: swagger_operation_findings(path, operation_value),
|
findings: operation_findings,
|
||||||
|
internal_finding_locations,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -178,6 +208,7 @@ fn parse_document_v2(root: &Value) -> Result<RestImportDocument, ImportParseErro
|
|||||||
version: Some("2.0".to_owned()),
|
version: Some("2.0".to_owned()),
|
||||||
title,
|
title,
|
||||||
servers,
|
servers,
|
||||||
|
security_schemes,
|
||||||
operations,
|
operations,
|
||||||
findings,
|
findings,
|
||||||
internal_finding_locations,
|
internal_finding_locations,
|
||||||
@@ -191,206 +222,29 @@ fn deduplicate_parameters(parameters: &mut Vec<RestImportParameter>) {
|
|||||||
parameters.reverse();
|
parameters.reverse();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn parse_document_legacy_v1(root: &Value) -> Result<RestImportDocument, ImportParseError> {
|
pub(super) fn swagger_servers(root: &Value) -> Vec<String> {
|
||||||
let title = root
|
let Some(host) = root.get("host").and_then(Value::as_str) else {
|
||||||
.pointer("/info/title")
|
return Vec::new();
|
||||||
.and_then(Value::as_str)
|
|
||||||
.unwrap_or("Imported API")
|
|
||||||
.to_owned();
|
|
||||||
let servers = swagger_servers(root);
|
|
||||||
let mut findings = Vec::new();
|
|
||||||
if servers.is_empty() {
|
|
||||||
findings.push(document_finding(
|
|
||||||
"missing_servers",
|
|
||||||
"В Swagger 2.0 документе не указаны host/schemes, base URL нужно будет выбрать вручную.",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
let mut operations = Vec::new();
|
|
||||||
let paths = root
|
|
||||||
.get("paths")
|
|
||||||
.and_then(Value::as_object)
|
|
||||||
.ok_or(ImportParseError::UnsupportedDocument)?;
|
|
||||||
for (path, path_item) in paths {
|
|
||||||
let path_pointer = format!("/paths/{}", path.replace('~', "~0").replace('/', "~1"));
|
|
||||||
let path_parameters = legacy_parameters(
|
|
||||||
root,
|
|
||||||
path_item.get("parameters"),
|
|
||||||
&format!("{path_pointer}/parameters"),
|
|
||||||
);
|
|
||||||
for method_name in ["get", "post", "put", "patch", "delete"] {
|
|
||||||
let Some(operation) = path_item.get(method_name) else {
|
|
||||||
continue;
|
|
||||||
};
|
};
|
||||||
let Some(method) = method_from_lower(method_name) else {
|
let base_path = root.get("basePath").and_then(Value::as_str).unwrap_or("");
|
||||||
continue;
|
if host.is_empty()
|
||||||
};
|
|| host.contains('@')
|
||||||
let operation_pointer = format!("{path_pointer}/{method_name}");
|
|| host.chars().any(char::is_whitespace)
|
||||||
let mut parameters = path_parameters.clone();
|
|| (!base_path.is_empty() && !base_path.starts_with('/'))
|
||||||
parameters.extend(legacy_parameters(
|
|| base_path.chars().any(char::is_control)
|
||||||
root,
|
{
|
||||||
operation.get("parameters"),
|
return Vec::new();
|
||||||
&format!("{operation_pointer}/parameters"),
|
|
||||||
));
|
|
||||||
let request_body_schema = parameters
|
|
||||||
.iter()
|
|
||||||
.find(|parameter| parameter.name == "body")
|
|
||||||
.and_then(|parameter| parameter.schema.clone());
|
|
||||||
let parameters = parameters
|
|
||||||
.into_iter()
|
|
||||||
.filter(|parameter| parameter.name != "body")
|
|
||||||
.collect();
|
|
||||||
operations.push(RestImportOperation {
|
|
||||||
key: format!("{} {}", method_name.to_uppercase(), path),
|
|
||||||
method,
|
|
||||||
path: path.clone(),
|
|
||||||
operation_id: operation
|
|
||||||
.get("operationId")
|
|
||||||
.and_then(Value::as_str)
|
|
||||||
.map(ToOwned::to_owned),
|
|
||||||
summary: operation
|
|
||||||
.get("summary")
|
|
||||||
.and_then(Value::as_str)
|
|
||||||
.map(ToOwned::to_owned),
|
|
||||||
description: operation
|
|
||||||
.get("description")
|
|
||||||
.and_then(Value::as_str)
|
|
||||||
.map(ToOwned::to_owned),
|
|
||||||
tags: legacy_tags(operation.get("tags")),
|
|
||||||
parameters,
|
|
||||||
request_body_schema,
|
|
||||||
request_body_schema_location: None,
|
|
||||||
response_schema: legacy_response_schema(root, operation),
|
|
||||||
response_schema_location: None,
|
|
||||||
servers: Vec::new(),
|
|
||||||
findings: swagger_operation_findings(path, operation),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
let schemes = root
|
||||||
Ok(RestImportDocument {
|
.get("schemes")
|
||||||
format: "swagger".to_owned(),
|
|
||||||
version: Some("2.0".to_owned()),
|
|
||||||
title,
|
|
||||||
servers,
|
|
||||||
operations,
|
|
||||||
findings,
|
|
||||||
internal_finding_locations: Vec::new(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn legacy_tags(value: Option<&Value>) -> Vec<String> {
|
|
||||||
value
|
|
||||||
.and_then(Value::as_array)
|
.and_then(Value::as_array)
|
||||||
.map(|items| {
|
.map(|items| {
|
||||||
items
|
items
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(Value::as_str)
|
.filter_map(Value::as_str)
|
||||||
.map(ToOwned::to_owned)
|
.filter(|scheme| matches!(*scheme, "http" | "https"))
|
||||||
.collect()
|
.collect::<Vec<_>>()
|
||||||
})
|
})
|
||||||
.unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn legacy_parameters(
|
|
||||||
root: &Value,
|
|
||||||
value: Option<&Value>,
|
|
||||||
base_pointer: &str,
|
|
||||||
) -> Vec<RestImportParameter> {
|
|
||||||
value
|
|
||||||
.and_then(Value::as_array)
|
|
||||||
.map(|items| {
|
|
||||||
items
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.filter_map(|(index, item)| {
|
|
||||||
let item = crate::rest::normalize::resolve_local_ref(root, item, 0);
|
|
||||||
let raw_location = item.get("in").and_then(Value::as_str)?;
|
|
||||||
let pointer = format!("{base_pointer}/{index}");
|
|
||||||
if raw_location == "body" {
|
|
||||||
return Some(RestImportParameter {
|
|
||||||
name: "body".to_owned(),
|
|
||||||
location: RestParameterLocation::Query,
|
|
||||||
required: item
|
|
||||||
.get("required")
|
|
||||||
.and_then(Value::as_bool)
|
|
||||||
.unwrap_or(false),
|
|
||||||
description: item
|
|
||||||
.get("description")
|
|
||||||
.and_then(Value::as_str)
|
|
||||||
.map(ToOwned::to_owned),
|
|
||||||
schema: item.get("schema").map(|schema| {
|
|
||||||
crate::rest::normalize::resolve_local_ref(root, schema, 0)
|
|
||||||
}),
|
|
||||||
source_location: crate::rest::model::SourceLocation { pointer },
|
|
||||||
schema_source_location: None,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
let location = match raw_location {
|
|
||||||
"path" => RestParameterLocation::Path,
|
|
||||||
"query" => RestParameterLocation::Query,
|
|
||||||
"header" => RestParameterLocation::Header,
|
|
||||||
_ => return None,
|
|
||||||
};
|
|
||||||
Some(RestImportParameter {
|
|
||||||
name: item.get("name").and_then(Value::as_str)?.to_owned(),
|
|
||||||
location,
|
|
||||||
required: item
|
|
||||||
.get("required")
|
|
||||||
.and_then(Value::as_bool)
|
|
||||||
.unwrap_or(false)
|
|
||||||
|| location == RestParameterLocation::Path,
|
|
||||||
description: item
|
|
||||||
.get("description")
|
|
||||||
.and_then(Value::as_str)
|
|
||||||
.map(ToOwned::to_owned),
|
|
||||||
schema: legacy_parameter_schema(root, &item),
|
|
||||||
source_location: crate::rest::model::SourceLocation { pointer },
|
|
||||||
schema_source_location: None,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
})
|
|
||||||
.unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn legacy_parameter_schema(root: &Value, parameter: &Value) -> Option<Value> {
|
|
||||||
if let Some(schema) = parameter.get("schema") {
|
|
||||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
|
||||||
}
|
|
||||||
let mut schema = serde_json::Map::new();
|
|
||||||
for key in ["type", "format", "items", "enum", "default", "description"] {
|
|
||||||
if let Some(value) = parameter.get(key) {
|
|
||||||
schema.insert(
|
|
||||||
key.to_owned(),
|
|
||||||
crate::rest::normalize::resolve_local_ref(root, value, 0),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
(!schema.is_empty()).then_some(Value::Object(schema))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn legacy_response_schema(root: &Value, operation: &Value) -> Option<Value> {
|
|
||||||
let responses = operation.get("responses")?.as_object()?;
|
|
||||||
for code in ["200", "201", "202", "default"] {
|
|
||||||
let Some(response) = responses.get(code) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let response = crate::rest::normalize::resolve_local_ref(root, response, 0);
|
|
||||||
if let Some(schema) = response.get("schema") {
|
|
||||||
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
fn swagger_servers(root: &Value) -> Vec<String> {
|
|
||||||
let Some(host) = root.get("host").and_then(Value::as_str) else {
|
|
||||||
return Vec::new();
|
|
||||||
};
|
|
||||||
let base_path = root.get("basePath").and_then(Value::as_str).unwrap_or("");
|
|
||||||
let schemes = root
|
|
||||||
.get("schemes")
|
|
||||||
.and_then(Value::as_array)
|
|
||||||
.map(|items| items.iter().filter_map(Value::as_str).collect::<Vec<_>>())
|
|
||||||
.filter(|items| !items.is_empty())
|
.filter(|items| !items.is_empty())
|
||||||
.unwrap_or_else(|| vec!["https"]);
|
.unwrap_or_else(|| vec!["https"]);
|
||||||
|
|
||||||
@@ -450,6 +304,14 @@ fn parameters(_root: &Value, value: Option<&Value>, base_pointer: &str) -> Parse
|
|||||||
}
|
}
|
||||||
let item = item.clone();
|
let item = item.clone();
|
||||||
let raw_location = item.get("in").and_then(Value::as_str)?;
|
let raw_location = item.get("in").and_then(Value::as_str)?;
|
||||||
|
let parameter_schema = swagger_parameter_schema(_root, &item);
|
||||||
|
if parameter_schema.is_none() {
|
||||||
|
findings.push(parameter_blocker(
|
||||||
|
"missing_parameter_schema",
|
||||||
|
"Swagger parameter не содержит schema/type.",
|
||||||
|
&pointer,
|
||||||
|
));
|
||||||
|
}
|
||||||
if raw_location == "body" {
|
if raw_location == "body" {
|
||||||
return Some(RestImportParameter {
|
return Some(RestImportParameter {
|
||||||
name: "body".to_owned(),
|
name: "body".to_owned(),
|
||||||
@@ -473,6 +335,14 @@ fn parameters(_root: &Value, value: Option<&Value>, base_pointer: &str) -> Parse
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
if raw_location == "formData" {
|
||||||
|
findings.extend(super::swagger2_findings::form_data_parameter(
|
||||||
|
&item,
|
||||||
|
parameter_schema.as_ref(),
|
||||||
|
&pointer,
|
||||||
|
));
|
||||||
|
return None;
|
||||||
|
}
|
||||||
let location = match raw_location {
|
let location = match raw_location {
|
||||||
"path" => RestParameterLocation::Path,
|
"path" => RestParameterLocation::Path,
|
||||||
"query" => RestParameterLocation::Query,
|
"query" => RestParameterLocation::Query,
|
||||||
@@ -494,14 +364,35 @@ fn parameters(_root: &Value, value: Option<&Value>, base_pointer: &str) -> Parse
|
|||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
if parameter_schema.as_ref().is_some_and(|schema| {
|
||||||
|
matches!(schema.get("type").and_then(Value::as_str), Some("array" | "object"))
|
||||||
|
}) || item.get("collectionFormat").is_some()
|
||||||
|
{
|
||||||
|
let finding_pointer = if item.get("collectionFormat").is_some() {
|
||||||
|
format!("{pointer}/collectionFormat")
|
||||||
|
} else {
|
||||||
|
pointer.clone()
|
||||||
|
};
|
||||||
|
findings.push(parameter_blocker(
|
||||||
|
"unsupported_parameter_style",
|
||||||
|
"Swagger array/object parameter serialization не поддерживается текущим REST mapping.",
|
||||||
|
&finding_pointer,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
if let Some(schema) = swagger_parameter_schema(_root, &item) {
|
||||||
|
super::openapi3_findings::schema_findings(
|
||||||
|
&schema,
|
||||||
|
&pointer,
|
||||||
|
&mut findings,
|
||||||
|
);
|
||||||
|
}
|
||||||
Some(RestImportParameter {
|
Some(RestImportParameter {
|
||||||
name: item.get("name").and_then(Value::as_str)?.to_owned(),
|
name: item.get("name").and_then(Value::as_str)?.to_owned(),
|
||||||
location,
|
location,
|
||||||
required: item
|
required: item
|
||||||
.get("required")
|
.get("required")
|
||||||
.and_then(Value::as_bool)
|
.and_then(Value::as_bool)
|
||||||
.unwrap_or(false)
|
.unwrap_or(false),
|
||||||
|| location == RestParameterLocation::Path,
|
|
||||||
description: item
|
description: item
|
||||||
.get("description")
|
.get("description")
|
||||||
.and_then(Value::as_str)
|
.and_then(Value::as_str)
|
||||||
@@ -597,6 +488,10 @@ fn swagger_parameter_schema(_root: &Value, parameter: &Value) -> Option<Value> {
|
|||||||
schema.insert(key.to_owned(), value.clone());
|
schema.insert(key.to_owned(), value.clone());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if schema.get("type").and_then(Value::as_str) == Some("file") {
|
||||||
|
schema.insert("type".to_owned(), Value::String("string".to_owned()));
|
||||||
|
schema.insert("format".to_owned(), Value::String("binary".to_owned()));
|
||||||
|
}
|
||||||
if schema.is_empty() {
|
if schema.is_empty() {
|
||||||
None
|
None
|
||||||
} else {
|
} else {
|
||||||
@@ -630,6 +525,266 @@ fn response_schema(
|
|||||||
.and_then(|response| response_schema_at(response, operation_pointer, "default"))
|
.and_then(|response| response_schema_at(response, operation_pointer, "default"))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn swagger_request_body_variants(
|
||||||
|
root: &Value,
|
||||||
|
path_item: &Value,
|
||||||
|
operation: &Value,
|
||||||
|
path_pointer: &str,
|
||||||
|
operation_pointer: &str,
|
||||||
|
) -> Vec<RestRequestBodyVariant> {
|
||||||
|
let parameters =
|
||||||
|
effective_swagger_parameters(path_item, operation, path_pointer, operation_pointer);
|
||||||
|
let body = parameters
|
||||||
|
.iter()
|
||||||
|
.find(|(parameter, _)| parameter.get("in").and_then(Value::as_str) == Some("body"));
|
||||||
|
let form = swagger_form_data_schema(¶meters);
|
||||||
|
let (schema, schema_source_location, schema_property_source_locations) =
|
||||||
|
if let Some((body, pointer)) = body {
|
||||||
|
let Some(schema) = body.get("schema").cloned() else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
(
|
||||||
|
schema,
|
||||||
|
Some(crate::rest::model::SourceLocation {
|
||||||
|
pointer: format!("{pointer}/schema"),
|
||||||
|
}),
|
||||||
|
Default::default(),
|
||||||
|
)
|
||||||
|
} else if let Some(form) = form {
|
||||||
|
form
|
||||||
|
} else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let required = body
|
||||||
|
.and_then(|(parameter, _)| parameter.get("required").and_then(Value::as_bool))
|
||||||
|
.unwrap_or_else(|| {
|
||||||
|
parameters.iter().any(|(parameter, _)| {
|
||||||
|
parameter.get("in").and_then(Value::as_str) == Some("formData")
|
||||||
|
&& parameter
|
||||||
|
.get("required")
|
||||||
|
.and_then(Value::as_bool)
|
||||||
|
.unwrap_or(false)
|
||||||
|
})
|
||||||
|
});
|
||||||
|
let content_types = effective_media_types(root, operation, "consumes", "application/json");
|
||||||
|
content_types
|
||||||
|
.into_iter()
|
||||||
|
.filter(|content_type| supported_request_content_type(content_type))
|
||||||
|
.map(|content_type| RestRequestBodyVariant {
|
||||||
|
content_type,
|
||||||
|
required,
|
||||||
|
schema: Some(schema.clone()),
|
||||||
|
multipart_field_mime_types: Default::default(),
|
||||||
|
source_location: crate::rest::model::SourceLocation {
|
||||||
|
pointer: schema_source_location
|
||||||
|
.as_ref()
|
||||||
|
.map(|location| location.pointer.trim_end_matches("/schema").to_owned())
|
||||||
|
.unwrap_or_else(|| format!("{operation_pointer}/parameters")),
|
||||||
|
},
|
||||||
|
schema_source_location: schema_source_location.clone(),
|
||||||
|
schema_property_source_locations: schema_property_source_locations.clone(),
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn effective_swagger_parameters(
|
||||||
|
path_item: &Value,
|
||||||
|
operation: &Value,
|
||||||
|
path_pointer: &str,
|
||||||
|
operation_pointer: &str,
|
||||||
|
) -> Vec<(Value, String)> {
|
||||||
|
let mut parameters = Vec::new();
|
||||||
|
for (owner, pointer) in [
|
||||||
|
(path_item, format!("{path_pointer}/parameters")),
|
||||||
|
(operation, format!("{operation_pointer}/parameters")),
|
||||||
|
] {
|
||||||
|
let Some(items) = owner.get("parameters").and_then(Value::as_array) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
for (index, parameter) in items.iter().enumerate() {
|
||||||
|
let Some(name) = parameter.get("name").and_then(Value::as_str) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some(location) = parameter.get("in").and_then(Value::as_str) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
parameters.retain(|(existing, _): &(Value, String)| {
|
||||||
|
existing.get("name").and_then(Value::as_str) != Some(name)
|
||||||
|
|| existing.get("in").and_then(Value::as_str) != Some(location)
|
||||||
|
});
|
||||||
|
parameters.push((parameter.clone(), format!("{pointer}/{index}")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
parameters
|
||||||
|
}
|
||||||
|
|
||||||
|
fn swagger_form_data_schema(
|
||||||
|
parameters: &[(Value, String)],
|
||||||
|
) -> Option<(
|
||||||
|
Value,
|
||||||
|
Option<crate::rest::model::SourceLocation>,
|
||||||
|
std::collections::BTreeMap<String, crate::rest::model::SourceLocation>,
|
||||||
|
)> {
|
||||||
|
let form_parameters = parameters
|
||||||
|
.iter()
|
||||||
|
.filter(|(parameter, _)| parameter.get("in").and_then(Value::as_str) == Some("formData"));
|
||||||
|
let mut properties = serde_json::Map::new();
|
||||||
|
let mut required = Vec::new();
|
||||||
|
let mut property_locations = std::collections::BTreeMap::new();
|
||||||
|
let mut root_pointer = None;
|
||||||
|
for (parameter, pointer) in form_parameters {
|
||||||
|
let Some(name) = parameter.get("name").and_then(Value::as_str) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
root_pointer.get_or_insert_with(|| {
|
||||||
|
pointer
|
||||||
|
.rsplit_once('/')
|
||||||
|
.map(|(parent, _)| parent.to_owned())
|
||||||
|
.unwrap_or_else(|| pointer.clone())
|
||||||
|
});
|
||||||
|
property_locations.insert(
|
||||||
|
name.to_owned(),
|
||||||
|
crate::rest::model::SourceLocation {
|
||||||
|
pointer: pointer.clone(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
properties.insert(
|
||||||
|
name.to_owned(),
|
||||||
|
swagger_parameter_schema(&Value::Null, parameter)
|
||||||
|
.unwrap_or_else(|| Value::Object(serde_json::Map::new())),
|
||||||
|
);
|
||||||
|
if parameter
|
||||||
|
.get("required")
|
||||||
|
.and_then(Value::as_bool)
|
||||||
|
.unwrap_or(false)
|
||||||
|
{
|
||||||
|
required.push(Value::String(name.to_owned()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if properties.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut schema = serde_json::Map::new();
|
||||||
|
schema.insert("type".to_owned(), Value::String("object".to_owned()));
|
||||||
|
schema.insert("properties".to_owned(), Value::Object(properties));
|
||||||
|
if !required.is_empty() {
|
||||||
|
schema.insert("required".to_owned(), Value::Array(required));
|
||||||
|
}
|
||||||
|
Some((
|
||||||
|
Value::Object(schema),
|
||||||
|
root_pointer.map(|pointer| crate::rest::model::SourceLocation { pointer }),
|
||||||
|
property_locations,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn supported_request_content_type(content_type: &str) -> bool {
|
||||||
|
content_type == "application/x-www-form-urlencoded"
|
||||||
|
|| content_type == "multipart/form-data"
|
||||||
|
|| content_type == "application/json"
|
||||||
|
|| content_type.ends_with("+json")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn effective_media_types(
|
||||||
|
root: &Value,
|
||||||
|
operation: &Value,
|
||||||
|
field: &str,
|
||||||
|
default: &str,
|
||||||
|
) -> Vec<String> {
|
||||||
|
operation
|
||||||
|
.get(field)
|
||||||
|
.or_else(|| root.get(field))
|
||||||
|
.and_then(Value::as_array)
|
||||||
|
.map(|items| {
|
||||||
|
items
|
||||||
|
.iter()
|
||||||
|
.filter_map(Value::as_str)
|
||||||
|
.map(ToOwned::to_owned)
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
})
|
||||||
|
.filter(|items| !items.is_empty())
|
||||||
|
.unwrap_or_else(|| vec![default.to_owned()])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn swagger_response_variants(
|
||||||
|
root: &Value,
|
||||||
|
operation: &Value,
|
||||||
|
operation_pointer: &str,
|
||||||
|
method: HttpMethod,
|
||||||
|
) -> Vec<RestResponseVariant> {
|
||||||
|
let Some(responses) = operation.get("responses").and_then(Value::as_object) else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let produces = effective_media_types(root, operation, "produces", "application/json");
|
||||||
|
let supported_produces = produces
|
||||||
|
.iter()
|
||||||
|
.filter(|content_type| supported_response_content_type(content_type))
|
||||||
|
.cloned()
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
let mut variants = responses
|
||||||
|
.iter()
|
||||||
|
.filter_map(|(code, response)| {
|
||||||
|
let status_code = code
|
||||||
|
.parse::<u16>()
|
||||||
|
.ok()
|
||||||
|
.filter(|code| (200..300).contains(code))?;
|
||||||
|
let schema = response.get("schema").cloned();
|
||||||
|
let pointer = format!(
|
||||||
|
"{operation_pointer}/responses/{}",
|
||||||
|
code.replace('~', "~0").replace('/', "~1")
|
||||||
|
);
|
||||||
|
if method == HttpMethod::Head {
|
||||||
|
return Some(vec![RestResponseVariant {
|
||||||
|
status_code,
|
||||||
|
content_type: None,
|
||||||
|
schema: None,
|
||||||
|
source_location: crate::rest::model::SourceLocation { pointer },
|
||||||
|
schema_source_location: None,
|
||||||
|
}]);
|
||||||
|
}
|
||||||
|
if schema.is_none() {
|
||||||
|
return Some(vec![RestResponseVariant {
|
||||||
|
status_code,
|
||||||
|
content_type: None,
|
||||||
|
schema,
|
||||||
|
source_location: crate::rest::model::SourceLocation { pointer },
|
||||||
|
schema_source_location: None,
|
||||||
|
}]);
|
||||||
|
}
|
||||||
|
if supported_produces.is_empty() {
|
||||||
|
return Some(Vec::new());
|
||||||
|
}
|
||||||
|
Some(
|
||||||
|
supported_produces
|
||||||
|
.iter()
|
||||||
|
.map(|content_type| RestResponseVariant {
|
||||||
|
status_code,
|
||||||
|
content_type: Some(content_type.clone()),
|
||||||
|
schema: schema.clone(),
|
||||||
|
source_location: crate::rest::model::SourceLocation {
|
||||||
|
pointer: pointer.clone(),
|
||||||
|
},
|
||||||
|
schema_source_location: Some(crate::rest::model::SourceLocation {
|
||||||
|
pointer: format!("{pointer}/schema"),
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.flatten()
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
variants.sort_by(|left, right| {
|
||||||
|
(left.status_code, left.content_type.as_deref().unwrap_or("")).cmp(&(
|
||||||
|
right.status_code,
|
||||||
|
right.content_type.as_deref().unwrap_or(""),
|
||||||
|
))
|
||||||
|
});
|
||||||
|
variants
|
||||||
|
}
|
||||||
|
|
||||||
|
fn supported_response_content_type(content_type: &str) -> bool {
|
||||||
|
content_type == "application/json" || content_type.ends_with("+json")
|
||||||
|
}
|
||||||
|
|
||||||
fn response_schema_at(
|
fn response_schema_at(
|
||||||
response: &Value,
|
response: &Value,
|
||||||
operation_pointer: &str,
|
operation_pointer: &str,
|
||||||
@@ -647,46 +802,3 @@ fn response_schema_at(
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn swagger_operation_findings(
|
|
||||||
path: &str,
|
|
||||||
operation: &Value,
|
|
||||||
) -> Vec<crate::rest::model::ImportFinding> {
|
|
||||||
let mut findings = Vec::new();
|
|
||||||
if operation
|
|
||||||
.get("consumes")
|
|
||||||
.and_then(Value::as_array)
|
|
||||||
.is_some_and(|items| {
|
|
||||||
!items
|
|
||||||
.iter()
|
|
||||||
.any(|item| item.as_str().is_some_and(|value| value.contains("json")))
|
|
||||||
})
|
|
||||||
{
|
|
||||||
findings.push(operation_finding(
|
|
||||||
path,
|
|
||||||
"unsupported_consumes",
|
|
||||||
"Метод использует content type без JSON. Проверьте настройки тела запроса после импорта.",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
findings
|
|
||||||
}
|
|
||||||
|
|
||||||
fn method_from_lower(value: &str) -> Option<HttpMethod> {
|
|
||||||
match value {
|
|
||||||
"get" => Some(HttpMethod::Get),
|
|
||||||
"post" => Some(HttpMethod::Post),
|
|
||||||
"put" => Some(HttpMethod::Put),
|
|
||||||
"patch" => Some(HttpMethod::Patch),
|
|
||||||
"delete" => Some(HttpMethod::Delete),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn path_item_blocker(_path: &str) -> ImportFinding {
|
|
||||||
ImportFinding {
|
|
||||||
code: "invalid_path_item".to_owned(),
|
|
||||||
severity: ImportFindingSeverity::Error,
|
|
||||||
message: "Path Item имеет неверную структуру и не был интерпретирован.".to_owned(),
|
|
||||||
operation_key: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,248 @@
|
|||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
use crate::rest::{
|
||||||
|
model::{ImportFinding, RestImportParameter, RestParameterLocation, SourceLocation},
|
||||||
|
recommendations::{document_blocker, operation_finding},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub(super) fn servers(root: &Value) -> Vec<(ImportFinding, SourceLocation)> {
|
||||||
|
let mut findings = Vec::new();
|
||||||
|
if let Some(host) = root.get("host")
|
||||||
|
&& (!host.is_string()
|
||||||
|
|| host.as_str().is_some_and(|host| {
|
||||||
|
host.is_empty() || host.contains('@') || host.chars().any(char::is_whitespace)
|
||||||
|
}))
|
||||||
|
{
|
||||||
|
push(
|
||||||
|
&mut findings,
|
||||||
|
"invalid_server",
|
||||||
|
"Swagger host неверен или содержит userinfo.",
|
||||||
|
"/host",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if let Some(base_path) = root.get("basePath")
|
||||||
|
&& (!base_path.is_string()
|
||||||
|
|| base_path.as_str().is_some_and(|path| {
|
||||||
|
(!path.is_empty() && !path.starts_with('/')) || path.chars().any(char::is_control)
|
||||||
|
}))
|
||||||
|
{
|
||||||
|
push(
|
||||||
|
&mut findings,
|
||||||
|
"invalid_server",
|
||||||
|
"Swagger basePath имеет неверный формат.",
|
||||||
|
"/basePath",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if let Some(schemes) = root.get("schemes").and_then(Value::as_array) {
|
||||||
|
for (index, scheme) in schemes.iter().enumerate() {
|
||||||
|
if !scheme
|
||||||
|
.as_str()
|
||||||
|
.is_some_and(|scheme| matches!(scheme, "http" | "https"))
|
||||||
|
{
|
||||||
|
push(
|
||||||
|
&mut findings,
|
||||||
|
"invalid_server",
|
||||||
|
"Swagger scheme должен быть http или https.",
|
||||||
|
&format!("/schemes/{index}"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
findings
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn operation(
|
||||||
|
root: &Value,
|
||||||
|
operation: &Value,
|
||||||
|
operation_pointer: &str,
|
||||||
|
) -> Vec<(ImportFinding, SourceLocation)> {
|
||||||
|
let mut findings = Vec::new();
|
||||||
|
for (media, location) in media_with_locations(root, operation, operation_pointer, "consumes") {
|
||||||
|
if !supported_request_media(&media) {
|
||||||
|
findings.push((
|
||||||
|
document_blocker(
|
||||||
|
"unsupported_consumes",
|
||||||
|
format!("Content type запроса {media} не поддерживается."),
|
||||||
|
),
|
||||||
|
location,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (media, location) in media_with_locations(root, operation, operation_pointer, "produces") {
|
||||||
|
if !supported_response_media(&media) {
|
||||||
|
findings.push((
|
||||||
|
document_blocker(
|
||||||
|
"unsupported_produces",
|
||||||
|
format!("Content type ответа {media} не поддерживается."),
|
||||||
|
),
|
||||||
|
location,
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(responses) = operation.get("responses").and_then(Value::as_object) {
|
||||||
|
for (status, response) in responses {
|
||||||
|
if let Some(schema) = response.get("schema") {
|
||||||
|
super::openapi3_findings::schema_findings(
|
||||||
|
schema,
|
||||||
|
&format!("{operation_pointer}/responses/{}/schema", escape(status)),
|
||||||
|
&mut findings,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
findings
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn form_data_parameter(
|
||||||
|
parameter: &Value,
|
||||||
|
schema: Option<&Value>,
|
||||||
|
pointer: &str,
|
||||||
|
) -> Vec<(ImportFinding, SourceLocation)> {
|
||||||
|
let Some(schema) = schema else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let mut findings = Vec::new();
|
||||||
|
super::openapi3_findings::schema_findings(schema, pointer, &mut findings);
|
||||||
|
super::openapi3_findings::form_field_schema_findings(schema, pointer, &mut findings);
|
||||||
|
if schema.get("type").and_then(Value::as_str) == Some("array")
|
||||||
|
&& parameter.get("collectionFormat").and_then(Value::as_str) != Some("multi")
|
||||||
|
{
|
||||||
|
let finding_pointer = parameter
|
||||||
|
.get("collectionFormat")
|
||||||
|
.map(|_| format!("{pointer}/collectionFormat"))
|
||||||
|
.unwrap_or_else(|| pointer.to_owned());
|
||||||
|
push(
|
||||||
|
&mut findings,
|
||||||
|
"unsupported_parameter_style",
|
||||||
|
"Swagger formData array требует collectionFormat: multi; csv/default не соответствует repeat-key wire contract.",
|
||||||
|
&finding_pointer,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
findings
|
||||||
|
}
|
||||||
|
|
||||||
|
fn media_with_locations(
|
||||||
|
root: &Value,
|
||||||
|
operation: &Value,
|
||||||
|
operation_pointer: &str,
|
||||||
|
field: &str,
|
||||||
|
) -> Vec<(String, SourceLocation)> {
|
||||||
|
let (value, pointer) = if let Some(value) = operation.get(field) {
|
||||||
|
(value, format!("{operation_pointer}/{field}"))
|
||||||
|
} else if let Some(value) = root.get(field) {
|
||||||
|
(value, format!("/{field}"))
|
||||||
|
} else {
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
value
|
||||||
|
.as_array()
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.enumerate()
|
||||||
|
.filter_map(|(index, value)| {
|
||||||
|
value.as_str().map(|value| {
|
||||||
|
(
|
||||||
|
value.to_owned(),
|
||||||
|
SourceLocation {
|
||||||
|
pointer: format!("{pointer}/{index}"),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn legacy_operation(path: &str, operation: &Value) -> Vec<ImportFinding> {
|
||||||
|
if operation
|
||||||
|
.get("consumes")
|
||||||
|
.and_then(Value::as_array)
|
||||||
|
.is_some_and(|items| {
|
||||||
|
!items
|
||||||
|
.iter()
|
||||||
|
.any(|item| item.as_str().is_some_and(|value| value.contains("json")))
|
||||||
|
})
|
||||||
|
{
|
||||||
|
vec![operation_finding(
|
||||||
|
path,
|
||||||
|
"unsupported_consumes",
|
||||||
|
"Метод использует content type без JSON. Проверьте настройки тела запроса после импорта.",
|
||||||
|
)]
|
||||||
|
} else {
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn path_parameters(
|
||||||
|
path: &str,
|
||||||
|
parameters: &[RestImportParameter],
|
||||||
|
) -> Vec<(ImportFinding, SourceLocation)> {
|
||||||
|
parameters
|
||||||
|
.iter()
|
||||||
|
.filter(|parameter| parameter.location == RestParameterLocation::Path)
|
||||||
|
.filter_map(|parameter| {
|
||||||
|
let finding = if !parameter.required {
|
||||||
|
Some((
|
||||||
|
"path_parameter_not_required",
|
||||||
|
format!("Path parameter {} должен быть required.", parameter.name),
|
||||||
|
))
|
||||||
|
} else if !path.contains(&format!("{{{}}}", parameter.name)) {
|
||||||
|
Some((
|
||||||
|
"path_parameter_placeholder_missing",
|
||||||
|
format!(
|
||||||
|
"Path parameter {} не имеет placeholder в пути.",
|
||||||
|
parameter.name
|
||||||
|
),
|
||||||
|
))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}?;
|
||||||
|
Some((
|
||||||
|
document_blocker(finding.0, finding.1),
|
||||||
|
parameter.source_location.clone(),
|
||||||
|
))
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn unsupported_methods(path_item: &Value) -> Vec<&str> {
|
||||||
|
const NON_METHOD: &[&str] = &["$ref", "parameters"];
|
||||||
|
const SUPPORTED: &[&str] = &["get", "post", "put", "patch", "delete", "head", "options"];
|
||||||
|
path_item
|
||||||
|
.as_object()
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(|item| item.keys())
|
||||||
|
.map(String::as_str)
|
||||||
|
.filter(|name| {
|
||||||
|
!name.starts_with("x-") && !NON_METHOD.contains(name) && !SUPPORTED.contains(name)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn supported_request_media(media: &str) -> bool {
|
||||||
|
matches!(
|
||||||
|
media,
|
||||||
|
"application/json" | "application/x-www-form-urlencoded" | "multipart/form-data"
|
||||||
|
) || media.ends_with("+json")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn supported_response_media(media: &str) -> bool {
|
||||||
|
media == "application/json" || media.ends_with("+json")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push(
|
||||||
|
findings: &mut Vec<(ImportFinding, SourceLocation)>,
|
||||||
|
code: &str,
|
||||||
|
message: &str,
|
||||||
|
pointer: &str,
|
||||||
|
) {
|
||||||
|
findings.push((
|
||||||
|
document_blocker(code, message),
|
||||||
|
SourceLocation {
|
||||||
|
pointer: pointer.to_owned(),
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn escape(value: &str) -> String {
|
||||||
|
value.replace('~', "~0").replace('/', "~1")
|
||||||
|
}
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
use serde_json::Value;
|
||||||
|
|
||||||
|
use super::swagger2::swagger_servers;
|
||||||
|
use crate::rest::{
|
||||||
|
model::{RestImportDocument, RestImportOperation, RestImportParameter, RestParameterLocation},
|
||||||
|
normalize::ImportParseError,
|
||||||
|
recommendations::document_finding,
|
||||||
|
};
|
||||||
|
|
||||||
|
pub(super) fn parse_document_legacy_v1(
|
||||||
|
root: &Value,
|
||||||
|
) -> Result<RestImportDocument, ImportParseError> {
|
||||||
|
let title = root
|
||||||
|
.pointer("/info/title")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.unwrap_or("Imported API")
|
||||||
|
.to_owned();
|
||||||
|
let servers = swagger_servers(root);
|
||||||
|
let mut findings = Vec::new();
|
||||||
|
if servers.is_empty() {
|
||||||
|
findings.push(document_finding(
|
||||||
|
"missing_servers",
|
||||||
|
"В Swagger 2.0 документе не указаны host/schemes, base URL нужно будет выбрать вручную.",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let mut operations = Vec::new();
|
||||||
|
let paths = root
|
||||||
|
.get("paths")
|
||||||
|
.and_then(Value::as_object)
|
||||||
|
.ok_or(ImportParseError::UnsupportedDocument)?;
|
||||||
|
for (path, path_item) in paths {
|
||||||
|
let path_pointer = format!("/paths/{}", path.replace('~', "~0").replace('/', "~1"));
|
||||||
|
let path_parameters = legacy_parameters(
|
||||||
|
root,
|
||||||
|
path_item.get("parameters"),
|
||||||
|
&format!("{path_pointer}/parameters"),
|
||||||
|
);
|
||||||
|
for method_name in ["get", "post", "put", "patch", "delete"] {
|
||||||
|
let Some(operation) = path_item.get(method_name) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let Some(method) = super::http_methods::from_lower(method_name) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let operation_pointer = format!("{path_pointer}/{method_name}");
|
||||||
|
let mut parameters = path_parameters.clone();
|
||||||
|
parameters.extend(legacy_parameters(
|
||||||
|
root,
|
||||||
|
operation.get("parameters"),
|
||||||
|
&format!("{operation_pointer}/parameters"),
|
||||||
|
));
|
||||||
|
let request_body_schema = parameters
|
||||||
|
.iter()
|
||||||
|
.find(|parameter| parameter.name == "body")
|
||||||
|
.and_then(|parameter| parameter.schema.clone());
|
||||||
|
let parameters = parameters
|
||||||
|
.into_iter()
|
||||||
|
.filter(|parameter| parameter.name != "body")
|
||||||
|
.collect();
|
||||||
|
operations.push(RestImportOperation {
|
||||||
|
key: format!("{} {}", method_name.to_uppercase(), path),
|
||||||
|
method,
|
||||||
|
path: path.clone(),
|
||||||
|
security_requirements: Default::default(),
|
||||||
|
operation_id: operation
|
||||||
|
.get("operationId")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.map(ToOwned::to_owned),
|
||||||
|
summary: operation
|
||||||
|
.get("summary")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.map(ToOwned::to_owned),
|
||||||
|
description: operation
|
||||||
|
.get("description")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.map(ToOwned::to_owned),
|
||||||
|
tags: legacy_tags(operation.get("tags")),
|
||||||
|
parameters,
|
||||||
|
request_body_schema,
|
||||||
|
request_body_schema_location: None,
|
||||||
|
request_body_variants: Vec::new(),
|
||||||
|
response_schema: legacy_response_schema(root, operation),
|
||||||
|
response_schema_location: None,
|
||||||
|
response_variants: Vec::new(),
|
||||||
|
servers: Vec::new(),
|
||||||
|
findings: super::swagger2_findings::legacy_operation(path, operation),
|
||||||
|
internal_finding_locations: Vec::new(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(RestImportDocument {
|
||||||
|
format: "swagger".to_owned(),
|
||||||
|
version: Some("2.0".to_owned()),
|
||||||
|
title,
|
||||||
|
servers,
|
||||||
|
security_schemes: Default::default(),
|
||||||
|
operations,
|
||||||
|
findings,
|
||||||
|
internal_finding_locations: Vec::new(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn legacy_tags(value: Option<&Value>) -> Vec<String> {
|
||||||
|
value
|
||||||
|
.and_then(Value::as_array)
|
||||||
|
.map(|items| {
|
||||||
|
items
|
||||||
|
.iter()
|
||||||
|
.filter_map(Value::as_str)
|
||||||
|
.map(ToOwned::to_owned)
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn legacy_parameters(
|
||||||
|
root: &Value,
|
||||||
|
value: Option<&Value>,
|
||||||
|
base_pointer: &str,
|
||||||
|
) -> Vec<RestImportParameter> {
|
||||||
|
value
|
||||||
|
.and_then(Value::as_array)
|
||||||
|
.map(|items| {
|
||||||
|
items
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.filter_map(|(index, item)| {
|
||||||
|
let item = crate::rest::normalize::resolve_local_ref(root, item, 0);
|
||||||
|
let raw_location = item.get("in").and_then(Value::as_str)?;
|
||||||
|
let pointer = format!("{base_pointer}/{index}");
|
||||||
|
if raw_location == "body" {
|
||||||
|
return Some(RestImportParameter {
|
||||||
|
name: "body".to_owned(),
|
||||||
|
location: RestParameterLocation::Query,
|
||||||
|
required: item
|
||||||
|
.get("required")
|
||||||
|
.and_then(Value::as_bool)
|
||||||
|
.unwrap_or(false),
|
||||||
|
description: item
|
||||||
|
.get("description")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.map(ToOwned::to_owned),
|
||||||
|
schema: item.get("schema").map(|schema| {
|
||||||
|
crate::rest::normalize::resolve_local_ref(root, schema, 0)
|
||||||
|
}),
|
||||||
|
source_location: crate::rest::model::SourceLocation { pointer },
|
||||||
|
schema_source_location: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let location = match raw_location {
|
||||||
|
"path" => RestParameterLocation::Path,
|
||||||
|
"query" => RestParameterLocation::Query,
|
||||||
|
"header" => RestParameterLocation::Header,
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
Some(RestImportParameter {
|
||||||
|
name: item.get("name").and_then(Value::as_str)?.to_owned(),
|
||||||
|
location,
|
||||||
|
required: item
|
||||||
|
.get("required")
|
||||||
|
.and_then(Value::as_bool)
|
||||||
|
.unwrap_or(false)
|
||||||
|
|| location == RestParameterLocation::Path,
|
||||||
|
description: item
|
||||||
|
.get("description")
|
||||||
|
.and_then(Value::as_str)
|
||||||
|
.map(ToOwned::to_owned),
|
||||||
|
schema: legacy_parameter_schema(root, &item),
|
||||||
|
source_location: crate::rest::model::SourceLocation { pointer },
|
||||||
|
schema_source_location: None,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn legacy_parameter_schema(root: &Value, parameter: &Value) -> Option<Value> {
|
||||||
|
if let Some(schema) = parameter.get("schema") {
|
||||||
|
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||||
|
}
|
||||||
|
let mut schema = serde_json::Map::new();
|
||||||
|
for key in ["type", "format", "items", "enum", "default", "description"] {
|
||||||
|
if let Some(value) = parameter.get(key) {
|
||||||
|
schema.insert(
|
||||||
|
key.to_owned(),
|
||||||
|
crate::rest::normalize::resolve_local_ref(root, value, 0),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(!schema.is_empty()).then_some(Value::Object(schema))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn legacy_response_schema(root: &Value, operation: &Value) -> Option<Value> {
|
||||||
|
let responses = operation.get("responses")?.as_object()?;
|
||||||
|
for code in ["200", "201", "202", "default"] {
|
||||||
|
let Some(response) = responses.get(code) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let response = crate::rest::normalize::resolve_local_ref(root, response, 0);
|
||||||
|
if let Some(schema) = response.get("schema") {
|
||||||
|
return Some(crate::rest::normalize::resolve_local_ref(root, schema, 0));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
@@ -221,10 +221,10 @@ paths:
|
|||||||
#[test]
|
#[test]
|
||||||
fn unsupported_method_has_exact_finding_pointer_and_coverage() {
|
fn unsupported_method_has_exact_finding_pointer_and_coverage() {
|
||||||
let ir = normalize(
|
let ir = normalize(
|
||||||
"openapi: 3.1.0\ninfo: { title: Unsupported }\npaths: { /ok: { get: { responses: { '200': { description: ok } } }, head: { responses: {} } } }",
|
"openapi: 3.1.0\ninfo: { title: Unsupported }\npaths: { /ok: { get: { responses: { '200': { description: ok } } }, trace: { responses: {} } } }",
|
||||||
);
|
);
|
||||||
validate_normalized_ir(&ir).unwrap();
|
validate_normalized_ir(&ir).unwrap();
|
||||||
let pointer = "/paths/~1ok/head";
|
let pointer = "/paths/~1ok/trace";
|
||||||
let construct_id = format!("3.1.0:{pointer}");
|
let construct_id = format!("3.1.0:{pointer}");
|
||||||
assert!(ir.findings.iter().any(|finding| {
|
assert!(ir.findings.iter().any(|finding| {
|
||||||
finding.code == "unsupported_http_method"
|
finding.code == "unsupported_http_method"
|
||||||
|
|||||||
@@ -0,0 +1,382 @@
|
|||||||
|
use crank_core::HttpMethod;
|
||||||
|
use crank_import::rest::model::NormalizedScalarKind;
|
||||||
|
use crank_import::rest::{
|
||||||
|
ImportFindingSeverity, NormalizationConfig, NormalizedSchemaKind, SourceDigest,
|
||||||
|
normalize_verified_document, validate_normalized_ir,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn normalize(document: &str) -> crank_import::rest::NormalizedIr {
|
||||||
|
normalize_verified_document(
|
||||||
|
document,
|
||||||
|
SourceDigest::parse("5".repeat(64)).unwrap(),
|
||||||
|
&NormalizationConfig::default(),
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn variants_keep_exact_schema_coverage_and_reject_tampered_provenance() {
|
||||||
|
let document = r#"
|
||||||
|
openapi: 3.1.0
|
||||||
|
info: {title: Exact variants, version: '1'}
|
||||||
|
servers: [{url: https://example.test}]
|
||||||
|
paths:
|
||||||
|
/items:
|
||||||
|
post:
|
||||||
|
operationId: createItem
|
||||||
|
requestBody:
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
name: {type: string}
|
||||||
|
responses:
|
||||||
|
'201':
|
||||||
|
description: ok
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema: {type: object, properties: {id: {type: integer}}}
|
||||||
|
"#;
|
||||||
|
let mut ir = normalize(document);
|
||||||
|
let request = ir.operations[0].request_body_variants[0]
|
||||||
|
.schema
|
||||||
|
.as_ref()
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
request.location.pointer,
|
||||||
|
"/paths/~1items/post/requestBody/content/application~1json/schema"
|
||||||
|
);
|
||||||
|
assert!(ir.coverage.iter().any(|entry| {
|
||||||
|
entry.location.pointer
|
||||||
|
== "/paths/~1items/post/requestBody/content/application~1json/schema/properties/name"
|
||||||
|
}));
|
||||||
|
|
||||||
|
ir.operations[0].request_body_variants[0]
|
||||||
|
.schema
|
||||||
|
.as_mut()
|
||||||
|
.unwrap()
|
||||||
|
.location
|
||||||
|
.pointer = "/paths/~1items/post/requestBody/content/application~1json".into();
|
||||||
|
assert!(validate_normalized_ir(&ir).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn exact_blockers_cover_unknown_method_style_media_and_missing_schema() {
|
||||||
|
let ir = normalize(
|
||||||
|
r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: {title: Findings, version: '1'}
|
||||||
|
servers: [{url: https://example.test}]
|
||||||
|
paths:
|
||||||
|
/items/{id}:
|
||||||
|
propfind: {responses: {'200': {description: nope}}}
|
||||||
|
get:
|
||||||
|
operationId: getItem
|
||||||
|
parameters:
|
||||||
|
- {name: id, in: path, required: false, style: matrix, schema: {type: string}}
|
||||||
|
requestBody:
|
||||||
|
content:
|
||||||
|
text/plain: {schema: {type: string}}
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: ok
|
||||||
|
content:
|
||||||
|
application/json: {}
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
let findings = ir
|
||||||
|
.findings
|
||||||
|
.iter()
|
||||||
|
.chain(
|
||||||
|
ir.operations
|
||||||
|
.iter()
|
||||||
|
.flat_map(|operation| &operation.findings),
|
||||||
|
)
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
for (code, pointer) in [
|
||||||
|
("unsupported_http_method", "/paths/~1items~1{id}/propfind"),
|
||||||
|
(
|
||||||
|
"unsupported_parameter_style",
|
||||||
|
"/paths/~1items~1{id}/get/parameters/0/style",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"path_parameter_not_required",
|
||||||
|
"/paths/~1items~1{id}/get/parameters/0",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"unsupported_request_media_type",
|
||||||
|
"/paths/~1items~1{id}/get/requestBody/content/text~1plain",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"missing_response_media_schema",
|
||||||
|
"/paths/~1items~1{id}/get/responses/200/content/application~1json",
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
findings.iter().any(|finding| {
|
||||||
|
finding.code == code
|
||||||
|
&& finding.location.pointer == pointer
|
||||||
|
&& finding.severity == ImportFindingSeverity::Error
|
||||||
|
}),
|
||||||
|
"missing {code} at {pointer}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn form_encoding_and_unserializable_shapes_are_exact_blockers() {
|
||||||
|
let ir = normalize(
|
||||||
|
r#"
|
||||||
|
openapi: 3.1.0
|
||||||
|
info: {title: Form blockers, version: '1'}
|
||||||
|
servers: [{url: https://example.test}]
|
||||||
|
paths:
|
||||||
|
/forms:
|
||||||
|
post:
|
||||||
|
operationId: sendForm
|
||||||
|
requestBody:
|
||||||
|
content:
|
||||||
|
application/x-www-form-urlencoded:
|
||||||
|
schema: {type: string}
|
||||||
|
encoding:
|
||||||
|
tag: {style: form, explode: false}
|
||||||
|
multipart/form-data:
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
metadata: {type: object, properties: {name: {type: string}}}
|
||||||
|
nested_tags: {type: array, items: {type: array, items: {type: string}}}
|
||||||
|
composed_metadata:
|
||||||
|
oneOf:
|
||||||
|
- {type: object, properties: {name: {type: string}}}
|
||||||
|
responses: {'204': {description: Empty}}
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
let findings = &ir.operations[0].findings;
|
||||||
|
for (code, pointer) in [
|
||||||
|
(
|
||||||
|
"unsupported_form_schema",
|
||||||
|
"/paths/~1forms/post/requestBody/content/application~1x-www-form-urlencoded/schema",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"unsupported_form_encoding",
|
||||||
|
"/paths/~1forms/post/requestBody/content/application~1x-www-form-urlencoded/encoding/tag/explode",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"unsupported_form_schema",
|
||||||
|
"/paths/~1forms/post/requestBody/content/multipart~1form-data/schema/properties/metadata",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"unsupported_form_schema",
|
||||||
|
"/paths/~1forms/post/requestBody/content/multipart~1form-data/schema/properties/nested_tags/items",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"unsupported_form_schema",
|
||||||
|
"/paths/~1forms/post/requestBody/content/multipart~1form-data/schema/properties/composed_metadata/oneOf/0",
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
findings.iter().any(|finding| {
|
||||||
|
finding.code == code
|
||||||
|
&& finding.location.pointer == pointer
|
||||||
|
&& finding.severity == ImportFindingSeverity::Error
|
||||||
|
}),
|
||||||
|
"missing {code} at {pointer}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
validate_normalized_ir(&ir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn swagger_form_data_arrays_require_multi_collection_format() {
|
||||||
|
let ir = normalize(
|
||||||
|
r#"
|
||||||
|
swagger: '2.0'
|
||||||
|
info: {title: Swagger form arrays, version: '1'}
|
||||||
|
host: example.test
|
||||||
|
schemes: [https]
|
||||||
|
consumes: [application/x-www-form-urlencoded]
|
||||||
|
paths:
|
||||||
|
/forms:
|
||||||
|
post:
|
||||||
|
operationId: sendForm
|
||||||
|
parameters:
|
||||||
|
- {name: default_csv, in: formData, type: array, items: {type: string}}
|
||||||
|
- {name: explicit_csv, in: formData, type: array, collectionFormat: csv, items: {type: string}}
|
||||||
|
- {name: repeat_keys, in: formData, type: array, collectionFormat: multi, items: {type: string}}
|
||||||
|
responses: {'204': {description: Empty}}
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
let findings = &ir.operations[0].findings;
|
||||||
|
for pointer in [
|
||||||
|
"/paths/~1forms/post/parameters/0",
|
||||||
|
"/paths/~1forms/post/parameters/1/collectionFormat",
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
findings.iter().any(|finding| {
|
||||||
|
finding.code == "unsupported_parameter_style"
|
||||||
|
&& finding.location.pointer == pointer
|
||||||
|
&& finding.severity == ImportFindingSeverity::Error
|
||||||
|
}),
|
||||||
|
"missing CSV blocker at {pointer}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert!(!findings.iter().any(|finding| {
|
||||||
|
finding.code == "unsupported_parameter_style"
|
||||||
|
&& finding.location.pointer == "/paths/~1forms/post/parameters/2/collectionFormat"
|
||||||
|
}));
|
||||||
|
validate_normalized_ir(&ir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unsupported_schema_keywords_and_invalid_server_port_are_exact_blockers() {
|
||||||
|
let ir = normalize(
|
||||||
|
r#"
|
||||||
|
openapi: 3.1.0
|
||||||
|
info: {title: Schema and server blockers, version: '1'}
|
||||||
|
servers:
|
||||||
|
- {url: 'https://example.test:not-a-port'}
|
||||||
|
- {url: "https://control.test/\n"}
|
||||||
|
paths:
|
||||||
|
/items:
|
||||||
|
post:
|
||||||
|
operationId: createItem
|
||||||
|
requestBody:
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
const: {kind: item}
|
||||||
|
minProperties: 1
|
||||||
|
maxProperties: 2
|
||||||
|
dependentRequired: {kind: [name]}
|
||||||
|
properties:
|
||||||
|
quantity: {type: number, multipleOf: 0.5}
|
||||||
|
responses: {'204': {description: Empty}}
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
let findings = ir
|
||||||
|
.findings
|
||||||
|
.iter()
|
||||||
|
.chain(ir.operations[0].findings.iter())
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
for (code, pointer) in [
|
||||||
|
("invalid_server", "/servers/0/url"),
|
||||||
|
("invalid_server", "/servers/1/url"),
|
||||||
|
(
|
||||||
|
"unsupported_schema_keyword",
|
||||||
|
"/paths/~1items/post/requestBody/content/application~1json/schema/const",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"unsupported_schema_keyword",
|
||||||
|
"/paths/~1items/post/requestBody/content/application~1json/schema/minProperties",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"unsupported_schema_keyword",
|
||||||
|
"/paths/~1items/post/requestBody/content/application~1json/schema/maxProperties",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"unsupported_schema_keyword",
|
||||||
|
"/paths/~1items/post/requestBody/content/application~1json/schema/dependentRequired",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"unsupported_schema_keyword",
|
||||||
|
"/paths/~1items/post/requestBody/content/application~1json/schema/properties/quantity/multipleOf",
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
findings.iter().any(|finding| {
|
||||||
|
finding.code == code
|
||||||
|
&& finding.location.pointer == pointer
|
||||||
|
&& finding.severity == ImportFindingSeverity::Error
|
||||||
|
}),
|
||||||
|
"missing {code} at {pointer}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
validate_normalized_ir(&ir).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn swagger_merges_path_form_data_and_preserves_file_type() {
|
||||||
|
let ir = normalize(
|
||||||
|
r#"
|
||||||
|
swagger: '2.0'
|
||||||
|
info: {title: Upload, version: '1'}
|
||||||
|
host: example.test
|
||||||
|
schemes: [https]
|
||||||
|
consumes: [multipart/form-data]
|
||||||
|
paths:
|
||||||
|
/upload:
|
||||||
|
parameters:
|
||||||
|
- {name: file, in: formData, type: file, required: true}
|
||||||
|
- {name: title, in: formData, type: string}
|
||||||
|
post:
|
||||||
|
operationId: upload
|
||||||
|
parameters:
|
||||||
|
- {name: title, in: formData, type: integer, required: true}
|
||||||
|
responses:
|
||||||
|
'204': {description: done}
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
let operation = &ir.operations[0];
|
||||||
|
let variant = &operation.request_body_variants[0];
|
||||||
|
let NormalizedSchemaKind::Object {
|
||||||
|
properties,
|
||||||
|
required,
|
||||||
|
..
|
||||||
|
} = &variant.schema.as_ref().unwrap().kind
|
||||||
|
else {
|
||||||
|
panic!("formData must normalize to an object");
|
||||||
|
};
|
||||||
|
assert_eq!(required, &["file".to_owned(), "title".to_owned()]);
|
||||||
|
assert!(matches!(
|
||||||
|
properties["file"].kind,
|
||||||
|
NormalizedSchemaKind::Scalar {
|
||||||
|
scalar_type: NormalizedScalarKind::String,
|
||||||
|
ref format,
|
||||||
|
..
|
||||||
|
} if format.as_deref() == Some("binary")
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
properties["title"].kind,
|
||||||
|
NormalizedSchemaKind::Scalar {
|
||||||
|
scalar_type: NormalizedScalarKind::Integer,
|
||||||
|
..
|
||||||
|
}
|
||||||
|
));
|
||||||
|
assert_eq!(
|
||||||
|
properties["file"].location.pointer,
|
||||||
|
"/paths/~1upload/parameters/0"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
properties["title"].location.pointer,
|
||||||
|
"/paths/~1upload/post/parameters/0"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn head_declared_body_is_normalized_as_no_content() {
|
||||||
|
let ir = normalize(
|
||||||
|
r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: {title: Head, version: '1'}
|
||||||
|
servers: [{url: https://example.test}]
|
||||||
|
paths:
|
||||||
|
/health:
|
||||||
|
head:
|
||||||
|
operationId: health
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: ok
|
||||||
|
content:
|
||||||
|
application/json: {schema: {type: object}}
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
let operation = &ir.operations[0];
|
||||||
|
assert_eq!(operation.method, HttpMethod::Head);
|
||||||
|
assert!(operation.response_schema.is_none());
|
||||||
|
assert_eq!(operation.response_variants.len(), 1);
|
||||||
|
assert!(operation.response_variants[0].schema.is_none());
|
||||||
|
assert!(operation.response_variants[0].content_type.is_none());
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
use crank_import::rest::{
|
||||||
|
NormalizationConfig, NormalizedIr, SourceDigest, normalize_verified_document, preview_from_ir,
|
||||||
|
validate_normalized_ir,
|
||||||
|
};
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn serialized_http_ir_preserves_variants_mime_aliases_and_mapping_without_parser_state() {
|
||||||
|
let document = r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: {title: Replay}
|
||||||
|
servers: [{url: 'https://example.test/api/v2'}]
|
||||||
|
paths:
|
||||||
|
/upload:
|
||||||
|
post:
|
||||||
|
operationId: upload
|
||||||
|
parameters:
|
||||||
|
- {in: query, name: body, schema: {type: string}}
|
||||||
|
- {in: header, name: content_type, schema: {type: string}}
|
||||||
|
requestBody:
|
||||||
|
required: true
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema: {type: object, required: [name], properties: {name: {type: string}}}
|
||||||
|
multipart/form-data:
|
||||||
|
schema: {type: object, required: [file], properties: {file: {type: string, format: binary}}}
|
||||||
|
encoding: {file: {contentType: 'image/png, image/jpeg'}}
|
||||||
|
responses:
|
||||||
|
'200': {description: OK, content: {application/json: {schema: {type: string}}}}
|
||||||
|
'204': {description: Empty}
|
||||||
|
"#;
|
||||||
|
let ir = normalize_verified_document(
|
||||||
|
document,
|
||||||
|
SourceDigest::parse("0".repeat(64)).unwrap(),
|
||||||
|
&NormalizationConfig::default(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let restored: NormalizedIr = serde_json::from_slice(&serde_json::to_vec(&ir).unwrap()).unwrap();
|
||||||
|
validate_normalized_ir(&restored).unwrap();
|
||||||
|
let first = preview_from_ir(&ir);
|
||||||
|
let second = preview_from_ir(&restored);
|
||||||
|
assert_eq!(first, second);
|
||||||
|
assert_eq!(second.groups[0].operations.len(), 1);
|
||||||
|
let candidate = &second.groups[0].operations[0];
|
||||||
|
let draft = &candidate.draft;
|
||||||
|
let draft_value = serde_json::to_value(draft).unwrap();
|
||||||
|
let persisted: crank_import::rest::RestImportCandidate =
|
||||||
|
serde_json::from_value(draft_value.clone()).unwrap();
|
||||||
|
assert_eq!(serde_json::to_value(persisted).unwrap(), draft_value);
|
||||||
|
for arguments in [
|
||||||
|
json!({"query_body": "query", "header_content_type": "header", "content_type": "application/json", "body": {"name": "Ada"}}),
|
||||||
|
json!({"query_body": "query", "header_content_type": "header", "content_type": "multipart/form-data", "body": {"file": {"data_base64": "AA==", "content_type": "image/png"}}}),
|
||||||
|
] {
|
||||||
|
draft.input_schema.validate_shape(&arguments).unwrap();
|
||||||
|
let mapped = draft
|
||||||
|
.input_mapping
|
||||||
|
.apply(&json!({"mcp": arguments}))
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(mapped["request"]["query"]["body"], "query");
|
||||||
|
assert_eq!(mapped["request"]["headers"]["content_type"], "header");
|
||||||
|
}
|
||||||
|
assert_eq!(draft.target.base_url, "https://example.test/api/v2");
|
||||||
|
assert_eq!(draft.target.response_contract.len(), 2);
|
||||||
|
assert_eq!(
|
||||||
|
draft.target.multipart_field_mime_types["multipart/form-data"]["file"],
|
||||||
|
["image/png", "image/jpeg"]
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
use crank_import::rest::preview_document_legacy_v1;
|
||||||
|
use crank_schema::SchemaKind;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn legacy_v1_keeps_reserved_names_flattening_and_scalar_semantics() {
|
||||||
|
let preview = preview_document_legacy_v1(
|
||||||
|
r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: {title: Legacy contract}
|
||||||
|
servers: [{url: 'https://example.test'}]
|
||||||
|
paths:
|
||||||
|
/items/{id}:
|
||||||
|
head:
|
||||||
|
responses: {'204': {description: Empty}}
|
||||||
|
post:
|
||||||
|
operationId: createItem
|
||||||
|
parameters:
|
||||||
|
- {in: path, name: id, schema: {type: string}}
|
||||||
|
- {in: query, name: body, schema: {type: string, default: old, nullable: true}}
|
||||||
|
requestBody:
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
file: {type: string, format: binary}
|
||||||
|
responses:
|
||||||
|
'200': {description: OK, content: {application/json: {schema: {type: string}}}}
|
||||||
|
'204': {description: Empty}
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(preview.groups[0].operations.len(), 1);
|
||||||
|
let draft = &preview.groups[0].operations[0].draft;
|
||||||
|
assert!(draft.input_schema.fields["id"].required);
|
||||||
|
assert_eq!(draft.input_schema.fields["file"].kind, SchemaKind::String);
|
||||||
|
assert_eq!(draft.input_schema.fields["file"].format, None);
|
||||||
|
assert!(!draft.input_schema.fields["body"].nullable);
|
||||||
|
assert_eq!(draft.input_schema.fields["body"].default_value, None);
|
||||||
|
assert!(draft.target.response_contract.is_empty());
|
||||||
|
let mapped = draft
|
||||||
|
.input_mapping
|
||||||
|
.apply(&json!({"mcp": {"id": "1", "body": "query-value", "file": "legacy-string"}}))
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(mapped["request"]["query"]["body"], "query-value");
|
||||||
|
assert_eq!(mapped["request"]["body"], json!({"file": "legacy-string"}));
|
||||||
|
assert_eq!(draft.output_schema.kind, SchemaKind::String);
|
||||||
|
}
|
||||||
@@ -246,7 +246,7 @@ components:
|
|||||||
.iter()
|
.iter()
|
||||||
.map(|parameter| parameter.name.as_str())
|
.map(|parameter| parameter.name.as_str())
|
||||||
.collect::<Vec<_>>(),
|
.collect::<Vec<_>>(),
|
||||||
vec!["id", "query"]
|
vec!["path_cookie", "id", "operation_cookie", "query"]
|
||||||
);
|
);
|
||||||
let errors = ir
|
let errors = ir
|
||||||
.findings
|
.findings
|
||||||
@@ -257,7 +257,6 @@ components:
|
|||||||
"missing_parameter_name",
|
"missing_parameter_name",
|
||||||
"missing_parameter_location",
|
"missing_parameter_location",
|
||||||
"unsupported_parameter_location",
|
"unsupported_parameter_location",
|
||||||
"unsupported_cookie_parameter",
|
|
||||||
"unresolved_parameter_reference",
|
"unresolved_parameter_reference",
|
||||||
]
|
]
|
||||||
.contains(&finding.code.as_str())
|
.contains(&finding.code.as_str())
|
||||||
@@ -267,10 +266,6 @@ components:
|
|||||||
assert_eq!(
|
assert_eq!(
|
||||||
errors,
|
errors,
|
||||||
std::collections::BTreeSet::from([
|
std::collections::BTreeSet::from([
|
||||||
(
|
|
||||||
"unsupported_cookie_parameter",
|
|
||||||
"/paths/~1items~1{id}/parameters/1",
|
|
||||||
),
|
|
||||||
("invalid_parameter", "/paths/~1items~1{id}/parameters/2",),
|
("invalid_parameter", "/paths/~1items~1{id}/parameters/2",),
|
||||||
(
|
(
|
||||||
"missing_parameter_name",
|
"missing_parameter_name",
|
||||||
@@ -284,10 +279,6 @@ components:
|
|||||||
"unsupported_parameter_location",
|
"unsupported_parameter_location",
|
||||||
"/paths/~1items~1{id}/get/parameters/2",
|
"/paths/~1items~1{id}/get/parameters/2",
|
||||||
),
|
),
|
||||||
(
|
|
||||||
"unsupported_cookie_parameter",
|
|
||||||
"/paths/~1items~1{id}/get/parameters/3",
|
|
||||||
),
|
|
||||||
])
|
])
|
||||||
);
|
);
|
||||||
assert!(
|
assert!(
|
||||||
@@ -299,7 +290,6 @@ components:
|
|||||||
"missing_parameter_name",
|
"missing_parameter_name",
|
||||||
"missing_parameter_location",
|
"missing_parameter_location",
|
||||||
"unsupported_parameter_location",
|
"unsupported_parameter_location",
|
||||||
"unsupported_cookie_parameter",
|
|
||||||
"unresolved_parameter_reference",
|
"unresolved_parameter_reference",
|
||||||
]
|
]
|
||||||
.contains(&finding.code.as_str())
|
.contains(&finding.code.as_str())
|
||||||
@@ -363,12 +353,12 @@ parameters:
|
|||||||
let errors = ir
|
let errors = ir
|
||||||
.findings
|
.findings
|
||||||
.iter()
|
.iter()
|
||||||
|
.chain(ir.operations[0].findings.iter())
|
||||||
.filter(|finding| {
|
.filter(|finding| {
|
||||||
[
|
[
|
||||||
"invalid_parameter",
|
"invalid_parameter",
|
||||||
"missing_parameter_name",
|
"missing_parameter_name",
|
||||||
"missing_parameter_location",
|
"missing_parameter_location",
|
||||||
"unsupported_parameter_location",
|
|
||||||
"unsupported_cookie_parameter",
|
"unsupported_cookie_parameter",
|
||||||
"unresolved_parameter_reference",
|
"unresolved_parameter_reference",
|
||||||
]
|
]
|
||||||
@@ -392,10 +382,6 @@ parameters:
|
|||||||
"missing_parameter_location",
|
"missing_parameter_location",
|
||||||
"/paths/~1items~1{id}/get/parameters/1",
|
"/paths/~1items~1{id}/get/parameters/1",
|
||||||
),
|
),
|
||||||
(
|
|
||||||
"unsupported_parameter_location",
|
|
||||||
"/paths/~1items~1{id}/get/parameters/2",
|
|
||||||
),
|
|
||||||
(
|
(
|
||||||
"unsupported_cookie_parameter",
|
"unsupported_cookie_parameter",
|
||||||
"/paths/~1items~1{id}/get/parameters/3",
|
"/paths/~1items~1{id}/get/parameters/3",
|
||||||
@@ -405,12 +391,12 @@ parameters:
|
|||||||
assert!(
|
assert!(
|
||||||
ir.findings
|
ir.findings
|
||||||
.iter()
|
.iter()
|
||||||
|
.chain(ir.operations[0].findings.iter())
|
||||||
.filter(|finding| {
|
.filter(|finding| {
|
||||||
[
|
[
|
||||||
"invalid_parameter",
|
"invalid_parameter",
|
||||||
"missing_parameter_name",
|
"missing_parameter_name",
|
||||||
"missing_parameter_location",
|
"missing_parameter_location",
|
||||||
"unsupported_parameter_location",
|
|
||||||
"unsupported_cookie_parameter",
|
"unsupported_cookie_parameter",
|
||||||
"unresolved_parameter_reference",
|
"unresolved_parameter_reference",
|
||||||
]
|
]
|
||||||
@@ -418,6 +404,13 @@ parameters:
|
|||||||
})
|
})
|
||||||
.all(|finding| finding.severity == ImportFindingSeverity::Error)
|
.all(|finding| finding.severity == ImportFindingSeverity::Error)
|
||||||
);
|
);
|
||||||
|
assert!(
|
||||||
|
ir.operations[0].findings.iter().any(|finding| {
|
||||||
|
finding.code == "missing_parameter_name"
|
||||||
|
&& finding.location.pointer == "/paths/~1items~1{id}/get/parameters/0"
|
||||||
|
}),
|
||||||
|
"operation parameter errors must remain scoped to the affected operation"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
mod unit {
|
mod unit {
|
||||||
use crank_core::HttpMethod;
|
use crank_core::HttpMethod;
|
||||||
use crank_import::rest::{ImportParseError, preview_document, preview_document_legacy_v1};
|
use crank_import::rest::{
|
||||||
|
ImportParseError, NormalizationConfig, SourceDigest, normalize_verified_document,
|
||||||
|
preview_document, preview_document_legacy_v1,
|
||||||
|
};
|
||||||
use crank_schema::SchemaKind;
|
use crank_schema::SchemaKind;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
|
|
||||||
@@ -174,7 +177,8 @@ paths:
|
|||||||
assert_eq!(labels.kind, SchemaKind::Array);
|
assert_eq!(labels.kind, SchemaKind::Array);
|
||||||
assert_eq!(labels.items.as_ref().unwrap().kind, SchemaKind::String);
|
assert_eq!(labels.items.as_ref().unwrap().kind, SchemaKind::String);
|
||||||
|
|
||||||
let payload = operation.draft.input_schema.field("payload").unwrap();
|
let body = operation.draft.input_schema.field("body").unwrap();
|
||||||
|
let payload = body.field("payload").unwrap();
|
||||||
assert_eq!(payload.description.as_deref(), Some("Request payload"));
|
assert_eq!(payload.description.as_deref(), Some("Request payload"));
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
payload.field("enabled").unwrap().description.as_deref(),
|
payload.field("enabled").unwrap().description.as_deref(),
|
||||||
@@ -214,7 +218,7 @@ paths:
|
|||||||
let v2 = preview_document(document).unwrap();
|
let v2 = preview_document(document).unwrap();
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
v2.groups[0].operations[0].draft.output_schema.kind,
|
v2.groups[0].operations[0].draft.output_schema.kind,
|
||||||
SchemaKind::String
|
SchemaKind::Oneof
|
||||||
);
|
);
|
||||||
|
|
||||||
let legacy = preview_document_legacy_v1(document).unwrap();
|
let legacy = preview_document_legacy_v1(document).unwrap();
|
||||||
@@ -555,10 +559,10 @@ paths:
|
|||||||
.map(|rule| rule.target.as_str())
|
.map(|rule| rule.target.as_str())
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
assert!(input_fields.contains_key("email"));
|
assert!(input_fields.contains_key("body"));
|
||||||
assert!(input_fields.contains_key("name"));
|
assert!(input_fields["body"].fields.contains_key("email"));
|
||||||
assert!(targets.contains(&"$.request.body.email"));
|
assert!(input_fields["body"].fields.contains_key("name"));
|
||||||
assert!(targets.contains(&"$.request.body.name"));
|
assert!(targets.contains(&"$.request.body"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -612,4 +616,344 @@ paths:
|
|||||||
assert!(codes.contains(&"weak_tool_name"));
|
assert!(codes.contains(&"weak_tool_name"));
|
||||||
assert!(codes.contains(&"too_many_output_fields"));
|
assert!(codes.contains(&"too_many_output_fields"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn previews_head_and_options_operations_and_rejects_trace_connect() {
|
||||||
|
let document = r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: { title: Method coverage }
|
||||||
|
paths:
|
||||||
|
/health:
|
||||||
|
head:
|
||||||
|
operationId: healthHead
|
||||||
|
responses: { '204': { description: Empty } }
|
||||||
|
options:
|
||||||
|
operationId: healthOptions
|
||||||
|
responses: { '204': { description: Empty } }
|
||||||
|
trace:
|
||||||
|
responses: { '200': { description: Unsupported } }
|
||||||
|
connect:
|
||||||
|
responses: { '200': { description: Unsupported } }
|
||||||
|
"#;
|
||||||
|
|
||||||
|
let preview = preview_document(document).unwrap();
|
||||||
|
let operations = preview
|
||||||
|
.groups
|
||||||
|
.iter()
|
||||||
|
.flat_map(|group| group.operations.iter())
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
assert_eq!(operations.len(), 2);
|
||||||
|
assert!(operations.iter().any(|operation| {
|
||||||
|
operation.key == "HEAD /health" && operation.method == HttpMethod::Head
|
||||||
|
}));
|
||||||
|
assert!(operations.iter().any(|operation| {
|
||||||
|
operation.key == "OPTIONS /health" && operation.method == HttpMethod::Options
|
||||||
|
}));
|
||||||
|
|
||||||
|
let unsupported = preview
|
||||||
|
.findings
|
||||||
|
.iter()
|
||||||
|
.filter(|finding| finding.code == "unsupported_http_method")
|
||||||
|
.count();
|
||||||
|
assert_eq!(unsupported, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn preserves_cookie_location_and_does_not_collapse_same_name_parameters() {
|
||||||
|
let document = r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: { title: Cookie parameters }
|
||||||
|
paths:
|
||||||
|
/sessions:
|
||||||
|
get:
|
||||||
|
operationId: listSessions
|
||||||
|
parameters:
|
||||||
|
- name: token
|
||||||
|
in: query
|
||||||
|
schema: { type: string }
|
||||||
|
- name: token
|
||||||
|
in: cookie
|
||||||
|
required: true
|
||||||
|
schema: { type: string }
|
||||||
|
responses:
|
||||||
|
'200': { description: OK }
|
||||||
|
"#;
|
||||||
|
|
||||||
|
let preview = preview_document(document).unwrap();
|
||||||
|
let candidate = &preview.groups[0].operations[0];
|
||||||
|
let cookie_and_query_rules = candidate
|
||||||
|
.draft
|
||||||
|
.input_mapping
|
||||||
|
.rules
|
||||||
|
.iter()
|
||||||
|
.filter(|rule| {
|
||||||
|
rule.target == "$.request.query.token" || rule.target == "$.request.cookies.token"
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
assert_eq!(cookie_and_query_rules.len(), 2);
|
||||||
|
assert_ne!(
|
||||||
|
cookie_and_query_rules[0].source,
|
||||||
|
cookie_and_query_rules[1].source
|
||||||
|
);
|
||||||
|
|
||||||
|
let ir = normalize_verified_document(
|
||||||
|
document,
|
||||||
|
SourceDigest::parse("0".repeat(64)).unwrap(),
|
||||||
|
&NormalizationConfig::default(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let operation = &ir.operations[0];
|
||||||
|
assert_eq!(operation.parameters.len(), 2);
|
||||||
|
assert!(operation.parameters.iter().any(|parameter| {
|
||||||
|
parameter.name == "token"
|
||||||
|
&& parameter.location == crank_import::rest::RestParameterLocation::Query
|
||||||
|
}));
|
||||||
|
assert!(operation.parameters.iter().any(|parameter| {
|
||||||
|
parameter.name == "token"
|
||||||
|
&& parameter.location == crank_import::rest::RestParameterLocation::Cookie
|
||||||
|
&& parameter.required
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn preserves_all_supported_request_media_variants() {
|
||||||
|
let document = r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: { title: Request media variants }
|
||||||
|
paths:
|
||||||
|
/imports:
|
||||||
|
post:
|
||||||
|
operationId: importPayload
|
||||||
|
requestBody:
|
||||||
|
required: true
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
required: [json_name]
|
||||||
|
properties: { json_name: { type: string } }
|
||||||
|
application/x-www-form-urlencoded:
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
required: [form_name]
|
||||||
|
properties: { form_name: { type: string } }
|
||||||
|
multipart/form-data:
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
required: [file]
|
||||||
|
properties: { file: { type: string, format: binary } }
|
||||||
|
encoding:
|
||||||
|
file: { contentType: "image/png, image/jpeg" }
|
||||||
|
responses:
|
||||||
|
'202': { description: Accepted }
|
||||||
|
"#;
|
||||||
|
|
||||||
|
let ir = normalize_verified_document(
|
||||||
|
document,
|
||||||
|
SourceDigest::parse("0".repeat(64)).unwrap(),
|
||||||
|
&NormalizationConfig::default(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let variants = &ir.operations[0].request_body_variants;
|
||||||
|
let content_types = variants
|
||||||
|
.iter()
|
||||||
|
.map(|variant| variant.content_type.as_str())
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
assert_eq!(
|
||||||
|
content_types,
|
||||||
|
vec![
|
||||||
|
"application/json",
|
||||||
|
"application/x-www-form-urlencoded",
|
||||||
|
"multipart/form-data"
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert!(variants.iter().all(|variant| variant.required));
|
||||||
|
assert!(variants.iter().all(|variant| variant.schema.is_some()));
|
||||||
|
assert_eq!(
|
||||||
|
variants[2].multipart_field_mime_types.get("file"),
|
||||||
|
Some(&vec!["image/png".to_owned(), "image/jpeg".to_owned()])
|
||||||
|
);
|
||||||
|
|
||||||
|
let preview = preview_document(document).unwrap();
|
||||||
|
let input_schema = &preview.groups[0].operations[0].draft.input_schema;
|
||||||
|
assert_eq!(input_schema.kind, SchemaKind::Oneof);
|
||||||
|
assert_eq!(input_schema.variants.len(), 3);
|
||||||
|
assert!(
|
||||||
|
input_schema
|
||||||
|
.validate_shape(&json!({
|
||||||
|
"content_type": "application/json",
|
||||||
|
"body": {"json_name": "Ada"}
|
||||||
|
}))
|
||||||
|
.is_ok()
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
input_schema
|
||||||
|
.validate_shape(&json!({
|
||||||
|
"content_type": "application/json",
|
||||||
|
"body": {"form_name": "Ada"}
|
||||||
|
}))
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
input_schema
|
||||||
|
.validate_shape(&json!({
|
||||||
|
"content_type": "multipart/form-data",
|
||||||
|
"body": {"file": {"data_base64": "SGVsbG8="}}
|
||||||
|
}))
|
||||||
|
.is_ok()
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
input_schema
|
||||||
|
.validate_shape(&json!({
|
||||||
|
"content_type": "multipart/form-data",
|
||||||
|
"body": {"file": {"data_base64": "SGVsbG8=", "extra": true}}
|
||||||
|
}))
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
input_schema
|
||||||
|
.validate_shape(&json!({
|
||||||
|
"content_type": "multipart/form-data",
|
||||||
|
"body": {}
|
||||||
|
}))
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
preview.groups[0].operations[0]
|
||||||
|
.draft
|
||||||
|
.target
|
||||||
|
.multipart_field_mime_types
|
||||||
|
.get("multipart/form-data")
|
||||||
|
.and_then(|fields| fields.get("file")),
|
||||||
|
Some(&vec!["image/png".to_owned(), "image/jpeg".to_owned()])
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn optional_variant_pair_preserves_omission_and_nullable_null_in_mapping() {
|
||||||
|
let document = r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: { title: Optional variants }
|
||||||
|
paths:
|
||||||
|
/events:
|
||||||
|
post:
|
||||||
|
operationId: createEvent
|
||||||
|
requestBody:
|
||||||
|
required: false
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema: { type: object, nullable: true, properties: { name: { type: string } } }
|
||||||
|
application/x-www-form-urlencoded:
|
||||||
|
schema: { type: object, properties: { title: { type: string } } }
|
||||||
|
responses: { '204': { description: Empty } }
|
||||||
|
"#;
|
||||||
|
let preview = preview_document(document).unwrap();
|
||||||
|
let draft = &preview.groups[0].operations[0].draft;
|
||||||
|
assert!(draft.input_schema.validate_shape(&json!({})).is_ok());
|
||||||
|
assert!(
|
||||||
|
draft
|
||||||
|
.input_schema
|
||||||
|
.validate_shape(&json!({"content_type": "application/json", "body": null}))
|
||||||
|
.is_ok()
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
draft
|
||||||
|
.input_schema
|
||||||
|
.validate_shape(
|
||||||
|
&json!({"content_type": "application/x-www-form-urlencoded", "body": null})
|
||||||
|
)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
// Omission is represented by its own closed branch, so an incomplete
|
||||||
|
// selector/body pair is rejected by the portable schema as well.
|
||||||
|
assert!(
|
||||||
|
draft
|
||||||
|
.input_schema
|
||||||
|
.validate_shape(&json!({"content_type": "application/json"}))
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
let mapped = draft
|
||||||
|
.input_mapping
|
||||||
|
.apply(&json!({"mcp": {"content_type": "application/json", "body": null}}))
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(mapped["request"]["body"], json!(null));
|
||||||
|
assert_eq!(mapped["request"]["body_content_type"], "application/json");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn preserves_multiple_success_responses_and_explicit_no_content() {
|
||||||
|
let document = r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: { title: Response variants }
|
||||||
|
paths:
|
||||||
|
/items:
|
||||||
|
get:
|
||||||
|
operationId: getItems
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: JSON result
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema: { type: object, properties: { id: { type: string } } }
|
||||||
|
'204': { description: No content }
|
||||||
|
'206':
|
||||||
|
description: Partial result
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema: { type: array, items: { type: string } }
|
||||||
|
"#;
|
||||||
|
|
||||||
|
let preview = preview_document(document).unwrap();
|
||||||
|
let output_schema = &preview.groups[0].operations[0].draft.output_schema;
|
||||||
|
let response_contract = &preview.groups[0].operations[0]
|
||||||
|
.draft
|
||||||
|
.target
|
||||||
|
.response_contract;
|
||||||
|
assert_eq!(output_schema.kind, SchemaKind::Oneof);
|
||||||
|
assert_eq!(output_schema.variants.len(), 3);
|
||||||
|
assert_eq!(
|
||||||
|
response_contract
|
||||||
|
.iter()
|
||||||
|
.map(|descriptor| (descriptor.status_code, descriptor.media_type.as_deref()))
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
vec![
|
||||||
|
(200, Some("application/json")),
|
||||||
|
(204, None),
|
||||||
|
(206, Some("application/json")),
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
output_schema
|
||||||
|
.variants
|
||||||
|
.iter()
|
||||||
|
.any(|variant| variant.kind == SchemaKind::Null)
|
||||||
|
);
|
||||||
|
|
||||||
|
let ir = normalize_verified_document(
|
||||||
|
document,
|
||||||
|
SourceDigest::parse("0".repeat(64)).unwrap(),
|
||||||
|
&NormalizationConfig::default(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let variants = &ir.operations[0].response_variants;
|
||||||
|
assert_eq!(
|
||||||
|
variants
|
||||||
|
.iter()
|
||||||
|
.map(|variant| variant.status_code)
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
vec![200, 204, 206]
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
variants[0].content_type.as_deref(),
|
||||||
|
Some("application/json")
|
||||||
|
);
|
||||||
|
assert!(variants[0].schema.is_some());
|
||||||
|
assert_eq!(variants[1].content_type, None);
|
||||||
|
assert!(variants[1].schema.is_none());
|
||||||
|
assert_eq!(
|
||||||
|
variants[2].content_type.as_deref(),
|
||||||
|
Some("application/json")
|
||||||
|
);
|
||||||
|
assert!(variants[2].schema.is_some());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -243,7 +243,11 @@ paths:
|
|||||||
let ir = normalize(compatible);
|
let ir = normalize(compatible);
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
ir.operations[0].request_body_schema.as_ref().map(|schema| &schema.kind),
|
ir.operations[0].request_body_schema.as_ref().map(|schema| &schema.kind),
|
||||||
Some(NormalizedSchemaKind::Object { properties, required })
|
Some(NormalizedSchemaKind::Object {
|
||||||
|
properties,
|
||||||
|
required,
|
||||||
|
..
|
||||||
|
})
|
||||||
if properties.len() == 2 && required == &vec!["id".to_owned(), "name".to_owned()]
|
if properties.len() == 2 && required == &vec!["id".to_owned(), "name".to_owned()]
|
||||||
));
|
));
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
use crank_import::rest::preview_document;
|
||||||
|
use crank_schema::SchemaKind;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn preserves_format_default_nullable_and_string_enum_in_rest_projection() {
|
||||||
|
let document = r#"
|
||||||
|
openapi: 3.1.0
|
||||||
|
info: { title: Schema metadata }
|
||||||
|
paths:
|
||||||
|
/metadata:
|
||||||
|
get:
|
||||||
|
operationId: metadata
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: OK
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
identifier:
|
||||||
|
type: string
|
||||||
|
format: uuid
|
||||||
|
default: 00000000-0000-0000-0000-000000000000
|
||||||
|
nullable: true
|
||||||
|
state:
|
||||||
|
type: string
|
||||||
|
enum: [draft, published]
|
||||||
|
default: draft
|
||||||
|
ratio:
|
||||||
|
type: number
|
||||||
|
format: double
|
||||||
|
default: 1.5
|
||||||
|
nullable: true
|
||||||
|
"#;
|
||||||
|
|
||||||
|
let preview = preview_document(document).unwrap();
|
||||||
|
let schema = &preview.groups[0].operations[0].draft.output_schema;
|
||||||
|
|
||||||
|
let identifier = schema.field("identifier").unwrap();
|
||||||
|
assert_eq!(identifier.kind, SchemaKind::String);
|
||||||
|
assert_eq!(identifier.format.as_deref(), Some("uuid"));
|
||||||
|
assert_eq!(
|
||||||
|
identifier.default_value,
|
||||||
|
Some(json!("00000000-0000-0000-0000-000000000000"))
|
||||||
|
);
|
||||||
|
assert!(identifier.nullable);
|
||||||
|
|
||||||
|
let state = schema.field("state").unwrap();
|
||||||
|
assert_eq!(state.kind, SchemaKind::Enum);
|
||||||
|
assert_eq!(state.enum_values, vec!["draft", "published"]);
|
||||||
|
assert_eq!(state.default_value, Some(json!("draft")));
|
||||||
|
|
||||||
|
let ratio = schema.field("ratio").unwrap();
|
||||||
|
assert_eq!(ratio.kind, SchemaKind::Number);
|
||||||
|
assert_eq!(ratio.format.as_deref(), Some("double"));
|
||||||
|
assert_eq!(ratio.default_value, Some(json!(1.5)));
|
||||||
|
assert!(ratio.nullable);
|
||||||
|
|
||||||
|
let serialized = serde_json::to_value(schema).unwrap();
|
||||||
|
assert_eq!(serialized["fields"]["identifier"]["format"], "uuid");
|
||||||
|
assert_eq!(serialized["fields"]["identifier"]["nullable"], true);
|
||||||
|
}
|
||||||
@@ -0,0 +1,780 @@
|
|||||||
|
mod security_schemes {
|
||||||
|
use crank_import::rest::{
|
||||||
|
ImportFindingSeverity, ImportParseError, NormalizationConfig, NormalizedSecuritySchemeKind,
|
||||||
|
SecurityParameterLocation, SecurityRequirementsSource, normalize_verified_document,
|
||||||
|
preview_from_ir, scan_secret_literals, validate_normalized_ir,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn normalize_document(
|
||||||
|
document: &str,
|
||||||
|
config: &NormalizationConfig,
|
||||||
|
) -> Result<crank_import::rest::NormalizedIr, ImportParseError> {
|
||||||
|
normalize_verified_document(
|
||||||
|
document,
|
||||||
|
crank_import::rest::SourceDigest::parse("b".repeat(64)).unwrap(),
|
||||||
|
config,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ac_1_projects_openapi_security_scheme_identity_onto_operation_metadata() {
|
||||||
|
let document = r#"
|
||||||
|
openapi: 3.1.0
|
||||||
|
info: { title: Security metadata }
|
||||||
|
components:
|
||||||
|
securitySchemes:
|
||||||
|
WorkspaceBearer:
|
||||||
|
type: http
|
||||||
|
scheme: bearer
|
||||||
|
bearerFormat: JWT
|
||||||
|
paths:
|
||||||
|
/private:
|
||||||
|
get:
|
||||||
|
operationId: private
|
||||||
|
security: [{ WorkspaceBearer: [] }]
|
||||||
|
responses: { '200': { description: ok } }
|
||||||
|
"#;
|
||||||
|
|
||||||
|
let ir = normalize_document(document, &NormalizationConfig::default()).unwrap();
|
||||||
|
let operation = ir
|
||||||
|
.operations
|
||||||
|
.iter()
|
||||||
|
.find(|operation| operation.path == "/private")
|
||||||
|
.unwrap();
|
||||||
|
let operation_contract = serde_json::to_string(operation).unwrap();
|
||||||
|
|
||||||
|
// This assertion deliberately inspects the operation projection, not the
|
||||||
|
// canonical source tree, so copying the original document is insufficient.
|
||||||
|
assert!(operation_contract.contains("WorkspaceBearer"));
|
||||||
|
assert!(operation_contract.contains("bearer"));
|
||||||
|
assert!(operation_contract.contains("JWT"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ac_6_never_copies_literal_secret_canaries_into_normalized_ir() {
|
||||||
|
const CANARY: &str = "atdd-secret-canary-2-10";
|
||||||
|
let document = format!(
|
||||||
|
r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: {{ title: Secret canary }}
|
||||||
|
components:
|
||||||
|
securitySchemes:
|
||||||
|
Bearer:
|
||||||
|
type: http
|
||||||
|
scheme: bearer
|
||||||
|
x-example-token: {CANARY}
|
||||||
|
x-credentials: {CANARY}
|
||||||
|
x-ciphertext: {CANARY}
|
||||||
|
paths:
|
||||||
|
/private:
|
||||||
|
get:
|
||||||
|
security: [{{ Bearer: [] }}]
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: ok
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
example: {{ token: {CANARY} }}
|
||||||
|
"#
|
||||||
|
);
|
||||||
|
|
||||||
|
let ir = normalize_document(&document, &NormalizationConfig::default()).unwrap();
|
||||||
|
let normalized = serde_json::to_string(&ir).unwrap();
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
!normalized.contains(CANARY),
|
||||||
|
"normalized IR must not retain literal credential canaries"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn security_requirements_inherit_and_operation_empty_array_disables_auth() {
|
||||||
|
let document = r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: { title: Requirements }
|
||||||
|
components:
|
||||||
|
securitySchemes:
|
||||||
|
Key: { type: apiKey, in: header, name: X-Workspace-Key }
|
||||||
|
security: [{ Key: [] }]
|
||||||
|
paths:
|
||||||
|
/inherited:
|
||||||
|
get: { responses: { '200': { description: ok } } }
|
||||||
|
/public:
|
||||||
|
get:
|
||||||
|
security: []
|
||||||
|
responses: { '200': { description: ok } }
|
||||||
|
/and:
|
||||||
|
get:
|
||||||
|
security: [{ Key: [], Other: [] }]
|
||||||
|
responses: { '200': { description: ok } }
|
||||||
|
"#;
|
||||||
|
let ir = normalize_document(document, &NormalizationConfig::default()).unwrap();
|
||||||
|
let inherited = ir
|
||||||
|
.operations
|
||||||
|
.iter()
|
||||||
|
.find(|operation| operation.path == "/inherited")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
inherited.security_requirements.source,
|
||||||
|
SecurityRequirementsSource::Document
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
inherited.security_requirements.alternatives[0].schemes,
|
||||||
|
["Key"]
|
||||||
|
);
|
||||||
|
let public = ir
|
||||||
|
.operations
|
||||||
|
.iter()
|
||||||
|
.find(|operation| operation.path == "/public")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
public.security_requirements.source,
|
||||||
|
SecurityRequirementsSource::Operation
|
||||||
|
);
|
||||||
|
assert!(public.security_requirements.alternatives.is_empty());
|
||||||
|
let and = ir
|
||||||
|
.operations
|
||||||
|
.iter()
|
||||||
|
.find(|operation| operation.path == "/and")
|
||||||
|
.unwrap();
|
||||||
|
assert!(
|
||||||
|
and.findings
|
||||||
|
.iter()
|
||||||
|
.any(|finding| finding.code == "unsupported_security_and_requirement")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
and.security_requirements.alternatives[0].schemes,
|
||||||
|
["Key", "Other"]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn security_alternatives_preserve_or_and_and_preview_exposes_typed_schemes() {
|
||||||
|
let document = r#"
|
||||||
|
openapi: 3.1.0
|
||||||
|
info: { title: Alternatives }
|
||||||
|
components:
|
||||||
|
securitySchemes:
|
||||||
|
Bearer:
|
||||||
|
type: http
|
||||||
|
scheme: bearer
|
||||||
|
bearerFormat: JWT
|
||||||
|
User:
|
||||||
|
type: apiKey
|
||||||
|
in: query
|
||||||
|
name: access_token
|
||||||
|
CookieKey:
|
||||||
|
type: apiKey
|
||||||
|
in: cookie
|
||||||
|
name: session
|
||||||
|
security:
|
||||||
|
- Bearer: []
|
||||||
|
- User: []
|
||||||
|
- CookieKey: []
|
||||||
|
paths:
|
||||||
|
/private:
|
||||||
|
get: { responses: { '200': { description: ok } } }
|
||||||
|
"#;
|
||||||
|
let ir = normalize_document(document, &NormalizationConfig::default()).unwrap();
|
||||||
|
let first = preview_from_ir(&ir);
|
||||||
|
let second = preview_from_ir(&ir);
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::to_vec(&first).unwrap(),
|
||||||
|
serde_json::to_vec(&second).unwrap()
|
||||||
|
);
|
||||||
|
let candidate = &first.groups[0].operations[0];
|
||||||
|
assert_eq!(candidate.security_requirements.alternatives.len(), 3);
|
||||||
|
assert!(
|
||||||
|
matches!(candidate.security_schemes["Bearer"].kind, NormalizedSecuritySchemeKind::Http { ref format_hint, .. } if format_hint.as_deref() == Some("JWT"))
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
matches!(candidate.security_schemes["User"].kind, NormalizedSecuritySchemeKind::ApiKey { location: SecurityParameterLocation::Query, ref parameter_name, .. } if parameter_name == "access_token")
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
matches!(candidate.security_schemes["CookieKey"].kind, NormalizedSecuritySchemeKind::ApiKey { location: SecurityParameterLocation::Cookie, ref parameter_name, .. } if parameter_name == "session")
|
||||||
|
);
|
||||||
|
assert!(!candidate.security_requirements.alternatives[2].supported);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn swagger2_security_definitions_project_basic_and_api_key_header_and_query() {
|
||||||
|
let document = r#"
|
||||||
|
swagger: '2.0'
|
||||||
|
info: { title: Swagger security }
|
||||||
|
securityDefinitions:
|
||||||
|
BasicAuth: { type: basic }
|
||||||
|
HeaderKey: { type: apiKey, in: header, name: X-Api-Key }
|
||||||
|
QueryKey: { type: apiKey, in: query, name: api_key }
|
||||||
|
security: [{ BasicAuth: [] }, { HeaderKey: [] }]
|
||||||
|
paths:
|
||||||
|
/private:
|
||||||
|
get: { responses: { '200': { description: ok } } }
|
||||||
|
"#;
|
||||||
|
let ir = normalize_document(document, &NormalizationConfig::default()).unwrap();
|
||||||
|
assert!(
|
||||||
|
matches!(ir.security_schemes["BasicAuth"].kind, NormalizedSecuritySchemeKind::Http { ref scheme, .. } if scheme == "basic")
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
matches!(ir.security_schemes["HeaderKey"].kind, NormalizedSecuritySchemeKind::ApiKey { location: SecurityParameterLocation::Header, ref parameter_name, .. } if parameter_name == "X-Api-Key")
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
matches!(ir.security_schemes["QueryKey"].kind, NormalizedSecuritySchemeKind::ApiKey { location: SecurityParameterLocation::Query, ref parameter_name, .. } if parameter_name == "api_key")
|
||||||
|
);
|
||||||
|
assert_eq!(ir.operations[0].security_requirements.alternatives.len(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unsupported_security_schemes_create_blockers_without_copying_credentials() {
|
||||||
|
let document = r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: { title: Unsupported }
|
||||||
|
components:
|
||||||
|
securitySchemes:
|
||||||
|
OAuth: { type: oauth2, flows: {} }
|
||||||
|
Oidc: { type: openIdConnect, openIdConnectUrl: https://issuer.test }
|
||||||
|
Mutual: { type: mutualTLS }
|
||||||
|
paths:
|
||||||
|
/private:
|
||||||
|
get:
|
||||||
|
security: [{ OAuth: [read] }, { Oidc: [] }, { Mutual: [] }, { Unknown: [] }]
|
||||||
|
responses: { '200': { description: ok } }
|
||||||
|
"#;
|
||||||
|
let ir = normalize_document(document, &NormalizationConfig::default()).unwrap();
|
||||||
|
let codes = ir.operations[0]
|
||||||
|
.findings
|
||||||
|
.iter()
|
||||||
|
.map(|finding| finding.code.as_str())
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
assert!(codes.contains(&"unsupported_security_scheme"));
|
||||||
|
assert!(codes.contains(&"unresolved_security_scheme"));
|
||||||
|
assert!(!codes.contains(&"invalid_security_scopes"));
|
||||||
|
assert!(!codes.contains(&"unexpected_security_scopes"));
|
||||||
|
assert!(ir.operations[0].findings.iter().any(|finding| {
|
||||||
|
finding.code == "unsupported_security_requirements"
|
||||||
|
&& finding.severity == ImportFindingSeverity::Error
|
||||||
|
}));
|
||||||
|
assert!(
|
||||||
|
ir.operations[0]
|
||||||
|
.security_requirements
|
||||||
|
.alternatives
|
||||||
|
.iter()
|
||||||
|
.all(|alternative| !alternative.supported)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn normalized_ir_rejects_unrelated_security_findings_and_accepts_valid_security_ir() {
|
||||||
|
let document = r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: { title: Validation }
|
||||||
|
components:
|
||||||
|
securitySchemes:
|
||||||
|
OAuth: { type: oauth2, flows: {} }
|
||||||
|
paths:
|
||||||
|
/private:
|
||||||
|
get:
|
||||||
|
security: [{ OAuth: [] }]
|
||||||
|
responses: { '200': { description: ok } }
|
||||||
|
"#;
|
||||||
|
let ir = normalize_document(document, &NormalizationConfig::default()).unwrap();
|
||||||
|
validate_normalized_ir(&ir).unwrap();
|
||||||
|
|
||||||
|
let mut tampered = ir;
|
||||||
|
let finding = tampered.operations[0]
|
||||||
|
.findings
|
||||||
|
.iter_mut()
|
||||||
|
.find(|finding| finding.code == "unsupported_security_scheme")
|
||||||
|
.unwrap();
|
||||||
|
finding.location.pointer = "/info/title".to_owned();
|
||||||
|
finding.construct_id = "3.0.3:/info/title".to_owned();
|
||||||
|
assert_eq!(
|
||||||
|
validate_normalized_ir(&tampered),
|
||||||
|
Err(ImportParseError::InvalidDocument)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unsupported_or_alternative_does_not_block_a_supported_choice() {
|
||||||
|
let document = r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: { title: Mixed alternatives }
|
||||||
|
components:
|
||||||
|
securitySchemes:
|
||||||
|
Bearer: { type: http, scheme: bearer }
|
||||||
|
OAuth: { type: oauth2, flows: {} }
|
||||||
|
security: [{ OAuth: [] }, { Bearer: [] }]
|
||||||
|
paths:
|
||||||
|
/private:
|
||||||
|
get: { responses: { '200': { description: ok } } }
|
||||||
|
"#;
|
||||||
|
let ir = normalize_document(document, &NormalizationConfig::default()).unwrap();
|
||||||
|
let operation = &ir.operations[0];
|
||||||
|
assert_eq!(operation.security_requirements.alternatives.len(), 2);
|
||||||
|
assert!(!operation.security_requirements.alternatives[0].supported);
|
||||||
|
assert!(operation.security_requirements.alternatives[1].supported);
|
||||||
|
assert!(
|
||||||
|
!operation
|
||||||
|
.findings
|
||||||
|
.iter()
|
||||||
|
.any(|finding| finding.code == "unsupported_security_requirements")
|
||||||
|
);
|
||||||
|
assert!(operation.findings.iter().any(|finding| {
|
||||||
|
finding.code == "unsupported_security_scheme"
|
||||||
|
&& finding.severity == ImportFindingSeverity::Warning
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn openapi_invalid_http_scopes_are_selection_aware_and_valid_or_sibling_survives() {
|
||||||
|
let document = r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: { title: Invalid HTTP scopes }
|
||||||
|
components:
|
||||||
|
securitySchemes:
|
||||||
|
Bearer: { type: http, scheme: bearer }
|
||||||
|
security:
|
||||||
|
- Bearer: [read]
|
||||||
|
- Bearer: "read"
|
||||||
|
- Bearer: [1]
|
||||||
|
- Bearer: []
|
||||||
|
paths:
|
||||||
|
/private:
|
||||||
|
get: { responses: { '200': { description: ok } } }
|
||||||
|
"#;
|
||||||
|
let ir = normalize_document(document, &NormalizationConfig::default()).unwrap();
|
||||||
|
let operation = &ir.operations[0];
|
||||||
|
let alternatives = &operation.security_requirements.alternatives;
|
||||||
|
assert_eq!(alternatives.len(), 4);
|
||||||
|
assert!(
|
||||||
|
alternatives[..3]
|
||||||
|
.iter()
|
||||||
|
.all(|alternative| !alternative.supported)
|
||||||
|
);
|
||||||
|
assert!(alternatives[3].supported);
|
||||||
|
assert!(operation.findings.iter().any(|finding| {
|
||||||
|
finding.code == "unexpected_security_scopes"
|
||||||
|
&& finding.severity == ImportFindingSeverity::Warning
|
||||||
|
}));
|
||||||
|
assert!(operation.findings.iter().any(|finding| {
|
||||||
|
finding.code == "invalid_security_scopes"
|
||||||
|
&& finding.severity == ImportFindingSeverity::Warning
|
||||||
|
}));
|
||||||
|
assert!(
|
||||||
|
!operation
|
||||||
|
.findings
|
||||||
|
.iter()
|
||||||
|
.any(|finding| { finding.code == "unsupported_security_requirements" })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn swagger_invalid_api_key_scopes_do_not_hide_valid_or_sibling() {
|
||||||
|
let document = r#"
|
||||||
|
swagger: '2.0'
|
||||||
|
info: { title: Invalid Swagger scopes }
|
||||||
|
securityDefinitions:
|
||||||
|
HeaderKey: { type: apiKey, in: header, name: X-Api-Key }
|
||||||
|
BasicAuth: { type: basic }
|
||||||
|
security:
|
||||||
|
- HeaderKey: [read]
|
||||||
|
- BasicAuth: []
|
||||||
|
paths:
|
||||||
|
/private:
|
||||||
|
get: { responses: { '200': { description: ok } } }
|
||||||
|
"#;
|
||||||
|
let ir = normalize_document(document, &NormalizationConfig::default()).unwrap();
|
||||||
|
let operation = &ir.operations[0];
|
||||||
|
assert!(!operation.security_requirements.alternatives[0].supported);
|
||||||
|
assert!(operation.security_requirements.alternatives[1].supported);
|
||||||
|
assert!(operation.findings.iter().any(|finding| {
|
||||||
|
finding.code == "unexpected_security_scopes"
|
||||||
|
&& finding.severity == ImportFindingSeverity::Warning
|
||||||
|
}));
|
||||||
|
assert!(
|
||||||
|
!operation
|
||||||
|
.findings
|
||||||
|
.iter()
|
||||||
|
.any(|finding| { finding.code == "unsupported_security_requirements" })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scanner_finds_examples_defaults_extensions_and_url_userinfo_without_values() {
|
||||||
|
const CANARIES: [&str; 5] = [
|
||||||
|
"example-token-secret",
|
||||||
|
"default-password-secret",
|
||||||
|
"extension-api-key-secret",
|
||||||
|
"url-userinfo-secret",
|
||||||
|
"header-example-secret",
|
||||||
|
];
|
||||||
|
let document = r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: { title: Redaction }
|
||||||
|
servers: [{ url: 'https://operator:url-userinfo-secret@example.test' }]
|
||||||
|
components:
|
||||||
|
securitySchemes:
|
||||||
|
Bearer: { type: http, scheme: bearer, x-example-token: extension-api-key-secret }
|
||||||
|
paths:
|
||||||
|
/private:
|
||||||
|
get:
|
||||||
|
parameters:
|
||||||
|
- name: token
|
||||||
|
in: header
|
||||||
|
example: header-example-secret
|
||||||
|
schema: { type: string, default: default-password-secret }
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: ok
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
example: { token: example-token-secret }
|
||||||
|
"#;
|
||||||
|
let findings = scan_secret_literals(document.as_bytes()).unwrap();
|
||||||
|
assert!(findings.len() >= CANARIES.len());
|
||||||
|
let ir = normalize_document(document, &NormalizationConfig::default()).unwrap();
|
||||||
|
let serialized = serde_json::to_string(&ir).unwrap();
|
||||||
|
assert!(CANARIES.iter().all(|canary| !serialized.contains(canary)));
|
||||||
|
let report = serde_json::to_string(&findings).unwrap();
|
||||||
|
assert!(CANARIES.iter().all(|canary| !report.contains(canary)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scanner_does_not_mistake_password_or_token_schema_properties_for_credentials() {
|
||||||
|
let document = r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: { title: Password fields }
|
||||||
|
paths:
|
||||||
|
/login:
|
||||||
|
post:
|
||||||
|
requestBody:
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
properties:
|
||||||
|
password: { type: string, format: password }
|
||||||
|
access_token: { type: string }
|
||||||
|
responses: { '204': { description: ok } }
|
||||||
|
"#;
|
||||||
|
assert!(
|
||||||
|
scan_secret_literals(document.as_bytes())
|
||||||
|
.unwrap()
|
||||||
|
.is_empty()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scanner_keeps_version_examples_and_null_credential_defaults() {
|
||||||
|
let document = r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: { title: Benign examples }
|
||||||
|
components:
|
||||||
|
securitySchemes:
|
||||||
|
Bearer: { type: http, scheme: bearer, clientSecret: null }
|
||||||
|
paths:
|
||||||
|
/version:
|
||||||
|
get:
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: ok
|
||||||
|
content:
|
||||||
|
text/plain:
|
||||||
|
example: 1.2.3
|
||||||
|
"#;
|
||||||
|
assert!(
|
||||||
|
scan_secret_literals(document.as_bytes())
|
||||||
|
.unwrap()
|
||||||
|
.is_empty()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scanner_allows_oauth_endpoint_urls_but_redacts_secret_query_parameters() {
|
||||||
|
let safe_document = r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: { title: OAuth URLs }
|
||||||
|
components:
|
||||||
|
securitySchemes:
|
||||||
|
OAuth:
|
||||||
|
type: oauth2
|
||||||
|
flows:
|
||||||
|
authorizationCode:
|
||||||
|
authorizationUrl: https://auth.example.test/authorize
|
||||||
|
tokenUrl: https://auth.example.test/token
|
||||||
|
scopes: {}
|
||||||
|
password:
|
||||||
|
tokenUrl: https://auth.example.test/password-token
|
||||||
|
scopes: {}
|
||||||
|
clientCredentials:
|
||||||
|
tokenUrl: https://auth.example.test/client-token
|
||||||
|
scopes: {}
|
||||||
|
"#;
|
||||||
|
assert!(
|
||||||
|
scan_secret_literals(safe_document.as_bytes())
|
||||||
|
.unwrap()
|
||||||
|
.is_empty()
|
||||||
|
);
|
||||||
|
|
||||||
|
let secret_document = safe_document
|
||||||
|
.replace(
|
||||||
|
"https://auth.example.test/token",
|
||||||
|
"https://auth.example.test/token?access_token=oauth-url-canary",
|
||||||
|
)
|
||||||
|
.replace(
|
||||||
|
"https://auth.example.test/password-token",
|
||||||
|
"https://auth.example.test/password-token?access_token=password-flow-canary",
|
||||||
|
)
|
||||||
|
.replace(
|
||||||
|
"https://auth.example.test/client-token",
|
||||||
|
"https://auth.example.test/client-token?access_token=client-flow-canary",
|
||||||
|
);
|
||||||
|
let findings = scan_secret_literals(secret_document.as_bytes()).unwrap();
|
||||||
|
assert!(findings.iter().any(|finding| {
|
||||||
|
finding.location.pointer
|
||||||
|
== "/components/securitySchemes/OAuth/flows/authorizationCode/tokenUrl"
|
||||||
|
}));
|
||||||
|
assert!(findings.iter().any(|finding| {
|
||||||
|
finding.location.pointer == "/components/securitySchemes/OAuth/flows/password/tokenUrl"
|
||||||
|
}));
|
||||||
|
assert!(findings.iter().any(|finding| {
|
||||||
|
finding.location.pointer
|
||||||
|
== "/components/securitySchemes/OAuth/flows/clientCredentials/tokenUrl"
|
||||||
|
}));
|
||||||
|
let report = serde_json::to_string(&findings).unwrap();
|
||||||
|
assert!(!report.contains("oauth-url-canary"));
|
||||||
|
assert!(!report.contains("password-flow-canary"));
|
||||||
|
assert!(!report.contains("client-flow-canary"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn scanner_redacts_contextual_credentials_non_strings_jwts_and_cookie_examples() {
|
||||||
|
const CANARIES: [&str; 8] = [
|
||||||
|
"982734651",
|
||||||
|
"true",
|
||||||
|
"opaque-query-canary",
|
||||||
|
"cookie-session-canary",
|
||||||
|
"set-cookie-canary",
|
||||||
|
"query-param-canary",
|
||||||
|
"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.c2lnbmF0dXJl",
|
||||||
|
"opaque-jwt-object-key-canary",
|
||||||
|
];
|
||||||
|
const JWT_KEY: &str = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.c2lnbmF0dXJl";
|
||||||
|
let document = format!(
|
||||||
|
r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: {{ title: Contextual redaction }}
|
||||||
|
servers: [{{ url: 'https://api.test/items?access_token=opaque-query-canary' }}]
|
||||||
|
components:
|
||||||
|
securitySchemes:
|
||||||
|
Custom: {{ type: http, scheme: bearer, x-clientSecret: 982734651, x-accessToken: true }}
|
||||||
|
paths:
|
||||||
|
/login:
|
||||||
|
post:
|
||||||
|
parameters:
|
||||||
|
- name: api_key
|
||||||
|
in: query
|
||||||
|
schema: {{ type: string }}
|
||||||
|
example: query-param-canary
|
||||||
|
- name: Cookie
|
||||||
|
in: header
|
||||||
|
schema: {{ type: string }}
|
||||||
|
example: cookie-session-canary
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: ok
|
||||||
|
headers:
|
||||||
|
Set-Cookie:
|
||||||
|
schema: {{ type: string }}
|
||||||
|
example: set-cookie-canary
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
example: {{{JWT_KEY}: opaque-jwt-object-key-canary}}
|
||||||
|
examples:
|
||||||
|
compact:
|
||||||
|
value: {{{JWT_KEY}}}
|
||||||
|
"#
|
||||||
|
);
|
||||||
|
let findings = scan_secret_literals(document.as_bytes()).unwrap();
|
||||||
|
let location_pointers: Vec<_> = findings
|
||||||
|
.iter()
|
||||||
|
.map(|finding| finding.location.pointer.as_str())
|
||||||
|
.collect();
|
||||||
|
assert!(
|
||||||
|
location_pointers
|
||||||
|
.iter()
|
||||||
|
.any(|pointer| pointer.ends_with("/x-clientSecret"))
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
location_pointers
|
||||||
|
.iter()
|
||||||
|
.any(|pointer| pointer.ends_with("/x-accessToken"))
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
location_pointers
|
||||||
|
.iter()
|
||||||
|
.any(|pointer| pointer.ends_with("/servers/0/url"))
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
location_pointers
|
||||||
|
.iter()
|
||||||
|
.any(|pointer| pointer.ends_with("/parameters/0/example"))
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
location_pointers
|
||||||
|
.iter()
|
||||||
|
.any(|pointer| pointer.ends_with("/parameters/1/example"))
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
location_pointers
|
||||||
|
.iter()
|
||||||
|
.any(|pointer| pointer.ends_with("/headers/Set-Cookie/example"))
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
location_pointers
|
||||||
|
.iter()
|
||||||
|
.any(|pointer| pointer.ends_with("/content/application~1json/example"))
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
location_pointers
|
||||||
|
.iter()
|
||||||
|
.any(|pointer| pointer
|
||||||
|
.ends_with("/content/application~1json/examples/compact/value"))
|
||||||
|
);
|
||||||
|
|
||||||
|
let ir = normalize_document(&document, &NormalizationConfig::default()).unwrap();
|
||||||
|
let serialized = serde_json::to_string(&ir).unwrap();
|
||||||
|
for canary in CANARIES {
|
||||||
|
assert!(!serialized.contains(canary), "IR retained canary {canary}");
|
||||||
|
}
|
||||||
|
let redacted_locations: Vec<_> = ir
|
||||||
|
.findings
|
||||||
|
.iter()
|
||||||
|
.filter(|finding| finding.code == "secret_literal_redacted")
|
||||||
|
.map(|finding| finding.location.pointer.as_str())
|
||||||
|
.collect();
|
||||||
|
assert!(
|
||||||
|
redacted_locations
|
||||||
|
.iter()
|
||||||
|
.any(|pointer| pointer.ends_with("/x-clientSecret"))
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
redacted_locations
|
||||||
|
.iter()
|
||||||
|
.any(|pointer| pointer.ends_with("/x-accessToken"))
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
redacted_locations
|
||||||
|
.iter()
|
||||||
|
.any(|pointer| pointer.ends_with("/servers/0/url"))
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
redacted_locations
|
||||||
|
.iter()
|
||||||
|
.any(|pointer| pointer.ends_with("/parameters/0/example"))
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
redacted_locations
|
||||||
|
.iter()
|
||||||
|
.any(|pointer| pointer.ends_with("/parameters/1/example"))
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
redacted_locations
|
||||||
|
.iter()
|
||||||
|
.any(|pointer| pointer.ends_with("/headers/Set-Cookie/example"))
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
redacted_locations
|
||||||
|
.iter()
|
||||||
|
.any(|pointer| pointer.ends_with("/content/application~1json/example"))
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
redacted_locations
|
||||||
|
.iter()
|
||||||
|
.any(|pointer| pointer
|
||||||
|
.ends_with("/content/application~1json/examples/compact/value"))
|
||||||
|
);
|
||||||
|
let report = serde_json::to_string(&ir.findings).unwrap();
|
||||||
|
assert!(report.contains("secret_literal_redacted"));
|
||||||
|
for canary in CANARIES {
|
||||||
|
assert!(
|
||||||
|
!report.contains(canary),
|
||||||
|
"finding report retained canary {canary}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unsafe_bearer_format_canary_is_redacted_and_not_projected() {
|
||||||
|
const CANARY: &str = "Bearer sk-format-canary";
|
||||||
|
let document = format!(
|
||||||
|
r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: {{ title: Format redaction }}
|
||||||
|
components:
|
||||||
|
securitySchemes:
|
||||||
|
Bearer:
|
||||||
|
type: http
|
||||||
|
scheme: bearer
|
||||||
|
bearerFormat: "{CANARY}"
|
||||||
|
paths:
|
||||||
|
/private:
|
||||||
|
get: {{ security: [{{ Bearer: [] }}], responses: {{ '200': {{ description: ok }} }} }}
|
||||||
|
"#
|
||||||
|
);
|
||||||
|
let ir = normalize_document(&document, &NormalizationConfig::default()).unwrap();
|
||||||
|
let serialized = serde_json::to_string(&ir).unwrap();
|
||||||
|
assert!(!serialized.contains(CANARY));
|
||||||
|
let scan_findings = scan_secret_literals(document.as_bytes()).unwrap();
|
||||||
|
assert!(scan_findings.iter().any(|finding| {
|
||||||
|
finding.location.pointer == "/components/securitySchemes/Bearer/bearerFormat"
|
||||||
|
}));
|
||||||
|
let redaction_findings: Vec<_> = ir
|
||||||
|
.findings
|
||||||
|
.iter()
|
||||||
|
.filter(|finding| finding.code == "secret_literal_redacted")
|
||||||
|
.collect();
|
||||||
|
assert_eq!(redaction_findings.len(), 1);
|
||||||
|
assert_eq!(
|
||||||
|
redaction_findings[0].location.pointer,
|
||||||
|
"/components/securitySchemes/Bearer/bearerFormat"
|
||||||
|
);
|
||||||
|
let report = serde_json::to_string(&ir.findings).unwrap();
|
||||||
|
assert!(report.contains("secret_literal_redacted"));
|
||||||
|
assert!(report.contains("/components/securitySchemes/Bearer/bearerFormat"));
|
||||||
|
assert!(!report.contains(CANARY));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn historical_v4_ir_without_security_fields_remains_valid() {
|
||||||
|
let document = r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: { title: Replay }
|
||||||
|
paths:
|
||||||
|
/old:
|
||||||
|
get: { responses: { '200': { description: ok } } }
|
||||||
|
"#;
|
||||||
|
let ir = normalize_document(document, &NormalizationConfig::default()).unwrap();
|
||||||
|
let mut value = serde_json::to_value(ir).unwrap();
|
||||||
|
value["normalizer_version"] = serde_json::json!("normalized-ir-v4");
|
||||||
|
value["projection_version"] = serde_json::json!("preview-v4");
|
||||||
|
value.as_object_mut().unwrap().remove("security_schemes");
|
||||||
|
for operation in value["operations"].as_array_mut().unwrap() {
|
||||||
|
operation
|
||||||
|
.as_object_mut()
|
||||||
|
.unwrap()
|
||||||
|
.remove("security_schemes");
|
||||||
|
operation
|
||||||
|
.as_object_mut()
|
||||||
|
.unwrap()
|
||||||
|
.remove("security_requirements");
|
||||||
|
}
|
||||||
|
let replay: crank_import::rest::NormalizedIr = serde_json::from_value(value).unwrap();
|
||||||
|
validate_normalized_ir(&replay).unwrap();
|
||||||
|
assert!(
|
||||||
|
replay.operations[0]
|
||||||
|
.security_requirements
|
||||||
|
.alternatives
|
||||||
|
.is_empty()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
use crank_core::HttpMethod;
|
||||||
|
use crank_import::rest::{
|
||||||
|
NormalizationConfig, NormalizedSchemaKind, SourceDigest, normalize_verified_document,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn normalize(document: &str) -> crank_import::rest::NormalizedIr {
|
||||||
|
normalize_verified_document(
|
||||||
|
document,
|
||||||
|
SourceDigest::parse("0".repeat(64)).unwrap(),
|
||||||
|
&NormalizationConfig::default(),
|
||||||
|
)
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn swagger2_form_data_uses_effective_consumes_and_builds_body_schema() {
|
||||||
|
let document = r#"
|
||||||
|
swagger: '2.0'
|
||||||
|
info: { title: Forms }
|
||||||
|
host: example.test
|
||||||
|
schemes: [https]
|
||||||
|
consumes: [application/json, multipart/form-data]
|
||||||
|
produces: [application/json]
|
||||||
|
paths:
|
||||||
|
/upload:
|
||||||
|
post:
|
||||||
|
operationId: upload
|
||||||
|
consumes: [application/x-www-form-urlencoded, multipart/form-data]
|
||||||
|
parameters:
|
||||||
|
- { name: title, in: formData, type: string, required: true }
|
||||||
|
- { name: count, in: formData, type: integer }
|
||||||
|
- { name: file, in: formData, type: file }
|
||||||
|
responses:
|
||||||
|
'200': { description: OK, schema: { type: object, properties: { id: { type: string } } } }
|
||||||
|
'204': { description: Empty }
|
||||||
|
"#;
|
||||||
|
|
||||||
|
let ir = normalize(document);
|
||||||
|
let operation = &ir.operations[0];
|
||||||
|
assert_eq!(operation.method, HttpMethod::Post);
|
||||||
|
assert_eq!(
|
||||||
|
operation
|
||||||
|
.request_body_variants
|
||||||
|
.iter()
|
||||||
|
.map(|variant| variant.content_type.as_str())
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
vec!["application/x-www-form-urlencoded", "multipart/form-data"]
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
operation
|
||||||
|
.request_body_variants
|
||||||
|
.iter()
|
||||||
|
.all(|variant| variant.required)
|
||||||
|
);
|
||||||
|
let Some(NormalizedSchemaKind::Object { properties, .. }) = operation
|
||||||
|
.request_body_variants
|
||||||
|
.first()
|
||||||
|
.and_then(|variant| variant.schema.as_ref())
|
||||||
|
.map(|schema| &schema.kind)
|
||||||
|
else {
|
||||||
|
panic!("formData must become an object request schema");
|
||||||
|
};
|
||||||
|
assert!(properties.contains_key("title"));
|
||||||
|
assert!(properties.contains_key("count"));
|
||||||
|
assert!(properties.contains_key("file"));
|
||||||
|
assert!(
|
||||||
|
operation
|
||||||
|
.findings
|
||||||
|
.iter()
|
||||||
|
.all(|finding| finding.code != "unsupported_consumes")
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
operation
|
||||||
|
.response_variants
|
||||||
|
.iter()
|
||||||
|
.map(|variant| (variant.status_code, variant.content_type.as_deref()))
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
vec![(200, Some("application/json")), (204, None)]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn swagger2_operation_produces_overrides_global_and_preserves_json_variants() {
|
||||||
|
let document = r#"
|
||||||
|
swagger: '2.0'
|
||||||
|
info: { title: Responses }
|
||||||
|
host: example.test
|
||||||
|
schemes: [https]
|
||||||
|
produces: [application/json]
|
||||||
|
paths:
|
||||||
|
/items:
|
||||||
|
get:
|
||||||
|
operationId: listItems
|
||||||
|
produces: [application/problem+json, application/xml]
|
||||||
|
responses:
|
||||||
|
'200': { description: OK, schema: { type: array, items: { type: string } } }
|
||||||
|
"#;
|
||||||
|
|
||||||
|
let ir = normalize(document);
|
||||||
|
let operation = &ir.operations[0];
|
||||||
|
assert_eq!(
|
||||||
|
operation
|
||||||
|
.response_variants
|
||||||
|
.iter()
|
||||||
|
.map(|variant| variant.content_type.as_deref())
|
||||||
|
.collect::<Vec<_>>(),
|
||||||
|
vec![Some("application/problem+json")]
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
operation
|
||||||
|
.findings
|
||||||
|
.iter()
|
||||||
|
.any(|finding| finding.code == "unsupported_produces")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn swagger2_imports_head_options_and_reports_path_blockers() {
|
||||||
|
let document = r#"
|
||||||
|
swagger: '2.0'
|
||||||
|
info: { title: Methods }
|
||||||
|
host: example.test
|
||||||
|
schemes: [https]
|
||||||
|
paths:
|
||||||
|
/health:
|
||||||
|
head:
|
||||||
|
operationId: healthHead
|
||||||
|
responses: { '204': { description: Empty } }
|
||||||
|
options:
|
||||||
|
operationId: healthOptions
|
||||||
|
responses: { '204': { description: Empty } }
|
||||||
|
/broken/{id}:
|
||||||
|
get:
|
||||||
|
parameters:
|
||||||
|
- { name: other, in: path, required: true, type: string }
|
||||||
|
responses: { '200': { description: OK } }
|
||||||
|
/malformed: invalid
|
||||||
|
"#;
|
||||||
|
|
||||||
|
let ir = normalize(document);
|
||||||
|
assert!(
|
||||||
|
ir.operations
|
||||||
|
.iter()
|
||||||
|
.any(|operation| operation.method == HttpMethod::Head)
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
ir.operations
|
||||||
|
.iter()
|
||||||
|
.any(|operation| operation.method == HttpMethod::Options)
|
||||||
|
);
|
||||||
|
assert!(ir.operations.iter().any(|operation| {
|
||||||
|
operation.findings.iter().any(|finding| {
|
||||||
|
finding.code == "path_parameter_placeholder_missing"
|
||||||
|
&& finding.severity == crank_import::rest::ImportFindingSeverity::Error
|
||||||
|
})
|
||||||
|
}));
|
||||||
|
assert!(ir.findings.iter().any(|finding| {
|
||||||
|
finding.code == "invalid_path_item"
|
||||||
|
&& finding.severity == crank_import::rest::ImportFindingSeverity::Error
|
||||||
|
}));
|
||||||
|
}
|
||||||
@@ -55,6 +55,7 @@ fn empty_target_context(context: MappingTargetContext) -> Value {
|
|||||||
("path".to_owned(), Value::Object(Map::new())),
|
("path".to_owned(), Value::Object(Map::new())),
|
||||||
("query".to_owned(), Value::Object(Map::new())),
|
("query".to_owned(), Value::Object(Map::new())),
|
||||||
("headers".to_owned(), Value::Object(Map::new())),
|
("headers".to_owned(), Value::Object(Map::new())),
|
||||||
|
("cookies".to_owned(), Value::Object(Map::new())),
|
||||||
("body".to_owned(), Value::Object(Map::new())),
|
("body".to_owned(), Value::Object(Map::new())),
|
||||||
])),
|
])),
|
||||||
)])),
|
)])),
|
||||||
|
|||||||
@@ -8,7 +8,9 @@ pub enum JsonPathRoot {
|
|||||||
RequestPath,
|
RequestPath,
|
||||||
RequestQuery,
|
RequestQuery,
|
||||||
RequestHeaders,
|
RequestHeaders,
|
||||||
|
RequestCookies,
|
||||||
RequestBody,
|
RequestBody,
|
||||||
|
RequestBodyContentType,
|
||||||
ResponseBody,
|
ResponseBody,
|
||||||
ResponseData,
|
ResponseData,
|
||||||
Output,
|
Output,
|
||||||
@@ -21,7 +23,9 @@ impl JsonPathRoot {
|
|||||||
Self::RequestPath => "request.path",
|
Self::RequestPath => "request.path",
|
||||||
Self::RequestQuery => "request.query",
|
Self::RequestQuery => "request.query",
|
||||||
Self::RequestHeaders => "request.headers",
|
Self::RequestHeaders => "request.headers",
|
||||||
|
Self::RequestCookies => "request.cookies",
|
||||||
Self::RequestBody => "request.body",
|
Self::RequestBody => "request.body",
|
||||||
|
Self::RequestBodyContentType => "request.body_content_type",
|
||||||
Self::ResponseBody => "response.body",
|
Self::ResponseBody => "response.body",
|
||||||
Self::ResponseData => "response.data",
|
Self::ResponseData => "response.data",
|
||||||
Self::Output => "output",
|
Self::Output => "output",
|
||||||
@@ -34,7 +38,9 @@ impl JsonPathRoot {
|
|||||||
Self::RequestPath => &["request", "path"],
|
Self::RequestPath => &["request", "path"],
|
||||||
Self::RequestQuery => &["request", "query"],
|
Self::RequestQuery => &["request", "query"],
|
||||||
Self::RequestHeaders => &["request", "headers"],
|
Self::RequestHeaders => &["request", "headers"],
|
||||||
|
Self::RequestCookies => &["request", "cookies"],
|
||||||
Self::RequestBody => &["request", "body"],
|
Self::RequestBody => &["request", "body"],
|
||||||
|
Self::RequestBodyContentType => &["request", "body_content_type"],
|
||||||
Self::ResponseBody => &["response", "body"],
|
Self::ResponseBody => &["response", "body"],
|
||||||
Self::ResponseData => &["response", "data"],
|
Self::ResponseData => &["response", "data"],
|
||||||
Self::Output => &["output"],
|
Self::Output => &["output"],
|
||||||
@@ -116,8 +122,13 @@ impl JsonPath {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn match_root(input: &str) -> Option<(JsonPathRoot, &str)> {
|
fn match_root(input: &str) -> Option<(JsonPathRoot, &str)> {
|
||||||
const ROOTS: [(&str, JsonPathRoot); 8] = [
|
const ROOTS: [(&str, JsonPathRoot); 10] = [
|
||||||
|
(
|
||||||
|
"request.body_content_type",
|
||||||
|
JsonPathRoot::RequestBodyContentType,
|
||||||
|
),
|
||||||
("request.headers", JsonPathRoot::RequestHeaders),
|
("request.headers", JsonPathRoot::RequestHeaders),
|
||||||
|
("request.cookies", JsonPathRoot::RequestCookies),
|
||||||
("response.body", JsonPathRoot::ResponseBody),
|
("response.body", JsonPathRoot::ResponseBody),
|
||||||
("response.data", JsonPathRoot::ResponseData),
|
("response.data", JsonPathRoot::ResponseData),
|
||||||
("request.path", JsonPathRoot::RequestPath),
|
("request.path", JsonPathRoot::RequestPath),
|
||||||
|
|||||||
@@ -122,6 +122,8 @@ fn target_root_context(root: JsonPathRoot) -> Option<MappingTargetContext> {
|
|||||||
JsonPathRoot::RequestPath
|
JsonPathRoot::RequestPath
|
||||||
| JsonPathRoot::RequestQuery
|
| JsonPathRoot::RequestQuery
|
||||||
| JsonPathRoot::RequestHeaders
|
| JsonPathRoot::RequestHeaders
|
||||||
|
| JsonPathRoot::RequestCookies
|
||||||
|
| JsonPathRoot::RequestBodyContentType
|
||||||
| JsonPathRoot::RequestBody => Some(MappingTargetContext::Input),
|
| JsonPathRoot::RequestBody => Some(MappingTargetContext::Input),
|
||||||
JsonPathRoot::Output => Some(MappingTargetContext::Output),
|
JsonPathRoot::Output => Some(MappingTargetContext::Output),
|
||||||
_ => None,
|
_ => None,
|
||||||
@@ -165,6 +167,8 @@ fn validate_target_root(
|
|||||||
JsonPathRoot::RequestPath
|
JsonPathRoot::RequestPath
|
||||||
| JsonPathRoot::RequestQuery
|
| JsonPathRoot::RequestQuery
|
||||||
| JsonPathRoot::RequestHeaders
|
| JsonPathRoot::RequestHeaders
|
||||||
|
| JsonPathRoot::RequestCookies
|
||||||
|
| JsonPathRoot::RequestBodyContentType
|
||||||
| JsonPathRoot::RequestBody
|
| JsonPathRoot::RequestBody
|
||||||
),
|
),
|
||||||
MappingTargetContext::Output => root == JsonPathRoot::Output,
|
MappingTargetContext::Output => root == JsonPathRoot::Output,
|
||||||
|
|||||||
@@ -136,6 +136,8 @@ pub enum RegistryError {
|
|||||||
ImportJobNotFound { job_id: String },
|
ImportJobNotFound { job_id: String },
|
||||||
#[error("import job {job_id} was already applied with different parameters")]
|
#[error("import job {job_id} was already applied with different parameters")]
|
||||||
ImportJobAlreadyApplied { job_id: String },
|
ImportJobAlreadyApplied { job_id: String },
|
||||||
|
#[error("import auth profile binding is unavailable")]
|
||||||
|
ImportAuthBindingUnavailable,
|
||||||
#[error("unsupported enum representation for field {field}")]
|
#[error("unsupported enum representation for field {field}")]
|
||||||
InvalidEnumRepresentation { field: &'static str },
|
InvalidEnumRepresentation { field: &'static str },
|
||||||
#[error("invalid numeric value for field {field}: {value}")]
|
#[error("invalid numeric value for field {field}: {value}")]
|
||||||
|
|||||||
@@ -47,14 +47,15 @@ pub mod requests {
|
|||||||
CreateInvocationLogRequest, CreatePlatformApiKeyRequest, CreateSecretRequest,
|
CreateInvocationLogRequest, CreatePlatformApiKeyRequest, CreateSecretRequest,
|
||||||
CreateVersionRequest, CreateWorkspaceRequest, CreateYamlImportJobRequest,
|
CreateVersionRequest, CreateWorkspaceRequest, CreateYamlImportJobRequest,
|
||||||
DecideApprovalRequest, DetachArtifactSourceRequest, ExpireApprovalRequest,
|
DecideApprovalRequest, DetachArtifactSourceRequest, ExpireApprovalRequest,
|
||||||
FinishApprovalRequest, FinishImportJobRequest, ImportConflictMode, ImportJobSourceEnvelope,
|
FinishApprovalRequest, FinishImportJobRequest, ImportAuthRequirement, ImportConflictMode,
|
||||||
ImportOperationDraft, ListApprovalRequestsQuery, ListArtifactSourcesQuery,
|
ImportJobSourceEnvelope, ImportOperationDraft, ListApprovalRequestsQuery,
|
||||||
ListInvocationLogsQuery, ListProductEventsQuery, MasterKeyIdentityCandidate,
|
ListArtifactSourcesQuery, ListInvocationLogsQuery, ListProductEventsQuery,
|
||||||
PublishAgentRequest, PublishRequest, RecordOnboardingCompletionRequest,
|
MasterKeyIdentityCandidate, PublishAgentRequest, PublishRequest,
|
||||||
RecordOnboardingMilestoneRequest, RecoverAdminPasswordRequest, RotateSecretRequest,
|
RecordOnboardingCompletionRequest, RecordOnboardingMilestoneRequest,
|
||||||
SaveAgentBindingsRequest, SaveAgentCatalogConfigRequest, SaveAuthProfileRequest,
|
RecoverAdminPasswordRequest, RotateSecretRequest, SaveAgentBindingsRequest,
|
||||||
SaveDescriptorMetadataRequest, SaveSampleMetadataRequest, SaveWorkspaceUpstreamRequest,
|
SaveAgentCatalogConfigRequest, SaveAuthProfileRequest, SaveDescriptorMetadataRequest,
|
||||||
UpdateAgentSummaryRequest, UpdateWorkspaceRequest, UsageQuery,
|
SaveSampleMetadataRequest, SaveWorkspaceUpstreamRequest, UpdateAgentSummaryRequest,
|
||||||
|
UpdateWorkspaceRequest, UsageQuery,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,19 +83,20 @@ pub use model::{
|
|||||||
CreateInvocationLogRequest, CreatePlatformApiKeyRequest, CreateSecretRequest,
|
CreateInvocationLogRequest, CreatePlatformApiKeyRequest, CreateSecretRequest,
|
||||||
CreateVersionRequest, CreateWorkspaceRequest, CreateYamlImportJobRequest,
|
CreateVersionRequest, CreateWorkspaceRequest, CreateYamlImportJobRequest,
|
||||||
DecideApprovalRequest, DescriptorKind, DescriptorMetadata, DetachArtifactSourceRequest,
|
DecideApprovalRequest, DescriptorKind, DescriptorMetadata, DetachArtifactSourceRequest,
|
||||||
ExpireApprovalRequest, FinishApprovalRequest, FinishImportJobRequest, ImportConflictMode,
|
ExpireApprovalRequest, FinishApprovalRequest, FinishImportJobRequest, ImportAuthRequirement,
|
||||||
ImportJob, ImportJobApplyResult, ImportJobCleanupReport, ImportJobId, ImportJobKind,
|
ImportConflictMode, ImportJob, ImportJobApplyResult, ImportJobCleanupReport, ImportJobId,
|
||||||
ImportJobSourceEnvelope, ImportJobStatus, ImportOperationDraft, InvitationRecord,
|
ImportJobKind, ImportJobSourceEnvelope, ImportJobStatus, ImportOperationDraft,
|
||||||
InvocationHistoryLoss, InvocationHistoryLossCategory, InvocationHistoryWriteOutcome,
|
InvitationRecord, InvocationHistoryLoss, InvocationHistoryLossCategory,
|
||||||
InvocationLogRecord, InvocationRetentionOutcome, InvocationRetentionPolicy,
|
InvocationHistoryWriteOutcome, InvocationLogRecord, InvocationRetentionOutcome,
|
||||||
InvocationRetentionStatus, ListApprovalRequestsQuery, ListArtifactSourcesQuery,
|
InvocationRetentionPolicy, InvocationRetentionStatus, ListApprovalRequestsQuery,
|
||||||
ListInvocationLogsQuery, ListProductEventsQuery, MASTER_KEY_CIPHER_CONTRACT,
|
ListArtifactSourcesQuery, ListInvocationLogsQuery, ListProductEventsQuery,
|
||||||
MAX_ARTIFACT_CLAIM_RECOVERY_BATCH, MAX_ARTIFACT_SOURCE_PAGE_SIZE, MasterKeyIdentityCandidate,
|
MASTER_KEY_CIPHER_CONTRACT, MAX_ARTIFACT_CLAIM_RECOVERY_BATCH, MAX_ARTIFACT_SOURCE_PAGE_SIZE,
|
||||||
MasterKeyIdentityRecord, MasterKeyRotationRecord, MasterKeyRotationStatus, MembershipRecord,
|
MasterKeyIdentityCandidate, MasterKeyIdentityRecord, MasterKeyRotationRecord,
|
||||||
OnboardingMilestoneResult, OnboardingPresentationMilestone, OperationAgentRef,
|
MasterKeyRotationStatus, MembershipRecord, OnboardingMilestoneResult,
|
||||||
OperationSampleMetadata, OperationStateExpectation, OperationSummary, OperationUsageSummary,
|
OnboardingPresentationMilestone, OperationAgentRef, OperationSampleMetadata,
|
||||||
OperationVersionRecord, Page, PlatformApiKeyRecord, ProductEventRecord, PublishAgentRequest,
|
OperationStateExpectation, OperationSummary, OperationUsageSummary, OperationVersionRecord,
|
||||||
PublishRequest, PublishedAgentCatalog, PublishedAgentTool, RecordOnboardingCompletionRequest,
|
Page, PlatformApiKeyRecord, ProductEventRecord, PublishAgentRequest, PublishRequest,
|
||||||
|
PublishedAgentCatalog, PublishedAgentTool, RecordOnboardingCompletionRequest,
|
||||||
RecordOnboardingMilestoneRequest, RecoverAdminPasswordRequest, RegistryOperation,
|
RecordOnboardingMilestoneRequest, RecoverAdminPasswordRequest, RegistryOperation,
|
||||||
RotateSecretRequest, SampleKind, SaveAgentBindingsRequest, SaveAgentCatalogConfigRequest,
|
RotateSecretRequest, SampleKind, SaveAgentBindingsRequest, SaveAgentCatalogConfigRequest,
|
||||||
SaveAuthProfileRequest, SaveDescriptorMetadataRequest, SaveSampleMetadataRequest,
|
SaveAuthProfileRequest, SaveDescriptorMetadataRequest, SaveSampleMetadataRequest,
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
use crank_artifacts::ArtifactRef;
|
use crank_artifacts::ArtifactRef;
|
||||||
use crank_core::{
|
use crank_core::{
|
||||||
Agent, AgentId, AgentOperationBinding, AgentStatus, AgentVersion, ApprovalRequest,
|
Agent, AgentId, AgentOperationBinding, AgentStatus, AgentVersion, ApprovalRequest,
|
||||||
ApprovalRequestId, ApprovalRequestStatus, AuthProfile, DescriptorId, ExecutionErrorCode,
|
ApprovalRequestId, ApprovalRequestStatus, AuthKind, AuthProfile, DescriptorId,
|
||||||
ExportMode, InvitationToken, InvocationLevel, InvocationLog, InvocationLogId, InvocationSource,
|
ExecutionErrorCode, ExportMode, InvitationToken, InvocationLevel, InvocationLog,
|
||||||
InvocationStatus, MembershipRole, OnboardingProjection, Operation, OperationId,
|
InvocationLogId, InvocationSource, InvocationStatus, MembershipRole, OnboardingProjection,
|
||||||
OperationSecurityLevel, OperationStatus, PlatformApiKey, PlatformApiKeyId, ProductEvent,
|
Operation, OperationId, OperationSecurityLevel, OperationStatus, PlatformApiKey,
|
||||||
ProductEventId, ProductEventKind, Protocol, SampleId, Secret, SecretId, SecretVersion,
|
PlatformApiKeyId, ProductEvent, ProductEventId, ProductEventKind, Protocol, SampleId, Secret,
|
||||||
ToolSelectionPolicy, UsagePeriod, UsageRollup, User, UserId, UserSessionId, Workspace,
|
SecretId, SecretVersion, ToolSelectionPolicy, UsagePeriod, UsageRollup, User, UserId,
|
||||||
WorkspaceId,
|
UserSessionId, Workspace, WorkspaceId,
|
||||||
};
|
};
|
||||||
use crank_mapping::MappingSet;
|
use crank_mapping::MappingSet;
|
||||||
use crank_schema::Schema;
|
use crank_schema::Schema;
|
||||||
@@ -648,6 +648,29 @@ pub enum ImportConflictMode {
|
|||||||
pub struct ImportOperationDraft {
|
pub struct ImportOperationDraft {
|
||||||
pub operation_key: String,
|
pub operation_key: String,
|
||||||
pub operation: RegistryOperation,
|
pub operation: RegistryOperation,
|
||||||
|
/// The effective single-scheme requirement selected for this operation.
|
||||||
|
/// The registry checks it against the referenced profile inside Apply.
|
||||||
|
pub auth_requirement: Option<ImportAuthRequirement>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(tag = "kind", rename_all = "snake_case")]
|
||||||
|
pub enum ImportAuthRequirement {
|
||||||
|
Bearer,
|
||||||
|
Basic,
|
||||||
|
ApiKeyHeader { parameter_name: String },
|
||||||
|
ApiKeyQuery { parameter_name: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ImportAuthRequirement {
|
||||||
|
pub const fn kind(&self) -> AuthKind {
|
||||||
|
match self {
|
||||||
|
Self::Bearer => AuthKind::Bearer,
|
||||||
|
Self::Basic => AuthKind::Basic,
|
||||||
|
Self::ApiKeyHeader { .. } => AuthKind::ApiKeyHeader,
|
||||||
|
Self::ApiKeyQuery { .. } => AuthKind::ApiKeyQuery,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::{ArtifactSourceId, ImportJobSourceEnvelope};
|
use crate::{ArtifactSourceId, ImportJobSourceEnvelope};
|
||||||
use crank_artifacts::ArtifactRef;
|
use crank_artifacts::ArtifactRef;
|
||||||
|
use crank_core::{AuthConfig, AuthProfile, AuthProfileId, SecretId};
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
const APPLICATION_RESULT_KEY: &str = "_crank_application_result";
|
const APPLICATION_RESULT_KEY: &str = "_crank_application_result";
|
||||||
const IMPORT_JOB_CLEANUP_BATCH: u32 = 128;
|
const IMPORT_JOB_CLEANUP_BATCH: u32 = 128;
|
||||||
@@ -388,6 +390,10 @@ async fn apply_import_job_transaction(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Validate the complete binding set before the first Operation insert.
|
||||||
|
// This transaction-level check closes the gap between preview and Apply.
|
||||||
|
validate_import_auth_bindings(tx, request.workspace_id, request.operations).await?;
|
||||||
|
|
||||||
let mut result = ImportJobApplyResult {
|
let mut result = ImportJobApplyResult {
|
||||||
application_key: request.application_key.to_owned(),
|
application_key: request.application_key.to_owned(),
|
||||||
skipped: request.pre_skipped.to_vec(),
|
skipped: request.pre_skipped.to_vec(),
|
||||||
@@ -485,6 +491,190 @@ async fn apply_import_job_transaction(
|
|||||||
Ok(result)
|
Ok(result)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn validate_import_auth_bindings(
|
||||||
|
tx: &mut Transaction<'_, Postgres>,
|
||||||
|
workspace_id: &WorkspaceId,
|
||||||
|
operations: &[crate::ImportOperationDraft],
|
||||||
|
) -> Result<(), RegistryError> {
|
||||||
|
let mut requirements_by_profile = BTreeMap::<String, Vec<&crate::ImportAuthRequirement>>::new();
|
||||||
|
for draft in operations {
|
||||||
|
match (
|
||||||
|
draft.auth_requirement.as_ref(),
|
||||||
|
draft.operation.execution_config.auth_profile_ref.as_ref(),
|
||||||
|
) {
|
||||||
|
(None, None) => {}
|
||||||
|
(Some(requirement), Some(profile_id)) => requirements_by_profile
|
||||||
|
.entry(profile_id.as_str().to_owned())
|
||||||
|
.or_default()
|
||||||
|
.push(requirement),
|
||||||
|
_ => return Err(RegistryError::ImportAuthBindingUnavailable),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if requirements_by_profile.is_empty() {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read the current workspace's profile config first to discover Secret
|
||||||
|
// references. Secret rows are locked in stable order before profile rows,
|
||||||
|
// matching save_auth_profile's secret-then-profile write order.
|
||||||
|
let mut observed_profiles = BTreeMap::<String, AuthProfile>::new();
|
||||||
|
let mut secret_ids = BTreeMap::<String, SecretId>::new();
|
||||||
|
for profile_id in requirements_by_profile.keys() {
|
||||||
|
let profile = read_import_auth_profile(tx, workspace_id, profile_id, false)
|
||||||
|
.await?
|
||||||
|
.ok_or(RegistryError::ImportAuthBindingUnavailable)?;
|
||||||
|
let requirements = &requirements_by_profile[profile_id];
|
||||||
|
if !requirements
|
||||||
|
.iter()
|
||||||
|
.all(|requirement| auth_profile_matches(profile_id, &profile, requirement))
|
||||||
|
{
|
||||||
|
return Err(RegistryError::ImportAuthBindingUnavailable);
|
||||||
|
}
|
||||||
|
for secret_id in profile.config.secret_ids() {
|
||||||
|
secret_ids
|
||||||
|
.entry(secret_id.as_str().to_owned())
|
||||||
|
.or_insert_with(|| secret_id.clone());
|
||||||
|
}
|
||||||
|
observed_profiles.insert(profile_id.clone(), profile);
|
||||||
|
}
|
||||||
|
|
||||||
|
for secret_id in secret_ids.values() {
|
||||||
|
let row = sqlx::query(
|
||||||
|
"select s.status,
|
||||||
|
exists (
|
||||||
|
select 1 from secret_versions sv
|
||||||
|
where sv.secret_id = s.id and sv.version = s.current_version
|
||||||
|
) as has_current_version
|
||||||
|
from secrets s
|
||||||
|
where s.workspace_id = $1 and s.id = $2
|
||||||
|
for update of s",
|
||||||
|
)
|
||||||
|
.bind(workspace_id.as_str())
|
||||||
|
.bind(secret_id.as_str())
|
||||||
|
.fetch_optional(&mut **tx)
|
||||||
|
.await?;
|
||||||
|
let Some(row) = row else {
|
||||||
|
return Err(RegistryError::ImportAuthBindingUnavailable);
|
||||||
|
};
|
||||||
|
if row.try_get::<String, _>("status")? != "active"
|
||||||
|
|| !row.try_get::<bool, _>("has_current_version")?
|
||||||
|
{
|
||||||
|
return Err(RegistryError::ImportAuthBindingUnavailable);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The profile may have changed while its former Secret rows were being
|
||||||
|
// locked. Lock profile rows only after Secrets (the order used by profile
|
||||||
|
// updates), then compare the binding config and revalidate compatibility.
|
||||||
|
for (profile_id, observed) in &observed_profiles {
|
||||||
|
let current = read_import_auth_profile(tx, workspace_id, profile_id, true)
|
||||||
|
.await?
|
||||||
|
.ok_or(RegistryError::ImportAuthBindingUnavailable)?;
|
||||||
|
if current.id != observed.id
|
||||||
|
|| current.workspace_id != observed.workspace_id
|
||||||
|
|| current.kind != observed.kind
|
||||||
|
|| current.config != observed.config
|
||||||
|
|| !requirements_by_profile[profile_id]
|
||||||
|
.iter()
|
||||||
|
.all(|requirement| auth_profile_matches(profile_id, ¤t, requirement))
|
||||||
|
{
|
||||||
|
return Err(RegistryError::ImportAuthBindingUnavailable);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn read_import_auth_profile(
|
||||||
|
tx: &mut Transaction<'_, Postgres>,
|
||||||
|
workspace_id: &WorkspaceId,
|
||||||
|
profile_id: &str,
|
||||||
|
lock: bool,
|
||||||
|
) -> Result<Option<AuthProfile>, RegistryError> {
|
||||||
|
let query = if lock {
|
||||||
|
"select id, workspace_id, name, kind, config_json, created_at, updated_at
|
||||||
|
from auth_profiles
|
||||||
|
where workspace_id = $1 and id = $2
|
||||||
|
for update"
|
||||||
|
} else {
|
||||||
|
"select id, workspace_id, name, kind, config_json, created_at, updated_at
|
||||||
|
from auth_profiles
|
||||||
|
where workspace_id = $1 and id = $2"
|
||||||
|
};
|
||||||
|
let row = sqlx::query(query)
|
||||||
|
.bind(workspace_id.as_str())
|
||||||
|
.bind(profile_id)
|
||||||
|
.fetch_optional(&mut **tx)
|
||||||
|
.await?;
|
||||||
|
row.map(|row| {
|
||||||
|
super::build_auth_profile(
|
||||||
|
row.try_get("id")?,
|
||||||
|
row.try_get("workspace_id")?,
|
||||||
|
row.try_get("name")?,
|
||||||
|
row.try_get("kind")?,
|
||||||
|
row.try_get("config_json")?,
|
||||||
|
row.try_get("created_at")?,
|
||||||
|
row.try_get("updated_at")?,
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.transpose()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn auth_profile_matches(
|
||||||
|
expected_profile_id: &str,
|
||||||
|
profile: &AuthProfile,
|
||||||
|
requirement: &crate::ImportAuthRequirement,
|
||||||
|
) -> bool {
|
||||||
|
if profile.id != AuthProfileId::new(expected_profile_id)
|
||||||
|
|| profile.kind != profile.config.kind()
|
||||||
|
|| profile.kind != requirement.kind()
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
match (requirement, &profile.config) {
|
||||||
|
(crate::ImportAuthRequirement::Bearer, AuthConfig::Bearer(_))
|
||||||
|
| (crate::ImportAuthRequirement::Basic, AuthConfig::Basic(_)) => true,
|
||||||
|
(
|
||||||
|
crate::ImportAuthRequirement::ApiKeyHeader { parameter_name },
|
||||||
|
AuthConfig::ApiKeyHeader(config),
|
||||||
|
) => {
|
||||||
|
is_valid_auth_header_name(&config.header_name)
|
||||||
|
&& is_valid_auth_header_name(parameter_name)
|
||||||
|
&& config.header_name.eq_ignore_ascii_case(parameter_name)
|
||||||
|
}
|
||||||
|
(
|
||||||
|
crate::ImportAuthRequirement::ApiKeyQuery { parameter_name },
|
||||||
|
AuthConfig::ApiKeyQuery(config),
|
||||||
|
) => config.param_name == *parameter_name,
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_valid_auth_header_name(value: &str) -> bool {
|
||||||
|
value.len() <= 128
|
||||||
|
&& !value.is_empty()
|
||||||
|
&& value.bytes().all(|byte| {
|
||||||
|
byte.is_ascii_alphanumeric()
|
||||||
|
|| matches!(
|
||||||
|
byte,
|
||||||
|
b'!' | b'#'
|
||||||
|
| b'$'
|
||||||
|
| b'%'
|
||||||
|
| b'&'
|
||||||
|
| b'\''
|
||||||
|
| b'*'
|
||||||
|
| b'+'
|
||||||
|
| b'-'
|
||||||
|
| b'.'
|
||||||
|
| b'^'
|
||||||
|
| b'_'
|
||||||
|
| b'`'
|
||||||
|
| b'|'
|
||||||
|
| b'~'
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
fn validate_source_envelope(
|
fn validate_source_envelope(
|
||||||
source: &ImportJobSourceEnvelope,
|
source: &ImportJobSourceEnvelope,
|
||||||
preview_payload: &Value,
|
preview_payload: &Value,
|
||||||
|
|||||||
@@ -448,6 +448,8 @@ fn target_summary(target: &Target) -> (String, String) {
|
|||||||
HttpMethod::Put => "PUT",
|
HttpMethod::Put => "PUT",
|
||||||
HttpMethod::Patch => "PATCH",
|
HttpMethod::Patch => "PATCH",
|
||||||
HttpMethod::Delete => "DELETE",
|
HttpMethod::Delete => "DELETE",
|
||||||
|
HttpMethod::Head => "HEAD",
|
||||||
|
HttpMethod::Options => "OPTIONS",
|
||||||
}
|
}
|
||||||
.to_owned(),
|
.to_owned(),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ mod integration {
|
|||||||
mod artifact_sources;
|
mod artifact_sources;
|
||||||
mod common;
|
mod common;
|
||||||
mod credential_touch;
|
mod credential_touch;
|
||||||
|
mod import_auth_binding;
|
||||||
mod master_key_identity;
|
mod master_key_identity;
|
||||||
mod migrations;
|
mod migrations;
|
||||||
mod observability;
|
mod observability;
|
||||||
|
|||||||
@@ -49,9 +49,13 @@ pub(super) fn test_operation(id: &str, version: u32, status: OperationStatus) ->
|
|||||||
method: HttpMethod::Post,
|
method: HttpMethod::Post,
|
||||||
path_template: "/v1/leads".to_owned(),
|
path_template: "/v1/leads".to_owned(),
|
||||||
static_headers: BTreeMap::from([("X-Static".to_owned(), "true".to_owned())]),
|
static_headers: BTreeMap::from([("X-Static".to_owned(), "true".to_owned())]),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
}),
|
}),
|
||||||
input_schema: Schema {
|
input_schema: Schema {
|
||||||
kind: SchemaKind::Object,
|
kind: SchemaKind::Object,
|
||||||
|
format: None,
|
||||||
description: Some("input".to_owned()),
|
description: Some("input".to_owned()),
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
@@ -60,6 +64,7 @@ pub(super) fn test_operation(id: &str, version: u32, status: OperationStatus) ->
|
|||||||
"email".to_owned(),
|
"email".to_owned(),
|
||||||
Schema {
|
Schema {
|
||||||
kind: SchemaKind::String,
|
kind: SchemaKind::String,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
@@ -76,6 +81,7 @@ pub(super) fn test_operation(id: &str, version: u32, status: OperationStatus) ->
|
|||||||
},
|
},
|
||||||
output_schema: Schema {
|
output_schema: Schema {
|
||||||
kind: SchemaKind::Object,
|
kind: SchemaKind::Object,
|
||||||
|
format: None,
|
||||||
description: Some("output".to_owned()),
|
description: Some("output".to_owned()),
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
@@ -84,6 +90,7 @@ pub(super) fn test_operation(id: &str, version: u32, status: OperationStatus) ->
|
|||||||
"id".to_owned(),
|
"id".to_owned(),
|
||||||
Schema {
|
Schema {
|
||||||
kind: SchemaKind::String,
|
kind: SchemaKind::String,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
|
|||||||
@@ -0,0 +1,570 @@
|
|||||||
|
use super::common::*;
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
fs,
|
||||||
|
os::unix::fs::PermissionsExt,
|
||||||
|
path::PathBuf,
|
||||||
|
sync::atomic::{AtomicU64, Ordering},
|
||||||
|
};
|
||||||
|
|
||||||
|
use crank_artifacts::{ArtifactRef, ArtifactStore};
|
||||||
|
use crank_core::{
|
||||||
|
ApiKeyHeaderAuthConfig, AuthConfig, AuthKind, AuthProfile, BearerAuthConfig, ExecutionConfig,
|
||||||
|
Secret, SecretKind, SecretStatus, Workspace, WorkspaceId, WorkspaceStatus,
|
||||||
|
};
|
||||||
|
use crank_registry::{
|
||||||
|
ApplyImportJobRequest, ArtifactSourceId, ArtifactSourceSensitivity,
|
||||||
|
CreateArtifactSourceRequest, CreateImportJobRequest, CreateSecretRequest,
|
||||||
|
CreateWorkspaceRequest, ImportAuthRequirement, ImportConflictMode, ImportJobId, ImportJobKind,
|
||||||
|
ImportJobSourceEnvelope, ImportJobStatus, ImportOperationDraft, MASTER_KEY_CIPHER_CONTRACT,
|
||||||
|
MasterKeyIdentityCandidate, PostgresRegistry, RegistryError, RegistryOperation,
|
||||||
|
SaveAuthProfileRequest,
|
||||||
|
};
|
||||||
|
use serde_json::json;
|
||||||
|
use time::OffsetDateTime;
|
||||||
|
use tokio::time::{Duration as TokioDuration, sleep};
|
||||||
|
|
||||||
|
static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
|
||||||
|
|
||||||
|
struct ImportSourceRoot(PathBuf);
|
||||||
|
|
||||||
|
impl ImportSourceRoot {
|
||||||
|
fn new() -> Self {
|
||||||
|
let path = std::env::temp_dir().join(format!(
|
||||||
|
"crank-registry-import-auth-{}-{}",
|
||||||
|
std::process::id(),
|
||||||
|
NEXT_ROOT.fetch_add(1, Ordering::Relaxed)
|
||||||
|
));
|
||||||
|
fs::create_dir(&path).unwrap();
|
||||||
|
fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap();
|
||||||
|
Self(path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for ImportSourceRoot {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = fs::set_permissions(&self.0, fs::Permissions::from_mode(0o700));
|
||||||
|
let _ = fs::remove_dir_all(&self.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn timestamp() -> OffsetDateTime {
|
||||||
|
OffsetDateTime::now_utc()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn create_workspace(registry: &PostgresRegistry, id: &str) -> WorkspaceId {
|
||||||
|
let now = timestamp();
|
||||||
|
let workspace_id = WorkspaceId::new(id);
|
||||||
|
registry
|
||||||
|
.create_workspace(CreateWorkspaceRequest {
|
||||||
|
workspace: &Workspace {
|
||||||
|
id: workspace_id.clone(),
|
||||||
|
slug: id.replace('_', "-"),
|
||||||
|
display_name: id.to_owned(),
|
||||||
|
status: WorkspaceStatus::Active,
|
||||||
|
settings: json!({}),
|
||||||
|
created_at: now,
|
||||||
|
updated_at: now,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
workspace_id
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn create_secret(registry: &PostgresRegistry, id: &str, workspace_id: &WorkspaceId) {
|
||||||
|
let now = timestamp();
|
||||||
|
registry
|
||||||
|
.verify_or_register_master_key_identity(MasterKeyIdentityCandidate {
|
||||||
|
epoch: 1,
|
||||||
|
fingerprint: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
|
||||||
|
cipher_contract: MASTER_KEY_CIPHER_CONTRACT,
|
||||||
|
observed_at: &now,
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
let secret = Secret {
|
||||||
|
id: id.into(),
|
||||||
|
workspace_id: workspace_id.clone(),
|
||||||
|
name: format!("secret-{id}"),
|
||||||
|
kind: SecretKind::Token,
|
||||||
|
status: SecretStatus::Active,
|
||||||
|
current_version: 1,
|
||||||
|
created_at: now,
|
||||||
|
updated_at: now,
|
||||||
|
last_used_at: None,
|
||||||
|
};
|
||||||
|
registry
|
||||||
|
.create_secret(CreateSecretRequest {
|
||||||
|
secret: &secret,
|
||||||
|
ciphertext: "opaque-test-ciphertext",
|
||||||
|
key_version: "test-key-v1",
|
||||||
|
master_key_epoch: 1,
|
||||||
|
created_by: None,
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn profile(
|
||||||
|
id: &str,
|
||||||
|
workspace_id: &WorkspaceId,
|
||||||
|
kind: AuthKind,
|
||||||
|
config: AuthConfig,
|
||||||
|
) -> AuthProfile {
|
||||||
|
let now = timestamp();
|
||||||
|
AuthProfile {
|
||||||
|
id: id.into(),
|
||||||
|
workspace_id: workspace_id.clone(),
|
||||||
|
name: format!("profile-{id}"),
|
||||||
|
kind,
|
||||||
|
config,
|
||||||
|
created_at: now,
|
||||||
|
updated_at: now,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn save_profile(registry: &PostgresRegistry, profile: &AuthProfile) {
|
||||||
|
registry
|
||||||
|
.save_auth_profile(SaveAuthProfileRequest {
|
||||||
|
workspace_id: &profile.workspace_id,
|
||||||
|
profile,
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn create_import_job(
|
||||||
|
registry: &PostgresRegistry,
|
||||||
|
root: &ImportSourceRoot,
|
||||||
|
job_number: usize,
|
||||||
|
) -> (ImportJobId, ArtifactSourceId, ArtifactRef) {
|
||||||
|
let store = ArtifactStore::open(&root.0).unwrap();
|
||||||
|
let artifact = store.put_registered(b"openapi: 3.1.0\n").unwrap();
|
||||||
|
let source_id = ArtifactSourceId::new(format!("src_import_auth_{job_number}"));
|
||||||
|
let now = timestamp();
|
||||||
|
let workspace_id = test_workspace_id();
|
||||||
|
registry
|
||||||
|
.create_artifact_source(CreateArtifactSourceRequest {
|
||||||
|
workspace_id: &workspace_id,
|
||||||
|
source_id: &source_id,
|
||||||
|
artifact: &artifact,
|
||||||
|
mime_type: "application/yaml",
|
||||||
|
sensitivity: ArtifactSourceSensitivity::Internal,
|
||||||
|
created_at: now,
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let source = ImportJobSourceEnvelope {
|
||||||
|
source_id: source_id.clone(),
|
||||||
|
digest: artifact.artifact_ref().clone(),
|
||||||
|
};
|
||||||
|
let payload = json!({
|
||||||
|
"source": {
|
||||||
|
"source_id": source.source_id.as_str(),
|
||||||
|
"digest": source.digest.as_str(),
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let id = ImportJobId::new(format!("job_import_auth_{job_number}"));
|
||||||
|
registry
|
||||||
|
.create_import_job(CreateImportJobRequest {
|
||||||
|
id: &id,
|
||||||
|
workspace_id: &workspace_id,
|
||||||
|
kind: ImportJobKind::OpenApi,
|
||||||
|
source_format: "openapi",
|
||||||
|
source_version: Some("v5"),
|
||||||
|
status: ImportJobStatus::Pending,
|
||||||
|
source: &source,
|
||||||
|
preview_payload: &payload,
|
||||||
|
created_at: &now,
|
||||||
|
expires_at: &(now + time::Duration::hours(1)),
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
(id, source_id, artifact.artifact_ref().clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn operation(id: &str, profile_id: Option<&str>) -> RegistryOperation {
|
||||||
|
let mut operation = test_operation(id, 1, crank_core::OperationStatus::Draft);
|
||||||
|
operation.execution_config = ExecutionConfig {
|
||||||
|
auth_profile_ref: profile_id.map(Into::into),
|
||||||
|
..operation.execution_config
|
||||||
|
};
|
||||||
|
operation
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn apply(
|
||||||
|
registry: &PostgresRegistry,
|
||||||
|
job_id: &ImportJobId,
|
||||||
|
drafts: &[ImportOperationDraft],
|
||||||
|
) -> Result<crank_registry::ImportJobApplyResult, RegistryError> {
|
||||||
|
let workspace_id = test_workspace_id();
|
||||||
|
let now = timestamp();
|
||||||
|
registry
|
||||||
|
.apply_import_job(ApplyImportJobRequest {
|
||||||
|
id: job_id,
|
||||||
|
workspace_id: &workspace_id,
|
||||||
|
application_key: "test-app-key",
|
||||||
|
conflict_mode: ImportConflictMode::Rename,
|
||||||
|
operations: drafts,
|
||||||
|
pre_skipped: &[],
|
||||||
|
finished_at: &now,
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn operation_count(database: &TestDatabase, ids: &[&str]) -> i64 {
|
||||||
|
let pool = database.raw_pool().await;
|
||||||
|
let count = sqlx::query_scalar::<_, i64>("select count(*) from operations where id = any($1)")
|
||||||
|
.bind(ids)
|
||||||
|
.fetch_one(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
pool.close().await;
|
||||||
|
count
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn apply_accepts_current_compatible_profile_and_shared_secret_then_rejects_disabled_secret() {
|
||||||
|
let database = TestDatabase::new().await;
|
||||||
|
let registry = database.registry().await;
|
||||||
|
let workspace_id = test_workspace_id();
|
||||||
|
let secret_id = "secret_import_shared";
|
||||||
|
create_secret(®istry, secret_id, &workspace_id).await;
|
||||||
|
for profile_id in ["auth_import_a", "auth_import_b"] {
|
||||||
|
save_profile(
|
||||||
|
®istry,
|
||||||
|
&profile(
|
||||||
|
profile_id,
|
||||||
|
&workspace_id,
|
||||||
|
AuthKind::ApiKeyHeader,
|
||||||
|
AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
|
||||||
|
header_name: "x-api-key".to_owned(),
|
||||||
|
secret_id: secret_id.into(),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
|
||||||
|
let root = ImportSourceRoot::new();
|
||||||
|
let (job_id, _, _) = create_import_job(®istry, &root, 1).await;
|
||||||
|
let drafts = [
|
||||||
|
ImportOperationDraft {
|
||||||
|
operation_key: "first".to_owned(),
|
||||||
|
operation: operation("op_import_auth_first", Some("auth_import_a")),
|
||||||
|
auth_requirement: Some(ImportAuthRequirement::ApiKeyHeader {
|
||||||
|
parameter_name: "X-Api-Key".to_owned(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
ImportOperationDraft {
|
||||||
|
operation_key: "second".to_owned(),
|
||||||
|
operation: operation("op_import_auth_second", Some("auth_import_b")),
|
||||||
|
auth_requirement: Some(ImportAuthRequirement::ApiKeyHeader {
|
||||||
|
parameter_name: "X-Api-Key".to_owned(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
let result = apply(®istry, &job_id, &drafts).await.unwrap();
|
||||||
|
assert_eq!(result.created.len(), 2);
|
||||||
|
assert_eq!(
|
||||||
|
operation_count(
|
||||||
|
&database,
|
||||||
|
&["op_import_auth_first", "op_import_auth_second"]
|
||||||
|
)
|
||||||
|
.await,
|
||||||
|
2
|
||||||
|
);
|
||||||
|
|
||||||
|
let pool = database.raw_pool().await;
|
||||||
|
sqlx::query("update secrets set status = 'disabled' where id = $1")
|
||||||
|
.bind(secret_id)
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
pool.close().await;
|
||||||
|
|
||||||
|
let (job_id, _, _) = create_import_job(®istry, &root, 2).await;
|
||||||
|
let disabled_error = apply(®istry, &job_id, &drafts).await.unwrap_err();
|
||||||
|
assert_eq!(
|
||||||
|
disabled_error.to_string(),
|
||||||
|
"import auth profile binding is unavailable"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
operation_count(
|
||||||
|
&database,
|
||||||
|
&["op_import_auth_first", "op_import_auth_second"]
|
||||||
|
)
|
||||||
|
.await,
|
||||||
|
2
|
||||||
|
);
|
||||||
|
database.cleanup().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn missing_and_foreign_profiles_have_the_same_safe_error_and_insert_no_operation() {
|
||||||
|
let database = TestDatabase::new().await;
|
||||||
|
let registry = database.registry().await;
|
||||||
|
let foreign_workspace = create_workspace(®istry, "ws_import_auth_foreign").await;
|
||||||
|
create_secret(®istry, "secret_import_foreign", &foreign_workspace).await;
|
||||||
|
save_profile(
|
||||||
|
®istry,
|
||||||
|
&profile(
|
||||||
|
"auth_import_foreign",
|
||||||
|
&foreign_workspace,
|
||||||
|
AuthKind::Bearer,
|
||||||
|
AuthConfig::Bearer(BearerAuthConfig {
|
||||||
|
header_name: "Authorization".to_owned(),
|
||||||
|
secret_id: "secret_import_foreign".into(),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
let root = ImportSourceRoot::new();
|
||||||
|
let (missing_job, _, _) = create_import_job(®istry, &root, 3).await;
|
||||||
|
let missing = [ImportOperationDraft {
|
||||||
|
operation_key: "missing".to_owned(),
|
||||||
|
operation: operation("op_import_auth_missing", Some("auth_import_absent")),
|
||||||
|
auth_requirement: Some(ImportAuthRequirement::Bearer),
|
||||||
|
}];
|
||||||
|
let missing_error = apply(®istry, &missing_job, &missing).await.unwrap_err();
|
||||||
|
|
||||||
|
let (foreign_job, _, _) = create_import_job(®istry, &root, 4).await;
|
||||||
|
let foreign = [ImportOperationDraft {
|
||||||
|
operation_key: "foreign".to_owned(),
|
||||||
|
operation: operation("op_import_auth_foreign_ref", Some("auth_import_foreign")),
|
||||||
|
auth_requirement: Some(ImportAuthRequirement::Bearer),
|
||||||
|
}];
|
||||||
|
let foreign_error = apply(®istry, &foreign_job, &foreign).await.unwrap_err();
|
||||||
|
assert_eq!(
|
||||||
|
missing_error.to_string(),
|
||||||
|
"import auth profile binding is unavailable"
|
||||||
|
);
|
||||||
|
assert_eq!(missing_error.to_string(), foreign_error.to_string());
|
||||||
|
assert_eq!(
|
||||||
|
operation_count(
|
||||||
|
&database,
|
||||||
|
&["op_import_auth_missing", "op_import_auth_foreign_ref"]
|
||||||
|
)
|
||||||
|
.await,
|
||||||
|
0
|
||||||
|
);
|
||||||
|
database.cleanup().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn apply_rejects_kind_parameter_and_missing_current_version_before_mutation() {
|
||||||
|
let database = TestDatabase::new().await;
|
||||||
|
let registry = database.registry().await;
|
||||||
|
let workspace_id = test_workspace_id();
|
||||||
|
create_secret(®istry, "secret_import_mismatch", &workspace_id).await;
|
||||||
|
save_profile(
|
||||||
|
®istry,
|
||||||
|
&profile(
|
||||||
|
"auth_import_mismatch",
|
||||||
|
&workspace_id,
|
||||||
|
AuthKind::ApiKeyHeader,
|
||||||
|
AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
|
||||||
|
header_name: "X-Api-Key".to_owned(),
|
||||||
|
secret_id: "secret_import_mismatch".into(),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let root = ImportSourceRoot::new();
|
||||||
|
let bad_requirements = [
|
||||||
|
ImportAuthRequirement::Bearer,
|
||||||
|
ImportAuthRequirement::ApiKeyHeader {
|
||||||
|
parameter_name: "X-Different".to_owned(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
for (index, requirement) in bad_requirements.into_iter().enumerate() {
|
||||||
|
let (job_id, _, _) = create_import_job(®istry, &root, 5 + index).await;
|
||||||
|
let operation_id = format!("op_import_auth_mismatch_{index}");
|
||||||
|
let draft = [ImportOperationDraft {
|
||||||
|
operation_key: operation_id.clone(),
|
||||||
|
operation: operation(&operation_id, Some("auth_import_mismatch")),
|
||||||
|
auth_requirement: Some(requirement),
|
||||||
|
}];
|
||||||
|
let error = apply(®istry, &job_id, &draft).await.unwrap_err();
|
||||||
|
assert_eq!(
|
||||||
|
error.to_string(),
|
||||||
|
"import auth profile binding is unavailable"
|
||||||
|
);
|
||||||
|
assert_eq!(operation_count(&database, &[&operation_id]).await, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
let pool = database.raw_pool().await;
|
||||||
|
sqlx::query("update secrets set current_version = 2 where id = $1")
|
||||||
|
.bind("secret_import_mismatch")
|
||||||
|
.execute(&pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
pool.close().await;
|
||||||
|
let (job_id, _, _) = create_import_job(®istry, &root, 7).await;
|
||||||
|
let draft = [ImportOperationDraft {
|
||||||
|
operation_key: "missing-current".to_owned(),
|
||||||
|
operation: operation(
|
||||||
|
"op_import_auth_missing_current",
|
||||||
|
Some("auth_import_mismatch"),
|
||||||
|
),
|
||||||
|
auth_requirement: Some(ImportAuthRequirement::ApiKeyHeader {
|
||||||
|
parameter_name: "X-Api-Key".to_owned(),
|
||||||
|
}),
|
||||||
|
}];
|
||||||
|
let error = apply(®istry, &job_id, &draft).await.unwrap_err();
|
||||||
|
assert_eq!(
|
||||||
|
error.to_string(),
|
||||||
|
"import auth profile binding is unavailable"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
operation_count(&database, &["op_import_auth_missing_current"]).await,
|
||||||
|
0
|
||||||
|
);
|
||||||
|
database.cleanup().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn no_auth_requires_no_profile_reference() {
|
||||||
|
let database = TestDatabase::new().await;
|
||||||
|
let registry = database.registry().await;
|
||||||
|
let root = ImportSourceRoot::new();
|
||||||
|
let (job_id, _, _) = create_import_job(®istry, &root, 8).await;
|
||||||
|
let draft = [ImportOperationDraft {
|
||||||
|
operation_key: "inconsistent".to_owned(),
|
||||||
|
operation: operation("op_import_auth_no_requirement", Some("auth_nonexistent")),
|
||||||
|
auth_requirement: None,
|
||||||
|
}];
|
||||||
|
let error = apply(®istry, &job_id, &draft).await.unwrap_err();
|
||||||
|
assert_eq!(
|
||||||
|
error.to_string(),
|
||||||
|
"import auth profile binding is unavailable"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
operation_count(&database, &["op_import_auth_no_requirement"]).await,
|
||||||
|
0
|
||||||
|
);
|
||||||
|
database.cleanup().await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn apply_waiting_on_secret_disable_rejects_without_partial_draft_mutation() {
|
||||||
|
let database = TestDatabase::new().await;
|
||||||
|
let registry = database.registry().await;
|
||||||
|
let workspace_id = test_workspace_id();
|
||||||
|
create_secret(®istry, "secret_import_race", &workspace_id).await;
|
||||||
|
save_profile(
|
||||||
|
®istry,
|
||||||
|
&profile(
|
||||||
|
"auth_import_race",
|
||||||
|
&workspace_id,
|
||||||
|
AuthKind::ApiKeyHeader,
|
||||||
|
AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
|
||||||
|
header_name: "X-Api-Key".to_owned(),
|
||||||
|
secret_id: "secret_import_race".into(),
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
let root = ImportSourceRoot::new();
|
||||||
|
let (job_id, _, _) = create_import_job(®istry, &root, 9).await;
|
||||||
|
let drafts = vec![
|
||||||
|
ImportOperationDraft {
|
||||||
|
operation_key: "race-first".to_owned(),
|
||||||
|
operation: operation("op_import_auth_race_first", Some("auth_import_race")),
|
||||||
|
auth_requirement: Some(ImportAuthRequirement::ApiKeyHeader {
|
||||||
|
parameter_name: "X-Api-Key".to_owned(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
ImportOperationDraft {
|
||||||
|
operation_key: "race-second".to_owned(),
|
||||||
|
operation: operation("op_import_auth_race_second", Some("auth_import_race")),
|
||||||
|
auth_requirement: Some(ImportAuthRequirement::ApiKeyHeader {
|
||||||
|
parameter_name: "X-Api-Key".to_owned(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
let pool = database.raw_pool().await;
|
||||||
|
let mut disable_tx = pool.begin().await.unwrap();
|
||||||
|
sqlx::query("select id from secrets where workspace_id = $1 and id = $2 for update")
|
||||||
|
.bind(workspace_id.as_str())
|
||||||
|
.bind("secret_import_race")
|
||||||
|
.fetch_one(&mut *disable_tx)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let concurrent_registry = registry.clone();
|
||||||
|
let concurrent_job_id = job_id.clone();
|
||||||
|
let (started_tx, started_rx) = tokio::sync::oneshot::channel();
|
||||||
|
let apply_task = tokio::spawn(async move {
|
||||||
|
let _ = started_tx.send(());
|
||||||
|
let workspace_id = test_workspace_id();
|
||||||
|
let finished_at = timestamp();
|
||||||
|
concurrent_registry
|
||||||
|
.apply_import_job(ApplyImportJobRequest {
|
||||||
|
id: &concurrent_job_id,
|
||||||
|
workspace_id: &workspace_id,
|
||||||
|
application_key: "race-app-key",
|
||||||
|
conflict_mode: ImportConflictMode::Rename,
|
||||||
|
operations: &drafts,
|
||||||
|
pre_skipped: &[],
|
||||||
|
finished_at: &finished_at,
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
});
|
||||||
|
started_rx.await.unwrap();
|
||||||
|
|
||||||
|
// Use a separate pool because the transaction holding the lock occupies
|
||||||
|
// the raw pool's only connection.
|
||||||
|
let observer_pool = database.raw_pool().await;
|
||||||
|
let mut waiting_for_secret_lock = false;
|
||||||
|
for _ in 0..100 {
|
||||||
|
waiting_for_secret_lock = sqlx::query_scalar::<_, bool>(
|
||||||
|
"select exists (
|
||||||
|
select 1 from pg_stat_activity
|
||||||
|
where wait_event_type = 'Lock'
|
||||||
|
and query like 'select s.status,%'
|
||||||
|
and query like '%for update of s%'
|
||||||
|
)",
|
||||||
|
)
|
||||||
|
.fetch_one(&observer_pool)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
if waiting_for_secret_lock {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
sleep(TokioDuration::from_millis(10)).await;
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
waiting_for_secret_lock,
|
||||||
|
"Apply should be waiting on the locked Secret row"
|
||||||
|
);
|
||||||
|
observer_pool.close().await;
|
||||||
|
|
||||||
|
sqlx::query("update secrets set status = 'disabled' where workspace_id = $1 and id = $2")
|
||||||
|
.bind(workspace_id.as_str())
|
||||||
|
.bind("secret_import_race")
|
||||||
|
.execute(&mut *disable_tx)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
disable_tx.commit().await.unwrap();
|
||||||
|
|
||||||
|
let result = apply_task.await.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
result.unwrap_err().to_string(),
|
||||||
|
"import auth profile binding is unavailable"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
operation_count(
|
||||||
|
&database,
|
||||||
|
&["op_import_auth_race_first", "op_import_auth_race_second"]
|
||||||
|
)
|
||||||
|
.await,
|
||||||
|
0
|
||||||
|
);
|
||||||
|
pool.close().await;
|
||||||
|
database.cleanup().await;
|
||||||
|
}
|
||||||
@@ -251,6 +251,9 @@ async fn published_version_is_not_rewritten_by_a_later_save() {
|
|||||||
method: HttpMethod::Post,
|
method: HttpMethod::Post,
|
||||||
path_template: "/mutated".to_owned(),
|
path_template: "/mutated".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
});
|
});
|
||||||
changed.updated_at = timestamp("2026-03-25T12:20:00Z");
|
changed.updated_at = timestamp("2026-03-25T12:20:00Z");
|
||||||
|
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ uuid.workspace = true
|
|||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
axum.workspace = true
|
axum.workspace = true
|
||||||
|
crank-import = { path = "../crank-import" }
|
||||||
futures-util = "0.3"
|
futures-util = "0.3"
|
||||||
metrics.workspace = true
|
metrics.workspace = true
|
||||||
metrics-util = "0.20.4"
|
metrics-util = "0.20.4"
|
||||||
|
|||||||
@@ -85,6 +85,7 @@ fn infer_safety_class(operation: &RuntimeOperation) -> OperationSafetyClass {
|
|||||||
match &operation.target {
|
match &operation.target {
|
||||||
Target::Rest(target) => match target.method {
|
Target::Rest(target) => match target.method {
|
||||||
HttpMethod::Get => OperationSafetyClass::Read,
|
HttpMethod::Get => OperationSafetyClass::Read,
|
||||||
|
HttpMethod::Head | HttpMethod::Options => OperationSafetyClass::Read,
|
||||||
HttpMethod::Delete => OperationSafetyClass::Destructive,
|
HttpMethod::Delete => OperationSafetyClass::Destructive,
|
||||||
HttpMethod::Post | HttpMethod::Put | HttpMethod::Patch => OperationSafetyClass::Write,
|
HttpMethod::Post | HttpMethod::Put | HttpMethod::Patch => OperationSafetyClass::Write,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -185,6 +185,7 @@ mod tests {
|
|||||||
fn operation() -> RuntimeOperation {
|
fn operation() -> RuntimeOperation {
|
||||||
let schema = Schema {
|
let schema = Schema {
|
||||||
kind: SchemaKind::Object,
|
kind: SchemaKind::Object,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
@@ -204,6 +205,9 @@ mod tests {
|
|||||||
method: HttpMethod::Post,
|
method: HttpMethod::Post,
|
||||||
path_template: "/".to_owned(),
|
path_template: "/".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
}),
|
}),
|
||||||
input_schema: schema.clone(),
|
input_schema: schema.clone(),
|
||||||
output_schema: schema,
|
output_schema: schema,
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ use std::time::{Duration, Instant};
|
|||||||
|
|
||||||
use crank_core::{
|
use crank_core::{
|
||||||
AdapterRegistry, CoordinationStateStore, ExecutionMode, InvocationSource, InvocationStatus,
|
AdapterRegistry, CoordinationStateStore, ExecutionMode, InvocationSource, InvocationStatus,
|
||||||
MeteringEvent, ResponseCacheStore, SharedMeteringSink, SharedProtocolAdapter,
|
MeteringEvent, ResponseCacheStore, SharedMeteringSink, SharedProtocolAdapter, Target,
|
||||||
};
|
};
|
||||||
use crank_metrics::{
|
use crank_metrics::{
|
||||||
CacheOutcome, ConfirmationOutcome, IdempotencyOutcome, InFlightGuard,
|
CacheOutcome, ConfirmationOutcome, IdempotencyOutcome, InFlightGuard,
|
||||||
@@ -24,7 +24,7 @@ use crate::{
|
|||||||
AdapterResponse, ExecutionAuthorization, PreparedRequest, RuntimeError,
|
AdapterResponse, ExecutionAuthorization, PreparedRequest, RuntimeError,
|
||||||
RuntimeExecutionRequest, RuntimeLimits, RuntimeOperation, RuntimeRequestContext,
|
RuntimeExecutionRequest, RuntimeLimits, RuntimeOperation, RuntimeRequestContext,
|
||||||
auth::apply_resolved_auth,
|
auth::apply_resolved_auth,
|
||||||
request_preparation::adapter_prepared_request,
|
request_preparation::{adapter_prepared_request, validate_selected_body_variant},
|
||||||
response_cache::{
|
response_cache::{
|
||||||
adapter_response_from_cached, cached_response_from_adapter, response_cache_key,
|
adapter_response_from_cached, cached_response_from_adapter, response_cache_key,
|
||||||
response_cache_ttl,
|
response_cache_ttl,
|
||||||
@@ -284,6 +284,7 @@ impl RuntimeExecutor {
|
|||||||
.input_schema
|
.input_schema
|
||||||
.validate_shape(input)
|
.validate_shape(input)
|
||||||
.map_err(RuntimeError::InputSchema)?;
|
.map_err(RuntimeError::InputSchema)?;
|
||||||
|
validate_selected_body_variant(operation, input)?;
|
||||||
|
|
||||||
if operation.input_mapping.is_empty() {
|
if operation.input_mapping.is_empty() {
|
||||||
return Ok(PreparedRequest::default());
|
return Ok(PreparedRequest::default());
|
||||||
@@ -293,7 +294,16 @@ impl RuntimeExecutor {
|
|||||||
.input_mapping
|
.input_mapping
|
||||||
.apply(&json!({ "mcp": input }))
|
.apply(&json!({ "mcp": input }))
|
||||||
.map_err(RuntimeError::InputMapping)?;
|
.map_err(RuntimeError::InputMapping)?;
|
||||||
PreparedRequest::from_mapping_output(&mapped_input)
|
let mut prepared = PreparedRequest::from_mapping_output(&mapped_input, &operation.target)?;
|
||||||
|
let Target::Rest(target) = &operation.target;
|
||||||
|
if let Some(contract) = &target.request_contract
|
||||||
|
&& input.get(&contract.body_field).is_none()
|
||||||
|
{
|
||||||
|
// Mapping initializes an empty body object for legacy field mappings.
|
||||||
|
// A typed optional body is absent unless its public argument was supplied.
|
||||||
|
prepared.body = None;
|
||||||
|
}
|
||||||
|
Ok(prepared)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn execute_prepared(
|
async fn execute_prepared(
|
||||||
@@ -838,8 +848,7 @@ fn transform_response(
|
|||||||
let span = Stage::RuntimeResponseTransform.span();
|
let span = Stage::RuntimeResponseTransform.span();
|
||||||
let result = span.in_scope(|| {
|
let result = span.in_scope(|| {
|
||||||
let finalized_output = finalize_output(operation, response)?;
|
let finalized_output = finalize_output(operation, response)?;
|
||||||
operation
|
output_schema_for_response(operation, response)?
|
||||||
.output_schema
|
|
||||||
.validate_shape(&finalized_output)
|
.validate_shape(&finalized_output)
|
||||||
.map_err(RuntimeError::OutputSchema)?;
|
.map_err(RuntimeError::OutputSchema)?;
|
||||||
Ok(finalized_output)
|
Ok(finalized_output)
|
||||||
@@ -854,6 +863,43 @@ fn transform_response(
|
|||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn output_schema_for_response<'a>(
|
||||||
|
operation: &'a RuntimeOperation,
|
||||||
|
response: &AdapterResponse,
|
||||||
|
) -> Result<&'a crank_schema::Schema, RuntimeError> {
|
||||||
|
let Target::Rest(target) = &operation.target;
|
||||||
|
if target.response_contract.is_empty() {
|
||||||
|
return Ok(&operation.output_schema);
|
||||||
|
}
|
||||||
|
let media_type = response
|
||||||
|
.headers
|
||||||
|
.get("content-type")
|
||||||
|
.and_then(|value| value.split(';').next())
|
||||||
|
.map(str::trim);
|
||||||
|
let descriptor = target
|
||||||
|
.response_contract
|
||||||
|
.iter()
|
||||||
|
.filter(|descriptor| descriptor.status_code == response.status_code)
|
||||||
|
.find(|descriptor| match (&descriptor.media_type, media_type) {
|
||||||
|
(Some(expected), Some(actual)) => expected.eq_ignore_ascii_case(actual),
|
||||||
|
(None, _) => response.body.is_null(),
|
||||||
|
_ => false,
|
||||||
|
})
|
||||||
|
.ok_or(RuntimeError::InvalidExecutionRequest)?;
|
||||||
|
if target.response_contract.len() > 1
|
||||||
|
&& operation.output_schema.kind == crank_schema::SchemaKind::Oneof
|
||||||
|
{
|
||||||
|
return operation
|
||||||
|
.output_schema
|
||||||
|
.variants
|
||||||
|
.get(descriptor.schema_variant)
|
||||||
|
.ok_or(RuntimeError::InvalidExecutionRequest);
|
||||||
|
}
|
||||||
|
(descriptor.schema_variant == 0)
|
||||||
|
.then_some(&operation.output_schema)
|
||||||
|
.ok_or(RuntimeError::InvalidExecutionRequest)
|
||||||
|
}
|
||||||
|
|
||||||
fn record_runtime_result<T>(span: &Span, result: &Result<T, RuntimeError>) {
|
fn record_runtime_result<T>(span: &Span, result: &Result<T, RuntimeError>) {
|
||||||
match result {
|
match result {
|
||||||
Ok(_) => StageOutcome::Success.record(span),
|
Ok(_) => StageOutcome::Success.record(span),
|
||||||
|
|||||||
@@ -262,8 +262,14 @@ async fn resolve_existing(
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn policy(operation: &RuntimeOperation) -> Option<&IdempotencyPolicy> {
|
pub fn policy(operation: &RuntimeOperation) -> Option<&IdempotencyPolicy> {
|
||||||
let is_mutating_rest =
|
let is_mutating_rest = matches!(
|
||||||
matches!(&operation.target, Target::Rest(target) if target.method != HttpMethod::Get);
|
&operation.target,
|
||||||
|
Target::Rest(target)
|
||||||
|
if matches!(
|
||||||
|
target.method,
|
||||||
|
HttpMethod::Post | HttpMethod::Put | HttpMethod::Patch | HttpMethod::Delete
|
||||||
|
)
|
||||||
|
);
|
||||||
if !is_mutating_rest {
|
if !is_mutating_rest {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
@@ -398,9 +404,13 @@ mod tests {
|
|||||||
method: HttpMethod::Post,
|
method: HttpMethod::Post,
|
||||||
path_template: "/orders".to_owned(),
|
path_template: "/orders".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
}),
|
}),
|
||||||
input_schema: Schema {
|
input_schema: Schema {
|
||||||
kind: SchemaKind::Object,
|
kind: SchemaKind::Object,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
@@ -412,6 +422,7 @@ mod tests {
|
|||||||
},
|
},
|
||||||
output_schema: Schema {
|
output_schema: Schema {
|
||||||
kind: SchemaKind::Object,
|
kind: SchemaKind::Object,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
|
|||||||
@@ -51,6 +51,8 @@ pub struct PreparedRequest {
|
|||||||
pub trusted_header_names: BTreeSet<String>,
|
pub trusted_header_names: BTreeSet<String>,
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub body: Option<serde_json::Value>,
|
pub body: Option<serde_json::Value>,
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub body_content_type: Option<String>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub timeout_ms: u64,
|
pub timeout_ms: u64,
|
||||||
}
|
}
|
||||||
@@ -72,6 +74,7 @@ impl From<PreparedRequest> for crank_core::PreparedRequest {
|
|||||||
headers: value.headers,
|
headers: value.headers,
|
||||||
trusted_header_names: value.trusted_header_names,
|
trusted_header_names: value.trusted_header_names,
|
||||||
body: value.body,
|
body: value.body,
|
||||||
|
body_content_type: value.body_content_type,
|
||||||
timeout_ms: value.timeout_ms,
|
timeout_ms: value.timeout_ms,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -85,6 +88,7 @@ impl From<crank_core::PreparedRequest> for PreparedRequest {
|
|||||||
headers: value.headers,
|
headers: value.headers,
|
||||||
trusted_header_names: value.trusted_header_names,
|
trusted_header_names: value.trusted_header_names,
|
||||||
body: value.body,
|
body: value.body,
|
||||||
|
body_content_type: value.body_content_type,
|
||||||
timeout_ms: value.timeout_ms,
|
timeout_ms: value.timeout_ms,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,85 @@
|
|||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
use crank_core::Target;
|
use crank_core::Target;
|
||||||
|
use crank_schema::{SchemaError, SchemaKind};
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
use crate::{PreparedRequest, RuntimeError, RuntimeOperation};
|
use crate::{PreparedRequest, RuntimeError, RuntimeOperation};
|
||||||
|
|
||||||
|
/// Validates the imported `content_type`/`body` pair before mapping. The
|
||||||
|
/// public schema exposes the union of supported body shapes, while this check
|
||||||
|
/// binds the selected media type to its corresponding branch.
|
||||||
|
pub(crate) fn validate_selected_body_variant(
|
||||||
|
operation: &RuntimeOperation,
|
||||||
|
input: &Value,
|
||||||
|
) -> Result<(), RuntimeError> {
|
||||||
|
let Target::Rest(target) = &operation.target;
|
||||||
|
let Some(contract) = &target.request_contract else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
let Some(input) = input.as_object() else {
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
let body_field = contract.body_field.as_str();
|
||||||
|
let Some(selector_field) = contract.selector_field.as_deref() else {
|
||||||
|
if contract.body_required && !input.contains_key(body_field) {
|
||||||
|
return Err(RuntimeError::InputSchema(SchemaError::missing_field(
|
||||||
|
format!("$.{body_field}"),
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
match (input.get(selector_field), input.get(body_field)) {
|
||||||
|
(None, None) if !contract.body_required => Ok(()),
|
||||||
|
(_, None) => Err(RuntimeError::InputSchema(SchemaError::missing_field(
|
||||||
|
format!("$.{body_field}"),
|
||||||
|
))),
|
||||||
|
(None, Some(_)) => Err(RuntimeError::InputSchema(SchemaError::missing_field(
|
||||||
|
format!("$.{selector_field}"),
|
||||||
|
))),
|
||||||
|
(Some(selector), Some(_)) => {
|
||||||
|
let Some(selector) = selector.as_str() else {
|
||||||
|
return Err(RuntimeError::InputSchema(SchemaError::invalid_type(
|
||||||
|
format!("$.{selector_field}"),
|
||||||
|
"enum",
|
||||||
|
"non-string",
|
||||||
|
)));
|
||||||
|
};
|
||||||
|
let Some(descriptor) = contract
|
||||||
|
.variants
|
||||||
|
.iter()
|
||||||
|
.find(|variant| variant.media_type == selector)
|
||||||
|
else {
|
||||||
|
return Err(RuntimeError::InputSchema(SchemaError::invalid_enum_value(
|
||||||
|
format!("$.{selector_field}"),
|
||||||
|
contract
|
||||||
|
.variants
|
||||||
|
.iter()
|
||||||
|
.map(|variant| variant.media_type.clone())
|
||||||
|
.collect(),
|
||||||
|
selector,
|
||||||
|
)));
|
||||||
|
};
|
||||||
|
let selected_schema = if operation.input_schema.kind == SchemaKind::Oneof {
|
||||||
|
operation
|
||||||
|
.input_schema
|
||||||
|
.variants
|
||||||
|
.get(descriptor.schema_variant)
|
||||||
|
.ok_or(RuntimeError::InvalidExecutionRequest)?
|
||||||
|
} else if descriptor.schema_variant == 0 {
|
||||||
|
&operation.input_schema
|
||||||
|
} else {
|
||||||
|
return Err(RuntimeError::InvalidExecutionRequest);
|
||||||
|
};
|
||||||
|
selected_schema
|
||||||
|
.validate_shape(&Value::Object(input.clone()))
|
||||||
|
.map_err(RuntimeError::InputSchema)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl PreparedRequest {
|
impl PreparedRequest {
|
||||||
pub fn from_mapping_output(mapped: &Value) -> Result<Self, RuntimeError> {
|
pub fn from_mapping_output(mapped: &Value, target: &Target) -> Result<Self, RuntimeError> {
|
||||||
let request =
|
let request =
|
||||||
mapped
|
mapped
|
||||||
.get("request")
|
.get("request")
|
||||||
@@ -15,12 +88,40 @@ impl PreparedRequest {
|
|||||||
reason: "mapped input must contain request root".to_owned(),
|
reason: "mapped input must contain request root".to_owned(),
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
|
let mut headers = read_string_map(request.get("headers"), "request.headers")?;
|
||||||
|
for (index, (name, value)) in read_string_map(request.get("cookies"), "request.cookies")?
|
||||||
|
.into_iter()
|
||||||
|
.enumerate()
|
||||||
|
{
|
||||||
|
headers.insert(
|
||||||
|
format!("x-crank-internal-cookie-{index}"),
|
||||||
|
format!("{name}\t{value}"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let typed_body_contract =
|
||||||
|
matches!(target, Target::Rest(target) if target.request_contract.is_some());
|
||||||
|
let body = if typed_body_contract {
|
||||||
|
request.get("body").cloned()
|
||||||
|
} else {
|
||||||
|
request.get("body").and_then(non_empty_legacy_body).cloned()
|
||||||
|
};
|
||||||
|
let body_content_type = match request.get("body_content_type") {
|
||||||
|
Some(Value::String(value)) => Some(value.clone()),
|
||||||
|
Some(_) => {
|
||||||
|
return Err(RuntimeError::InvalidPreparedRequest {
|
||||||
|
field: "request.body_content_type".to_owned(),
|
||||||
|
reason: "must be a string".to_owned(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
path_params: read_string_map(request.get("path"), "request.path")?,
|
path_params: read_string_map(request.get("path"), "request.path")?,
|
||||||
query_params: read_string_map(request.get("query"), "request.query")?,
|
query_params: read_string_map(request.get("query"), "request.query")?,
|
||||||
headers: read_string_map(request.get("headers"), "request.headers")?,
|
headers,
|
||||||
trusted_header_names: Default::default(),
|
trusted_header_names: Default::default(),
|
||||||
body: request.get("body").and_then(non_empty_body).cloned(),
|
body,
|
||||||
|
body_content_type,
|
||||||
timeout_ms: 0,
|
timeout_ms: 0,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -93,10 +194,74 @@ fn stringify_value(value: &Value) -> Result<String, String> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn non_empty_body(value: &Value) -> Option<&Value> {
|
fn non_empty_legacy_body(value: &Value) -> Option<&Value> {
|
||||||
match value {
|
match value {
|
||||||
Value::Null => None,
|
Value::Null => None,
|
||||||
Value::Object(object) if object.is_empty() => None,
|
Value::Object(object) if object.is_empty() => None,
|
||||||
_ => Some(value),
|
_ => Some(value),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use crank_core::{
|
||||||
|
HttpMethod, RestRequestContract, RestRequestContractVersion, RestRequestDescriptor,
|
||||||
|
RestTarget, Target,
|
||||||
|
};
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
use crate::PreparedRequest;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn legacy_empty_and_null_bodies_remain_absent() {
|
||||||
|
let target = legacy_target();
|
||||||
|
for body in [json!(null), json!({})] {
|
||||||
|
let mapped = json!({"request": {"body": body}});
|
||||||
|
assert_eq!(
|
||||||
|
PreparedRequest::from_mapping_output(&mapped, &target)
|
||||||
|
.unwrap()
|
||||||
|
.body,
|
||||||
|
None
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn typed_contract_preserves_explicit_empty_and_null_bodies() {
|
||||||
|
let mut target = legacy_target();
|
||||||
|
let Target::Rest(rest) = &mut target;
|
||||||
|
rest.request_contract = Some(RestRequestContract {
|
||||||
|
version: RestRequestContractVersion::V1,
|
||||||
|
body_field: "body".to_owned(),
|
||||||
|
selector_field: None,
|
||||||
|
body_required: true,
|
||||||
|
variants: vec![RestRequestDescriptor {
|
||||||
|
media_type: "application/json".to_owned(),
|
||||||
|
schema_variant: 0,
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
for body in [json!(null), json!({})] {
|
||||||
|
let mapped = json!({"request": {"body": body}});
|
||||||
|
assert_eq!(
|
||||||
|
PreparedRequest::from_mapping_output(&mapped, &target)
|
||||||
|
.unwrap()
|
||||||
|
.body,
|
||||||
|
Some(body)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn legacy_target() -> Target {
|
||||||
|
Target::Rest(RestTarget {
|
||||||
|
base_url: "https://example.invalid".to_owned(),
|
||||||
|
method: HttpMethod::Post,
|
||||||
|
path_template: "/".to_owned(),
|
||||||
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,355 @@
|
|||||||
|
mod support;
|
||||||
|
|
||||||
|
use support::RuntimeExecutorTestExt;
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
collections::BTreeMap,
|
||||||
|
sync::{
|
||||||
|
Arc, Mutex,
|
||||||
|
atomic::{AtomicUsize, Ordering},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
use async_trait::async_trait;
|
||||||
|
use crank_core::{
|
||||||
|
AdapterResponse, ExecutionConfig, ExecutionMode, OperationId, Protocol, ProtocolAdapter,
|
||||||
|
ProtocolAdapterError, Target, ToolDescription,
|
||||||
|
};
|
||||||
|
use crank_import::rest::{RestImportCandidate, preview_document};
|
||||||
|
use crank_runtime::{RuntimeExecutorBuilder, RuntimeOperation};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
struct CaptureAdapter {
|
||||||
|
calls: Arc<AtomicUsize>,
|
||||||
|
prepared: Arc<Mutex<Option<crank_core::PreparedRequest>>>,
|
||||||
|
response: AdapterResponse,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait]
|
||||||
|
impl ProtocolAdapter for CaptureAdapter {
|
||||||
|
fn protocol(&self) -> Protocol {
|
||||||
|
Protocol::Rest
|
||||||
|
}
|
||||||
|
|
||||||
|
fn supports_mode(&self, mode: ExecutionMode) -> bool {
|
||||||
|
mode == ExecutionMode::Unary
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn invoke_unary(
|
||||||
|
&self,
|
||||||
|
_target: &Target,
|
||||||
|
prepared: &crank_core::PreparedRequest,
|
||||||
|
_context: &crank_core::RuntimeRequestContext,
|
||||||
|
) -> Result<AdapterResponse, ProtocolAdapterError> {
|
||||||
|
self.calls.fetch_add(1, Ordering::SeqCst);
|
||||||
|
*self.prepared.lock().expect("prepared lock") = Some(prepared.clone());
|
||||||
|
Ok(self.response.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn imported_media_selector_is_validated_before_adapter_and_travels_out_of_band() {
|
||||||
|
let operation = imported_operation(
|
||||||
|
r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: { title: Media }
|
||||||
|
servers: [{ url: https://example.invalid }]
|
||||||
|
paths:
|
||||||
|
/events:
|
||||||
|
post:
|
||||||
|
requestBody:
|
||||||
|
required: true
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema: { type: object, required: [name], properties: { name: { type: string } } }
|
||||||
|
application/x-www-form-urlencoded:
|
||||||
|
schema: { type: object, required: [title], properties: { title: { type: string } } }
|
||||||
|
responses: { '204': { description: Empty } }
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
let calls = Arc::new(AtomicUsize::new(0));
|
||||||
|
let prepared = Arc::new(Mutex::new(None));
|
||||||
|
let executor = RuntimeExecutorBuilder::new()
|
||||||
|
.register_adapter(Arc::new(CaptureAdapter {
|
||||||
|
calls: Arc::clone(&calls),
|
||||||
|
prepared: Arc::clone(&prepared),
|
||||||
|
response: response(204, BTreeMap::new(), Value::Null),
|
||||||
|
}))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
for invalid in [
|
||||||
|
json!({"body": {"name": "Ada"}}),
|
||||||
|
json!({"content_type": "text/plain", "body": {"name": "Ada"}}),
|
||||||
|
json!({"content_type": "application/json", "body": {"title": "wrong branch"}}),
|
||||||
|
] {
|
||||||
|
assert!(executor.execute(&operation, &invalid).await.is_err());
|
||||||
|
}
|
||||||
|
assert_eq!(calls.load(Ordering::SeqCst), 0);
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
executor
|
||||||
|
.execute(
|
||||||
|
&operation,
|
||||||
|
&json!({"content_type": "application/json", "body": {"name": "Ada"}}),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.is_ok()
|
||||||
|
);
|
||||||
|
let prepared = prepared.lock().expect("prepared lock").clone().unwrap();
|
||||||
|
assert_eq!(prepared.body, Some(json!({"name": "Ada"})));
|
||||||
|
assert_eq!(
|
||||||
|
prepared.body_content_type.as_deref(),
|
||||||
|
Some("application/json")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn imported_single_body_preserves_empty_object_and_required_file_fails_before_adapter() {
|
||||||
|
let empty_operation = imported_operation(
|
||||||
|
r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: { title: Empty }
|
||||||
|
servers: [{ url: https://example.invalid }]
|
||||||
|
paths:
|
||||||
|
/empty:
|
||||||
|
post:
|
||||||
|
requestBody:
|
||||||
|
required: true
|
||||||
|
content:
|
||||||
|
application/json: { schema: { type: object } }
|
||||||
|
responses: { '204': { description: Empty } }
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
let calls = Arc::new(AtomicUsize::new(0));
|
||||||
|
let prepared = Arc::new(Mutex::new(None));
|
||||||
|
let executor = RuntimeExecutorBuilder::new()
|
||||||
|
.register_adapter(Arc::new(CaptureAdapter {
|
||||||
|
calls: Arc::clone(&calls),
|
||||||
|
prepared: Arc::clone(&prepared),
|
||||||
|
response: response(204, BTreeMap::new(), Value::Null),
|
||||||
|
}))
|
||||||
|
.build();
|
||||||
|
assert!(
|
||||||
|
executor
|
||||||
|
.execute(&empty_operation, &json!({"body": {}}))
|
||||||
|
.await
|
||||||
|
.is_ok()
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
prepared
|
||||||
|
.lock()
|
||||||
|
.expect("prepared lock")
|
||||||
|
.as_ref()
|
||||||
|
.unwrap()
|
||||||
|
.body,
|
||||||
|
Some(json!({}))
|
||||||
|
);
|
||||||
|
|
||||||
|
let file_operation = imported_operation(
|
||||||
|
r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: { title: Upload }
|
||||||
|
servers: [{ url: https://example.invalid }]
|
||||||
|
paths:
|
||||||
|
/upload:
|
||||||
|
post:
|
||||||
|
requestBody:
|
||||||
|
required: true
|
||||||
|
content:
|
||||||
|
multipart/form-data:
|
||||||
|
schema:
|
||||||
|
type: object
|
||||||
|
required: [file]
|
||||||
|
properties: { file: { type: string, format: binary } }
|
||||||
|
responses: { '204': { description: Empty } }
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
executor
|
||||||
|
.execute(&file_operation, &json!({"body": {}}))
|
||||||
|
.await
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn response_status_selects_its_linked_output_schema_branch() {
|
||||||
|
let operation = imported_operation(
|
||||||
|
r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: { title: Responses }
|
||||||
|
servers: [{ url: https://example.invalid }]
|
||||||
|
paths:
|
||||||
|
/items:
|
||||||
|
get:
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: Full
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema: { type: object, required: [id], properties: { id: { type: string } } }
|
||||||
|
'206':
|
||||||
|
description: Partial
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema: { type: array, items: { type: string } }
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
let executor = RuntimeExecutorBuilder::new()
|
||||||
|
.register_adapter(Arc::new(CaptureAdapter {
|
||||||
|
calls: Arc::new(AtomicUsize::new(0)),
|
||||||
|
prepared: Arc::new(Mutex::new(None)),
|
||||||
|
response: response(
|
||||||
|
200,
|
||||||
|
BTreeMap::from([("content-type".to_owned(), "application/json".to_owned())]),
|
||||||
|
json!(["schema-for-206"]),
|
||||||
|
),
|
||||||
|
}))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
assert!(executor.execute(&operation, &json!({})).await.is_err());
|
||||||
|
|
||||||
|
for (status, body) in [(200, json!({"id": "full"})), (206, json!(["partial"]))] {
|
||||||
|
let executor = RuntimeExecutorBuilder::new()
|
||||||
|
.register_adapter(Arc::new(CaptureAdapter {
|
||||||
|
calls: Arc::new(AtomicUsize::new(0)),
|
||||||
|
prepared: Arc::new(Mutex::new(None)),
|
||||||
|
response: response(
|
||||||
|
status,
|
||||||
|
BTreeMap::from([("content-type".to_owned(), "application/json".to_owned())]),
|
||||||
|
body.clone(),
|
||||||
|
),
|
||||||
|
}))
|
||||||
|
.build();
|
||||||
|
assert_eq!(
|
||||||
|
executor.execute(&operation, &json!({})).await.unwrap(),
|
||||||
|
body
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn single_response_preserves_all_source_composition_branches() {
|
||||||
|
let operation = imported_operation(
|
||||||
|
r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: {title: Response union}
|
||||||
|
servers: [{url: https://example.invalid}]
|
||||||
|
paths:
|
||||||
|
/items:
|
||||||
|
get:
|
||||||
|
responses:
|
||||||
|
'200':
|
||||||
|
description: Either
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema:
|
||||||
|
oneOf:
|
||||||
|
- {type: string}
|
||||||
|
- {type: integer}
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
let Target::Rest(target) = &operation.target;
|
||||||
|
assert_eq!(target.response_contract.len(), 1);
|
||||||
|
assert_eq!(operation.output_schema.variants.len(), 2);
|
||||||
|
for body in [json!("text"), json!(42)] {
|
||||||
|
let executor = RuntimeExecutorBuilder::new()
|
||||||
|
.register_adapter(Arc::new(CaptureAdapter {
|
||||||
|
calls: Arc::new(AtomicUsize::new(0)),
|
||||||
|
prepared: Arc::new(Mutex::new(None)),
|
||||||
|
response: response(
|
||||||
|
200,
|
||||||
|
BTreeMap::from([("content-type".to_owned(), "application/json".to_owned())]),
|
||||||
|
body.clone(),
|
||||||
|
),
|
||||||
|
}))
|
||||||
|
.build();
|
||||||
|
assert_eq!(
|
||||||
|
executor.execute(&operation, &json!({})).await.unwrap(),
|
||||||
|
body
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn optional_single_body_distinguishes_omission_empty_object_and_null() {
|
||||||
|
let operation = imported_operation(
|
||||||
|
r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: {title: Optional body}
|
||||||
|
servers: [{url: https://example.invalid}]
|
||||||
|
paths:
|
||||||
|
/items:
|
||||||
|
post:
|
||||||
|
requestBody:
|
||||||
|
required: false
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema: {type: object, nullable: true}
|
||||||
|
responses: {'204': {description: Empty}}
|
||||||
|
"#,
|
||||||
|
);
|
||||||
|
let prepared = Arc::new(Mutex::new(None));
|
||||||
|
let executor = RuntimeExecutorBuilder::new()
|
||||||
|
.register_adapter(Arc::new(CaptureAdapter {
|
||||||
|
calls: Arc::new(AtomicUsize::new(0)),
|
||||||
|
prepared: Arc::clone(&prepared),
|
||||||
|
response: response(204, BTreeMap::new(), Value::Null),
|
||||||
|
}))
|
||||||
|
.build();
|
||||||
|
for (input, expected) in [
|
||||||
|
(json!({}), None),
|
||||||
|
(json!({"body": {}}), Some(json!({}))),
|
||||||
|
(json!({"body": null}), Some(Value::Null)),
|
||||||
|
] {
|
||||||
|
executor.execute(&operation, &input).await.unwrap();
|
||||||
|
assert_eq!(prepared.lock().unwrap().as_ref().unwrap().body, expected);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn imported_operation(document: &str) -> RuntimeOperation {
|
||||||
|
let preview = preview_document(document).expect("preview");
|
||||||
|
let draft = preview.groups[0].operations[0].draft.clone();
|
||||||
|
runtime_operation(draft)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn runtime_operation(draft: RestImportCandidate) -> RuntimeOperation {
|
||||||
|
RuntimeOperation {
|
||||||
|
operation_id: OperationId::new("op_http_contract"),
|
||||||
|
operation_version: 1,
|
||||||
|
tool_name: draft.name,
|
||||||
|
protocol: Protocol::Rest,
|
||||||
|
target: Target::Rest(draft.target),
|
||||||
|
input_schema: draft.input_schema,
|
||||||
|
output_schema: draft.output_schema,
|
||||||
|
input_mapping: draft.input_mapping,
|
||||||
|
output_mapping: draft.output_mapping,
|
||||||
|
execution_config: ExecutionConfig {
|
||||||
|
timeout_ms: 1_000,
|
||||||
|
retry_policy: None,
|
||||||
|
response_cache: None,
|
||||||
|
idempotency: None,
|
||||||
|
safety: None,
|
||||||
|
approval_policy: None,
|
||||||
|
auth_profile_ref: None,
|
||||||
|
headers: BTreeMap::new(),
|
||||||
|
},
|
||||||
|
tool_description: ToolDescription {
|
||||||
|
title: draft.tool_description.title,
|
||||||
|
description: draft.tool_description.description,
|
||||||
|
tags: draft.tool_description.tags,
|
||||||
|
examples: draft.tool_description.examples,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn response(status_code: u16, headers: BTreeMap<String, String>, body: Value) -> AdapterResponse {
|
||||||
|
AdapterResponse {
|
||||||
|
status_code,
|
||||||
|
headers,
|
||||||
|
data: body.clone(),
|
||||||
|
body,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
mod support;
|
||||||
|
|
||||||
|
use support::RuntimeExecutorTestExt;
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
collections::BTreeMap,
|
||||||
|
sync::{Arc, Mutex},
|
||||||
|
};
|
||||||
|
|
||||||
|
use axum::{
|
||||||
|
Router,
|
||||||
|
body::Bytes,
|
||||||
|
extract::{OriginalUri, State},
|
||||||
|
http::{HeaderMap, StatusCode},
|
||||||
|
routing::post,
|
||||||
|
};
|
||||||
|
use crank_adapter_rest::{OutboundHttpPolicy, RestAdapter};
|
||||||
|
use crank_core::{ExecutionConfig, OperationId, Protocol, Target};
|
||||||
|
use crank_import::rest::preview_document;
|
||||||
|
use crank_runtime::{RuntimeExecutorBuilder, RuntimeOperation};
|
||||||
|
use serde_json::json;
|
||||||
|
use tokio::net::TcpListener;
|
||||||
|
|
||||||
|
type Requests = Arc<Mutex<Vec<(HeaderMap, String, Bytes)>>>;
|
||||||
|
|
||||||
|
async fn capture(
|
||||||
|
State(requests): State<Requests>,
|
||||||
|
OriginalUri(uri): OriginalUri,
|
||||||
|
headers: HeaderMap,
|
||||||
|
body: Bytes,
|
||||||
|
) -> StatusCode {
|
||||||
|
requests
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.push((headers, uri.to_string(), body));
|
||||||
|
StatusCode::NO_CONTENT
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn imported_variants_execute_on_wire_and_reject_invalid_inputs_before_dispatch() {
|
||||||
|
let requests: Requests = Arc::new(Mutex::new(Vec::new()));
|
||||||
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let base_url = format!("http://{}", listener.local_addr().unwrap());
|
||||||
|
let app = Router::new()
|
||||||
|
.route("/events", post(capture))
|
||||||
|
.with_state(Arc::clone(&requests));
|
||||||
|
let server = tokio::spawn(async move {
|
||||||
|
axum::serve(listener, app).await.unwrap();
|
||||||
|
});
|
||||||
|
let source = r#"
|
||||||
|
openapi: 3.0.3
|
||||||
|
info: {title: Wire contract}
|
||||||
|
servers: [{url: 'http://wire.invalid'}]
|
||||||
|
paths:
|
||||||
|
/events:
|
||||||
|
post:
|
||||||
|
operationId: createEvent
|
||||||
|
parameters:
|
||||||
|
- {name: body, in: query, schema: {type: string}}
|
||||||
|
- {name: content_type, in: cookie, schema: {type: string}}
|
||||||
|
requestBody:
|
||||||
|
required: false
|
||||||
|
content:
|
||||||
|
application/json:
|
||||||
|
schema: {type: object, nullable: true, required: [name], properties: {name: {type: string}}}
|
||||||
|
application/x-www-form-urlencoded:
|
||||||
|
schema: {type: object, required: [title], properties: {title: {type: string}}}
|
||||||
|
multipart/form-data:
|
||||||
|
schema: {type: object, required: [file], properties: {file: {type: string, format: binary}}}
|
||||||
|
encoding: {file: {contentType: 'image/png, image/jpeg'}}
|
||||||
|
responses: {'204': {description: Empty}}
|
||||||
|
"#.replace("http://wire.invalid", &base_url);
|
||||||
|
let preview = preview_document(&source).unwrap();
|
||||||
|
assert_eq!(preview.groups[0].operations.len(), 1);
|
||||||
|
assert!(
|
||||||
|
!preview
|
||||||
|
.findings
|
||||||
|
.iter()
|
||||||
|
.any(|finding| finding.severity == crank_import::rest::ImportFindingSeverity::Error)
|
||||||
|
);
|
||||||
|
let draft = preview.groups[0].operations[0].draft.clone();
|
||||||
|
let operation = RuntimeOperation {
|
||||||
|
operation_id: OperationId::new("op_http_wire"),
|
||||||
|
operation_version: 1,
|
||||||
|
tool_name: draft.name,
|
||||||
|
protocol: Protocol::Rest,
|
||||||
|
target: Target::Rest(draft.target),
|
||||||
|
input_schema: draft.input_schema,
|
||||||
|
output_schema: draft.output_schema,
|
||||||
|
input_mapping: draft.input_mapping,
|
||||||
|
output_mapping: draft.output_mapping,
|
||||||
|
execution_config: ExecutionConfig {
|
||||||
|
timeout_ms: 2000,
|
||||||
|
retry_policy: None,
|
||||||
|
response_cache: None,
|
||||||
|
idempotency: None,
|
||||||
|
safety: None,
|
||||||
|
approval_policy: None,
|
||||||
|
auth_profile_ref: None,
|
||||||
|
headers: BTreeMap::new(),
|
||||||
|
},
|
||||||
|
tool_description: draft.tool_description,
|
||||||
|
};
|
||||||
|
let executor = RuntimeExecutorBuilder::new()
|
||||||
|
.register_adapter(Arc::new(RestAdapter::with_policy(
|
||||||
|
OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]),
|
||||||
|
)))
|
||||||
|
.build();
|
||||||
|
for invalid in [
|
||||||
|
json!({"body": {"name": "Ada"}}),
|
||||||
|
json!({"content_type": "application/json"}),
|
||||||
|
json!({"content_type": "text/plain", "body": {"name": "Ada"}}),
|
||||||
|
json!({"content_type": "application/json", "body": {"title": "wrong"}}),
|
||||||
|
json!({"content_type": "multipart/form-data", "body": {}}),
|
||||||
|
json!({"content_type": "multipart/form-data", "body": {"file": {"data_base64": "AA==", "filename": "bad\r\nname"}}}),
|
||||||
|
json!({"content_type": "multipart/form-data", "body": {"file": {"data_base64": "AA==", "content_type": "text/plain"}}}),
|
||||||
|
json!({"content_type": "multipart/form-data", "body": {"file": {"data_base64": "AA=="}}}),
|
||||||
|
json!({"content_type": "application/x-www-form-urlencoded", "body": null}),
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
executor.execute(&operation, &invalid).await.is_err(),
|
||||||
|
"accepted {invalid}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for invalid_base64 in [
|
||||||
|
"AA==\n",
|
||||||
|
"_w==",
|
||||||
|
"data:application/octet-stream;base64,AA==",
|
||||||
|
"AA",
|
||||||
|
"%%%",
|
||||||
|
] {
|
||||||
|
let invalid = json!({"content_type":"multipart/form-data", "body":{"file":{"data_base64":invalid_base64,"content_type":"image/png"}}});
|
||||||
|
assert!(executor.execute(&operation, &invalid).await.is_err());
|
||||||
|
}
|
||||||
|
assert!(requests.lock().unwrap().is_empty());
|
||||||
|
for valid in [
|
||||||
|
json!({"query_body": "wire-query", "cookie_content_type": "wire-cookie", "content_type": "application/json", "body": {"name": "Ada"}}),
|
||||||
|
json!({"content_type": "application/x-www-form-urlencoded", "body": {"title": "A B"}}),
|
||||||
|
json!({"content_type": "multipart/form-data", "body": {"file": {"data_base64": "AAH/", "filename": "image.png", "content_type": "image/png"}}}),
|
||||||
|
json!({"content_type": "application/json", "body": null}),
|
||||||
|
json!({}),
|
||||||
|
] {
|
||||||
|
executor.execute(&operation, &valid).await.unwrap();
|
||||||
|
}
|
||||||
|
let captured = requests.lock().unwrap();
|
||||||
|
assert_eq!(captured.len(), 5);
|
||||||
|
assert_eq!(captured[0].0["content-type"], "application/json");
|
||||||
|
assert_eq!(captured[0].0["cookie"], "content_type=wire-cookie");
|
||||||
|
assert_eq!(captured[0].1, "/events?body=wire-query");
|
||||||
|
assert_eq!(
|
||||||
|
serde_json::from_slice::<serde_json::Value>(&captured[0].2).unwrap(),
|
||||||
|
json!({"name":"Ada"})
|
||||||
|
);
|
||||||
|
assert_eq!(&captured[1].2[..], b"title=A+B");
|
||||||
|
assert!(
|
||||||
|
captured[2].0["content-type"]
|
||||||
|
.to_str()
|
||||||
|
.unwrap()
|
||||||
|
.starts_with("multipart/form-data; boundary=")
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
captured[2]
|
||||||
|
.2
|
||||||
|
.windows(9)
|
||||||
|
.any(|bytes| bytes == b"\r\n\r\n\0\x01\xff\r\n")
|
||||||
|
);
|
||||||
|
assert_eq!(&captured[3].2[..], b"null");
|
||||||
|
assert!(captured[4].2.is_empty());
|
||||||
|
server.abort();
|
||||||
|
}
|
||||||
@@ -296,6 +296,9 @@ fn destructive_delete_operation() -> Operation<Schema, MappingSet> {
|
|||||||
method: HttpMethod::Delete,
|
method: HttpMethod::Delete,
|
||||||
path_template: "/orders/{order_id}".to_owned(),
|
path_template: "/orders/{order_id}".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
}),
|
}),
|
||||||
input_schema: object_schema(BTreeMap::from([("order_id".to_owned(), string_schema())])),
|
input_schema: object_schema(BTreeMap::from([("order_id".to_owned(), string_schema())])),
|
||||||
output_schema: object_schema(BTreeMap::from([("deleted".to_owned(), bool_schema())])),
|
output_schema: object_schema(BTreeMap::from([("deleted".to_owned(), bool_schema())])),
|
||||||
@@ -353,6 +356,7 @@ fn destructive_delete_operation() -> Operation<Schema, MappingSet> {
|
|||||||
fn object_schema(fields: BTreeMap<String, Schema>) -> Schema {
|
fn object_schema(fields: BTreeMap<String, Schema>) -> Schema {
|
||||||
Schema {
|
Schema {
|
||||||
kind: SchemaKind::Object,
|
kind: SchemaKind::Object,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
@@ -367,6 +371,7 @@ fn object_schema(fields: BTreeMap<String, Schema>) -> Schema {
|
|||||||
fn string_schema() -> Schema {
|
fn string_schema() -> Schema {
|
||||||
Schema {
|
Schema {
|
||||||
kind: SchemaKind::String,
|
kind: SchemaKind::String,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
@@ -381,6 +386,7 @@ fn string_schema() -> Schema {
|
|||||||
fn bool_schema() -> Schema {
|
fn bool_schema() -> Schema {
|
||||||
Schema {
|
Schema {
|
||||||
kind: SchemaKind::Boolean,
|
kind: SchemaKind::Boolean,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
|
|||||||
@@ -310,6 +310,9 @@ fn idempotent_post_operation() -> Operation<Schema, MappingSet> {
|
|||||||
method: HttpMethod::Post,
|
method: HttpMethod::Post,
|
||||||
path_template: "/orders".to_owned(),
|
path_template: "/orders".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
}),
|
}),
|
||||||
input_schema: object_schema(BTreeMap::from([("request_id".to_owned(), string_schema())])),
|
input_schema: object_schema(BTreeMap::from([("request_id".to_owned(), string_schema())])),
|
||||||
output_schema: object_schema(BTreeMap::from([("result".to_owned(), string_schema())])),
|
output_schema: object_schema(BTreeMap::from([("result".to_owned(), string_schema())])),
|
||||||
@@ -359,6 +362,7 @@ fn idempotent_post_operation() -> Operation<Schema, MappingSet> {
|
|||||||
fn object_schema(fields: BTreeMap<String, Schema>) -> Schema {
|
fn object_schema(fields: BTreeMap<String, Schema>) -> Schema {
|
||||||
Schema {
|
Schema {
|
||||||
kind: SchemaKind::Object,
|
kind: SchemaKind::Object,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
@@ -373,6 +377,7 @@ fn object_schema(fields: BTreeMap<String, Schema>) -> Schema {
|
|||||||
fn string_schema() -> Schema {
|
fn string_schema() -> Schema {
|
||||||
Schema {
|
Schema {
|
||||||
kind: SchemaKind::String,
|
kind: SchemaKind::String,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
|
|||||||
@@ -72,9 +72,13 @@ fn no_input_get_operation() -> Operation<Schema, MappingSet> {
|
|||||||
method: HttpMethod::Get,
|
method: HttpMethod::Get,
|
||||||
path_template: "/health".to_owned(),
|
path_template: "/health".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
}),
|
}),
|
||||||
input_schema: Schema {
|
input_schema: Schema {
|
||||||
kind: SchemaKind::Object,
|
kind: SchemaKind::Object,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
@@ -86,6 +90,7 @@ fn no_input_get_operation() -> Operation<Schema, MappingSet> {
|
|||||||
},
|
},
|
||||||
output_schema: Schema {
|
output_schema: Schema {
|
||||||
kind: SchemaKind::Object,
|
kind: SchemaKind::Object,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
|
|||||||
@@ -322,6 +322,9 @@ fn operation(
|
|||||||
method,
|
method,
|
||||||
path_template: "/resource".to_owned(),
|
path_template: "/resource".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
}),
|
}),
|
||||||
input_schema: object_schema("key"),
|
input_schema: object_schema("key"),
|
||||||
output_schema: object_schema("result"),
|
output_schema: object_schema("result"),
|
||||||
@@ -366,6 +369,7 @@ fn operation(
|
|||||||
fn object_schema(field: &str) -> Schema {
|
fn object_schema(field: &str) -> Schema {
|
||||||
Schema {
|
Schema {
|
||||||
kind: SchemaKind::Object,
|
kind: SchemaKind::Object,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
@@ -374,6 +378,7 @@ fn object_schema(field: &str) -> Schema {
|
|||||||
field.to_owned(),
|
field.to_owned(),
|
||||||
Schema {
|
Schema {
|
||||||
kind: SchemaKind::String,
|
kind: SchemaKind::String,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
|
|||||||
@@ -597,6 +597,9 @@ fn operation() -> Operation<Schema, MappingSet> {
|
|||||||
method: HttpMethod::Post,
|
method: HttpMethod::Post,
|
||||||
path_template: "/test".to_owned(),
|
path_template: "/test".to_owned(),
|
||||||
static_headers: BTreeMap::new(),
|
static_headers: BTreeMap::new(),
|
||||||
|
request_contract: None,
|
||||||
|
response_contract: Vec::new(),
|
||||||
|
multipart_field_mime_types: BTreeMap::new(),
|
||||||
}),
|
}),
|
||||||
input_schema: object_schema(BTreeMap::from([("name".to_owned(), string_schema())])),
|
input_schema: object_schema(BTreeMap::from([("name".to_owned(), string_schema())])),
|
||||||
output_schema: object_schema(BTreeMap::from([("accepted".to_owned(), bool_schema())])),
|
output_schema: object_schema(BTreeMap::from([("accepted".to_owned(), bool_schema())])),
|
||||||
@@ -651,6 +654,7 @@ fn operation() -> Operation<Schema, MappingSet> {
|
|||||||
fn object_schema(fields: BTreeMap<String, Schema>) -> Schema {
|
fn object_schema(fields: BTreeMap<String, Schema>) -> Schema {
|
||||||
Schema {
|
Schema {
|
||||||
kind: SchemaKind::Object,
|
kind: SchemaKind::Object,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
@@ -665,6 +669,7 @@ fn object_schema(fields: BTreeMap<String, Schema>) -> Schema {
|
|||||||
fn string_schema() -> Schema {
|
fn string_schema() -> Schema {
|
||||||
Schema {
|
Schema {
|
||||||
kind: SchemaKind::String,
|
kind: SchemaKind::String,
|
||||||
|
format: None,
|
||||||
description: None,
|
description: None,
|
||||||
required: true,
|
required: true,
|
||||||
nullable: false,
|
nullable: false,
|
||||||
@@ -679,6 +684,7 @@ fn string_schema() -> Schema {
|
|||||||
fn bool_schema() -> Schema {
|
fn bool_schema() -> Schema {
|
||||||
Schema {
|
Schema {
|
||||||
kind: SchemaKind::Boolean,
|
kind: SchemaKind::Boolean,
|
||||||
|
format: None,
|
||||||
..string_schema()
|
..string_schema()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Loaded 100 of 109 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user