use std::sync::Arc;
use atproto_identity::egress::{Allowlist, PublicResolver};
use atproto_identity::resolve::InnerIdentityResolver;
use reqwest::dns::Resolve;
use serde_json::Value;
use tokio::sync::{Semaphore, mpsc};
use crate::cache::BlobCache;
use crate::errors::ConfigError;
use crate::proto::cancel;
use crate::proto::subs;
use crate::proto::writer::Outgoing;
pub const DEFAULT_MAX_MESSAGE_BYTES: usize = 33_554_432;
pub const DEFAULT_MAX_CONCURRENT_REQUESTS: usize = 16;
pub const DEFAULT_MAX_QUEUED_REQUESTS: usize = 1024;
pub const DEFAULT_BLOB_MAX_UPLOAD_BYTES: u64 = 16_777_216;
pub const DEFAULT_BLOB_MAX_DOWNLOAD_BYTES: u64 = 16_777_216;
pub const DEFAULT_BLOB_MAX_INLINE_BYTES: u64 = 262_144;
pub const DEFAULT_BLOB_CACHE_MAX_BYTES: u64 = 536_870_912;
#[derive(Debug, Clone, Copy)]
pub struct Limits {
pub max_message_bytes: usize,
pub max_concurrent_requests: usize,
pub max_queued_requests: usize,
pub blob_max_upload_bytes: u64,
pub blob_max_download_bytes: u64,
pub blob_max_inline_bytes: u64,
pub allow_insecure_endpoints: bool,
pub preserve_exif: bool,
}
impl Default for Limits {
fn default() -> Self {
Self {
max_message_bytes: DEFAULT_MAX_MESSAGE_BYTES,
max_concurrent_requests: DEFAULT_MAX_CONCURRENT_REQUESTS,
max_queued_requests: DEFAULT_MAX_QUEUED_REQUESTS,
blob_max_upload_bytes: DEFAULT_BLOB_MAX_UPLOAD_BYTES,
blob_max_download_bytes: DEFAULT_BLOB_MAX_DOWNLOAD_BYTES,
blob_max_inline_bytes: DEFAULT_BLOB_MAX_INLINE_BYTES,
allow_insecure_endpoints: false,
preserve_exif: false,
}
}
}
impl Limits {
pub fn from_env() -> Result<Self, ConfigError> {
Self::from_lookup(env_value)
}
pub fn from_lookup(lookup: impl Fn(&str) -> Option<String>) -> Result<Self, ConfigError> {
let mut limits = Self::default();
let number = |name: &'static str, minimum: u64, default: u64| {
parse_number(name, lookup(name).as_deref(), minimum, default)
};
if let Some(value) = number(
"ATPMCP_MAX_MESSAGE_BYTES",
1024,
DEFAULT_MAX_MESSAGE_BYTES as u64,
)? {
limits.max_message_bytes = usize::try_from(value).unwrap_or(usize::MAX);
}
if let Some(value) = number(
"ATPMCP_MAX_CONCURRENT_REQUESTS",
1,
DEFAULT_MAX_CONCURRENT_REQUESTS as u64,
)? {
limits.max_concurrent_requests = usize::try_from(value).unwrap_or(usize::MAX);
}
if let Some(value) = number(
"ATPMCP_MAX_QUEUED_REQUESTS",
1,
DEFAULT_MAX_QUEUED_REQUESTS as u64,
)? {
limits.max_queued_requests = usize::try_from(value).unwrap_or(usize::MAX);
}
if let Some(value) = number(
"ATPMCP_BLOB_MAX_UPLOAD_BYTES",
1,
DEFAULT_BLOB_MAX_UPLOAD_BYTES,
)? {
limits.blob_max_upload_bytes = value;
}
if let Some(value) = number(
"ATPMCP_BLOB_MAX_DOWNLOAD_BYTES",
1,
DEFAULT_BLOB_MAX_DOWNLOAD_BYTES,
)? {
limits.blob_max_download_bytes = value;
}
if let Some(value) = number(
"ATPMCP_BLOB_MAX_INLINE_BYTES",
0,
DEFAULT_BLOB_MAX_INLINE_BYTES,
)? {
limits.blob_max_inline_bytes = value;
}
limits.allow_insecure_endpoints = parse_waiver(
"ATPMCP_ALLOW_INSECURE_ENDPOINTS",
lookup("ATPMCP_ALLOW_INSECURE_ENDPOINTS").as_deref(),
)?;
limits.preserve_exif = parse_waiver(
"ATPMCP_PRESERVE_EXIF",
lookup("ATPMCP_PRESERVE_EXIF").as_deref(),
)?;
Ok(limits)
}
}
pub(crate) fn env_value(name: &str) -> Option<String> {
match std::env::var(name) {
Ok(value) => Some(value),
Err(std::env::VarError::NotPresent) => None,
Err(std::env::VarError::NotUnicode(raw)) => Some(raw.to_string_lossy().into_owned()),
}
}
pub(crate) fn parse_number(
name: &'static str,
raw: Option<&str>,
minimum: u64,
default: u64,
) -> Result<Option<u64>, ConfigError> {
let Some(raw) = raw.map(str::trim).filter(|raw| !raw.is_empty()) else {
return Ok(None);
};
if !raw.bytes().all(|byte| byte.is_ascii_digit()) {
return Err(ConfigError::NotANumber {
name,
value: raw.to_string(),
default,
});
}
let value: u64 = raw.parse().map_err(|_| ConfigError::NotANumber {
name,
value: raw.to_string(),
default,
})?;
if value < minimum {
return Err(ConfigError::BelowMinimum {
name,
value,
minimum,
});
}
Ok(Some(value))
}
pub(crate) fn parse_waiver(name: &'static str, raw: Option<&str>) -> Result<bool, ConfigError> {
let Some(raw) = raw else {
return Ok(false);
};
match raw.trim().to_ascii_lowercase().as_str() {
"1" | "true" | "yes" | "on" => Ok(true),
"" | "0" | "false" | "no" | "off" => Ok(false),
_ => Err(ConfigError::NotAWaiver {
name,
value: raw.to_string(),
}),
}
}
pub const DEFAULT_PLC_HOSTNAME: &str = atproto_identity::config::DEFAULT_PLC_HOSTNAME;
pub(crate) fn plc_hostname(lookup: impl Fn(&str) -> Option<String>) -> Result<String, ConfigError> {
const NAME: &str = "PLC_HOSTNAME";
let Some(raw) = lookup(NAME) else {
return Ok(DEFAULT_PLC_HOSTNAME.to_string());
};
atproto_identity::config::validate_plc_hostname(NAME, &raw).map_err(|error| {
ConfigError::NotAPlcDirectory {
name: NAME,
value: raw.clone(),
reason: match error {
atproto_identity::errors::ConfigError::InvalidPlcHostname { reason, .. } => reason,
other => other.to_string(),
},
}
})
}
pub(crate) fn dns_nameservers(
lookup: impl Fn(&str) -> Option<String>,
) -> Result<Vec<std::net::IpAddr>, ConfigError> {
const NAME: &str = "DNS_NAMESERVERS";
let raw = lookup(NAME).unwrap_or_default();
let nameservers: atproto_identity::config::DnsNameservers =
raw.clone()
.try_into()
.map_err(|error: anyhow::Error| ConfigError::NotANameserverList {
name: NAME,
value: raw.clone(),
entry: match error.downcast_ref::<atproto_identity::errors::ConfigError>() {
Some(atproto_identity::errors::ConfigError::InvalidNameserverIP { value }) => {
value.clone()
}
_ => raw.clone(),
},
separator: atproto_identity::config::LIST_SEPARATOR,
})?;
Ok(nameservers.as_ref().clone())
}
pub struct ServerContext {
pub resolver: Arc<InnerIdentityResolver>,
pub request_client: reqwest::Client,
pub blob_client: reqwest::Client,
pub web_client: reqwest::Client,
pub cache: Arc<BlobCache>,
pub limits: Limits,
pub out: mpsc::Sender<Outgoing>,
pub inflight: cancel::Registry,
pub subscriptions: subs::Registry,
pub permits: Arc<Semaphore>,
pub server_info: Value,
}
impl ServerContext {
pub fn new(
resolver: Arc<InnerIdentityResolver>,
cache: Arc<BlobCache>,
limits: Limits,
out: mpsc::Sender<Outgoing>,
) -> reqwest::Result<Self> {
let guard =
AddressGuard::for_config(limits.allow_insecure_endpoints, &resolver.plc_hostname);
Ok(Self {
request_client: request_client(&guard)?,
blob_client: blob_client(&guard)?,
web_client: web_client(&guard)?,
resolver,
cache,
limits,
out,
inflight: cancel::Registry::new(),
subscriptions: subs::Registry::new(),
permits: Arc::new(Semaphore::new(limits.max_concurrent_requests)),
server_info: serde_json::json!({
"name": "atpmcp",
"version": env!("CARGO_PKG_VERSION"),
}),
})
}
}
#[derive(Clone)]
pub struct AddressGuard {
guarded: bool,
allowlist: Allowlist,
lookup: Option<Arc<dyn Resolve>>,
}
impl std::fmt::Debug for AddressGuard {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AddressGuard")
.field("guarded", &self.guarded)
.field("allowlist", &self.allowlist)
.field("lookup", &self.lookup.as_ref().map(|_| "custom"))
.finish()
}
}
impl AddressGuard {
#[must_use]
pub fn for_config(waived: bool, plc_hostname: &str) -> Self {
let mut allowlist = Allowlist::new();
if let Some(host) =
reqwest::Url::parse(&atproto_identity::plc::directory_base(plc_hostname))
.ok()
.and_then(|url| url.domain().map(str::to_string))
{
allowlist = allowlist.host(&host);
}
Self {
guarded: !waived,
allowlist,
lookup: None,
}
}
#[must_use]
pub fn is_guarded(&self) -> bool {
self.guarded
}
#[cfg(test)]
#[must_use]
pub(crate) fn with_lookup(mut self, lookup: Arc<dyn Resolve>) -> Self {
self.lookup = Some(lookup);
self
}
fn apply(&self, builder: reqwest::ClientBuilder) -> reqwest::ClientBuilder {
match (self.guarded, self.lookup.clone()) {
(true, lookup) => {
let resolver = match lookup {
Some(lookup) => PublicResolver::over(lookup),
None => PublicResolver::new(),
};
builder.dns_resolver(resolver.with_allowlist(self.allowlist.clone()))
}
(false, Some(lookup)) => builder.dns_resolver(lookup),
(false, None) => builder,
}
}
}
const CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
const REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
pub fn identity_client(guard: &AddressGuard) -> reqwest::Result<reqwest::Client> {
guard
.apply(reqwest::Client::builder())
.connect_timeout(CONNECT_TIMEOUT)
.timeout(REQUEST_TIMEOUT)
.redirect(atproto_identity::redirect::validated_policy())
.build()
}
pub fn request_client(guard: &AddressGuard) -> reqwest::Result<reqwest::Client> {
guard
.apply(reqwest::Client::builder())
.connect_timeout(CONNECT_TIMEOUT)
.timeout(REQUEST_TIMEOUT)
.redirect(crate::host_policy::no_redirects())
.build()
}
fn blob_client(guard: &AddressGuard) -> reqwest::Result<reqwest::Client> {
guard
.apply(reqwest::Client::builder())
.connect_timeout(CONNECT_TIMEOUT)
.timeout(std::time::Duration::from_secs(120))
.redirect(reqwest::redirect::Policy::none())
.build()
}
pub fn web_client(guard: &AddressGuard) -> reqwest::Result<reqwest::Client> {
guard
.apply(reqwest::Client::builder())
.connect_timeout(CONNECT_TIMEOUT)
.timeout(REQUEST_TIMEOUT)
.redirect(atproto_identity::redirect::validated_policy())
.user_agent(concat!("atpmcp/", env!("CARGO_PKG_VERSION")))
.build()
}
#[cfg(test)]
mod tests {
use super::*;
fn lookup(vars: &[(&str, &str)]) -> impl Fn(&str) -> Option<String> {
let vars: Vec<(String, String)> = vars
.iter()
.map(|(name, value)| ((*name).to_string(), (*value).to_string()))
.collect();
move |name| {
vars.iter()
.find(|(key, _)| key == name)
.map(|(_, value)| value.clone())
}
}
#[test]
fn unset_and_empty_variables_keep_the_defaults() {
let defaults = Limits::default();
for vars in [
vec![],
vec![
("ATPMCP_BLOB_MAX_UPLOAD_BYTES", ""),
("ATPMCP_MAX_MESSAGE_BYTES", " "),
("ATPMCP_ALLOW_INSECURE_ENDPOINTS", ""),
],
] {
let limits = Limits::from_lookup(lookup(&vars)).expect("defaults are valid");
assert_eq!(limits.blob_max_upload_bytes, defaults.blob_max_upload_bytes);
assert_eq!(limits.max_message_bytes, defaults.max_message_bytes);
assert!(!limits.allow_insecure_endpoints);
}
}
#[test]
fn a_whole_number_sets_the_limit() {
let limits = Limits::from_lookup(lookup(&[
("ATPMCP_BLOB_MAX_UPLOAD_BYTES", "1048576"),
("ATPMCP_BLOB_MAX_INLINE_BYTES", "0"),
("ATPMCP_MAX_CONCURRENT_REQUESTS", " 4 "),
]))
.expect("valid values");
assert_eq!(limits.blob_max_upload_bytes, 1_048_576);
assert_eq!(limits.blob_max_inline_bytes, 0, "zero means never inline");
assert_eq!(limits.max_concurrent_requests, 4);
}
#[test]
fn a_value_that_is_not_digits_alone_is_refused_by_name() {
for value in ["1M", "16MiB", "1_048_576", "1e6", "-1", "0x100000"] {
let error = Limits::from_lookup(lookup(&[("ATPMCP_BLOB_MAX_UPLOAD_BYTES", value)]))
.expect_err(value);
assert!(
matches!(
&error,
ConfigError::NotANumber {
name: "ATPMCP_BLOB_MAX_UPLOAD_BYTES",
..
}
),
"{value}: {error}"
);
let message = error.to_string();
assert!(message.starts_with("error-atpmcp-config-1 "), "{message}");
assert!(
message.contains("16777216"),
"shows the accepted form: {message}"
);
}
}
#[test]
fn a_value_below_its_minimum_is_refused() {
for (name, value) in [
("ATPMCP_MAX_MESSAGE_BYTES", "100"),
("ATPMCP_MAX_CONCURRENT_REQUESTS", "0"),
("ATPMCP_MAX_QUEUED_REQUESTS", "0"),
("ATPMCP_BLOB_MAX_DOWNLOAD_BYTES", "0"),
] {
let error = Limits::from_lookup(lookup(&[(name, value)])).expect_err(name);
assert!(
matches!(error, ConfigError::BelowMinimum { name: n, .. } if n == name),
"{name}={value}: {error}"
);
}
}
#[test]
fn preserving_exif_is_off_unless_switched_on() {
assert!(!Limits::from_lookup(lookup(&[])).unwrap().preserve_exif);
for on in ["1", "true", " ON "] {
let limits = Limits::from_lookup(lookup(&[("ATPMCP_PRESERVE_EXIF", on)])).unwrap();
assert!(limits.preserve_exif, "{on:?} preserves");
}
for off in ["0", "off", ""] {
let limits = Limits::from_lookup(lookup(&[("ATPMCP_PRESERVE_EXIF", off)])).unwrap();
assert!(!limits.preserve_exif, "{off:?} strips");
}
let error =
Limits::from_lookup(lookup(&[("ATPMCP_PRESERVE_EXIF", "keep")])).expect_err("refused");
assert!(
error
.to_string()
.starts_with("error-atpmcp-config-3 ATPMCP_PRESERVE_EXIF=\"keep\""),
"{error}"
);
}
#[test]
fn the_waiver_is_on_off_or_refused() {
for on in ["1", "true", "YES", " on "] {
let limits =
Limits::from_lookup(lookup(&[("ATPMCP_ALLOW_INSECURE_ENDPOINTS", on)])).unwrap();
assert!(limits.allow_insecure_endpoints, "{on:?} waives");
}
for off in ["0", "false", "No", "off", ""] {
let limits =
Limits::from_lookup(lookup(&[("ATPMCP_ALLOW_INSECURE_ENDPOINTS", off)])).unwrap();
assert!(!limits.allow_insecure_endpoints, "{off:?} keeps the policy");
}
for neither in ["y", "enabled", "2"] {
let error =
Limits::from_lookup(lookup(&[("ATPMCP_ALLOW_INSECURE_ENDPOINTS", neither)]))
.expect_err(neither);
assert!(
error.to_string().starts_with("error-atpmcp-config-3 "),
"{neither:?}: {error}"
);
}
}
#[test]
fn dns_nameservers_are_read_and_a_bad_entry_is_named() {
assert!(dns_nameservers(lookup(&[])).unwrap().is_empty());
assert!(
dns_nameservers(lookup(&[("DNS_NAMESERVERS", "")]))
.unwrap()
.is_empty()
);
assert_eq!(
dns_nameservers(lookup(&[("DNS_NAMESERVERS", " 1.1.1.1 ;::1")])).unwrap(),
vec![
"1.1.1.1".parse::<std::net::IpAddr>().unwrap(),
"::1".parse().unwrap()
]
);
let error = dns_nameservers(lookup(&[("DNS_NAMESERVERS", "1.1.1.1,8.8.8.8")]))
.expect_err("a comma is not the separator");
assert_eq!(
error.to_string(),
"error-atpmcp-config-5 DNS_NAMESERVERS=\"1.1.1.1,8.8.8.8\" is not a list of \
nameserver addresses: \"1.1.1.1,8.8.8.8\" is not an IP address. Separate \
addresses with ';', like 1.1.1.1;8.8.8.8"
);
let error = dns_nameservers(lookup(&[("DNS_NAMESERVERS", "1.1.1.1;resolver")]))
.expect_err("a name is not an address");
assert!(
matches!(&error, ConfigError::NotANameserverList { entry, .. } if entry == "resolver"),
"{error}"
);
}
#[test]
fn an_unusable_plc_hostname_is_refused_by_name() {
for value in [
"",
" ",
"has space",
"plc.example.com?x=1",
"plc.example.com#top",
"http://",
"https:///",
"/",
"HTTPS://plc.example.com",
"ftp://plc.example.com",
"https://https://plc.example.com",
] {
let error = plc_hostname(lookup(&[("PLC_HOSTNAME", value)])).expect_err(value);
assert!(
matches!(
&error,
ConfigError::NotAPlcDirectory {
name: "PLC_HOSTNAME",
..
}
),
"{value:?}: {error}"
);
let message = error.to_string();
assert!(
message.starts_with("error-atpmcp-config-4 PLC_HOSTNAME="),
"{value:?}: {message}"
);
}
}
#[test]
fn a_colon_that_is_not_a_port_is_refused() {
for value in [
"http:/x",
"https:x",
"http:/",
"https:/",
"http:",
"http:/127.0.0.1:2582",
"plc.example.com:",
"http://plc.example.com:x",
] {
let error = plc_hostname(lookup(&[("PLC_HOSTNAME", value)])).expect_err(value);
let message = error.to_string();
assert!(
message.starts_with("error-atpmcp-config-4 PLC_HOSTNAME="),
"{value:?}: {message}"
);
assert!(
message.contains("is not followed by a port number"),
"{value:?}: {message}"
);
}
}
#[test]
fn a_hostname_or_an_http_url_is_accepted_as_written() {
for (value, expected) in [
("plc.directory", "plc.directory"),
("plc.example.com:2582", "plc.example.com:2582"),
("localhost:2582", "localhost:2582"),
("http://[::1]:2582", "http://[::1]:2582"),
("[::1]", "[::1]"),
("user:pw@plc.example.com", "user:pw@plc.example.com"),
("https://plc.directory/", "https://plc.directory/"),
("http://localhost:2582", "http://localhost:2582"),
("http://127.0.0.1:2582", "http://127.0.0.1:2582"),
(
"https://mirror.example.com/plc",
"https://mirror.example.com/plc",
),
(" plc.directory\n", "plc.directory"),
] {
assert_eq!(
plc_hostname(lookup(&[("PLC_HOSTNAME", value)])).expect(value),
expected,
"{value:?}"
);
}
assert_eq!(plc_hostname(lookup(&[])).unwrap(), DEFAULT_PLC_HOSTNAME);
}
#[test]
fn defaults_keep_the_inline_ceiling_well_below_the_transfer_ceiling() {
let limits = Limits::default();
assert!(limits.blob_max_inline_bytes < limits.blob_max_download_bytes);
assert!(limits.blob_max_inline_bytes < limits.blob_max_upload_bytes);
}
#[test]
fn the_message_ceiling_admits_a_base64_encoded_maximum_blob() {
let limits = Limits::default();
let encoded = limits.blob_max_upload_bytes.div_ceil(3) * 4;
assert!(
(limits.max_message_bytes as u64) > encoded,
"message ceiling {} must exceed base64-encoded blob size {encoded}",
limits.max_message_bytes
);
}
fn read_request(stream: &mut std::net::TcpStream) {
use std::io::Read as _;
let mut raw = Vec::new();
let mut buffer = [0u8; 4096];
let head_end = loop {
if let Some(end) = raw.windows(4).position(|window| window == b"\r\n\r\n") {
break end + 4;
}
let read = stream.read(&mut buffer).expect("read");
assert!(read > 0, "the connection closed mid-request");
raw.extend_from_slice(&buffer[..read]);
};
let head = String::from_utf8_lossy(&raw[..head_end]).to_ascii_lowercase();
let length: usize = head
.lines()
.find_map(|line| line.strip_prefix("content-length:"))
.map_or(0, |value| value.trim().parse().expect("a length"));
while raw.len() < head_end + length {
let read = stream.read(&mut buffer).expect("read");
assert!(read > 0, "the connection closed mid-body");
raw.extend_from_slice(&buffer[..read]);
}
}
fn redirecting(status: u16, location: String) -> String {
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
let url = format!("http://{}", listener.local_addr().expect("addr"));
std::thread::spawn(move || {
use std::io::Write as _;
if let Ok((mut stream, _)) = listener.accept() {
read_request(&mut stream);
let _ = write!(
stream,
"HTTP/1.1 {status} Redirect\r\nLocation: {location}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
);
}
});
url
}
fn was_reached(listener: &std::net::TcpListener) -> bool {
listener.set_nonblocking(true).expect("nonblocking");
listener.accept().is_ok()
}
#[tokio::test]
async fn the_request_client_follows_no_redirect() {
let target = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
let location = format!(
"http://{}/containers/create",
target.local_addr().expect("addr")
);
let start = redirecting(307, location.clone());
let error = request_client(&AddressGuard::for_config(false, DEFAULT_PLC_HOSTNAME))
.expect("client")
.post(format!("{start}/xrpc/com.atproto.repo.createRecord"))
.json(&serde_json::json!({ "note": "model-supplied" }))
.send()
.await
.expect_err("a redirect is refused, not followed");
assert!(error.is_redirect(), "{error:?}");
assert!(format!("{error:?}").contains(&location), "{error:?}");
assert!(!was_reached(&target), "the redirect was followed");
}
fn sources(dir: &std::path::Path, found: &mut Vec<std::path::PathBuf>) {
for entry in std::fs::read_dir(dir).expect("read src") {
let path = entry.expect("entry").path();
if path.is_dir() {
sources(&path, found);
} else if path.extension().is_some_and(|ext| ext == "rs") {
found.push(path);
}
}
}
#[test]
fn no_client_outside_test_code_is_a_default_one() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let mut files = Vec::new();
sources(&root, &mut files);
assert!(files.len() > 10, "found {} files", files.len());
let mut offenders = Vec::new();
for file in files {
let text = std::fs::read_to_string(&file).expect("read");
let code = text.split("#[cfg(test)]").next().unwrap_or_default();
for (number, line) in code.lines().enumerate() {
if line.trim_start().starts_with("//") {
continue;
}
if line.contains("Client::new()") || line.contains("Client::default()") {
offenders.push(format!("{}:{}", file.display(), number + 1));
}
}
}
assert!(offenders.is_empty(), "default clients: {offenders:?}");
}
#[tokio::test]
async fn the_identity_client_refuses_a_redirect_the_policy_would() {
let target = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
let location = format!(
"http://{}/.well-known/atproto-did",
target.local_addr().expect("addr")
);
let start = redirecting(302, location.clone());
let error = identity_client(&AddressGuard::for_config(false, DEFAULT_PLC_HOSTNAME))
.expect("client")
.get(format!("{start}/.well-known/atproto-did"))
.send()
.await
.expect_err("a loopback hop is refused");
assert!(error.is_redirect(), "{error:?}");
let refusal = std::error::Error::source(&error)
.and_then(|source| source.downcast_ref::<atproto_identity::errors::RedirectError>());
assert!(
matches!(
refusal,
Some(atproto_identity::errors::RedirectError::EndpointRefused { hop, .. })
if *hop == location
),
"the refusal names the hop: {error:?}"
);
assert!(!was_reached(&target), "the redirect was followed");
}
struct Loopback;
impl Resolve for Loopback {
fn resolve(&self, _name: reqwest::dns::Name) -> reqwest::dns::Resolving {
Box::pin(async {
let addrs: reqwest::dns::Addrs = Box::new(std::iter::once(
std::net::SocketAddr::from(([127, 0, 0, 1], 0)),
));
Ok(addrs)
})
}
}
async fn ok_server() -> u16 {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("bind");
let port = listener.local_addr().expect("addr").port();
tokio::spawn(async move {
while let Ok((mut socket, _)) = listener.accept().await {
tokio::spawn(async move {
let mut request = [0u8; 4096];
let _ = socket.read(&mut request).await;
let _ = socket
.write_all(
b"HTTP/1.1 200 OK\r\ncontent-length: 0\r\nconnection: close\r\n\r\n",
)
.await;
});
}
});
port
}
fn chain(error: &dyn std::error::Error) -> String {
let mut text = error.to_string();
let mut source = error.source();
while let Some(next) = source {
text.push_str(" / ");
text.push_str(&next.to_string());
source = next.source();
}
text
}
fn clients(guard: &AddressGuard) -> [(&'static str, reqwest::Client); 4] {
[
("identity", identity_client(guard).expect("identity client")),
("request", request_client(guard).expect("request client")),
("blob", blob_client(guard).expect("blob client")),
("web", web_client(guard).expect("web client")),
]
}
#[tokio::test]
async fn the_guard_refuses_a_name_that_resolves_to_loopback() {
let port = ok_server().await;
let guard =
AddressGuard::for_config(false, DEFAULT_PLC_HOSTNAME).with_lookup(Arc::new(Loopback));
assert!(guard.is_guarded());
let url = format!("http://pds.example.com:{port}/");
for (which, client) in clients(&guard) {
let error = client.get(&url).send().await.expect_err(which);
assert!(error.is_connect(), "{which}: {error:?}");
let chain = chain(&error);
assert!(
chain.contains("error-atproto-identity-egress-1"),
"{which}: {chain}"
);
assert!(chain.contains("127.0.0.1"), "{which}: {chain}");
}
}
#[tokio::test]
async fn the_waiver_lifts_the_guard_for_every_client() {
let port = ok_server().await;
let guard =
AddressGuard::for_config(true, DEFAULT_PLC_HOSTNAME).with_lookup(Arc::new(Loopback));
assert!(!guard.is_guarded());
let url = format!("http://pds.example.com:{port}/");
for (which, client) in clients(&guard) {
let response = client.get(&url).send().await.expect(which);
assert_eq!(response.status(), reqwest::StatusCode::OK, "{which}");
}
}
#[tokio::test]
async fn the_configured_plc_host_is_admitted_and_nothing_else() {
let port = ok_server().await;
for plc_hostname in [
"plc.example.com",
"https://plc.example.com",
"plc.example.com:2582",
] {
let guard =
AddressGuard::for_config(false, plc_hostname).with_lookup(Arc::new(Loopback));
for (which, client) in clients(&guard) {
let response = client
.get(format!("http://plc.example.com:{port}/"))
.send()
.await
.unwrap_or_else(|error| panic!("{plc_hostname} {which}: {error:?}"));
assert_eq!(response.status(), reqwest::StatusCode::OK);
let error = client
.get(format!("http://pds.example.com:{port}/"))
.send()
.await
.expect_err(which);
assert!(
chain(&error).contains("error-atproto-identity-egress-1"),
"{plc_hostname} {which}: {error:?}"
);
}
}
}
#[test]
fn a_literal_plc_hostname_adds_no_host() {
let guard = AddressGuard::for_config(false, "http://127.0.0.1:2582");
assert!(guard.allowlist.is_empty(), "{guard:?}");
let guard = AddressGuard::for_config(false, DEFAULT_PLC_HOSTNAME);
assert!(
guard.allowlist.allows_host(DEFAULT_PLC_HOSTNAME),
"{guard:?}"
);
}
}