use atproto_identity::model::Document;
use atproto_identity::plc::directory_base;
use atproto_identity::validation::validate_service_endpoint;
use crate::context::Limits;
use crate::errors::ToolError;
pub fn check_endpoint(limits: &Limits, endpoint: &str) -> Result<(), ToolError> {
if limits.allow_insecure_endpoints {
tracing::debug!(endpoint = %endpoint, "Endpoint policy waived by configuration.");
return Ok(());
}
validate_service_endpoint(endpoint).map_err(|error| ToolError::EndpointRefused {
endpoint: endpoint.to_string(),
reason: error.to_string(),
})
}
pub fn check_plc_hostname(limits: &Limits, hostname: &str) -> Result<(), ToolError> {
check_endpoint(limits, &directory_base(hostname))
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PdsEndpointUnusable {
NoneNamed,
Refused {
endpoint: String,
reason: String,
},
}
impl PdsEndpointUnusable {
pub fn tool_reason(&self, did: &str, alternative: Option<&str>) -> String {
match self {
Self::NoneNamed => format!("the DID document for {did} names no PDS endpoint"),
Self::Refused { endpoint, reason } => {
let mut message = format!(
"the DID document for {did} names the PDS endpoint {endpoint}, which the \
endpoint policy refuses ({reason}). An endpoint read from a DID document is \
always checked, whatever ATPMCP_ALLOW_INSECURE_ENDPOINTS says"
);
if let Some(argument) = alternative {
message.push_str(&format!("; pass '{argument}' to name a host explicitly"));
}
message
}
}
}
}
pub fn pds_endpoint(document: &Document, waived: bool) -> Result<String, PdsEndpointUnusable> {
let named = document.pds_endpoints();
let Some(first) = named.first() else {
return Err(PdsEndpointUnusable::NoneNamed);
};
if waived {
tracing::debug!(endpoint = %first, "Endpoint policy waived by configuration.");
return Ok((*first).to_string());
}
if let Some(accepted) = document.pds_endpoints_validated().first() {
return Ok((*accepted).to_string());
}
Err(PdsEndpointUnusable::Refused {
endpoint: (*first).to_string(),
reason: validate_service_endpoint(first)
.err()
.map(|error| error.to_string())
.unwrap_or_default(),
})
}
#[must_use]
pub fn no_redirects() -> reqwest::redirect::Policy {
reqwest::redirect::Policy::custom(|attempt| {
let reason = format!(
"redirect to {} not followed: atpmcp follows no redirects on this request",
attempt.url()
);
attempt.error(reason)
})
}
#[cfg(test)]
mod tests {
use super::*;
fn document(endpoints: &[&str]) -> Document {
let services: Vec<serde_json::Value> = endpoints
.iter()
.enumerate()
.map(|(i, endpoint)| {
serde_json::json!({
"id": if i == 0 { "#atproto_pds".to_string() } else { format!("#pds{i}") },
"type": "AtprotoPersonalDataServer",
"serviceEndpoint": endpoint,
})
})
.collect();
serde_json::from_value(serde_json::json!({
"id": "did:plc:ewvi7nxzyoun6zhxrhs64oiz",
"service": services,
}))
.expect("a minimal DID document")
}
#[test]
fn a_local_pds_is_refused_by_name_unless_waived() {
let doc = document(&["http://localhost:4800"]);
match pds_endpoint(&doc, false) {
Err(PdsEndpointUnusable::Refused { endpoint, reason }) => {
assert_eq!(endpoint, "http://localhost:4800");
assert!(
!reason.is_empty(),
"the refusal carries the policy's reason"
);
}
other => panic!("expected a named refusal, got {other:?}"),
}
assert_eq!(
pds_endpoint(&doc, true).as_deref(),
Ok("http://localhost:4800"),
"waived, the document's endpoint is used as named"
);
}
#[test]
fn a_document_with_no_pds_says_so() {
assert_eq!(
pds_endpoint(&document(&[]), false),
Err(PdsEndpointUnusable::NoneNamed)
);
assert_eq!(
pds_endpoint(&document(&[]), true),
Err(PdsEndpointUnusable::NoneNamed)
);
}
#[test]
fn unwaived_it_matches_the_validated_list() {
let doc = document(&["http://localhost:4800", "https://pds.example.com"]);
assert_eq!(
pds_endpoint(&doc, false).as_deref(),
Ok("https://pds.example.com")
);
assert_eq!(
pds_endpoint(&doc, true).as_deref(),
Ok("http://localhost:4800")
);
assert_eq!(
pds_endpoint(&document(&["https://pds.example.com"]), false).as_deref(),
Ok("https://pds.example.com")
);
}
#[test]
fn the_tool_reason_says_which_refusal_and_what_to_do() {
let refused = pds_endpoint(&document(&["http://localhost:4800"]), false).unwrap_err();
let message = refused.tool_reason("did:plc:x", Some("endpoint"));
assert!(message.contains("http://localhost:4800"), "{message}");
assert!(message.contains("always checked"), "{message}");
assert!(
message.contains("ATPMCP_ALLOW_INSECURE_ENDPOINTS"),
"{message}"
);
assert!(message.contains("pass 'endpoint'"), "{message}");
assert!(
!refused.tool_reason("did:plc:x", None).contains("pass '"),
"no alternative is offered where the tool has none"
);
let none = PdsEndpointUnusable::NoneNamed.tool_reason("did:plc:x", None);
assert!(none.contains("names no PDS endpoint"), "{none}");
}
#[test]
fn a_plc_directory_with_a_scheme_is_checked_as_written() {
let limits = Limits::default();
check_plc_hostname(&limits, "https://plc.directory").expect("an https directory");
check_plc_hostname(&limits, "https://plc.directory/").expect("with a trailing slash");
check_plc_hostname(&limits, "plc.directory").expect("a bare hostname means https");
let error = check_plc_hostname(&limits, "http://plc.directory")
.expect_err("plain HTTP is refused unless waived");
let message = error.to_string();
assert!(
message.contains("Endpoint refused by policy: http://plc.directory:"),
"the refusal names the URL the resolver would request: {message}"
);
assert!(!message.contains("https://http"), "{message}");
for refused in ["localhost", "169.254.169.254", "https://127.0.0.1"] {
assert!(check_plc_hostname(&limits, refused).is_err(), "{refused}");
}
}
#[test]
fn the_waiver_admits_a_plain_http_plc_directory() {
let limits = Limits {
allow_insecure_endpoints: true,
..Limits::default()
};
check_plc_hostname(&limits, "http://127.0.0.1:2582").expect("waived");
}
}