atpmcp 0.15.0

AT Protocol MCP server (Model Context Protocol 2026-07-28)
//! The host policy for a caller-named endpoint.
//!
//! `download_blob`'s and `invoke_xrpc`'s `endpoint`, and the identity tools'
//! `plc_directory_hostname`, each name a host this process will then connect
//! to. The caller is a model, so an unchecked one is an SSRF primitive
//! reachable from a prompt -- which is exactly what `blob.rs` says about the
//! endpoints it reads from a DID document, where it applies
//! [`Document::pds_endpoints_validated`](atproto_identity::model::Document::pds_endpoints_validated)
//! for that reason. The same policy
//! belongs on an argument, which is if anything more directly caller-supplied.
//!
//! The policy refuses plain HTTP, address literals (including
//! `169.254.169.254`), single-label hosts such as `localhost`, embedded
//! credentials and non-default ports.
//!
//! An operator can opt out with `ATPMCP_ALLOW_INSECURE_ENDPOINTS`, because the
//! policy also refuses `http://127.0.0.1:4800`, where this workspace's own
//! `pds` listens by default. That is an environment variable rather than a
//! tool argument on purpose: an operator can widen the policy, a prompt
//! cannot.
//!
//! The operator's own `PLC_HOSTNAME` is not a caller-named host and is not
//! checked. It is configuration, set where the waiver is set, and a model
//! cannot change it; checking it would only make a local directory usable by
//! also waiving the policy for every host a model names. It was checked in
//! `resolve_identity` and `get_record` and in no other tool.
//!
//! # What the waiver covers
//!
//! The `endpoint` and `plc_directory_hostname` arguments, and `atpmcp login`.
//! Never an endpoint read from a DID document during a tool call. That one is
//! chosen by whoever controls the DID and reached by calls that name no host --
//! `get_record` on an attacker's DID is read-only, so a host may run it without
//! asking, and nothing in the call says where it goes. The waiver is a
//! standing environment variable, set once for local work and still set while
//! the same server talks to the real network, and in that state the check on a
//! DID document's endpoint is the protection left. `login` is different: it is
//! a command the operator runs, not a tool a model can call, so the waiver
//! costs nothing there. [`pds_endpoint`] makes that choice, and says which
//! refusal happened when there is no endpoint to use.
//!
//! That is this URL policy. The address guard below is one switch for every
//! client, and the waiver lifts it everywhere.
//!
//! # Addresses
//!
//! Everything above reads the URL. What a name resolves to is checked when the
//! connection is made, by [`AddressGuard`](crate::context::AddressGuard): every
//! client looks names up through atproto-identity's `PublicResolver`, which
//! drops loopback, private and link-local addresses, so a public-looking name
//! whose address record is `127.0.0.1` or `169.254.169.254` is refused too
//! (`error-atproto-identity-egress-1`). -04 §11.2 has those addresses
//! "rejected unless explicitly permitted by configuration". The operator's
//! `PLC_HOSTNAME` is configuration and is admitted whatever it resolves to. The
//! waiver lifts the guard for every client, an endpoint read from a DID
//! document included -- unlike the URL rule, it has one switch, as atproto-pds
//! and atproto-entryway each do. An address literal never reaches a resolver,
//! which is why the URL rule refusing literals stays.
//!
//! # Redirects
//!
//! Every check above is on the first URL. Where that host redirects to is its
//! own choice, so a validated `https://` endpoint answering `307 Location:
//! http://127.0.0.1:2375/containers/create` would otherwise walk straight past
//! the policy -- and a 307 sends the request body again. So no client here
//! follows a redirect unchecked. Requests follow none ([`no_redirects`]).
//! Identity resolution follows a few, because the handle specification allows
//! them, and checks each one, under atproto-identity's
//! [`validated_policy`](atproto_identity::redirect::validated_policy), which
//! `atpdid` uses too; see [`identity_client`](crate::context::identity_client).
//! A redirect is never waived: `ATPMCP_ALLOW_INSECURE_ENDPOINTS` covers the
//! hosts an operator or a model names, and a redirect names the host a server
//! picked next.

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;

