check message length before prefix comparisons

This commit is contained in:
Ken Sedgwick
2025-02-20 16:04:29 -08:00
parent 22f9c32121
commit dfa4b24b7d

View File

@@ -78,6 +78,11 @@ impl<'a> RelayMessage<'a> {
return Err(Error::Empty);
}
// make sure we can inspect the begning of the message below ...
if msg.len() < 12 {
return Err(Error::DecodeFailed("message too short".into()));
}
// Notice
// Relay response format: ["NOTICE", <message>]
if msg.len() >= 12 && &msg[0..=9] == "[\"NOTICE\"," {
@@ -159,6 +164,16 @@ mod tests {
fn test_handle_various_messages() -> Result<()> {
let tests = vec![
// Valid cases
(
// shortest valid message
r#"["EOSE","x"]"#,
Ok(RelayMessage::eose("x")),
),
(
// also very short
r#"["NOTICE",""]"#,
Ok(RelayMessage::notice("")),
),
(
r#"["NOTICE","Invalid event format!"]"#,
Ok(RelayMessage::notice("Invalid event format!")),
@@ -197,11 +212,11 @@ mod tests {
),
(
r#"["EOSE"]"#,
Err(Error::DecodeFailed("unrecognized message type".into())),
Err(Error::DecodeFailed("message too short".into())),
),
(
r#"["NOTICE"]"#,
Err(Error::DecodeFailed("unrecognized message type".into())),
Err(Error::DecodeFailed("message too short".into())),
),
(
r#"["NOTICE": 404]"#,