Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid using unwrap #184

Merged
merged 2 commits into from
Mar 3, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion rust/aes-gcm-siv/benches/aes_gcm_siv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ pub fn aes_gcm_siv(c: &mut Criterion) {

let key = vec![0xFF; 32];

let cipher = aes_gcm_siv::Aes256GcmSiv::new(&key).unwrap();
let cipher = aes_gcm_siv::Aes256GcmSiv::new(&key).expect("valid key size");
let aad = [0xADu8; 16];
let nonce = [0x42u8; 12];
let tag = [0x01; 16];
Expand Down
16 changes: 9 additions & 7 deletions rust/aes-gcm-siv/src/aes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,15 +91,17 @@ impl Aes256 {
}

#[test]
fn aes_kat() {
let key =
hex::decode("0000000000000000000000000000000000000000000000000000000000000000").unwrap();
let pt = hex::decode("00000000000000000000000000000010000000000000000000000000000000080000000000000000000000000000000400000000000000000000000000000002000000000000000000000000000000010000000000000000000000000000001000000000000000000000000000000008000000000000000000000000000000040000000000000000000000000000000200000000000000000000000000000001").unwrap();
let ct = hex::decode("1490A05A7CEE43BDE98B56E309DC0126ABFA77CD6E85DA245FB0BDC5E52CFC29DD4AB1284D4AE17B41E85924470C36F7CEA7403D4D606B6E074EC5D3BAF39D18530F8AFBC74536B9A963B4F1C4CB738B1490A05A7CEE43BDE98B56E309DC0126ABFA77CD6E85DA245FB0BDC5E52CFC29DD4AB1284D4AE17B41E85924470C36F7CEA7403D4D606B6E074EC5D3BAF39D18530F8AFBC74536B9A963B4F1C4CB738B").unwrap();
fn aes_kat() -> Result<()> {
let key = hex::decode("0000000000000000000000000000000000000000000000000000000000000000")
.expect("valid hex");
let pt = hex::decode("00000000000000000000000000000010000000000000000000000000000000080000000000000000000000000000000400000000000000000000000000000002000000000000000000000000000000010000000000000000000000000000001000000000000000000000000000000008000000000000000000000000000000040000000000000000000000000000000200000000000000000000000000000001").expect("valid hex");
let ct = hex::decode("1490A05A7CEE43BDE98B56E309DC0126ABFA77CD6E85DA245FB0BDC5E52CFC29DD4AB1284D4AE17B41E85924470C36F7CEA7403D4D606B6E074EC5D3BAF39D18530F8AFBC74536B9A963B4F1C4CB738B1490A05A7CEE43BDE98B56E309DC0126ABFA77CD6E85DA245FB0BDC5E52CFC29DD4AB1284D4AE17B41E85924470C36F7CEA7403D4D606B6E074EC5D3BAF39D18530F8AFBC74536B9A963B4F1C4CB738B").expect("valid hex");

let aes = Aes256::new(&key).unwrap();
let aes = Aes256::new(&key)?;

let mut buf = pt;
aes.encrypt(&mut buf).unwrap();
aes.encrypt(&mut buf)?;
assert_eq!(hex::encode(buf), hex::encode(ct));

Ok(())
}
2 changes: 1 addition & 1 deletion rust/aes-gcm-siv/src/aes_gcm_siv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ impl Aes256GcmSiv {

let mut ctr = [0u8; PAD_SIZE];
let mut pad = [0u8; PAD_SIZE];
let mut counter = u32::from_le_bytes(nonce[..4].try_into().unwrap());
let mut counter = u32::from_le_bytes(nonce[..4].try_into().expect("Correct size"));

let pads_required = (buffer.len() + PAD_SIZE) / PAD_SIZE;

Expand Down
1 change: 1 addition & 0 deletions rust/aes-gcm-siv/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

#![cfg_attr(target_arch = "aarch64", feature(stdsimd))]
#![cfg_attr(target_arch = "aarch64", feature(aarch64_target_feature))]
#![deny(clippy::unwrap_used)]

mod aes;
mod aes_gcm_siv;
Expand Down
18 changes: 10 additions & 8 deletions rust/aes-gcm-siv/src/polyval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,15 +80,17 @@ impl Polyval {
}

#[test]
fn polyval_kat() {
let h = hex::decode("25629347589242761d31f826ba4b757b").unwrap();
let input1 = hex::decode("4f4f95668c83dfb6401762bb2d01a262").unwrap();
let input2 = hex::decode("d1a24ddd2721d006bbe45f20d3c9f362").unwrap();
let mut poly = Polyval::new(&h).unwrap();
poly.update(&input1).unwrap();
poly.update(&input2).unwrap();
fn polyval_kat() -> Result<()> {
let h = hex::decode("25629347589242761d31f826ba4b757b").expect("valid hex");
let input1 = hex::decode("4f4f95668c83dfb6401762bb2d01a262").expect("valid hex");
let input2 = hex::decode("d1a24ddd2721d006bbe45f20d3c9f362").expect("valid hex");
let mut poly = Polyval::new(&h)?;
poly.update(&input1)?;
poly.update(&input2)?;

let result = poly.finalize().unwrap();
let result = poly.finalize()?;

assert_eq!(hex::encode(&result), "f7a3b47b846119fae5b7866cf5e5b77e");

Ok(())
}
52 changes: 30 additions & 22 deletions rust/aes-gcm-siv/tests/aes_gcm_siv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ struct WycheproofTestSet {
test_groups: Vec<WycheproofTestGroup>,
}

fn test_kat(kat: WycheproofTest) {
fn test_kat(kat: WycheproofTest) -> Result<(), aes_gcm_siv::Error> {
let key = hex::decode(kat.key).expect("valid hex");
let aad = hex::decode(kat.aad).expect("valid hex");
let nonce = hex::decode(kat.nonce).expect("valid hex");
Expand All @@ -65,15 +65,15 @@ fn test_kat(kat: WycheproofTest) {
wut => panic!("unknown result field {}", wut),
};

let aes_gcm_siv = aes_gcm_siv::Aes256GcmSiv::new(&key).unwrap();
let aes_gcm_siv = aes_gcm_siv::Aes256GcmSiv::new(&key)?;

let mut buf = pt.clone();
let generated_tag = aes_gcm_siv.encrypt(&mut buf, &nonce, &aad).unwrap();
let generated_tag = aes_gcm_siv.encrypt(&mut buf, &nonce, &aad)?;

if valid {
assert_eq!(hex::encode(generated_tag), hex::encode(&tag));
assert_eq!(hex::encode(&buf), hex::encode(ct));
aes_gcm_siv.decrypt(&mut buf, &nonce, &aad, &tag).unwrap();
aes_gcm_siv.decrypt(&mut buf, &nonce, &aad, &tag)?;
assert_eq!(hex::encode(&buf), hex::encode(pt));
} else {
assert_ne!(hex::encode(generated_tag), hex::encode(&tag));
Expand All @@ -87,10 +87,12 @@ fn test_kat(kat: WycheproofTest) {
Err(aes_gcm_siv::Error::InvalidTag)
);
}

Ok(())
}

#[test]
fn wycheproof_kats() {
fn wycheproof_kats() -> Result<(), aes_gcm_siv::Error> {
let kat_data = include_bytes!("data/aes_gcm_siv_test.json");
let kats: WycheproofTestSet = serde_json::from_slice(kat_data).expect("Valid JSON");

Expand All @@ -99,10 +101,12 @@ fn wycheproof_kats() {
for group in kats.test_groups {
if group.iv_size == 96 && group.key_size == 256 && group.tag_size == 128 {
for test in group.tests {
test_kat(test)
test_kat(test)?
}
}
}

Ok(())
}

#[derive(Default, Debug)]
Expand Down Expand Up @@ -165,20 +169,22 @@ impl FromStr for BoringKat {
}

#[test]
fn boringssl_tests() {
fn boringssl_tests() -> Result<(), aes_gcm_siv::Error> {
let kat_data = include_bytes!("data/boringssl.txt");
let kat_data = String::from_utf8(kat_data.to_vec()).expect("Valid UTF-8");

for kats in kat_data.split("\n\n") {
let kat = BoringKat::from_str(kats).expect("valid");
test_kat(kat.into());
test_kat(kat.into())?;
}

Ok(())
}

// This test takes several minutes when compiled without optimizations.
#[cfg(not(debug_assertions))]
#[test]
fn iterated_input_test() {
fn iterated_input_test() -> Result<(), aes_gcm_siv::Error> {
/*
A test which iteratively encrypts messages with lengths between 0
and 128K bytes, with the nonce changing every invocation. Finally
Expand All @@ -189,48 +195,50 @@ fn iterated_input_test() {
BoringSSL's implementation.
*/

let key =
hex::decode("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef").unwrap();
let aead = aes_gcm_siv::Aes256GcmSiv::new(&key).unwrap();
let key = hex::decode("0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef")
.expect("valid hex");
let aead = aes_gcm_siv::Aes256GcmSiv::new(&key)?;

let mut nonce = hex::decode("00112233445566778899aabb").unwrap();
let mut nonce = hex::decode("00112233445566778899aabb").expect("valid hex");
let mut buf = vec![];
let mut aad = [0u8; 32];

for _ in 0..(128 * 1024) {
let tag = aead.encrypt(&mut buf, &nonce, &aad).unwrap();
let tag = aead.encrypt(&mut buf, &nonce, &aad)?;
nonce[0..12].copy_from_slice(&tag[0..12]);
buf.push(tag[15]);
aad[(tag[13] as usize) % aad.len()] = tag[14];
}

let mut empty = vec![];
let final_tag = aead.encrypt(&mut empty, &nonce, &buf).unwrap();
let final_tag = aead.encrypt(&mut empty, &nonce, &buf)?;

assert_eq!(hex::encode(final_tag), "329f590781135f33c9a13d9553392b06");
Ok(())
}

// This test takes several minutes when compiled without optimizations.
#[cfg(not(debug_assertions))]
#[test]
fn long_input_tests() {
fn long_input_tests() -> Result<(), aes_gcm_siv::Error> {
/*
128 megabyte input, then hashed down to 128 bits. Crosschecked by BoringSSL
*/
let key =
hex::decode("0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF").unwrap();
let aead = aes_gcm_siv::Aes256GcmSiv::new(&key).unwrap();
let key = hex::decode("0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF0123456789ABCDEF")
.expect("valid hex");
let aead = aes_gcm_siv::Aes256GcmSiv::new(&key)?;

let nonce = hex::decode("00112233445566778899AABB").unwrap();
let nonce = hex::decode("00112233445566778899AABB").expect("valid hex");
let mut buf = vec![0u8; 1024 * 1024 * 128];
let aad = [0u8; 32];

let tag = aead.encrypt(&mut buf, &nonce, &aad).unwrap();
let tag = aead.encrypt(&mut buf, &nonce, &aad)?;

assert_eq!(hex::encode(tag), "4d37433fd26590cc6e3b2217f5167cae");

let mut empty = vec![];
let tag = aead.encrypt(&mut empty, &nonce, &buf).unwrap();
let tag = aead.encrypt(&mut empty, &nonce, &buf)?;

assert_eq!(hex::encode(tag), "337615a813dfde73e0fe646b16780b76");
Ok(())
}
1 change: 1 addition & 0 deletions rust/bridge/ffi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
//

#![allow(clippy::missing_safety_doc)]
#![warn(clippy::unwrap_used)]

use libc::{c_char, c_uchar, c_uint, size_t};
use libsignal_bridge::ffi::*;
Expand Down
3 changes: 2 additions & 1 deletion rust/bridge/ffi/src/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,8 @@ impl log::Log for FfiLogger {
.file()
.map(|file| CString::new(file).expect("no 0 bytes in file"));
let message = CString::new(record.args().to_string()).unwrap_or_else(|_| {
CString::new(record.args().to_string().replace("\0", "\\0")).unwrap()
CString::new(record.args().to_string().replace("\0", "\\0"))
.expect("We escaped any NULLs")
});
(self.log)(
target.as_ptr(),
Expand Down
1 change: 1 addition & 0 deletions rust/bridge/jni/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
//

#![allow(clippy::missing_safety_doc)]
#![deny(clippy::unwrap_used)]
jack-signal marked this conversation as resolved.
Show resolved Hide resolved

use jni::objects::JClass;
use jni::sys::{jbyteArray, jlongArray, jobject};
Expand Down
7 changes: 6 additions & 1 deletion rust/bridge/node/futures/src/exception.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,12 @@ impl PersistentException {
pub fn new<'a, V: Value>(cx: &mut impl Context<'a>, value: Handle<'a, V>) -> Self {
let wrapped = match value.downcast::<JsObject, _>(cx) {
Ok(object) => PersistentExceptionValue::Object(object.root(cx)),
Err(_) => PersistentExceptionValue::String(value.to_string(cx).unwrap().value(cx)),
Err(_) => PersistentExceptionValue::String(
value
.to_string(cx)
.expect("Exception can be converted to string")
.value(cx),
),
};
Self { wrapped }
}
Expand Down
2 changes: 1 addition & 1 deletion rust/bridge/node/futures/src/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ where
///
/// When the future completes, it is replaced by `None` to avoid accidentally polling twice.
fn poll(self: Arc<Self>) {
let future = &mut *self.future.lock().unwrap();
let future = &mut *self.future.lock().expect("Lock can be taken");
if let Some(active_future) = future {
match active_future
.as_mut()
Expand Down
4 changes: 2 additions & 2 deletions rust/bridge/node/futures/src/future.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ impl<T: 'static + Send> Future for JsFuture<T> {
type Output = T;

fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context) -> Poll<Self::Output> {
let mut state_guard = self.state.lock().unwrap();
let mut state_guard = self.state.lock().expect("Lock can be taken");
let state = mem::replace(&mut *state_guard, JsFutureState::Consumed);
match state {
JsFutureState::Settled(Ok(result)) => return Poll::Ready(result),
Expand Down Expand Up @@ -126,7 +126,7 @@ fn settle_promise<T: Send + 'static, R: JsPromiseResultConstructor>(
let js_result = cx.argument(1)?;

if let Some(future_state) = future_state.upgrade() {
let mut state_guard = future_state.lock().unwrap();
let mut state_guard = future_state.lock().expect("Lock can be taken");
let previous_state = mem::replace(&mut *state_guard, JsFutureState::Consumed);

if let JsFutureState::Pending { transform, waker } = previous_state {
Expand Down
1 change: 1 addition & 0 deletions rust/bridge/node/futures/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
#![feature(trait_alias)]
#![feature(wake_trait)]
#![warn(missing_docs)]
#![warn(clippy::unwrap_used)]

mod executor;
pub use executor::{ContextEx, EventQueueEx};
Expand Down
2 changes: 2 additions & 0 deletions rust/bridge/node/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
// SPDX-License-Identifier: AGPL-3.0-only
//

#![warn(clippy::unwrap_used)]

use neon::prelude::*;

pub mod logging;
Expand Down
4 changes: 2 additions & 2 deletions rust/bridge/shared/src/ffi/storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ impl IdentityKeyStore for &FfiIdentityKeyStoreStruct {
1 => Ok(true),
r => Err(SignalProtocolError::ApplicationCallbackError(
"save_identity",
Box::new(CallbackError::check(r).unwrap()),
Box::new(CallbackError::check(r).expect("verified non-zero")),
)),
}
}
Expand Down Expand Up @@ -135,7 +135,7 @@ impl IdentityKeyStore for &FfiIdentityKeyStoreStruct {
1 => Ok(true),
r => Err(SignalProtocolError::ApplicationCallbackError(
"is_trusted_identity",
Box::new(CallbackError::check(r).unwrap()),
Box::new(CallbackError::check(r).expect("verified non-zero")),
)),
}
}
Expand Down
1 change: 1 addition & 0 deletions rust/bridge/shared/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
//

#![allow(clippy::missing_safety_doc)]
#![deny(clippy::unwrap_used)]

#[cfg(not(any(feature = "ffi", feature = "jni", feature = "node")))]
compile_error!("Feature \"ffi\", \"jni\", or \"node\" must be enabled for this crate.");
Expand Down
2 changes: 2 additions & 0 deletions rust/poksho/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
// SPDX-License-Identifier: AGPL-3.0-only
//

#![warn(clippy::unwrap_used)]

pub mod args;
pub mod errors;
pub mod proof;
Expand Down
7 changes: 4 additions & 3 deletions rust/poksho/src/shohmacsha256.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ pub struct ShoHmacSha256 {
impl ShoApi for ShoHmacSha256 {
fn new(label: &[u8]) -> ShoHmacSha256 {
let mut sho = ShoHmacSha256 {
hasher: Hmac::<Sha256>::new_varkey(&[0; HASH_LEN]).unwrap(),
hasher: Hmac::<Sha256>::new_varkey(&[0; HASH_LEN]).expect("HMAC accepts 256-bit keys"),
cv: [0; HASH_LEN],
mode: Mode::RATCHETED,
};
Expand All @@ -38,7 +38,7 @@ impl ShoApi for ShoHmacSha256 {

fn absorb(&mut self, input: &[u8]) {
if let Mode::RATCHETED = self.mode {
self.hasher = Hmac::<Sha256>::new_varkey(&self.cv).unwrap();
self.hasher = Hmac::<Sha256>::new_varkey(&self.cv).expect("HMAC accepts 256-bit keys");
self.mode = Mode::ABSORBING;
}
self.hasher.update(input);
Expand All @@ -61,7 +61,8 @@ impl ShoApi for ShoHmacSha256 {
panic!();
}
let mut output = Vec::<u8>::new();
let output_hasher_prefix = Hmac::<Sha256>::new_varkey(&self.cv).unwrap();
let output_hasher_prefix =
Hmac::<Sha256>::new_varkey(&self.cv).expect("HMAC accepts 256-bit keys");
let mut i = 0;
while i * HASH_LEN < outlen {
let mut output_hasher = output_hasher_prefix.clone();
Expand Down
2 changes: 1 addition & 1 deletion rust/poksho/src/sign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ mod tests {
use curve25519_dalek::constants::RISTRETTO_BASEPOINT_POINT;

#[test]
#[allow(clippy::needless_range_loop)]
#[allow(clippy::needless_range_loop, clippy::unwrap_used)]
fn test_signature() {
let mut block64 = [0u8; 64];
let mut block32 = [0u8; 32];
Expand Down