feat(import): bind OpenAPI security schemes safely
This commit is contained in:
1 parent
c562d5368d
commit
41a0e46110
38 files changed
+4651
-590
No files matched your search
@@ -99,6 +99,7 @@ paths:
|
||||
&preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /items".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
@@ -117,6 +118,73 @@ paths:
|
||||
assert_eq!(active_sources, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn external_literal_credential_is_rejected_before_snapshot_persistence() {
|
||||
let canary = "external-atdd-secret-canary-2-10";
|
||||
let app = Router::new().route(
|
||||
"/schemas.yaml",
|
||||
get(move || async move {
|
||||
format!(
|
||||
"Item: {{ type: object, properties: {{ token: {{ type: string, example: '{canary}' }} }} }}"
|
||||
)
|
||||
}),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
let origin = format!("http://{address}");
|
||||
let registry = test_registry().await;
|
||||
let service = test_service_with_external_references(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_external_literal_credential"),
|
||||
vec![format!("{origin}/")],
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let upload = OpenApiUpload {
|
||||
bytes: format!(
|
||||
r#"
|
||||
openapi: 3.1.0
|
||||
info: {{ title: External secret canary }}
|
||||
paths:
|
||||
/items:
|
||||
get:
|
||||
responses:
|
||||
'200':
|
||||
description: ok
|
||||
content:
|
||||
application/json:
|
||||
schema: {{ $ref: '{origin}/schemas.yaml#/Item' }}
|
||||
"#
|
||||
)
|
||||
.into_bytes(),
|
||||
mime_type: "application/yaml".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
};
|
||||
|
||||
let error = service
|
||||
.preview_openapi_import(&workspace_id, upload)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(!format!("{error:?}").contains(canary));
|
||||
let dependency_sources: i64 = sqlx::query_scalar(
|
||||
"select count(*) from artifact_sources
|
||||
where workspace_id = $1 and source_id like 'src_openapi_dep_%'",
|
||||
)
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
let import_jobs: i64 =
|
||||
sqlx::query_scalar("select count(*) from import_jobs where workspace_id = $1")
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(dependency_sources, 0);
|
||||
assert_eq!(import_jobs, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn missing_external_snapshot_fails_closed_before_draft_mutation() {
|
||||
@@ -188,6 +256,7 @@ paths:
|
||||
&preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /items".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
@@ -270,6 +339,7 @@ paths:
|
||||
&corrupt_preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /items".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
@@ -522,6 +592,7 @@ 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(),
|
||||
},
|
||||
@@ -592,6 +663,84 @@ 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(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(result.created.len(), 1);
|
||||
let completed = registry
|
||||
.get_import_job(&workspace_id, &job_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(completed.status, ImportJobStatus::Completed);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn exact_v4_contract_replays_legacy_preview_without_v5_reparse_or_dependency_reads() {
|
||||
use sha2::Digest;
|
||||
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_v4_compatibility"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, openapi_upload())
|
||||
.await
|
||||
.unwrap();
|
||||
let job_id: crank_registry::ImportJobId = preview.job_id.as_str().into();
|
||||
let mut job = registry
|
||||
.get_import_job(&workspace_id, &job_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let missing_dependency = serde_json::json!([{
|
||||
"source_id": "src_openapi_dep_v4_must_not_be_read",
|
||||
"digest": format!("sha256:{}", "0".repeat(64)),
|
||||
"canonical_uri": "https://schemas.example.test/v4.yaml"
|
||||
}]);
|
||||
let mut persisted_preview = job.preview_payload["preview"].clone();
|
||||
for group in persisted_preview["groups"].as_array_mut().unwrap() {
|
||||
for operation in group["operations"].as_array_mut().unwrap() {
|
||||
let object = operation.as_object_mut().unwrap();
|
||||
object.remove("security_requirements");
|
||||
object.remove("security_schemes");
|
||||
}
|
||||
}
|
||||
let expected_preview_digest = format!(
|
||||
"{:x}",
|
||||
sha2::Sha256::digest(serde_json::to_vec(&persisted_preview).unwrap())
|
||||
);
|
||||
job.preview_payload["preview"] = persisted_preview;
|
||||
job.preview_payload["preview_digest"] = serde_json::json!(expected_preview_digest);
|
||||
job.preview_payload["normalization"]["normalizer_version"] =
|
||||
serde_json::json!("normalized-ir-v4");
|
||||
job.preview_payload["normalization"]["projection_version"] = serde_json::json!("preview-v4");
|
||||
job.preview_payload["normalization"]["ir_fingerprint"] = serde_json::json!("a".repeat(64));
|
||||
job.preview_payload["dependency_snapshots"] = missing_dependency;
|
||||
sqlx::query("update import_jobs set preview_payload = $1 where workspace_id = $2 and id = $3")
|
||||
.bind(&job.preview_payload)
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(job_id.as_str())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let result = service
|
||||
.create_openapi_import(
|
||||
&workspace_id,
|
||||
&job_id,
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /v2/latest".to_owned()],
|
||||
auth_mappings: vec![],
|
||||
server_url: Some("https://api.frankfurter.dev".to_owned()),
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
|
||||
@@ -108,6 +108,7 @@ 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(),
|
||||
};
|
||||
@@ -199,6 +200,7 @@ 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,659 @@
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn literal_credential_is_rejected_before_any_import_artifact_or_job_is_created() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_literal_credential_rejected"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let canary = "atdd-secret-canary-2-10-api";
|
||||
let upload = OpenApiUpload {
|
||||
bytes: format!(
|
||||
r#"
|
||||
openapi: 3.0.3
|
||||
info: {{ title: Secret canary }}
|
||||
paths:
|
||||
/items:
|
||||
get:
|
||||
responses:
|
||||
'200': {{ description: ok }}
|
||||
x-api-key: {canary}
|
||||
"#
|
||||
)
|
||||
.into_bytes(),
|
||||
mime_type: "application/yaml".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
};
|
||||
|
||||
let error = service
|
||||
.preview_openapi_import(&workspace_id, upload)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(!format!("{error:?}").contains(canary));
|
||||
let import_jobs: i64 =
|
||||
sqlx::query_scalar("select count(*) from import_jobs where workspace_id = $1")
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
let artifact_sources: i64 =
|
||||
sqlx::query_scalar("select count(*) from artifact_sources where workspace_id = $1")
|
||||
.bind(workspace_id.as_str())
|
||||
.fetch_one(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(import_jobs, 0);
|
||||
assert_eq!(artifact_sources, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn auth_profiles_are_workspace_scoped_revalidated_and_shared_secret_availability_is_current()
|
||||
{
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_auth_profile_binding"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let secret = service
|
||||
.create_secret(
|
||||
&workspace_id,
|
||||
None,
|
||||
SecretPayload {
|
||||
name: "shared-openapi-token".to_owned(),
|
||||
kind: SecretKind::Token,
|
||||
value: json!("integration-secret-canary"),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let ciphertext = registry
|
||||
.get_current_secret_version(&workspace_id, &secret.id)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.secret_version
|
||||
.ciphertext;
|
||||
let secret_hash = format!("{:x}", sha2::Sha256::digest(b"integration-secret-canary"));
|
||||
let profile_a = create_bearer_profile(&service, &workspace_id, "profile-a", &secret.id).await;
|
||||
let profile_b = create_bearer_profile(&service, &workspace_id, "profile-b", &secret.id).await;
|
||||
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, two_protected_operations_upload())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(preview.auth_profile_choices.len(), 2);
|
||||
for choice in &preview.auth_profile_choices {
|
||||
assert!(choice.supported);
|
||||
assert_eq!(choice.profiles.len(), 2);
|
||||
}
|
||||
let response = serde_json::to_string(&preview).unwrap();
|
||||
assert!(!response.contains("integration-secret-canary"));
|
||||
|
||||
let applied = service
|
||||
.create_openapi_import(
|
||||
&workspace_id,
|
||||
&preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /a".to_owned(), "GET /b".to_owned()],
|
||||
auth_mappings: vec![
|
||||
OpenApiAuthMapping {
|
||||
operation_key: "GET /a".to_owned(),
|
||||
alternative_index: 0,
|
||||
auth_profile_id: Some(profile_a.id.as_str().to_owned()),
|
||||
},
|
||||
OpenApiAuthMapping {
|
||||
operation_key: "GET /b".to_owned(),
|
||||
alternative_index: 0,
|
||||
auth_profile_id: Some(profile_b.id.as_str().to_owned()),
|
||||
},
|
||||
],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(applied.created.len(), 2);
|
||||
for created in &applied.created {
|
||||
let version = service
|
||||
.get_operation_version(
|
||||
&workspace_id,
|
||||
&created.operation_id.as_str().into(),
|
||||
created.version,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let profile_ref = version
|
||||
.snapshot
|
||||
.execution_config
|
||||
.auth_profile_ref
|
||||
.as_ref()
|
||||
.unwrap();
|
||||
let serialized_operation = serde_json::to_string(&version.snapshot).unwrap();
|
||||
assert!(serialized_operation.contains(profile_ref.as_str()));
|
||||
assert!(!serialized_operation.contains("integration-secret-canary"));
|
||||
assert!(!serialized_operation.contains(&ciphertext));
|
||||
assert!(!serialized_operation.contains(&secret_hash));
|
||||
}
|
||||
let changed_mapping_replay = service
|
||||
.create_openapi_import(
|
||||
&workspace_id,
|
||||
&preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /a".to_owned(), "GET /b".to_owned()],
|
||||
auth_mappings: vec![
|
||||
OpenApiAuthMapping {
|
||||
operation_key: "GET /a".to_owned(),
|
||||
alternative_index: 0,
|
||||
auth_profile_id: Some(profile_b.id.as_str().to_owned()),
|
||||
},
|
||||
OpenApiAuthMapping {
|
||||
operation_key: "GET /b".to_owned(),
|
||||
alternative_index: 0,
|
||||
auth_profile_id: Some(profile_a.id.as_str().to_owned()),
|
||||
},
|
||||
],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
)
|
||||
.await;
|
||||
assert!(changed_mapping_replay.is_err());
|
||||
assert_eq!(
|
||||
service.list_operations(&workspace_id).await.unwrap().len(),
|
||||
2
|
||||
);
|
||||
|
||||
let now = time::OffsetDateTime::now_utc();
|
||||
let foreign_workspace_id = WorkspaceId::new("ws_openapi_auth_foreign");
|
||||
let foreign_workspace = Workspace {
|
||||
id: foreign_workspace_id.clone(),
|
||||
slug: "openapi-auth-foreign".to_owned(),
|
||||
display_name: "OpenAPI Auth Foreign".to_owned(),
|
||||
status: WorkspaceStatus::Active,
|
||||
settings: json!({}),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
};
|
||||
registry
|
||||
.create_workspace(CreateWorkspaceRequest {
|
||||
workspace: &foreign_workspace,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let foreign_secret = service
|
||||
.create_secret(
|
||||
&foreign_workspace_id,
|
||||
None,
|
||||
SecretPayload {
|
||||
name: "foreign-token".to_owned(),
|
||||
kind: SecretKind::Token,
|
||||
value: json!("foreign-secret-canary"),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let foreign_profile = create_bearer_profile(
|
||||
&service,
|
||||
&foreign_workspace_id,
|
||||
"foreign-profile",
|
||||
&foreign_secret.id,
|
||||
)
|
||||
.await;
|
||||
let choices_preview = service
|
||||
.preview_openapi_import(&workspace_id, two_protected_operations_upload())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
choices_preview
|
||||
.auth_profile_choices
|
||||
.iter()
|
||||
.flat_map(|choice| &choice.profiles)
|
||||
.all(|profile| profile.id != foreign_profile.id.as_str())
|
||||
);
|
||||
|
||||
let missing_error =
|
||||
apply_first_protected_mapping(&service, &workspace_id, "auth_missing_profile")
|
||||
.await
|
||||
.unwrap_err();
|
||||
let foreign_error =
|
||||
apply_first_protected_mapping(&service, &workspace_id, foreign_profile.id.as_str())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(format!("{missing_error:?}"), format!("{foreign_error:?}"));
|
||||
assert!(!format!("{foreign_error:?}").contains(foreign_profile.id.as_str()));
|
||||
|
||||
sqlx::query("update secrets set status = 'disabled' where workspace_id = $1 and id = $2")
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(secret.id.as_str())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
let disabled_preview = service
|
||||
.preview_openapi_import(&workspace_id, two_protected_operations_upload())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
disabled_preview
|
||||
.auth_profile_choices
|
||||
.iter()
|
||||
.all(|choice| choice.profiles.is_empty())
|
||||
);
|
||||
let before_disabled_apply = service.list_operations(&workspace_id).await.unwrap().len();
|
||||
let disabled_error = service
|
||||
.create_openapi_import_with_locale(
|
||||
&workspace_id,
|
||||
&disabled_preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /a".to_owned()],
|
||||
auth_mappings: vec![OpenApiAuthMapping {
|
||||
operation_key: "GET /a".to_owned(),
|
||||
alternative_index: 0,
|
||||
auth_profile_id: Some(profile_a.id.as_str().to_owned()),
|
||||
}],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
OpenApiUploadLocale::Ru,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
match &disabled_error {
|
||||
admin_api::error::ApiError::Unprocessable { message, context } => {
|
||||
assert_eq!(
|
||||
message,
|
||||
"выбранный профиль аутентификации недоступен для этого импорта"
|
||||
);
|
||||
assert_eq!(
|
||||
context.as_ref().unwrap()["error_code"],
|
||||
"openapi_auth_binding_unavailable"
|
||||
);
|
||||
}
|
||||
other => panic!("expected localized auth binding error, got {other:?}"),
|
||||
}
|
||||
let disabled_shared_profile_error =
|
||||
apply_first_protected_mapping(&service, &workspace_id, profile_b.id.as_str())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
format!("{disabled_shared_profile_error:?}"),
|
||||
format!("{missing_error:?}")
|
||||
);
|
||||
assert_eq!(
|
||||
service.list_operations(&workspace_id).await.unwrap().len(),
|
||||
before_disabled_apply
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn selected_supported_or_and_explicit_no_auth_alternatives_apply_without_collapsing_semantics()
|
||||
{
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry,
|
||||
test_storage_root("openapi_import_auth_alternatives"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let secret = service
|
||||
.create_secret(
|
||||
&workspace_id,
|
||||
None,
|
||||
SecretPayload {
|
||||
name: "or-token".to_owned(),
|
||||
kind: SecretKind::Token,
|
||||
value: json!("or-profile-secret"),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let profile = create_bearer_profile(&service, &workspace_id, "or-bearer", &secret.id).await;
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, security_alternatives_upload())
|
||||
.await
|
||||
.unwrap();
|
||||
let choices = preview
|
||||
.auth_profile_choices
|
||||
.iter()
|
||||
.filter(|choice| choice.operation_key == "GET /choice")
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(choices.len(), 2);
|
||||
assert!(choices[0].supported);
|
||||
assert_eq!(choices[0].profiles.len(), 1);
|
||||
assert!(!choices[1].supported);
|
||||
let either = preview
|
||||
.auth_profile_choices
|
||||
.iter()
|
||||
.filter(|choice| choice.operation_key == "GET /either")
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(either.len(), 2);
|
||||
assert!(either[1].supported);
|
||||
|
||||
let applied = service
|
||||
.create_openapi_import(
|
||||
&workspace_id,
|
||||
&preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec![
|
||||
"GET /choice".to_owned(),
|
||||
"GET /either".to_owned(),
|
||||
"GET /public".to_owned(),
|
||||
],
|
||||
auth_mappings: vec![
|
||||
OpenApiAuthMapping {
|
||||
operation_key: "GET /choice".to_owned(),
|
||||
alternative_index: 0,
|
||||
auth_profile_id: Some(profile.id.as_str().to_owned()),
|
||||
},
|
||||
OpenApiAuthMapping {
|
||||
operation_key: "GET /either".to_owned(),
|
||||
alternative_index: 1,
|
||||
auth_profile_id: None,
|
||||
},
|
||||
],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(applied.created.len(), 3);
|
||||
for created in &applied.created {
|
||||
let version = service
|
||||
.get_operation_version(
|
||||
&workspace_id,
|
||||
&created.operation_id.as_str().into(),
|
||||
created.version,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let auth_profile_ref = version.snapshot.execution_config.auth_profile_ref;
|
||||
match created.operation_key.as_str() {
|
||||
"GET /choice" => assert_eq!(auth_profile_ref, Some(profile.id.clone())),
|
||||
"GET /either" | "GET /public" => assert!(auth_profile_ref.is_none()),
|
||||
other => panic!("unexpected operation {other}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn changed_security_scheme_after_preview_fails_digest_check_without_draft_mutation() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry.clone(),
|
||||
test_storage_root("openapi_import_security_scheme_drift"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let secret = service
|
||||
.create_secret(
|
||||
&workspace_id,
|
||||
None,
|
||||
SecretPayload {
|
||||
name: "drift-test-token".to_owned(),
|
||||
kind: SecretKind::Token,
|
||||
value: json!("scheme-drift-profile-secret"),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let profile =
|
||||
create_bearer_profile(&service, &workspace_id, "drift-test-profile", &secret.id).await;
|
||||
let bearer_preview = service
|
||||
.preview_openapi_import(&workspace_id, security_scheme_upload(false))
|
||||
.await
|
||||
.unwrap();
|
||||
let api_key_preview = service
|
||||
.preview_openapi_import(&workspace_id, security_scheme_upload(true))
|
||||
.await
|
||||
.unwrap();
|
||||
let bearer_job: crank_registry::ImportJobId = bearer_preview.job_id.as_str().into();
|
||||
let api_key_job: crank_registry::ImportJobId = api_key_preview.job_id.as_str().into();
|
||||
let api_key_source = registry
|
||||
.get_import_job(&workspace_id, &api_key_job)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.preview_payload["source"]
|
||||
.clone();
|
||||
sqlx::query(
|
||||
"update import_jobs
|
||||
set preview_payload = jsonb_set(
|
||||
jsonb_set(preview_payload, '{source,source_id}', $1, false),
|
||||
'{source,digest}', $2, false
|
||||
)
|
||||
where workspace_id = $3 and id = $4",
|
||||
)
|
||||
.bind(&api_key_source["source_id"])
|
||||
.bind(&api_key_source["digest"])
|
||||
.bind(workspace_id.as_str())
|
||||
.bind(bearer_job.as_str())
|
||||
.execute(registry.pool())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let error = service
|
||||
.create_openapi_import(
|
||||
&workspace_id,
|
||||
&bearer_job,
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /secure".to_owned()],
|
||||
auth_mappings: vec![OpenApiAuthMapping {
|
||||
operation_key: "GET /secure".to_owned(),
|
||||
alternative_index: 0,
|
||||
auth_profile_id: Some(profile.id.as_str().to_owned()),
|
||||
}],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
match error {
|
||||
admin_api::error::ApiError::Unprocessable { context, .. } => assert_eq!(
|
||||
context.unwrap()["error_code"],
|
||||
"openapi_upload.source_integrity"
|
||||
),
|
||||
other => panic!("expected source integrity error, got {other:?}"),
|
||||
}
|
||||
let job = registry
|
||||
.get_import_job(&workspace_id, &bearer_job)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
job.error_text.as_deref(),
|
||||
Some("import_replay_verification_failed")
|
||||
);
|
||||
assert!(
|
||||
service
|
||||
.list_operations(&workspace_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[serial]
|
||||
async fn auth_mapping_for_unselected_operation_is_rejected_without_draft_mutation() {
|
||||
let registry = test_registry().await;
|
||||
let service = test_service(
|
||||
registry,
|
||||
test_storage_root("openapi_import_unselected_auth_mapping"),
|
||||
test_auth_settings(),
|
||||
test_secret_crypto(),
|
||||
);
|
||||
let workspace_id = WorkspaceId::new("ws_default");
|
||||
let preview = service
|
||||
.preview_openapi_import(&workspace_id, two_protected_operations_upload())
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(
|
||||
service
|
||||
.create_openapi_import(
|
||||
&workspace_id,
|
||||
&preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /a".to_owned()],
|
||||
auth_mappings: vec![OpenApiAuthMapping {
|
||||
operation_key: "GET /b".to_owned(),
|
||||
alternative_index: 0,
|
||||
auth_profile_id: None,
|
||||
}],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
service
|
||||
.list_operations(&workspace_id)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
fn two_protected_operations_upload() -> OpenApiUpload {
|
||||
OpenApiUpload {
|
||||
bytes: br#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Protected API }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
components:
|
||||
securitySchemes:
|
||||
bearerAuth: { type: http, scheme: bearer }
|
||||
security:
|
||||
- bearerAuth: []
|
||||
paths:
|
||||
/a:
|
||||
get:
|
||||
responses: { '200': { description: ok } }
|
||||
/b:
|
||||
get:
|
||||
responses: { '200': { description: ok } }
|
||||
"#
|
||||
.to_vec(),
|
||||
mime_type: "application/yaml".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
}
|
||||
}
|
||||
|
||||
fn security_alternatives_upload() -> OpenApiUpload {
|
||||
OpenApiUpload {
|
||||
bytes: br#"
|
||||
openapi: 3.0.3
|
||||
info: { title: Security alternatives }
|
||||
servers: [{ url: https://api.example.test }]
|
||||
components:
|
||||
securitySchemes:
|
||||
bearerAuth: { type: http, scheme: bearer }
|
||||
oauth: { type: oauth2, flows: { implicit: { authorizationUrl: https://auth.example.test, scopes: {} } } }
|
||||
security:
|
||||
- bearerAuth: []
|
||||
- oauth: []
|
||||
paths:
|
||||
/choice:
|
||||
get:
|
||||
responses: { '200': { description: ok } }
|
||||
/either:
|
||||
get:
|
||||
security:
|
||||
- bearerAuth: []
|
||||
- {}
|
||||
responses: { '200': { description: ok } }
|
||||
/public:
|
||||
get:
|
||||
security: []
|
||||
responses: { '200': { description: ok } }
|
||||
"#
|
||||
.to_vec(),
|
||||
mime_type: "application/yaml".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
}
|
||||
}
|
||||
|
||||
fn security_scheme_upload(api_key: bool) -> OpenApiUpload {
|
||||
let security_scheme = if api_key {
|
||||
"auth: { type: apiKey, in: header, name: X-Token }"
|
||||
} else {
|
||||
"auth: { type: http, scheme: bearer }"
|
||||
};
|
||||
OpenApiUpload {
|
||||
bytes: format!(
|
||||
"openapi: 3.0.3\ninfo: {{ title: Scheme drift }}\nservers: [{{ url: https://api.example.test }}]\ncomponents:\n securitySchemes:\n {security_scheme}\nsecurity:\n - auth: []\npaths:\n /secure:\n get:\n responses: {{ '200': {{ description: ok }} }}\n"
|
||||
)
|
||||
.into_bytes(),
|
||||
mime_type: "application/yaml".to_owned(),
|
||||
locale: OpenApiUploadLocale::En,
|
||||
}
|
||||
}
|
||||
|
||||
async fn create_bearer_profile(
|
||||
service: &admin_api::service::AdminService,
|
||||
workspace_id: &WorkspaceId,
|
||||
name: &str,
|
||||
secret_id: &SecretId,
|
||||
) -> crank_core::AuthProfile {
|
||||
service
|
||||
.create_auth_profile(
|
||||
workspace_id,
|
||||
AuthProfilePayload {
|
||||
name: name.to_owned(),
|
||||
kind: AuthKind::Bearer,
|
||||
config: AuthConfig::Bearer(BearerAuthConfig {
|
||||
header_name: "Authorization".to_owned(),
|
||||
secret_id: secret_id.clone(),
|
||||
}),
|
||||
},
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
async fn apply_first_protected_mapping(
|
||||
service: &admin_api::service::AdminService,
|
||||
workspace_id: &WorkspaceId,
|
||||
auth_profile_id: &str,
|
||||
) -> Result<OpenApiImportCreateResponse, admin_api::error::ApiError> {
|
||||
let preview = service
|
||||
.preview_openapi_import(workspace_id, two_protected_operations_upload())
|
||||
.await?;
|
||||
service
|
||||
.create_openapi_import(
|
||||
workspace_id,
|
||||
&preview.job_id.as_str().into(),
|
||||
OpenApiImportCreatePayload {
|
||||
selected_operation_keys: vec!["GET /a".to_owned()],
|
||||
auth_mappings: vec![OpenApiAuthMapping {
|
||||
operation_key: "GET /a".to_owned(),
|
||||
alternative_index: 0,
|
||||
auth_profile_id: Some(auth_profile_id.to_owned()),
|
||||
}],
|
||||
server_url: None,
|
||||
conflict_mode: "skip".to_owned(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
Reference in new issue
Block a user