story 2-10-security-schemes-secrets: implemented and reviewed via bmad-loop
This commit is contained in:
1 parent
f5f40cb167
commit
ecfb4e788f
45 files changed
+6025
-829
No files matched your search
@@ -14,6 +14,115 @@ mod http_contract;
|
||||
mod import_plan_apply;
|
||||
mod import_plan_create;
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn upload_rejects_credential_literals_before_persisting_source_artifacts() {
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("openapi_import_storage_redaction");
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
storage_root,
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let upload = OpenApiUpload {
|
||||
bytes: br#"{
|
||||
"openapi":"3.0.3",
|
||||
"info":{"title":"Redaction persistence","version":"1"},
|
||||
"servers":[{"url":"https://bare-canary@api.example.test/v1?api_key=query-canary"}],
|
||||
"components":{"securitySchemes":{"key":{"type":"apiKey","in":"header","name":"X-Api-Key"}}},
|
||||
"paths":{"/private":{"get":{
|
||||
"operationId":"privateOperation",
|
||||
"parameters":[{"name":"X-Api-Key","in":"header","example":"opaque-canary-42"}],
|
||||
"responses":{"200":{"description":"ok"}},
|
||||
"x-client-secret":true
|
||||
}}}
|
||||
}"#
|
||||
.to_vec(),
|
||||
mime_type: "application/json".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
};
|
||||
let error = service
|
||||
.preview_openapi_import(&workspace_id, upload)
|
||||
.await
|
||||
.expect_err("credential-bearing uploads must be rejected before persistence");
|
||||
let rendered_error = format!("{error:?}");
|
||||
assert!(
|
||||
rendered_error.contains("invalid_document"),
|
||||
"unexpected typed error: {rendered_error}"
|
||||
);
|
||||
for canary in ["bare-canary", "query-canary", "opaque-canary-42"] {
|
||||
assert!(
|
||||
!rendered_error.contains(canary),
|
||||
"API error leaked {canary}"
|
||||
);
|
||||
}
|
||||
let source_count: i64 =
|
||||
sqlx::query_scalar("select count(*) from artifact_sources where workspace_id = $1")
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(source_count, 0, "unsafe upload created an artifact source");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn legacy_apply_rejects_required_auth_without_binding_before_creating_draft() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_unresolved_auth"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let upload = OpenApiUpload {
|
||||
bytes: br#"{
|
||||
"openapi":"3.0.3",
|
||||
"info":{"title":"Required auth","version":"1"},
|
||||
"servers":[{"url":"https://api.example.test"}],
|
||||
"components":{"securitySchemes":{"bearer":{"type":"http","scheme":"bearer"}}},
|
||||
"security":[{"bearer":[]}],
|
||||
"paths":{"/secure":{"get":{"operationId":"secureOperation","responses":{"200":{"description":"ok"}}}}}
|
||||
}"#
|
||||
.to_vec(),
|
||||
mime_type: "application/json".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
};
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload)
|
||||
.await
|
||||
.unwrap();
|
||||
let result = service
|
||||
.create_openapi_import(
|
||||
&workspace_id,
|
||||
&preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /secure".to_owned()],
|
||||
server_url: None,
|
||||
conflict_mode: "rename".to_owned(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let error = result.expect_err("legacy apply cannot bypass unresolved required auth");
|
||||
assert!(format!("{error:?}").contains("invalid_document"));
|
||||
assert!(
|
||||
service
|
||||
.list_operations(&workspace_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
let job = registry
|
||||
.get_import_job(&workspace_id, &preview.job_id.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(job.status, ImportJobStatus::Failed);
|
||||
}
|
||||
|
||||
const OPENAPI3: &str = r#"
|
||||
openapi: 3.0.3
|
||||
info:
|
||||
@@ -80,11 +189,11 @@ async fn previews_openapi_and_creates_draft_operations() {
|
||||
assert_eq!(preview_job.status, ImportJobStatus::Pending);
|
||||
assert_eq!(
|
||||
preview_job.preview_payload["normalization"]["normalizer_version"],
|
||||
"normalized-ir-v4"
|
||||
crank_import::rest::NORMALIZER_VERSION
|
||||
);
|
||||
assert_eq!(
|
||||
preview_job.preview_payload["normalization"]["projection_version"],
|
||||
"preview-v4"
|
||||
crank_import::rest::PROJECTION_VERSION
|
||||
);
|
||||
assert!(preview_job.preview_payload["normalization"]["ir_fingerprint"].is_string());
|
||||
|
||||
|
||||
@@ -1,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;
|
||||
@@ -105,6 +109,7 @@ paths:
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
server.abort();
|
||||
assert_eq!(applied.created.len(), 1);
|
||||
assert_eq!(fetches.load(Ordering::SeqCst), 2);
|
||||
let active_sources: i64 = sqlx::query_scalar(
|
||||
@@ -117,6 +122,115 @@ paths:
|
||||
assert_eq!(active_sources, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn external_secret_document_is_rejected_before_blob_registration() {
|
||||
let external_document = "Item: { type: object, x-api-key: external-secret-canary-42, properties: { id: { type: string } } }";
|
||||
let fetched = Arc::new(AtomicUsize::new(0));
|
||||
let fetch_count = Arc::clone(&fetched);
|
||||
let app = Router::new().route(
|
||||
"/schemas.yaml",
|
||||
get(move || {
|
||||
let fetch_count = Arc::clone(&fetch_count);
|
||||
async move {
|
||||
fetch_count.fetch_add(1, Ordering::SeqCst);
|
||||
external_document
|
||||
}
|
||||
}),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
let origin = format!("http://{address}");
|
||||
let registry = test_registry().await;
|
||||
let storage_root = test_storage_root("openapi_import_external_secret_rejected");
|
||||
let service = test_service_with_external_references(
|
||||
registry.clone(),
|
||||
storage_root.clone(),
|
||||
vec![format!("{origin}/")],
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let error = service
|
||||
.preview_openapi_import(
|
||||
&workspace_id,
|
||||
OpenApiUpload {
|
||||
bytes: format!(
|
||||
r#"
|
||||
openapi: 3.1.0
|
||||
info: {{ title: Safe primary with unsafe external }}
|
||||
servers: [{{ url: https://api.example.test }}]
|
||||
paths:
|
||||
/items:
|
||||
get:
|
||||
operationId: listItems
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content: {{ application/json: {{ schema: {{ $ref: '{origin}/schemas.yaml#/Item' }} }} }}
|
||||
"#
|
||||
)
|
||||
.into_bytes(),
|
||||
mime_type: "application/yaml".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect_err("unsafe external bundle must be rejected before source persistence");
|
||||
server.abort();
|
||||
assert_eq!(fetched.load(Ordering::SeqCst), 1);
|
||||
let rendered_error = format!("{error:?}");
|
||||
assert!(rendered_error.contains("invalid_document"));
|
||||
assert!(!rendered_error.contains("external-secret-canary-42"));
|
||||
|
||||
// The raw dependency's content-addressed path must not exist even as an
|
||||
// unregistered blob, and no other stored file may contain its literal.
|
||||
let external_digest = format!("{:x}", Sha256::digest(external_document.as_bytes()));
|
||||
let external_blob = storage_root
|
||||
.join("sha256")
|
||||
.join(&external_digest[..2])
|
||||
.join(&external_digest);
|
||||
assert!(
|
||||
!external_blob.exists(),
|
||||
"secret-bearing external response was written to the artifact store"
|
||||
);
|
||||
assert!(!storage_contains_literal(
|
||||
&storage_root,
|
||||
b"external-secret-canary-42"
|
||||
));
|
||||
|
||||
let dependency_sources: i64 = sqlx::query_scalar(
|
||||
"select count(*) from artifact_sources
|
||||
where workspace_id = $1 and source_id like 'src_openapi_dep_%'",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(dependency_sources, 0);
|
||||
let active_sources: i64 = sqlx::query_scalar(
|
||||
"select count(*) from artifact_sources where workspace_id = $1 and lifecycle = 'active'",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(active_sources, 0);
|
||||
}
|
||||
|
||||
fn storage_contains_literal(root: &std::path::Path, literal: &[u8]) -> bool {
|
||||
std::fs::read_dir(root).unwrap().any(|entry| {
|
||||
let path = entry.unwrap().path();
|
||||
if path.is_dir() {
|
||||
storage_contains_literal(&path, literal)
|
||||
} else {
|
||||
std::fs::read(path)
|
||||
.unwrap()
|
||||
.windows(literal.len())
|
||||
.any(|window| window == literal)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn missing_external_snapshot_fails_closed_before_draft_mutation() {
|
||||
@@ -316,7 +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;
|
||||
@@ -368,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
|
||||
@@ -403,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]
|
||||
@@ -606,3 +724,90 @@ async fn exact_v3_contract_replays_persisted_preview_without_v4_or_dependency_re
|
||||
.unwrap();
|
||||
assert_eq!(completed.status, ImportJobStatus::Completed);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn exact_v4_security_contract_replays_its_persisted_security_classification() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_v4_security_compatibility"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let upload = OpenApiUpload {
|
||||
bytes: br#"{
|
||||
"openapi":"3.0.3",
|
||||
"info":{"title":"Historical security","version":"1"},
|
||||
"servers":[{"url":"https://api.example.test"}],
|
||||
"components":{"securitySchemes":{"basic":{"type":"http","scheme":"basic"}}},
|
||||
"security":[{"basic":[]}],
|
||||
"paths":{
|
||||
"/secure":{"get":{"operationId":"secure","responses":{"200":{"description":"ok"}}}},
|
||||
"/public":{"get":{"operationId":"public","security":[],"responses":{"200":{"description":"ok"}}}}
|
||||
}
|
||||
}"#
|
||||
.to_vec(),
|
||||
mime_type: "application/json".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
};
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload)
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: crank_registry::ImportJobId = preview.job_id.as_str().into();
|
||||
let job = registry
|
||||
.get_import_job(&workspace_id, &job_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
// Keep the genuine baseline-v4 normalization/projection, preview and digest intact.
|
||||
// Only bind its source envelope to this test's newly registered immutable source blob.
|
||||
let mut payload: serde_json::Value =
|
||||
serde_json::from_str(BASELINE_V4_SECURITY_PREVIEW_PAYLOAD).unwrap();
|
||||
assert_eq!(
|
||||
payload.pointer("/source/digest"),
|
||||
job.preview_payload.pointer("/source/digest"),
|
||||
"baseline fixture must refer to the exact uploaded source bytes",
|
||||
);
|
||||
payload["source"]["source_id"] = job.preview_payload["source"]["source_id"].clone();
|
||||
assert_eq!(
|
||||
payload["normalization"]["normalizer_version"],
|
||||
"normalized-ir-v4"
|
||||
);
|
||||
assert_eq!(payload["normalization"]["projection_version"], "preview-v4");
|
||||
sqlx::query("update import_jobs set preview_payload = $1::jsonb where id = $2")
|
||||
.bind(serde_json::to_string(&payload).unwrap())
|
||||
.bind(job_id.as_str())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let result = service
|
||||
.create_openapi_import(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /secure".to_owned()],
|
||||
server_url: Some("https://api.example.test".to_owned()),
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let error =
|
||||
result.expect_err("historical v4 security blocker must refuse the selected candidate");
|
||||
assert!(
|
||||
format!("{error:?}").contains("invalid_document"),
|
||||
"v4 contract was rejected before candidate validation: {error:?}"
|
||||
);
|
||||
assert!(
|
||||
service
|
||||
.list_operations(&workspace_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
mod security_bundle;
|
||||
+413
@@ -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(®istry, &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(®istry, &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(®istry, &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(®istry, &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
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -58,6 +58,26 @@ paths:
|
||||
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 }
|
||||
@@ -593,7 +613,7 @@ async fn disabled_auth_secret_rejects_apply_without_leaking_credentials() {
|
||||
let redacted_plan = create_plan(
|
||||
&client,
|
||||
&base_url,
|
||||
OPENAPI_TWO_OPERATIONS,
|
||||
OPENAPI_TWO_APIKEY_OPERATIONS,
|
||||
json!({
|
||||
"selection_mode": "partial",
|
||||
"selected_operation_keys": ["GET /beta"],
|
||||
@@ -619,7 +639,7 @@ async fn disabled_auth_secret_rejects_apply_without_leaking_credentials() {
|
||||
let plan = create_plan(
|
||||
&client,
|
||||
&base_url,
|
||||
OPENAPI_SINGLE,
|
||||
OPENAPI_SINGLE_APIKEY_OPERATION,
|
||||
json!({
|
||||
"selection_mode": "full",
|
||||
"selected_operation_keys": [],
|
||||
@@ -657,7 +677,7 @@ async fn disabled_auth_secret_rejects_apply_without_leaking_credentials() {
|
||||
let plan = create_plan(
|
||||
&client,
|
||||
&base_url,
|
||||
OPENAPI_SINGLE,
|
||||
&OPENAPI_SINGLE_APIKEY_OPERATION.replace("X-Api-Key", "X-Changed-Key"),
|
||||
json!({
|
||||
"selection_mode": "full",
|
||||
"selected_operation_keys": [],
|
||||
@@ -695,6 +715,128 @@ async fn disabled_auth_secret_rejects_apply_without_leaking_credentials() {
|
||||
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() {
|
||||
@@ -844,3 +986,4 @@ async fn ac_4_corpus_operation_completes_the_real_http_to_mcp_workflow() {
|
||||
}
|
||||
|
||||
mod corpus_hostile;
|
||||
mod security_source;
|
||||
+11
-14
@@ -45,16 +45,13 @@ async fn ac_5_hostile_corpus_cases_are_bounded_atomic_and_redacted() {
|
||||
);
|
||||
assert_eq!(operation_list(&client, &base_url).await, before);
|
||||
|
||||
let secret = std::fs::read_to_string(root.join("hostile-secret.json")).unwrap();
|
||||
let secret_plan = create_plan(&client, &base_url, &secret, full_plan()).await;
|
||||
let exposed = format!("{}{}", secret_plan.preview, secret_plan.body);
|
||||
assert!(
|
||||
!exposed.contains("sk_test_corpus_secret_canary"),
|
||||
"secret canary leaked into plan evidence"
|
||||
);
|
||||
assert_eq!(operation_list(&client, &base_url).await, before);
|
||||
|
||||
for file in ["hostile-malformed.json", "hostile-oversized.json"] {
|
||||
// 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)
|
||||
@@ -90,7 +87,7 @@ async fn ac_5_hostile_corpus_cases_are_bounded_atomic_and_redacted() {
|
||||
|
||||
// Real HTTP preview+plan: a root security requirement combined with an
|
||||
// explicit empty operation override must leave the public operation
|
||||
// actionable and block only the inherited one. No Apply mutation follows.
|
||||
// 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" },
|
||||
@@ -149,8 +146,8 @@ async fn ac_5_hostile_corpus_cases_are_bounded_atomic_and_redacted() {
|
||||
);
|
||||
assert_eq!(
|
||||
secured["reason"].as_str(),
|
||||
Some("unsupported_security_requirement"),
|
||||
"secured candidate must expose the exact security blocker: {}",
|
||||
Some("auth_profile_required"),
|
||||
"secured candidate must expose its unresolved binding: {}",
|
||||
security_plan.body
|
||||
);
|
||||
assert_eq!(
|
||||
@@ -264,7 +261,7 @@ async fn p0_api_malformed_local_security_is_atomic_across_openapi_versions() {
|
||||
.find(|item| item["key"] == "GET /public")
|
||||
.unwrap();
|
||||
assert_eq!(bad["state"], "blocked", "{version}: {}", plan.body);
|
||||
assert_eq!(bad["reason"], "unsupported_security_requirement");
|
||||
assert_eq!(bad["reason"], "invalid_security_requirements");
|
||||
assert_eq!(public["state"], "actionable", "{version}: {}", plan.body);
|
||||
assert!(public["reason"].is_null());
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -1,5 +1,21 @@
|
||||
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 full_plan_is_server_authored_with_bounded_confirmation_and_no_mutation() {
|
||||
@@ -636,167 +652,6 @@ async fn exact_skip_rename_and_new_version_decisions_are_saved_verbatim() {
|
||||
assert!(candidate.get("operation").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn auth_profile_references_are_validated_stored_and_inherited() {
|
||||
let registry = test_registry().await;
|
||||
let upstream_base_url = spawn_upstream_server().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_plan_auth"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
|
||||
let secret_token = "plan-secret-canary-2-13";
|
||||
let secret = service
|
||||
.create_secret(
|
||||
&workspace_id,
|
||||
None,
|
||||
SecretPayload {
|
||||
name: "plan-auth-token".to_owned(),
|
||||
kind: SecretKind::Token,
|
||||
value: json!({ "token": secret_token }),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let auth_profile = service
|
||||
.create_auth_profile(
|
||||
&workspace_id,
|
||||
AuthProfilePayload {
|
||||
name: "plan-auth-profile".to_owned(),
|
||||
kind: AuthKind::ApiKeyHeader,
|
||||
config: AuthConfig::ApiKeyHeader(ApiKeyHeaderAuthConfig {
|
||||
header_name: "X-Api-Key".to_owned(),
|
||||
secret_id: SecretId::new(secret.id.as_str()),
|
||||
}),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let plan = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
plan_payload(
|
||||
"full",
|
||||
vec![],
|
||||
vec![decision(
|
||||
"GET /v2/latest",
|
||||
"create",
|
||||
None,
|
||||
None,
|
||||
Some(auth_profile.id.as_str()),
|
||||
)],
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let stored = registry
|
||||
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
stored.payload["candidates"][0]["operation"]["execution_config"]["auth_profile_ref"],
|
||||
auth_profile.id.as_str()
|
||||
);
|
||||
// Only the reference survives: no secret material anywhere in the plan.
|
||||
assert!(!stored.payload.to_string().contains(secret_token));
|
||||
assert_eq!(
|
||||
plan.candidates.first().unwrap().auth_profile_id.as_deref(),
|
||||
Some(auth_profile.id.as_str())
|
||||
);
|
||||
|
||||
// An unknown profile reference fails closed in the workspace scope check.
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let error = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
plan_payload(
|
||||
"full",
|
||||
vec![],
|
||||
vec![decision(
|
||||
"GET /v2/latest",
|
||||
"create",
|
||||
None,
|
||||
None,
|
||||
Some("auth_missing_profile"),
|
||||
)],
|
||||
),
|
||||
)
|
||||
.await
|
||||
.expect_err("an unknown auth profile reference must be rejected");
|
||||
assert_error_code(&error, "operation_auth_profile_invalid");
|
||||
assert_http_status(error, axum::http::StatusCode::UNPROCESSABLE_ENTITY);
|
||||
|
||||
// `new_version` without an explicit choice inherits the target's ref.
|
||||
let existing = service
|
||||
.create_operation(&workspace_id, {
|
||||
let mut payload = test_operation_payload(&upstream_base_url, "latest_rates");
|
||||
payload.execution_config.auth_profile_ref =
|
||||
Some(AuthProfileId::new(auth_profile.id.as_str()));
|
||||
payload
|
||||
})
|
||||
.await
|
||||
.expect("an existing operation with the candidate name");
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, upload(OPENAPI_SINGLE))
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: ImportJobId = preview.job_id.as_str().into();
|
||||
let plan = service
|
||||
.create_openapi_import_plan(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
plan_payload(
|
||||
"full",
|
||||
vec![],
|
||||
vec![decision(
|
||||
"GET /v2/latest",
|
||||
"new_version",
|
||||
Some(existing.operation_id.as_str()),
|
||||
None,
|
||||
None,
|
||||
)],
|
||||
),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let stored = registry
|
||||
.get_import_plan(&workspace_id, &plan.plan_reference.as_str().into())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let candidate = &stored.payload["candidates"][0];
|
||||
assert_eq!(
|
||||
candidate["decision"]["auth_profile_id"],
|
||||
auth_profile.id.as_str(),
|
||||
"the inherited target reference is reflected in the candidate summary"
|
||||
);
|
||||
assert_eq!(
|
||||
candidate["operation"]["execution_config"]["auth_profile_ref"],
|
||||
auth_profile.id.as_str(),
|
||||
"the inherited target reference must be retained in the snapshot"
|
||||
);
|
||||
assert!(!stored.payload.to_string().contains(secret_token));
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
#[serial]
|
||||
async fn stale_or_terminal_jobs_preview_again_without_mutating_the_job() {
|
||||
|
||||
@@ -109,6 +109,7 @@ fn decision(
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,4 +161,7 @@ fn assert_http_status(error: ApiError, expected: axum::http::StatusCode) {
|
||||
}
|
||||
|
||||
mod creation;
|
||||
pub(super) use creation::OPENAPI_SINGLE_SECURITY;
|
||||
mod security_availability;
|
||||
mod security_binding;
|
||||
mod validation;
|
||||
+292
@@ -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"
|
||||
);
|
||||
}
|
||||
+732
@@ -0,0 +1,732 @@
|
||||
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();
|
||||
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],
|
||||
),
|
||||
)
|
||||
.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 (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",
|
||||
),
|
||||
] {
|
||||
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")
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user