fix(http-client): keep query parameters written on separate lines (#8204)

A long request target can be split over indented lines in two layouts: lines starting with /, ? or &, and the "query parameters on separate lines" layout where `GET .../html?` is followed by indented `firstname=John&` lines. The parser joined only the first, so the second sent the request to `.../html?` and silently dropped every parameter, and the editor highlighted those lines as plain text.

An indented line now also continues a target whose last part ends in ? or &, in ide-http's parser and in the editor's highlighting; a protocol version after the last part is dropped as on the request line, and an indented header after a complete target stays a header.

Co-authored-by: ntbang0901 <[email protected]>
Цей коміт міститься в:
ntbang0901 authored and GitHub committed 2026-12-05 18:16:07 +08:00
1 джерело 529cd33ddc
коміт 8a26dff72b
4 files changed
+85 -20

No files matched your search

+17
Переглянути файл
@@ -776,4 +776,21 @@ mod tests {
assert_eq!(r.redirects[1].location, format!("http://127.0.0.1:{port}/c"));
assert_eq!(seen[2].0.lines().next().unwrap(), "GET /c HTTP/1.1");
}
#[tokio::test]
async fn sends_query_parameters_written_on_separate_lines() {
let (port, server) = scripted(vec![response("200 OK", "", "ok")]).await;
let text = format!(
"GET http://127.0.0.1:{port}/api/get/html?\n firstname=John&\n lastname=Doe&\n town=Freetown\nAccept: */*\n"
);
let input = crate::RunInput { text: &text, index: 0, file: None, root: None, env: None };
let exchange = crate::run(input, &CancellationToken::new()).await.unwrap();
let (head, _) = &server.await.unwrap()[0];
assert_eq!(
head.lines().next().unwrap(),
"GET /api/get/html?firstname=John&lastname=Doe&town=Freetown HTTP/1.1"
);
assert!(head.to_ascii_lowercase().contains("\r\naccept: */*"), "{head}");
assert_eq!(exchange.response.unwrap().status, 200);
}
}
+41 -8
Переглянути файл
@@ -108,12 +108,15 @@ fn request_line(line: &str) -> Option<(String, String)> {
} else {
return None;
};
// Drop a trailing protocol version.
let url = match target.rsplit_once(char::is_whitespace) {
Some((u, v)) if v.starts_with("HTTP/") => u.trim(),
Some((method, without_version(target).to_owned()))
}
/// `target` without a trailing protocol version (`… HTTP/1.1`).
fn without_version(target: &str) -> &str {
match target.rsplit_once(char::is_whitespace) {
Some((url, version)) if version.starts_with("HTTP/") => url.trim(),
_ => target,
};
Some((method, url.to_owned()))
}
}
fn looks_like_url(t: &str) -> bool {
@@ -172,11 +175,14 @@ pub fn parse(text: &str) -> HttpFile {
i += 1;
}
let Some((req_idx, (method, mut url))) = request else { continue };
// Multi-line query: indented continuation lines.
// A long request target goes on indented lines: one starting with `/`, `?` or `&`, and any one
// after a part ending in `?` or `&` (`…/html?`, then `firstname=John&`, as IntelliJ IDEA's "Put
// query parameters on separate lines" writes them). Line breaks and indents are not sent.
while i < lines.len() {
let l = lines[i];
let t = l.trim();
if l.starts_with([' ', '\t']) && (t.starts_with('?') || t.starts_with('&') || t.starts_with('/')) {
let t = without_version(l.trim());
let continues = url.ends_with(['?', '&']) || t.starts_with(['?', '&', '/']);
if l.starts_with([' ', '\t']) && !t.is_empty() && continues {
url.push_str(t);
i += 1;
} else {
@@ -335,6 +341,33 @@ https://example.com/health
assert_eq!(f.requests[0].headers, vec![("A".into(), "b".into())]);
}
#[test]
fn joins_a_request_target_written_on_separate_lines() {
let url = |text: &str| parse(text).requests[0].block.url.clone();
// The two layouts of IntelliJ IDEA's documentation, "Break long requests into several lines".
let f = parse(
"GET https://example.com:8080/api/get/html?\n firstname=John&\n lastname=Doe&\n planet=Tatooine&\n town=Freetown\nAccept: */*\n",
);
assert_eq!(
f.requests[0].block.url,
"https://example.com:8080/api/get/html?firstname=John&lastname=Doe&planet=Tatooine&town=Freetown"
);
assert_eq!(f.requests[0].headers, vec![("Accept".into(), "*/*".into())]);
assert_eq!(
url("GET http://example.com:8080\n /api\n /html\n /get\n ?id=123\n &value=content\n"),
"http://example.com:8080/api/html/get?id=123&value=content"
);
// A first line ending in `&`, tabs, and the protocol version after the last part.
assert_eq!(
url("GET https://example.com/api?a=1&\n\tb=2&\n\tc=3 HTTP/1.1\n"),
"https://example.com/api?a=1&b=2&c=3"
);
// Indented lines after a target that is complete stay headers.
let f = parse("GET https://example.com/api\n Accept: */*\n");
assert_eq!(f.requests[0].block.url, "https://example.com/api");
assert_eq!(f.requests[0].headers, vec![("Accept".into(), "*/*".into())]);
}
#[test]
fn plain_text_is_not_a_request() {
assert!(parse("hello world\n").requests.is_empty());
+10
Переглянути файл
@@ -183,6 +183,16 @@ describe("http highlighting", () => {
expect(t).toContainEqual(["link", "/next"]);
});
it("continues the URL on indented lines after a part ending in ? or &", () => {
const t = tokens(
"GET https://example.com/api/get/html?\n firstname=John&\n town=Freetown HTTP/1.1\nAccept: */*\n\n{}",
);
const url = t.filter(([name]) => name === "link").map(([, text]) => text.trim());
expect(url.join("")).toBe("https://example.com/api/get/html?firstname=John&town=Freetown");
expect(t).toContainEqual(["meta", " HTTP/1.1"]);
expect(t).toContainEqual(["propertyName", "Accept"]);
});
it("highlights variables inside JSON strings and unquoted values", () => {
const t = tokens('POST /items\n\n{"name": "Hello {{name}}!", "count": {{count}}, "escaped": "a\\\"b"}');
for (const name of ["name", "count"]) expect(t).toContainEqual(["variableName.special", `{{${name}}}`]);
+17 -12
Переглянути файл
@@ -16,6 +16,8 @@ interface State {
string: "propertyName" | "string" | null;
/** Position within the current line's structure. */
part: "start" | "url" | "headerValue" | "rest";
/** The request target so far ends in `?` or `&`: an indented line continues it (as `ide-http::parse` reads it). */
urlOpen: boolean;
}
function variable(stream: Parameters<StreamParser<State>["token"]>[0]): string | null {
@@ -27,9 +29,18 @@ function variable(stream: Parameters<StreamParser<State>["token"]>[0]): string |
return null;
}
/** A piece of the request target, on the request line or a line continuing it; a version may end it. */
function urlToken(stream: Parameters<StreamParser<State>["token"]>[0], state: State): string | null {
if (stream.match(/^\s+HTTP\/[\d.]+\s*$/)) return "meta";
if (stream.eatSpace()) return null;
if (!stream.match(/^[^\s{]+/)) stream.next();
state.urlOpen = /[?&]$/.test(stream.current());
return "link";
}
export const httpParser: StreamParser<State> = {
name: "http",
startState: () => ({ phase: "preamble", handler: false, json: null, string: null, part: "start" }),
startState: () => ({ phase: "preamble", handler: false, json: null, string: null, part: "start", urlOpen: false }),
copyState: (s) => ({ ...s }),
blankLine(state) {
if (state.phase === "headers" || (state.phase === "preamble" && state.part === "url")) state.phase = "body";
@@ -59,6 +70,7 @@ export const httpParser: StreamParser<State> = {
const v = variable(stream);
if (v) {
if (state.phase === "preamble" && state.part === "start") state.part = "url";
if (state.part === "url") state.urlOpen = false;
return v;
}
@@ -90,12 +102,7 @@ export const httpParser: StreamParser<State> = {
return null;
}
}
if (state.part === "url") {
if (stream.match(/^\s+HTTP\/[\d.]+\s*$/)) return "meta";
if (stream.eatSpace()) return null;
if (!stream.match(/^[^\s{]+/)) stream.next();
return "link";
}
if (state.part === "url") return urlToken(stream, state);
// `@name` / `@var` remainder.
if (stream.match(/^\s*=\s*/)) return "operator";
if (!stream.match(/^[^{]+/)) stream.next();
@@ -104,10 +111,11 @@ export const httpParser: StreamParser<State> = {
if (state.phase === "headers") {
if (state.part === "start") {
if (stream.match(/^\s+[?&/]/)) {
if (stream.match(/^\s+[?&/]/) || (state.urlOpen && stream.match(/^\s+(?=\S)/))) {
state.part = "url";
return "link";
}
state.urlOpen = false;
if (stream.match(/^(#|\/\/)/)) {
stream.skipToEnd();
return "comment";
@@ -121,10 +129,7 @@ export const httpParser: StreamParser<State> = {
stream.skipToEnd();
return null;
}
if (state.part === "url") {
if (!stream.match(/^[^\s{]+/)) stream.next();
return "link";
}
if (state.part === "url") return urlToken(stream, state);
if (stream.eat(":")) return "punctuation";
if (!stream.match(/^[^{]+/)) stream.next();
return "string";