1 use actix_web::HttpRequest;
3 use http::{header::HeaderName, HeaderMap, HeaderValue};
4 use http_signature_normalization_actix::Config as ConfigActix;
5 use http_signature_normalization_reqwest::prelude::{Config, SignExt};
6 use lemmy_utils::LemmyError;
11 sign::{Signer, Verifier},
13 use reqwest::{Client, Response};
14 use serde::{Deserialize, Serialize};
15 use sha2::{Digest, Sha256};
16 use std::{collections::BTreeMap, str::FromStr};
20 static ref CONFIG2: ConfigActix = ConfigActix::new();
21 static ref HTTP_SIG_CONFIG: Config = Config::new();
24 /// Creates an HTTP post request to `inbox_url`, with the given `client` and `headers`, and
25 /// `activity` as request body. The request is signed with `private_key` and then sent.
26 pub async fn sign_and_send(
28 headers: BTreeMap<String, String>,
33 ) -> Result<Response, LemmyError> {
34 let signing_key_id = format!("{}#main-key", actor_id);
36 let mut header_map = HeaderMap::new();
39 HeaderName::from_str(h.0.as_str())?,
40 HeaderValue::from_str(h.1.as_str())?,
44 .post(&inbox_url.to_string())
46 .signature_with_digest(
47 HTTP_SIG_CONFIG.clone(),
51 move |signing_string| {
52 let private_key = PKey::private_key_from_pem(private_key.as_bytes())?;
53 let mut signer = Signer::new(MessageDigest::sha256(), &private_key)?;
54 signer.update(signing_string.as_bytes())?;
56 Ok(base64::encode(signer.sign_to_vec()?)) as Result<_, LemmyError>
64 /// Verifies the HTTP signature on an incoming inbox request.
65 pub fn verify_signature(request: &HttpRequest, public_key: &str) -> Result<(), LemmyError> {
66 let verified = CONFIG2
69 request.uri().path_and_query(),
70 request.headers().clone(),
72 .verify(|signature, signing_string| -> Result<bool, LemmyError> {
74 "Verifying with key {}, message {}",
75 &public_key, &signing_string
77 let public_key = PKey::public_key_from_pem(public_key.as_bytes())?;
78 let mut verifier = Verifier::new(MessageDigest::sha256(), &public_key)?;
79 verifier.update(signing_string.as_bytes())?;
80 Ok(verifier.verify(&base64::decode(signature)?)?)
84 debug!("verified signature for {}", &request.uri());
87 Err(anyhow!("Invalid signature on request: {}", &request.uri()).into())
91 #[derive(Clone, Debug, Deserialize, Serialize)]
92 #[serde(rename_all = "camelCase")]
93 pub struct PublicKey {
94 pub(crate) id: String,
95 pub(crate) owner: Box<Url>,
96 pub public_key_pem: String,