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 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(crate) fn verify_signature(
69 request: &HttpRequest,
70 actor: &dyn ActorType,
71 ) -> Result<(), LemmyError> {
72 let public_key = actor.public_key().context(location_info!())?;
73 let verified = CONFIG2
76 request.uri().path_and_query(),
77 request.headers().clone(),
79 .verify(|signature, signing_string| -> Result<bool, LemmyError> {
81 "Verifying with key {}, message {}",
82 &public_key, &signing_string
84 let public_key = PKey::public_key_from_pem(public_key.as_bytes())?;
85 let mut verifier = Verifier::new(MessageDigest::sha256(), &public_key)?;
86 verifier.update(&signing_string.as_bytes())?;
87 Ok(verifier.verify(&base64::decode(signature)?)?)
91 debug!("verified signature for {}", &request.uri());
94 Err(anyhow!("Invalid signature on request: {}", &request.uri()).into())
98 /// Extension for actor public key, which is needed on user and community for HTTP signatures.
100 /// Taken from: https://docs.rs/activitystreams/0.5.0-alpha.17/activitystreams/ext/index.html
101 #[derive(Clone, Debug, Default, Deserialize, Serialize)]
102 #[serde(rename_all = "camelCase")]
103 pub struct PublicKeyExtension {
104 pub public_key: PublicKey,
107 #[derive(Clone, Debug, Default, Deserialize, Serialize)]
108 #[serde(rename_all = "camelCase")]
109 pub struct PublicKey {
112 pub public_key_pem: String,
116 pub fn to_ext(&self) -> PublicKeyExtension {
118 public_key: self.to_owned(),
123 impl<U> UnparsedExtension<U> for PublicKeyExtension
127 type Error = serde_json::Error;
129 fn try_from_unparsed(unparsed_mut: &mut U) -> Result<Self, Self::Error> {
130 Ok(PublicKeyExtension {
131 public_key: unparsed_mut.remove("publicKey")?,
135 fn try_into_unparsed(self, unparsed_mut: &mut U) -> Result<(), Self::Error> {
136 unparsed_mut.insert("publicKey", self.public_key)?;