fix(http-client): encode the credentials of Authorization: Basic user password (#7855)

Authorization: Basic user password in a .http file went out as written, so the server answered 401 to a correct password; a converted curl -u user:password writes that same line. The credentials are now Base64-encoded when the request is prepared. The line is split before variables are filled in, so a variable's value may contain spaces; credentials that are already encoded, also from a variable, are sent unchanged.

Co-authored-by: ntbang0901 <[email protected]>
Цей коміт міститься в:
ntbang0901 authored and GitHub committed 2026-12-04 01:02:52 +08:00
1 джерело 7ff13704ff
коміт 42b6363646
3 files changed
+57 -4

No files matched your search

+55 -2
Переглянути файл
@@ -4,6 +4,8 @@ use crate::body::RequestBody;
use crate::client::{describe, with_scheme};
use crate::env::{Environments, Resolver};
use crate::parse::{BodyPart, RawRequest};
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use ide_core::{CancellationToken, IdeError, IdeResult};
use serde::{Deserialize, Serialize};
use specta::Type;
@@ -82,8 +84,15 @@ pub fn prepare(
let resolver = Resolver { file_vars, env: envs.variables(env), env_first: env.is_some() };
let mut missing = BTreeSet::new();
let url = resolver.substitute(&raw.block.url, &mut missing);
let headers: Vec<(String, String)> =
raw.headers.iter().map(|(k, v)| (k.clone(), resolver.substitute(v, &mut missing))).collect();
let mut substitute = |text: &str| resolver.substitute(text, &mut missing);
let headers: Vec<(String, String)> = raw
.headers
.iter()
.map(|(k, v)| {
let basic = k.eq_ignore_ascii_case("authorization").then(|| basic_credentials(v, &mut substitute));
(k.clone(), basic.flatten().unwrap_or_else(|| substitute(v)))
})
.collect();
// Multipart bodies delimit parts with CRLF per RFC 2046 §5.1; joining
// with bare LF leaves servers (e.g. Tomcat) unable to find the boundary.
let is_multipart = headers
@@ -133,6 +142,28 @@ pub fn prepare(
})
}
/// `Basic user password` encoded for the wire, as IntelliJ's HTTP Client does. Split before
/// substitution: the value of a variable may contain spaces.
fn basic_credentials(value: &str, mut substitute: impl FnMut(&str) -> String) -> Option<String> {
let mut words = vec![String::new()];
let mut rest = value;
while let Some(c) = rest.chars().next() {
let variable = rest.starts_with("{{").then(|| rest.find("}}")).flatten().map(|end| end + 2);
let (text, after) = rest.split_at(variable.unwrap_or(c.len_utf8()));
rest = after;
match words.last_mut() {
Some(word) if !c.is_whitespace() => word.push_str(text),
Some(word) if word.is_empty() => {}
_ => words.push(String::new()),
}
}
let [scheme, user, password] = words.as_slice() else { return None };
if !substitute(scheme).eq_ignore_ascii_case("basic") {
return None;
}
Some(format!("Basic {}", STANDARD.encode(format!("{}:{}", substitute(user), substitute(password)))))
}
fn looks_textual(content_type: Option<&str>, bytes: &[u8]) -> bool {
if let Some(ct) = content_type {
let ct = ct.to_ascii_lowercase();
@@ -307,6 +338,28 @@ mod tests {
assert_eq!(url(None), "http://localhost:8080/v1/x?env=none");
}
#[test]
fn basic_authorization_is_encoded() {
let envs =
Environments::from_json(r#"{"dev":{"user":"bob","password":"se cret","encoded":"Ym9iOng="}}"#, "").unwrap();
for (header, sent) in [
("Authorization: Basic bob secret", "Basic Ym9iOnNlY3JldA=="),
("authorization: basic bob secret", "Basic Ym9iOnNlY3JldA=="),
("Authorization: Basic {{user}} {{ password }}", "Basic Ym9iOnNlIGNyZXQ="),
("Authorization: Basic {{encoded}}", "Basic Ym9iOng="),
("Authorization: Basic Ym9iOng=", "Basic Ym9iOng="),
("Authorization: Bearer a b", "Bearer a b"),
("X-Other: Basic bob secret", "Basic bob secret"),
] {
let f = parse(&format!("GET https://api.test/\n{header}\n"));
let p = prepare(&f.requests[0], &f.variables, &envs, Some("dev"), None).unwrap();
assert_eq!(p.headers[0].1, sent, "{header}");
}
let f = parse("GET https://api.test/\nAuthorization: Basic {{user}} {{nope}}\n");
let err = prepare(&f.requests[0], &f.variables, &envs, Some("dev"), None).unwrap_err();
assert!(err.message.contains("nope"), "{}", err.message);
}
#[test]
fn reports_unresolved_variables() {
let f = parse("GET https://{{host}}/x\n");
+1 -1
Переглянути файл
@@ -42,7 +42,7 @@ Content-Type: application/json
| Request line | `METHOD URL [HTTP/version]`, or just a URL for `GET`. Methods: `GET`, `POST`, `PUT`, `DELETE`, `PATCH`, `HEAD`, `OPTIONS`, `TRACE`, `CONNECT`. |
| Long URLs | Indented lines starting with `?`, `&` or `/` continue the URL. |
| Relative URLs | `GET /path` needs a `Host:` header. A URL without a scheme gets `http://`. |
| Headers | `Name: value` lines up to the first blank line. |
| Headers | `Name: value` lines up to the first blank line. `Authorization: Basic user password` is sent Base64-encoded. |
| Body | Everything after the blank line. `< ./file` sends a file's bytes as they are, relative to the `.http` file. |
| Multipart | With a `multipart/*` `Content-Type`, body lines are joined with CRLF. Write the boundaries yourself. |
+1 -1
Переглянути файл
@@ -42,7 +42,7 @@ Content-Type: application/json
| 请求行 | `METHOD URL [HTTP/版本]`,只写 URL 时为 `GET`。支持的方法:`GET`、`POST`、`PUT`、`DELETE`、`PATCH`、`HEAD`、`OPTIONS`、`TRACE`、`CONNECT`。 |
| 长 URL | 以 `?`、`&` 或 `/` 开头的缩进行会接到 URL 后面。 |
| 相对 URL | `GET /path` 需要 `Host:` 请求头。没有协议的 URL 会补上 `http://`。 |
| 请求头 | 第一个空行之前的 `Name: value` 行。 |
| 请求头 | 第一个空行之前的 `Name: value` 行。`Authorization: Basic user password` 会以 Base64 编码发送。 |
| 请求体 | 空行之后的所有内容。`< ./file` 按原始字节发送文件内容,路径相对于 `.http` 文件。 |
| Multipart | `Content-Type` 为 `multipart/*` 时,请求体各行用 CRLF 连接。边界需要自己写。 |