]> Untitled Git - lemmy.git/blob - crates/apub_lib/src/signatures.rs
Adding unique constraint for activity ap_id. Fixes #1878 (#1935)
[lemmy.git] / crates / apub_lib / src / signatures.rs
1 use crate::APUB_JSON_CONTENT_TYPE;
2 use actix_web::HttpRequest;
3 use anyhow::anyhow;
4 use http::{header::HeaderName, HeaderMap, HeaderValue};
5 use http_signature_normalization_actix::Config as ConfigActix;
6 use http_signature_normalization_reqwest::prelude::{Config, SignExt};
7 use lemmy_utils::LemmyError;
8 use log::debug;
9 use openssl::{
10   hash::MessageDigest,
11   pkey::PKey,
12   sign::{Signer, Verifier},
13 };
14 use reqwest::{Client, Response};
15 use serde::{Deserialize, Serialize};
16 use sha2::{Digest, Sha256};
17 use std::str::FromStr;
18 use url::Url;
19
20 lazy_static! {
21   static ref CONFIG2: ConfigActix = ConfigActix::new();
22   static ref HTTP_SIG_CONFIG: Config = Config::new();
23 }
24
25 /// Creates an HTTP post request to `inbox_url`, with the given `client` and `headers`, and
26 /// `activity` as request body. The request is signed with `private_key` and then sent.
27 pub async fn sign_and_send(
28   client: &Client,
29   inbox_url: &Url,
30   activity: String,
31   actor_id: &Url,
32   private_key: String,
33 ) -> Result<Response, LemmyError> {
34   let signing_key_id = format!("{}#main-key", actor_id);
35
36   let mut headers = HeaderMap::new();
37   let mut host = inbox_url.domain().expect("read inbox domain").to_string();
38   if let Some(port) = inbox_url.port() {
39     host = format!("{}:{}", host, port);
40   }
41   headers.insert(
42     HeaderName::from_str("Content-Type")?,
43     HeaderValue::from_str(APUB_JSON_CONTENT_TYPE)?,
44   );
45   headers.insert(HeaderName::from_str("Host")?, HeaderValue::from_str(&host)?);
46
47   let response = client
48     .post(&inbox_url.to_string())
49     .headers(headers)
50     .signature_with_digest(
51       HTTP_SIG_CONFIG.clone(),
52       signing_key_id,
53       Sha256::new(),
54       activity,
55       move |signing_string| {
56         let private_key = PKey::private_key_from_pem(private_key.as_bytes())?;
57         let mut signer = Signer::new(MessageDigest::sha256(), &private_key)?;
58         signer.update(signing_string.as_bytes())?;
59
60         Ok(base64::encode(signer.sign_to_vec()?)) as Result<_, LemmyError>
61       },
62     )
63     .await?;
64
65   Ok(response)
66 }
67
68 /// Verifies the HTTP signature on an incoming inbox request.
69 pub fn verify_signature(request: &HttpRequest, public_key: &str) -> Result<(), LemmyError> {
70   let verified = CONFIG2
71     .begin_verify(
72       request.method(),
73       request.uri().path_and_query(),
74       request.headers().clone(),
75     )?
76     .verify(|signature, signing_string| -> Result<bool, LemmyError> {
77       debug!(
78         "Verifying with key {}, message {}",
79         &public_key, &signing_string
80       );
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)?)?)
85     })?;
86
87   if verified {
88     debug!("verified signature for {}", &request.uri());
89     Ok(())
90   } else {
91     Err(anyhow!("Invalid signature on request: {}", &request.uri()).into())
92   }
93 }
94
95 #[derive(Clone, Debug, Deserialize, Serialize)]
96 #[serde(rename_all = "camelCase")]
97 pub struct PublicKey {
98   pub(crate) id: String,
99   pub(crate) owner: Box<Url>,
100   pub public_key_pem: String,
101 }