use super::CacheTier;
use super::errors::preflight_error;
use super::guard::AddrGuard;
use super::redirect::RedirectScope;
use super::redirect::redirect_policy;
use super::redirect::trusted_origin_redirect_policy;
use super::resolver::BlockedAddrResolver;
#[cfg(test)]
use super::resolver::TestLookup;
use crate::error::Result;
use crate::net_policy::{
AccessSnapshot, GuardedEgress, RegistryAccessPolicy, SystemProxy, TrustedPrefix,
WorkspaceRegistryAccess, normalize_host,
};
use reqwest::{Client, Url};
use std::hash::{Hash, Hasher};
use std::str::FromStr;
use std::sync::Arc;
pub(super) const HTTP_TIMEOUT_SECS: u64 = 30;
pub(super) const HTTP_CONNECT_TIMEOUT_SECS: u64 = 10;
fn detect_system_proxy() -> SystemProxy {
#[cfg(test)]
{
SystemProxy::default()
}
#[cfg(not(test))]
{
SystemProxy::detect()
}
}
#[derive(Debug, Clone)]
pub(super) enum ProxyRoute {
System(SystemProxy),
Bypass,
#[cfg(test)]
Fixed(Url),
}
impl ProxyRoute {
pub(super) fn for_tier(guard: &AddrGuard, egress: GuardedEgress) -> Self {
match (guard, egress) {
(AddrGuard::Baseline, GuardedEgress::Direct | GuardedEgress::Proxy)
| (AddrGuard::WorkspaceDeclared(_), GuardedEgress::Proxy) => {
Self::System(detect_system_proxy())
}
(AddrGuard::WorkspaceDeclared(_), GuardedEgress::Direct) => Self::Bypass,
}
}
pub(super) fn exempt_hosts(&self) -> Arc<[String]> {
match self {
Self::System(proxy) => proxy.hosts().map(normalize_host).collect(),
Self::Bypass => Arc::from([]),
#[cfg(test)]
Self::Fixed(url) => url.host_str().map(normalize_host).into_iter().collect(),
}
}
fn apply(&self, builder: reqwest::ClientBuilder) -> reqwest::ClientBuilder {
match self {
Self::System(_) => builder,
Self::Bypass => builder.no_proxy(),
#[cfg(test)]
Self::Fixed(url) => match reqwest::Proxy::all(url.as_str()) {
Ok(proxy) => builder.no_proxy().proxy(proxy),
Err(_) => builder,
},
}
}
}
pub(super) fn base_client_builder(route: &ProxyRoute) -> reqwest::ClientBuilder {
route
.apply(Client::builder())
.user_agent(format!("deps-lsp/{}", env!("CARGO_PKG_VERSION")))
.connect_timeout(std::time::Duration::from_secs(HTTP_CONNECT_TIMEOUT_SECS))
.timeout(std::time::Duration::from_secs(HTTP_TIMEOUT_SECS))
.referer(false)
}
pub(super) fn build_client_inner(
redirect: reqwest::redirect::Policy,
resolver: BlockedAddrResolver,
route: &ProxyRoute,
) -> Client {
#[expect(
clippy::expect_used,
reason = "fixed, hardcoded client configuration — no attacker-influenced input; can \
only fail on a genuinely broken TLS backend, which is unrecoverable anyway"
)]
base_client_builder(route)
.redirect(redirect)
.dns_resolver(resolver)
.build()
.expect("failed to create HTTP client")
}
#[cfg(test)]
pub(super) fn build_guarded_client_with_lookup(guard: AddrGuard, lookup: TestLookup) -> Client {
let route = ProxyRoute::for_tier(&guard, GuardedEgress::Direct);
build_client_inner(
redirect_policy(guard.clone(), RedirectScope::AnyHost),
BlockedAddrResolver::with_lookup(guard, route.exempt_hosts(), lookup),
&route,
)
}
#[derive(Clone)]
pub(super) struct Transport {
client: Client,
tier: CacheTier,
preflight: Option<BlockedAddrResolver>,
}
impl Transport {
pub(super) const fn client(&self) -> &Client {
&self.client
}
pub(super) const fn tier(&self) -> CacheTier {
self.tier
}
#[cfg(test)]
pub(super) const fn has_preflight(&self) -> bool {
self.preflight.is_some()
}
pub(super) fn baseline() -> Self {
Self::standard(
AddrGuard::Baseline,
GuardedEgress::Direct,
CacheTier::Baseline,
RedirectScope::AnyHost,
)
}
pub(super) fn workspace(policy: &Arc<RegistryAccessPolicy>) -> Self {
let snapshot = policy.snapshot();
let tier = CacheTier::WorkspaceDeclared(snapshot.level);
let egress = policy.egress();
Self::standard(
AddrGuard::WorkspaceDeclared(snapshot),
egress,
tier,
RedirectScope::for_egress(egress),
)
}
pub(super) fn origin_pinned(trusted_origin: &TrustedPrefix) -> Self {
Self::assemble(
trusted_origin_redirect_policy(trusted_origin.clone()),
AddrGuard::Baseline,
GuardedEgress::Direct,
CacheTier::Baseline,
)
}
pub(super) fn origin_pinned_guarded(
trusted_origin: &TrustedPrefix,
snapshot: AccessSnapshot,
egress: GuardedEgress,
) -> Self {
let digest = pinned_digest(trusted_origin, snapshot.level);
Self::assemble(
trusted_origin_redirect_policy(trusted_origin.clone()),
AddrGuard::WorkspaceDeclared(snapshot),
egress,
CacheTier::Pinned { digest },
)
}
fn standard(
guard: AddrGuard,
egress: GuardedEgress,
tier: CacheTier,
scope: RedirectScope,
) -> Self {
let redirect = redirect_policy(guard.clone(), scope);
Self::assemble(redirect, guard, egress, tier)
}
fn assemble(
redirect: reqwest::redirect::Policy,
guard: AddrGuard,
egress: GuardedEgress,
tier: CacheTier,
) -> Self {
let route = ProxyRoute::for_tier(&guard, egress);
let resolver = BlockedAddrResolver::new(guard, route.exempt_hosts());
Self::from_parts(redirect, resolver, egress, &route, tier)
}
pub(super) fn from_parts(
redirect: reqwest::redirect::Policy,
resolver: BlockedAddrResolver,
egress: GuardedEgress,
route: &ProxyRoute,
tier: CacheTier,
) -> Self {
let preflight = match (&resolver.guard, egress) {
(AddrGuard::WorkspaceDeclared(_), GuardedEgress::Proxy) => Some(BlockedAddrResolver {
exempt: Arc::from([]),
..resolver.clone()
}),
(AddrGuard::Baseline, GuardedEgress::Direct | GuardedEgress::Proxy)
| (AddrGuard::WorkspaceDeclared(_), GuardedEgress::Direct) => None,
};
Self {
client: build_client_inner(redirect, resolver, route),
tier,
preflight,
}
}
pub(super) async fn preflight(&self, url: &str) -> Result<()> {
let Some(resolver) = &self.preflight else {
return Ok(());
};
let Some(domain) = Url::parse(url).ok().and_then(|parsed| match parsed.host() {
Some(url::Host::Domain(domain)) => Some(domain.to_string()),
Some(url::Host::Ipv4(_) | url::Host::Ipv6(_)) | None => None,
}) else {
return Ok(());
};
let name = reqwest::dns::Name::from_str(&domain)
.map_err(|error| preflight_error(url, Box::new(error)))?;
reqwest::dns::Resolve::resolve(resolver, name)
.await
.map(drop)
.map_err(|error| preflight_error(url, error))
}
}
pub(super) fn pinned_digest(
trusted_origin: &TrustedPrefix,
snapshot: WorkspaceRegistryAccess,
) -> u64 {
let mut hasher = std::collections::hash_map::DefaultHasher::new();
trusted_origin.hash(&mut hasher);
snapshot.hash(&mut hasher);
hasher.finish()
}