From 1b9aeae53c82bc300d20eb2ebc7d8995630d7dc4 Mon Sep 17 00:00:00 2001 From: Kitaiti Makoto Date: Fri, 5 Feb 2021 10:23:54 +0900 Subject: [PATCH] Add test for signagure() --- plume-common/src/activity_pub/request.rs | 58 ++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/plume-common/src/activity_pub/request.rs b/plume-common/src/activity_pub/request.rs index 04a07c83..73e6d6ee 100644 --- a/plume-common/src/activity_pub/request.rs +++ b/plume-common/src/activity_pub/request.rs @@ -163,3 +163,61 @@ pub fn signature( signature = sign )).map_err(|_| Error()) } + +#[cfg(test)] +mod tests { + use super::{signature, Error}; + use crate::activity_pub::sign::{gen_keypair, Signer}; + use openssl::{hash::MessageDigest, pkey::PKey, rsa::Rsa}; + use reqwest::header::HeaderMap; + + struct MySigner { + public_key: String, + private_key: String, + } + + impl MySigner { + fn new() -> Self { + let (pub_key, priv_key) = gen_keypair(); + Self { + public_key: String::from_utf8(pub_key).unwrap(), + private_key: String::from_utf8(priv_key).unwrap(), + } + } + } + + impl Signer for MySigner { + type Error = Error; + + fn get_key_id(&self) -> String { + "mysigner".into() + } + + fn sign(&self, to_sign: &str) -> Result, Self::Error> { + let key = PKey::from_rsa(Rsa::private_key_from_pem(self.private_key.as_ref()).unwrap()) + .unwrap(); + let mut signer = openssl::sign::Signer::new(MessageDigest::sha256(), &key).unwrap(); + signer.update(to_sign.as_bytes()).unwrap(); + signer.sign_to_vec().map_err(|_| Error()) + } + + fn verify(&self, data: &str, signature: &[u8]) -> Result { + let key = PKey::from_rsa(Rsa::public_key_from_pem(self.public_key.as_ref()).unwrap()) + .unwrap(); + let mut verifier = openssl::sign::Verifier::new(MessageDigest::sha256(), &key).unwrap(); + verifier.update(data.as_bytes()).unwrap(); + verifier.verify(&signature).map_err(|_| Error()) + } + } + + #[test] + fn test_signature_request_target() { + let signer = MySigner::new(); + let headers = HeaderMap::new(); + let result = signature(&signer, &headers, ("post", "/inbox", None)).unwrap(); + let fields: Vec<&str> = result.to_str().unwrap().split(",").collect(); + assert_eq!(r#"headers="(request-target)""#, fields[2]); + let sign = &fields[3][11..(fields[3].len() - 1)]; + assert!(signer.verify("post /inbox", sign.as_bytes()).is_ok()); + } +}