use std::{net::SocketAddr, path::Path, time::Duration};
use reqwest::{
header::{HeaderValue, AUTHORIZATION, LOCATION},
NoProxy, Proxy, Response,
};
use rho_protocol::{
methods::{
ForgeFetchParams, ForgeFetchResponse, FORGE_FETCH, FORGE_FETCH_MAX_BYTES,
FORGE_FETCH_MAX_REDIRECTS,
},
Caller, ClientEnvironment, ErrorCode, HostStreamWriter, RpcError,
};
use tokio::{sync::OnceCell, time::Instant};
use url::Url;
use super::{
absolute, failed, gh_command, log_call, spawn_stream, supervised_output, var, Machine, Origin,
FORGE_DEADLINE,
};
use crate::{app::pull_requests::gh_failure, error_causes::with_causes};
const GH_TOKEN_DEADLINE: Duration = Duration::from_secs(10);
const GITHUB_IMAGES: &str = ".githubusercontent.com";
const GITHUB_ATTACHMENTS: &str = "github-production-user-asset-6210df.s3.amazonaws.com";
const SOCKS: [&str; 4] = ["socks4", "socks4a", "socks5", "socks5h"];
pub(crate) struct Web {
scheme: &'static str,
port: Option<u16>,
deadline: Duration,
resolve: Vec<(String, SocketAddr)>,
client: OnceCell<reqwest::Client>,
}
impl Web {
pub(crate) fn public() -> Self {
Self {
scheme: "https",
port: None,
deadline: FORGE_DEADLINE,
resolve: Vec::new(),
client: OnceCell::new(),
}
}
async fn client(
&self,
environment: &ClientEnvironment,
origin: Origin,
) -> Result<reqwest::Client, RpcError> {
if origin == Origin::Fallback {
return client(environment, self);
}
self.client
.get_or_try_init(|| async { client(environment, self) })
.await
.cloned()
}
}
pub(super) async fn fetch(
machine: &Machine,
caller: Caller,
params: ForgeFetchParams,
web: &Web,
) -> Result<ForgeFetchResponse, RpcError> {
let limit = params.byte_limit();
let ForgeFetchParams { url, host, gh, .. } = params;
let url = Url::parse(&url);
let url_shown = url
.as_ref()
.map_or_else(|_| "(not a URL)".to_owned(), shown);
tracing::info_span!("forge_fetch", url = %url_shown, forge = %host)
.in_scope(|| log_call(&caller, FORGE_FETCH, gh.as_ref()));
let url = url.map_err(|error| refused(format!("It isn't a URL: {error}.")))?;
let gh = gh.as_ref().map(absolute).transpose()?;
let late = format!(
"It didn't come within {} s (FORGE_DEADLINE_SECS).",
web.deadline.as_secs()
);
let deadline = Instant::now() + web.deadline;
let answered = tokio::time::timeout_at(deadline, async {
let (environment, origin) = machine.login_environment_and_origin().await;
let client = web.client(&environment, origin).await?;
follow(&client, url, &host, web, gh, &environment).await
})
.await;
let response = answered.map_err(|_| failed(late.clone()))??;
if let Some(length) = response.content_length().filter(|&length| length > limit) {
return Err(refused(format!(
"It's {length} bytes, over the {limit} this fetch takes (max_bytes, up to FORGE_FETCH_MAX_BYTES, {FORGE_FETCH_MAX_BYTES})."
)));
}
let stream = spawn_stream(&caller, |writer| {
pump(response, limit, deadline, late, writer)
})?;
Ok(ForgeFetchResponse::new(stream))
}
async fn follow(
client: &reqwest::Client,
mut url: Url,
host: &str,
web: &Web,
gh: Option<&Path>,
environment: &ClientEnvironment,
) -> Result<Response, RpcError> {
let token = OnceCell::new();
for hop in 0..=FORGE_FETCH_MAX_REDIRECTS {
allowed(&url, host, web)?;
let signing = match gh {
Some(gh) if signs_in(&url, host, web) => {
Some(token.get_or_init(|| ask(gh, host, environment)).await)
}
_ => None,
};
let unsigned = signing.and_then(|token| token.as_ref().err());
let hop_failed = |what: String| {
failed(match unsigned {
Some(why) => format!("{what}; it went unsigned: {why}."),
None => format!("{what}."),
})
};
tracing::debug!(
hop,
url = %shown(&url),
signed = matches!(signing, Some(Ok(_))),
"forge fetch"
);
let mut request = client.get(url.clone());
if let Some(Ok(bearer)) = signing {
request = request.header(AUTHORIZATION, bearer.clone());
}
let response = request
.send()
.await
.map_err(|error| hop_failed(said(error)))?;
let status = response.status();
if status.is_success() {
return Ok(response);
}
if !status.is_redirection() {
return Err(hop_failed(format!("It answered {status}")));
}
let location = response
.headers()
.get(LOCATION)
.ok_or_else(|| hop_failed(format!("It answered {status} without saying where to")))?;
url = location
.to_str()
.ok()
.and_then(|to| url.join(to).ok())
.ok_or_else(|| refused("It moved somewhere that isn't a URL.".to_owned()))?;
}
Err(refused(format!(
"It redirected more than {FORGE_FETCH_MAX_REDIRECTS} times (FORGE_FETCH_MAX_REDIRECTS)."
)))
}
fn plain_host(url: &Url, web: &Web) -> Option<String> {
let plain = url.scheme() == web.scheme
&& url.username().is_empty()
&& url.password().is_none()
&& url.port() == web.port;
if !plain {
return None;
}
url.host_str().map(str::to_ascii_lowercase)
}
fn allowed(url: &Url, host: &str, web: &Web) -> Result<(), RpcError> {
let forge = host.to_ascii_lowercase();
let ours = plain_host(url, web).is_some_and(|to| {
to == forge
|| (!forge.is_empty() && to.ends_with(&format!(".{forge}")))
|| to.ends_with(GITHUB_IMAGES)
|| to == GITHUB_ATTACHMENTS
});
if ours {
Ok(())
} else {
Err(refused(format!(
"The daemon fetches pictures over {} from {host}, the hosts under it and GitHub's image hosts alone, with no user or port.",
web.scheme
)))
}
}
fn signs_in(url: &Url, host: &str, web: &Web) -> bool {
plain_host(url, web).is_some_and(|to| to.eq_ignore_ascii_case(host))
}
async fn ask(
gh: &Path,
host: &str,
environment: &ClientEnvironment,
) -> Result<HeaderValue, String> {
let mut command = gh_command(gh, environment);
command
.args(["auth", "token"])
.arg(format!("--hostname={host}"));
let asked = tokio::time::timeout(GH_TOKEN_DEADLINE, supervised_output(&mut command)).await;
let late = asked.is_err();
let unsigned = match asked {
Ok(Ok(output)) if output.status.success() => {
let token = output.stdout.trim_ascii();
if token.is_empty() {
"gh auth token printed no token".to_owned()
} else {
let bearer = HeaderValue::from_bytes(&[b"Bearer ".as_slice(), token].concat());
match bearer {
Ok(mut bearer) => {
bearer.set_sensitive(true);
return Ok(bearer);
}
Err(_) => "gh auth token printed what a header can't carry".to_owned(),
}
}
}
Ok(Ok(output)) => format!(
"gh auth token failed: {}",
gh_failure(&output.stderr, output.status).trim_end_matches('.')
),
Ok(Err(error)) => format!("Couldn't run gh: {error}"),
Err(_) => format!(
"gh gave no token within {} s (GH_TOKEN_DEADLINE)",
GH_TOKEN_DEADLINE.as_secs()
),
};
if late {
tracing::warn!("a forge fetch goes unsigned: {unsigned}");
} else {
tracing::debug!("a forge fetch goes unsigned: {unsigned}");
}
Err(unsigned)
}
fn client(environment: &ClientEnvironment, web: &Web) -> Result<reqwest::Client, RpcError> {
let mut builder = crate::web_client::no_redirect_builder()
.no_proxy()
.user_agent(concat!("rho/", env!("CARGO_PKG_VERSION")));
if let Some(proxy) = proxy(environment)? {
builder = builder.proxy(proxy);
}
for (name, address) in &web.resolve {
builder = builder.resolve(name, *address);
}
builder.build().map_err(|error| {
failed(format!(
"Couldn't make the fetch's client: {}.",
said(error)
))
})
}
fn proxy(environment: &ClientEnvironment) -> Result<Option<Proxy>, RpcError> {
let first = |names: [&'static str; 2]| {
names.into_iter().find_map(|name| {
let value = var(environment, name).filter(|value| !value.is_empty())?;
Some((name, value))
})
};
let Some((name, address)) =
first(["https_proxy", "HTTPS_PROXY"]).or_else(|| first(["all_proxy", "ALL_PROXY"]))
else {
return Ok(None);
};
let scheme = address
.split_once("://")
.map(|(scheme, _)| scheme.to_ascii_lowercase());
if let Some(scheme) = scheme.filter(|scheme| SOCKS.contains(&scheme.as_str())) {
return Err(failed(format!(
"The login's {name} names a {scheme} proxy, which the daemon can't fetch through: only an http or https one."
)));
}
let proxy = Proxy::all(address)
.map_err(|_| failed(format!("The login's {name} isn't a proxy's URL.")))?;
let bypass = first(["no_proxy", "NO_PROXY"]).and_then(|(_, hosts)| NoProxy::from_string(hosts));
Ok(Some(proxy.no_proxy(bypass)))
}
enum Ended {
Done,
Cut,
Failed(String),
Closed,
}
async fn pump(
mut response: Response,
limit: u64,
deadline: Instant,
late: String,
mut writer: HostStreamWriter,
) {
let ended = tokio::time::timeout_at(deadline, copy(&mut response, limit, &mut writer)).await;
match ended {
Ok(Ended::Done) => writer.finish(),
Ok(Ended::Cut) => {
tracing::debug!(
limit,
"a forge fetch ran past its limit, so its stream ends truncated"
);
writer.truncate();
}
Ok(Ended::Failed(message)) => writer.fail(message),
Ok(Ended::Closed) => {}
Err(_) => writer.fail(late),
}
}
async fn copy(response: &mut Response, limit: u64, writer: &mut HostStreamWriter) -> Ended {
let mut room = limit;
loop {
let chunk = tokio::select! {
chunk = response.chunk() => chunk,
() = writer.closed() => return Ended::Closed,
};
let mut chunk = match chunk {
Ok(Some(chunk)) => chunk,
Ok(None) => return Ended::Done,
Err(error) => return Ended::Failed(format!("{}.", said(error))),
};
let length = chunk.len() as u64;
let over = length > room;
if over {
chunk.truncate(room as usize);
}
room -= chunk.len() as u64;
if !chunk.is_empty() && writer.write(chunk.into()).await.is_err() {
return Ended::Closed;
}
if over {
return Ended::Cut;
}
}
}
fn shown(url: &Url) -> String {
format!(
"{}://{}{}",
url.scheme(),
url.host_str().unwrap_or_default(),
url.path()
)
}
fn said(error: reqwest::Error) -> String {
with_causes(&error.without_url())
}
fn refused(message: String) -> RpcError {
RpcError::new(ErrorCode::ForgeFetchRefused, message)
}
#[cfg(test)]
#[path = "fetch_tests.rs"]
mod tests;