]> Untitled Git - lemmy.git/blob - crates/apub_lib/src/signatures.rs
Consolidate and lower reqwest timeouts. Fixes #2150 (#2151)
[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, REQWEST_TIMEOUT};
8 use once_cell::sync::Lazy;
9 use openssl::{
10   hash::MessageDigest,
11   pkey::PKey,
12   sign::{Signer, Verifier},
13 };
14 use reqwest::Response;
15 use reqwest_middleware::ClientWithMiddleware;
16 use serde::{Deserialize, Serialize};
17 use sha2::{Digest, Sha256};
18 use std::str::FromStr;
19 use tracing::debug;
20 use url::Url;
21
22 static CONFIG2: Lazy<ConfigActix> = Lazy::new(ConfigActix::new);
23 static HTTP_SIG_CONFIG: Lazy<Config> = Lazy::new(Config::new);
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: &ClientWithMiddleware,
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 request = client
48     .post(&inbox_url.to_string())
49     // signature is only valid for 10 seconds, so no reason to wait any longer
50     .timeout(REQWEST_TIMEOUT)
51     .headers(headers)
52     .signature_with_digest(
53       HTTP_SIG_CONFIG.clone(),
54       signing_key_id,
55       Sha256::new(),
56       activity,
57       move |signing_string| {
58         let private_key = PKey::private_key_from_pem(private_key.as_bytes())?;
59         let mut signer = Signer::new(MessageDigest::sha256(), &private_key)?;
60         signer.update(signing_string.as_bytes())?;
61
62         Ok(base64::encode(signer.sign_to_vec()?)) as Result<_, LemmyError>
63       },
64     )
65     .await?;
66
67   let response = client.execute(request).await?;
68
69   Ok(response)
70 }
71
72 /// Verifies the HTTP signature on an incoming inbox request.
73 pub fn verify_signature(request: &HttpRequest, public_key: &str) -> Result<(), LemmyError> {
74   let verified = CONFIG2
75     .begin_verify(
76       request.method(),
77       request.uri().path_and_query(),
78       request.headers().clone(),
79     )?
80     .verify(|signature, signing_string| -> Result<bool, LemmyError> {
81       debug!(
82         "Verifying with key {}, message {}",
83         &public_key, &signing_string
84       );
85       let public_key = PKey::public_key_from_pem(public_key.as_bytes())?;
86       let mut verifier = Verifier::new(MessageDigest::sha256(), &public_key)?;
87       verifier.update(signing_string.as_bytes())?;
88       Ok(verifier.verify(&base64::decode(signature)?)?)
89     })?;
90
91   if verified {
92     debug!("verified signature for {}", &request.uri());
93     Ok(())
94   } else {
95     Err(anyhow!("Invalid signature on request: {}", &request.uri()).into())
96   }
97 }
98
99 #[derive(Clone, Debug, Deserialize, Serialize)]
100 #[serde(rename_all = "camelCase")]
101 pub struct PublicKey {
102   pub(crate) id: String,
103   pub(crate) owner: Box<Url>,
104   pub public_key_pem: String,
105 }