Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
64 changes: 64 additions & 0 deletions crates/application/tests/execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down
47 changes: 23 additions & 24 deletions crates/desktop/src/app/tests/editor_state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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| {
Expand All @@ -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(),
Expand All @@ -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}}}}}"))
);
}
Expand All @@ -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();
}
Expand Down
118 changes: 116 additions & 2 deletions crates/postman/src/conversion/authentication.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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<String, AuthenticationValue>,
resource_id: &str,
diagnostics: &mut Vec<ImportDiagnostic>,
) {
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,
Expand Down Expand Up @@ -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());
}
}
}
47 changes: 44 additions & 3 deletions crates/postman/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -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")
Expand Down
Loading
Loading