use std::sync::{Arc, Mutex};
use pretty_assertions::assert_eq;
use rho_protocol::methods::{HostPath, HostStreamEnd};
use tokio::{
io::{AsyncReadExt as _, AsyncWriteExt as _},
net::{TcpListener, TcpStream},
};
use super::*;
use crate::app::daemon_host::machine_test_support::*;
#[cfg(unix)]
use crate::executable::write_program;
#[derive(Clone, Debug, PartialEq, Eq)]
struct Asked {
host: String,
target: String,
authorization: Option<String>,
}
impl Asked {
fn new(host: &str, target: &str, authorization: Option<&str>) -> Self {
Self {
host: host.to_owned(),
target: target.to_owned(),
authorization: authorization.map(str::to_owned),
}
}
}
type Answer = dyn Fn(&Asked, u16) -> Vec<u8> + Send + Sync;
struct Server {
port: u16,
asked: Arc<Mutex<Vec<Asked>>>,
}
impl Server {
fn asked(&self) -> Vec<Asked> {
self.asked.lock().unwrap().clone()
}
}
async fn serve(answer: impl Fn(&Asked, u16) -> Vec<u8> + Send + Sync + 'static) -> Server {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let asked = Arc::new(Mutex::new(Vec::new()));
let answer: Arc<Answer> = Arc::new(answer);
let seen = Arc::clone(&asked);
tokio::spawn(async move {
loop {
let Ok((socket, _)) = listener.accept().await else {
return;
};
tokio::spawn(answer_each(
socket,
port,
Arc::clone(&answer),
Arc::clone(&seen),
));
}
});
Server { port, asked }
}
async fn answer_each(
mut socket: TcpStream,
port: u16,
answer: Arc<Answer>,
seen: Arc<Mutex<Vec<Asked>>>,
) {
let mut buffer = Vec::new();
loop {
let end = loop {
if let Some(end) = buffer.windows(4).position(|window| window == b"\r\n\r\n") {
break end;
}
let mut read = [0; 4096];
match socket.read(&mut read).await {
Ok(0) | Err(_) => return,
Ok(count) => buffer.extend_from_slice(&read[..count]),
}
};
let head = String::from_utf8_lossy(&buffer[..end]).into_owned();
buffer.drain(..end + 4);
let mut lines = head.split("\r\n");
let target = lines.next().unwrap().split(' ').nth(1).unwrap();
let mut asked = Asked::new("", target, None);
for (name, value) in lines.filter_map(|line| line.split_once(':')) {
let value = value.trim();
match name.to_ascii_lowercase().as_str() {
"host" => asked.host = value.split(':').next().unwrap().to_owned(),
"authorization" => asked.authorization = Some(value.to_owned()),
_ => {}
}
}
seen.lock().unwrap().push(asked.clone());
let response = answer(&asked, port);
if socket.write_all(&response).await.is_err() {
return;
}
if String::from_utf8_lossy(&response).contains("Connection: close") {
let _ = socket.shutdown().await;
return;
}
}
}
fn picture(body: &[u8]) -> Vec<u8> {
let head = format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n", body.len());
[head.as_bytes(), body].concat()
}
fn unsized_picture(body: &[u8]) -> Vec<u8> {
[
b"HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n".as_slice(),
body,
]
.concat()
}
fn moved(location: &str) -> Vec<u8> {
format!("HTTP/1.1 302 Found\r\nLocation: {location}\r\nContent-Length: 0\r\n\r\n").into_bytes()
}
fn not_found() -> Vec<u8> {
b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n".to_vec()
}
fn web(port: u16, deadline: Duration) -> Web {
let here = SocketAddr::from(([127, 0, 0, 1], 0));
let hosts = ["forge.test", "img.forge.test", "x.githubusercontent.com"];
Web {
scheme: "http",
port: Some(port),
deadline,
resolve: hosts.map(|host| (host.to_owned(), here)).to_vec(),
client: OnceCell::new(),
}
}
async fn fetch_on(
machine: &Machine,
caller: &Caller,
web: &Web,
url: String,
gh: Option<HostPath>,
max_bytes: u64,
) -> Result<ForgeFetchResponse, RpcError> {
let params = ForgeFetchParams::new(url, "forge.test", gh, max_bytes);
fetch(machine, caller.clone(), params, web).await
}
#[test]
fn only_the_forges_hosts_are_fetched() {
let cases = [
("https://github.com/user-attachments/assets/1", true),
("https://GitHub.com/a.png", true),
("https://github.com:443/a.png", true),
("https://api.github.com/x", true),
(
"https://private-user-images.githubusercontent.com/1.png",
true,
),
(
"https://github-production-user-asset-6210df.s3.amazonaws.com/1.png",
true,
),
("http://github.com/a.png", false),
("https://githubusercontent.com/a.png", false),
("https://example.com/a.png", false),
("https://169.254.169.254/latest/meta-data", false),
("https://localhost/a.png", false),
("https://github.com.evil.example/a.png", false),
("https://x.githubusercontent.com@10.0.0.1/a.png", false),
("https://github.com:x@github.com/a.png", false),
("https://10.0.0.1\\.githubusercontent.com/a.png", false),
(
"https://user-images.githubusercontent.com:8080/a.png",
false,
),
("file:///etc/passwd", false),
("https:///a.png", false),
];
for (url, fetched) in cases {
let parsed = Url::parse(url).unwrap();
let answer = allowed(&parsed, "github.com", &Web::public());
assert_eq!(answer.is_ok(), fetched, "{url}");
if let Err(error) = answer {
assert_eq!(error.code, ErrorCode::ForgeFetchRefused.code(), "{url}");
}
}
}
#[test]
fn the_token_goes_to_the_forge_alone() {
let cases = [
("https://github.com/user-attachments/assets/1", true),
("https://GitHub.com/a.png", true),
("https://github.com?x", true),
("http://github.com/a.png", false),
("https://api.github.com/a.png", false),
("https://avatars.githubusercontent.com/u/1", false),
("https://github.com.evil.example/a.png", false),
("https://github.com@evil.example/a.png", false),
("https://github.com:8443/a.png", false),
];
for (url, sends) in cases {
let parsed = Url::parse(url).unwrap();
assert_eq!(
signs_in(&parsed, "GitHub.com", &Web::public()),
sends,
"{url}"
);
}
}
#[cfg(unix)]
#[tokio::test]
async fn a_fetch_follows_checked_redirects_and_signs_the_forge_alone() {
let server = serve(|asked, port| match asked.target.as_str() {
"/moved" => moved(&format!("http://img.forge.test:{port}/under")),
"/under" => moved(&format!("http://x.githubusercontent.com:{port}/storage")),
"/storage" => moved("/picture"),
"/picture" => picture(b"PNG"),
"/away" => moved(&format!("http://elsewhere.test:{port}/picture")),
"/loop" => moved("/loop"),
_ => not_found(),
})
.await;
let dir = tempfile::tempdir().unwrap();
let gh = dir.path().join("gh");
write_program(
&gh,
"#!/bin/sh\n[ \"$*\" = 'auth token --hostname=forge.test' ] && echo secret\n",
);
let (machine, caller) = (machine_in(&[]), caller());
let web = web(server.port, FORGE_DEADLINE);
let at = |path: &str| format!("http://forge.test:{}{path}", server.port);
let fetch = |path: &str| fetch_on(&machine, &caller, &web, at(path), Some(host(&gh)), 1 << 20);
let fetched = fetch("/moved").await.unwrap();
assert_eq!(
read_out(&caller, fetched.stream).await,
(b"PNG".to_vec(), HostStreamEnd::Done)
);
let signed = Some("Bearer secret");
assert_eq!(
server.asked(),
[
Asked::new("forge.test", "/moved", signed),
Asked::new("img.forge.test", "/under", None),
Asked::new("x.githubusercontent.com", "/storage", None),
Asked::new("x.githubusercontent.com", "/picture", None),
]
);
let looped = fetch("/loop").await.unwrap_err();
let away = fetch("/away").await.unwrap_err();
for refused in [&looped, &away] {
assert_eq!(
refused.code,
ErrorCode::ForgeFetchRefused.code(),
"{refused:?}"
);
}
let mut asked = server.asked();
let after = asked.split_off(4);
let looping = Asked::new("forge.test", "/loop", signed);
let expected = [
vec![looping; 1 + FORGE_FETCH_MAX_REDIRECTS as usize],
vec![Asked::new("forge.test", "/away", signed)],
]
.concat();
assert_eq!(after, expected);
}
#[tokio::test]
async fn a_picture_past_the_limit_is_refused_or_cut() {
let server = serve(|asked, _| match asked.target.as_str() {
"/said" => picture(&[b'x'; 2000]),
"/unsaid" => unsized_picture(&[b'x'; 2000]),
"/exact" => picture(&[b'x'; 1000]),
_ => not_found(),
})
.await;
let (machine, caller) = (machine_in(&[]), caller());
let web = web(server.port, FORGE_DEADLINE);
let at = |path: &str| format!("http://forge.test:{}{path}", server.port);
let fetch = |path: &str| fetch_on(&machine, &caller, &web, at(path), None, 1000);
let said = fetch("/said").await.unwrap_err();
assert_eq!(said.code, ErrorCode::ForgeFetchRefused.code());
assert!(
said.message.contains("2000") && said.message.contains("1000"),
"{}",
said.message
);
let unsaid = fetch("/unsaid").await.unwrap();
assert_eq!(
read_out(&caller, unsaid.stream).await,
(vec![b'x'; 1000], HostStreamEnd::Truncated)
);
let exact = fetch("/exact").await.unwrap();
assert_eq!(
read_out(&caller, exact.stream).await,
(vec![b'x'; 1000], HostStreamEnd::Done)
);
let gone = fetch("/gone").await.unwrap_err();
assert_eq!(
(gone.code, gone.message.as_str()),
(
ErrorCode::HostCallFailed.code(),
"It answered 404 Not Found."
)
);
}
#[tokio::test]
async fn a_fetch_that_hangs_fails_at_its_deadline() {
let server = serve(|asked, _| match asked.target.as_str() {
"/picture" => picture(b"PNG"),
"/partway" => b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\npartial".to_vec(),
_ => Vec::new(),
})
.await;
let (machine, caller) = (machine_in(&[]), caller());
let web = web(server.port, Duration::from_secs(1));
let at = |path: &str| format!("http://forge.test:{}{path}", server.port);
let late = "It didn't come within";
let warm = fetch_on(&machine, &caller, &web, at("/picture"), None, 1000)
.await
.unwrap();
assert_eq!(read_out(&caller, warm.stream).await.1, HostStreamEnd::Done);
let partway = fetch_on(&machine, &caller, &web, at("/partway"), None, 1000)
.await
.unwrap();
let (bytes, end) = read_out(&caller, partway.stream).await;
assert_eq!(bytes, b"partial");
assert!(
matches!(&end, HostStreamEnd::Failed { message, .. } if message.starts_with(late)),
"{end:?}"
);
let silent = fetch_on(&machine, &caller, &web, at("/silent"), None, 1000)
.await
.unwrap_err();
assert_eq!(silent.code, ErrorCode::HostCallFailed.code());
assert!(silent.message.starts_with(late), "{}", silent.message);
}
#[tokio::test]
async fn a_fetch_goes_through_the_logins_proxy() {
let proxy = serve(|_, _| picture(b"PNG")).await;
let address = format!("http://127.0.0.1:{}", proxy.port);
let (machine, caller) = (machine_in(&[("https_proxy", address.as_str())]), caller());
let web = Web {
resolve: Vec::new(),
..web(9, FORGE_DEADLINE)
};
let url = "http://forge.test:9/picture";
let fetched = fetch_on(&machine, &caller, &web, url.to_owned(), None, 1000)
.await
.unwrap();
assert_eq!(
read_out(&caller, fetched.stream).await,
(b"PNG".to_vec(), HostStreamEnd::Done)
);
assert_eq!(proxy.asked(), [Asked::new("forge.test", url, None)]);
}
#[tokio::test]
async fn a_socks_proxy_is_refused_by_name() {
let (machine, caller) = (
machine_in(&[("all_proxy", "SOCKS5H://rho:hunter2@127.0.0.1:1080")]),
caller(),
);
let web = web(9, FORGE_DEADLINE);
let url = "http://forge.test:9/picture".to_owned();
let refused = fetch_on(&machine, &caller, &web, url, None, 1000)
.await
.unwrap_err();
assert_eq!(refused.code, ErrorCode::HostCallFailed.code());
assert_eq!(
refused.message,
"The login's all_proxy names a socks5h proxy, which the daemon can't fetch through: only an http or https one."
);
}
#[cfg(unix)]
#[tokio::test]
async fn a_failed_fetch_says_why_it_went_unsigned() {
let server = serve(|_, _| not_found()).await;
let dir = tempfile::tempdir().unwrap();
let gh = dir.path().join("gh");
write_program(
&gh,
"#!/bin/sh\necho 'no oauth token found for forge.test' >&2\nexit 1\n",
);
let (machine, caller) = (machine_in(&[]), caller());
let web = web(server.port, FORGE_DEADLINE);
let fetch = |to: &str| {
let url = format!("http://{to}:{}/picture", server.port);
fetch_on(&machine, &caller, &web, url, Some(host(&gh)), 1000)
};
let forge = fetch("forge.test").await.unwrap_err();
assert_eq!(
forge.message,
"It answered 404 Not Found; it went unsigned: gh auth token failed: no oauth token found for forge.test."
);
let image_host = fetch("x.githubusercontent.com").await.unwrap_err();
assert_eq!(image_host.message, "It answered 404 Not Found.");
}