1 use crate::APUB_JSON_CONTENT_TYPE;
2 use activitystreams::chrono::Utc;
3 use actix_web::HttpRequest;
5 use http::{header::HeaderName, HeaderMap, HeaderValue};
6 use http_signature_normalization_actix::Config as ConfigActix;
7 use http_signature_normalization_reqwest::prelude::{Config, SignExt};
8 use lemmy_utils::LemmyError;
13 sign::{Signer, Verifier},
15 use reqwest::{Client, Response};
16 use serde::{Deserialize, Serialize};
17 use sha2::{Digest, Sha256};
18 use std::str::FromStr;
22 static ref CONFIG2: ConfigActix = ConfigActix::new();
23 static ref HTTP_SIG_CONFIG: Config = Config::new().mastodon_compat();
26 /// Creates an HTTP post request to `inbox_url`, with the given `client` and `headers`, and
27 /// `activity` as request body. The request is signed with `private_key` and then sent.
28 pub async fn sign_and_send(
34 ) -> Result<Response, LemmyError> {
35 let signing_key_id = format!("{}#main-key", actor_id);
37 let mut headers = HeaderMap::new();
38 let mut host = inbox_url.domain().expect("read inbox domain").to_string();
39 if let Some(port) = inbox_url.port() {
40 host = format!("{}:{}", host, port);
43 HeaderName::from_str("Content-Type")?,
44 HeaderValue::from_str(APUB_JSON_CONTENT_TYPE)?,
46 headers.insert(HeaderName::from_str("Host")?, HeaderValue::from_str(&host)?);
48 HeaderName::from_str("Date")?,
49 HeaderValue::from_str(&Utc::now().to_rfc2822())?,
53 .post(&inbox_url.to_string())
55 .signature_with_digest(
56 HTTP_SIG_CONFIG.clone(),
60 move |signing_string| {
61 let private_key = PKey::private_key_from_pem(private_key.as_bytes())?;
62 let mut signer = Signer::new(MessageDigest::sha256(), &private_key)?;
63 signer.update(signing_string.as_bytes())?;
65 Ok(base64::encode(signer.sign_to_vec()?)) as Result<_, LemmyError>
73 /// Verifies the HTTP signature on an incoming inbox request.
74 pub fn verify_signature(request: &HttpRequest, public_key: &str) -> Result<(), LemmyError> {
75 let verified = CONFIG2
78 request.uri().path_and_query(),
79 request.headers().clone(),
81 .verify(|signature, signing_string| -> Result<bool, LemmyError> {
83 "Verifying with key {}, message {}",
84 &public_key, &signing_string
86 let public_key = PKey::public_key_from_pem(public_key.as_bytes())?;
87 let mut verifier = Verifier::new(MessageDigest::sha256(), &public_key)?;
88 verifier.update(signing_string.as_bytes())?;
89 Ok(verifier.verify(&base64::decode(signature)?)?)
93 debug!("verified signature for {}", &request.uri());
96 Err(anyhow!("Invalid signature on request: {}", &request.uri()).into())
100 #[derive(Clone, Debug, Deserialize, Serialize)]
101 #[serde(rename_all = "camelCase")]
102 pub struct PublicKey {
103 pub(crate) id: String,
104 pub(crate) owner: Box<Url>,
105 pub public_key_pem: String,