//! 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::(extra).is_err()); let mut short = ok; short["id"] = serde_json::json!("AAAA"); assert!(serde_json::from_value::(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::(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::(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::()) { let _ = MailboxId::parse(&text); let _ = InviteId::parse(&text); let _ = Sha256Hash::parse(&text); let _ = Token::parse(&text); let _ = Author::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::(), 0..300)) { let _ = serde_json::from_slice::(&bytes); let _ = serde_json::from_slice::(&bytes); let _ = serde_json::from_slice::(&bytes); let _ = serde_json::from_slice::(&bytes); let _ = serde_json::from_slice::(&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); } if let Ok(author) = Author::parse(&text) { prop_assert_eq!(&author.to_wire(), &text); } } /// Bytes survive the wire unchanged. #[test] fn bytes_round_trip(bytes in proptest::collection::vec(any::(), 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[..]); } } // Wake-up (`.agents/features/wake-up.md` §2.1): the push endpoint a mailbox may hold. #[test] fn a_push_endpoint_is_https_or_loopback_http_and_nothing_else() { for good in [ "https://ntfy.sh/upAbCdEf0123456789?up=1", "https://push.example.cz:8443/x", "https://[2001:db8::1]/up", "https://ntfy.sh", ] { let e = PushEndpoint::parse(good).unwrap_or_else(|_| panic!("{good}")); assert_eq!(e.as_str(), good); assert!(!e.is_loopback_http()); } assert_eq!( PushEndpoint::parse("https://NTFY.sh/a").map(|e| e.host().to_string()), Ok("ntfy.sh".into()) ); for loopback in [ "http://127.0.0.1:9000/up", "http://[::1]:9000/up", "http://localhost/up", ] { assert!(PushEndpoint::parse(loopback) .expect("loopback") .is_loopback_http()); } for bad in [ "", "ntfy.sh/up", "ftp://ntfy.sh/up", "http://ntfy.sh/up", "http://10.0.0.1/up", "https:///up", "https://user:pw@ntfy.sh/up", "https://user@ntfy.sh/up", "https://ntfy.sh/up#frag", "https://ntfy.sh/a b", "https://ntfy.sh/\u{e9}", "https://ntfy.sh:0/up", "https://ntfy.sh:65536/up", "https://ntfy.sh:08/up", "https://ntfy.sh:/up", "https://[::1/up", "https://ntfy]sh/up", ] { assert!(PushEndpoint::parse(bad).is_err(), "{bad}"); } let long = format!("https://ntfy.sh/{}", "a".repeat(MAX_PUSH_ENDPOINT_BYTES)); assert_eq!( PushEndpoint::parse(&long), Err(ParseError::TooLarge { max: MAX_PUSH_ENDPOINT_BYTES }) ); } #[test] fn set_push_refuses_unknown_fields_and_bad_endpoints_and_debug_hides_the_path() { let ok: SetPush = serde_json::from_str(r#"{"endpoint":"https://ntfy.sh/upSecret"}"#).expect("json"); assert_eq!(ok.endpoint.as_str(), "https://ntfy.sh/upSecret"); assert!(!format!("{ok:?}").contains("upSecret")); assert!(serde_json::from_str::(r#"{"endpoint":"http://ntfy.sh/x"}"#).is_err()); assert!( serde_json::from_str::(r#"{"endpoint":"https://ntfy.sh/x","extra":1}"#).is_err() ); assert_eq!( serde_json::to_string(&ok).expect("json"), r#"{"endpoint":"https://ntfy.sh/upSecret"}"# ); } proptest! { #[test] fn a_push_endpoint_parser_never_panics(text in "\\PC{0,64}") { let _ = PushEndpoint::parse(&text); let _ = PushEndpoint::parse(&format!("https://{text}")); } } // Reactions and replies (`.agents/features/reactions-replies.md` §2.1): a message's author. #[test] fn an_author_is_16_bytes_in_22_canonical_characters_and_prints_as_its_wire() { let author = Author::from_bytes([0x5A; 16]); let wire = author.to_wire(); assert_eq!(wire.len(), 22); assert_eq!(Author::parse(&wire), Ok(author)); assert_eq!( serde_json::to_string(&author).expect("json"), format!("\"{wire}\"") ); assert!(Author::parse(&wire[..21]).is_err()); assert!(Author::parse(&Token::from_bytes([1; 32]).to_wire()).is_err()); let zero = Author::from_bytes([0; 16]).to_wire(); assert_eq!( Author::parse(&format!("{}B", &zero[..21])), Err(ParseError::Encoding) ); assert_eq!(format!("{author:?}"), format!("Author({wire})")); }