feat(import): complete OpenAPI onboarding and verify delivery
CI / Rust Checks (pull_request) Failing after 1s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped

This commit is contained in:
bsodfather committed 2026-10-09 17:50:38 +03:00
1 parent bb3e376767
commit e93de7015a
244 files changed
+57020 -5139

No files matched your search

@@ -1,11 +1,15 @@
use super::super::common::test_service_with_external_references;
use super::*;
use axum::{Router, routing::get};
use sha2::{Digest, Sha256};
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
// Serialized by the integration harness at baseline f5f40cb167a82b1e3c1ea2475db5cbaed9d9abfa; this v4 payload preserves the then-current security blocker and digest.
const BASELINE_V4_SECURITY_PREVIEW_PAYLOAD: &str = r###"{"dependencies":[],"dependency_snapshots":[],"normalization":{"config":{"external_references_enabled":false,"max_aliases":128,"max_bytes":262144,"max_collection_items":10000,"max_depth":64,"max_expanded_nodes":100000,"max_external_document_bytes":262144,"max_nodes":50000,"max_reference_depth":32,"max_reference_documents":32,"max_references":4096,"max_scalar_bytes":262144,"normalizer_version":"normalized-ir-v4","projection_version":"preview-v4"},"ir_fingerprint":"ae2319de76c13d631b26843623092d966e5deea7cda9e3e40e4acc6fa36a25a8","normalizer_version":"normalized-ir-v4","projection_version":"preview-v4"},"preview":{"findings":[{"code":"unsupported_security_requirement","message":"Требование безопасности должно быть привязано к настроенному Auth Profile перед публикацией этой операции; остальные операции не блокируются.","operation_key":"GET /secure","severity":"error"}],"groups":[{"key":"imported_operation","operations":[{"category":"imported","description":"Выполняет GET /public","draft":{"category":"imported","display_name":"Public","input_mapping":{},"input_schema":{"description":"Входные параметры MCP-инструмента","nullable":false,"required":true,"type":"object"},"name":"public","output_mapping":{"rules":[{"required":true,"source":"$.response.body","target":"$.output"}]},"output_schema":{"description":"Успешный ответ без тела","nullable":false,"required":true,"type":"null"},"target":{"base_url":"https://api.example.test","method":"GET","path_template":"/public","response_contract":[{"schema_variant":0,"status_code":200}]},"tool_description":{"description":"Выполняет GET /public","examples":[{"input":{}}],"title":"Public"},"wizard_state":{}},"findings":[{"code":"missing_summary","message":"У метода нет summary, отображаемое имя будет сгенерировано автоматически.","operation_key":"GET /public","severity":"warning"},{"code":"missing_description","message":"У метода нет description. Перед публикацией лучше описать, когда агенту стоит вызывать этот инструмент.","operation_key":"GET /public","severity":"warning"},{"code":"missing_response_schema","message":"У метода не найдена схема успешного ответа, результат будет описан как общий объект.","operation_key":"GET /public","severity":"warning"},{"code":"no_input_fields","message":"У инструмента нет входных параметров. Это нормально для справочных методов, но проверьте, что агенту не нужно передавать фильтры.","operation_key":"GET /public","severity":"info"},{"code":"empty_output_schema","message":"В ответе не найдено отдельных полей. Перед публикацией проверьте схему ответа и маппинг результата.","operation_key":"GET /public","severity":"warning"},{"code":"weak_tool_description","message":"Описание инструмента слишком короткое или техническое. Перед публикацией добавьте, когда агент должен вызывать инструмент и что будет в успешном ответе.","operation_key":"GET /public","severity":"warning"},{"code":"weak_tool_name","message":"Имя инструмента `public` выглядит слишком общим. Лучше использовать имя с конкретным действием и объектом.","operation_key":"GET /public","severity":"warning"}],"input_fields":0,"key":"GET /public","method":"GET","operation_id":"public","output_fields":0,"path":"/public","server_urls":["https://api.example.test"],"suggested_display_name":"Public","suggested_name":"public"},{"category":"imported","description":"Выполняет GET /secure","draft":{"category":"imported","display_name":"Secure","input_mapping":{},"input_schema":{"description":"Входные параметры MCP-инструмента","nullable":false,"required":true,"type":"object"},"name":"secure","output_mapping":{"rules":[{"required":true,"source":"$.response.body","target":"$.output"}]},"output_schema":{"description":"Успешный ответ без тела","nullable":false,"required":true,"type":"null"},"target":{"base_url":"https://api.example.test","method":"GET","path_template":"/secure","response_contract":[{"schema_variant":0,"status_code":200}]},"tool_description":{"description":"Выполняет GET /secure","examples":[{"input":{}}],"title":"Secure"},"wizard_state":{}},"findings":[{"code":"missing_summary","message":"У мет Line truncated
#[tokio::test]
#[serial]
async fn external_relative_chain_survives_reversed_builder_order_and_apply_never_refetches() {
@@ -35,7 +39,7 @@ async fn external_relative_chain_survives_reversed_builder_order_and_apply_never
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
@@ -99,13 +103,13 @@ paths:
&preview.job_id.as_str().into(),
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /items".to_owned()],
auth_mappings: vec![],
server_url: None,
conflict_mode: "skip".to_owned(),
},
)
.await
.unwrap();
server.abort();
assert_eq!(applied.created.len(), 1);
assert_eq!(fetches.load(Ordering::SeqCst), 2);
let active_sources: i64 = sqlx::query_scalar(
@@ -120,53 +124,80 @@ paths:
#[tokio::test]
#[serial]
async fn external_literal_credential_is_rejected_before_snapshot_persistence() {
let canary = "external-atdd-secret-canary-2-10";
async fn external_secret_document_is_rejected_before_blob_registration() {
let external_document = "Item: { type: object, x-api-key: external-secret-canary-42, properties: { id: { type: string } } }";
let fetched = Arc::new(AtomicUsize::new(0));
let fetch_count = Arc::clone(&fetched);
let app = Router::new().route(
"/schemas.yaml",
get(move || async move {
format!(
"Item: {{ type: object, properties: {{ token: {{ type: string, example: '{canary}' }} }} }}"
)
get(move || {
let fetch_count = Arc::clone(&fetch_count);
async move {
fetch_count.fetch_add(1, Ordering::SeqCst);
external_document
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_external_secret_rejected");
let service = test_service_with_external_references(
registry.clone(),
test_storage_root("openapi_import_external_literal_credential"),
storage_root.clone(),
vec![format!("{origin}/")],
);
let workspace_id = WorkspaceId::new("ws_default");
let upload = OpenApiUpload {
bytes: format!(
r#"
let error = service
.preview_openapi_import(
&workspace_id,
OpenApiUpload {
bytes: format!(
r#"
openapi: 3.1.0
info: {{ title: External secret canary }}
info: {{ title: Safe primary with unsafe external }}
servers: [{{ url: https://api.example.test }}]
paths:
/items:
get:
operationId: listItems
responses:
'200':
description: ok
content:
application/json:
schema: {{ $ref: '{origin}/schemas.yaml#/Item' }}
content: {{ application/json: {{ schema: {{ $ref: '{origin}/schemas.yaml#/Item' }} }} }}
"#
)
.into_bytes(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
},
)
.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));
.expect_err("unsafe external bundle must be rejected before source persistence");
server.abort();
assert_eq!(fetched.load(Ordering::SeqCst), 1);
let rendered_error = format!("{error:?}");
assert!(rendered_error.contains("invalid_document"));
assert!(!rendered_error.contains("external-secret-canary-42"));
// The raw dependency's content-addressed path must not exist even as an
// unregistered blob, and no other stored file may contain its literal.
let external_digest = format!("{:x}", Sha256::digest(external_document.as_bytes()));
let external_blob = storage_root
.join("sha256")
.join(&external_digest[..2])
.join(&external_digest);
assert!(
!external_blob.exists(),
"secret-bearing external response was written to the artifact store"
);
assert!(!storage_contains_literal(
&storage_root,
b"external-secret-canary-42"
));
let dependency_sources: i64 = sqlx::query_scalar(
"select count(*) from artifact_sources
where workspace_id = $1 and source_id like 'src_openapi_dep_%'",
@@ -175,14 +206,29 @@ paths:
.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);
let active_sources: i64 = sqlx::query_scalar(
"select count(*) from artifact_sources where workspace_id = $1 and lifecycle = 'active'",
)
.bind(workspace_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap();
assert_eq!(active_sources, 0);
}
fn storage_contains_literal(root: &std::path::Path, literal: &[u8]) -> bool {
std::fs::read_dir(root).unwrap().any(|entry| {
let path = entry.unwrap().path();
if path.is_dir() {
storage_contains_literal(&path, literal)
} else {
std::fs::read(path)
.unwrap()
.windows(literal.len())
.any(|window| window == literal)
}
})
}
#[tokio::test]
@@ -256,7 +302,6 @@ paths:
&preview.job_id.as_str().into(),
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /items".to_owned()],
auth_mappings: vec![],
server_url: None,
conflict_mode: "skip".to_owned(),
},
@@ -339,7 +384,6 @@ paths:
&corrupt_preview.job_id.as_str().into(),
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /items".to_owned()],
auth_mappings: vec![],
server_url: None,
conflict_mode: "skip".to_owned(),
},
@@ -386,7 +430,7 @@ async fn external_materialization_uses_one_wall_clock_timeout_and_cleans_cancell
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let timeout_server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
@@ -438,6 +482,7 @@ paths:
)
.await
.unwrap();
timeout_server.abort();
assert!(started.elapsed() < std::time::Duration::from_millis(800));
assert_eq!(fetches.load(Ordering::SeqCst), 2);
let job = registry
@@ -473,7 +518,10 @@ paths:
.fetch_one(registry.pool())
.await
.unwrap();
assert_eq!(detached_dependencies, 1);
assert_eq!(
detached_dependencies, 0,
"staged dependencies must not be persisted before the fetch chain completes"
);
}
#[tokio::test]
@@ -592,7 +640,6 @@ async fn exact_v2_contract_replays_persisted_preview_without_v3_or_dependency_re
&job_id,
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
auth_mappings: vec![],
server_url: Some("https://api.frankfurter.dev".to_owned()),
conflict_mode: "skip".to_owned(),
},
@@ -663,7 +710,6 @@ async fn exact_v3_contract_replays_persisted_preview_without_v4_or_dependency_re
&job_id,
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
auth_mappings: vec![],
server_url: Some("https://api.frankfurter.dev".to_owned()),
conflict_mode: "skip".to_owned(),
},
@@ -681,54 +727,58 @@ async fn exact_v3_contract_replays_persisted_preview_without_v4_or_dependency_re
#[tokio::test]
#[serial]
async fn exact_v4_contract_replays_legacy_preview_without_v5_reparse_or_dependency_reads() {
use sha2::Digest;
async fn exact_v4_security_contract_replays_its_persisted_security_classification() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_v4_compatibility"),
test_storage_root("openapi_import_v4_security_compatibility"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let upload = OpenApiUpload {
bytes: br#"{
"openapi":"3.0.3",
"info":{"title":"Historical security","version":"1"},
"servers":[{"url":"https://api.example.test"}],
"components":{"securitySchemes":{"basic":{"type":"http","scheme":"basic"}}},
"security":[{"basic":[]}],
"paths":{
"/secure":{"get":{"operationId":"secure","responses":{"200":{"description":"ok"}}}},
"/public":{"get":{"operationId":"public","security":[],"responses":{"200":{"description":"ok"}}}}
}
}"#
.to_vec(),
mime_type: "application/json".to_owned(),
locale: OpenApiUploadLocale::En,
};
let preview = service
.preview_openapi_import(&workspace_id, openapi_upload())
.preview_openapi_import(&workspace_id, upload)
.await
.unwrap();
let job_id: crank_registry::ImportJobId = preview.job_id.as_str().into();
let mut job = registry
let 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())
// Keep the genuine baseline-v4 normalization/projection, preview and digest intact.
// Only bind its source envelope to this test's newly registered immutable source blob.
let mut payload: serde_json::Value =
serde_json::from_str(BASELINE_V4_SECURITY_PREVIEW_PAYLOAD).unwrap();
assert_eq!(
payload.pointer("/source/digest"),
job.preview_payload.pointer("/source/digest"),
"baseline fixture must refer to the exact uploaded source bytes",
);
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())
payload["source"]["source_id"] = job.preview_payload["source"]["source_id"].clone();
assert_eq!(
payload["normalization"]["normalizer_version"],
"normalized-ir-v4"
);
assert_eq!(payload["normalization"]["projection_version"], "preview-v4");
sqlx::query("update import_jobs set preview_payload = $1::jsonb where id = $2")
.bind(serde_json::to_string(&payload).unwrap())
.bind(job_id.as_str())
.execute(registry.pool())
.await
@@ -739,19 +789,25 @@ async fn exact_v4_contract_replays_legacy_preview_without_v5_reparse_or_dependen
&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()),
selected_operation_keys: vec!["GET /secure".to_owned()],
server_url: Some("https://api.example.test".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);
.await;
let error =
result.expect_err("historical v4 security blocker must refuse the selected candidate");
assert!(
format!("{error:?}").contains("invalid_document"),
"v4 contract was rejected before candidate validation: {error:?}"
);
assert!(
service
.list_operations(&workspace_id)
.await
.unwrap()
.is_empty()
);
}
mod security_bundle;
@@ -0,0 +1,413 @@
use super::*;
// --- Referenced security credentials RED regressions ---
// These tests prove that credential literals hidden behind local/external $ref
// security scheme + parameter splits are rejected before artifact persistence.
#[tokio::test]
#[serial]
async fn referenced_security_credentials_local_scheme_ref_with_parameter_default_canary_rejected() {
let canary = b"local-ref-canary-001-Zx9qK";
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_local_scheme_ref_canary");
let service = test_service(
registry.clone(),
storage_root.clone(),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let upload = OpenApiUpload {
bytes: r##"{
"openapi":"3.1.0",
"info":{"title":"Local ref scheme","version":"1"},
"servers":[{"url":"https://api.example.test"}],
"x-scheme":{"type":"apiKey","in":"header","name":"X-Custom"},
"x-key":{"type":"string","default":"local-ref-canary-001-Zx9qK"},
"components":{
"securitySchemes":{"custom":{"$ref":"#/x-scheme"}}
},
"security":[{"custom":[]}],
"paths":{
"/test":{"get":{
"operationId":"test", "security":[{"custom":[]}],
"parameters":[{"name":"X-Custom","in":"header","schema":{"$ref":"#/x-key"}}],
"responses":{"200":{"description":"ok"}}
}}
}
}"##
.as_bytes()
.to_vec(),
mime_type: "application/json".to_owned(),
locale: OpenApiUploadLocale::En,
};
let result = service.preview_openapi_import(&workspace_id, upload).await;
// Canary must NOT appear in the API response (error or preview).
let response_repr = match &result {
Ok(preview) => serde_json::to_string(preview).unwrap(),
Err(err) => format!("{err:?}"),
};
assert!(
response_repr.contains("invalid_document"),
"unsafe local ref bundle was not rejected: {response_repr}"
);
assert!(
!response_repr.contains(std::str::from_utf8(canary).unwrap()),
"credential canary leaked into API response"
);
// Canary must NOT be persisted to artifact storage.
assert!(
!storage_contains_literal(&storage_root, canary),
"raw credential literal from referenced local scheme ref persisted to storage"
);
assert_rejected_bundle_unpersisted(&registry, &workspace_id, &storage_root).await;
}
#[tokio::test]
#[serial]
async fn encoded_access_token_fragment_is_rejected_before_persistence() {
let canary = b"fragment-ingress-canary-004-Qm7vN";
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_encoded_fragment_canary");
let service = test_service(
registry.clone(),
storage_root.clone(),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let upload = OpenApiUpload {
bytes: br##"{
"openapi":"3.1.0",
"info":{"title":"Encoded fragment credential","version":"1"},
"servers":[{"url":"https://api.example.test/v1#%61%63%63%65%73%73%5F%74%6F%6B%65%6E=fragment-ingress-canary-004-Qm7vN"}],
"paths":{"/health":{"get":{"responses":{"200":{"description":"ok"}}}}}
}"##
.to_vec(),
mime_type: "application/json".to_owned(),
locale: OpenApiUploadLocale::En,
};
let error = service
.preview_openapi_import(&workspace_id, upload)
.await
.expect_err("encoded access_token fragment must be rejected at ingress");
let rendered_error = format!("{error:?}");
assert!(rendered_error.contains("invalid_document"));
assert!(rendered_error.len() <= 512, "error must remain bounded");
assert!(!rendered_error.contains("fragment-ingress-canary-004-Qm7vN"));
assert!(!rendered_error.contains("%61%63%63%65%73%73%5F%74%6F%6B%65%6E"));
assert_rejected_bundle_unpersisted(&registry, &workspace_id, &storage_root).await;
assert!(!storage_contains_literal(&storage_root, canary));
}
#[tokio::test]
#[serial]
async fn referenced_security_credentials_external_scheme_ref_local_parameter_default_canary_rejected()
{
let canary = b"split-ext-canary-002-Yw8pJ";
// External document defines the apiKey security scheme with header X-Custom.
let external_doc = r#"{"x-scheme":{"type":"apiKey","in":"header","name":"X-Custom"}}"#;
let fetched = Arc::new(AtomicUsize::new(0));
let fetch_count = Arc::clone(&fetched);
let app = Router::new().route(
"/scheme.yaml",
get(move || {
let fc = Arc::clone(&fetch_count);
async move {
fc.fetch_add(1, Ordering::SeqCst);
external_doc.to_owned()
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_ext_scheme_ref_canary");
let service = test_service_with_external_references(
registry.clone(),
storage_root.clone(),
vec![format!("{origin}/")],
);
let workspace_id = WorkspaceId::new("ws_default");
// Primary references the external scheme; contains a local parameter
// with name X-Custom and schema.default = canary.
let upload = OpenApiUpload {
bytes: format!(
r#"{{
"openapi":"3.1.0",
"info":{{"title":"Ext scheme ref","version":"1"}},
"servers":[{{"url":"https://api.example.test"}}],
"components":{{
"securitySchemes":{{"custom":{{"$ref":"{origin}/scheme.yaml#/x-scheme"}}}}
}},
"security":[{{"custom":[]}}],
"paths":{{
"/test":{{"get":{{
"operationId":"test", "security":[{{"custom":[]}}],
"parameters":[{{"name":"X-Custom","in":"header","schema":{{"type":"string","default":"{canary}"}}}}],
"responses":{{"200":{{"description":"ok"}}}}
}}}}
}}
}}"#,
origin = origin,
canary = std::str::from_utf8(canary).unwrap(),
)
.into_bytes(),
mime_type: "application/json".to_owned(),
locale: OpenApiUploadLocale::En,
};
let result = service.preview_openapi_import(&workspace_id, upload).await;
server.abort();
assert_eq!(
fetched.load(Ordering::SeqCst),
1,
"external scheme must be fetched before the split is checked"
);
let response_repr = match &result {
Ok(preview) => serde_json::to_string(preview).unwrap(),
Err(err) => format!("{err:?}"),
};
assert!(
response_repr.contains("invalid_document"),
"unsafe external scheme bundle was not rejected: {response_repr}"
);
assert!(
!response_repr.contains(std::str::from_utf8(canary).unwrap()),
"credential canary leaked into API response"
);
assert!(
!storage_contains_literal(&storage_root, canary),
"raw credential literal from split external scheme ref persisted to storage"
);
assert_rejected_bundle_unpersisted(&registry, &workspace_id, &storage_root).await;
}
#[tokio::test]
#[serial]
async fn referenced_security_credentials_local_scheme_external_parameter_default_canary_rejected() {
let canary = b"split-local-canary-003-Xv7oI";
// External document defines a parameter schema whose default is the canary.
let external_doc = format!(
r#"{{"x-key":{{"type":"string","default":"{canary}"}}}}"#,
canary = std::str::from_utf8(canary).unwrap(),
);
let fetched = Arc::new(AtomicUsize::new(0));
let fetch_count = Arc::clone(&fetched);
let app = Router::new().route(
"/key.yaml",
get(move || {
let fc = Arc::clone(&fetch_count);
async move {
fc.fetch_add(1, Ordering::SeqCst);
external_doc.clone()
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_local_scheme_ext_param_canary");
let service = test_service_with_external_references(
registry.clone(),
storage_root.clone(),
vec![format!("{origin}/")],
);
let workspace_id = WorkspaceId::new("ws_default");
// Primary declares the scheme directly (no $ref); parameter schema is
// an external $ref whose resolved default would be the canary.
let upload = OpenApiUpload {
bytes: format!(
r#"{{
"openapi":"3.1.0",
"info":{{"title":"Local scheme ext param","version":"1"}},
"servers":[{{"url":"https://api.example.test"}}],
"components":{{
"securitySchemes":{{"custom":{{"type":"apiKey","in":"header","name":"X-Custom"}}}}
}},
"security":[{{"custom":[]}}],
"paths":{{
"/test":{{"get":{{
"operationId":"test", "security":[{{"custom":[]}}],
"parameters":[{{"name":"X-Custom","in":"header","schema":{{"$ref":"{origin}/key.yaml#/x-key"}}}}],
"responses":{{"200":{{"description":"ok"}}}}
}}}}
}}
}}"#,
origin = origin,
)
.into_bytes(),
mime_type: "application/json".to_owned(),
locale: OpenApiUploadLocale::En,
};
let result = service.preview_openapi_import(&workspace_id, upload).await;
server.abort();
assert_eq!(
fetched.load(Ordering::SeqCst),
1,
"external parameter must be fetched before the split is checked"
);
let response_repr = match &result {
Ok(preview) => serde_json::to_string(preview).unwrap(),
Err(err) => format!("{err:?}"),
};
assert!(
response_repr.contains("invalid_document"),
"unsafe external parameter bundle was not rejected: {response_repr}"
);
assert!(
!response_repr.contains(std::str::from_utf8(canary).unwrap()),
"credential canary leaked into API response"
);
assert!(
!storage_contains_literal(&storage_root, canary),
"raw credential literal from external referenced parameter persisted to storage"
);
assert_rejected_bundle_unpersisted(&registry, &workspace_id, &storage_root).await;
}
#[tokio::test]
#[serial]
async fn safe_external_security_scheme_and_parameter_are_preserved() {
let external_doc = r#"{"x-scheme":{"type":"apiKey","in":"header","name":"X-Custom"}}"#;
let fetched = Arc::new(AtomicUsize::new(0));
let fetch_count = Arc::clone(&fetched);
let app = Router::new().route(
"/scheme.yaml",
get(move || {
let count = Arc::clone(&fetch_count);
async move {
count.fetch_add(1, Ordering::SeqCst);
external_doc
}
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_safe_external_security_ref");
let service = test_service_with_external_references(
registry.clone(),
storage_root,
vec![format!("{origin}/")],
);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(
&workspace_id,
OpenApiUpload {
bytes: format!(
r#"openapi: 3.1.0
info: {{ title: Safe external scheme, version: '1' }}
servers: [{{ url: https://api.example.test }}]
components:
securitySchemes:
custom: {{ $ref: '{origin}/scheme.yaml#/x-scheme' }}
security: [{{ custom: [] }}]
paths:
/test:
get:
operationId: safeExternalSecurity
security: [{{ custom: [] }}]
parameters:
- name: X-Custom
in: header
schema: {{ type: string }}
- name: locale
in: query
schema: {{ type: string, default: en }}
responses:
'200': {{ description: ok }}
"#
)
.into_bytes(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
},
)
.await
.expect("safe referenced schemes and parameters remain importable");
server.abort();
assert_eq!(fetched.load(Ordering::SeqCst), 1);
let operation = preview
.preview
.groups
.iter()
.flat_map(|group| &group.operations)
.find(|operation| operation.key == "GET /test")
.expect("operation preview is preserved");
assert!(matches!(
&operation.security_schemes["custom"].kind,
crank_import::rest::NormalizedSecuritySchemeKind::ApiKey {
parameter_name,
location: crank_import::rest::SecurityParameterLocation::Header,
..
} if parameter_name == "X-Custom"
));
let input_schema = serde_json::to_value(&operation.draft.input_schema).unwrap();
assert_eq!(
input_schema.pointer("/fields/locale/default_value"),
Some(&serde_json::json!("en")),
"benign locale default must remain visible in the preview"
);
let job = registry
.get_import_job(&workspace_id, &preview.job_id.as_str().into())
.await
.unwrap()
.unwrap();
assert_eq!(
job.preview_payload["dependency_snapshots"]
.as_array()
.unwrap()
.len(),
1
);
}
async fn assert_rejected_bundle_unpersisted(
registry: &crank_registry::PostgresRegistry,
workspace_id: &WorkspaceId,
storage_root: &std::path::Path,
) {
let sources: i64 =
sqlx::query_scalar("select count(*) from artifact_sources where workspace_id = $1")
.bind(workspace_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap();
let jobs: i64 = sqlx::query_scalar("select count(*) from import_jobs where workspace_id = $1")
.bind(workspace_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap();
assert_eq!(sources, 0, "rejected bundle registered a source");
assert_eq!(jobs, 0, "rejected bundle created an import job");
assert!(
!storage_has_files(storage_root),
"rejected bundle stored artifact bytes"
);
}
fn storage_has_files(path: &std::path::Path) -> bool {
std::fs::read_dir(path).unwrap().any(|entry| {
let path = entry.unwrap().path();
if path.is_dir() {
storage_has_files(&path)
} else {
true
}
})
}
@@ -26,10 +26,17 @@ async fn http_contract_preview_apply_and_replay_preserve_json_multipart_schemas_
.unwrap()
.preview_payload["preview"]
.clone();
assert_eq!(
persisted_preview_before_apply,
serde_json::to_value(&preview.preview).unwrap()
);
// Readiness is workspace-aware response metadata, not part of the immutable
// projection persisted with the source job.
let mut response_projection = serde_json::to_value(&preview.preview).unwrap();
for group in response_projection["groups"].as_array_mut().unwrap() {
for operation in group["operations"].as_array_mut().unwrap() {
assert_eq!(operation["status"], "actionable");
operation.as_object_mut().unwrap().remove("status");
}
}
assert!(preview.preview.conflicts.is_empty());
assert_eq!(persisted_preview_before_apply, response_projection);
let operations = preview
.preview
@@ -108,7 +115,6 @@ async fn http_contract_preview_apply_and_replay_preserve_json_multipart_schemas_
let payload = OpenApiImportCreatePayload {
selected_operation_keys: vec![candidate.key.clone()],
auth_mappings: vec![],
server_url: None,
conflict_mode: "skip".to_owned(),
};
@@ -200,7 +206,6 @@ async fn xml_and_unsupported_media_block_apply_without_registry_mutation() {
&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(),
},
@@ -0,0 +1,991 @@
use serde_json::{Value, json};
use serial_test::serial;
use std::{sync::Arc, time::Duration};
use async_trait::async_trait;
use crank_community_mcp::session::InMemorySessionStore;
use crank_core::{
MachineAccessMode, MachineCredentialVerifier, MachineCredentialVerifierError,
OperationSecurityLevel, PlatformApiKeyScope, VerifiedMachineCredential,
};
struct CorpusMcpCredentialVerifier;
#[async_trait]
impl MachineCredentialVerifier for CorpusMcpCredentialVerifier {
async fn verify_bearer_token(
&self,
_workspace_slug: &str,
_agent_slug: &str,
token: &str,
) -> Result<Option<VerifiedMachineCredential>, MachineCredentialVerifierError> {
Ok(
(token == "corpus-test-token").then_some(VerifiedMachineCredential {
machine_access_mode: MachineAccessMode::StaticAgentKey,
max_security_level: OperationSecurityLevel::Standard,
scopes: vec![PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
platform_api_key_id: None,
}),
)
}
}
use super::super::common::*;
const OPENAPI_SINGLE: &str = r#"
openapi: 3.0.3
info: { title: Apply test }
servers: [{ url: https://api.example.test }]
paths:
/alpha:
get:
operationId: alpha
responses: { '200': { description: ok } }
"#;
const OPENAPI_TWO_OPERATIONS: &str = r#"
openapi: 3.0.3
info: { title: Partial Apply test }
servers: [{ url: https://api.example.test }]
paths:
/alpha:
get:
operationId: alpha
responses: { '200': { description: ok } }
/beta:
get:
operationId: beta
responses: { '200': { description: ok } }
"#;
const OPENAPI_TWO_APIKEY_OPERATIONS: &str = r#"
openapi: 3.0.3
info: { title: Authenticated Apply test, version: '1' }
servers: [{ url: https://api.example.test }]
components: { securitySchemes: { apiKey: { type: apiKey, in: header, name: X-Api-Key } } }
security: [{ apiKey: [] }]
paths:
/alpha: { get: { operationId: alpha, responses: { '200': { description: ok } } } }
/beta: { get: { operationId: beta, responses: { '200': { description: ok } } } }
"#;
const OPENAPI_SINGLE_APIKEY_OPERATION: &str = r#"
openapi: 3.0.3
info: { title: Authenticated Apply test, version: '1' }
servers: [{ url: https://api.example.test }]
components: { securitySchemes: { apiKey: { type: apiKey, in: header, name: X-Api-Key } } }
paths:
/alpha: { get: { operationId: alpha, security: [{ apiKey: [] }], responses: { '200': { description: ok } } } }
"#;
const OPENAPI_WITH_BLOCKER: &str = r#"
openapi: 3.0.3
info: { title: Blocked full Apply test }
servers: [{ url: https://api.example.test }]
paths:
/actionable:
get:
operationId: actionable
responses: { '200': { description: ok } }
/blocked:
post:
operationId: blocked
requestBody:
required: true
content:
application/xml:
schema: { type: string }
responses: { '200': { description: ok } }
"#;
struct CreatedPlan {
reference: String,
digest: String,
body: Value,
preview: Value,
}
async fn create_plan(
client: &reqwest::Client,
base_url: impl AsRef<str>,
document: &str,
plan_payload: Value,
) -> CreatedPlan {
let base_url = base_url.as_ref();
let upload = reqwest::multipart::Part::bytes(document.as_bytes().to_vec())
.file_name("import.yaml")
.mime_str("application/yaml")
.unwrap();
let preview_response = client
.post(format!("{base_url}/imports/openapi/preview"))
.multipart(reqwest::multipart::Form::new().part("file", upload))
.send()
.await
.expect("OpenAPI preview request should reach the Admin API");
assert_eq!(
preview_response.status(),
reqwest::StatusCode::OK,
"preview failed: {}",
preview_response.text().await.unwrap_or_default()
);
let preview: Value = preview_response.json().await.unwrap();
let job_id = preview["job_id"]
.as_str()
.expect("preview response must include the persisted job ID");
let plan_response = client
.post(format!("{base_url}/imports/openapi/{job_id}/plans"))
.json(&plan_payload)
.send()
.await
.expect("ImportPlan request should reach the Admin API");
let status = plan_response.status();
let body: Value = plan_response.json().await.unwrap_or(Value::Null);
assert_eq!(
status,
reqwest::StatusCode::OK,
"plan creation failed: {body}"
);
let reference = body["plan_reference"]
.as_str()
.expect("CreatePlan must return its server-issued reference")
.to_owned();
let digest = body["plan_digest"]
.as_str()
.expect("CreatePlan must return its server-derived digest")
.to_owned();
assert!(reference.starts_with("plan_"));
assert_eq!(digest.len(), 64);
assert!(digest.bytes().all(|byte| byte.is_ascii_hexdigit()));
CreatedPlan {
reference,
digest,
body,
preview,
}
}
async fn apply_plan(
client: &reqwest::Client,
base_url: impl AsRef<str>,
plan: &CreatedPlan,
idempotency_key: &str,
) -> (reqwest::StatusCode, Value) {
let base_url = base_url.as_ref();
let response = client
.post(format!(
"{base_url}/imports/openapi/{}/apply",
plan.reference
))
.json(&json!({
"plan_digest": plan.digest,
"idempotency_key": idempotency_key
}))
.send()
.await
.expect("Apply request should reach the Admin API");
let status = response.status();
let body = response.json::<Value>().await.unwrap_or(Value::Null);
(status, body)
}
async fn operation_list(client: &reqwest::Client, base_url: impl AsRef<str>) -> Value {
let base_url = base_url.as_ref();
let response = client
.get(format!("{base_url}/operations"))
.send()
.await
.expect("operation list request should reach the Admin API");
assert_eq!(response.status(), reqwest::StatusCode::OK);
response.json().await.unwrap()
}
fn full_plan() -> Value {
json!({ "selection_mode": "full", "selected_operation_keys": [] })
}
fn report_has_outcome_status(report: &Value, expected: &str) -> bool {
report["outcomes"].as_array().is_some_and(|outcomes| {
outcomes
.iter()
.any(|outcome| outcome["status"] == expected || outcome["outcome"] == expected)
})
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn apply_creates_one_draft_from_a_server_created_plan() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry,
test_storage_root("import_plan_apply_new_draft"),
))
.await;
let client = authorized_client(&base_url).await;
let plan = create_plan(&client, &base_url, OPENAPI_SINGLE, full_plan()).await;
assert_eq!(plan.body["counts"]["actionable"], 1);
let (status, report) = apply_plan(&client, &base_url, &plan, "apply-new-draft").await;
assert_eq!(status, reqwest::StatusCode::OK, "Apply failed: {report}");
assert_eq!(report["plan_digest"], plan.digest);
assert_eq!(report["outcomes"].as_array().unwrap().len(), 1);
assert!(report_has_outcome_status(&report, "created"));
assert!(report["outcomes"].to_string().contains("GET /alpha"));
let operations = operation_list(&client, &base_url).await;
assert_eq!(operations["total"], 1);
assert_eq!(operations["items"][0]["status"], "draft");
assert_eq!(operations["items"][0]["current_draft_version"], 1);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn full_apply_with_a_blocked_candidate_is_atomic_and_reports_the_failure() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry,
test_storage_root("import_plan_apply_full_blocked"),
))
.await;
let client = authorized_client(&base_url).await;
let plan = create_plan(&client, &base_url, OPENAPI_WITH_BLOCKER, full_plan()).await;
assert_eq!(plan.body["counts"]["blocked"], 1);
let before = operation_list(&client, &base_url).await;
let (status, report) = apply_plan(&client, &base_url, &plan, "apply-full-blocked").await;
assert_eq!(
status,
reqwest::StatusCode::CONFLICT,
"unexpected report: {report}"
);
assert_eq!(operation_list(&client, &base_url).await, before);
assert!(
report["outcomes"].is_array(),
"blocked Apply must return outcomes: {report}"
);
assert!(report_has_outcome_status(&report, "rejected"));
assert!(report["outcomes"].to_string().contains("POST /blocked"));
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn explicit_partial_plan_applies_only_selected_candidates_and_explains_exclusions() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry,
test_storage_root("import_plan_apply_partial"),
))
.await;
let client = authorized_client(&base_url).await;
let plan = create_plan(
&client,
&base_url,
OPENAPI_TWO_OPERATIONS,
json!({
"selection_mode": "partial",
"selected_operation_keys": ["GET /alpha"]
}),
)
.await;
assert_eq!(plan.body["counts"]["selected"], 1);
assert_eq!(plan.body["counts"]["excluded"], 1);
let (status, report) = apply_plan(&client, &base_url, &plan, "apply-partial").await;
assert_eq!(status, reqwest::StatusCode::OK, "Apply failed: {report}");
assert!(report["outcomes"].is_array());
assert!(report_has_outcome_status(&report, "created"));
let report_text = report.to_string();
assert!(report_text.contains("GET /alpha"));
assert!(report_text.contains("GET /beta"));
assert!(report_text.contains("excluded"));
let operations = operation_list(&client, &base_url).await;
assert_eq!(operations["total"], 1);
assert_eq!(operations["items"][0]["name"], "alpha");
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn same_key_and_digest_replay_report_without_extra_draft_and_changed_digest_conflicts() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry,
test_storage_root("import_plan_apply_idempotency"),
))
.await;
let client = authorized_client(&base_url).await;
let plan = create_plan(&client, &base_url, OPENAPI_SINGLE, full_plan()).await;
let (first_status, first_report) =
apply_plan(&client, &base_url, &plan, "stable-apply-key").await;
assert_eq!(
first_status,
reqwest::StatusCode::OK,
"Apply failed: {first_report}"
);
let operations_after_first = operation_list(&client, &base_url).await;
let (replay_status, replay_report) =
apply_plan(&client, &base_url, &plan, "stable-apply-key").await;
assert_eq!(replay_status, reqwest::StatusCode::OK);
assert_eq!(replay_report, first_report);
assert_eq!(
operation_list(&client, &base_url).await,
operations_after_first
);
let changed = CreatedPlan {
reference: plan.reference.clone(),
digest: "0".repeat(64),
body: plan.body.clone(),
preview: plan.preview.clone(),
};
let (changed_status, _) = apply_plan(&client, &base_url, &changed, "stable-apply-key").await;
assert_eq!(changed_status, reqwest::StatusCode::CONFLICT);
assert_eq!(
operation_list(&client, &base_url).await,
operations_after_first
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn concurrent_same_key_apply_converges_on_one_persisted_report() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry,
test_storage_root("import_plan_apply_concurrent_replay"),
))
.await;
let client = authorized_client(&base_url).await;
let plan = create_plan(&client, &base_url, OPENAPI_SINGLE, full_plan()).await;
let (left, right) = tokio::join!(
apply_plan(&client, &base_url, &plan, "concurrent-apply-key"),
apply_plan(&client, &base_url, &plan, "concurrent-apply-key"),
);
assert_eq!(left.0, reqwest::StatusCode::OK, "left: {}", left.1);
assert_eq!(right.0, reqwest::StatusCode::OK, "right: {}", right.1);
assert_eq!(left.1, right.1);
assert_eq!(operation_list(&client, &base_url).await["total"], 1);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn apply_rejects_client_candidate_fields_and_malformed_digest() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry,
test_storage_root("import_plan_apply_input_validation"),
))
.await;
let client = authorized_client(&base_url).await;
let plan = create_plan(&client, &base_url, OPENAPI_SINGLE, full_plan()).await;
let url = format!("{base_url}/imports/openapi/{}/apply", plan.reference);
let extra_fields = client
.post(&url)
.json(&json!({
"plan_digest": plan.digest,
"idempotency_key": "validation-key",
"operations": [{ "operation_id": "attacker-chosen" }]
}))
.send()
.await
.unwrap();
assert_eq!(
extra_fields.status(),
reqwest::StatusCode::UNPROCESSABLE_ENTITY
);
let malformed_digest = client
.post(url)
.json(&json!({
"plan_digest": "not-a-digest",
"idempotency_key": "validation-key"
}))
.send()
.await
.unwrap();
assert_eq!(malformed_digest.status(), reqwest::StatusCode::BAD_REQUEST);
assert_eq!(operation_list(&client, &base_url).await["total"], 0);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn exact_skip_and_rename_decisions_affect_only_the_confirmed_operations() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry,
test_storage_root("import_plan_apply_skip_rename"),
))
.await;
let client = authorized_client(&base_url).await;
let initial = create_plan(&client, &base_url, OPENAPI_SINGLE, full_plan()).await;
let (initial_status, initial_report) =
apply_plan(&client, &base_url, &initial, "skip-rename-seed").await;
assert_eq!(initial_status, reqwest::StatusCode::OK, "{initial_report}");
let before_skip = operation_list(&client, &base_url).await;
let operation_id = before_skip["items"][0]["id"]
.as_str()
.expect("operation list includes the workspace operation ID");
let skip = create_plan(
&client,
&base_url,
OPENAPI_SINGLE,
json!({
"selection_mode": "full",
"selected_operation_keys": [],
"decisions": [{
"operation_key": "GET /alpha",
"action": "skip",
"target_operation_id": operation_id
}]
}),
)
.await;
let (skip_status, skip_report) =
apply_plan(&client, &base_url, &skip, "skip-exact-target").await;
assert_eq!(skip_status, reqwest::StatusCode::OK, "{skip_report}");
assert!(report_has_outcome_status(&skip_report, "skipped"));
assert_eq!(skip_report["outcomes"][0]["operation_id"], operation_id);
assert_eq!(operation_list(&client, &base_url).await, before_skip);
let rename = create_plan(
&client,
&base_url,
OPENAPI_SINGLE,
json!({
"selection_mode": "full",
"selected_operation_keys": [],
"decisions": [{
"operation_key": "GET /alpha",
"action": "rename",
"confirmed_name": "alpha_imported"
}]
}),
)
.await;
let (rename_status, rename_report) =
apply_plan(&client, &base_url, &rename, "rename-confirmed-name").await;
assert_eq!(rename_status, reqwest::StatusCode::OK, "{rename_report}");
assert!(report_has_outcome_status(&rename_report, "renamed"));
let after_rename = operation_list(&client, &base_url).await;
assert_eq!(after_rename["total"], 2);
assert!(
after_rename["items"]
.as_array()
.unwrap()
.iter()
.any(|item| { item["name"] == "alpha_imported" && item["status"] == "draft" })
);
assert!(
after_rename["items"]
.as_array()
.unwrap()
.iter()
.any(|item| { item["id"] == operation_id && item["name"] == "alpha" })
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn new_version_preserves_published_version_and_prior_version() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry,
test_storage_root("import_plan_apply_new_version_published"),
))
.await;
let client = authorized_client(&base_url).await;
let seed = create_plan(&client, &base_url, OPENAPI_SINGLE, full_plan()).await;
let (seed_status, seed_report) =
apply_plan(&client, &base_url, &seed, "new-version-seed").await;
assert_eq!(seed_status, reqwest::StatusCode::OK, "{seed_report}");
let seeded = operation_list(&client, &base_url).await;
let operation_id = seeded["items"][0]["id"].as_str().unwrap().to_owned();
let publish = client
.post(format!("{base_url}/operations/{operation_id}/publish"))
.header(
reqwest::header::IF_MATCH,
operation_etag(&client, &base_url, &operation_id).await,
)
.json(&json!({ "version": 1 }))
.send()
.await
.expect("publish request should reach the Admin API");
assert_eq!(publish.status(), reqwest::StatusCode::OK);
let published: Value = publish.json().await.unwrap();
assert_eq!(published["published_version"], 1);
let prior_version_before: Value = client
.get(format!("{base_url}/operations/{operation_id}/versions/1"))
.send()
.await
.unwrap()
.json()
.await
.unwrap();
let plan = create_plan(
&client,
&base_url,
OPENAPI_SINGLE,
json!({
"selection_mode": "full",
"selected_operation_keys": [],
"decisions": [{
"operation_key": "GET /alpha",
"action": "new_version",
"target_operation_id": operation_id
}]
}),
)
.await;
let (status, report) = apply_plan(&client, &base_url, &plan, "new-version-exact-target").await;
assert_eq!(status, reqwest::StatusCode::OK, "{report}");
assert!(report_has_outcome_status(&report, "versioned"));
assert_eq!(report["outcomes"][0]["operation_id"], operation_id);
assert_eq!(report["outcomes"][0]["version"], 2);
let after = operation_list(&client, &base_url).await;
assert_eq!(after["total"], 1);
assert_eq!(after["items"][0]["id"], operation_id);
assert_eq!(after["items"][0]["latest_published_version"], 1);
assert_eq!(after["items"][0]["current_draft_version"], 2);
let published_again: Value = client
.get(format!("{base_url}/operations/{operation_id}/versions/1"))
.send()
.await
.unwrap()
.json()
.await
.unwrap();
assert_eq!(published_again, prior_version_before);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn disabled_auth_secret_rejects_apply_without_leaking_credentials() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry.clone(),
test_storage_root("import_plan_apply_revoked_auth"),
))
.await;
let client = authorized_client(&base_url).await;
let secret_canary = "import-plan-auth-canary-must-not-leak";
let secret_response = client
.post(format!("{base_url}/secrets"))
.json(&json!({
"name": "import-plan-auth-token",
"kind": "token",
"value": { "token": secret_canary }
}))
.send()
.await
.unwrap();
assert_eq!(secret_response.status(), reqwest::StatusCode::OK);
let secret: Value = secret_response.json().await.unwrap();
let secret_id = secret["id"].as_str().unwrap();
let profile_response = client
.post(format!("{base_url}/auth-profiles"))
.json(&json!({
"name": "import-plan-auth-profile",
"kind": "api_key_header",
"config": {
"api_key_header": {
"header_name": "X-Api-Key",
"secret_id": secret_id
}
}
}))
.send()
.await
.unwrap();
assert_eq!(profile_response.status(), reqwest::StatusCode::OK);
let profile: Value = profile_response.json().await.unwrap();
let auth_profile_id = profile["id"].as_str().unwrap();
let redacted_plan = create_plan(
&client,
&base_url,
OPENAPI_TWO_APIKEY_OPERATIONS,
json!({
"selection_mode": "partial",
"selected_operation_keys": ["GET /beta"],
"decisions": [{
"operation_key": "GET /beta",
"action": "create",
"auth_profile_id": auth_profile_id
}]
}),
)
.await;
let (redacted_status, redacted_report) =
apply_plan(&client, &base_url, &redacted_plan, "redacted-auth-report").await;
assert_eq!(
redacted_status,
reqwest::StatusCode::OK,
"{redacted_report}"
);
assert!(redacted_report["source_digest"].is_string());
assert!(!redacted_report.to_string().contains(secret_canary));
assert!(!redacted_report.to_string().contains("ciphertext"));
let plan = create_plan(
&client,
&base_url,
OPENAPI_SINGLE_APIKEY_OPERATION,
json!({
"selection_mode": "full",
"selected_operation_keys": [],
"decisions": [{
"operation_key": "GET /alpha",
"action": "create",
"auth_profile_id": auth_profile_id
}]
}),
)
.await;
// A profile can remain active while its credential mapping changes.
// The confirmed plan must not silently adopt the new configuration.
sqlx::query(
"update auth_profiles
set config_json = jsonb_set(config_json, '{api_key_header,header_name}', '\"X-Changed-Key\"'),
updated_at = now()
where workspace_id = $1 and id = $2",
)
.bind("ws_default")
.bind(auth_profile_id)
.execute(registry.pool())
.await
.unwrap();
let (drift_status, drift_error) =
apply_plan(&client, &base_url, &plan, "changed-auth-config-apply").await;
assert_eq!(drift_status, reqwest::StatusCode::CONFLICT, "{drift_error}");
assert_eq!(
drift_error["error"]["context"]["error_code"],
"import_plan_auth_unavailable"
);
assert_eq!(operation_list(&client, &base_url).await["total"], 1);
let plan = create_plan(
&client,
&base_url,
&OPENAPI_SINGLE_APIKEY_OPERATION.replace("X-Api-Key", "X-Changed-Key"),
json!({
"selection_mode": "full",
"selected_operation_keys": [],
"decisions": [{
"operation_key": "GET /alpha",
"action": "create",
"auth_profile_id": auth_profile_id
}]
}),
)
.await;
// There is no profile revoke endpoint; disabling its backing credential
// models revocation between confirmation and apply.
sqlx::query(
"update secrets set status = 'disabled', updated_at = now() where workspace_id = $1 and id = $2",
)
.bind("ws_default")
.bind(secret_id)
.execute(registry.pool())
.await
.unwrap();
let (status, error) = apply_plan(&client, &base_url, &plan, "revoked-auth-apply").await;
assert_eq!(status, reqwest::StatusCode::CONFLICT, "{error}");
assert_eq!(
error["error"]["context"]["error_code"],
"import_plan_auth_unavailable"
);
let response_text = error.to_string();
assert!(!response_text.contains(secret_canary));
assert!(!response_text.contains("ciphertext"));
let after = operation_list(&client, &base_url).await;
assert_eq!(after["total"], 1);
assert_eq!(after["items"][0]["name"], "beta");
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn profiles_sharing_active_secret_are_selectable_and_both_block_after_disable() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry.clone(),
test_storage_root("import_plan_shared_auth_secret"),
))
.await;
let client = authorized_client(&base_url).await;
let secret_response = client
.post(format!("{base_url}/secrets"))
.json(&json!({
"name": "shared-import-auth-token",
"kind": "token",
"value": { "token": "shared-import-canary" }
}))
.send()
.await
.unwrap();
assert_eq!(secret_response.status(), reqwest::StatusCode::OK);
let secret: Value = secret_response.json().await.unwrap();
let secret_id = secret["id"].as_str().unwrap();
let make_profile = |name: &str| {
client
.post(format!("{base_url}/auth-profiles"))
.json(&json!({
"name": name,
"kind": "api_key_header",
"config": { "api_key_header": {
"header_name": "X-Api-Key",
"secret_id": secret_id
}}
}))
};
let first: Value = make_profile("shared-auth-a")
.send()
.await
.unwrap()
.json()
.await
.unwrap();
let second: Value = make_profile("shared-auth-b")
.send()
.await
.unwrap()
.json()
.await
.unwrap();
let document = r#"{
"openapi":"3.0.3",
"info":{"title":"Shared profile test","version":"1"},
"servers":[{"url":"https://api.example.test"}],
"components":{"securitySchemes":{"key":{"type":"apiKey","in":"header","name":"X-Api-Key"}}},
"paths":{
"/a":{"get":{"operationId":"sharedA","security":[{"key":[]}],"responses":{"200":{"description":"ok"}}}},
"/b":{"get":{"operationId":"sharedB","security":[{"key":[]}],"responses":{"200":{"description":"ok"}}}}
}
}"#;
let plan = create_plan(
&client,
&base_url,
document,
json!({
"selection_mode":"full",
"selected_operation_keys":[],
"decisions":[
{"operation_key":"GET /a","action":"create","auth_profile_id":first["id"]},
{"operation_key":"GET /b","action":"create","auth_profile_id":second["id"]}
]
}),
)
.await;
let (status, report) = apply_plan(&client, &base_url, &plan, "shared-secret-active").await;
assert_eq!(status, reqwest::StatusCode::OK, "{report}");
assert_eq!(operation_list(&client, &base_url).await["total"], 2);
let first_id = first["id"].as_str().unwrap();
let second_id = second["id"].as_str().unwrap();
let disabled_document = document
.replace("sharedA", "sharedAAfterDisable")
.replace("sharedB", "sharedBAfterDisable");
let mut disabled_plans = Vec::new();
for (key, profile_id) in [("GET /a", first_id), ("GET /b", second_id)] {
disabled_plans.push((
key,
create_plan(
&client,
&base_url,
&disabled_document,
json!({
"selection_mode":"partial",
"selected_operation_keys":[key],
"decisions":[{"operation_key":key,"action":"create","auth_profile_id":profile_id}]
}),
)
.await,
));
}
sqlx::query("update secrets set status = 'disabled', updated_at = now() where workspace_id = $1 and id = $2")
.bind("ws_default")
.bind(secret_id)
.execute(registry.pool())
.await
.unwrap();
for (key, plan) in disabled_plans {
let (status, error) = apply_plan(
&client,
&base_url,
&plan,
&format!("shared-secret-disabled-{key}"),
)
.await;
assert_eq!(status, reqwest::StatusCode::CONFLICT, "{error}");
assert_eq!(
error["error"]["context"]["error_code"],
"import_plan_auth_unavailable"
);
assert_eq!(operation_list(&client, &base_url).await["total"], 2);
}
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn ac_4_corpus_operation_completes_the_real_http_to_mcp_workflow() {
use axum::{Json, Router};
let registry = test_registry().await;
let (request_tx, mut request_rx) = tokio::sync::mpsc::unbounded_channel();
let upstream =
Router::new().fallback(move |method: axum::http::Method, uri: axum::http::Uri| {
let request_tx = request_tx.clone();
async move {
request_tx.send((method, uri)).unwrap();
Json(json!({"id":"corpus-0"}))
}
});
let upstream_base = spawn_admin_api(upstream).await;
let storage = test_storage_root("corpus_ac4");
let base_url = spawn_admin_api(build_test_app(registry.clone(), storage)).await;
let client = authorized_client(&base_url).await;
let fixture_path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../crates/crank-import/tests/corpus/representative-00.json");
let mut fixture: Value = serde_json::from_slice(&std::fs::read(fixture_path).unwrap()).unwrap();
let upstream_origin = upstream_base
.as_ref()
.split("/api/admin/workspaces/")
.next()
.unwrap();
fixture["servers"] = json!([{ "url": upstream_origin }]);
let document = serde_json::to_string(&fixture).unwrap();
let plan = create_plan(&client, &base_url, &document, full_plan()).await;
assert_eq!(plan.body["counts"]["actionable"], 1);
let (status, report) = apply_plan(&client, &base_url, &plan, "corpus-ac4-import").await;
assert_eq!(status, reqwest::StatusCode::OK, "Apply failed: {report}");
assert!(report_has_outcome_status(&report, "created"));
let operations = operation_list(&client, &base_url).await;
assert_eq!(operations["total"], 1);
assert_eq!(operations["items"][0]["status"], "draft");
let operation_id = operations["items"][0]["id"].as_str().unwrap().to_owned();
// The admin test run performs the persisted Draft validation and a real
// HTTP execution against the local fixture server before publication.
let test_run = client
.post(format!("{base_url}/operations/{operation_id}/test-runs"))
.json(&json!({"version":1,"input":{}}))
.send()
.await
.unwrap();
assert_eq!(test_run.status(), reqwest::StatusCode::OK);
let test_result: Value = test_run.json().await.unwrap();
assert_eq!(test_result["ok"], true, "Draft test failed: {test_result}");
let published = client
.post(format!("{base_url}/operations/{operation_id}/publish"))
.header(
reqwest::header::IF_MATCH,
operation_etag(&client, &base_url, &operation_id).await,
)
.json(&json!({"version":1}))
.send()
.await
.unwrap();
assert_eq!(published.status(), reqwest::StatusCode::OK);
let agent = client.post(format!("{base_url}/agents")).json(&json!({
"slug":"corpus-regression-agent","display_name":"Corpus Regression Agent",
"description":"Local corpus acceptance fixture","instructions":{},"tool_selection_policy":{}
})).send().await.unwrap().json::<Value>().await.unwrap();
let agent_id = agent["agent_id"].as_str().unwrap();
let bindings = client.post(format!("{base_url}/agents/{agent_id}/bindings"))
.header(reqwest::header::IF_MATCH, agent_etag(&client, &base_url, agent_id).await)
.json(&json!([{"operation_id":operation_id,"operation_version":1,"tool_name":"corpusOperation00","tool_title":"Synthetic operation 00","enabled":true}]))
.send().await.unwrap();
assert_eq!(bindings.status(), reqwest::StatusCode::OK);
let agent_publish = client
.post(format!("{base_url}/agents/{agent_id}/publish"))
.header(
reqwest::header::IF_MATCH,
agent_etag(&client, &base_url, agent_id).await,
)
.json(&json!({"version":1}))
.send()
.await
.unwrap();
assert_eq!(agent_publish.status(), reqwest::StatusCode::OK);
let mcp = crank_community_mcp::build_app(
registry,
Duration::ZERO,
None,
test_secret_crypto(),
crank_runtime::community_with_outbound_policy(
crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]),
)
.build(),
crank_runtime::RequestRateLimiter::new(
crank_runtime::RequestRateLimitConfig::new(100, 100).unwrap(),
),
Arc::new(crank_runtime::InMemoryCoordinationStateStore::default()),
Arc::new(InMemorySessionStore::default()),
Arc::new(CorpusMcpCredentialVerifier),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move {
axum::serve(listener, mcp).await.unwrap();
});
let mcp_base = format!("http://{address}");
let mcp_url = format!("{mcp_base}/v1/default/corpus-regression-agent");
let initialized = client.post(&mcp_url).bearer_auth("corpus-test-token")
.header("accept", "application/json, text/event-stream")
.json(&json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"corpus","version":"1"}}}))
.send().await.unwrap();
assert_eq!(initialized.status(), reqwest::StatusCode::OK);
let session = initialized
.headers()
.get("mcp-session-id")
.unwrap()
.to_str()
.unwrap()
.to_owned();
let notification = client
.post(&mcp_url)
.bearer_auth("corpus-test-token")
.header("accept", "application/json, text/event-stream")
.header("mcp-session-id", &session)
.header("mcp-protocol-version", "2025-11-25")
.json(&json!({"jsonrpc":"2.0","method":"notifications/initialized","params":{}}))
.send()
.await
.unwrap();
assert_eq!(notification.status(), reqwest::StatusCode::ACCEPTED);
let called = client.post(&mcp_url).bearer_auth("corpus-test-token")
.header("accept", "application/json, text/event-stream").header("mcp-session-id", session)
.header("mcp-protocol-version", "2025-11-25")
.json(&json!({"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"corpusOperation00","arguments":{}}}))
.send().await.unwrap();
assert_eq!(called.status(), reqwest::StatusCode::OK);
let call: Value = called.json().await.unwrap();
assert_eq!(call["result"]["isError"], false, "MCP call failed: {call}");
assert_eq!(call["result"]["structuredContent"]["id"], "corpus-0");
for stage in ["Draft test run", "MCP call"] {
let (method, uri) = request_rx
.try_recv()
.unwrap_or_else(|_| panic!("{stage} missed upstream"));
assert_eq!(method, axum::http::Method::GET, "{stage}");
assert_eq!(uri.path(), "/items/0", "{stage}");
}
}
mod corpus_hostile;
mod locale;
mod security_source;
mod support_matrix;
@@ -0,0 +1,292 @@
use super::*;
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn ac_5_hostile_corpus_cases_are_bounded_atomic_and_redacted() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(registry, test_storage_root("corpus_ac5"))).await;
let client = authorized_client(&base_url).await;
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../crates/crank-import/tests/corpus");
let hostile_xml = std::fs::read_to_string(root.join("hostile-xml.json")).unwrap();
let before = operation_list(&client, &base_url).await;
let started = std::time::Instant::now();
let plan = create_plan(&client, &base_url, &hostile_xml, full_plan()).await;
assert!(
started.elapsed() < Duration::from_secs(5),
"hostile document exceeded bounded test budget"
);
assert!(
plan.body["counts"]["blocked"].as_u64().unwrap_or(0) > 0,
"hostile XML must be a blocker: {}",
plan.body
);
let xml_candidate = &plan.preview["preview"]["groups"][0]["operations"][0];
assert_eq!(xml_candidate["key"], "GET /xml");
assert!(
xml_candidate["findings"]
.as_array()
.is_some_and(|findings| findings.iter().any(|finding| finding["code"]
== "unsupported_xml_response_media_type"
&& finding["severity"] == "error")),
"HTTP preview must expose the exact XML blocker: {}",
plan.preview
);
assert_eq!(
plan.body["candidates"][0]["reason"], "unsupported_xml_response_media_type",
"HTTP plan must retain the XML blocker: {}",
plan.body
);
let (status, report) = apply_plan(&client, &base_url, &plan, "corpus-ac5-hostile").await;
assert_eq!(
status,
reqwest::StatusCode::CONFLICT,
"blocker must reject atomically: {report}"
);
assert_eq!(operation_list(&client, &base_url).await, before);
// Credential-bearing sources are rejected before their original bytes
// can enter artifact storage, rather than producing a persisted plan.
for file in [
"hostile-secret.json",
"hostile-malformed.json",
"hostile-oversized.json",
] {
let source = std::fs::read(root.join(file)).unwrap();
let started = std::time::Instant::now();
let upload = reqwest::multipart::Part::bytes(source)
.file_name(file)
.mime_str("application/json")
.unwrap();
let response = client
.post(format!("{base_url}/imports/openapi/preview"))
.multipart(reqwest::multipart::Form::new().part("file", upload))
.send()
.await
.unwrap();
let status = response.status();
let body = response.text().await.unwrap_or_default();
assert!(
!status.is_success(),
"{file} unexpectedly passed preview: {body}"
);
assert!(
started.elapsed() < Duration::from_secs(5),
"{file} exceeded bounded upload/parse time"
);
assert!(
!body.contains("sk_test_corpus_secret_canary"),
"hostile error response leaked a secret canary"
);
assert_eq!(
operation_list(&client, &base_url).await,
before,
"{file} mutated the operation registry"
);
}
// Real HTTP preview+plan: a root security requirement combined with an
// explicit empty operation override must leave the public operation
// actionable and leave the inherited one unresolved without a profile.
let mixed_security: Value = serde_json::json!({
"openapi": "3.0.3",
"info": { "title": "Mixed security plan probe", "version": "1" },
"servers": [{ "url": "https://security.example.test" }],
"components": { "securitySchemes": { "probe": { "type": "http", "scheme": "basic" } } },
"security": [{ "probe": [] }],
"paths": {
"/public": { "get": { "security": [], "operationId": "securityPublic",
"responses": { "200": { "description": "ok" } } } },
"/secured": { "get": { "operationId": "securitySecured",
"responses": { "200": { "description": "ok" } } } }
}
});
let security_mixed = serde_json::to_string(&mixed_security).unwrap();
let security_plan = create_plan(&client, &base_url, &security_mixed, full_plan()).await;
assert_eq!(
security_plan.body["counts"]["selected"], 2,
"{}",
security_plan.body
);
assert_eq!(
security_plan.body["counts"]["actionable"], 1,
"{}",
security_plan.body
);
assert_eq!(
security_plan.body["counts"]["blocked"], 1,
"{}",
security_plan.body
);
let security_candidates = security_plan.body["candidates"].as_array().unwrap();
let by_key = |key: &str| {
security_candidates
.iter()
.find(|candidate| candidate["key"] == key)
.unwrap_or_else(|| panic!("candidate {key} missing: {}", security_plan.body))
};
let public = by_key("GET /public");
let secured = by_key("GET /secured");
assert_eq!(
public["state"].as_str(),
Some("actionable"),
"public candidate with empty security override must stay actionable: {}",
security_plan.body
);
assert!(
public["reason"].is_null(),
"public candidate must not carry a security blocker: {}",
security_plan.body
);
assert_eq!(
secured["state"].as_str(),
Some("blocked"),
"inherited security requirement must block the affected candidate: {}",
security_plan.body
);
assert_eq!(
secured["reason"].as_str(),
Some("auth_profile_required"),
"secured candidate must expose its unresolved binding: {}",
security_plan.body
);
assert_eq!(
operation_list(&client, &base_url).await,
before,
"security-scoped plan must not mutate the operation registry"
);
let (blocked_status, blocked_report) = apply_plan(
&client,
&base_url,
&security_plan,
"corpus-ac5-security-blocked",
)
.await;
assert_eq!(
blocked_status,
reqwest::StatusCode::CONFLICT,
"{blocked_report}"
);
assert_eq!(operation_list(&client, &base_url).await, before);
let public_plan = create_plan(
&client,
&base_url,
&security_mixed,
json!({
"selection_mode": "partial",
"selected_operation_keys": ["GET /public"]
}),
)
.await;
assert_eq!(public_plan.body["counts"]["actionable"], 1);
assert_eq!(public_plan.body["counts"]["blocked"], 0);
let (public_status, public_report) = apply_plan(
&client,
&base_url,
&public_plan,
"corpus-ac5-security-public",
)
.await;
assert_eq!(public_status, reqwest::StatusCode::OK, "{public_report}");
assert!(report_has_outcome_status(&public_report, "created"));
let after = operation_list(&client, &base_url).await;
assert_eq!(after["total"], 1, "{after}");
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn p0_api_malformed_local_security_is_atomic_across_openapi_versions() {
for (version, document) in [
(
"openapi-3.1",
serde_json::json!({
"openapi": "3.1.0",
"info": { "title": "Security API regression", "version": "1" },
"servers": [{ "url": "https://security.example.test" }],
"security": [{ "probe": [] }],
"paths": {
"/bad": { "get": { "security": "basic", "operationId": "badOp",
"responses": { "200": { "description": "ok" } } } },
"/public": { "get": { "security": [], "operationId": "publicOp",
"responses": { "200": { "description": "ok" } } } }
}
}),
),
(
"swagger-2.0",
serde_json::json!({
"swagger": "2.0",
"info": { "title": "Security API regression", "version": "1" },
"host": "security.example.test",
"schemes": ["https"],
"security": [{ "apiKey": [] }],
"paths": {
"/bad": { "get": { "security": "apikey", "operationId": "badOp",
"responses": { "200": { "description": "ok" } } } },
"/public": { "get": { "security": [], "operationId": "publicOp",
"responses": { "200": { "description": "ok" } } } }
}
}),
),
] {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry,
test_storage_root(&format!("security_api_{version}")),
))
.await;
let client = authorized_client(&base_url).await;
let source = serde_json::to_string(&document).unwrap();
let before = operation_list(&client, &base_url).await;
let plan = create_plan(&client, &base_url, &source, full_plan()).await;
assert_eq!(
plan.body["counts"]["actionable"], 1,
"{version}: {}",
plan.body
);
assert_eq!(
plan.body["counts"]["blocked"], 1,
"{version}: {}",
plan.body
);
let candidates = plan.body["candidates"].as_array().unwrap();
let bad = candidates
.iter()
.find(|item| item["key"] == "GET /bad")
.unwrap();
let public = candidates
.iter()
.find(|item| item["key"] == "GET /public")
.unwrap();
assert_eq!(bad["state"], "blocked", "{version}: {}", plan.body);
assert_eq!(bad["reason"], "invalid_security_requirements");
assert_eq!(public["state"], "actionable", "{version}: {}", plan.body);
assert!(public["reason"].is_null());
let (status, report) = apply_plan(&client, &base_url, &plan, "security-full").await;
assert_eq!(status, reqwest::StatusCode::CONFLICT, "{version}: {report}");
assert_eq!(operation_list(&client, &base_url).await, before);
let public_plan = create_plan(
&client,
&base_url,
&source,
json!({
"selection_mode": "partial",
"selected_operation_keys": ["GET /public"]
}),
)
.await;
assert_eq!(public_plan.body["counts"]["actionable"], 1);
assert_eq!(public_plan.body["counts"]["blocked"], 0);
let (status, report) =
apply_plan(&client, &base_url, &public_plan, "security-public").await;
assert_eq!(status, reqwest::StatusCode::OK, "{version}: {report}");
assert!(report_has_outcome_status(&report, "created"));
let after = operation_list(&client, &base_url).await;
assert_eq!(after["total"], 1, "{version}: {after}");
assert_eq!(after["items"][0]["status"], "draft");
}
}
@@ -0,0 +1,198 @@
use super::*;
use crank_core::WorkspaceId;
use crank_registry::{CreateImportPlanRequest, ImportPlanId};
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn plan_apply_localizes_repreview_guidance_by_accept_language() {
let registry = test_registry().await;
let base_url = spawn_admin_api(build_test_app(
registry,
test_storage_root("import_plan_apply_locale"),
))
.await;
let client = authorized_client(&base_url).await;
let plan = create_plan(&client, &base_url, OPENAPI_SINGLE, full_plan()).await;
let url = format!(
"{}/imports/openapi/{}/apply",
base_url.as_ref(),
plan.reference
);
let wrong_digest = "0".repeat(64);
// Russian session: Russian recovery guidance, identical machine code and
// recovery flags.
let ru = client
.post(&url)
.header("accept-language", "ru")
.json(&json!({ "plan_digest": wrong_digest, "idempotency_key": "locale-ru" }))
.send()
.await
.unwrap();
assert_eq!(ru.status(), reqwest::StatusCode::CONFLICT);
let ru_body: Value = ru.json().await.unwrap();
assert_eq!(
ru_body["error"]["context"]["error_code"],
"import_plan_digest_mismatch"
);
assert_eq!(
ru_body["error"]["context"]["repreview_required"],
json!(true)
);
assert_eq!(
ru_body["error"]["context"]["recovery"],
"repreview_required"
);
assert!(
ru_body["error"]["message"]
.as_str()
.unwrap_or_default()
.contains("создайте новый preview"),
"Russian session must receive Russian guidance: {ru_body:?}"
);
// No locale header keeps the English default behavior.
let en = client
.post(&url)
.json(&json!({ "plan_digest": wrong_digest, "idempotency_key": "locale-en" }))
.send()
.await
.unwrap();
assert_eq!(en.status(), reqwest::StatusCode::CONFLICT);
let en_body: Value = en.json().await.unwrap();
assert_eq!(
en_body["error"]["context"]["error_code"],
"import_plan_digest_mismatch"
);
assert!(
en_body["error"]["message"]
.as_str()
.unwrap_or_default()
.contains("create a fresh preview"),
"EN default must remain English: {en_body:?}"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn plan_apply_localizes_registry_name_conflict_by_accept_language() {
let registry = test_registry().await;
let storage_root = test_storage_root("import_plan_apply_locale_name_conflict");
let service = test_service(
registry.clone(),
storage_root.clone(),
test_auth_settings(),
test_secret_crypto(),
);
let base_url = spawn_admin_api(build_test_app(registry.clone(), storage_root)).await;
let client = authorized_client(&base_url).await;
let workspace_id = WorkspaceId::new("ws_default");
let created = create_plan(&client, &base_url, OPENAPI_SINGLE, full_plan()).await;
// Keep a historical v1-shaped plan to exercise the registry's typed
// name-conflict mapping directly. A v2 plan would stop earlier at the
// catalog-revision guard after the concurrent name claim below.
let original_id: ImportPlanId = created.reference.as_str().into();
let original = registry
.get_import_plan(&workspace_id, &original_id)
.await
.unwrap()
.expect("HTTP-created plan is persisted");
let legacy_id: ImportPlanId = "plan_locale_apply_name_conflict_v1".into();
let mut legacy_payload = original.payload.clone();
legacy_payload["schema_version"] = json!("import-plan-v1");
legacy_payload["plan_reference"] = json!(legacy_id.as_str());
let legacy_fields = legacy_payload.as_object_mut().unwrap();
for field in [
"catalog_revision",
"excluded_reasons",
"findings",
"support_matrix_version",
] {
legacy_fields.remove(field);
}
let legacy = registry
.create_import_plan(CreateImportPlanRequest {
id: &legacy_id,
workspace_id: &workspace_id,
job_id: &original.job_id,
payload: &legacy_payload,
created_at: &original.created_at,
expires_at: &original.expires_at,
})
.await
.unwrap();
let candidate_name = created.body["candidates"][0]["name"]
.as_str()
.expect("plan contains its candidate name");
service
.create_operation(
&workspace_id,
test_operation_payload("https://api.example.test", candidate_name),
)
.await
.unwrap();
let url = format!(
"{}/imports/openapi/{}/apply",
base_url.as_ref(),
legacy_id.as_str()
);
for (locale, idempotency_key, expected_message) in [
(
Some("ru"),
"name-conflict-ru",
"имя операции изменилось после создания плана",
),
(
None,
"name-conflict-en",
"an operation name changed after the plan was created",
),
] {
let mut request = client.post(&url).json(&json!({
"plan_digest": legacy.digest,
"idempotency_key": idempotency_key
}));
if let Some(locale) = locale {
request = request.header("accept-language", locale);
}
let response = request.send().await.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::CONFLICT);
let body: Value = response.json().await.unwrap();
assert_eq!(
body["error"]["context"]["error_code"],
"import_plan_name_conflict"
);
assert_eq!(
body["error"]["context"]["recovery"],
"confirm_skip_rename_or_new_version"
);
assert_eq!(body["error"]["message"], expected_message);
}
let matching_operations: i64 =
sqlx::query_scalar("select count(*) from operations where workspace_id = $1 and name = $2")
.bind(workspace_id.as_str())
.bind(candidate_name)
.fetch_one(registry.pool())
.await
.unwrap();
assert_eq!(
matching_operations, 1,
"Apply must not create another operation"
);
let applications: i64 = sqlx::query_scalar(
"select count(*) from import_plan_applications where workspace_id = $1 and plan_id = $2",
)
.bind(workspace_id.as_str())
.bind(legacy_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap();
assert_eq!(
applications, 0,
"a rejected Apply must not persist an application"
);
}
@@ -0,0 +1,184 @@
use super::*;
const SECURITY_SOURCE_A: &str = r#"
openapi: 3.0.3
info: { title: Security source A, version: '1' }
servers: [{ url: https://api.example.test }]
components:
securitySchemes:
apiKey:
type: apiKey
in: header
name: X-Api-Key
paths:
/secure:
get:
operationId: secureWithApiKey
security: [{ apiKey: [] }]
responses: { '200': { description: ok } }
"#;
const SECURITY_SOURCE_B: &str = r#"
openapi: 3.0.3
info: { title: Security source A, version: '1' }
servers: [{ url: https://api.example.test }]
components:
securitySchemes:
apiKey:
type: apiKey
in: header
name: X-Rotated-Key
paths:
/secure:
get:
operationId: secureWithApiKey
security: [{ apiKey: [] }]
responses: { '200': { description: ok } }
"#;
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn changed_security_scheme_invalidates_old_plan_before_draft_creation() {
let registry = test_registry().await;
let storage_root = test_storage_root("import_plan_security_source_change");
let base_url = spawn_admin_api(build_test_app(registry.clone(), storage_root)).await;
let client = authorized_client(&base_url).await;
let secret_response = client
.post(format!("{base_url}/secrets"))
.json(&json!({
"name": "security-source-test-secret",
"kind": "token",
"value": { "token": "source-change-canary" }
}))
.send()
.await
.unwrap();
assert_eq!(secret_response.status(), reqwest::StatusCode::OK);
let secret: Value = secret_response.json().await.unwrap();
let profile_response = client
.post(format!("{base_url}/auth-profiles"))
.json(&json!({
"name": "security-source-test-profile",
"kind": "api_key_header",
"config": { "api_key_header": {
"header_name": "X-Api-Key",
"secret_id": secret["id"]
}}
}))
.send()
.await
.unwrap();
assert_eq!(profile_response.status(), reqwest::StatusCode::OK);
let profile: Value = profile_response.json().await.unwrap();
let plan = create_plan(
&client,
&base_url,
SECURITY_SOURCE_A,
json!({
"selection_mode": "full",
"selected_operation_keys": [],
"decisions": [{
"operation_key": "GET /secure",
"action": "create",
"auth_profile_id": profile["id"]
}]
}),
)
.await;
assert_eq!(plan.body["candidates"][0]["auth_profile_id"], profile["id"]);
assert_eq!(plan.body["candidates"][0]["security_alternative_index"], 0);
let stored_plan = registry
.get_import_plan(
&crank_core::WorkspaceId::new("ws_default"),
&plan.reference.clone().into(),
)
.await
.unwrap()
.unwrap();
assert_eq!(
stored_plan.payload["candidates"][0]["operation"]["execution_config"]["auth_profile_ref"],
profile["id"],
"the old plan must persist its explicit profile binding"
);
assert_eq!(
stored_plan.payload["candidates"][0]["auth_requirement"]["parameter_name"],
"X-Api-Key"
);
// Register a second immutable source with only the security parameter
// changed. Its own upload/preview proves these are valid changed bytes,
// rather than corruption of the first content-addressed artifact.
let source_b_upload = reqwest::multipart::Part::bytes(SECURITY_SOURCE_B.as_bytes().to_vec())
.file_name("security-b.yaml")
.mime_str("application/yaml")
.unwrap();
let source_b_response = client
.post(format!("{base_url}/imports/openapi/preview"))
.multipart(reqwest::multipart::Form::new().part("file", source_b_upload))
.send()
.await
.unwrap();
assert_eq!(source_b_response.status(), reqwest::StatusCode::OK);
let source_b_preview: Value = source_b_response.json().await.unwrap();
assert_eq!(
source_b_preview["preview"]["groups"][0]["operations"][0]["security_schemes"]["apiKey"]["kind"]
["parameter_name"],
"X-Rotated-Key"
);
let workspace_id = crank_core::WorkspaceId::new("ws_default");
let original_job_id: crank_registry::ImportJobId =
plan.preview["job_id"].as_str().unwrap().into();
let changed_job_id: crank_registry::ImportJobId =
source_b_preview["job_id"].as_str().unwrap().into();
let original_job = registry
.get_import_job(&workspace_id, &original_job_id)
.await
.unwrap()
.unwrap();
let changed_job = registry
.get_import_job(&workspace_id, &changed_job_id)
.await
.unwrap()
.unwrap();
assert_ne!(
original_job.preview_payload["source"]["digest"],
changed_job.preview_payload["source"]["digest"],
"the changed scheme must come from a different verified source artifact"
);
assert_eq!(
stored_plan.payload["source"]["digest"], original_job.preview_payload["source"]["digest"],
"the plan must remain anchored to source A"
);
// Simulate the existing new-source/re-preview condition on the anchored
// pending job while retaining its original plan. The replacement is a
// separately registered and digest-verified B snapshot; Apply must
// compare the newly derived fingerprint with the old plan fingerprint.
sqlx::query("update import_jobs set preview_payload = $3 where id = $1 and workspace_id = $2")
.bind(original_job_id.as_str())
.bind(workspace_id.as_str())
.bind(&changed_job.preview_payload)
.execute(registry.pool())
.await
.unwrap();
let replaced_job = registry
.get_import_job(&workspace_id, &original_job_id)
.await
.unwrap()
.unwrap();
assert_eq!(
replaced_job.preview_payload["source"]["digest"],
changed_job.preview_payload["source"]["digest"]
);
let (status, error) = apply_plan(&client, &base_url, &plan, "security-source-changed").await;
assert_eq!(status, reqwest::StatusCode::CONFLICT, "{error}");
assert_eq!(
error["error"]["context"]["error_code"], "import_plan_fingerprint_stale",
"the old plan must require re-preview after source security changes"
);
assert_eq!(error["error"]["context"]["repreview_required"], true);
assert_eq!(operation_list(&client, &base_url).await["total"], 0);
}
@@ -0,0 +1,106 @@
use super::*;
use admin_api::error::ApiError;
use admin_api::service::{
OpenApiImportPlanApplyPayload, OpenApiImportPlanCreatePayload, OpenApiUpload,
OpenApiUploadLocale,
};
use crank_core::WorkspaceId;
use crank_registry::{CreateImportPlanRequest, ImportPlanId};
#[tokio::test]
#[serial]
async fn older_v2_support_matrix_rejects_new_apply_but_keeps_plan_auditable() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_old_support_matrix_apply"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(
&workspace_id,
OpenApiUpload {
bytes: OPENAPI_SINGLE.as_bytes().to_vec(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
},
)
.await
.unwrap();
let job_id = preview.job_id.as_str().into();
let created = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
OpenApiImportPlanCreatePayload {
selection_mode: "full".to_owned(),
selected_operation_keys: Vec::new(),
server_url: None,
decisions: Vec::new(),
},
)
.await
.unwrap();
let original_id: ImportPlanId = created.plan_reference.as_str().into();
let original = registry
.get_import_plan(&workspace_id, &original_id)
.await
.unwrap()
.unwrap();
// Model an immutable plan saved under an earlier support matrix. The
// registry derives its valid semantic digest from the changed payload.
let old_id: ImportPlanId = "plan_older_support_matrix".into();
let mut old_payload = original.payload.clone();
old_payload["plan_reference"] = json!(old_id.as_str());
old_payload["support_matrix_version"] = json!("1.0.2");
let older = registry
.create_import_plan(CreateImportPlanRequest {
id: &old_id,
workspace_id: &workspace_id,
job_id: &original.job_id,
payload: &old_payload,
created_at: &original.created_at,
expires_at: &original.expires_at,
})
.await
.unwrap();
assert_ne!(older.digest, original.digest);
let audit = service
.revalidate_openapi_import_plan(&workspace_id, &old_id)
.await
.unwrap();
assert_eq!(audit.revalidation_status, "stale");
assert!(audit.revalidation_required);
assert_eq!(audit.reason.as_deref(), Some("importer_version_changed"));
let error = service
.apply_openapi_import_plan(
&workspace_id,
&old_id,
OpenApiImportPlanApplyPayload {
plan_digest: older.digest,
idempotency_key: "old-matrix-new-attempt".to_owned(),
},
)
.await
.expect_err("old support matrix must not authorize a new Apply");
match error {
ApiError::Conflict {
context: Some(context),
..
} => assert_eq!(context["error_code"], "importer_version_changed"),
other => panic!("expected typed re-preview conflict, got {other:?}"),
}
assert!(
service
.list_operations(&workspace_id)
.await
.unwrap()
.is_empty()
);
}
@@ -0,0 +1,997 @@
use super::*;
pub(crate) const OPENAPI_SINGLE_SECURITY: &str = r#"
openapi: 3.0.3
info: { title: Import security, version: '1' }
servers: [{ url: https://api.example.test }]
components:
securitySchemes:
Key: { type: apiKey, in: header, name: X-Api-Key }
Bearer: { type: http, scheme: bearer }
paths:
/v2/latest:
get:
operationId: latestRates
security: [{ Key: [] }, { Bearer: [] }]
responses: { '200': { description: ok } }
"#;
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn preview_name_conflicts_are_typed_and_deterministic() {
let registry = test_registry().await;
let upstream = spawn_upstream_server().await;
let service = test_service(
registry,
test_storage_root("openapi_preview_name_conflicts"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace = WorkspaceId::new("ws_default");
service
.create_operation(
&workspace,
test_operation_payload(&upstream, "duplicate_id"),
)
.await
.unwrap();
let document = r#"
openapi: 3.0.3
info: { title: Naming }
servers: [{ url: https://api.example.test }]
paths:
/one:
get:
operationId: duplicate_id
responses: { '200': { description: ok } }
/two:
get:
operationId: duplicate_id
responses: { '200': { description: ok } }
/bad:
get:
operationId: bad-id
responses: { '200': { description: ok } }
"#;
let first = service
.preview_openapi_import(&workspace, upload(document))
.await
.unwrap();
let repeated = service
.preview_openapi_import(&workspace, upload(document))
.await
.unwrap();
assert_eq!(first.preview.conflicts, repeated.preview.conflicts);
assert!(
first
.preview
.conflicts
.iter()
.any(|item| item.conflict_type == "duplicate_name")
);
assert!(
first
.preview
.conflicts
.iter()
.any(|item| item.conflict_type == "invalid_name")
);
assert!(
first
.preview
.conflicts
.iter()
.any(|item| item.conflict_type == "taken_name")
);
assert!(first.preview.conflicts.iter().all(|item| {
item.source_location
.as_ref()
.is_some_and(|location| location.pointer.starts_with("/paths/"))
&& !item.proposed_name.is_empty()
}));
assert_eq!(service.list_operations(&workspace).await.unwrap().len(), 1);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn reopening_plan_is_read_only_and_reports_catalog_drift() {
let registry = test_registry().await;
let upstream = spawn_upstream_server().await;
let service = test_service(
registry,
test_storage_root("openapi_plan_reopen_catalog"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let plan = service
.create_openapi_import_plan(&workspace, &job_id, plan_payload("full", vec![], vec![]))
.await
.unwrap();
let plan_id = plan.plan_reference.as_str().into();
let current = service
.revalidate_openapi_import_plan(&workspace, &plan_id)
.await
.unwrap();
assert_eq!(current.revalidation_status, "current");
assert!(!current.revalidation_required);
assert!(
service
.list_operations(&workspace)
.await
.unwrap()
.is_empty()
);
service
.create_operation(
&workspace,
test_operation_payload(&upstream, "unrelated_operation"),
)
.await
.unwrap();
let stale = service
.revalidate_openapi_import_plan(&workspace, &plan_id)
.await
.unwrap();
assert_eq!(stale.revalidation_status, "stale");
assert!(stale.revalidation_required);
assert_eq!(service.list_operations(&workspace).await.unwrap().len(), 1);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn full_plan_is_server_authored_with_bounded_confirmation_and_no_mutation() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_full"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
assert_eq!(preview.preview.groups[0].operations[0].status, "actionable");
let job_id: ImportJobId = preview.job_id.as_str().into();
let job = registry
.get_import_job(&workspace_id, &job_id)
.await
.unwrap()
.unwrap();
let plan = service
.create_openapi_import_plan(&workspace_id, &job_id, plan_payload("full", vec![], vec![]))
.await
.unwrap();
assert!(plan.plan_reference.starts_with("plan_"));
assert!(
plan.plan_digest.len() == 64
&& plan
.plan_digest
.bytes()
.all(|byte| byte.is_ascii_hexdigit())
);
assert_eq!(plan.selection_mode, "full");
assert_eq!(plan.counts.selected, 1);
assert_eq!(plan.counts.excluded, 0);
assert_eq!(plan.counts.actionable, 1);
assert_eq!(plan.counts.blocked, 0);
let candidate = &plan.candidates[0];
assert_eq!(candidate.key, "GET /v2/latest");
assert_eq!(candidate.name, "latest_rates");
assert_eq!(candidate.state, "actionable");
assert_eq!(candidate.action.as_deref(), Some("create"));
assert_eq!(candidate.reason, None);
let expires_at = OffsetDateTime::parse(
&plan.expires_at,
&time::format_description::well_known::Rfc3339,
)
.unwrap();
assert!(expires_at > OffsetDateTime::now_utc());
assert!(expires_at <= job.expires_at);
let stored = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
.await
.unwrap()
.expect("the created plan must be readable in its workspace");
assert_eq!(stored.digest, plan.plan_digest);
assert_eq!(stored.payload["schema_version"], "import-plan-v2");
assert_eq!(stored.payload["catalog_revision"], plan.catalog_revision);
assert_eq!(stored.payload["support_matrix_version"], "1.0.3");
assert!(stored.payload["findings"]["document"].is_array());
assert!(stored.payload["findings"]["candidates"].is_array());
assert_eq!(stored.expires_at, expires_at);
assert_eq!(
stored.payload["selection"]["selected"],
json!(["GET /v2/latest"])
);
assert_eq!(stored.payload["selection"]["excluded"], json!([]));
assert_eq!(stored.payload["counts"]["actionable"], json!(1));
let candidate = &stored.payload["candidates"][0];
assert_eq!(candidate["decision"]["action"], "create");
assert!(
candidate["operation"]["id"]
.as_str()
.unwrap()
.starts_with("op_")
);
assert_eq!(candidate["operation"]["status"], "draft");
assert_eq!(
stored.payload["source"]["digest"],
job.preview_payload["source"]["digest"]
);
assert!(stored.payload["fingerprint"]["ir_fingerprint"].is_string());
let repeated = service
.create_openapi_import_plan(&workspace_id, &job_id, plan_payload("full", vec![], vec![]))
.await
.unwrap();
assert_ne!(repeated.plan_reference, plan.plan_reference);
assert_eq!(repeated.plan_digest, plan.plan_digest);
let repeated_stored = registry
.get_import_plan(&workspace_id, &repeated.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
assert_ne!(
repeated_stored.payload["candidates"][0]["operation"]["id"],
stored.payload["candidates"][0]["operation"]["id"]
);
// Planning is non-mutating: no operation exists and the job stays pending.
assert!(
service
.list_operations(&workspace_id)
.await
.unwrap()
.is_empty()
);
let job = registry
.get_import_job(&workspace_id, &job_id)
.await
.unwrap()
.unwrap();
assert_eq!(job.status, ImportJobStatus::Pending);
assert_eq!(job.error_text, None);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn partial_plan_counts_selection_and_rejects_invalid_request_material() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_partial"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_TWO_OPS))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let keys = preview_operation_keys(&preview);
assert_eq!(keys.len(), 2);
let (first, second) = (keys[0].clone(), keys[1].clone());
let expected_display_name = preview
.preview
.groups
.iter()
.flat_map(|group| &group.operations)
.find(|candidate| candidate.key == second)
.expect("excluded candidate is in preview")
.draft
.name
.clone();
let plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload("partial", vec![first.clone()], vec![]),
)
.await
.unwrap();
assert_eq!(plan.counts.selected, 1);
assert_eq!(plan.counts.excluded, 1);
assert_eq!(plan.counts.actionable, 1);
assert_eq!(plan.counts.blocked, 0);
let excluded = plan
.candidates
.iter()
.find(|candidate| candidate.key == second)
.expect("the excluded candidate is listed for confirmation");
assert_eq!(excluded.state, "excluded");
assert_eq!(excluded.name, expected_display_name);
assert_eq!(excluded.reason.as_deref(), Some("not_selected"));
let stored = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
assert_eq!(
stored.payload["excluded_reasons"],
json!([{
"key": second,
"name": expected_display_name,
"reason": "not_selected",
}])
);
let plan_id: crank_registry::ImportPlanId = plan.plan_reference.as_str().into();
let revalidated = service
.revalidate_openapi_import_plan(&workspace_id, &plan_id)
.await
.unwrap();
let revalidated_excluded = revalidated
.candidates
.iter()
.find(|candidate| candidate.key == second)
.expect("excluded candidate remains visible during revalidation");
assert_eq!(revalidated_excluded.name, expected_display_name);
let stored = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
let expected_all = json!([first, second]);
assert_eq!(stored.payload["selection"]["all"], expected_all);
// `excluded` candidates never receive a decision, target or draft material.
let listed = stored.payload["candidates"].as_array().unwrap();
assert_eq!(listed.len(), 1);
assert_eq!(listed[0]["key"], first);
assert!(listed[0].get("target").is_none());
let cases: Vec<(OpenApiImportPlanCreatePayload, &'static str)> = vec![
(
plan_payload("full", vec![first.clone()], vec![]),
"import_plan_selection_mismatch",
),
(
plan_payload("partial", vec!["GET /unknown".to_owned()], vec![]),
"import_plan_unknown_operation_key",
),
(
plan_payload("partial", vec![], vec![]),
"import_plan_invalid_input",
),
(
plan_payload("partial", vec![first.clone(), first.clone()], vec![]),
"import_plan_invalid_input",
),
(
plan_payload("bogus", vec![first.clone()], vec![]),
"import_plan_invalid_input",
),
(
plan_payload(
"partial",
vec![first.clone()],
vec![decision("GET /other", "create", None, None, None)],
),
"import_plan_decision_unselected",
),
(
plan_payload(
"partial",
vec![first.clone(), second.clone()],
vec![
decision(&first, "create", None, None, None),
decision(&first, "skip", Some("op_other"), None, None),
],
),
"import_plan_invalid_input",
),
(
plan_payload(
"partial",
vec![first.clone()],
vec![decision(&first, "skip", None, None, None)],
),
"import_plan_invalid_input",
),
(
plan_payload(
"partial",
vec![first.clone()],
vec![decision(
&first,
"skip",
Some("op_other"),
Some("other_name"),
None,
)],
),
"import_plan_invalid_input",
),
(
plan_payload(
"partial",
vec![first.clone(), second.clone()],
vec![decision(
&first,
"skip",
Some("op_other"),
None,
Some("auth_profile_any"),
)],
),
"import_plan_invalid_input",
),
(
plan_payload(
"partial",
vec![first.clone(), second.clone()],
vec![
decision(&first, "create", None, Some("renamed"), None),
decision(&second, "rename", Some("op_other"), None, None),
],
),
"import_plan_invalid_input",
),
(
plan_payload(
"partial",
vec![first.clone()],
vec![decision(&first, "rename", None, None, None)],
),
"import_plan_invalid_input",
),
(
plan_payload(
"partial",
vec![first.clone()],
vec![decision(&first, "new_version", None, None, None)],
),
"import_plan_invalid_input",
),
];
for (payload, expected_code) in cases {
let error = service
.create_openapi_import_plan(&workspace_id, &job_id, payload)
.await
.expect_err("invalid plan material must be rejected");
assert_error_code(&error, expected_code);
assert_http_status(error, axum::http::StatusCode::BAD_REQUEST);
}
// The successful plan above still exists untouched.
let readable = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
.await
.unwrap();
assert!(readable.is_some());
assert!(
service
.list_operations(&workspace_id)
.await
.unwrap()
.is_empty()
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn client_supplied_candidate_material_has_no_authority() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_client_authority"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
// Client-supplied digests, payloads or candidate arrays are not part of
// the request contract and must not influence the server-authored plan.
let request = json!({
"selection_mode": "full",
"selected_operation_keys": [],
"plan_digest": format!("sha256:{}", "ab".repeat(32)),
"plan_payload": {
"schema_version": "import-plan-client-v999",
"candidates": [{ "key": "GET /forged", "name": "forged" }],
},
"candidates": [{ "key": "GET /forged" }],
});
assert!(
serde_json::from_value::<OpenApiImportPlanCreatePayload>(request).is_err(),
"client-supplied candidate material must be rejected at the request boundary"
);
let payload: OpenApiImportPlanCreatePayload = serde_json::from_value(json!({
"selection_mode": "full",
"selected_operation_keys": []
}))
.unwrap();
let plan = service
.create_openapi_import_plan(&workspace_id, &job_id, payload)
.await
.unwrap();
let stored = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
let material = stored.payload.to_string();
assert!(!material.contains("import-plan-client-v999"));
assert!(!material.contains("GET /forged"));
assert!(!material.contains("abababab"));
assert_eq!(
stored.payload["selection"]["all"],
json!(["GET /v2/latest"])
);
assert_eq!(stored.payload["schema_version"], "import-plan-v2");
assert!(stored.digest.len() == 64 && stored.digest.bytes().all(|b| b.is_ascii_hexdigit()));
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn plan_creation_is_workspace_scoped() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_scope"),
test_auth_settings(),
test_secret_crypto(),
);
let primary = WorkspaceId::new("ws_default");
let secondary = WorkspaceId::new("ws_plan_scope_secondary");
let created_at = OffsetDateTime::now_utc();
registry
.create_workspace(CreateWorkspaceRequest {
workspace: &Workspace {
id: secondary.clone(),
slug: "ws-plan-scope-secondary".to_owned(),
display_name: "Plan scope secondary".to_owned(),
status: WorkspaceStatus::Active,
settings: json!({}),
created_at,
updated_at: created_at,
},
})
.await
.unwrap();
let preview = service
.preview_openapi_import(&primary, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let plan = service
.create_openapi_import_plan(&primary, &job_id, plan_payload("full", vec![], vec![]))
.await
.unwrap();
let cross_scope_error = service
.create_openapi_import_plan(&secondary, &job_id, plan_payload("full", vec![], vec![]))
.await
.expect_err("a foreign job must be invisible, not planned");
assert_http_status(cross_scope_error, axum::http::StatusCode::NOT_FOUND);
let stored = registry
.get_import_plan(&secondary, &plan.plan_reference.as_str().into())
.await
.unwrap();
assert!(stored.is_none(), "a foreign plan id must be invisible");
let reopen_error = service
.revalidate_openapi_import_plan(&secondary, &plan.plan_reference.as_str().into())
.await
.expect_err("a foreign plan cannot be reopened");
assert_http_status(reopen_error, axum::http::StatusCode::NOT_FOUND);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn exact_skip_rename_and_new_version_decisions_are_saved_verbatim() {
let registry = test_registry().await;
let upstream_base_url = spawn_upstream_server().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_decisions"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
// A conflicting existing operation so `create` is no longer safe by default.
let existing = service
.create_operation(
&workspace_id,
test_operation_payload(&upstream_base_url, "latest_rates"),
)
.await
.unwrap();
let operation_id = existing.operation_id;
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"full",
vec![],
vec![decision(
"GET /v2/latest",
"skip",
Some(operation_id.as_str()),
None,
None,
)],
),
)
.await
.expect("skip must target the exact existing operation");
let stored = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
let candidate = &stored.payload["candidates"][0];
assert_eq!(plan.counts.actionable, 1);
assert_eq!(candidate["decision"]["action"], "skip");
assert_eq!(candidate["target"]["operation_id"], json!(operation_id));
assert_eq!(
candidate["target"]["expected_state"],
json!({
"status": "draft",
"current_draft_version": 1,
"latest_published_version": null
})
);
assert!(
candidate.get("operation").is_none(),
"skip must not create draft material"
);
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let renamed = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"full",
vec![],
vec![decision(
"GET /v2/latest",
"rename",
None,
Some("latest_rates_confirmed"),
None,
)],
),
)
.await
.unwrap();
let stored = registry
.get_import_plan(&workspace_id, &renamed.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
assert_eq!(
stored.payload["candidates"][0]["decision"]["confirmed_name"],
"latest_rates_confirmed"
);
assert_eq!(
stored.payload["candidates"][0]["operation"]["name"],
"latest_rates_confirmed"
);
assert!(
stored.payload["candidates"][0]["operation"]["id"]
.as_str()
.unwrap()
.starts_with("op_")
);
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let versioned = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"full",
vec![],
vec![decision(
"GET /v2/latest",
"new_version",
Some(operation_id.as_str()),
None,
None,
)],
),
)
.await
.unwrap();
let stored = registry
.get_import_plan(&workspace_id, &versioned.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
let candidate = &stored.payload["candidates"][0];
assert_eq!(
candidate["operation"]["id"], operation_id,
"new_version snapshot must bind the exact target operation"
);
assert_eq!(candidate["operation"]["version"], 2);
assert_eq!(
candidate["target"]["expected_state"],
json!({
"status": "draft",
"current_draft_version": 1,
"latest_published_version": null
})
);
// Planning never mutates: only the original Draft Version exists.
let operations = service.list_operations(&workspace_id).await.unwrap();
assert_eq!(operations.len(), 1);
assert_eq!(operations[0].name, "latest_rates");
assert_eq!(operations[0].current_draft_version, 1);
// A mismatched target is rejected with the stable target code.
let other = service
.create_operation(
&workspace_id,
test_operation_payload(&upstream_base_url, "other_operation"),
)
.await
.unwrap();
for mismatched in [
vec![decision(
"GET /v2/latest",
"skip",
Some(other.operation_id.as_str()),
None,
None,
)],
vec![decision(
"GET /v2/latest",
"new_version",
Some(other.operation_id.as_str()),
None,
None,
)],
] {
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let error = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload("full", vec![], mismatched),
)
.await
.expect_err("a mismatched target must be rejected");
assert_error_code(&error, "import_plan_target_invalid");
assert_http_status(error, axum::http::StatusCode::BAD_REQUEST);
}
// An explicit `create` against a taken name conflicts; the server never
// auto-selects a replacement name.
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let error = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"full",
vec![],
vec![decision("GET /v2/latest", "create", None, None, None)],
),
)
.await
.expect_err("create with a taken name must conflict");
assert_error_code(&error, "import_plan_name_conflict");
assert_http_status(error, axum::http::StatusCode::CONFLICT);
// Without an explicit decision the same collision stays a bounded,
// redacted blocked candidate inside the immutable plan.
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let plan = service
.create_openapi_import_plan(&workspace_id, &job_id, plan_payload("full", vec![], vec![]))
.await
.unwrap();
assert_eq!(plan.counts.actionable, 0);
assert_eq!(plan.counts.blocked, 1);
let stored = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
let candidate = &stored.payload["candidates"][0];
assert_eq!(candidate["state"], "blocked");
assert_eq!(candidate["reason"], "operation_name_conflict");
assert!(candidate.get("operation").is_none());
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn stale_or_terminal_jobs_preview_again_without_mutating_the_job() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_stale"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
sqlx::query(
"update import_jobs
set preview_payload = jsonb_set(preview_payload, '{preview_digest}', to_jsonb($1::text))
where id = $2",
)
.bind("0".repeat(64))
.bind(job_id.as_str())
.execute(registry.pool())
.await
.unwrap();
let error = service
.create_openapi_import_plan(&workspace_id, &job_id, plan_payload("full", vec![], vec![]))
.await
.expect_err("a stale preview contract must be rejected");
assert_error_code(&error, "import_replay_verification_failed");
let context = public_error_context(&error).cloned().unwrap();
assert_eq!(context["repreview_required"], json!(true));
assert_eq!(
context.get("recovery").and_then(Value::as_str),
Some("repreview_required")
);
assert_http_status(error, axum::http::StatusCode::CONFLICT);
// Unlike the legacy path the job itself is untouched: other stored
// plans anchored to it must remain readable.
let job = registry
.get_import_job(&workspace_id, &job_id)
.await
.unwrap()
.unwrap();
assert_eq!(job.status, ImportJobStatus::Pending);
assert_eq!(job.error_text, None);
assert!(job.finished_at.is_none());
assert!(
service
.list_operations(&workspace_id)
.await
.unwrap()
.is_empty()
);
let completed_at = OffsetDateTime::now_utc();
registry
.finish_import_job(FinishImportJobRequest {
id: &job_id,
status: ImportJobStatus::Failed,
created_operation_ids: &json!([]),
error_text: Some("test_finalized"),
finished_at: &completed_at,
})
.await
.unwrap();
let error = service
.create_openapi_import_plan(&workspace_id, &job_id, plan_payload("full", vec![], vec![]))
.await
.expect_err("a terminal job cannot be planned");
assert_error_code(&error, "import_plan_job_terminal");
assert_http_status(error, axum::http::StatusCode::CONFLICT);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn public_plan_route_returns_bounded_confirmation_and_requires_a_session() {
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_plan_http");
let service = test_service(
registry.clone(),
storage_root.clone(),
test_auth_settings(),
test_secret_crypto(),
);
let app = build_test_app(registry.clone(), storage_root);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id = preview.job_id.clone();
let server = spawn_admin_api(app).await;
let client = authorized_client(&server).await;
let url = format!("{}/imports/openapi/{}/plans", server.as_ref(), job_id);
// Without a session (and thus without a workspace owner context) the
// public contract refuses and no plan is created.
let anonymous = reqwest::Client::new();
let denied = anonymous
.post(&url)
.json(&json!({ "selection_mode": "full", "selected_operation_keys": [] }))
.send()
.await
.unwrap();
assert_eq!(denied.status(), reqwest::StatusCode::UNAUTHORIZED);
let accepted = client
.post(&url)
.json(&json!({ "selection_mode": "full", "selected_operation_keys": [] }))
.send()
.await
.unwrap();
assert_eq!(accepted.status(), reqwest::StatusCode::OK);
let body: Value = accepted.json().await.unwrap();
let plan_reference = body["plan_reference"].as_str().unwrap_or_default();
assert!(
plan_reference.starts_with("plan_"),
"plan reference must be server-issued: {body:?}"
);
let plan_digest = body["plan_digest"].as_str().unwrap_or_default();
assert!(
plan_digest.len() == 64 && plan_digest.bytes().all(|b| b.is_ascii_hexdigit()),
"plan digest must be the registry-derived SHA-256: {body:?}"
);
assert_eq!(body["selection_mode"], "full");
assert_eq!(
body["counts"],
json!({ "selected": 1, "excluded": 0, "actionable": 1, "blocked": 0 })
);
assert_eq!(body["candidates"].as_array().unwrap().len(), 1);
assert_eq!(body["candidates"][0]["key"], "GET /v2/latest");
assert_eq!(body["candidates"][0]["state"], "actionable");
assert_eq!(body["candidates"][0]["action"], "create");
assert!(body["expires_at"].is_string());
// The HTTP response is the bounded confirmation only: no draft snapshot,
// no raw preview material, no secret material.
assert!(body["candidates"][0].get("operation").is_none());
assert!(!body.to_string().to_lowercase().contains("password"));
// The plan is readable in the same workspace right after the 200.
let plan_id = crank_registry::ImportPlanId::new(plan_reference);
let readable = registry
.get_import_plan(&workspace_id, &plan_id)
.await
.unwrap()
.expect("the HTTP-created plan must be persisted");
assert_eq!(readable.digest, plan_digest);
}
@@ -0,0 +1,135 @@
use super::*;
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn partial_plan_applies_when_excluded_operation_name_exceeds_selected_name_limit() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_long_excluded_name"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let long_operation_id = "a".repeat(257);
let document = format!(
r#"openapi: 3.0.3
info:
title: Long excluded operation name
version: "1"
servers:
- url: https://api.example.test
paths:
/selected:
get:
operationId: selectedMethod
responses:
"200":
description: ok
/excluded:
get:
operationId: {long_operation_id}
responses:
"200":
description: ok
"#
);
let preview = service
.preview_openapi_import(&workspace_id, upload(&document))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let selected_key = "GET /selected";
let excluded_key = "GET /excluded";
let excluded_draft_name = preview
.preview
.groups
.iter()
.flat_map(|group| &group.operations)
.find(|candidate| candidate.key == excluded_key)
.expect("long-name method is present in preview")
.draft
.name
.clone();
assert_eq!(excluded_draft_name, long_operation_id);
assert!(excluded_draft_name.len() > 256);
let plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"partial",
vec![selected_key.to_owned()],
vec![decision(selected_key, "create", None, None, None)],
),
)
.await
.unwrap();
let created_excluded = plan
.candidates
.iter()
.find(|candidate| candidate.key == excluded_key)
.expect("excluded method is returned by plan creation");
assert_eq!(created_excluded.name, excluded_draft_name);
assert_eq!(plan.counts.selected, 1);
assert_eq!(plan.counts.excluded, 1);
let plan_id = crank_registry::ImportPlanId::new(plan.plan_reference.clone());
let stored = registry
.get_import_plan(&workspace_id, &plan_id)
.await
.unwrap()
.expect("created plan is persisted");
assert_eq!(
stored.payload["excluded_reasons"][0]["name"],
excluded_draft_name
);
let revalidated = service
.revalidate_openapi_import_plan(&workspace_id, &plan_id)
.await
.unwrap();
let revalidated_excluded = revalidated
.candidates
.iter()
.find(|candidate| candidate.key == excluded_key)
.expect("excluded method remains visible during revalidation");
assert_eq!(revalidated_excluded.name, excluded_draft_name);
let report = service
.apply_openapi_import_plan(
&workspace_id,
&plan_id,
admin_api::service::OpenApiImportPlanApplyPayload {
plan_digest: plan.plan_digest,
idempotency_key: "long-excluded-name-apply".to_owned(),
},
)
.await
.expect("excluded descriptive metadata must not invalidate a partial plan");
assert_eq!(
report.status,
crank_registry::ImportPlanApplyStatus::Applied
);
assert_eq!(report.counts.created, 1);
assert_eq!(
report
.outcomes
.iter()
.find(|outcome| outcome.key == selected_key)
.expect("selected method appears in apply report")
.outcome,
crank_registry::ImportPlanCandidateOutcome::Created
);
let reported_excluded = report
.outcomes
.iter()
.find(|outcome| outcome.key == excluded_key)
.expect("apply report includes the excluded method");
assert_eq!(reported_excluded.name, excluded_draft_name);
let operations = service.list_operations(&workspace_id).await.unwrap();
assert_eq!(operations.len(), 1, "only the selected method is applied");
assert_eq!(operations[0].status, crank_core::OperationStatus::Draft);
assert_eq!(operations[0].current_draft_version, 1);
}
@@ -0,0 +1,360 @@
use super::*;
/// Server-created plan reached through the public HTTP contract, so the locale
/// tests exercise the real route handlers rather than the service methods.
struct HttpPlan {
plan_reference: String,
plan_digest: String,
}
async fn create_http_plan(client: &reqwest::Client, base_url: &str) -> HttpPlan {
let upload_part = reqwest::multipart::Part::bytes(OPENAPI_SINGLE.as_bytes().to_vec())
.file_name("import.yaml")
.mime_str("application/yaml")
.unwrap();
let preview = client
.post(format!("{base_url}/imports/openapi/preview"))
.multipart(reqwest::multipart::Form::new().part("file", upload_part))
.send()
.await
.unwrap();
assert_eq!(preview.status(), reqwest::StatusCode::OK);
let preview: Value = preview.json().await.unwrap();
let job_id = preview["job_id"].as_str().unwrap().to_owned();
let plan = client
.post(format!("{base_url}/imports/openapi/{job_id}/plans"))
.json(&json!({ "selection_mode": "full", "selected_operation_keys": [] }))
.send()
.await
.unwrap();
assert_eq!(plan.status(), reqwest::StatusCode::OK);
let plan: Value = plan.json().await.unwrap();
HttpPlan {
plan_reference: plan["plan_reference"].as_str().unwrap().to_owned(),
plan_digest: plan["plan_digest"].as_str().unwrap().to_owned(),
}
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn plan_create_localizes_repreview_guidance_by_accept_language() {
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_plan_locale_create");
let service = test_service(
registry.clone(),
storage_root.clone(),
test_auth_settings(),
test_secret_crypto(),
);
let app = build_test_app(registry.clone(), storage_root);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id = preview.job_id.clone();
// Corrupt the persisted preview contract so plan creation must ask for a
// fresh preview.
sqlx::query(
"update import_jobs
set preview_payload = jsonb_set(preview_payload, '{preview_digest}', to_jsonb($1::text))
where id = $2",
)
.bind("0".repeat(64))
.bind(&job_id)
.execute(registry.pool())
.await
.unwrap();
let server = spawn_admin_api(app).await;
let client = authorized_client(&server).await;
let url = format!("{}/imports/openapi/{}/plans", server.as_ref(), job_id);
// Russian session: Russian recovery guidance, identical machine code and
// recovery flags.
let ru = client
.post(&url)
.header("accept-language", "ru-RU, ru;q=0.9")
.json(&json!({ "selection_mode": "full", "selected_operation_keys": [] }))
.send()
.await
.unwrap();
assert_eq!(ru.status(), reqwest::StatusCode::CONFLICT);
let ru_body: Value = ru.json().await.unwrap();
assert_eq!(
ru_body["error"]["context"]["error_code"],
"import_replay_verification_failed"
);
assert_eq!(
ru_body["error"]["context"]["repreview_required"],
json!(true)
);
assert_eq!(
ru_body["error"]["context"]["recovery"],
"repreview_required"
);
assert!(
ru_body["error"]["message"]
.as_str()
.unwrap_or_default()
.contains("создайте новый preview"),
"Russian session must receive Russian guidance: {ru_body:?}"
);
// No locale header keeps the English default behavior.
let en = client
.post(&url)
.json(&json!({ "selection_mode": "full", "selected_operation_keys": [] }))
.send()
.await
.unwrap();
assert_eq!(en.status(), reqwest::StatusCode::CONFLICT);
let en_body: Value = en.json().await.unwrap();
assert_eq!(
en_body["error"]["context"]["error_code"],
"import_replay_verification_failed"
);
assert!(
en_body["error"]["message"]
.as_str()
.unwrap_or_default()
.contains("create a fresh preview"),
"EN default must remain English: {en_body:?}"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn plan_revalidate_accepts_locale_without_machine_drift() {
let registry = test_registry().await;
let app = build_test_app(
registry,
test_storage_root("openapi_import_plan_locale_revalidate"),
);
let server = spawn_admin_api(app).await;
let client = authorized_client(&server).await;
let plan = create_http_plan(&client, server.as_ref()).await;
let url = format!(
"{}/imports/openapi/plans/{}",
server.as_ref(),
plan.plan_reference
);
let ru = client
.get(&url)
.header("accept-language", "ru")
.send()
.await
.unwrap();
assert_eq!(ru.status(), reqwest::StatusCode::OK);
let ru: Value = ru.json().await.unwrap();
assert_eq!(ru["plan_digest"], plan.plan_digest);
assert_eq!(ru["revalidation_status"], "current");
assert_eq!(ru["revalidation_required"], false);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn plan_create_localizes_expired_preview_by_accept_language() {
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_plan_locale_expired");
let service = test_service(
registry.clone(),
storage_root.clone(),
test_auth_settings(),
test_secret_crypto(),
);
let app = build_test_app(registry.clone(), storage_root);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id = preview.job_id.clone();
// Expire the preview job without corrupting its replay contract.
sqlx::query("update import_jobs set expires_at = now() - interval '1 minute' where id = $1")
.bind(&job_id)
.execute(registry.pool())
.await
.unwrap();
let server = spawn_admin_api(app).await;
let client = authorized_client(&server).await;
let url = format!("{}/imports/openapi/{}/plans", server.as_ref(), job_id);
let body = json!({ "selection_mode": "full", "selected_operation_keys": [] });
let ru = client
.post(&url)
.header("accept-language", "ru")
.json(&body)
.send()
.await
.unwrap();
assert_eq!(ru.status(), reqwest::StatusCode::BAD_REQUEST);
let ru_body: Value = ru.json().await.unwrap();
assert_eq!(ru_body["error"]["code"], "validation_error");
assert!(
ru_body["error"].get("context").is_none(),
"expired-preview validation keeps no context: {ru_body:?}"
);
assert!(
ru_body["error"]["message"]
.as_str()
.unwrap_or_default()
.contains("истёк"),
"Russian session must receive Russian guidance: {ru_body:?}"
);
// No locale header keeps the English default behavior.
let en = client.post(&url).json(&body).send().await.unwrap();
assert_eq!(en.status(), reqwest::StatusCode::BAD_REQUEST);
let en_body: Value = en.json().await.unwrap();
assert_eq!(en_body["error"]["code"], "validation_error");
assert!(en_body["error"].get("context").is_none());
assert_eq!(en_body["error"]["message"], "import preview has expired");
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn plan_create_localizes_name_conflict_guidance_by_accept_language() {
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_plan_locale_name_conflict");
let service = test_service(
registry.clone(),
storage_root.clone(),
test_auth_settings(),
test_secret_crypto(),
);
let app = build_test_app(registry.clone(), storage_root);
let workspace_id = WorkspaceId::new("ws_default");
// Occupy the candidate's suggested name so an explicit `create` decision
// conflicts.
service
.create_operation(
&workspace_id,
test_operation_payload("https://api.example.test", "latest_rates"),
)
.await
.unwrap();
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id = preview.job_id.clone();
let server = spawn_admin_api(app).await;
let client = authorized_client(&server).await;
let url = format!("{}/imports/openapi/{}/plans", server.as_ref(), job_id);
let body = json!({
"selection_mode": "full",
"selected_operation_keys": [],
"decisions": [{
"operation_key": "GET /v2/latest",
"action": "create",
}]
});
let ru = client
.post(&url)
.header("accept-language", "ru")
.json(&body)
.send()
.await
.unwrap();
assert_eq!(ru.status(), reqwest::StatusCode::CONFLICT);
let ru_body: Value = ru.json().await.unwrap();
assert_eq!(
ru_body["error"]["context"]["error_code"],
"import_plan_name_conflict"
);
assert_eq!(
ru_body["error"]["context"]["recovery"],
"confirm_skip_rename_or_new_version"
);
assert!(
ru_body["error"]["message"]
.as_str()
.unwrap_or_default()
.contains("уже существует"),
"Russian session must receive Russian guidance: {ru_body:?}"
);
// No locale header keeps the exact English wording.
let en = client.post(&url).json(&body).send().await.unwrap();
assert_eq!(en.status(), reqwest::StatusCode::CONFLICT);
let en_body: Value = en.json().await.unwrap();
assert_eq!(
en_body["error"]["context"]["error_code"],
"import_plan_name_conflict"
);
assert_eq!(
en_body["error"]["message"],
"operation with name latest_rates already exists"
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn legacy_create_localizes_expired_preview_by_accept_language() {
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_legacy_create_locale_expired");
let service = test_service(
registry.clone(),
storage_root.clone(),
test_auth_settings(),
test_secret_crypto(),
);
let app = build_test_app(registry.clone(), storage_root);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id = preview.job_id.clone();
// Expire the preview job so the legacy create route /imports/openapi/{id}/create
// rejects before any selection work.
sqlx::query("update import_jobs set expires_at = now() - interval '1 minute' where id = $1")
.bind(&job_id)
.execute(registry.pool())
.await
.unwrap();
let server = spawn_admin_api(app).await;
let client = authorized_client(&server).await;
let url = format!("{}/imports/openapi/{}/create", server.as_ref(), job_id);
let body = json!({ "selected_operation_keys": [] });
let ru = client
.post(&url)
.header("accept-language", "ru")
.json(&body)
.send()
.await
.unwrap();
assert_eq!(ru.status(), reqwest::StatusCode::BAD_REQUEST);
let ru_body: Value = ru.json().await.unwrap();
assert_eq!(ru_body["error"]["code"], "validation_error");
assert!(
ru_body["error"].get("context").is_none(),
"legacy expired-preview validation keeps no context: {ru_body:?}"
);
assert!(
ru_body["error"]["message"]
.as_str()
.unwrap_or_default()
.contains("истёк"),
"Russian session must receive Russian guidance: {ru_body:?}"
);
// No locale header keeps the exact English wording.
let en = client.post(&url).json(&body).send().await.unwrap();
assert_eq!(en.status(), reqwest::StatusCode::BAD_REQUEST);
let en_body: Value = en.json().await.unwrap();
assert_eq!(en_body["error"]["code"], "validation_error");
assert_eq!(en_body["error"]["message"], "import preview has expired");
}
@@ -0,0 +1,170 @@
use admin_api::{
error::ApiError,
service::{
AuthProfilePayload, OpenApiImportPlanCreatePayload, OpenApiImportPlanDecision,
OpenApiUpload, OpenApiUploadLocale, SecretPayload,
},
};
use axum::response::IntoResponse;
use crank_core::{
ApiKeyHeaderAuthConfig, AuthConfig, AuthKind, AuthProfileId, OperationId, SecretId, SecretKind,
Workspace, WorkspaceId, WorkspaceStatus,
};
use crank_registry::{
CreateWorkspaceRequest, FinishImportJobRequest, ImportJobId, ImportJobStatus,
};
use serde_json::{Value, json};
use serial_test::serial;
use time::OffsetDateTime;
use super::super::common::*;
const OPENAPI_SINGLE: &str = r#"
openapi: 3.0.3
info:
title: Frankfurter API
servers:
- url: https://api.frankfurter.dev
paths:
/v2/latest:
get:
operationId: latestRates
summary: Получить последние курсы валют
tags: [currency]
parameters:
- name: base
in: query
required: true
schema: { type: string }
responses:
'200':
description: OK
content:
application/json:
schema:
type: object
properties:
base: { type: string }
rates:
type: object
"#;
const OPENAPI_TWO_OPS: &str = r#"
openapi: 3.0.3
info: { title: Two Operations }
servers: [{ url: https://api.example.test }]
paths:
/alpha:
get:
operationId: alpha
responses: { '200': { description: ok } }
/beta:
get:
operationId: betaOp
responses: { '200': { description: ok } }
"#;
const OPENAPI_GLOBAL_BLOCKER: &str = r#"
openapi: 3.0.3
info: { title: Global blocker }
servers: [{ url: https://api.example.test }]
paths:
/valid:
get:
responses: { '200': { description: ok } }
/broken: not-a-path-item
"#;
fn upload(document: &str) -> OpenApiUpload {
OpenApiUpload {
bytes: document.as_bytes().to_vec(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
}
}
fn preview_operation_keys(
preview: &admin_api::service::OpenApiImportPreviewResponse,
) -> Vec<String> {
let mut keys = preview
.preview
.groups
.iter()
.flat_map(|group| &group.operations)
.map(|operation| operation.key.clone())
.collect::<Vec<_>>();
keys.sort();
keys
}
fn decision(
key: &str,
action: &str,
target: Option<&str>,
name: Option<&str>,
auth: Option<&str>,
) -> OpenApiImportPlanDecision {
OpenApiImportPlanDecision {
operation_key: key.to_owned(),
action: action.to_owned(),
target_operation_id: target.map(ToOwned::to_owned),
confirmed_name: name.map(ToOwned::to_owned),
auth_profile_id: auth.map(ToOwned::to_owned),
security_alternative_index: None,
}
}
fn plan_payload(
selection_mode: &str,
selected: Vec<String>,
decisions: Vec<OpenApiImportPlanDecision>,
) -> OpenApiImportPlanCreatePayload {
OpenApiImportPlanCreatePayload {
selection_mode: selection_mode.to_owned(),
selected_operation_keys: selected,
server_url: None,
decisions,
}
}
fn public_error_context(error: &ApiError) -> Option<&Value> {
match error {
ApiError::Unauthorized { context, .. }
| ApiError::Forbidden { context, .. }
| ApiError::Validation { context, .. }
| ApiError::Unprocessable { context, .. }
| ApiError::NotFound { context, .. }
| ApiError::Conflict { context, .. }
| ApiError::PayloadTooLarge { context, .. }
| ApiError::PreconditionRequired { context, .. }
| ApiError::RateLimited { context, .. }
| ApiError::Internal { context, .. } => context.as_ref(),
}
}
fn assert_error_code(error: &ApiError, expected_code: &str) {
assert_eq!(
public_error_context(error)
.and_then(|context| context.get("error_code"))
.and_then(Value::as_str),
Some(expected_code),
"unexpected API error: {error:?}"
);
}
/// Asserts the rendered HTTP status of a rejection without private accessors.
fn assert_http_status(error: ApiError, expected: axum::http::StatusCode) {
assert_eq!(
error.into_response().status(),
expected,
"the rendered status must match the public contract"
);
}
mod creation;
mod excluded_names;
mod locale;
mod route_get;
pub(super) use creation::OPENAPI_SINGLE_SECURITY;
mod security_availability;
mod security_binding;
mod validation;
@@ -0,0 +1,87 @@
use super::*;
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn persisted_plan_get_requires_owner_and_reports_catalog_drift() {
let registry = test_registry().await;
let storage_root = test_storage_root("openapi_import_plan_get_route");
let service = test_service(
registry.clone(),
storage_root.clone(),
test_auth_settings(),
test_secret_crypto(),
);
let workspace = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let plan = service
.create_openapi_import_plan(&workspace, &job_id, plan_payload("full", vec![], vec![]))
.await
.unwrap();
let plan_id = plan.plan_reference.clone();
let plan_digest = plan.plan_digest.clone();
let foreign_workspace = WorkspaceId::new("ws_plan_get_foreign");
let now = OffsetDateTime::now_utc();
registry
.create_workspace(CreateWorkspaceRequest {
workspace: &Workspace {
id: foreign_workspace.clone(),
slug: "ws-plan-get-foreign".to_owned(),
display_name: "Foreign plan workspace".to_owned(),
status: WorkspaceStatus::Active,
settings: json!({}),
created_at: now,
updated_at: now,
},
})
.await
.unwrap();
let server = spawn_admin_api(build_test_app(registry, storage_root)).await;
let client = authorized_client(&server).await;
let url = format!("{server}/imports/openapi/plans/{plan_id}");
let anonymous = reqwest::Client::new().get(&url).send().await.unwrap();
assert_eq!(anonymous.status(), reqwest::StatusCode::UNAUTHORIZED);
let foreign = client
.get(url.replace("ws_default", foreign_workspace.as_str()))
.send()
.await
.unwrap();
assert_eq!(foreign.status(), reqwest::StatusCode::FORBIDDEN);
let current = client.get(&url).send().await.unwrap();
assert_eq!(current.status(), reqwest::StatusCode::OK);
let current: Value = current.json().await.unwrap();
assert_eq!(current["plan_reference"], plan_id);
assert_eq!(current["plan_digest"], plan_digest);
assert_eq!(current["revalidation_status"], "current");
assert_eq!(current["revalidation_required"], false);
assert!(
service
.list_operations(&workspace)
.await
.unwrap()
.is_empty()
);
let upstream = spawn_upstream_server().await;
service
.create_operation(
&workspace,
test_operation_payload(&upstream, "plan_get_catalog_drift"),
)
.await
.unwrap();
let stale = client.get(&url).send().await.unwrap();
assert_eq!(stale.status(), reqwest::StatusCode::OK);
let stale: Value = stale.json().await.unwrap();
assert_eq!(stale["plan_reference"], plan_id);
assert_eq!(stale["plan_digest"], plan_digest);
assert_eq!(stale["revalidation_status"], "stale");
assert_eq!(stale["revalidation_required"], true);
assert_eq!(service.list_operations(&workspace).await.unwrap().len(), 1);
}
@@ -0,0 +1,292 @@
use super::*;
const OPENAPI_SECURITY_BINDING: &str = r#"
openapi: 3.0.3
info: { title: Security binding availability, version: '1' }
servers: [{ url: https://api.example.test }]
components:
securitySchemes:
Key: { type: apiKey, in: header, name: X-Api-Key }
Bearer: { type: http, scheme: bearer }
paths:
/v2/latest:
get:
operationId: latestRates
security: [{ Key: [] }, { Bearer: [] }]
responses: { '200': { description: ok } }
"#;
fn security_upload() -> OpenApiUpload {
OpenApiUpload {
bytes: OPENAPI_SECURITY_BINDING.as_bytes().to_vec(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
}
}
fn binding_decision(auth_profile_id: &str) -> OpenApiImportPlanDecision {
let mut binding = decision(
"GET /v2/latest",
"create",
None,
None,
Some(auth_profile_id),
);
binding.security_alternative_index = Some(0);
binding
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn security_binding_refuses_foreign_and_unavailable_auth_material_before_draft() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_plan_security_availability"),
test_auth_settings(),
test_secret_crypto(),
);
let primary = WorkspaceId::new("ws_default");
let foreign = WorkspaceId::new("ws_security_foreign");
let created_at = OffsetDateTime::now_utc();
registry
.create_workspace(CreateWorkspaceRequest {
workspace: &Workspace {
id: foreign.clone(),
slug: "ws-security-foreign".to_owned(),
display_name: "Foreign security workspace".to_owned(),
status: WorkspaceStatus::Active,
settings: json!({}),
created_at,
updated_at: created_at,
},
})
.await
.unwrap();
let foreign_canary = "foreign-security-profile-canary";
let foreign_secret = service
.create_secret(
&foreign,
None,
SecretPayload {
name: "foreign-security-secret".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": foreign_canary }),
},
None,
)
.await
.unwrap();
let foreign_profile = service
.create_auth_profile(
&foreign,
AuthProfilePayload {
name: "foreign-security-profile-name".to_owned(),
kind: AuthKind::ApiKeyHeader,
config: AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
header_name: "X-Api-Key".to_owned(),
secret_id: SecretId::new(foreign_secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
// A foreign profile is absent from the current workspace's advertised
// choices and submission fails with a generic workspace-safe error.
let preview = service
.preview_openapi_import(&primary, security_upload())
.await
.unwrap();
let preview_text = serde_json::to_string(&preview).unwrap();
for private_value in [
foreign_profile.id.as_str(),
foreign_profile.name.as_str(),
foreign_secret.id.as_str(),
foreign_canary,
] {
assert!(
!preview_text.contains(private_value),
"foreign profile metadata appeared in preview choices"
);
}
assert!(preview.security_profile_choices.iter().all(|choice| {
choice
.profiles
.iter()
.all(|profile| profile.id != foreign_profile.id.as_str())
}));
let job_id: ImportJobId = preview.job_id.as_str().into();
let foreign_error = service
.create_openapi_import_plan(
&primary,
&job_id,
plan_payload(
"full",
vec![],
vec![binding_decision(foreign_profile.id.as_str())],
),
)
.await
.expect_err("a profile from another workspace must not bind");
assert_error_code(&foreign_error, "import_plan_auth_unavailable");
let foreign_error_text = format!("{foreign_error:?}");
assert_http_status(foreign_error, axum::http::StatusCode::UNPROCESSABLE_ENTITY);
for private_value in [
foreign_profile.id.as_str(),
foreign_profile.name.as_str(),
foreign_secret.id.as_str(),
foreign_canary,
] {
assert!(
!foreign_error_text.contains(private_value),
"foreign profile or secret metadata leaked: {foreign_error_text}"
);
}
// A previously valid local profile whose Secret is disabled is removed
// from choices and cannot be used in a newly confirmed ImportPlan.
let disabled_canary = "disabled-security-secret-canary";
let disabled_secret = service
.create_secret(
&primary,
None,
SecretPayload {
name: "disabled-security-secret".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": disabled_canary }),
},
None,
)
.await
.unwrap();
let disabled_profile = service
.create_auth_profile(
&primary,
AuthProfilePayload {
name: "disabled-security-profile".to_owned(),
kind: AuthKind::ApiKeyHeader,
config: AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
header_name: "X-Api-Key".to_owned(),
secret_id: SecretId::new(disabled_secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
sqlx::query(
"update secrets set status = 'disabled', updated_at = now() where workspace_id = $1 and id = $2",
)
.bind(primary.as_str())
.bind(disabled_secret.id.as_str())
.execute(registry.pool())
.await
.unwrap();
let preview = service
.preview_openapi_import(&primary, security_upload())
.await
.unwrap();
assert!(preview.security_profile_choices.iter().all(|choice| {
choice
.profiles
.iter()
.all(|profile| profile.id != disabled_profile.id.as_str())
}));
let job_id: ImportJobId = preview.job_id.as_str().into();
let disabled_error = service
.create_openapi_import_plan(
&primary,
&job_id,
plan_payload(
"full",
vec![],
vec![binding_decision(disabled_profile.id.as_str())],
),
)
.await
.expect_err("a disabled linked Secret must reject the profile binding");
assert_error_code(&disabled_error, "secret_not_active");
let disabled_error_text = format!("{disabled_error:?}");
assert!(!disabled_error_text.contains(disabled_canary));
// A profile whose active Secret has no stored current version is equally
// unavailable. Direct SQL models the broken persisted reference while
// retaining the real Admin preview and plan validation paths.
let missing_version_canary = "missing-version-security-canary";
let missing_version_secret = service
.create_secret(
&primary,
None,
SecretPayload {
name: "missing-version-security-secret".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": missing_version_canary }),
},
None,
)
.await
.unwrap();
let missing_version_profile = service
.create_auth_profile(
&primary,
AuthProfilePayload {
name: "missing-version-security-profile".to_owned(),
kind: AuthKind::ApiKeyHeader,
config: AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
header_name: "X-Api-Key".to_owned(),
secret_id: SecretId::new(missing_version_secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
sqlx::query("delete from secret_versions where secret_id = $1 and version = 1")
.bind(missing_version_secret.id.as_str())
.execute(registry.pool())
.await
.unwrap();
let preview = service
.preview_openapi_import(&primary, security_upload())
.await
.unwrap();
assert!(preview.security_profile_choices.iter().all(|choice| {
choice
.profiles
.iter()
.all(|profile| profile.id != missing_version_profile.id.as_str())
}));
let job_id: ImportJobId = preview.job_id.as_str().into();
let missing_version_error = service
.create_openapi_import_plan(
&primary,
&job_id,
plan_payload(
"full",
vec![],
vec![binding_decision(missing_version_profile.id.as_str())],
),
)
.await
.expect_err("a Secret without a current version must reject the profile binding");
assert_error_code(&missing_version_error, "operation_auth_profile_invalid");
let missing_version_error_text = format!("{missing_version_error:?}");
for private_value in [
missing_version_profile.id.as_str(),
missing_version_profile.name.as_str(),
missing_version_secret.id.as_str(),
missing_version_canary,
] {
assert!(
!missing_version_error_text.contains(private_value),
"missing-version Secret metadata leaked: {missing_version_error_text}"
);
}
assert!(
service.list_operations(&primary).await.unwrap().is_empty(),
"no unavailable profile binding may create a Draft"
);
}
@@ -0,0 +1,770 @@
use super::*;
const OPENAPI_SINGLE_PUBLIC: &str = r#"
openapi: 3.0.3
info: { title: Public import, version: '1' }
servers: [{ url: https://api.example.test }]
paths:
/v2/latest:
get:
operationId: latestRates
responses: { '200': { description: ok } }
"#;
const OPENAPI_SINGLE_EXPLICIT_NO_AUTH: &str = r#"
openapi: 3.0.3
info: { title: Explicit no auth import, version: '1' }
servers: [{ url: https://api.example.test }]
paths:
/v2/latest:
get:
operationId: latestRates
security: []
responses: { '200': { description: ok } }
"#;
const OPENAPI_BASIC_AND_QUERY_SECURITY: &str = r#"
openapi: 3.0.3
info: { title: Basic and query import, version: '1' }
servers: [{ url: https://api.example.test }]
components:
securitySchemes:
Basic: { type: http, scheme: basic }
QueryKey: { type: apiKey, in: query, name: access_token }
paths:
/v2/basic:
get:
operationId: basicRates
security: [{ Basic: [] }, { QueryKey: [] }]
responses: { '200': { description: ok } }
/v2/query:
get:
operationId: queryRates
security: [{ Basic: [] }, { QueryKey: [] }]
responses: { '200': { description: ok } }
"#;
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn auth_profile_references_are_validated_stored_and_inherited() {
let registry = test_registry().await;
let upstream_base_url = spawn_upstream_server().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_auth"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let secret_token = "plan-secret-canary-2-13";
let secret = service
.create_secret(
&workspace_id,
None,
SecretPayload {
name: "plan-auth-token".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": secret_token }),
},
None,
)
.await
.unwrap();
let auth_profile = service
.create_auth_profile(
&workspace_id,
AuthProfilePayload {
name: "plan-auth-profile".to_owned(),
kind: AuthKind::ApiKeyHeader,
config: AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
header_name: "X-Api-Key".to_owned(),
secret_id: SecretId::new(secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
let bearer_secret = service
.create_secret(
&workspace_id,
None,
SecretPayload {
name: "plan-bearer-token".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": "bearer-choice-canary" }),
},
None,
)
.await
.unwrap();
let bearer_profile = service
.create_auth_profile(
&workspace_id,
AuthProfilePayload {
name: "plan-bearer-profile".to_owned(),
kind: AuthKind::Bearer,
config: AuthConfig::Bearer(crank_core::BearerAuthConfig {
header_name: "Authorization".to_owned(),
secret_id: SecretId::new(bearer_secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE_SECURITY))
.await
.unwrap();
assert_eq!(preview.preview.groups[0].operations[0].status, "unresolved");
let selectable = preview
.security_profile_choices
.iter()
.find(|choice| choice.operation_key == "GET /v2/latest" && choice.alternative_index == 0)
.expect("preview must expose choices for supported security alternatives");
assert!(selectable.profiles.iter().any(|choice| {
choice.id == auth_profile.id.as_str() && choice.kind == AuthKind::ApiKeyHeader
}));
assert!(
selectable
.profiles
.iter()
.all(|choice| { choice.id != bearer_profile.id.as_str() })
);
let bearer_choice = preview
.security_profile_choices
.iter()
.find(|choice| choice.operation_key == "GET /v2/latest" && choice.alternative_index == 1)
.expect("preview must expose profile choices for the second OR alternative");
assert!(bearer_choice.profiles.iter().any(|choice| {
choice.id == bearer_profile.id.as_str() && choice.kind == AuthKind::Bearer
}));
assert!(
bearer_choice
.profiles
.iter()
.all(|choice| { choice.id != auth_profile.id.as_str() })
);
let job_id: ImportJobId = preview.job_id.as_str().into();
let mut auth_decision = decision(
"GET /v2/latest",
"create",
None,
None,
Some(auth_profile.id.as_str()),
);
auth_decision.security_alternative_index = Some(0);
let plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload("full", vec![], vec![auth_decision]),
)
.await
.unwrap();
let stored = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
assert_eq!(
stored.payload["candidates"][0]["operation"]["execution_config"]["auth_profile_ref"],
auth_profile.id.as_str()
);
assert_eq!(
stored.payload["candidates"][0]["decision"]["security_alternative_index"],
0
);
// Only the reference survives: no secret material anywhere in the plan.
assert!(!stored.payload.to_string().contains(secret_token));
assert_eq!(
plan.candidates.first().unwrap().auth_profile_id.as_deref(),
Some(auth_profile.id.as_str())
);
let mut bearer_decision = decision(
"GET /v2/latest",
"create",
None,
None,
Some(bearer_profile.id.as_str()),
);
bearer_decision.security_alternative_index = Some(1);
let bearer_plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload("full", vec![], vec![bearer_decision]),
)
.await
.unwrap();
let stored_bearer = registry
.get_import_plan(&workspace_id, &bearer_plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
assert_eq!(
stored_bearer.payload["candidates"][0]["operation"]["execution_config"]["auth_profile_ref"],
bearer_profile.id.as_str()
);
assert_eq!(
stored_bearer.payload["candidates"][0]["decision"]["security_alternative_index"],
1
);
assert!(
!stored_bearer
.payload
.to_string()
.contains("bearer-choice-canary")
);
// An unknown profile reference fails closed in the workspace scope check.
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE_SECURITY))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let error = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"full",
vec![],
vec![decision(
"GET /v2/latest",
"create",
None,
None,
Some("auth_missing_profile"),
)],
),
)
.await
.expect_err("an unknown auth profile reference must be rejected");
assert_error_code(&error, "import_plan_auth_unavailable");
assert_http_status(error, axum::http::StatusCode::UNPROCESSABLE_ENTITY);
// `new_version` without an explicit choice inherits the target's ref.
let existing = service
.create_operation(&workspace_id, {
let mut payload = test_operation_payload(&upstream_base_url, "latest_rates");
payload.execution_config.auth_profile_ref =
Some(AuthProfileId::new(auth_profile.id.as_str()));
payload
})
.await
.expect("an existing operation with the candidate name");
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE_SECURITY))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"full",
vec![],
vec![decision(
"GET /v2/latest",
"new_version",
Some(existing.operation_id.as_str()),
None,
None,
)],
),
)
.await
.unwrap();
let stored = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
let candidate = &stored.payload["candidates"][0];
assert_eq!(
candidate["decision"]["auth_profile_id"],
auth_profile.id.as_str(),
"the inherited target reference is reflected in the candidate summary"
);
assert_eq!(
candidate["operation"]["execution_config"]["auth_profile_ref"],
auth_profile.id.as_str(),
"the inherited target reference must be retained in the snapshot"
);
assert!(!stored.payload.to_string().contains(secret_token));
let public_preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE_PUBLIC))
.await
.unwrap();
let public_job_id: ImportJobId = public_preview.job_id.as_str().into();
let public_plan = service
.create_openapi_import_plan(
&workspace_id,
&public_job_id,
plan_payload(
"full",
vec![],
vec![decision(
"GET /v2/latest",
"new_version",
Some(existing.operation_id.as_str()),
None,
None,
)],
),
)
.await
.expect("a no-security source may inherit the target's existing profile");
let public_stored = registry
.get_import_plan(&workspace_id, &public_plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
assert_eq!(
public_stored.payload["candidates"][0]["auth_requirement"]["kind"], "unconstrained",
"no source security declaration is represented explicitly for transactional Apply"
);
let report = service
.apply_openapi_import_plan(
&workspace_id,
&crank_registry::ImportPlanId::new(public_plan.plan_reference.clone()),
admin_api::service::OpenApiImportPlanApplyPayload {
plan_digest: public_plan.plan_digest.clone(),
idempotency_key: "new-version-inherited-public".to_owned(),
},
)
.await
.expect("Apply must retain profile and Secret transactional validation");
assert_eq!(
report.status,
crank_registry::ImportPlanApplyStatus::Applied
);
assert_eq!(
report.outcomes[0].outcome,
crank_registry::ImportPlanCandidateOutcome::Versioned
);
assert_eq!(report.outcomes[0].version, Some(2));
let operation = service
.list_operations(&workspace_id)
.await
.unwrap()
.into_iter()
.find(|operation| operation.id == existing.operation_id.as_str())
.unwrap();
assert_eq!(operation.current_draft_version, 2);
let explicit_no_auth_preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE_EXPLICIT_NO_AUTH))
.await
.unwrap();
let explicit_no_auth_job_id: ImportJobId = explicit_no_auth_preview.job_id.as_str().into();
let incompatible_profile_decision = decision(
"GET /v2/latest",
"new_version",
Some(existing.operation_id.as_str()),
None,
Some(auth_profile.id.as_str()),
);
let error = service
.create_openapi_import_plan(
&workspace_id,
&explicit_no_auth_job_id,
plan_payload("full", vec![], vec![incompatible_profile_decision]),
)
.await
.expect_err("explicit Auth Profile stays incompatible with security: []");
assert_error_code(&error, "import_plan_auth_incompatible");
let explicit_no_auth_plan = service
.create_openapi_import_plan(
&workspace_id,
&explicit_no_auth_job_id,
plan_payload(
"full",
vec![],
vec![decision(
"GET /v2/latest",
"new_version",
Some(existing.operation_id.as_str()),
None,
None,
)],
),
)
.await
.expect("an explicit empty security requirement clears inherited auth");
let no_auth_stored = registry
.get_import_plan(
&workspace_id,
&explicit_no_auth_plan.plan_reference.as_str().into(),
)
.await
.unwrap()
.unwrap();
assert!(no_auth_stored.payload["candidates"][0]["operation"]["execution_config"]
["auth_profile_ref"]
.is_null());
let no_auth_report = service
.apply_openapi_import_plan(
&workspace_id,
&crank_registry::ImportPlanId::new(explicit_no_auth_plan.plan_reference.clone()),
admin_api::service::OpenApiImportPlanApplyPayload {
plan_digest: explicit_no_auth_plan.plan_digest.clone(),
idempotency_key: "new-version-explicit-no-auth".to_owned(),
},
)
.await
.expect("explicit no-auth new_version applies without inherited credentials");
assert_eq!(
no_auth_report.outcomes[0].outcome,
crank_registry::ImportPlanCandidateOutcome::Versioned
);
assert_eq!(no_auth_report.outcomes[0].version, Some(3));
let operation = service
.list_operations(&workspace_id)
.await
.unwrap()
.into_iter()
.find(|operation| operation.id == existing.operation_id.as_str())
.unwrap();
assert_eq!(operation.current_draft_version, 3);
let operation_id = OperationId::new(existing.operation_id.clone());
let version = registry
.get_operation_version(&workspace_id, &operation_id, 3)
.await
.unwrap()
.unwrap();
assert!(version.snapshot.execution_config.auth_profile_ref.is_none());
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn basic_and_query_profiles_bind_to_matching_security_alternatives_and_apply() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_basic_query_auth"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let username_secret = service
.create_secret(
&workspace_id,
None,
SecretPayload {
name: "basic-username".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": "plan-user" }),
},
None,
)
.await
.unwrap();
let password_secret = service
.create_secret(
&workspace_id,
None,
SecretPayload {
name: "basic-password".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": "plan-password-canary" }),
},
None,
)
.await
.unwrap();
let basic_profile = service
.create_auth_profile(
&workspace_id,
AuthProfilePayload {
name: "basic-profile".to_owned(),
kind: AuthKind::Basic,
config: AuthConfig::Basic(crank_core::BasicAuthConfig {
username_secret_id: SecretId::new(username_secret.id.as_str()),
password_secret_id: SecretId::new(password_secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
let query_secret = service
.create_secret(
&workspace_id,
None,
SecretPayload {
name: "query-key".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": "query-key-canary" }),
},
None,
)
.await
.unwrap();
let query_profile = service
.create_auth_profile(
&workspace_id,
AuthProfilePayload {
name: "query-profile".to_owned(),
kind: AuthKind::ApiKeyQuery,
config: AuthConfig::ApiKeyQuery(crank_core::ApiKeyQueryAuthConfig {
param_name: "access_token".to_owned(),
secret_id: SecretId::new(query_secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
let incompatible_secret = service
.create_secret(
&workspace_id,
None,
SecretPayload {
name: "incompatible-token".to_owned(),
kind: SecretKind::Token,
value: json!({ "token": "incompatible-canary" }),
},
None,
)
.await
.unwrap();
let incompatible_profile = service
.create_auth_profile(
&workspace_id,
AuthProfilePayload {
name: "incompatible-bearer-profile".to_owned(),
kind: AuthKind::Bearer,
config: AuthConfig::Bearer(crank_core::BearerAuthConfig {
header_name: "Authorization".to_owned(),
secret_id: SecretId::new(incompatible_secret.id.as_str()),
}),
},
None,
)
.await
.unwrap();
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_BASIC_AND_QUERY_SECURITY))
.await
.unwrap();
for operation_key in ["GET /v2/basic", "GET /v2/query"] {
let basic_alternative = preview
.security_profile_choices
.iter()
.find(|choice| choice.operation_key == operation_key && choice.alternative_index == 0)
.expect("Basic alternative must be represented in preview");
assert!(basic_alternative.profiles.iter().any(|choice| {
choice.id == basic_profile.id.as_str() && choice.kind == AuthKind::Basic
}));
assert!(
basic_alternative
.profiles
.iter()
.all(|choice| choice.id != query_profile.id.as_str())
);
assert!(
basic_alternative
.profiles
.iter()
.all(|choice| choice.id != incompatible_profile.id.as_str())
);
let query_alternative = preview
.security_profile_choices
.iter()
.find(|choice| choice.operation_key == operation_key && choice.alternative_index == 1)
.expect("query alternative must be represented in preview");
assert!(query_alternative.profiles.iter().any(|choice| {
choice.id == query_profile.id.as_str() && choice.kind == AuthKind::ApiKeyQuery
}));
assert!(
query_alternative
.profiles
.iter()
.all(|choice| choice.id != basic_profile.id.as_str())
);
assert!(
query_alternative
.profiles
.iter()
.all(|choice| choice.id != incompatible_profile.id.as_str())
);
}
let job_id: ImportJobId = preview.job_id.as_str().into();
let mut basic_decision = decision(
"GET /v2/basic",
"create",
None,
None,
Some(basic_profile.id.as_str()),
);
basic_decision.security_alternative_index = Some(0);
let basic_plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"partial",
vec!["GET /v2/basic".to_owned()],
vec![basic_decision],
),
)
.await
.unwrap();
assert_eq!(basic_plan.counts.actionable, 1);
let basic_candidate = basic_plan
.candidates
.iter()
.find(|candidate| candidate.key == "GET /v2/basic")
.unwrap();
assert_eq!(
basic_candidate.auth_profile_id.as_deref(),
Some(basic_profile.id.as_str())
);
let mut query_decision = decision(
"GET /v2/query",
"create",
None,
None,
Some(query_profile.id.as_str()),
);
query_decision.security_alternative_index = Some(1);
let query_plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"partial",
vec!["GET /v2/query".to_owned()],
vec![query_decision.clone()],
),
)
.await
.unwrap();
assert_eq!(query_plan.counts.actionable, 1);
let query_candidate = query_plan
.candidates
.iter()
.find(|candidate| candidate.key == "GET /v2/query")
.unwrap();
assert_eq!(
query_candidate.auth_profile_id.as_deref(),
Some(query_profile.id.as_str())
);
for (index, (plan, expected_profile, idempotency_key)) in [
(
&basic_plan,
basic_profile.id.as_str(),
"apply-basic-profile",
),
(
&query_plan,
query_profile.id.as_str(),
"apply-query-profile",
),
]
.into_iter()
.enumerate()
{
let fresh_plan;
let plan = if index == 1 {
let stale = service
.apply_openapi_import_plan(
&workspace_id,
&crank_registry::ImportPlanId::new(plan.plan_reference.clone()),
admin_api::service::OpenApiImportPlanApplyPayload {
plan_digest: plan.plan_digest.clone(),
idempotency_key: "stale-query-profile".to_owned(),
},
)
.await
.expect_err("the earlier query plan is stale after catalog mutation");
assert_error_code(&stale, "import_plan_fingerprint_stale");
let refreshed = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_BASIC_AND_QUERY_SECURITY))
.await
.unwrap();
fresh_plan = service
.create_openapi_import_plan(
&workspace_id,
&refreshed.job_id.as_str().into(),
plan_payload(
"partial",
vec!["GET /v2/query".to_owned()],
vec![query_decision.clone()],
),
)
.await
.unwrap();
&fresh_plan
} else {
plan
};
let report = service
.apply_openapi_import_plan(
&workspace_id,
&crank_registry::ImportPlanId::new(plan.plan_reference.clone()),
admin_api::service::OpenApiImportPlanApplyPayload {
plan_digest: plan.plan_digest.clone(),
idempotency_key: idempotency_key.to_owned(),
},
)
.await
.unwrap();
assert_eq!(
report.status,
crank_registry::ImportPlanApplyStatus::Applied
);
let operation_id = OperationId::new(report.outcomes[0].operation_id.clone().unwrap());
let version = registry
.get_operation_version(&workspace_id, &operation_id, 1)
.await
.unwrap()
.unwrap();
assert_eq!(
version
.snapshot
.execution_config
.auth_profile_ref
.as_ref()
.map(|profile_id| profile_id.as_str()),
Some(expected_profile)
);
}
let basic_stored = registry
.get_import_plan(&workspace_id, &basic_plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
assert!(
!basic_stored
.payload
.to_string()
.contains("plan-password-canary")
);
let query_stored = registry
.get_import_plan(&workspace_id, &query_plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
assert!(
!query_stored
.payload
.to_string()
.contains("query-key-canary")
);
}
@@ -0,0 +1,350 @@
use super::*;
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn preview_rejects_candidate_2001_without_truncation_or_operations() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_preview_candidate_limit"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace = WorkspaceId::new("ws_default");
let mut document = String::from(
"openapi: 3.0.3\ninfo: { title: Limit }\nservers: [{ url: https://api.example.test }]\npaths:\n",
);
for index in 0..2001 {
document.push_str(&format!(" /p{index}:\n get:\n operationId: op{index}\n responses: {{ '200': {{ description: ok }} }}\n"));
}
let error = service
.preview_openapi_import(&workspace, upload(&document))
.await
.expect_err("candidate 2001 must be rejected as a whole");
assert_error_code(&error, "openapi_preview_too_many_candidates");
assert!(
service
.list_operations(&workspace)
.await
.unwrap()
.is_empty()
);
let active_sources: i64 = sqlx::query_scalar(
"select count(*) from artifact_sources where workspace_id = $1 and lifecycle = 'active'",
)
.bind(workspace.as_str())
.fetch_one(registry.pool())
.await
.unwrap();
assert_eq!(active_sources, 0);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn partial_plan_rejects_selected_blocker_before_persistence() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_partial_blocker"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_GLOBAL_BLOCKER))
.await
.unwrap();
assert_eq!(preview.preview.groups[0].operations[0].status, "blocked");
let job_id: ImportJobId = preview.job_id.as_str().into();
let key = preview.preview.groups[0].operations[0].key.clone();
let error = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload("partial", vec![key], vec![]),
)
.await
.expect_err("blocked partial selection must be rejected");
assert_error_code(&error, "import_plan_partial_blocked");
assert!(
service
.list_operations(&workspace_id)
.await
.unwrap()
.is_empty()
);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn explicit_targets_are_checked_even_when_the_candidate_is_blocked() {
let registry = test_registry().await;
let upstream_base_url = spawn_upstream_server().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_blocked_target"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_GLOBAL_BLOCKER))
.await
.unwrap();
let blocker_code = preview
.preview
.findings
.iter()
.find(|finding| finding.severity == crank_import::rest::ImportFindingSeverity::Error)
.map(|finding| finding.code.clone())
.expect("the fixture produces a global error finding");
let candidate = &preview.preview.groups[0].operations[0];
let job_id: ImportJobId = preview.job_id.as_str().into();
// A mismatched/unknown explicit target is a request error even though
// the candidate is already blocked by the preview.
let error = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"full",
vec![],
vec![decision(
&candidate.key,
"skip",
Some("op_does_not_exist"),
None,
None,
)],
),
)
.await
.expect_err("an unknown target is a request error even for a blocked candidate");
assert_error_code(&error, "import_plan_target_invalid");
assert_http_status(error, axum::http::StatusCode::BAD_REQUEST);
// A resolvable exact target is recorded while the candidate stays
// blocked with its bounded redacted reason.
let existing = service
.create_operation(
&workspace_id,
test_operation_payload(&upstream_base_url, &candidate.draft.name),
)
.await
.unwrap();
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_GLOBAL_BLOCKER))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"full",
vec![],
vec![decision(
&candidate.key,
"skip",
Some(existing.operation_id.as_str()),
None,
None,
)],
),
)
.await
.expect("a valid explicit target is accepted for a blocked candidate");
let stored = registry
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
.await
.unwrap()
.unwrap();
let candidate = &stored.payload["candidates"][0];
assert_eq!(candidate["state"], "blocked");
assert_eq!(candidate["reason"], blocker_code);
assert_eq!(
candidate["target"]["operation_id"],
json!(existing.operation_id)
);
assert!(
candidate.get("operation").is_none(),
"a blocked candidate never stores draft material"
);
assert!(service.list_operations(&workspace_id).await.unwrap().len() <= 1);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn archived_rest_target_cannot_be_planned_for_new_version() {
let registry = test_registry().await;
let upstream_base_url = spawn_upstream_server().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_plan_archived_target"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let existing = service
.create_operation(
&workspace_id,
test_operation_payload(&upstream_base_url, "latest_rates"),
)
.await
.unwrap();
registry
.archive_operation(
&workspace_id,
&OperationId::new(existing.operation_id.clone()),
&time::OffsetDateTime::now_utc(),
)
.await
.unwrap();
let preview = service
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let error = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
plan_payload(
"full",
vec![],
vec![decision(
"GET /v2/latest",
"new_version",
Some(existing.operation_id.as_str()),
None,
None,
)],
),
)
.await
.expect_err("archived target cannot accept a new Draft Version");
assert_error_code(&error, "import_plan_target_invalid");
assert_http_status(error, axum::http::StatusCode::BAD_REQUEST);
}
#[tokio::test(flavor = "multi_thread")]
#[serial]
async fn detached_dependency_snapshot_repreview_requires_without_a_plan() {
let app = axum::Router::new().route(
"/schema.yaml",
axum::routing::get(|| async {
"Result: { type: object, properties: { id: { type: string } } }"
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
let origin = format!("http://{address}");
let registry = test_registry().await;
let service = test_service_with_external_references(
registry.clone(),
test_storage_root("openapi_import_plan_dependency_stale"),
vec![format!("{origin}/")],
);
let workspace_id = WorkspaceId::new("ws_default");
let upload = OpenApiUpload {
bytes: format!(
r#"
openapi: 3.1.0
info: {{ title: External dependency }}
servers: [{{ url: https://api.example.test }}]
paths:
/items:
get:
operationId: listItems
responses:
'200':
description: ok
content:
application/json:
schema: {{ $ref: '{origin}/schema.yaml#/Result' }}
"#
)
.into_bytes(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
};
let preview = service
.preview_openapi_import(&workspace_id, upload)
.await
.unwrap();
let job_id: ImportJobId = preview.job_id.as_str().into();
let job = registry
.get_import_job(&workspace_id, &job_id)
.await
.unwrap()
.unwrap();
let dependency_sources = job.preview_payload["dependencies"]
.as_array()
.cloned()
.unwrap();
assert!(
!dependency_sources.is_empty(),
"fixture must create a dependency"
);
// The plan is creatable while the stored snapshot is still active.
let fresh = service
.create_openapi_import_plan(&workspace_id, &job_id, plan_payload("full", vec![], vec![]))
.await
.expect("an active dependency snapshot must not block planning");
assert_eq!(
registry
.get_import_plan(&workspace_id, &fresh.plan_reference.as_str().into())
.await
.unwrap()
.unwrap()
.payload["dependencies"]
.as_array()
.unwrap()
.len(),
dependency_sources.len()
);
// Detach one stored snapshot: the same job now requires re-preview and
// no plan is created; the legacy job itself stays untouched.
let victim = &dependency_sources[0];
sqlx::query(
"update artifact_sources
set lifecycle = 'detached', updated_at = now(), detached_at = now()
where workspace_id = $1 and source_id = $2",
)
.bind(workspace_id.as_str())
.bind(victim["source_id"].as_str().unwrap())
.execute(registry.pool())
.await
.unwrap();
let error = service
.create_openapi_import_plan(&workspace_id, &job_id, plan_payload("full", vec![], vec![]))
.await
.expect_err("a detached dependency snapshot is re-preview material");
assert_error_code(&error, "import_dependency_verification_failed");
let context = public_error_context(&error).cloned().unwrap();
assert_eq!(context["repreview_required"], json!(true));
assert_http_status(error, axum::http::StatusCode::CONFLICT);
let job = registry
.get_import_job(&workspace_id, &job_id)
.await
.unwrap()
.unwrap();
assert_eq!(job.status, ImportJobStatus::Pending);
assert_eq!(job.error_text, None);
assert!(job.finished_at.is_none());
assert!(
service
.list_operations(&workspace_id)
.await
.unwrap()
.is_empty()
);
}
@@ -0,0 +1,142 @@
use super::*;
use admin_api::service::OpenApiImportPlanCreatePayload;
use std::fmt::Write as _;
const OPERATION_COUNT: usize = 2_000;
const MAX_UPLOAD_BYTES: usize = 256 * 1024;
const MAX_STORED_PLAN_BYTES: usize = 16 * 1024 * 1024;
fn large_openapi_document() -> String {
let mut document = String::from(
"openapi: 3.0.3\n\
info: { title: Large preview, version: '1' }\n\
servers: [{ url: 'https://api.example.test' }]\n\
paths:\n",
);
for index in 0..OPERATION_COUNT {
writeln!(
document,
" /p{index:04}:\n get:\n operationId: o{index:04}\n responses: {{ '200': {{ description: ok }} }}"
)
.unwrap();
}
document
}
#[tokio::test]
#[serial]
async fn previews_and_plans_two_thousand_operations_without_catalog_mutation() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_large_preview"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let document = large_openapi_document();
assert!(
document.len() <= MAX_UPLOAD_BYTES,
"generated document is {} bytes, over the 256 KiB upload limit",
document.len()
);
let preview = service
.preview_openapi_import(
&workspace_id,
OpenApiUpload {
bytes: document.into_bytes(),
mime_type: "application/yaml".to_owned(),
locale: OpenApiUploadLocale::En,
},
)
.await
.expect("valid 2,000-operation OpenAPI document should preview");
let preview_candidates = preview
.preview
.groups
.iter()
.flat_map(|group| &group.operations)
.collect::<Vec<_>>();
assert_eq!(preview_candidates.len(), OPERATION_COUNT);
assert_eq!(preview_candidates[0].key, "GET /p0000");
assert_eq!(preview_candidates[OPERATION_COUNT - 1].key, "GET /p1999");
assert!(preview_candidates.iter().all(|candidate| {
candidate.status == "actionable"
&& candidate.method == crank_core::HttpMethod::Get
&& candidate.path.starts_with("/p")
}));
let job_id: crank_registry::ImportJobId = preview.job_id.as_str().into();
let plan = service
.create_openapi_import_plan(
&workspace_id,
&job_id,
OpenApiImportPlanCreatePayload {
selection_mode: "full".to_owned(),
selected_operation_keys: Vec::new(),
server_url: None,
decisions: Vec::new(),
},
)
.await
.expect("full plan should include all 2,000 operations");
assert_eq!(plan.counts.selected, OPERATION_COUNT);
assert_eq!(plan.counts.actionable, OPERATION_COUNT);
assert_eq!(plan.counts.excluded, 0);
assert_eq!(plan.counts.blocked, 0);
assert_eq!(plan.candidates.len(), OPERATION_COUNT);
assert!(plan.candidates.iter().all(|candidate| {
candidate.state == "actionable" && candidate.action.as_deref() == Some("create")
}));
let plan_id = plan.plan_reference.as_str().into();
let stored = registry
.get_import_plan(&workspace_id, &plan_id)
.await
.unwrap()
.expect("full plan should be persisted and readable");
let stored_payload_bytes = serde_json::to_vec(&stored.payload).unwrap().len();
assert!(
stored_payload_bytes <= MAX_STORED_PLAN_BYTES,
"stored plan payload is {stored_payload_bytes} bytes, over 16 MiB"
);
let stored_candidates = stored.payload["candidates"]
.as_array()
.expect("stored plan contains its full candidate list");
assert_eq!(stored_candidates.len(), OPERATION_COUNT);
assert!(stored_candidates.iter().all(|candidate| {
candidate["state"] == "actionable" && candidate["decision"]["action"] == "create"
}));
assert_eq!(stored.payload["counts"]["selected"], OPERATION_COUNT);
assert_eq!(stored.payload["counts"]["actionable"], OPERATION_COUNT);
let revalidated = service
.revalidate_openapi_import_plan(&workspace_id, &plan_id)
.await
.expect("revalidating the unchanged plan should be read-only and current");
assert_eq!(revalidated.revalidation_status, "current");
assert!(!revalidated.revalidation_required);
assert_eq!(revalidated.counts.selected, OPERATION_COUNT);
assert_eq!(revalidated.counts.actionable, OPERATION_COUNT);
assert_eq!(revalidated.counts.excluded, 0);
assert_eq!(revalidated.counts.blocked, 0);
assert_eq!(revalidated.candidates.len(), OPERATION_COUNT);
let (operations, operation_versions) = sqlx::query_as::<_, (i64, i64)>(
"select
(select count(*) from operations where workspace_id = $1),
(select count(*) from operation_versions ov
join operations o on o.id = ov.operation_id where o.workspace_id = $1)",
)
.bind(workspace_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap();
assert_eq!(operations, 0, "preview and plan must not create operations");
assert_eq!(
operation_versions, 0,
"preview and plan must not create operation versions"
);
}
@@ -1,659 +0,0 @@
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
}
@@ -0,0 +1,262 @@
use super::*;
use admin_api::error::ApiError;
use crank_artifacts::MAX_ARTIFACT_BYTES;
use crank_core::HttpMethod;
#[derive(Debug, PartialEq, Eq)]
struct CatalogCounts {
operations: i64,
operation_versions: i64,
auth_profiles: i64,
agent_operation_bindings: i64,
}
async fn catalog_counts(
registry: &crank_registry::PostgresRegistry,
workspace_id: &WorkspaceId,
) -> CatalogCounts {
let (operations, operation_versions, auth_profiles, agent_operation_bindings) =
sqlx::query_as::<_, (i64, i64, i64, i64)>(
"select
(select count(*) from operations where workspace_id = $1),
(select count(*) from operation_versions ov
join operations o on o.id = ov.operation_id where o.workspace_id = $1),
(select count(*) from auth_profiles where workspace_id = $1),
(select count(*) from agent_operation_bindings b
join operations o on o.id = b.operation_id where o.workspace_id = $1)",
)
.bind(workspace_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap();
CatalogCounts {
operations,
operation_versions,
auth_profiles,
agent_operation_bindings,
}
}
fn upload(bytes: Vec<u8>) -> OpenApiUpload {
OpenApiUpload {
bytes,
mime_type: "application/json".to_owned(),
locale: OpenApiUploadLocale::En,
}
}
const PREVIEWABLE_DOCUMENT: &[u8] = br#"{
"openapi":"3.0.3",
"info":{"title":"Preview lifecycle","version":"1"},
"paths":{"/ready":{"get":{"responses":{"200":{"description":"ok"}}}}}
}"#;
async fn insert_malformed_auth_profile(
registry: &crank_registry::PostgresRegistry,
workspace_id: &WorkspaceId,
) {
sqlx::query(
"insert into auth_profiles
(id, workspace_id, name, kind, config_json, created_at, updated_at)
values ('auth_decode_failure', $1, 'decode-failure', 'bearer', 'null'::jsonb, now(), now())",
)
.bind(workspace_id.as_str())
.execute(registry.pool())
.await
.unwrap();
}
async fn insert_catalog_overflow(
registry: &crank_registry::PostgresRegistry,
workspace_id: &WorkspaceId,
) {
sqlx::query(
"insert into operations
(id, workspace_id, name, display_name, protocol, status, created_at, updated_at)
select 'op_catalog_' || g, $1, 'catalog_op_' || g, 'Catalog Op ' || g,
'rest', 'draft', now(), now()
from generate_series(1, 10001) as g",
)
.bind(workspace_id.as_str())
.execute(registry.pool())
.await
.unwrap();
}
async fn durable_import_jobs(
registry: &crank_registry::PostgresRegistry,
workspace_id: &WorkspaceId,
) -> i64 {
sqlx::query_scalar("select count(*) from import_jobs where workspace_id = $1")
.bind(workspace_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap()
}
async fn active_artifact_sources(
registry: &crank_registry::PostgresRegistry,
workspace_id: &WorkspaceId,
) -> i64 {
sqlx::query_scalar(
"select count(*) from artifact_sources where workspace_id = $1 and lifecycle = 'active'",
)
.bind(workspace_id.as_str())
.fetch_one(registry.pool())
.await
.unwrap()
}
fn assert_upload_error(error: ApiError, variant: &str, code: &str) {
let context = match (variant, error) {
("validation", ApiError::Validation { context, .. }) => context,
("payload_too_large", ApiError::PayloadTooLarge { context, .. }) => context,
(expected, actual) => panic!("expected {expected} error, got {actual:?}"),
}
.expect("OpenAPI upload errors carry a machine-readable code");
assert_eq!(context["error_code"], format!("openapi_upload.{code}"));
}
#[tokio::test]
#[serial]
async fn preview_outcomes_do_not_mutate_operation_catalog() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_upload_outcomes"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let before = catalog_counts(&registry, &workspace_id).await;
let preview = service
.preview_openapi_import(
&workspace_id,
upload(
br#"{
"openapi":"3.0.3",
"info":{"title":"Upload outcomes","version":"1"},
"paths":{"/ready":{"get":{"responses":{"200":{"description":"ok"}}}}}
}"#
.to_vec(),
),
)
.await
.expect("valid OpenAPI document should return a preview");
let candidates = preview
.preview
.groups
.iter()
.flat_map(|group| &group.operations)
.collect::<Vec<_>>();
assert_eq!(candidates.len(), 1);
assert_eq!(candidates[0].method, HttpMethod::Get);
assert_eq!(candidates[0].path, "/ready");
assert_eq!(candidates[0].key, "GET /ready");
assert_eq!(catalog_counts(&registry, &workspace_id).await, before);
let before = catalog_counts(&registry, &workspace_id).await;
let error = service
.preview_openapi_import(&workspace_id, upload(Vec::new()))
.await
.expect_err("empty upload should be rejected");
assert_upload_error(error, "validation", "empty_file");
assert_eq!(catalog_counts(&registry, &workspace_id).await, before);
let before = catalog_counts(&registry, &workspace_id).await;
let error = service
.preview_openapi_import(&workspace_id, upload(b"{".to_vec()))
.await
.expect_err("malformed OpenAPI document should be rejected");
assert_upload_error(error, "validation", "invalid_document");
assert_eq!(catalog_counts(&registry, &workspace_id).await, before);
let before = catalog_counts(&registry, &workspace_id).await;
let error = service
.preview_openapi_import(&workspace_id, upload(vec![b' '; MAX_ARTIFACT_BYTES + 1]))
.await
.expect_err("oversized upload should be rejected");
assert_upload_error(error, "payload_too_large", "file_too_large");
assert_eq!(catalog_counts(&registry, &workspace_id).await, before);
let before = catalog_counts(&registry, &workspace_id).await;
let error = service
.preview_openapi_import(
&workspace_id,
upload(
br#"{
"openapi":"3.0.3",
"info":{"title":"No methods","version":"1"},
"paths":{}
}"#
.to_vec(),
),
)
.await
.expect_err("document without supported methods should be rejected");
assert_upload_error(error, "validation", "no_methods");
assert_eq!(catalog_counts(&registry, &workspace_id).await, before);
}
#[tokio::test]
#[serial]
async fn preview_profile_decode_failure_leaves_no_pending_job_or_source() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_upload_profile_decode_failure"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
insert_malformed_auth_profile(&registry, &workspace_id).await;
service
.preview_openapi_import(&workspace_id, upload(PREVIEWABLE_DOCUMENT.to_vec()))
.await
.expect_err("malformed auth profile must fail preview enrichment");
assert_eq!(
durable_import_jobs(&registry, &workspace_id).await,
0,
"profile lookup failure must not leave a durable import job"
);
assert_eq!(
active_artifact_sources(&registry, &workspace_id).await,
0,
"profile lookup failure must not leave attached sources"
);
}
#[tokio::test]
#[serial]
async fn preview_catalog_limit_failure_leaves_no_pending_job_or_source() {
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_upload_catalog_limit_failure"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
insert_catalog_overflow(&registry, &workspace_id).await;
service
.preview_openapi_import(&workspace_id, upload(PREVIEWABLE_DOCUMENT.to_vec()))
.await
.expect_err("catalog over the import limit must fail preview enrichment");
assert_eq!(
durable_import_jobs(&registry, &workspace_id).await,
0,
"catalog lookup failure must not leave a durable import job"
);
assert_eq!(
active_artifact_sources(&registry, &workspace_id).await,
0,
"catalog lookup failure must not leave attached sources"
);
}
@@ -0,0 +1,93 @@
use super::*;
#[tokio::test]
#[serial]
async fn exact_v5_contract_replays_saved_preview_without_source_locations() {
use sha2::{Digest, Sha256};
fn remove_source_locations(value: &mut serde_json::Value) {
match value {
serde_json::Value::Object(object) => {
object.remove("source_location");
for value in object.values_mut() {
remove_source_locations(value);
}
}
serde_json::Value::Array(values) => {
for value in values {
remove_source_locations(value);
}
}
_ => {}
}
}
let registry = test_registry().await;
let service = test_service(
registry.clone(),
test_storage_root("openapi_import_v5_compatibility"),
test_auth_settings(),
test_secret_crypto(),
);
let workspace_id = WorkspaceId::new("ws_default");
let preview = service
.preview_openapi_import(&workspace_id, openapi_upload())
.await
.unwrap();
let job_id: crank_registry::ImportJobId = preview.job_id.as_str().into();
let mut payload = registry
.get_import_job(&workspace_id, &job_id)
.await
.unwrap()
.unwrap()
.preview_payload;
// A preview persisted under v5 has the then-current projection and digest,
// without the source_location fields added by v6.
let persisted_preview = payload
.get_mut("preview")
.expect("newly saved job includes its preview");
assert!(persisted_preview.to_string().contains("source_location"));
remove_source_locations(persisted_preview);
let digest = format!(
"{:x}",
Sha256::digest(serde_json::to_vec(persisted_preview).unwrap())
);
payload["normalization"]["normalizer_version"] = "normalized-ir-v5".into();
payload["normalization"]["projection_version"] = "preview-v5".into();
payload["normalization"]["config"]["normalizer_version"] = "normalized-ir-v5".into();
payload["normalization"]["config"]["projection_version"] = "preview-v5".into();
payload["preview_digest"] = digest.into();
// If v5 is reparsed, this deliberately absent dependency makes the replay fail.
payload["dependency_snapshots"] = serde_json::json!([{
"source_id": "src_openapi_dep_v5_must_not_be_read",
"digest": format!("sha256:{}", "0".repeat(64)),
"canonical_uri": "https://schemas.example.test/v5.yaml"
}]);
sqlx::query("update import_jobs set preview_payload = $1::jsonb where id = $2")
.bind(serde_json::to_string(&payload).unwrap())
.bind(job_id.as_str())
.execute(registry.pool())
.await
.unwrap();
let result = service
.create_openapi_import(
&workspace_id,
&job_id,
OpenApiImportCreatePayload {
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
server_url: Some("https://api.frankfurter.dev".to_owned()),
conflict_mode: "skip".to_owned(),
},
)
.await
.unwrap();
assert_eq!(result.created.len(), 1);
let completed = registry
.get_import_job(&workspace_id, &job_id)
.await
.unwrap()
.unwrap();
assert_eq!(completed.status, ImportJobStatus::Completed);
}