use anda_core::{BoxError, RPCRequestRef};
use ic_auth_types::ByteBufB64;
pub(crate) fn rpc_body(method: &str, params: Vec<u8>) -> Result<Vec<u8>, BoxError> {
let params = ByteBufB64::from(params);
Ok(cbor2::to_canonical_vec(&RPCRequestRef {
method,
params: ¶ms,
})?)
}
pub(crate) fn check_url(url: &str, allow_http: bool) -> Result<reqwest::Url, BoxError> {
let parsed = reqwest::Url::parse(url).map_err(|err| format!("Invalid url {url:?}: {err}"))?;
let scheme = parsed.scheme();
let scheme_ok = scheme == "https" || (allow_http && scheme == "http");
if !scheme_ok {
let expected = if allow_http { "http or https" } else { "https" };
return Err(
format!("Invalid url {url:?}: scheme must be {expected}, got {scheme:?}").into(),
);
}
if !parsed.has_host() {
return Err(format!("Invalid url {url:?}: missing host").into());
}
if !parsed.username().is_empty() || parsed.password().is_some() {
return Err(format!("Invalid url {url:?}: embedded userinfo is not allowed").into());
}
Ok(parsed)
}
#[cfg(feature = "client")]
pub(crate) async fn send_request(
http: reqwest::Client,
url: reqwest::Url,
method: http::Method,
headers: Option<http::HeaderMap>,
body: Option<Vec<u8>>,
) -> Result<reqwest::Response, BoxError> {
let mut req = http.request(method, url);
if let Some(headers) = headers {
req = req.headers(headers);
}
if let Some(body) = body {
req = req.body(body);
}
req.send().await.map_err(|e| e.into())
}