Normalize panic message

Change all unwrap to expect
Normalize expect's messages
Don't panic where it could be avoided easily
This commit is contained in:
Trinity Pointard
2018-10-20 08:44:33 +02:00
parent 9d70eeae61
commit 4e6f3209d5
18 changed files with 279 additions and 252 deletions
+1 -1
View File
@@ -17,7 +17,7 @@ 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>().unwrap());
Self::from_activity(conn, obj, act.create_props.actor_link::<Id>().expect("FromActivity::try_from_activity: id not found error"));
true
} else {
false
+11 -4
View File
@@ -82,14 +82,13 @@ impl<'a, 'r> FromRequest<'a, 'r> for ApRequest {
"application/ld+json" => Outcome::Success(ApRequest),
"text/html" => Outcome::Forward(true),
_ => Outcome::Forward(false)
}).fold(Outcome::Forward(false), |out, ct| if out.is_success() || (out.is_forward() && out.clone().forwarded().unwrap()) {
}).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()
.filter(|u| !u.is_local())
@@ -97,7 +96,8 @@ pub fn broadcast<S: sign::Signer, A: Activity, T: inbox::WithInbox + Actor>(send
.collect::<Vec<String>>()
.unique();
let mut act = serde_json::to_value(act).unwrap();
let mut act = serde_json::to_value(act).expect("activity_pub::broadcast: serialization error");
act["@context"] = context();
let signed = act.sign(sender);
@@ -112,7 +112,14 @@ pub fn broadcast<S: sign::Signer, A: Activity, T: inbox::WithInbox + Actor>(send
.body(signed.to_string())
.send();
match res {
Ok(mut r) => println!("Successfully sent activity to inbox ({})\n\n{:?}", inbox, r.text().unwrap()),
Ok(mut r) => {
println!("Successfully sent activity to inbox ({})", inbox);
if let Ok(response) = r.text() {
println!("Response: \"{:?}\"\n\n", response)
} else {
println!("Error while reading response")
}
},
Err(e) => println!("Error while sending to inbox ({:?})", e)
}
}
+14 -14
View File
@@ -14,30 +14,30 @@ pub struct Digest(String);
impl Digest {
pub fn digest(body: String) -> HeaderValue {
let mut hasher = Hasher::new(MessageDigest::sha256()).unwrap();
hasher.update(&body.into_bytes()[..]).unwrap();
let res = base64::encode(&hasher.finish().unwrap());
HeaderValue::from_str(&format!("SHA-256={}", res)).unwrap()
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")
}
pub fn verify(&self, body: String) -> bool {
if self.algorithm()=="SHA-256" {
let mut hasher = Hasher::new(MessageDigest::sha256()).unwrap();
hasher.update(&body.into_bytes()).unwrap();
self.value().deref()==hasher.finish().unwrap().deref()
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('=').unwrap();
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('=').unwrap()+1;
base64::decode(&self.0[pos..]).unwrap()
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, ()> {
@@ -60,13 +60,13 @@ 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).unwrap());
headers.insert(ACCEPT, HeaderValue::from_str(&ap_accept_header().into_iter().collect::<Vec<_>>().join(", ")).unwrap());
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
}
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().unwrap())).collect::<Vec<String>>().join("\n");
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);
@@ -77,5 +77,5 @@ pub fn signature<S: Signer>(signer: &S, headers: HeaderMap) -> HeaderValue {
key_id = signer.get_key_id(),
signed_headers = signed_headers,
signature = sign
)).unwrap()
)).expect("request::signature: signature header error")
}
+9 -6
View File
@@ -12,9 +12,12 @@ use serde_json;
/// Returns (public key, private key)
pub fn gen_keypair() -> (Vec<u8>, Vec<u8>) {
let keypair = Rsa::generate(2048).unwrap();
let keypair = PKey::from_rsa(keypair).unwrap();
(keypair.public_key_to_pem().unwrap(), keypair.private_key_to_pem_pkcs8().unwrap())
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")
)
}
pub trait Signer {
@@ -101,7 +104,7 @@ pub fn verify_http_headers<S: Signer+::std::fmt::Debug>(sender: &S, all_headers:
if sig_header.is_none() {
return SignatureValidity::Absent
}
let sig_header = sig_header.unwrap();
let sig_header = sig_header.expect("sign::verify_http_headers: unreachable");
let mut _key_id = None;
let mut _algorithm = None;
@@ -120,8 +123,8 @@ pub fn verify_http_headers<S: Signer+::std::fmt::Debug>(sender: &S, all_headers:
if signature.is_none() || headers.is_none() {//missing part of the header
return SignatureValidity::Invalid
}
let headers = headers.unwrap().split_whitespace().collect::<Vec<_>>();
let signature = signature.unwrap();
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)))
.map(|(header, value)| format!("{}: {}", header.to_lowercase(), value.unwrap_or("")))