Add unit tests for main model parts (#310)

Add tests for following models:
- Blog
- Instance
- Media
- User
This commit is contained in:
fdb-hiroshima
2018-11-24 12:44:17 +01:00
committed by Baptiste Gelez
parent 0b9727ed28
commit 8a4702df92
30 changed files with 3779 additions and 1123 deletions
+9 -4
View File
@@ -1,4 +1,4 @@
use activitypub::{Object, activity::Create};
use activitypub::{activity::Create, Object};
use activity_pub::Id;
@@ -9,7 +9,7 @@ pub enum InboxError {
#[fail(display = "Invalid activity type")]
InvalidType,
#[fail(display = "Couldn't undo activity")]
CantUndo
CantUndo,
}
pub trait FromActivity<T: Object, C>: Sized {
@@ -17,7 +17,13 @@ pub trait FromActivity<T: Object, C>: Sized {
fn try_from_activity(conn: &C, act: Create) -> bool {
if let Ok(obj) = act.create_props.object_object() {
Self::from_activity(conn, obj, act.create_props.actor_link::<Id>().expect("FromActivity::try_from_activity: id not found error"));
Self::from_activity(
conn,
obj,
act.create_props
.actor_link::<Id>()
.expect("FromActivity::try_from_activity: id not found error"),
);
true
} else {
false
@@ -32,7 +38,6 @@ pub trait Notify<C> {
pub trait Deletable<C, A> {
fn delete(&self, conn: &C) -> A;
fn delete_id(id: String, actor_id: String, conn: &C);
}
pub trait WithInbox {
+48 -29
View File
@@ -1,10 +1,11 @@
use activitypub::{Activity, Actor, Object, Link};
use activitypub::{Activity, Actor, Link, Object};
use array_tool::vec::Uniq;
use reqwest::Client;
use rocket::{
Outcome, http::Status,
response::{Response, Responder},
request::{FromRequest, Request}
http::Status,
request::{FromRequest, Request},
response::{Responder, Response},
Outcome,
};
use serde_json;
@@ -24,7 +25,7 @@ pub fn ap_accept_header() -> Vec<&'static str> {
"application/ld+json; profile=\"https://w3.org/ns/activitystreams\"",
"application/ld+json;profile=\"https://w3.org/ns/activitystreams\"",
"application/activity+json",
"application/ld+json"
"application/ld+json",
]
}
@@ -52,7 +53,7 @@ pub fn context() -> serde_json::Value {
])
}
pub struct ActivityStream<T> (T);
pub struct ActivityStream<T>(T);
impl<T> ActivityStream<T> {
pub fn new(t: T) -> ActivityStream<T> {
@@ -64,9 +65,11 @@ impl<'r, O: Object> Responder<'r> for ActivityStream<O> {
fn respond_to(self, request: &Request) -> Result<Response<'r>, Status> {
let mut json = serde_json::to_value(&self.0).map_err(|_| Status::InternalServerError)?;
json["@context"] = context();
serde_json::to_string(&json).respond_to(request).map(|r| Response::build_from(r)
.raw_header("Content-Type", "application/activity+json")
.finalize())
serde_json::to_string(&json).respond_to(request).map(|r| {
Response::build_from(r)
.raw_header("Content-Type", "application/activity+json")
.finalize()
})
}
}
@@ -76,29 +79,45 @@ impl<'a, 'r> FromRequest<'a, 'r> for ApRequest {
type Error = ();
fn from_request(request: &'a Request<'r>) -> Outcome<Self, (Status, Self::Error), ()> {
request.headers().get_one("Accept").map(|header| header.split(",").map(|ct| match ct.trim() {
// bool for Forward: true if found a valid Content-Type for Plume first (HTML), false otherwise
"application/ld+json; profile=\"https://w3.org/ns/activitystreams\"" |
"application/ld+json;profile=\"https://w3.org/ns/activitystreams\"" |
"application/activity+json" |
"application/ld+json" => Outcome::Success(ApRequest),
"text/html" => Outcome::Forward(true),
_ => Outcome::Forward(false)
}).fold(Outcome::Forward(false), |out, ct| if out.clone().forwarded().unwrap_or(out.is_success()) {
out
} else {
ct
}).map_forward(|_| ())).unwrap_or(Outcome::Forward(()))
request
.headers()
.get_one("Accept")
.map(|header| {
header
.split(",")
.map(|ct| match ct.trim() {
// bool for Forward: true if found a valid Content-Type for Plume first (HTML), false otherwise
"application/ld+json; profile=\"https://w3.org/ns/activitystreams\""
| "application/ld+json;profile=\"https://w3.org/ns/activitystreams\""
| "application/activity+json"
| "application/ld+json" => Outcome::Success(ApRequest),
"text/html" => Outcome::Forward(true),
_ => Outcome::Forward(false),
})
.fold(Outcome::Forward(false), |out, ct| {
if out.clone().forwarded().unwrap_or(out.is_success()) {
out
} else {
ct
}
})
.map_forward(|_| ())
})
.unwrap_or(Outcome::Forward(()))
}
}
pub fn broadcast<S: sign::Signer, A: Activity, T: inbox::WithInbox + Actor>(sender: &S, act: A, to: Vec<T>) {
let boxes = to.into_iter()
pub fn broadcast<S: sign::Signer, A: Activity, T: inbox::WithInbox + Actor>(
sender: &S,
act: A,
to: Vec<T>,
) {
let boxes = to
.into_iter()
.filter(|u| !u.is_local())
.map(|u| u.get_shared_inbox_url().unwrap_or(u.get_inbox_url()))
.collect::<Vec<String>>()
.unique();
let mut act = serde_json::to_value(act).expect("activity_pub::broadcast: serialization error");
act["@context"] = context();
let signed = act.sign(sender);
@@ -121,8 +140,8 @@ pub fn broadcast<S: sign::Signer, A: Activity, T: inbox::WithInbox + Actor>(send
} else {
println!("Error while reading response")
}
},
Err(e) => println!("Error while sending to inbox ({:?})", e)
}
Err(e) => println!("Error while sending to inbox ({:?})", e),
}
}
}
@@ -152,7 +171,7 @@ impl Link for Id {}
#[serde(rename_all = "camelCase")]
pub struct ApSignature {
#[activitystreams(concrete(PublicKey), functional)]
pub public_key: Option<serde_json::Value>
pub public_key: Option<serde_json::Value>,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize, Properties)]
@@ -165,7 +184,7 @@ pub struct PublicKey {
pub owner: Option<serde_json::Value>,
#[activitystreams(concrete(String), functional)]
pub public_key_pem: Option<serde_json::Value>
pub public_key_pem: Option<serde_json::Value>,
}
#[derive(Clone, Debug, Default, UnitString)]
+59 -15
View File
@@ -1,5 +1,5 @@
use base64;
use chrono::{DateTime, offset::Utc};
use chrono::{offset::Utc, DateTime};
use openssl::hash::{Hasher, MessageDigest};
use reqwest::header::{ACCEPT, CONTENT_TYPE, DATE, HeaderMap, HeaderValue, USER_AGENT};
use std::ops::Deref;
@@ -14,35 +14,52 @@ pub struct Digest(String);
impl Digest {
pub fn digest(body: String) -> HeaderValue {
let mut hasher = Hasher::new(MessageDigest::sha256()).expect("Digest::digest: initialization error");
hasher.update(&body.into_bytes()[..]).expect("Digest::digest: content insertion error");
let mut hasher =
Hasher::new(MessageDigest::sha256()).expect("Digest::digest: initialization error");
hasher
.update(&body.into_bytes()[..])
.expect("Digest::digest: content insertion error");
let res = base64::encode(&hasher.finish().expect("Digest::digest: finalizing error"));
HeaderValue::from_str(&format!("SHA-256={}", res)).expect("Digest::digest: header creation error")
HeaderValue::from_str(&format!("SHA-256={}", res))
.expect("Digest::digest: header creation error")
}
pub fn verify(&self, body: String) -> bool {
if self.algorithm()=="SHA-256" {
let mut hasher = Hasher::new(MessageDigest::sha256()).expect("Digest::digest: initialization error");
hasher.update(&body.into_bytes()).expect("Digest::digest: content insertion error");
self.value().deref()==hasher.finish().expect("Digest::digest: finalizing error").deref()
if self.algorithm() == "SHA-256" {
let mut hasher =
Hasher::new(MessageDigest::sha256()).expect("Digest::digest: initialization error");
hasher
.update(&body.into_bytes())
.expect("Digest::digest: content insertion error");
self.value().deref()
== hasher
.finish()
.expect("Digest::digest: finalizing error")
.deref()
} else {
false //algorithm not supported
}
}
pub fn algorithm(&self) -> &str {
let pos = self.0.find('=').expect("Digest::algorithm: invalid header error");
let pos = self
.0
.find('=')
.expect("Digest::algorithm: invalid header error");
&self.0[..pos]
}
pub fn value(&self) -> Vec<u8> {
let pos = self.0.find('=').expect("Digest::value: invalid header error")+1;
let pos = self
.0
.find('=')
.expect("Digest::value: invalid header error") + 1;
base64::decode(&self.0[pos..]).expect("Digest::value: invalid encoding error")
}
pub fn from_header(dig: &str) -> Result<Self, ()> {
if let Some(pos) = dig.find('=') {
let pos = pos+1;
let pos = pos + 1;
if let Ok(_) = base64::decode(&dig[pos..]) {
Ok(Digest(dig.to_owned()))
} else {
@@ -60,15 +77,42 @@ pub fn headers() -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert(USER_AGENT, HeaderValue::from_static(PLUME_USER_AGENT));
headers.insert(DATE, HeaderValue::from_str(&date).expect("request::headers: date error"));
headers.insert(ACCEPT, HeaderValue::from_str(&ap_accept_header().into_iter().collect::<Vec<_>>().join(", ")).expect("request::headers: accept error"));
headers.insert(
DATE,
HeaderValue::from_str(&date).expect("request::headers: date error"),
);
headers.insert(
ACCEPT,
HeaderValue::from_str(
&ap_accept_header()
.into_iter()
.collect::<Vec<_>>()
.join(", "),
).expect("request::headers: accept error"),
);
headers.insert(CONTENT_TYPE, HeaderValue::from_static(AP_CONTENT_TYPE));
headers
}
pub fn signature<S: Signer>(signer: &S, headers: HeaderMap) -> HeaderValue {
let signed_string = headers.iter().map(|(h,v)| format!("{}: {}", h.as_str().to_lowercase(), v.to_str().expect("request::signature: invalid header error"))).collect::<Vec<String>>().join("\n");
let signed_headers = headers.iter().map(|(h,_)| h.as_str()).collect::<Vec<&str>>().join(" ").to_lowercase();
let signed_string = headers
.iter()
.map(|(h, v)| {
format!(
"{}: {}",
h.as_str().to_lowercase(),
v.to_str()
.expect("request::signature: invalid header error")
)
})
.collect::<Vec<String>>()
.join("\n");
let signed_headers = headers
.iter()
.map(|(h, _)| h.as_str())
.collect::<Vec<&str>>()
.join(" ")
.to_lowercase();
let data = signer.sign(signed_string);
let sign = base64::encode(&data[..]);
+66 -43
View File
@@ -1,12 +1,8 @@
use super::request;
use base64;
use chrono::Utc;
use hex;
use openssl::{
pkey::PKey,
rsa::Rsa,
sha::sha256
};
use super::request;
use openssl::{pkey::PKey, rsa::Rsa, sha::sha256};
use rocket::http::HeaderMap;
use serde_json;
@@ -15,14 +11,18 @@ pub fn gen_keypair() -> (Vec<u8>, Vec<u8>) {
let keypair = Rsa::generate(2048).expect("sign::gen_keypair: key generation error");
let keypair = PKey::from_rsa(keypair).expect("sign::gen_keypair: parsing error");
(
keypair.public_key_to_pem().expect("sign::gen_keypair: public key encoding error"),
keypair.private_key_to_pem_pkcs8().expect("sign::gen_keypair: private key encoding error")
keypair
.public_key_to_pem()
.expect("sign::gen_keypair: public key encoding error"),
keypair
.private_key_to_pem_pkcs8()
.expect("sign::gen_keypair: private key encoding error"),
)
}
pub trait Signer {
fn get_key_id(&self) -> String;
/// Sign some data with the signer keypair
fn sign(&self, to_sign: String) -> Vec<u8>;
/// Verify if the signature is valid
@@ -30,8 +30,12 @@ pub trait Signer {
}
pub trait Signable {
fn sign<T>(&mut self, creator: &T) -> &mut Self where T: Signer;
fn verify<T>(self, creator: &T) -> bool where T: Signer;
fn sign<T>(&mut self, creator: &T) -> &mut Self
where
T: Signer;
fn verify<T>(self, creator: &T) -> bool
where
T: Signer;
fn hash(data: String) -> String {
let bytes = data.into_bytes();
@@ -48,10 +52,12 @@ impl Signable for serde_json::Value {
"created": creation_date
});
let options_hash = Self::hash(json!({
let options_hash = Self::hash(
json!({
"@context": "https://w3id.org/identity/v1",
"created": creation_date
}).to_string());
}).to_string(),
);
let document_hash = Self::hash(self.to_string());
let to_be_signed = options_hash + &document_hash;
@@ -63,29 +69,34 @@ impl Signable for serde_json::Value {
}
fn verify<T: Signer>(mut self, creator: &T) -> bool {
let signature_obj = if let Some(sig) = self.as_object_mut().and_then(|o| o.remove("signature")) {
let signature_obj =
if let Some(sig) = self.as_object_mut().and_then(|o| o.remove("signature")) {
sig
} else {
//signature not present
return false;
};
let signature = if let Ok(sig) =
base64::decode(&signature_obj["signatureValue"].as_str().unwrap_or(""))
{
sig
} else {
//signature not present
return false
};
let signature = if let Ok(sig) = base64::decode(&signature_obj["signatureValue"].as_str().unwrap_or("")) {
sig
} else {
return false
return false;
};
let creation_date = &signature_obj["created"];
let options_hash = Self::hash(json!({
let options_hash = Self::hash(
json!({
"@context": "https://w3id.org/identity/v1",
"created": creation_date
}).to_string());
}).to_string(),
);
let document_hash = Self::hash(self.to_string());
let to_be_signed = options_hash + &document_hash;
creator.verify(to_be_signed, signature)
}
}
#[derive(Debug,Copy,Clone,PartialEq)]
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum SignatureValidity {
Invalid,
ValidNoDigest,
@@ -95,14 +106,18 @@ pub enum SignatureValidity {
impl SignatureValidity {
pub fn is_secure(&self) -> bool {
self==&SignatureValidity::Valid
self == &SignatureValidity::Valid
}
}
pub fn verify_http_headers<S: Signer+::std::fmt::Debug>(sender: &S, all_headers: HeaderMap, data: String) -> SignatureValidity{
pub fn verify_http_headers<S: Signer + ::std::fmt::Debug>(
sender: &S,
all_headers: HeaderMap,
data: String,
) -> SignatureValidity {
let sig_header = all_headers.get_one("Signature");
if sig_header.is_none() {
return SignatureValidity::Absent
return SignatureValidity::Absent;
}
let sig_header = sig_header.expect("sign::verify_http_headers: unreachable");
@@ -112,35 +127,43 @@ pub fn verify_http_headers<S: Signer+::std::fmt::Debug>(sender: &S, all_headers:
let mut signature = None;
for part in sig_header.split(',') {
match part {
part if part.starts_with("keyId=") => _key_id = Some(&part[7..part.len()-1]),
part if part.starts_with("algorithm=") => _algorithm = Some(&part[11..part.len()-1]),
part if part.starts_with("headers=") => headers = Some(&part[9..part.len()-1]),
part if part.starts_with("signature=") => signature = Some(&part[11..part.len()-1]),
_ => {},
part if part.starts_with("keyId=") => _key_id = Some(&part[7..part.len() - 1]),
part if part.starts_with("algorithm=") => _algorithm = Some(&part[11..part.len() - 1]),
part if part.starts_with("headers=") => headers = Some(&part[9..part.len() - 1]),
part if part.starts_with("signature=") => signature = Some(&part[11..part.len() - 1]),
_ => {}
}
}
if signature.is_none() || headers.is_none() {//missing part of the header
return SignatureValidity::Invalid
if signature.is_none() || headers.is_none() {
//missing part of the header
return SignatureValidity::Invalid;
}
let headers = headers.expect("sign::verify_http_headers: unreachable").split_whitespace().collect::<Vec<_>>();
let headers = headers
.expect("sign::verify_http_headers: unreachable")
.split_whitespace()
.collect::<Vec<_>>();
let signature = signature.expect("sign::verify_http_headers: unreachable");
let h = headers.iter()
.map(|header| (header,all_headers.get_one(header)))
let h = headers
.iter()
.map(|header| (header, all_headers.get_one(header)))
.map(|(header, value)| format!("{}: {}", header.to_lowercase(), value.unwrap_or("")))
.collect::<Vec<_>>().join("\n");
.collect::<Vec<_>>()
.join("\n");
if !sender.verify(h, base64::decode(signature).unwrap_or(Vec::new())) {
return SignatureValidity::Invalid
return SignatureValidity::Invalid;
}
if !headers.contains(&"digest") {// signature is valid, but body content is not verified
return SignatureValidity::ValidNoDigest
if !headers.contains(&"digest") {
// signature is valid, but body content is not verified
return SignatureValidity::ValidNoDigest;
}
let digest = all_headers.get_one("digest").unwrap_or("");
let digest = request::Digest::from_header(digest);
if !digest.map(|d| d.verify(data)).unwrap_or(false) {// signature was valid, but body content does not match its digest
if !digest.map(|d| d.verify(data)).unwrap_or(false) {
// signature was valid, but body content does not match its digest
SignatureValidity::Invalid
} else {
SignatureValidity::Valid// all check passed
SignatureValidity::Valid // all check passed
}
}