/// Check a caller-named service endpoint URL against the policy.
///
/// # Errors
///
/// [`ToolError::EndpointRefused`] naming the endpoint and why, unless the
/// operator set `ATPMCP_ALLOW_INSECURE_ENDPOINTS`.
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(),
    })
}

/// Check a caller-named PLC directory against the policy.
///
/// What is checked is the URL the resolver will request, built by
/// [`directory_base`] itself: `https://` in front of a bare hostname, and a
/// value that already carries a scheme as written. This used to prefix
/// `https://` unconditionally, so a correct `https://plc.directory` was checked
/// as `https://https://plc.directory` -- host `https`, a single-label host --
/// and refused, and `http://…` was refused with that garbled URL rather than
/// for being plain HTTP.
///
/// Only for a directory the *caller* names. The operator's `PLC_HOSTNAME` is
/// configuration, like the waiver itself, and is not checked; see
/// `tools::identity` for where the two are told apart.
///
/// # Errors
///
/// [`ToolError::EndpointRefused`], as [`check_endpoint`].
pub fn check_plc_hostname(limits: &Limits, hostname: &str) -> Result<(), ToolError> {
    check_endpoint(limits, &directory_base(hostname))
}

/// Why a DID document gave no PDS endpoint this process will connect to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PdsEndpointUnusable {
    /// The document names no PDS at all.
    NoneNamed,
    /// It names one, and the policy refuses it.
    Refused {
        /// The first endpoint the document names.
        endpoint: String,
        /// Why the policy refuses it.
        reason: String,
    },
}

impl PdsEndpointUnusable {
    /// The explanation a tool returns. A tool call never waives the policy for
    /// an endpoint read from a DID document, so a refusal says so, and names
    /// `alternative` -- the argument that names a host explicitly, which the
    /// waiver does cover -- when the tool has one.
    ///
    /// These used to be one message, "No usable PDS endpoint found", which
    /// reads as "the document names no PDS" when the document named one and
    /// the policy refused it.
    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
            }
        }
    }
}

/// The PDS endpoint to use from a DID document.
///
/// Not waived, this is the first endpoint that passes the policy, exactly
/// [`Document::pds_endpoints_validated`]'s first; the difference is only that a
/// refusal says which refusal it was. Waived, it is the first endpoint the
/// document names, unchecked. Only `atpmcp login` passes `waived` -- see the
/// module docs for why a tool call never does.
///
/// # Errors
///
/// [`PdsEndpointUnusable::NoneNamed`] when the document names no PDS, and
/// [`PdsEndpointUnusable::Refused`], naming the first endpoint and the policy's
/// reason, when it names only ones the policy refuses.
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(),
    })
}

/// The redirect policy for every other request: none are followed.
///
/// An XRPC call, `get_record`, a lexicon record and `createSession` have no
/// reason to be redirected, and a 307 would send a model-supplied body, or an
/// app password, again to wherever it pointed. Refused with an error rather
/// than with `Policy::none()`, which hands the 3xx back as the response and
/// leaves the JSON reader to report a decode failure that says nothing about a
/// redirect. This way the tool reports `error following redirect`, and the
/// error logged with it names the target.
#[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::*;

    /// A DID document naming `endpoints` as PDS services, in order.
    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")
    }

    /// The local-development case the waiver exists for: this workspace's
    /// own `pds` at `http://localhost:4800`.
    #[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)
        );
    }

    /// Not waived, this is `pds_endpoints_validated`'s first: a refused
    /// endpoint is passed over for an acceptable one. Waived, the first named.
    #[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}");
    }

    /// The finding: a directory given with its scheme was checked with a
    /// second one in front of it, `https://https://plc.directory`, whose host
    /// is `https`, and refused.
    #[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");
    }
}