From 42973bf3198847d50fe77ab56def09965d44b376 Mon Sep 17 00:00:00 2001 From: Crizant Lai Date: Tue, 3 Nov 2026 17:58:21 +1000 Subject: [PATCH 1/2] fix(postman): preserve API key placement when importing collections - Import header and query placements correctly, and report missing, invalid, or conflicting settings - Add coverage for Postman collection v2 and v2.1 --- CHANGELOG.md | 5 + crates/application/tests/execution.rs | 59 ++++++ .../postman/src/conversion/authentication.rs | 47 ++++- crates/postman/src/tests.rs | 171 +++++++++++++++++- .../postman/collection-apikey-v2.1.json | 80 ++++++++ .../postman/collection-apikey-v2.json | 41 +++++ 6 files changed, 398 insertions(+), 5 deletions(-) create mode 100644 tests/fixtures/postman/collection-apikey-v2.1.json create mode 100644 tests/fixtures/postman/collection-apikey-v2.json diff --git a/CHANGELOG.md b/CHANGELOG.md index 07779973..9da0d9d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,11 @@ Release dates use Australia/Brisbane time (UTC+10). ## [Unreleased] +### Fixed + +- Import Postman API Key header and query placement correctly, and report missing, + invalid, or conflicting placement settings without defaulting to a header. + ### Changed - Use dedicated Basic, Bearer, and API Key authentication fields, with a password diff --git a/crates/application/tests/execution.rs b/crates/application/tests/execution.rs index 09bb3b35..85123298 100644 --- a/crates/application/tests/execution.rs +++ b/crates/application/tests/execution.rs @@ -20,6 +20,65 @@ use sha2::{Digest, Sha256}; const SECRET: &str = "SUPER_SECRET_VALUE_THAT_MUST_NEVER_APPEAR"; +#[tokio::test] +async fn imported_postman_api_keys_execute_in_the_selected_placement() { + for name in ["collection-apikey-v2.json", "collection-apikey-v2.1.json"] { + let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../tests/fixtures/postman") + .join(name); + let imported = probe_postman::inspect_postman_source(path) + .unwrap() + .convert(false) + .unwrap(); + for item in &imported.collection.items { + let probe_core::CollectionItem::Request(source) = item else { + panic!("expected request"); + }; + let (base, server) = serve_once(http_response("", b"hello")); + let mut request = source.clone(); + request.url = Some(format!("{base}/items")); + let overrides = [("token".to_owned(), "imported-secret".to_owned())]; + let response = prepare_request( + &request, + &RequestResolution { + overrides: &overrides, + ..RequestResolution::default() + }, + &NoSecrets, + ) + .unwrap() + .into_http() + .unwrap() + .execute( + &HttpEngine::new().unwrap(), + ExecutionOptions::default(), + None, + std::future::pending::<()>(), + |_| {}, + ) + .await + .unwrap() + .response; + assert_eq!(response.status, 200); + let head = String::from_utf8(server.join().unwrap()).unwrap(); + if request.metadata.name.as_deref() == Some("header") { + assert!(head.starts_with("GET /items HTTP/1.1\r\n"), "{head}"); + assert!( + head.to_ascii_lowercase() + .contains("x-api-key: imported-secret\r\n"), + "{head}" + ); + } else { + assert!( + head.starts_with("GET /items?X-API-Key=imported-secret HTTP/1.1\r\n"), + "{head}" + ); + assert!(!head.to_ascii_lowercase().contains("x-api-key:"), "{head}"); + } + } + } +} + #[tokio::test] async fn api_key_placement_secrets_hide_url_structure_in_both_branches() { use probe_core::{Authentication, AuthenticationKind, AuthenticationValue, QueryParameter}; diff --git a/crates/postman/src/conversion/authentication.rs b/crates/postman/src/conversion/authentication.rs index 13641a2e..62247d25 100644 --- a/crates/postman/src/conversion/authentication.rs +++ b/crates/postman/src/conversion/authentication.rs @@ -43,7 +43,10 @@ pub(super) fn convert_authentication( } } let kind = authentication_kind(auth_type); - if !matches!(kind, AuthenticationKind::Basic | AuthenticationKind::Bearer) { + if !matches!( + kind, + AuthenticationKind::Basic | AuthenticationKind::Bearer | AuthenticationKind::ApiKey + ) { diagnostics.push(warning( "execution_unsupported", "request", @@ -55,15 +58,55 @@ pub(super) fn convert_authentication( ), )); } - let properties = convert_properties( + let mut properties = convert_properties( format, object.get(auth_type).unwrap_or(&Value::Null), resource_id, diagnostics, )?; + if kind == AuthenticationKind::ApiKey { + normalize_api_key_placement(&mut properties, resource_id, diagnostics); + } Ok(Some(Authentication { kind, properties })) } +fn normalize_api_key_placement( + properties: &mut BTreeMap, + resource_id: &str, + diagnostics: &mut Vec, +) { + let source = properties.get("in"); + let placement = properties.get("placement"); + if let (Some(source), Some(placement)) = (source, placement) + && source != placement + { + diagnostics.push(warning( + "conflicting_api_key_placement", + "request", + Some(resource_id), + Some("auth.apikey.in"), + "Postman API Key 'in' conflicts with 'placement'; both properties are preserved and Probe uses 'placement'", + )); + return; + } + if !matches!( + source.or(placement), + Some(AuthenticationValue::String(value)) if matches!(value.as_str(), "header" | "query") + ) { + diagnostics.push(warning( + "invalid_api_key_placement", + "request", + Some(resource_id), + Some("auth.apikey.in"), + "Postman API Key placement is missing or unsupported; expected 'header' or 'query'; properties are preserved without a default", + )); + return; + } + if let Some(source) = properties.remove("in") { + properties.insert("placement".to_owned(), source); + } +} + fn authentication_kind(auth_type: &str) -> AuthenticationKind { match auth_type { "apikey" => AuthenticationKind::ApiKey, diff --git a/crates/postman/src/tests.rs b/crates/postman/src/tests.rs index ce5ba161..516f0af1 100644 --- a/crates/postman/src/tests.rs +++ b/crates/postman/src/tests.rs @@ -5,8 +5,9 @@ use std::{ }; use probe_core::{ - AuthenticationKind, Body, CollectionItem, EnvironmentVariable, GraphqlBody, MultipartPartKind, - RequestBody, VariableValue, VariableValueSet, VariableValueType, WorkspaceItemRef, + AuthenticationKind, AuthenticationValue, Body, CollectionItem, EnvironmentVariable, + GraphqlBody, MultipartPartKind, RequestBody, VariableValue, VariableValueSet, + VariableValueType, WorkspaceItemRef, }; use probe_opencollection::create_bundled_workspace_from_collection; @@ -137,6 +138,170 @@ fn imports_v2_object_authentication() { ); } +#[test] +fn imports_api_key_placements_and_round_trips() { + for name in ["collection-apikey-v2.json", "collection-apikey-v2.1.json"] { + let imported = inspect_postman_source(fixture(name)) + .unwrap() + .convert(false) + .unwrap(); + assert!(imported.diagnostics.is_empty()); + assert!(!imported.partial); + let destination = temporary_path("apikey.yml"); + let loaded = + create_bundled_workspace_from_collection(&destination, &imported.collection).unwrap(); + for (index, placement) in ["header", "query"].iter().enumerate() { + let CollectionItem::Request(request) = &imported.collection.items[index] else { + panic!("expected request"); + }; + let auth = request.authentication.as_ref().unwrap(); + assert_eq!(auth.kind, AuthenticationKind::ApiKey); + assert_eq!( + auth.properties, + std::collections::BTreeMap::from([ + ( + "key".into(), + AuthenticationValue::String("X-API-Key".into()) + ), + ( + "value".into(), + AuthenticationValue::String("{{token}}".into()) + ), + ( + "placement".into(), + AuthenticationValue::String((*placement).into()) + ), + ( + "custom".into(), + AuthenticationValue::String("{{custom}}".into()) + ), + ]) + ); + let WorkspaceItemRef::Request(key) = loaded.workspace().root_items()[index] else { + panic!("expected request"); + }; + assert_eq!(loaded.workspace().request(key).unwrap(), request); + } + fs::remove_file(destination).unwrap(); + } +} + +#[test] +fn api_key_missing_invalid_and_conflicting_placements_preserve_source_data() { + use serde_json::{Value, json}; + + for format in [ + PostmanSourceFormat::CollectionV2, + PostmanSourceFormat::CollectionV2_1, + ] { + for (extra, expected_code) in [ + (json!({}), Some("invalid_api_key_placement")), + (json!({"in": "cookie"}), Some("invalid_api_key_placement")), + (json!({"in": ""}), Some("invalid_api_key_placement")), + (json!({"in": null}), Some("invalid_api_key_placement")), + (json!({"in": true}), Some("invalid_api_key_placement")), + ( + json!({"in": "{{placement}}"}), + Some("invalid_api_key_placement"), + ), + ( + json!({"in": "header", "placement": "query"}), + Some("conflicting_api_key_placement"), + ), + ( + json!({"in": "query", "placement": null}), + Some("conflicting_api_key_placement"), + ), + ( + json!({"in": "cookie", "placement": "header"}), + Some("conflicting_api_key_placement"), + ), + ( + json!({"placement": "invalid"}), + Some("invalid_api_key_placement"), + ), + (json!({"placement": "query"}), None), + (json!({"in": "query", "placement": "query"}), None), + ] { + let mut properties = + json!({"key": "{{key}}", "value": "{{value}}", "custom": [1, false]}); + properties + .as_object_mut() + .unwrap() + .extend(extra.as_object().unwrap().clone()); + let value = match format { + PostmanSourceFormat::CollectionV2 => properties.clone(), + PostmanSourceFormat::CollectionV2_1 => Value::Array( + properties + .as_object() + .unwrap() + .iter() + .map(|(key, value)| json!({"key": key, "value": value})) + .collect(), + ), + }; + let name = match format { + PostmanSourceFormat::CollectionV2 => "collection-apikey-v2.json", + PostmanSourceFormat::CollectionV2_1 => "collection-apikey-v2.1.json", + }; + let mut source: Value = + serde_json::from_slice(&fs::read(fixture(name)).unwrap()).unwrap(); + source["item"].as_array_mut().unwrap().truncate(1); + source["item"][0]["id"] = json!("request"); + source["item"][0]["request"]["auth"]["apikey"] = value; + let path = temporary_path("apikey.json"); + fs::write(&path, serde_json::to_vec(&source).unwrap()).unwrap(); + let imported = inspect_postman_source(&path) + .unwrap() + .convert(false) + .unwrap(); + fs::remove_file(path).unwrap(); + let diagnostics = &imported.diagnostics; + let CollectionItem::Request(request) = &imported.collection.items[0] else { + panic!("expected request"); + }; + let auth = request.authentication.as_ref().unwrap(); + assert_eq!( + auth.properties["key"], + AuthenticationValue::String("{{key}}".into()) + ); + assert_eq!( + auth.properties["value"], + AuthenticationValue::String("{{value}}".into()) + ); + assert_eq!( + auth.properties["custom"], + AuthenticationValue::Sequence(vec![ + AuthenticationValue::Number("1".into()), + AuthenticationValue::Boolean(false), + ]) + ); + if let Some(code) = expected_code { + assert_eq!(diagnostics.len(), 1, "{properties:?}"); + assert_eq!(diagnostics[0].code, code); + assert_eq!(diagnostics[0].resource_id.as_deref(), Some("request")); + assert_eq!(auth.properties.len(), properties.as_object().unwrap().len()); + for field in ["in", "placement"] { + let expected = properties.get(field).map(|value| match value { + Value::String(value) => AuthenticationValue::String(value.clone()), + Value::Bool(value) => AuthenticationValue::Boolean(*value), + Value::Null => AuthenticationValue::Null, + _ => panic!("unexpected placement test value"), + }); + assert_eq!(auth.properties.get(field), expected.as_ref()); + } + } else { + assert!(diagnostics.is_empty()); + assert!(!auth.properties.contains_key("in")); + assert_eq!( + auth.properties["placement"], + AuthenticationValue::String("query".into()) + ); + } + } + } +} + #[test] fn imports_all_supported_bodies_and_expands_authentication_inheritance() { let preview = inspect_postman_source(fixture("collection-bodies-v2.1.json")).unwrap(); @@ -250,7 +415,7 @@ fn strict_mode_rejects_lossy_data_and_partial_is_explicit() { .any(|item| item.code == "dynamic_variable_unsupported") ); assert!( - imported + !imported .diagnostics .iter() .any(|item| item.code == "execution_unsupported") diff --git a/tests/fixtures/postman/collection-apikey-v2.1.json b/tests/fixtures/postman/collection-apikey-v2.1.json new file mode 100644 index 00000000..a0ce0fe2 --- /dev/null +++ b/tests/fixtures/postman/collection-apikey-v2.1.json @@ -0,0 +1,80 @@ +{ + "info": { + "_postman_id": "pm_v21", + "name": "Postman Pets", + "description": "Pet operations", + "version": { + "major": 1, + "minor": 2, + "patch": 3, + "identifier": "beta" + }, + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json" + }, + "item": [ + { + "name": "header", + "request": { + "method": "GET", + "url": "https://api.example.com/items", + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "key", + "value": "X-API-Key", + "type": "string" + }, + { + "key": "value", + "value": "{{token}}", + "type": "string" + }, + { + "key": "in", + "value": "header", + "type": "string" + }, + { + "key": "custom", + "value": "{{custom}}", + "type": "string" + } + ] + } + } + }, + { + "name": "query", + "request": { + "method": "GET", + "url": "https://api.example.com/items", + "auth": { + "type": "apikey", + "apikey": [ + { + "key": "key", + "value": "X-API-Key", + "type": "string" + }, + { + "key": "value", + "value": "{{token}}", + "type": "string" + }, + { + "key": "in", + "value": "query", + "type": "string" + }, + { + "key": "custom", + "value": "{{custom}}", + "type": "string" + } + ] + } + } + } + ] +} diff --git a/tests/fixtures/postman/collection-apikey-v2.json b/tests/fixtures/postman/collection-apikey-v2.json new file mode 100644 index 00000000..d01beb79 --- /dev/null +++ b/tests/fixtures/postman/collection-apikey-v2.json @@ -0,0 +1,41 @@ +{ + "info": { + "_postman_id": "pm_v2", + "name": "Postman V2", + "schema": "https://schema.getpostman.com/json/collection/v2.0.0/collection.json" + }, + "item": [ + { + "name": "header", + "request": { + "method": "GET", + "url": "https://api.example.com/items", + "auth": { + "type": "apikey", + "apikey": { + "key": "X-API-Key", + "value": "{{token}}", + "in": "header", + "custom": "{{custom}}" + } + } + } + }, + { + "name": "query", + "request": { + "method": "GET", + "url": "https://api.example.com/items", + "auth": { + "type": "apikey", + "apikey": { + "key": "X-API-Key", + "value": "{{token}}", + "in": "query", + "custom": "{{custom}}" + } + } + } + } + ] +} From 6d22e1f93d685854e1c625922ce63de996cb3cf4 Mon Sep 17 00:00:00 2001 From: Crizant Lai Date: Tue, 3 Nov 2026 18:12:43 +1000 Subject: [PATCH 2/2] test: consolidate authentication regression coverage --- crates/application/tests/execution.rs | 97 ++++++------ crates/desktop/src/app/tests/editor_state.rs | 47 +++--- .../postman/src/conversion/authentication.rs | 71 +++++++++ crates/postman/src/tests.rs | 144 ++---------------- .../postman/collection-apikey-v2.1.json | 4 +- .../postman/collection-apikey-v2.json | 4 +- 6 files changed, 159 insertions(+), 208 deletions(-) diff --git a/crates/application/tests/execution.rs b/crates/application/tests/execution.rs index 85123298..ca1059f5 100644 --- a/crates/application/tests/execution.rs +++ b/crates/application/tests/execution.rs @@ -22,7 +22,11 @@ const SECRET: &str = "SUPER_SECRET_VALUE_THAT_MUST_NEVER_APPEAR"; #[tokio::test] async fn imported_postman_api_keys_execute_in_the_selected_placement() { - for name in ["collection-apikey-v2.json", "collection-apikey-v2.1.json"] { + // The importer covers both placements per format; execute one representative of each here. + for (name, index) in [ + ("collection-apikey-v2.json", 0), + ("collection-apikey-v2.1.json", 1), + ] { let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("../../tests/fixtures/postman") .join(name); @@ -30,51 +34,52 @@ async fn imported_postman_api_keys_execute_in_the_selected_placement() { .unwrap() .convert(false) .unwrap(); - for item in &imported.collection.items { - let probe_core::CollectionItem::Request(source) = item else { - panic!("expected request"); - }; - let (base, server) = serve_once(http_response("", b"hello")); - let mut request = source.clone(); - request.url = Some(format!("{base}/items")); - let overrides = [("token".to_owned(), "imported-secret".to_owned())]; - let response = prepare_request( - &request, - &RequestResolution { - overrides: &overrides, - ..RequestResolution::default() - }, - &NoSecrets, - ) - .unwrap() - .into_http() - .unwrap() - .execute( - &HttpEngine::new().unwrap(), - ExecutionOptions::default(), - None, - std::future::pending::<()>(), - |_| {}, - ) - .await - .unwrap() - .response; - assert_eq!(response.status, 200); - let head = String::from_utf8(server.join().unwrap()).unwrap(); - if request.metadata.name.as_deref() == Some("header") { - assert!(head.starts_with("GET /items HTTP/1.1\r\n"), "{head}"); - assert!( - head.to_ascii_lowercase() - .contains("x-api-key: imported-secret\r\n"), - "{head}" - ); - } else { - assert!( - head.starts_with("GET /items?X-API-Key=imported-secret HTTP/1.1\r\n"), - "{head}" - ); - assert!(!head.to_ascii_lowercase().contains("x-api-key:"), "{head}"); - } + let probe_core::CollectionItem::Request(source) = &imported.collection.items[index] else { + panic!("expected request"); + }; + let (base, server) = serve_once(http_response("", b"hello")); + let mut request = source.clone(); + request.url = Some(format!("{base}/items")); + let overrides = [ + ("key".to_owned(), "X-API-Key".to_owned()), + ("token".to_owned(), "imported-secret".to_owned()), + ]; + let response = prepare_request( + &request, + &RequestResolution { + overrides: &overrides, + ..RequestResolution::default() + }, + &NoSecrets, + ) + .unwrap() + .into_http() + .unwrap() + .execute( + &HttpEngine::new().unwrap(), + ExecutionOptions::default(), + None, + std::future::pending::<()>(), + |_| {}, + ) + .await + .unwrap() + .response; + assert_eq!(response.status, 200); + let head = String::from_utf8(server.join().unwrap()).unwrap(); + if index == 0 { + assert!(head.starts_with("GET /items HTTP/1.1\r\n"), "{head}"); + assert!( + head.to_ascii_lowercase() + .contains("x-api-key: imported-secret\r\n"), + "{head}" + ); + } else { + assert!( + head.starts_with("GET /items?X-API-Key=imported-secret HTTP/1.1\r\n"), + "{head}" + ); + assert!(!head.to_ascii_lowercase().contains("x-api-key:"), "{head}"); } } } diff --git a/crates/desktop/src/app/tests/editor_state.rs b/crates/desktop/src/app/tests/editor_state.rs index 42c721d7..094c6144 100644 --- a/crates/desktop/src/app/tests/editor_state.rs +++ b/crates/desktop/src/app/tests/editor_state.rs @@ -457,7 +457,6 @@ fn authentication_fields_map_edits_and_preserve_imported_properties(cx: &mut Tes let (window, [http, _, _]) = editor_workspace(cx); window .update(cx, |view, _, cx| { - view.select_request(http, cx); view.request_editor .set_section(http, EditorSection::Authentication); cx.notify(); @@ -468,9 +467,24 @@ fn authentication_fields_map_edits_and_preserve_imported_properties(cx: &mut Tes Value::Sequence(vec![Value::Boolean(true)]), )])); for (kind, fields) in [ - (AuthenticationKind::Basic, vec!["username", "password"]), - (AuthenticationKind::Bearer, vec!["token"]), - (AuthenticationKind::ApiKey, vec!["key", "value"]), + ( + AuthenticationKind::Basic, + &[ + ("username", "authentication-username"), + ("password", "authentication-password"), + ][..], + ), + ( + AuthenticationKind::Bearer, + &[("token", "authentication-token")][..], + ), + ( + AuthenticationKind::ApiKey, + &[ + ("key", "authentication-key"), + ("value", "authentication-value"), + ][..], + ), ] { window .update(cx, |view, _, cx| { @@ -490,18 +504,9 @@ fn authentication_fields_map_edits_and_preserve_imported_properties(cx: &mut Tes }) .unwrap(); cx.run_until_parked(); - for field in &fields { + for &(field, selector) in fields { let mut visual = VisualTestContext::from_window(window.into(), cx); - let bounds = visual - .debug_bounds(match *field { - "username" => "authentication-username", - "password" => "authentication-password", - "token" => "authentication-token", - "key" => "authentication-key", - "value" => "authentication-value", - _ => unreachable!(), - }) - .unwrap(); + let bounds = visual.debug_bounds(selector).unwrap(); visual.simulate_click( point(bounds.center().x, bounds.bottom() - px(12.0)), Modifiers::default(), @@ -519,16 +524,16 @@ fn authentication_fields_map_edits_and_preserve_imported_properties(cx: &mut Tes cx.run_until_parked(); } window - .update(cx, |view, _, cx| { + .read_with(cx, |view, _| { let auth = view .active_request() .unwrap() .authentication .as_ref() .unwrap(); - for field in &fields { + for &(field, _) in fields { assert_eq!( - auth.properties[*field], + auth.properties[field], Value::String(format!("{{{{{field}}}}}")) ); } @@ -539,12 +544,6 @@ fn authentication_fields_map_edits_and_preserve_imported_properties(cx: &mut Tes Value::String("query".to_owned()) ); } - let before = auth.clone(); - view.edit_request(http, |request| set_authentication(request, Some(kind)), cx); - assert_eq!( - view.active_request().unwrap().authentication.as_ref(), - Some(&before) - ); }) .unwrap(); } diff --git a/crates/postman/src/conversion/authentication.rs b/crates/postman/src/conversion/authentication.rs index 62247d25..3d4e14ce 100644 --- a/crates/postman/src/conversion/authentication.rs +++ b/crates/postman/src/conversion/authentication.rs @@ -267,3 +267,74 @@ fn typed_auth_value( } } } + +#[cfg(test)] +mod tests { + use super::*; + use AuthenticationValue::{Boolean, Null, String as Text}; + + #[test] + fn api_key_placement_diagnostics_preserve_properties() { + let text = |value: &str| Some(Text(value.to_owned())); + for (source, placement, code) in [ + (None, None, "invalid_api_key_placement"), + (text("cookie"), None, "invalid_api_key_placement"), + (text(""), None, "invalid_api_key_placement"), + (Some(Null), None, "invalid_api_key_placement"), + (Some(Boolean(true)), None, "invalid_api_key_placement"), + (text("{{placement}}"), None, "invalid_api_key_placement"), + ( + text("header"), + text("query"), + "conflicting_api_key_placement", + ), + (text("query"), Some(Null), "conflicting_api_key_placement"), + ( + text("cookie"), + text("header"), + "conflicting_api_key_placement", + ), + (None, text("invalid"), "invalid_api_key_placement"), + ] { + let mut properties = BTreeMap::from([ + ("key".into(), Text("{{key}}".into())), + ("value".into(), Text("{{value}}".into())), + ( + "custom".into(), + AuthenticationValue::Sequence(vec![Boolean(false)]), + ), + ]); + properties.extend( + [("in", source), ("placement", placement)] + .into_iter() + .filter_map(|(key, value)| value.map(|value| (key.to_owned(), value))), + ); + let original = properties.clone(); + let mut diagnostics = Vec::new(); + normalize_api_key_placement(&mut properties, "request", &mut diagnostics); + assert_eq!(properties, original); + assert_eq!(diagnostics.len(), 1); + assert_eq!(diagnostics[0].code, code); + assert_eq!( + diagnostics[0].severity, + probe_core::ImportDiagnosticSeverity::Warning + ); + assert_eq!(diagnostics[0].resource_id.as_deref(), Some("request")); + } + } + + #[test] + fn api_key_existing_placement_is_normalized_without_warnings() { + for source in [None, Some(Text("query".into()))] { + let expected = BTreeMap::from([("placement".into(), Text("query".into()))]); + let mut properties = expected.clone(); + if let Some(source) = source { + properties.insert("in".into(), source); + } + let mut diagnostics = Vec::new(); + normalize_api_key_placement(&mut properties, "request", &mut diagnostics); + assert_eq!(properties, expected); + assert!(diagnostics.is_empty()); + } + } +} diff --git a/crates/postman/src/tests.rs b/crates/postman/src/tests.rs index 516f0af1..71d5b669 100644 --- a/crates/postman/src/tests.rs +++ b/crates/postman/src/tests.rs @@ -140,6 +140,8 @@ fn imports_v2_object_authentication() { #[test] fn imports_api_key_placements_and_round_trips() { + use AuthenticationValue::String as Text; + for name in ["collection-apikey-v2.json", "collection-apikey-v2.1.json"] { let imported = inspect_postman_source(fixture(name)) .unwrap() @@ -158,24 +160,14 @@ fn imports_api_key_placements_and_round_trips() { assert_eq!(auth.kind, AuthenticationKind::ApiKey); assert_eq!( auth.properties, - std::collections::BTreeMap::from([ - ( - "key".into(), - AuthenticationValue::String("X-API-Key".into()) - ), - ( - "value".into(), - AuthenticationValue::String("{{token}}".into()) - ), - ( - "placement".into(), - AuthenticationValue::String((*placement).into()) - ), - ( - "custom".into(), - AuthenticationValue::String("{{custom}}".into()) - ), - ]) + [ + ("key", "{{key}}"), + ("value", "{{token}}"), + ("placement", *placement), + ("custom", "{{custom}}") + ] + .map(|(key, value)| (key.to_owned(), Text(value.to_owned()))) + .into() ); let WorkspaceItemRef::Request(key) = loaded.workspace().root_items()[index] else { panic!("expected request"); @@ -186,122 +178,6 @@ fn imports_api_key_placements_and_round_trips() { } } -#[test] -fn api_key_missing_invalid_and_conflicting_placements_preserve_source_data() { - use serde_json::{Value, json}; - - for format in [ - PostmanSourceFormat::CollectionV2, - PostmanSourceFormat::CollectionV2_1, - ] { - for (extra, expected_code) in [ - (json!({}), Some("invalid_api_key_placement")), - (json!({"in": "cookie"}), Some("invalid_api_key_placement")), - (json!({"in": ""}), Some("invalid_api_key_placement")), - (json!({"in": null}), Some("invalid_api_key_placement")), - (json!({"in": true}), Some("invalid_api_key_placement")), - ( - json!({"in": "{{placement}}"}), - Some("invalid_api_key_placement"), - ), - ( - json!({"in": "header", "placement": "query"}), - Some("conflicting_api_key_placement"), - ), - ( - json!({"in": "query", "placement": null}), - Some("conflicting_api_key_placement"), - ), - ( - json!({"in": "cookie", "placement": "header"}), - Some("conflicting_api_key_placement"), - ), - ( - json!({"placement": "invalid"}), - Some("invalid_api_key_placement"), - ), - (json!({"placement": "query"}), None), - (json!({"in": "query", "placement": "query"}), None), - ] { - let mut properties = - json!({"key": "{{key}}", "value": "{{value}}", "custom": [1, false]}); - properties - .as_object_mut() - .unwrap() - .extend(extra.as_object().unwrap().clone()); - let value = match format { - PostmanSourceFormat::CollectionV2 => properties.clone(), - PostmanSourceFormat::CollectionV2_1 => Value::Array( - properties - .as_object() - .unwrap() - .iter() - .map(|(key, value)| json!({"key": key, "value": value})) - .collect(), - ), - }; - let name = match format { - PostmanSourceFormat::CollectionV2 => "collection-apikey-v2.json", - PostmanSourceFormat::CollectionV2_1 => "collection-apikey-v2.1.json", - }; - let mut source: Value = - serde_json::from_slice(&fs::read(fixture(name)).unwrap()).unwrap(); - source["item"].as_array_mut().unwrap().truncate(1); - source["item"][0]["id"] = json!("request"); - source["item"][0]["request"]["auth"]["apikey"] = value; - let path = temporary_path("apikey.json"); - fs::write(&path, serde_json::to_vec(&source).unwrap()).unwrap(); - let imported = inspect_postman_source(&path) - .unwrap() - .convert(false) - .unwrap(); - fs::remove_file(path).unwrap(); - let diagnostics = &imported.diagnostics; - let CollectionItem::Request(request) = &imported.collection.items[0] else { - panic!("expected request"); - }; - let auth = request.authentication.as_ref().unwrap(); - assert_eq!( - auth.properties["key"], - AuthenticationValue::String("{{key}}".into()) - ); - assert_eq!( - auth.properties["value"], - AuthenticationValue::String("{{value}}".into()) - ); - assert_eq!( - auth.properties["custom"], - AuthenticationValue::Sequence(vec![ - AuthenticationValue::Number("1".into()), - AuthenticationValue::Boolean(false), - ]) - ); - if let Some(code) = expected_code { - assert_eq!(diagnostics.len(), 1, "{properties:?}"); - assert_eq!(diagnostics[0].code, code); - assert_eq!(diagnostics[0].resource_id.as_deref(), Some("request")); - assert_eq!(auth.properties.len(), properties.as_object().unwrap().len()); - for field in ["in", "placement"] { - let expected = properties.get(field).map(|value| match value { - Value::String(value) => AuthenticationValue::String(value.clone()), - Value::Bool(value) => AuthenticationValue::Boolean(*value), - Value::Null => AuthenticationValue::Null, - _ => panic!("unexpected placement test value"), - }); - assert_eq!(auth.properties.get(field), expected.as_ref()); - } - } else { - assert!(diagnostics.is_empty()); - assert!(!auth.properties.contains_key("in")); - assert_eq!( - auth.properties["placement"], - AuthenticationValue::String("query".into()) - ); - } - } - } -} - #[test] fn imports_all_supported_bodies_and_expands_authentication_inheritance() { let preview = inspect_postman_source(fixture("collection-bodies-v2.1.json")).unwrap(); diff --git a/tests/fixtures/postman/collection-apikey-v2.1.json b/tests/fixtures/postman/collection-apikey-v2.1.json index a0ce0fe2..ea5b41af 100644 --- a/tests/fixtures/postman/collection-apikey-v2.1.json +++ b/tests/fixtures/postman/collection-apikey-v2.1.json @@ -22,7 +22,7 @@ "apikey": [ { "key": "key", - "value": "X-API-Key", + "value": "{{key}}", "type": "string" }, { @@ -54,7 +54,7 @@ "apikey": [ { "key": "key", - "value": "X-API-Key", + "value": "{{key}}", "type": "string" }, { diff --git a/tests/fixtures/postman/collection-apikey-v2.json b/tests/fixtures/postman/collection-apikey-v2.json index d01beb79..2c7c5441 100644 --- a/tests/fixtures/postman/collection-apikey-v2.json +++ b/tests/fixtures/postman/collection-apikey-v2.json @@ -13,7 +13,7 @@ "auth": { "type": "apikey", "apikey": { - "key": "X-API-Key", + "key": "{{key}}", "value": "{{token}}", "in": "header", "custom": "{{custom}}" @@ -29,7 +29,7 @@ "auth": { "type": "apikey", "apikey": { - "key": "X-API-Key", + "key": "{{key}}", "value": "{{token}}", "in": "query", "custom": "{{custom}}"