2 use activitystreams::unparsed::UnparsedMutExt;
3 use activitystreams_ext::UnparsedExtension;
4 use actix_web::{client::ClientRequest, HttpRequest};
5 use anyhow::{anyhow, Context};
6 use http_signature_normalization_actix::{
7 digest::{DigestClient, SignExt},
10 use lemmy_utils::{location_info, LemmyError};
15 sign::{Signer, Verifier},
17 use serde::{Deserialize, Serialize};
18 use sha2::{Digest, Sha256};
22 static ref HTTP_SIG_CONFIG: Config = Config::new();
25 /// Signs request headers with the given keypair.
27 request: ClientRequest,
31 ) -> Result<DigestClient<String>, LemmyError> {
32 let signing_key_id = format!("{}#main-key", actor_id);
34 let digest_client = request
35 .signature_with_digest(
36 HTTP_SIG_CONFIG.clone(),
40 move |signing_string| {
41 let private_key = PKey::private_key_from_pem(private_key.as_bytes())?;
42 let mut signer = Signer::new(MessageDigest::sha256(), &private_key)?;
43 signer.update(signing_string.as_bytes())?;
45 Ok(base64::encode(signer.sign_to_vec()?)) as Result<_, LemmyError>
53 pub fn verify(request: &HttpRequest, actor: &dyn ActorType) -> Result<(), LemmyError> {
54 let public_key = actor.public_key().context(location_info!())?;
55 let verified = HTTP_SIG_CONFIG
58 request.uri().path_and_query(),
59 request.headers().clone(),
61 .verify(|signature, signing_string| -> Result<bool, LemmyError> {
63 "Verifying with key {}, message {}",
64 &public_key, &signing_string
66 let public_key = PKey::public_key_from_pem(public_key.as_bytes())?;
67 let mut verifier = Verifier::new(MessageDigest::sha256(), &public_key)?;
68 verifier.update(&signing_string.as_bytes())?;
69 Ok(verifier.verify(&base64::decode(signature)?)?)
73 debug!("verified signature for {}", &request.uri());
76 Err(anyhow!("Invalid signature on request: {}", &request.uri()).into())
80 // The following is taken from here:
81 // https://docs.rs/activitystreams/0.5.0-alpha.17/activitystreams/ext/index.html
83 #[derive(Clone, Debug, Default, Deserialize, Serialize)]
84 #[serde(rename_all = "camelCase")]
85 pub struct PublicKey {
88 pub public_key_pem: String,
91 #[derive(Clone, Debug, Default, Deserialize, Serialize)]
92 #[serde(rename_all = "camelCase")]
93 pub struct PublicKeyExtension {
94 pub public_key: PublicKey,
98 pub fn to_ext(&self) -> PublicKeyExtension {
100 public_key: self.to_owned(),
105 impl<U> UnparsedExtension<U> for PublicKeyExtension
109 type Error = serde_json::Error;
111 fn try_from_unparsed(unparsed_mut: &mut U) -> Result<Self, Self::Error> {
112 Ok(PublicKeyExtension {
113 public_key: unparsed_mut.remove("publicKey")?,
117 fn try_into_unparsed(self, unparsed_mut: &mut U) -> Result<(), Self::Error> {
118 unparsed_mut.insert("publicKey", self.public_key)?;