Files
Amicitia-Tabellarius/crates/protocol/tests/wire.rs
T

187 lines
6.6 KiB
Rust

//! The wire spelling: one value, one spelling, and no input that panics a parser.
use proptest::prelude::*;
use tabellarius_protocol::*;
#[test]
fn ids_and_tokens_round_trip_through_their_wire_spelling() {
let id = MailboxId::from_bytes([7; 16]);
assert_eq!(id.to_wire().len(), 22);
assert_eq!(MailboxId::parse(&id.to_wire()), Ok(id));
let token = Token::from_bytes([9; 32]);
assert_eq!(token.to_wire().len(), 43);
assert_eq!(Token::from_bearer(&token.to_bearer()), Ok(token));
}
#[test]
fn a_wrong_length_alphabet_padding_or_spelling_is_refused() {
let good = MailboxId::from_bytes([0xAB; 16]).to_wire();
// one character short, one too many
assert!(MailboxId::parse(&good[..21]).is_err());
assert!(MailboxId::parse(&format!("{good}A")).is_err());
// the standard alphabet and padding are not this protocol's
assert_eq!(
MailboxId::parse(&good.replace('-', "+").replace('_', "/").replace('q', "+")),
Err(ParseError::Encoding)
);
assert_eq!(
MailboxId::parse(&format!("{good}==")),
Err(ParseError::Encoding)
);
// a Token is not a MailboxId
assert!(matches!(
MailboxId::parse(&Token::from_bytes([1; 32]).to_wire()),
Err(ParseError::Length { expected: 16, .. })
));
assert_eq!(
MailboxId::parse(""),
Err(ParseError::Length {
expected: 16,
got: 0
})
);
}
#[test]
fn a_second_spelling_of_the_same_bytes_is_refused() {
// 16 bytes leave 4 unused bits in the last character. 'A' (000000) is canonical for a zero
// tail; 'B' (000001) decodes to the same bytes with a non-zero unused bit.
let canonical = MailboxId::from_bytes([0; 16]).to_wire();
assert!(canonical.ends_with('A'));
let other = format!("{}B", &canonical[..21]);
assert_eq!(MailboxId::parse(&other), Err(ParseError::Encoding));
}
#[test]
fn a_bearer_header_needs_its_scheme() {
let token = Token::from_bytes([3; 32]);
assert_eq!(
Token::from_bearer(&token.to_wire()),
Err(ParseError::Scheme)
);
assert_eq!(
Token::from_bearer(&format!("bearer {}", token.to_wire())),
Err(ParseError::Scheme)
);
assert!(Token::from_bearer(&format!("Bearer {}", token.to_wire())).is_err());
}
#[test]
fn a_token_is_never_printed() {
let token = Token::from_bytes([0x5A; 32]);
let shown = format!("{token:?}");
assert_eq!(shown, "Token(..)");
assert!(!shown.contains(&token.to_wire()));
}
#[test]
fn the_hash_of_a_token_is_its_sha256() {
// SHA-256 of 32 zero bytes, a published value.
let hash = Token::from_bytes([0; 32]).hash();
let hex: String = hash.as_bytes().iter().map(|b| format!("{b:02x}")).collect();
assert_eq!(
hex,
"66687aadf862bd776c8fc18b8e9f8e20089714856ee233b3902a591d0d5f2925"
);
}
#[test]
fn json_bodies_refuse_unknown_fields_and_bad_values() {
let ok = serde_json::json!({
"id": MailboxId::from_bytes([1; 16]).to_wire(),
"postTokenHash": Sha256Hash::from_bytes([2; 32]).to_wire(),
"fetchTokenHash": Sha256Hash::from_bytes([3; 32]).to_wire(),
});
let parsed: CreateMailbox = serde_json::from_value(ok.clone()).expect("valid body");
assert_eq!(parsed.id, MailboxId::from_bytes([1; 16]));
let mut extra = ok.clone();
extra["name"] = serde_json::json!("Eva");
assert!(serde_json::from_value::<CreateMailbox>(extra).is_err());
let mut short = ok;
short["id"] = serde_json::json!("AAAA");
assert!(serde_json::from_value::<CreateMailbox>(short).is_err());
}
#[test]
fn a_key_package_over_the_limit_is_refused_before_decoding() {
let at_limit = KeyPackageBytes::new(vec![0; MAX_KEY_PACKAGE_BYTES]).expect("at the limit");
let body = serde_json::json!({
"id": InviteId::from_bytes([1; 16]).to_wire(),
"secretHash": Sha256Hash::from_bytes([2; 32]).to_wire(),
"keyPackage": at_limit,
});
assert!(serde_json::from_value::<CreateInvite>(body.clone()).is_ok());
let mut over = body;
over["keyPackage"] = serde_json::json!("A".repeat(MAX_KEY_PACKAGE_BYTES / 3 * 4 + 8));
let err = serde_json::from_value::<CreateInvite>(over).expect_err("over the limit");
assert!(err.to_string().contains("more than"), "{err}");
assert!(KeyPackageBytes::new(vec![0; MAX_KEY_PACKAGE_BYTES + 1]).is_err());
}
#[test]
fn time_is_kept_only_to_the_hour_and_the_day() {
assert_eq!(hour_of(7199), 1);
assert_eq!(hour_of(-1), -1);
assert_eq!(day_of(86_399), 0);
assert_eq!(day_of(86_400), 1);
}
fn config() -> ProptestConfig {
ProptestConfig {
cases: 10_000,
..ProptestConfig::default()
}
}
proptest! {
#![proptest_config(config())]
/// Any string at all: every parser answers with a value or an error, never a panic.
#[test]
fn no_string_panics_a_parser(text in any::<String>()) {
let _ = MailboxId::parse(&text);
let _ = InviteId::parse(&text);
let _ = Sha256Hash::parse(&text);
let _ = Token::parse(&text);
let _ = Token::from_bearer(&text);
let _ = WireBytes::parse(&text, MAX_BLOB_BYTES);
}
/// Strings from the base64url alphabet (the ones that get furthest into the decoder).
#[test]
fn no_base64url_string_panics_a_parser(text in "[A-Za-z0-9_=+/-]{0,90}") {
let _ = MailboxId::parse(&text);
let _ = Token::parse(&text);
let _ = Token::from_bearer(&format!("Bearer {text}"));
let _ = WireBytes::parse(&text, 64);
}
/// Any JSON-ish bytes given to every request body: an error or a value, never a panic.
#[test]
fn no_body_panics_the_json_parsers(bytes in proptest::collection::vec(any::<u8>(), 0..300)) {
let _ = serde_json::from_slice::<CreateMailbox>(&bytes);
let _ = serde_json::from_slice::<RotatePostToken>(&bytes);
let _ = serde_json::from_slice::<CreateInvite>(&bytes);
let _ = serde_json::from_slice::<FetchedBlobs>(&bytes);
let _ = serde_json::from_slice::<ClaimedInvite>(&bytes);
}
/// Every id that parses has exactly the spelling it was given.
#[test]
fn whatever_parses_has_one_spelling(text in "[A-Za-z0-9_-]{22}") {
if let Ok(id) = MailboxId::parse(&text) {
prop_assert_eq!(id.to_wire(), text);
}
}
/// Bytes survive the wire unchanged.
#[test]
fn bytes_round_trip(bytes in proptest::collection::vec(any::<u8>(), 0..512)) {
let wire = serde_json::to_string(&BlobBytes::new(bytes.clone()).expect("small")).expect("json");
let back: BlobBytes = serde_json::from_str(&wire).expect("parses");
prop_assert_eq!(back.bytes(), &bytes[..]);
}
}