moonproof-indexer-client 0.2.2

Rust client for the Midnight indexer's GraphQL API
Documentation
//! Indexer GraphQL endpoints and the credential some of them need.
//!
//! The Midnight-hosted indexers need none. Blockfrost, which serves
//! mainnet and preprod, authenticates every request with a project id,
//! accepted as a `project_id` query parameter on HTTP and WebSocket
//! alike, or as a `project_id` header on HTTP.

use reqwest::header::{HeaderMap, HeaderValue};
use url::Url;

use crate::IndexerError;

/// Query parameter, and HTTP header, carrying a Blockfrost project id.
pub const PROJECT_ID: &str = "project_id";

/// Path of the GraphQL endpoint on a self-hosted indexer.
pub const DEFAULT_GRAPHQL_PATH: &str = "/api/v4/graphql";

/// An indexer GraphQL endpoint with its project id split out.
#[derive(Clone)]
pub struct IndexerEndpoint {
    /// The endpoint without the project id.
    pub url: Url,
    pub project_id: Option<String>,
}

impl std::fmt::Debug for IndexerEndpoint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("IndexerEndpoint")
            .field("url", &self.url.as_str())
            .field(
                "project_id",
                &self.project_id.as_ref().map(|_| "<redacted>"),
            )
            .finish()
    }
}

impl IndexerEndpoint {
    /// Parse `raw`. A bare host gets the self-hosted GraphQL path; any
    /// other path is kept, since Blockfrost serves GraphQL at `/api/v0`.
    /// A `project_id` query parameter moves out of the URL: HTTP
    /// requests send it as a header, so it never sits in a request URL
    /// that a transport error would print.
    pub fn parse(raw: &str) -> Result<Self, IndexerError> {
        let mut url = Url::parse(raw)?;
        if url.path().is_empty() || url.path() == "/" {
            url.set_path(DEFAULT_GRAPHQL_PATH);
        }
        let mut project_id = None;
        let rest: Vec<(String, String)> = url
            .query_pairs()
            .filter_map(|(k, v)| {
                if k == PROJECT_ID {
                    project_id = Some(v.into_owned());
                    None
                } else {
                    Some((k.into_owned(), v.into_owned()))
                }
            })
            .collect();
        if rest.is_empty() {
            url.set_query(None);
        } else {
            url.query_pairs_mut().clear().extend_pairs(rest);
        }
        Ok(Self { url, project_id })
    }

    /// An HTTP client that authenticates every request.
    pub fn http_client(&self) -> Result<reqwest::Client, IndexerError> {
        let mut headers = HeaderMap::new();
        if let Some(id) = &self.project_id {
            let mut value = HeaderValue::from_str(id).map_err(|e| {
                IndexerError::InvalidResponse(format!(
                    "project id is not a valid header value: {e}"
                ))
            })?;
            value.set_sensitive(true);
            headers.insert(PROJECT_ID, value);
        }
        let builder = reqwest::Client::builder().default_headers(headers);
        #[cfg(not(target_arch = "wasm32"))]
        let builder = builder.tcp_nodelay(true).pool_max_idle_per_host(8);
        Ok(builder.build()?)
    }

    /// The endpoint with the project id back in the query, for the
    /// WebSocket handshake, which cannot carry it as a header.
    #[must_use]
    pub fn url_with_project_id(&self) -> Url {
        let mut url = self.url.clone();
        if let Some(id) = &self.project_id {
            url.query_pairs_mut().append_pair(PROJECT_ID, id);
        }
        url
    }
}

/// `url` with any `project_id` value replaced, for logs and messages.
#[must_use]
pub fn redact_project_id(url: &str) -> String {
    let Ok(mut parsed) = Url::parse(url) else {
        return url.to_owned();
    };
    if !parsed.query_pairs().any(|(k, _)| k == PROJECT_ID) {
        return url.to_owned();
    }
    let pairs: Vec<(String, String)> = parsed
        .query_pairs()
        .map(|(k, v)| {
            let v = if k == PROJECT_ID {
                "<redacted>".to_owned()
            } else {
                v.into_owned()
            };
            (k.into_owned(), v)
        })
        .collect();
    parsed.query_pairs_mut().clear().extend_pairs(pairs);
    parsed.to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_bare_host_gets_the_self_hosted_path() {
        let ep = IndexerEndpoint::parse("http://127.0.0.1:8088").unwrap();
        assert_eq!(ep.url.as_str(), "http://127.0.0.1:8088/api/v4/graphql");
        assert!(ep.project_id.is_none());
    }

    #[test]
    fn the_project_id_moves_out_of_the_url() {
        let ep = IndexerEndpoint::parse(
            "https://midnight-preprod.blockfrost.io/api/v0?project_id=nightpreprodX",
        )
        .unwrap();
        assert_eq!(
            ep.url.as_str(),
            "https://midnight-preprod.blockfrost.io/api/v0"
        );
        assert_eq!(ep.project_id.as_deref(), Some("nightpreprodX"));
        assert_eq!(
            ep.url_with_project_id().as_str(),
            "https://midnight-preprod.blockfrost.io/api/v0?project_id=nightpreprodX"
        );
        assert!(!format!("{ep:?}").contains("nightpreprodX"));
    }

    #[test]
    fn redaction_hides_only_the_project_id() {
        assert_eq!(
            redact_project_id("wss://rpc.midnight-mainnet.blockfrost.io/?project_id=secret&x=1"),
            "wss://rpc.midnight-mainnet.blockfrost.io/?project_id=%3Credacted%3E&x=1"
        );
        assert_eq!(
            redact_project_id("ws://127.0.0.1:9944"),
            "ws://127.0.0.1:9944"
        );
    }
}