use std::{
ffi::OsStr,
fs,
io::Write as _,
process::{Child, Command, Output, Stdio},
time::Duration,
};
use serde_json::json;
use tez::{Method, StatusCode, header};
#[path = "cli_support/httpmock.rs"]
mod httpmock;
use httpmock::{MockResponse, Server, StreamingServer};
const GZIP: &[u8] = &[
31, 139, 8, 0, 0, 0, 0, 0, 0, 19, 11, 73, 173, 82, 72, 206, 207, 45, 40, 74, 45, 46, 206, 204,
207, 83, 72, 203, 172, 40, 41, 45, 74, 213, 227, 2, 0, 58, 171, 44, 106, 25, 0, 0, 0,
];
const DECODED: &[u8] = b"Tez compression fixture.\n";
const PRECISE_JSON_NUMBER: &str = "123456789012345678901234567890";
const PROCESS_START_TIMEOUT: Duration = Duration::from_secs(10);
#[test]
fn help_keeps_short_h_for_headers() {
let help = run(["--help"], None);
let version = run(["--version"], None);
assert!(help.status.success());
let help = String::from_utf8(help.stdout).unwrap();
assert!(help.contains("tez [OPTIONS] [METHOD] URL [ITEM...]"));
assert!(help.contains("-h, --headers"));
assert!(help.contains("--help"));
assert_eq!(
version.stdout,
format!("tez {}\n", env!("CARGO_PKG_VERSION")).as_bytes()
);
}
#[test]
fn parser_errors_do_not_collide_with_timeout_exit_status() {
let unknown = run(["--definitely-not-an-option"], None);
let timeout = run(["--timeout", "not-a-number", ":"], None);
assert_eq!(unknown.status.code(), Some(1));
assert_eq!(timeout.status.code(), Some(1));
assert!(stderr(&unknown).contains("unexpected argument"));
assert!(stderr(&timeout).contains("positive number of seconds"));
}
#[tokio::test(flavor = "multi_thread")]
async fn shorthand_get_query_headers_and_pipe_output_are_exact() {
let server = Server::start(|_| MockResponse::ok("response")).await;
let target = format!(":{}/echo?existing=yes", server.port());
let output = run(
[
"--ignore-stdin",
&target,
"page==2",
"X-Trace:one",
"X-Trace:two",
],
None,
);
assert!(output.status.success(), "{}", stderr(&output));
assert_eq!(output.stdout, b"response");
let requests = server.requests();
assert_eq!(requests.len(), 1);
let request = &requests[0];
assert_eq!(request.method, Method::GET);
assert_eq!(request.path_and_query(), "/echo?existing=yes&page=2");
assert_eq!(request.header(header::ACCEPT.as_str()), Some("*/*"));
assert_eq!(request.header_values("x-trace"), ["one", "two"]);
assert!(request.body.is_empty());
server.shutdown().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn json_fields_infer_post_and_explicit_method_wins() {
let server = Server::start(|_| MockResponse::ok("created")).await;
let output = run(
[
"--ignore-stdin",
"PATCH",
&server.url("/users"),
"name=Tez",
"active:=true",
"count:=2",
"precise:=123456789012345678901234567890",
],
None,
);
assert!(output.status.success(), "{}", stderr(&output));
let requests = server.requests();
let request = &requests[0];
assert_eq!(request.method, Method::PATCH);
assert_eq!(
request.header(header::CONTENT_TYPE.as_str()),
Some("application/json")
);
assert_eq!(
request.header(header::ACCEPT.as_str()),
Some("application/json, */*;q=0.5")
);
let body = serde_json::from_slice::<serde_json::Value>(&request.body).unwrap();
assert_eq!(body["active"], json!(true));
assert_eq!(body["count"], json!(2));
assert_eq!(body["name"], json!("Tez"));
assert_eq!(body["precise"].to_string(), PRECISE_JSON_NUMBER);
assert!(
String::from_utf8_lossy(&request.body).contains(PRECISE_JSON_NUMBER),
"the precise number must remain decimal on the wire"
);
server.shutdown().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn forms_preserve_fields_and_uploads_stream_as_multipart() {
let form_server = Server::start(|_| MockResponse::ok("form")).await;
let form = run(
[
"--ignore-stdin",
"-f",
&form_server.url("/form"),
"tag=one",
"tag=two",
],
None,
);
assert!(form.status.success(), "{}", stderr(&form));
let form_request = &form_server.requests()[0];
assert_eq!(form_request.method, Method::POST);
assert_eq!(
form_request.header(header::CONTENT_TYPE.as_str()),
Some("application/x-www-form-urlencoded")
);
assert_eq!(form_request.body, "tag=one&tag=two");
form_server.shutdown().await;
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("avatar.txt");
fs::write(&path, b"streamed-file").unwrap();
let upload = format!("photo@{};type=text/custom", path.display());
let multipart_server = Server::start(|_| MockResponse::ok("multipart")).await;
let multipart = run(
[
"--ignore-stdin",
"--multipart",
&multipart_server.url("/upload"),
"caption=Tez",
&upload,
],
None,
);
assert!(multipart.status.success(), "{}", stderr(&multipart));
let multipart_request = &multipart_server.requests()[0];
assert_eq!(multipart_request.method, Method::POST);
assert!(
multipart_request
.header(header::CONTENT_TYPE.as_str())
.is_some_and(|value| value.starts_with("multipart/form-data; boundary="))
);
assert_eq!(
multipart_request.header(header::CONTENT_LENGTH.as_str()),
None
);
let body = String::from_utf8_lossy(&multipart_request.body);
assert!(body.contains("name=\"caption\""));
assert!(body.contains("Tez"));
assert!(body.contains("name=\"photo\""));
assert!(body.contains("filename=\"avatar.txt\""));
assert!(body.contains("Content-Type: text/custom"));
assert!(body.contains("streamed-file"));
multipart_server.shutdown().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn stdin_and_body_files_use_streaming_framing() {
let stdin_server = Server::start(|_| MockResponse::ok("stdin")).await;
let input = b"first\nsecond\n".to_vec();
let output = run([stdin_server.url("/stdin")], Some(input.clone()));
assert!(output.status.success(), "{}", stderr(&output));
let request = &stdin_server.requests()[0];
assert_eq!(request.method, Method::POST);
assert_eq!(request.body, input);
assert_eq!(request.header(header::CONTENT_LENGTH.as_str()), None);
stdin_server.shutdown().await;
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("body.bin");
fs::write(&path, b"body-file").unwrap();
let file = format!("@{}", path.display());
let file_server = Server::start(|_| MockResponse::ok("file")).await;
let output = run(["--ignore-stdin", &file_server.url("/file"), &file], None);
assert!(output.status.success(), "{}", stderr(&output));
let request = &file_server.requests()[0];
assert_eq!(request.method, Method::POST);
assert_eq!(request.body, "body-file");
assert_eq!(request.header(header::CONTENT_LENGTH.as_str()), Some("9"));
file_server.shutdown().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn stdin_reaches_the_server_before_eof() {
let mut server = StreamingServer::start().await;
let mut child = start([server.url()], true);
let mut stdin = child.stdin.take().expect("request stdin must be piped");
stdin.write_all(b"first-").unwrap();
stdin.flush().unwrap();
let first = tokio::time::timeout(PROCESS_START_TIMEOUT, server.first_frame())
.await
.expect("the first request frame must arrive before stdin closes");
assert_eq!(first, "first-");
stdin.write_all(b"second").unwrap();
drop(stdin);
let output = tokio::task::spawn_blocking(move || child.wait_with_output())
.await
.unwrap()
.unwrap();
assert!(output.status.success(), "{}", stderr(&output));
assert_eq!(output.stdout, b"streamed");
assert_eq!(server.body(), "first-second");
server.finish().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn an_open_stdin_does_not_hold_a_timed_out_process_alive() {
let mut server = StreamingServer::start().await;
let mut child = start(
["--timeout".to_owned(), "0.5".to_owned(), server.url()],
true,
);
let mut stdin = child.stdin.take().expect("request stdin must be piped");
stdin.write_all(b"partial").unwrap();
stdin.flush().unwrap();
tokio::time::timeout(PROCESS_START_TIMEOUT, server.first_frame())
.await
.expect("the first request frame must arrive before the deadline");
let output = tokio::time::timeout(
Duration::from_secs(3),
tokio::task::spawn_blocking(move || child.wait_with_output()),
)
.await
.expect("a request deadline must terminate the process with stdin still open")
.unwrap()
.unwrap();
assert_eq!(output.status.code(), Some(2), "{}", stderr(&output));
drop(stdin);
server.finish().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn auth_and_explicit_headers_have_clear_precedence() {
let basic_server = Server::start(|_| MockResponse::ok("basic")).await;
let basic = run(
[
"--ignore-stdin",
"-a",
"user:pass",
&basic_server.url("/basic"),
],
None,
);
assert!(basic.status.success(), "{}", stderr(&basic));
assert_eq!(
basic_server.requests()[0].header(header::AUTHORIZATION.as_str()),
Some("Basic dXNlcjpwYXNz")
);
basic_server.shutdown().await;
let bearer_server = Server::start(|_| MockResponse::ok("bearer")).await;
let bearer = run(
[
"--ignore-stdin",
"-A",
"bearer",
"-a",
"secret-token",
&bearer_server.url("/bearer"),
"Authorization:Custom value",
],
None,
);
assert!(bearer.status.success(), "{}", stderr(&bearer));
assert_eq!(
bearer_server.requests()[0].header(header::AUTHORIZATION.as_str()),
Some("Custom value")
);
bearer_server.shutdown().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn default_headers_can_be_unset_without_backend_features_leaking() {
let server = Server::start(|_| {
MockResponse::ok(GZIP).with_header(header::CONTENT_ENCODING.as_str(), "gzip")
})
.await;
let output = run(
[
"--ignore-stdin",
&server.url("/encoded"),
"User-Agent:",
"Accept-Encoding:",
],
None,
);
assert!(output.status.success(), "{}", stderr(&output));
assert_eq!(output.stdout, GZIP);
let request = &server.requests()[0];
assert_eq!(request.header(header::USER_AGENT.as_str()), None);
assert_eq!(request.header(header::ACCEPT_ENCODING.as_str()), None);
server.shutdown().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn a_later_accept_encoding_value_restores_automatic_decoding() {
let server = Server::start(|_| {
MockResponse::ok(GZIP).with_header(header::CONTENT_ENCODING.as_str(), "gzip")
})
.await;
let output = run(
[
"--ignore-stdin",
&server.url("/encoded"),
"Accept-Encoding:",
"Accept-Encoding:gzip",
],
None,
);
assert!(output.status.success(), "{}", stderr(&output));
assert_eq!(output.stdout, DECODED);
assert_eq!(
server.requests()[0].header(header::ACCEPT_ENCODING.as_str()),
Some("gzip")
);
server.shutdown().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn redirects_are_opt_in_same_origin_and_remember_cookies() {
let server = Server::start(|request| {
if request.uri.path() == "/start" {
MockResponse::with_status(StatusCode::FOUND, "")
.with_header(header::LOCATION.as_str(), "/final")
.with_header(header::SET_COOKIE.as_str(), "session=tez; Path=/")
} else {
MockResponse::ok("followed")
}
})
.await;
let first = run(["--ignore-stdin", &server.url("/start")], None);
assert!(first.status.success(), "{}", stderr(&first));
assert!(first.stdout.is_empty());
assert_eq!(server.requests().len(), 1);
let followed = run(["--ignore-stdin", "-F", &server.url("/start")], None);
assert!(followed.status.success(), "{}", stderr(&followed));
assert_eq!(followed.stdout, b"followed");
let requests = server.requests();
assert_eq!(requests.len(), 3);
assert_eq!(requests[2].uri.path(), "/final");
assert_eq!(
requests[2].header(header::COOKIE.as_str()),
Some("session=tez")
);
server.shutdown().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn streamed_redirects_reopen_files_and_reject_stdin_replay() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("body.bin");
fs::write(&path, b"replayable-file").unwrap();
let body_file = format!("@{}", path.display());
let files = Server::start(|request| {
if request.uri.path() == "/start" {
MockResponse::with_status(StatusCode::TEMPORARY_REDIRECT, "")
.with_header(header::LOCATION.as_str(), "/final#section")
.with_header(header::SET_COOKIE.as_str(), "redirect=remembered; Path=/")
} else {
MockResponse::ok("file-followed")
}
})
.await;
let output = run(
[
"--ignore-stdin",
"-F",
"PUT",
&files.url("/start"),
"trace==initial",
&body_file,
],
None,
);
assert!(output.status.success(), "{}", stderr(&output));
assert_eq!(output.stdout, b"file-followed");
let requests = files.requests();
assert_eq!(requests.len(), 2);
assert_eq!(requests[0].method, Method::PUT);
assert_eq!(requests[1].method, Method::PUT);
assert_eq!(requests[0].path_and_query(), "/start?trace=initial");
assert_eq!(requests[1].path_and_query(), "/final");
assert_eq!(requests[0].body, "replayable-file");
assert_eq!(requests[1].body, "replayable-file");
assert_eq!(
requests[1].header(header::COOKIE.as_str()),
Some("redirect=remembered")
);
files.shutdown().await;
let upload = format!("file@{}", path.display());
let multipart = Server::start(|request| {
if request.uri.path() == "/start" {
MockResponse::with_status(StatusCode::PERMANENT_REDIRECT, "")
.with_header(header::LOCATION.as_str(), "/final")
} else {
MockResponse::ok("multipart-followed")
}
})
.await;
let output = run(
[
"--ignore-stdin",
"--multipart",
"-F",
"PUT",
&multipart.url("/start"),
&upload,
],
None,
);
assert!(output.status.success(), "{}", stderr(&output));
assert_eq!(output.stdout, b"multipart-followed");
let requests = multipart.requests();
assert_eq!(requests.len(), 2);
assert_eq!(requests[0].method, Method::PUT);
assert_eq!(requests[1].method, Method::PUT);
assert!(
requests
.iter()
.all(|request| String::from_utf8_lossy(&request.body).contains("replayable-file"))
);
multipart.shutdown().await;
let stdin = Server::start(|_| {
MockResponse::with_status(StatusCode::TEMPORARY_REDIRECT, "")
.with_header(header::LOCATION.as_str(), "/final")
})
.await;
let output = run(
["-F", "PUT", &stdin.url("/start")],
Some(b"one-shot".to_vec()),
);
assert_eq!(output.status.code(), Some(6), "{}", stderr(&output));
assert!(stderr(&output).contains("standard input"));
assert_eq!(stdin.requests().len(), 1);
stdin.shutdown().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn streamed_post_redirects_drop_the_body_before_get() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("body.txt");
fs::write(&path, b"initial-body").unwrap();
let body_file = format!("@{}", path.display());
let server = Server::start(|request| {
if request.uri.path() == "/start" {
MockResponse::with_status(StatusCode::FOUND, "")
.with_header(header::LOCATION.as_str(), "/final")
} else {
MockResponse::ok("rewritten")
}
})
.await;
let output = run(
[
"--ignore-stdin",
"-F",
&server.url("/start"),
"Content-Type:text/custom",
&body_file,
],
None,
);
assert!(output.status.success(), "{}", stderr(&output));
assert_eq!(output.stdout, b"rewritten");
let requests = server.requests();
assert_eq!(requests.len(), 2);
assert_eq!(requests[0].method, Method::POST);
assert_eq!(requests[0].body, "initial-body");
assert_eq!(requests[1].method, Method::GET);
assert!(requests[1].body.is_empty());
assert_eq!(requests[1].header(header::CONTENT_LENGTH.as_str()), None);
assert_eq!(requests[1].header(header::CONTENT_TYPE.as_str()), None);
server.shutdown().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn streamed_redirects_share_one_total_deadline() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("body.txt");
fs::write(&path, b"deadline-body").unwrap();
let body_file = format!("@{}", path.display());
let server = Server::start(|request| match request.uri.path() {
"/start" => MockResponse::with_status(StatusCode::TEMPORARY_REDIRECT, "")
.with_header(header::LOCATION.as_str(), "/middle")
.with_delay(Duration::from_millis(120)),
"/middle" => MockResponse::with_status(StatusCode::TEMPORARY_REDIRECT, "")
.with_header(header::LOCATION.as_str(), "/final")
.with_delay(Duration::from_millis(120)),
_ => MockResponse::ok("too-late"),
})
.await;
let output = run(
[
"--ignore-stdin",
"-F",
"--timeout",
"0.18",
"PUT",
&server.url("/start"),
&body_file,
],
None,
);
assert_eq!(output.status.code(), Some(2), "{}", stderr(&output));
assert!(stderr(&output).contains("deadline"));
server.shutdown().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn cross_origin_redirects_are_returned_without_forwarding_credentials() {
let destination = Server::start(|_| MockResponse::ok("unsafe")).await;
let location = destination.url("/destination");
let origin = Server::start(move |_| {
MockResponse::with_status(StatusCode::FOUND, "")
.with_header(header::LOCATION.as_str(), &location)
})
.await;
let output = run(
[
"--ignore-stdin",
"-F",
"--check-status",
"-A",
"bearer",
"-a",
"secret-token",
&origin.url("/start"),
],
None,
);
assert_eq!(output.status.code(), Some(3), "{}", stderr(&output));
assert!(destination.requests().is_empty());
assert_eq!(
origin.requests()[0].header(header::AUTHORIZATION.as_str()),
Some("Bearer secret-token")
);
origin.shutdown().await;
destination.shutdown().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn redirect_exhaustion_and_timeout_use_scriptable_exit_codes() {
let redirects = Server::start(|_| {
MockResponse::with_status(StatusCode::FOUND, "")
.with_header(header::LOCATION.as_str(), "/again")
})
.await;
let output = run(
[
"--ignore-stdin",
"-F",
"--max-redirects",
"1",
&redirects.url("/again"),
],
None,
);
assert_eq!(output.status.code(), Some(6), "{}", stderr(&output));
assert!(stderr(&output).contains("redirect"));
redirects.shutdown().await;
let slow =
Server::start(|_| MockResponse::ok("late").with_delay(Duration::from_millis(500))).await;
let output = run(
["--ignore-stdin", "--timeout", "0.05", &slow.url("/slow")],
None,
);
assert_eq!(output.status.code(), Some(2), "{}", stderr(&output));
assert!(stderr(&output).contains("deadline"));
slow.shutdown().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn checked_statuses_and_output_modes_match_scripting_expectations() {
let server = Server::start(|request| {
let status = if request.uri.path() == "/server-error" {
StatusCode::BAD_GATEWAY
} else {
StatusCode::NOT_FOUND
};
MockResponse::with_status(status, "problem").with_header("x-mode", "test")
})
.await;
let unchecked = run(["--ignore-stdin", &server.url("/missing")], None);
assert!(unchecked.status.success(), "{}", stderr(&unchecked));
assert_eq!(unchecked.stdout, b"problem");
let client_error = run(
[
"--ignore-stdin",
"--check-status",
"-h",
&server.url("/missing"),
],
None,
);
assert_eq!(client_error.status.code(), Some(4));
let headers = String::from_utf8(client_error.stdout).unwrap();
assert!(headers.starts_with("HTTP/1.1 404 Not Found\n"));
assert!(headers.contains("x-mode: test\n"));
assert!(!headers.contains("problem"));
let server_error = run(
[
"--ignore-stdin",
"--check-status",
"-b",
&server.url("/server-error"),
],
None,
);
assert_eq!(server_error.status.code(), Some(5));
assert_eq!(server_error.stdout, b"problem");
server.shutdown().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn output_files_are_exact_and_errors_never_echo_request_values() {
let server = Server::start(|_| MockResponse::ok(vec![0, 1, 2, 255])).await;
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("download.bin");
let path_text = path.to_string_lossy().into_owned();
let output = run(
["--ignore-stdin", "-o", &path_text, &server.url("/download")],
None,
);
assert!(output.status.success(), "{}", stderr(&output));
assert!(output.stdout.is_empty());
assert_eq!(fs::read(path).unwrap(), [0, 1, 2, 255]);
server.shutdown().await;
let error = run(
[
"--ignore-stdin",
"http://127.0.0.1:1/private",
"top-secret-value",
],
None,
);
assert_eq!(error.status.code(), Some(1));
assert!(!stderr(&error).contains("top-secret-value"));
assert!(!stderr(&error).contains("/private"));
let proxy = run(
[
"--ignore-stdin",
"--proxy",
"socks5://user:proxy-secret@127.0.0.1:1080",
"example.com",
],
None,
);
assert_eq!(proxy.status.code(), Some(1));
assert!(stderr(&proxy).contains("client proxy URL is invalid"));
assert!(!stderr(&proxy).contains("proxy-secret"));
}
#[tokio::test(flavor = "multi_thread")]
async fn downloads_follow_same_origin_redirects_and_resume_named_files() {
let followed = Server::start(|request| {
if request.uri.path() == "/start" {
MockResponse::with_status(StatusCode::FOUND, "")
.with_header(header::LOCATION.as_str(), "/final")
} else {
MockResponse::ok("downloaded")
}
})
.await;
let directory = tempfile::tempdir().unwrap();
let followed_path = directory.path().join("followed.txt");
let followed_path = followed_path.to_string_lossy().into_owned();
let output = run(
[
"--ignore-stdin",
"--download",
"--output",
&followed_path,
&followed.url("/start"),
],
None,
);
assert!(output.status.success(), "{}", stderr(&output));
assert_eq!(fs::read(&followed_path).unwrap(), b"downloaded");
assert_eq!(followed.requests().len(), 2);
followed.shutdown().await;
let resumed =
Server::start(|_| MockResponse::with_status(StatusCode::PARTIAL_CONTENT, "tail")).await;
let resumed_path = directory.path().join("resume.txt");
fs::write(&resumed_path, b"part-").unwrap();
let resumed_path = resumed_path.to_string_lossy().into_owned();
let output = run(
[
"--ignore-stdin",
"--download",
"--continue",
"--output",
&resumed_path,
&resumed.url("/file"),
],
None,
);
assert!(output.status.success(), "{}", stderr(&output));
assert_eq!(fs::read(&resumed_path).unwrap(), b"part-tail");
assert_eq!(
resumed.requests()[0].header(header::RANGE.as_str()),
Some("bytes=5-")
);
resumed.shutdown().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn offline_renders_the_prepared_request_without_contacting_the_server() {
let server = Server::start(|_| MockResponse::ok("not contacted")).await;
let url = server.url("/users");
let output = run(
[
"--ignore-stdin",
"--offline",
&url,
"name=Tez",
"active:=true",
],
None,
);
assert!(output.status.success(), "{}", stderr(&output));
let preview = String::from_utf8(output.stdout).unwrap();
assert!(preview.starts_with(&format!("POST {url} HTTP/1.1\n")));
assert!(preview.contains("content-type: application/json\n"));
assert!(preview.ends_with("{\"active\":true,\"name\":\"Tez\"}"));
assert!(server.requests().is_empty());
server.shutdown().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn verbose_output_keeps_response_pipes_clean_and_redacts_credentials() {
let server = Server::start(|_| MockResponse::ok("body")).await;
let output = run(
[
"--ignore-stdin",
"--verbose",
"-A",
"bearer",
"-a",
"verbose-token",
&server.url("/verbose"),
],
None,
);
assert!(output.status.success(), "{}", stderr(&output));
assert_eq!(output.stdout, b"body");
let stderr = stderr(&output);
assert!(stderr.starts_with("GET "));
assert!(stderr.contains("authorization: [redacted]\n"));
assert!(!stderr.contains("verbose-token"));
server.shutdown().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn sessions_remember_headers_supported_auth_and_cookies() {
let server = Server::start(|_| {
MockResponse::ok("ok").with_header(header::SET_COOKIE.as_str(), "sid=tez; Path=/")
})
.await;
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("session.json");
let path = path.to_string_lossy().into_owned();
let first = run(
[
"--ignore-stdin",
"--session",
&path,
"-A",
"bearer",
"-a",
"session-token",
&server.url("/first"),
"X-Session:initial",
],
None,
);
assert!(first.status.success(), "{}", stderr(&first));
let second = run(
["--ignore-stdin", "--session", &path, &server.url("/second")],
None,
);
assert!(second.status.success(), "{}", stderr(&second));
let requests = server.requests();
assert_eq!(requests.len(), 2);
assert_eq!(
requests[1].header(header::AUTHORIZATION.as_str()),
Some("Bearer session-token")
);
assert_eq!(requests[1].header("x-session"), Some("initial"));
assert_eq!(requests[1].header(header::COOKIE.as_str()), Some("sid=tez"));
let before_read_only = fs::read(&path).unwrap();
let read_only = run(
[
"--ignore-stdin",
"--session-read-only",
&path,
&server.url("/readonly"),
"X-Session:replacement",
],
None,
);
assert!(read_only.status.success(), "{}", stderr(&read_only));
assert_eq!(fs::read(&path).unwrap(), before_read_only);
assert_eq!(
server.requests()[2].header("x-session"),
Some("replacement")
);
server.shutdown().await;
}
fn run<I, S>(args: I, stdin: Option<Vec<u8>>) -> Output
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let mut child = start(args, stdin.is_some());
if let Some(stdin) = stdin {
child
.stdin
.take()
.expect("piped stdin must be available")
.write_all(&stdin)
.expect("request stdin must be written");
}
child
.wait_with_output()
.expect("the tez command must finish")
}
fn start<I, S>(args: I, pipe_stdin: bool) -> Child
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let mut command = Command::new(env!("CARGO_BIN_EXE_tez"));
command
.args(args)
.stdout(Stdio::piped())
.stderr(Stdio::piped());
for name in [
"HTTP_PROXY",
"HTTPS_PROXY",
"ALL_PROXY",
"http_proxy",
"https_proxy",
"all_proxy",
"NO_PROXY",
"no_proxy",
] {
command.env_remove(name);
}
command.env("NO_PROXY", "*");
if pipe_stdin {
command.stdin(Stdio::piped());
} else {
command.stdin(Stdio::null());
}
command.spawn().expect("the tez command must start")
}
fn stderr(output: &Output) -> String {
String::from_utf8_lossy(&output.stderr).into_owned()
}