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..ca1059f5 100644 --- a/crates/application/tests/execution.rs +++ b/crates/application/tests/execution.rs @@ -20,6 +20,70 @@ 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() { + // 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); + let imported = probe_postman::inspect_postman_source(path) + .unwrap() + .convert(false) + .unwrap(); + 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}"); + } + } +} + #[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/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 13641a2e..3d4e14ce 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, @@ -224,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 ce5ba161..71d5b669 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,46 @@ 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() + .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, + [ + ("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"); + }; + assert_eq!(loaded.workspace().request(key).unwrap(), request); + } + fs::remove_file(destination).unwrap(); + } +} + #[test] fn imports_all_supported_bodies_and_expands_authentication_inheritance() { let preview = inspect_postman_source(fixture("collection-bodies-v2.1.json")).unwrap(); @@ -250,7 +291,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..ea5b41af --- /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": "{{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": "{{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..2c7c5441 --- /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": "{{key}}", + "value": "{{token}}", + "in": "header", + "custom": "{{custom}}" + } + } + } + }, + { + "name": "query", + "request": { + "method": "GET", + "url": "https://api.example.com/items", + "auth": { + "type": "apikey", + "apikey": { + "key": "{{key}}", + "value": "{{token}}", + "in": "query", + "custom": "{{custom}}" + } + } + } + } + ] +}