use std::collections::HashSet;
use std::future::Future;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
static FORGE_TOKEN_DENIED: Mutex<Option<HashSet<String>>> = Mutex::new(None);
static FORGE_TOKEN_ALLOWED: Mutex<Option<HashSet<String>>> = Mutex::new(None);
static NETRC_DENIED: Mutex<Option<HashSet<String>>> = Mutex::new(None);
static NETRC_DENIED_ANY_HOST: AtomicBool = AtomicBool::new(false);
const PUBLIC_FORGE_HOSTS: [&str; 4] =
["github.com", "api.github.com", "gitlab.com", "codeberg.org"];
fn host_of(url: &str) -> Option<String> {
let url = url::Url::parse(url).ok()?;
url.host_str().map(str::to_ascii_lowercase)
}
fn insert(set: &Mutex<Option<HashSet<String>>>, host: String) {
set.lock()
.unwrap()
.get_or_insert_with(HashSet::new)
.insert(host);
}
fn contains(set: &Mutex<Option<HashSet<String>>>, host: &str) -> bool {
set.lock()
.unwrap()
.as_ref()
.is_some_and(|hosts| hosts.contains(&host.to_ascii_lowercase()))
}
pub fn deny_forge_token_for_url(api_url: &str) {
if let Some(host) = host_of(api_url)
&& !PUBLIC_FORGE_HOSTS.contains(&host.as_str())
{
insert(&FORGE_TOKEN_DENIED, host);
}
}
pub fn allow_forge_token_for_url(api_url: &str) {
if let Some(host) = host_of(api_url) {
insert(&FORGE_TOKEN_ALLOWED, host);
}
}
pub fn forge_token_denied(host: &str) -> bool {
contains(&FORGE_TOKEN_DENIED, host) && !contains(&FORGE_TOKEN_ALLOWED, host)
}
pub fn deny_netrc_for_url(url: &str) {
let authority = url
.split_once("://")
.map(|(_, rest)| rest.split(['/', '?', '#']).next().unwrap_or_default());
match (authority, host_of(url)) {
(Some(authority), Some(host)) if !authority.contains('{') => {
insert(&NETRC_DENIED, host);
}
_ => NETRC_DENIED_ANY_HOST.store(true, Ordering::Relaxed),
}
}
tokio::task_local! {
static TRUSTED_TOOL: bool;
}
pub async fn with_trusted_tool_scope<T>(future: impl Future<Output = T>) -> T {
TRUSTED_TOOL.scope(true, future).await
}
pub async fn with_tool_scope<T>(trusted: bool, future: impl Future<Output = T>) -> T {
let tool = Box::pin(TRUSTED_TOOL.scope(trusted, future));
crate::tera::with_templates_trusted(trusted, tool).await
}
pub fn inherit_trusted_scope<F: Future>(future: F) -> impl Future<Output = F::Output> {
let tool = TRUSTED_TOOL.try_with(|trusted| *trusted).unwrap_or(false);
let templates = crate::tera::in_trusted_templates();
async move {
match (tool, templates) {
(true, true) => with_tool_scope(true, future).await,
(true, false) => with_trusted_tool_scope(future).await,
(false, true) => crate::tera::with_trusted_templates(future).await,
(false, false) => future.await,
}
}
}
pub fn netrc_denied(url: &url::Url) -> bool {
if TRUSTED_TOOL.try_with(|trusted| *trusted).unwrap_or(false) {
return false;
}
NETRC_DENIED_ANY_HOST.load(Ordering::Relaxed)
|| url
.host_str()
.is_some_and(|host| contains(&NETRC_DENIED, host))
}
#[cfg(test)]
pub(crate) fn reset() {
for set in [&FORGE_TOKEN_DENIED, &FORGE_TOKEN_ALLOWED, &NETRC_DENIED] {
*set.lock().unwrap() = None;
}
NETRC_DENIED_ANY_HOST.store(false, Ordering::Relaxed);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_untrusted_forge_hosts() {
let _lock = crate::testing::lock_ignoring_poison(&crate::testing::SETTINGS_LOCK);
reset();
deny_forge_token_for_url("https://Evil.example/api/v3");
deny_forge_token_for_url("https://api.github.com");
deny_forge_token_for_url("https://ghe.corp.example/api/v3");
allow_forge_token_for_url("https://ghe.corp.example/api/v3");
assert!(forge_token_denied("evil.example"));
assert!(!forge_token_denied("api.github.com"));
assert!(!forge_token_denied("ghe.corp.example"));
assert!(!forge_token_denied("other.example"));
reset();
}
#[test]
fn test_netrc_denied_by_default_for_project_hosts() {
let _lock = crate::testing::lock_ignoring_poison(&crate::testing::SETTINGS_LOCK);
reset();
let url = |s: &str| url::Url::parse(s).unwrap();
deny_netrc_for_url("https://Files.example:443/project-{{ version }}.tgz");
assert!(netrc_denied(&url("https://files.example/private.env")));
assert!(netrc_denied(&url("https://FILES.example/other")));
assert!(!netrc_denied(&url("https://mirror.example/x")));
let trusted = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap()
.block_on(with_trusted_tool_scope(async {
netrc_denied(&url("https://files.example/private.env"))
}));
assert!(!trusted);
let (inherited, plain, parallel, outside) = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.build()
.unwrap()
.block_on(async {
let target = url("https://files.example/private.env");
let (inherited, plain, parallel) = with_trusted_tool_scope(async {
let t = target.clone();
let inherited =
tokio::spawn(inherit_trusted_scope(async move { netrc_denied(&t) }));
let t = target.clone();
let plain = tokio::spawn(async move { netrc_denied(&t) });
let parallel =
crate::parallel::parallel(vec![target.clone()], |t| async move {
Ok(netrc_denied(&t))
});
(
inherited.await.unwrap(),
plain.await.unwrap(),
parallel.await.unwrap(),
)
})
.await;
let t = target.clone();
let outside = tokio::spawn(inherit_trusted_scope(async move { netrc_denied(&t) }))
.await
.unwrap();
(inherited, plain, parallel, outside)
});
assert!(!inherited);
assert!(plain);
assert_eq!(parallel, [false]);
assert!(outside);
let (nested, nested_templates, back) = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap()
.block_on(with_tool_scope(true, async {
let target = url("https://files.example/private.env");
let (nested, templates) = with_tool_scope(false, async {
(netrc_denied(&target), crate::tera::in_trusted_templates())
})
.await;
(nested, templates, netrc_denied(&target))
}));
assert!(nested);
assert!(!nested_templates);
assert!(!back);
deny_netrc_for_url("https://{{ os() }}.evil.example/tool");
assert!(netrc_denied(&url("https://linux.evil.example/tool")));
assert!(netrc_denied(&url("https://mirror.example/x")));
reset();
}
}