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