2 use activitystreams::unparsed::UnparsedMutExt;
3 use activitystreams_ext::UnparsedExtension;
4 use actix_web::HttpRequest;
5 use anyhow::{anyhow, Context};
6 use http::{header::HeaderName, HeaderMap, HeaderValue};
7 use http_signature_normalization_actix::Config as ConfigActix;
8 use http_signature_normalization_reqwest::prelude::{Config, SignExt};
9 use lemmy_utils::{location_info, LemmyError};
14 sign::{Signer, Verifier},
16 use reqwest::{Client, Response};
17 use serde::{Deserialize, Serialize};
18 use sha2::{Digest, Sha256};
19 use std::{collections::BTreeMap, str::FromStr};
23 static ref CONFIG2: ConfigActix = ConfigActix::new();
24 static ref HTTP_SIG_CONFIG: Config = Config::new();
27 /// Creates an HTTP post request to `inbox_url`, with the given `client` and `headers`, and
28 /// `activity` as request body. The request is signed with `private_key` and then sent.
29 pub(crate) async fn sign_and_send(
31 headers: BTreeMap<String, String>,
36 ) -> Result<Response, LemmyError> {
37 let signing_key_id = format!("{}#main-key", actor_id);
39 let mut header_map = HeaderMap::new();
42 HeaderName::from_str(h.0.as_str())?,
43 HeaderValue::from_str(h.1.as_str())?,
47 .post(&inbox_url.to_string())
49 .signature_with_digest(
50 HTTP_SIG_CONFIG.clone(),
54 move |signing_string| {
55 let private_key = PKey::private_key_from_pem(private_key.as_bytes())?;
56 let mut signer = Signer::new(MessageDigest::sha256(), &private_key)?;
57 signer.update(signing_string.as_bytes())?;
59 Ok(base64::encode(signer.sign_to_vec()?)) as Result<_, LemmyError>
67 /// Verifies the HTTP signature on an incoming inbox request.
68 pub fn verify_signature(request: &HttpRequest, actor: &dyn ActorType) -> Result<(), LemmyError> {
69 let public_key = actor.public_key().context(location_info!())?;
70 let verified = CONFIG2
73 request.uri().path_and_query(),
74 request.headers().clone(),
76 .verify(|signature, signing_string| -> Result<bool, LemmyError> {
78 "Verifying with key {}, message {}",
79 &public_key, &signing_string
81 let public_key = PKey::public_key_from_pem(public_key.as_bytes())?;
82 let mut verifier = Verifier::new(MessageDigest::sha256(), &public_key)?;
83 verifier.update(signing_string.as_bytes())?;
84 Ok(verifier.verify(&base64::decode(signature)?)?)
88 debug!("verified signature for {}", &request.uri());
91 Err(anyhow!("Invalid signature on request: {}", &request.uri()).into())
95 /// Extension for actor public key, which is needed on person and community for HTTP signatures.
97 /// Taken from: https://docs.rs/activitystreams/0.5.0-alpha.17/activitystreams/ext/index.html
98 #[derive(Clone, Debug, Deserialize, Serialize)]
99 #[serde(rename_all = "camelCase")]
100 pub struct PublicKeyExtension {
101 pub public_key: PublicKey,
104 #[derive(Clone, Debug, Deserialize, Serialize)]
105 #[serde(rename_all = "camelCase")]
106 pub struct PublicKey {
109 pub public_key_pem: String,
113 pub fn to_ext(&self) -> PublicKeyExtension {
115 public_key: self.to_owned(),
120 impl<U> UnparsedExtension<U> for PublicKeyExtension
124 type Error = serde_json::Error;
126 fn try_from_unparsed(unparsed_mut: &mut U) -> Result<Self, Self::Error> {
127 Ok(PublicKeyExtension {
128 public_key: unparsed_mut.remove("publicKey")?,
132 fn try_into_unparsed(self, unparsed_mut: &mut U) -> Result<(), Self::Error> {
133 unparsed_mut.insert("publicKey", self.public_key)?;