use super::*;
#[tokio::test(flavor = "multi_thread")]
async fn test_github_oauth_401_refreshes_and_retries_once() {
let (port, count, requests) = spawn_recording_server(vec![
unauthorized_response(),
github_oauth_token_response(),
json_empty_array_response(),
])
.await;
let server_url = format!("http://127.0.0.1:{port}");
let dir = tempfile::tempdir().unwrap();
let cache_path = dir.path().join("github-oauth-tokens.toml");
let _guard = set_test_github_oauth(&server_url, cache_path.clone());
seed_github_oauth_cache(&cache_path);
let mut headers = HeaderMap::new();
headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer ghu-stale"));
let client = Client::new(Duration::from_secs(3), ClientKind::Http).unwrap();
let text = client
.get_text_request(format!("{server_url}/api/v3/repos/owner/repo/releases"))
.headers(&headers)
.send()
.await
.unwrap_or_else(|err| {
let requests = requests.lock().unwrap();
panic!(
"request failed: {err:#}\nrequests:\n{}",
requests.join("\n---\n")
);
});
assert_eq!(text, "[]");
assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 3);
let requests = requests.lock().unwrap();
let first_request = requests[0].to_ascii_lowercase();
let refresh_request = requests[1].to_ascii_lowercase();
let retry_request = requests[2].to_ascii_lowercase();
assert!(first_request.contains("get /api/v3/repos/owner/repo/releases"));
assert!(first_request.contains("authorization: bearer ghu-stale"));
assert!(refresh_request.contains("post /login/oauth/access_token"));
assert!(retry_request.contains("get /api/v3/repos/owner/repo/releases"));
assert!(retry_request.contains("authorization: bearer ghu-refreshed"));
let cache = std::fs::read_to_string(cache_path).unwrap();
assert!(cache.contains("ghu-refreshed"));
}
#[tokio::test(flavor = "multi_thread")]
async fn test_github_oauth_401_reports_refreshed_token_source() {
let (port, count, _requests) = spawn_recording_server(vec![
unauthorized_response(),
github_oauth_token_response(),
unauthorized_response(),
])
.await;
let server_url = format!("http://127.0.0.1:{port}");
let dir = tempfile::tempdir().unwrap();
let cache_path = dir.path().join("github-oauth-tokens.toml");
let _guard = set_test_github_oauth(&server_url, cache_path.clone());
seed_github_oauth_cache(&cache_path);
let mut headers = HeaderMap::new();
headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer ghu-stale"));
let client = Client::new(Duration::from_secs(3), ClientKind::Http).unwrap();
let err = client
.get_text_request(format!("{server_url}/api/v3/repos/owner/repo/releases"))
.headers(&headers)
.send()
.await
.unwrap_err();
let msg = format!("{err:?}");
assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 3);
assert!(
msg.contains("github auth: yes (token from GitHub OAuth)"),
"{msg}"
);
assert!(
msg.contains("token from GitHub OAuth was rejected by GitHub"),
"{msg}"
);
}
async fn send_github_403(response: &'static str, retries: i64) -> (Report, usize) {
let attempts = retries as usize + 1;
let (port, count) = spawn_canned_server(vec![response; 8]).await;
let _guard = set_test_http_retries(retries);
let client = Client::new(Duration::from_secs(3), ClientKind::Http).unwrap();
let err = client
.get_text_request(format!(
"http://127.0.0.1:{port}/api/v3/repos/aubepkg/aube/contents/x.json"
))
.send()
.await
.expect_err("403 should be an error");
let seen = count.load(std::sync::atomic::Ordering::SeqCst);
assert!(
seen <= attempts,
"server saw {seen} requests, more than the {attempts} allowed"
);
(err, seen)
}
#[tokio::test(flavor = "current_thread")]
async fn test_github_rate_limited_403_is_retried() {
let (err, seen) = send_github_403(github_rate_limited_response(), 3).await;
assert_eq!(seen, 4, "exhausted limit should be retried: {err:?}");
assert!(is_transient(&err), "{err:?}");
let msg = format!("{err:?}");
assert!(
msg.contains("github rate limit: 0/5000 (core), resets at 1789456621"),
"{msg}"
);
assert!(
msg.contains("API rate limit exceeded for installation"),
"{msg}"
);
}
#[tokio::test(flavor = "current_thread")]
async fn test_github_secondary_rate_limited_403_is_retried() {
let (err, seen) = send_github_403(github_secondary_rate_limited_response(), 2).await;
assert_eq!(seen, 3, "secondary limit should be retried: {err:?}");
assert!(is_transient(&err), "{err:?}");
assert!(
format!("{err:?}").contains("secondary rate limit"),
"{err:?}"
);
}
#[tokio::test(flavor = "current_thread")]
async fn test_github_forbidden_with_quota_left_is_not_retried() {
let (err, seen) = send_github_403(github_forbidden_response(), 3).await;
assert_eq!(seen, 1, "a refusal should not be retried: {err:?}");
assert!(!is_transient(&err), "{err:?}");
}
#[tokio::test(flavor = "current_thread")]
async fn test_github_forbidden_report_includes_body_and_auth_state() {
let (port, _count) = spawn_canned_server(vec![github_forbidden_response()]).await;
let url = format!("http://127.0.0.1:{port}/repos/microsoft/edit/releases");
let resp = reqwest::Client::new().get(url).send().await.unwrap();
let rate_limit = github_rate_limit_summary(&resp);
let status_error = resp
.error_for_status_ref()
.expect_err("403 response should be an error");
let body = resp.text().await.unwrap();
let err = github_forbidden_report(status_error, true, rate_limit, false, &body);
let msg = format!("{err:?}");
assert!(msg.contains("github auth: yes"));
assert!(msg.contains("github rate limit: 42/5000 (core), resets at 1781337353"));
assert!(msg.contains(r#"{"message":"secondary rate limit","docs":"url"}"#));
}
#[tokio::test(flavor = "current_thread")]
async fn test_github_unauthorized_report_names_token_source() {
let (port, _count) = spawn_canned_server(vec![unauthorized_response()]).await;
let url = format!("http://127.0.0.1:{port}/repos/owner/repo/releases");
let resp = reqwest::Client::new().get(url).send().await.unwrap();
let status_error = resp
.error_for_status_ref()
.expect_err("401 response should be an error");
let body = resp.text().await.unwrap();
let err = github_unauthorized_report(
status_error,
true,
Some(&crate::github::TokenSource::EnvVar("GITHUB_TOKEN")),
&body,
);
let msg = format!("{err:?}");
assert!(
msg.contains("github auth: yes (token from GITHUB_TOKEN)"),
"{msg}"
);
assert!(msg.contains("Bad credentials"), "{msg}");
assert!(
msg.contains("token in `GITHUB_TOKEN` was rejected by GitHub (401 Unauthorized)"),
"{msg}"
);
assert!(msg.contains("github-tokens.html"), "{msg}");
}
#[tokio::test(flavor = "current_thread")]
async fn test_github_unauthorized_report_names_non_env_token_sources() {
let sources = [
(crate::github::TokenSource::TokensFile, "github_tokens.toml"),
(crate::github::TokenSource::GhCli, "gh CLI (hosts.yml)"),
(
crate::github::TokenSource::CredentialCommand,
"credential_command",
),
(crate::github::TokenSource::GithubOauth, "GitHub OAuth"),
(
crate::github::TokenSource::GitCredential,
"git credential fill",
),
];
let (port, _count) = spawn_canned_server(vec![unauthorized_response(); sources.len()]).await;
let url = format!("http://127.0.0.1:{port}/repos/owner/repo/releases");
for (source, label) in sources {
let resp = reqwest::Client::new().get(&url).send().await.unwrap();
let status_error = resp.error_for_status_ref().unwrap_err();
let body = resp.text().await.unwrap();
let msg = format!(
"{:?}",
github_unauthorized_report(status_error, true, Some(&source), &body)
);
assert!(
msg.contains(&format!("github auth: yes (token from {label})")),
"{msg}"
);
assert!(
msg.contains(&format!("token from {label} was rejected by GitHub")),
"{msg}"
);
}
}
#[tokio::test(flavor = "current_thread")]
async fn test_github_unauthorized_report_without_known_source() {
let (port, _count) =
spawn_canned_server(vec![unauthorized_response(), unauthorized_response()]).await;
let url = format!("http://127.0.0.1:{port}/repos/owner/repo/releases");
let resp = reqwest::Client::new().get(&url).send().await.unwrap();
let status_error = resp.error_for_status_ref().unwrap_err();
let body = resp.text().await.unwrap();
let used_msg = format!(
"{:?}",
github_unauthorized_report(status_error, true, None, &body)
);
assert!(used_msg.contains("github auth: yes"), "{used_msg}");
assert!(!used_msg.contains("token from"), "{used_msg}");
assert!(used_msg.contains("configured GitHub token"), "{used_msg}");
let resp = reqwest::Client::new().get(&url).send().await.unwrap();
let status_error = resp.error_for_status_ref().unwrap_err();
let body = resp.text().await.unwrap();
let anon_msg = format!(
"{:?}",
github_unauthorized_report(status_error, false, None, &body)
);
assert!(anon_msg.contains("github auth: no"), "{anon_msg}");
assert!(!anon_msg.contains("hint:"), "{anon_msg}");
}
#[tokio::test(flavor = "current_thread")]
async fn test_github_unauthorized_report_ignores_source_when_no_auth_sent() {
let (port, _count) = spawn_canned_server(vec![unauthorized_response()]).await;
let url = format!("http://127.0.0.1:{port}/repos/owner/repo/releases");
let resp = reqwest::Client::new().get(url).send().await.unwrap();
let status_error = resp.error_for_status_ref().unwrap_err();
let body = resp.text().await.unwrap();
let msg = format!(
"{:?}",
github_unauthorized_report(
status_error,
false,
Some(&crate::github::TokenSource::EnvVar("GITHUB_TOKEN")),
&body
)
);
assert!(msg.contains("github auth: no"), "{msg}");
assert!(!msg.contains("token from"), "{msg}");
assert!(!msg.contains("hint:"), "{msg}");
}
#[tokio::test(flavor = "current_thread")]
async fn test_read_bounded_error_body_caps_large_body() {
let big_body = "x".repeat(MAX_ERROR_BODY_BYTES + 4096);
let raw = format!(
"HTTP/1.1 401 Unauthorized\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
big_body.len(),
big_body
);
let leaked: &'static str = Box::leak(raw.into_boxed_str());
let (port, _count) = spawn_canned_server(vec![leaked]).await;
let url = format!("http://127.0.0.1:{port}/repos/owner/repo/releases");
let resp = reqwest::Client::new().get(url).send().await.unwrap();
let body = read_bounded_error_body(resp, Duration::from_secs(30)).await;
assert_eq!(body.len(), MAX_ERROR_BODY_BYTES);
}
#[tokio::test(flavor = "current_thread")]
async fn test_read_bounded_error_body_honors_deadline() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
tokio::spawn(async move {
if let Ok((mut sock, _)) = listener.accept().await {
let mut buf = [0u8; 1024];
let _ = sock.read(&mut buf).await;
let _ = sock
.write_all(b"HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n")
.await;
loop {
if sock.write_all(b"x").await.is_err() {
break;
}
tokio::time::sleep(Duration::from_millis(20)).await;
}
}
});
let url = format!("http://127.0.0.1:{port}/repos/owner/repo/releases");
let resp = reqwest::Client::new().get(url).send().await.unwrap();
let start = tokio::time::Instant::now();
let body = read_bounded_error_body(resp, Duration::from_millis(150)).await;
assert!(
start.elapsed() < Duration::from_secs(5),
"read must stop at the deadline"
);
assert!(
body.is_empty(),
"timed-out read yields no body, got {body:?}"
);
}
#[test]
fn test_netrc_should_apply_treats_netrc_as_fallback() {
assert!(netrc_should_apply(false, false));
assert!(!netrc_should_apply(false, true));
assert!(netrc_should_apply(true, true));
assert!(netrc_should_apply(true, false));
}
fn basic_netrc_headers() -> HeaderMap {
let mut h = HeaderMap::new();
h.insert(AUTHORIZATION, HeaderValue::from_static("Basic bmV0cmM="));
h
}
fn auth_value(headers: &HeaderMap) -> Vec<String> {
headers
.get_all(AUTHORIZATION)
.iter()
.map(|v| v.to_str().unwrap().to_string())
.collect()
}
#[test]
fn test_apply_netrc_keeps_forge_token_on_un_redirected_url() {
let url: Url = "https://api.github.com/repos/o/r/releases/assets/1"
.parse()
.unwrap();
let mut headers = HeaderMap::new();
headers.insert(
AUTHORIZATION,
HeaderValue::from_static("Bearer forge-token"),
);
let out = apply_netrc_credentials(headers, &url, &url, basic_netrc_headers());
assert_eq!(auth_value(&out), vec!["Bearer forge-token".to_string()]);
}
#[test]
fn test_apply_netrc_fills_in_when_no_existing_auth() {
let url: Url = "https://example.com/file".parse().unwrap();
let out = apply_netrc_credentials(HeaderMap::new(), &url, &url, basic_netrc_headers());
assert_eq!(auth_value(&out), vec!["Basic bmV0cmM=".to_string()]);
}
#[test]
fn test_apply_netrc_overrides_existing_auth_when_url_redirected() {
let original: Url = "https://public.example.com/file".parse().unwrap();
let redirected: Url = "https://mirror.internal/file".parse().unwrap();
let mut headers = HeaderMap::new();
headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer stale"));
let out = apply_netrc_credentials(headers, &original, &redirected, basic_netrc_headers());
assert_eq!(auth_value(&out), vec!["Basic bmV0cmM=".to_string()]);
}
#[test]
fn test_cross_host_replacement_clears_credentials_without_netrc() {
let original: Url = "https://user:password@public.example.com/file"
.parse()
.unwrap();
let mut redirected: Url = "https://user:password@mirror.internal/file"
.parse()
.unwrap();
let mut headers = HeaderMap::new();
headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer stale"));
headers.insert("x-api-key", HeaderValue::from_static("secret"));
headers.insert("x-request-id", HeaderValue::from_static("keep-me"));
clear_cross_host_credentials(&mut headers, &original, &mut redirected);
assert!(!headers.contains_key(AUTHORIZATION));
assert!(!headers.contains_key("x-api-key"));
assert_eq!(headers["x-request-id"], "keep-me");
assert!(redirected.username().is_empty());
assert!(redirected.password().is_none());
}
#[test]
fn test_apply_netrc_keeps_forge_token_on_same_host_path_rewrite() {
let original: Url = "https://github.com/o/r/releases/download/v1/f.tar.gz"
.parse()
.unwrap();
let rewritten: Url = "https://github.com/o/r/releases/download/v1/f-linux.tar.gz"
.parse()
.unwrap();
let mut headers = HeaderMap::new();
headers.insert(
AUTHORIZATION,
HeaderValue::from_static("Bearer forge-token"),
);
let out = apply_netrc_credentials(headers, &original, &rewritten, basic_netrc_headers());
assert_eq!(auth_value(&out), vec!["Bearer forge-token".to_string()]);
}
#[test]
fn test_rejects_credentials_on_https_to_http_replacement() {
let original: Url = "https://public.example.com/file".parse().unwrap();
let rewritten: Url = "http://mirror.internal/file".parse().unwrap();
let mut headers = HeaderMap::new();
headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer secret"));
let err = ensure_secure_replacement_credentials(&original, &rewritten, &headers).unwrap_err();
assert!(err.to_string().contains("refusing to send credentials"));
let mut cookie_headers = HeaderMap::new();
cookie_headers.insert(COOKIE, HeaderValue::from_static("session=secret"));
assert!(ensure_secure_replacement_credentials(&original, &rewritten, &cookie_headers).is_err());
let mut api_key_headers = HeaderMap::new();
api_key_headers.insert("x-api-key", HeaderValue::from_static("secret"));
assert!(
ensure_secure_replacement_credentials(&original, &rewritten, &api_key_headers).is_err()
);
let rewritten_with_credentials: Url =
"http://user:password@mirror.internal/file".parse().unwrap();
assert!(
ensure_secure_replacement_credentials(
&original,
&rewritten_with_credentials,
&HeaderMap::new(),
)
.is_err()
);
assert!(
ensure_secure_replacement_credentials(&original, &rewritten, &HeaderMap::new()).is_ok()
);
assert!(
ensure_secure_replacement_credentials(
&"http://public.example.com/file".parse().unwrap(),
&rewritten,
&headers,
)
.is_ok()
);
}
#[test]
fn unscoped_credential_detection_ignores_headers_reqwest_already_strips() {
let mut headers = HeaderMap::new();
headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer secret"));
headers.insert(COOKIE, HeaderValue::from_static("session=secret"));
headers.insert("x-request-id", HeaderValue::from_static("keep-me"));
assert!(!has_unscoped_credential(&headers));
headers.insert("x-api-key", HeaderValue::from_static("secret"));
assert!(has_unscoped_credential(&headers));
ForwardRules::default().retain_for(
&mut headers,
&Url::parse("https://origin.test/").unwrap(),
&Url::parse("https://elsewhere.test/").unwrap(),
);
assert!(!headers.contains_key(AUTHORIZATION));
assert!(!headers.contains_key("x-api-key"));
assert_eq!(headers["x-request-id"], "keep-me");
}
#[test]
fn user_headers_replace_host_auth_headers_instead_of_appending() {
let mut headers = HeaderMap::new();
headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer automatic"));
let mut user = HeaderMap::new();
user.insert(AUTHORIZATION, HeaderValue::from_static("Bearer configured"));
headers.extend(user);
let values = headers.get_all(AUTHORIZATION).iter().collect::<Vec<_>>();
assert_eq!(values, ["Bearer configured"]);
}
#[test]
fn header_digest_depends_on_values_without_exposing_them() {
let mut a = HeaderMap::new();
a.insert(AUTHORIZATION, HeaderValue::from_static("Bearer one"));
let mut b = HeaderMap::new();
b.insert(AUTHORIZATION, HeaderValue::from_static("Bearer two"));
assert_ne!(header_digest(&a), header_digest(&b));
assert_eq!(header_digest(&a), header_digest(&a.clone()));
assert!(!header_digest(&a).contains("one"));
}
#[test]
fn forward_hosts_accept_exact_hosts_and_subdomain_wildcards_only() {
for ok in ["cdn.example.com", "*.example.com", "localhost"] {
assert!(is_valid_forward_host(ok), "{ok}");
}
for bad in [
"",
"*",
"*.",
"*.*.com",
"a*.com",
"example.com:443",
"https://x.com",
".x.com",
"x.com.",
] {
assert!(!is_valid_forward_host(bad), "{bad}");
}
let patterns = vec![
"cdn.example.com".to_string(),
"*.assets.example.com".to_string(),
];
assert!(host_matches_any(&patterns, "cdn.example.com"));
assert!(host_matches_any(&patterns, "CDN.example.com"));
let mixed = vec!["*.Assets.EXAMPLE.com".to_string()];
assert!(host_matches_any(&mixed, "a.assets.example.com"));
assert!(host_matches_any(&mixed, "A.ASSETS.example.com"));
assert!(host_matches_any(&patterns, "a.assets.example.com"));
assert!(host_matches_any(&patterns, "a.b.assets.example.com"));
assert!(!host_matches_any(&patterns, "assets.example.com"));
assert!(!host_matches_any(&patterns, "evilassets.example.com"));
assert!(!host_matches_any(&patterns, "cdn.example.com.evil.test"));
}
#[test]
fn forward_rules_keep_only_listed_headers_on_listed_https_hosts() {
let key = HeaderName::from_static("x-api-key");
let mut headers = HeaderMap::new();
headers.insert(&key, HeaderValue::from_static("secret"));
headers.insert("x-other-token", HeaderValue::from_static("secret"));
headers.insert("x-request-id", HeaderValue::from_static("keep-me"));
let (rule_name, rule_value) =
forward_rule_header(&key, &["cdn.example.com".to_string()]).unwrap();
headers.insert(rule_name, rule_value);
let (mut real, rules) = split_forward_rules(&headers);
let mut resent = real.clone();
rules.attach_to(&mut resent);
let (resent_real, resent_rules) = split_forward_rules(&resent);
assert_eq!(resent_real, real);
assert_eq!(resent_rules.0, rules.0);
assert!(
real.keys()
.all(|name| !name.as_str().starts_with(FORWARD_RULE_PREFIX))
);
assert!(rules.applies_to(&real));
let from = Url::parse("https://origin.test/x").unwrap();
let mut elsewhere = real.clone();
rules.retain_for(
&mut elsewhere,
&from,
&Url::parse("https://other.example.com/x").unwrap(),
);
assert!(!elsewhere.contains_key(&key) && !elsewhere.contains_key("x-other-token"));
assert_eq!(elsewhere["x-request-id"], "keep-me");
let mut plain = real.clone();
let plain_next = Url::parse("http://cdn.example.com/x").unwrap();
rules.retain_for(&mut plain, &from, &plain_next);
assert!(!plain.contains_key(&key));
let mut http_chain = real.clone();
rules.retain_for(
&mut http_chain,
&Url::parse("http://origin.test/x").unwrap(),
&plain_next,
);
assert_eq!(http_chain["x-api-key"], "secret");
rules.retain_for(
&mut real,
&from,
&Url::parse("https://cdn.example.com/x").unwrap(),
);
assert_eq!(real["x-api-key"], "secret");
assert!(!real.contains_key("x-other-token"));
}
#[test]
fn with_host_auth_layers_configured_headers_over_automatic_ones() {
let url = Url::parse("https://example.com/file").unwrap();
let mut user = HeaderMap::new();
user.insert(AUTHORIZATION, HeaderValue::from_static("Bearer configured"));
user.insert("x-extra", HeaderValue::from_static("1"));
let merged = with_host_auth(&url, &user).unwrap();
assert_eq!(merged.get_all(AUTHORIZATION).iter().count(), 1);
assert_eq!(merged[AUTHORIZATION], "Bearer configured");
assert_eq!(merged["x-extra"], "1");
}
#[test]
fn a_raw_content_404_with_a_token_is_retried_without_it() {
let raw = Url::parse("https://raw.githubusercontent.com/o/r/abc/SKILL.md").unwrap();
let mut with_token = HeaderMap::new();
with_token.insert(AUTHORIZATION, HeaderValue::from_static("Bearer ghp_stale"));
assert_eq!(
raw_content_token_to_drop(&raw, StatusCode::NOT_FOUND, &with_token),
Some("ghp_stale")
);
assert_eq!(
raw_content_token_to_drop(&raw, StatusCode::OK, &with_token),
None
);
assert_eq!(
raw_content_token_to_drop(&raw, StatusCode::NOT_FOUND, &HeaderMap::new()),
None
);
let api = Url::parse("https://api.github.com/repos/o/r/contents/SKILL.md").unwrap();
assert_eq!(
raw_content_token_to_drop(&api, StatusCode::NOT_FOUND, &with_token),
None
);
let other = Url::parse("https://example.com/o/r/abc/SKILL.md").unwrap();
assert_eq!(
raw_content_token_to_drop(&other, StatusCode::NOT_FOUND, &with_token),
None
);
let msg = rejected_raw_token_warning(Some(&crate::github::TokenSource::EnvVar("GITHUB_TOKEN")));
assert!(
msg.contains("did not accept the token in `GITHUB_TOKEN`"),
"{msg}"
);
assert!(msg.contains("mise token github"), "{msg}");
assert!(
rejected_raw_token_warning(None).contains("configured GitHub token"),
"{}",
rejected_raw_token_warning(None)
);
}
const NOT_FOUND_RESPONSE: &str =
"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
const SKILL_RESPONSE: &str = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 6\r\nConnection: close\r\n\r\nskill\n";
fn raw_content_client(port: u16) -> Client {
let timeout = Duration::from_secs(3);
let resolved = |decode: bool| {
Client::_new_with(decode)
.no_proxy()
.resolve(
"raw.githubusercontent.com",
std::net::SocketAddr::from(([127, 0, 0, 1], port)),
)
.read_timeout(timeout)
.connect_timeout(timeout)
.build()
.unwrap()
};
Client {
reqwest: Ok(resolved(true)),
manual_redirects: Default::default(),
undecoded: std::sync::OnceLock::from(Ok(resolved(false))),
undecoded_manual_redirects: Default::default(),
timeout,
read_timeout: Some(timeout),
downgrade: Downgrade::Refuse,
kind: ClientKind::Http,
}
}
async fn get_raw_content_with_token(
responses: Vec<&'static str>,
) -> (
Result<String>,
usize,
std::sync::Arc<std::sync::Mutex<Vec<String>>>,
) {
let (port, count, requests) = spawn_recording_server(responses).await;
let mut headers = HeaderMap::new();
headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer ghp-stale"));
let result = raw_content_client(port)
.get_text_request(format!(
"http://raw.githubusercontent.com:{port}/o/r/abc/SKILL.md"
))
.headers(&headers)
.send()
.await;
(
result,
count.load(std::sync::atomic::Ordering::SeqCst),
requests,
)
}
#[tokio::test(flavor = "multi_thread")]
async fn a_raw_content_404_is_fetched_again_without_the_token() {
let (result, count, requests) =
get_raw_content_with_token(vec![NOT_FOUND_RESPONSE, SKILL_RESPONSE, SKILL_RESPONSE]).await;
assert_eq!(result.unwrap(), "skill\n");
assert_eq!(count, 2);
let requests = requests.lock().unwrap();
assert!(
requests[0]
.to_ascii_lowercase()
.contains("authorization: bearer ghp-stale"),
"{}",
requests[0]
);
assert!(
!requests[1].to_ascii_lowercase().contains("authorization:"),
"{}",
requests[1]
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_raw_content_404_without_the_token_is_still_a_404() {
let (result, count, requests) = get_raw_content_with_token(vec![NOT_FOUND_RESPONSE; 6]).await;
let err = result.unwrap_err();
assert!(format!("{err:#}").contains("404"), "{err:#}");
assert_eq!(count, 2);
let requests = requests.lock().unwrap();
assert!(
!requests[1].to_ascii_lowercase().contains("authorization:"),
"{}",
requests[1]
);
}
#[tokio::test(flavor = "multi_thread")]
async fn a_download_retry_after_a_raw_content_404_leaves_the_token_out() {
let _guard = set_test_http_retries(1);
let (port, count, requests) = spawn_recording_server(vec![
NOT_FOUND_RESPONSE,
truncated_download_response(),
resumed_download_response(),
])
.await;
let dir = tempfile::tempdir().unwrap();
let destination = dir.path().join("artifact");
let mut headers = HeaderMap::new();
headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer ghp-stale"));
raw_content_client(port)
.download_file_with_headers(
format!("http://raw.githubusercontent.com:{port}/o/r/abc/artifact"),
&destination,
&headers,
None,
)
.await
.unwrap();
assert_eq!(std::fs::read(&destination).unwrap(), b"helloworld");
assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 3);
let requests = requests.lock().unwrap();
assert!(
requests[0]
.to_ascii_lowercase()
.contains("authorization: bearer ghp-stale"),
"{}",
requests[0]
);
let resumed = requests[2].to_ascii_lowercase();
assert!(!requests[1].to_ascii_lowercase().contains("authorization:"));
assert!(!resumed.contains("authorization:"), "{resumed}");
assert!(resumed.contains("range: bytes=5-"), "{resumed}");
assert!(resumed.contains("if-range: \"artifact-v1\""), "{resumed}");
}