]> Untitled Git - lemmy.git/blob - crates/apub_lib/src/signatures.rs
Add tracing (#1942)
[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 once_cell::sync::Lazy;
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 tracing::debug;
19 use url::Url;
20
21 static CONFIG2: Lazy<ConfigActix> = Lazy::new(ConfigActix::new);
22 static HTTP_SIG_CONFIG: Lazy<Config> = Lazy::new(Config::new);
23
24 /// Creates an HTTP post request to `inbox_url`, with the given `client` and `headers`, and
25 /// `activity` as request body. The request is signed with `private_key` and then sent.
26 pub async fn sign_and_send(
27   client: &Client,
28   inbox_url: &Url,
29   activity: String,
30   actor_id: &Url,
31   private_key: String,
32 ) -> Result<Response, LemmyError> {
33   let signing_key_id = format!("{}#main-key", actor_id);
34
35   let mut headers = HeaderMap::new();
36   let mut host = inbox_url.domain().expect("read inbox domain").to_string();
37   if let Some(port) = inbox_url.port() {
38     host = format!("{}:{}", host, port);
39   }
40   headers.insert(
41     HeaderName::from_str("Content-Type")?,
42     HeaderValue::from_str(APUB_JSON_CONTENT_TYPE)?,
43   );
44   headers.insert(HeaderName::from_str("Host")?, HeaderValue::from_str(&host)?);
45
46   let response = client
47     .post(&inbox_url.to_string())
48     .headers(headers)
49     .signature_with_digest(
50       HTTP_SIG_CONFIG.clone(),
51       signing_key_id,
52       Sha256::new(),
53       activity,
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())?;
58
59         Ok(base64::encode(signer.sign_to_vec()?)) as Result<_, LemmyError>
60       },
61     )
62     .await?;
63
64   Ok(response)
65 }
66
67 /// Verifies the HTTP signature on an incoming inbox request.
68 pub fn verify_signature(request: &HttpRequest, public_key: &str) -> Result<(), LemmyError> {
69   let verified = CONFIG2
70     .begin_verify(
71       request.method(),
72       request.uri().path_and_query(),
73       request.headers().clone(),
74     )?
75     .verify(|signature, signing_string| -> Result<bool, LemmyError> {
76       debug!(
77         "Verifying with key {}, message {}",
78         &public_key, &signing_string
79       );
80       let public_key = PKey::public_key_from_pem(public_key.as_bytes())?;
81       let mut verifier = Verifier::new(MessageDigest::sha256(), &public_key)?;
82       verifier.update(signing_string.as_bytes())?;
83       Ok(verifier.verify(&base64::decode(signature)?)?)
84     })?;
85
86   if verified {
87     debug!("verified signature for {}", &request.uri());
88     Ok(())
89   } else {
90     Err(anyhow!("Invalid signature on request: {}", &request.uri()).into())
91   }
92 }
93
94 #[derive(Clone, Debug, Deserialize, Serialize)]
95 #[serde(rename_all = "camelCase")]
96 pub struct PublicKey {
97   pub(crate) id: String,
98   pub(crate) owner: Box<Url>,
99   pub public_key_pem: String,
100 }