buzzrelay/src/send.rs

69 lines
2.2 KiB
Rust
Raw Normal View History

2022-12-13 03:12:35 +00:00
use http::StatusCode;
2022-12-11 00:07:39 +00:00
use http_digest_headers::{DigestHeader, DigestMethod};
use serde::Serialize;
use sigh::{PrivateKey, SigningConfig, alg::RsaSha256};
#[derive(Debug, thiserror::Error)]
pub enum SendError {
#[error("HTTP Digest generation error")]
Digest,
#[error("JSON encoding error")]
Json(#[from] serde_json::Error),
#[error("Signature error")]
Signature(#[from] sigh::Error),
#[error("HTTP request error")]
HttpReq(#[from] http::Error),
#[error("HTTP client error")]
Http(#[from] reqwest::Error),
2022-12-13 03:12:35 +00:00
#[error("Invalid URI")]
InvalidUri,
#[error("Error response from remote")]
Response(String),
2022-12-11 00:07:39 +00:00
}
pub async fn send<T: Serialize>(
client: &reqwest::Client,
2022-12-13 03:12:35 +00:00
uri: &str,
2022-12-11 00:07:39 +00:00
key_id: &str,
private_key: &PrivateKey,
body: T,
) -> Result<(), SendError> {
let body = serde_json::to_vec(&body)
.map_err(SendError::Json)?;
let mut digest_header = DigestHeader::new()
.with_method(DigestMethod::SHA256, &body)
.map(|h| format!("{}", h))
.map_err(|_| SendError::Digest)?;
if digest_header.starts_with("sha-") {
digest_header.replace_range(..4, "SHA-");
}
// mastodon uses base64::alphabet::STANDARD, not base64::alphabet::URL_SAFE
digest_header.replace_range(
7..,
&digest_header[7..].replace("-", "+").replace("_", "/")
);
2022-12-13 03:12:35 +00:00
let url = reqwest::Url::parse(uri)
.map_err(|_| SendError::InvalidUri)?;
2022-12-11 00:07:39 +00:00
let mut req = http::Request::builder()
.method("POST")
2022-12-13 03:12:35 +00:00
.uri(uri)
.header("host", format!("{}", url.host().ok_or(SendError::InvalidUri)?))
2022-12-11 00:07:39 +00:00
.header("content-type", "application/activity+json")
.header("date", chrono::Utc::now().to_rfc2822()
.replace("+0000", "GMT"))
.header("digest", digest_header)
.body(body)
.map_err(SendError::HttpReq)?;
SigningConfig::new(RsaSha256, private_key, key_id)
.sign(&mut req)?;
let res = client.execute(req.try_into()?)
.await?;
2022-12-13 03:12:35 +00:00
if res.status() >= StatusCode::OK && res.status() < StatusCode::MULTIPLE_CHOICES {
Ok(())
} else {
let response = res.text().await?;
Err(SendError::Response(response))
}
2022-12-11 00:07:39 +00:00
}