lxmf: hash messages canonically and match upstream names and paper URIs

This commit is contained in:
DeFiDude committed 2026-11-10 00:00:36 -07:00
1 parent 00f439df7e
commit 408d088e56
13 files changed
+1597 -186

No files matched your search

Generated
+7
View File
@@ -669,6 +669,7 @@ dependencies = [
"thiserror 2.0.18",
"tokio",
"tracing",
"unicode-general-category",
"unicode-normalization",
]
@@ -1627,6 +1628,12 @@ dependencies = [
"thiserror 2.0.18",
]
[[package]]
name = "unicode-general-category"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2281c8c1d221438e373249e065ca4989c4c36952c211ff21a0ee91c44a3869e7"
[[package]]
name = "unicode-ident"
version = "1.0.24"
+1
View File
@@ -58,6 +58,7 @@ thiserror = "2"
hex = "0.4"
tempfile = "3"
unicode-normalization = "0.1"
unicode-general-category = "0.6"
# Testing
proptest = "1"
+1
View File
@@ -27,6 +27,7 @@ sha2 = { workspace = true }
rand = { workspace = true }
hex = { workspace = true }
unicode-normalization = { workspace = true }
unicode-general-category = { workspace = true }
[target.'cfg(target_os = "ios")'.dependencies]
objc2 = "0.6"
+356 -117
View File
@@ -7,7 +7,6 @@
use std::collections::HashMap;
use crate::constants::*;
use crate::presentation::{MAX_ADVERTISED_NAME_CHARS, sanitize_name};
/// Announce handler type.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -101,12 +100,12 @@ impl PropagationNodeAnnounceData {
}
}
/// Set the advertised node name unchanged; an empty name is not advertised.
pub fn set_name(&mut self, name: &str) {
let name = sanitize_name(name, MAX_ADVERTISED_NAME_CHARS);
if name.is_empty() {
self.metadata.remove(&PN_META_NAME);
} else {
self.metadata.insert(PN_META_NAME, name.into_bytes());
self.metadata.insert(PN_META_NAME, name.as_bytes().to_vec());
}
}
}
@@ -144,55 +143,271 @@ pub fn get_propagation_node_app_data(data: &PropagationNodeAnnounceData) -> Vec<
crate::encode_value(&announce_data)
}
/// Parse a propagation-node announce array with at least seven elements.
/// Decode MessagePack with the acceptance rules of Python's umsgpack decoder.
fn decode_python(data: &[u8]) -> Option<rmpv::Value> {
crate::message::canonical::validate_leading(data).ok()?;
rmpv::decode::read_value(&mut &data[..]).ok()
}
/// Python `==` between a decoded value and an integer.
fn python_equals_int(value: &rmpv::Value, target: i64) -> bool {
match value {
rmpv::Value::Integer(n) => n.as_i64() == Some(target),
rmpv::Value::Boolean(b) => i64::from(*b) == target,
rmpv::Value::F32(f) => f64::from(*f) == target as f64,
rmpv::Value::F64(f) => *f == target as f64,
_ => false,
}
}
/// Python `len()`; `None` where Python raises `TypeError`.
fn python_len(value: &rmpv::Value) -> Option<usize> {
match value {
rmpv::Value::Array(items) => Some(items.len()),
rmpv::Value::Map(entries) => Some(entries.len()),
rmpv::Value::String(text) => text.as_str().map(|t| t.chars().count()),
rmpv::Value::Binary(bytes) => Some(bytes.len()),
_ => None,
}
}
/// Python `value[index]` for a non-negative integer index.
fn python_index(value: &rmpv::Value, index: usize) -> Option<rmpv::Value> {
match value {
rmpv::Value::Array(items) => items.get(index).cloned(),
rmpv::Value::Binary(bytes) => bytes.get(index).map(|b| rmpv::Value::from(*b)),
rmpv::Value::String(text) => text
.as_str()?
.chars()
.nth(index)
.map(|c| rmpv::Value::from(c.to_string())),
rmpv::Value::Map(entries) => entries
.iter()
.rev()
.find(|(k, _)| python_equals_int(k, index as i64))
.map(|(_, v)| v.clone()),
_ => None,
}
}
/// Characters stripped by Python `bytes.strip()` / skipped by `int(bytes)`.
fn is_ascii_python_space(c: char) -> bool {
matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0b' | '\x0c')
}
/// Decimal value of a digit accepted by Python `int(str)` (`Nd` characters).
fn decimal_digit(c: char, unicode: bool) -> Option<u32> {
if let Some(d) = c.to_digit(10) {
return Some(d);
}
if !unicode || c.is_ascii() {
return None;
}
use unicode_general_category::{GeneralCategory, get_general_category};
let is_nd = |c: char| get_general_category(c) == GeneralCategory::DecimalNumber;
if !is_nd(c) {
return None;
}
// Unicode assigns Nd characters in contiguous runs that start at zero.
let mut start = c as u32;
while start > 0 && char::from_u32(start - 1).is_some_and(is_nd) {
start -= 1;
}
Some((c as u32 - start) % 10)
}
/// Text of a str/bytes value with Python's surrounding whitespace removed.
fn python_numeric_text(value: &rmpv::Value) -> Option<(String, bool)> {
match value {
rmpv::Value::String(text) => Some((
crate::presentation::python_strip(text.as_str()?).to_string(),
true,
)),
rmpv::Value::Binary(bytes) => {
let text = std::str::from_utf8(bytes).ok().filter(|t| t.is_ascii())?;
Some((text.trim_matches(is_ascii_python_space).to_string(), false))
}
_ => None,
}
}
/// Digits with single underscores between them, mapped to ASCII.
fn python_digit_run(text: &str, unicode: bool) -> Option<String> {
let mut out = String::new();
let mut previous_digit = false;
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
if c == '_' {
let next_digit = chars
.peek()
.is_some_and(|n| decimal_digit(*n, unicode).is_some());
if !previous_digit || !next_digit {
return None;
}
previous_digit = false;
continue;
}
let digit = decimal_digit(c, unicode)?;
out.push(char::from_digit(digit, 10).expect("decimal digit"));
previous_digit = true;
}
(!out.is_empty()).then_some(out)
}
/// Python `int(value)`; `None` where Python raises. Saturates outside `i128`.
fn python_int(value: &rmpv::Value) -> Option<i128> {
match value {
rmpv::Value::Integer(n) => n
.as_i64()
.map(i128::from)
.or_else(|| n.as_u64().map(i128::from)),
rmpv::Value::Boolean(b) => Some(i128::from(*b)),
rmpv::Value::F32(f) => f.is_finite().then(|| f.trunc() as i128),
rmpv::Value::F64(f) => f.is_finite().then(|| f.trunc() as i128),
rmpv::Value::String(_) | rmpv::Value::Binary(_) => {
let (text, unicode) = python_numeric_text(value)?;
let (negative, digits) = match text.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, text.strip_prefix('+').unwrap_or(&text)),
};
let digits = python_digit_run(digits, unicode)?;
let magnitude = digits.bytes().fold(0i128, |acc, d| {
acc.saturating_mul(10).saturating_add(i128::from(d - b'0'))
});
Some(if negative { -magnitude } else { magnitude })
}
_ => None,
}
}
/// Python `float(value)`; `None` where Python raises.
fn python_float(value: &rmpv::Value) -> Option<f64> {
match value {
rmpv::Value::Integer(n) => n
.as_i64()
.map(|i| i as f64)
.or_else(|| n.as_u64().map(|u| u as f64)),
rmpv::Value::Boolean(b) => Some(f64::from(u8::from(*b))),
rmpv::Value::F32(f) => Some(f64::from(*f)),
rmpv::Value::F64(f) => Some(*f),
rmpv::Value::String(_) | rmpv::Value::Binary(_) => {
let (text, unicode) = python_numeric_text(value)?;
let body = text.strip_prefix(['+', '-']).unwrap_or(&text);
let lower = body.to_ascii_lowercase();
if matches!(lower.as_str(), "inf" | "infinity" | "nan") {
return text.to_ascii_lowercase().parse::<f64>().ok();
}
let sign = &text[..text.len() - body.len()];
let (mantissa, exponent) = match body.find(['e', 'E']) {
Some(at) => (&body[..at], Some(&body[at + 1..])),
None => (body, None),
};
let (whole, fraction) = match mantissa.split_once('.') {
Some((w, f)) => (w, Some(f)),
None => (mantissa, None),
};
let run = |part: &str| {
if part.is_empty() {
Some(String::new())
} else {
python_digit_run(part, unicode)
}
};
let whole = run(whole)?;
let fraction = match fraction {
Some(part) => Some(run(part)?),
None => None,
};
if whole.is_empty() && fraction.as_deref().is_none_or(str::is_empty) {
return None;
}
let mut normalized = format!("{sign}{whole}");
if let Some(fraction) = fraction {
normalized.push('.');
normalized.push_str(&fraction);
}
if let Some(exponent) = exponent {
let exponent_body = exponent.strip_prefix(['+', '-']).unwrap_or(exponent);
let exponent_sign = &exponent[..exponent.len() - exponent_body.len()];
normalized.push('e');
normalized.push_str(exponent_sign);
normalized.push_str(&python_digit_run(exponent_body, unicode)?);
}
normalized.parse::<f64>().ok()
}
_ => None,
}
}
/// `Some(state)` when Python's `value == True` or `value == False` holds.
fn python_bool_state(value: &rmpv::Value) -> Option<bool> {
if python_equals_int(value, 1) {
Some(true)
} else if python_equals_int(value, 0) {
Some(false)
} else {
None
}
}
fn python_floats(list: &rmpv::Value) -> Option<()> {
if !list.is_array() {
return None;
}
for i in 0..3 {
python_float(&python_index(list, i)?)?;
}
Some(())
}
/// The decoded announce when Python `pn_announce_data_is_valid` accepts it.
fn valid_pn_announce(data: &[u8]) -> Option<rmpv::Value> {
let value = decode_python(data)?;
let length = python_len(&value)?;
if length < 7 {
return None;
}
python_int(&python_index(&value, 1)?)?;
python_bool_state(&python_index(&value, 2)?)?;
python_int(&python_index(&value, 3)?)?;
python_int(&python_index(&value, 4)?)?;
python_floats(&python_index(&value, 5)?)?;
if !python_index(&value, 6)?.is_map() {
return None;
}
if length > 7 {
python_floats(&python_index(&value, 7)?)?;
}
Some(value)
}
/// Python `pn_announce_data_is_valid`, including its `int()`/`float()`
/// coercions and the transitional slot 7 check.
pub fn pn_announce_data_is_valid(data: &[u8]) -> bool {
valid_pn_announce(data).is_some()
}
/// Parse propagation-node announce data that [`pn_announce_data_is_valid`] accepts.
///
/// Requires a boolean state, numeric timebase, nonnegative finite limits/costs,
/// a cost array with at least three values, and a metadata map. Rust casts apply; costs must
/// fit in `u8` after conversion. The legacy slot is ignored. Only metadata with
/// `u8` keys and binary values is retained. Extra array elements and trailing
/// MessagePack bytes are not rejected.
///
/// This parser does not authenticate the announce or enforce timebase freshness.
/// Its coercion and filtering rules differ from Python `pn_announce_data_is_valid`.
/// Values are extracted with `int()` as the Python announce handler does; it
/// returns `None` where that handler's conversion raises. Limits below zero
/// become zero and costs saturate to the `u8` range. Fractional costs in slot
/// 7 are not read. Only metadata with `u8` keys and binary values is retained.
pub fn parse_pn_announce_data(data: &[u8]) -> Option<PropagationNodeAnnounceData> {
fn nonnegative_u64(value: &rmpv::Value) -> Option<u64> {
value
.as_u64()
.or_else(|| value.as_i64().and_then(|number| number.try_into().ok()))
.or_else(|| {
value.as_f64().and_then(|number| {
(number.is_finite() && number >= 0.0).then_some(number as u64)
})
})
}
let value = valid_pn_announce(data)?;
let int_at = |index: usize| python_int(&python_index(&value, index)?);
let timebase = int_at(1)?.clamp(i128::from(i64::MIN), i128::from(i64::MAX)) as i64;
let node_state = python_bool_state(&python_index(&value, 2)?)?;
let limit = |raw: i128| raw.clamp(0, i128::from(u64::MAX)) as u64;
let transfer_limit = limit(int_at(3)?);
let sync_limit = limit(int_at(4)?);
let costs = python_index(&value, 5)?;
let cost =
|index: usize| python_int(&python_index(&costs, index)?).map(|raw| raw.clamp(0, 255) as u8);
let (stamp_cost, stamp_flex, peering_cost) = (cost(0)?, cost(1)?, cost(2)?);
let value: rmpv::Value = rmpv::decode::read_value(&mut &data[..]).ok()?;
let arr = value.as_array()?;
if arr.len() < 7 {
return None;
}
let timebase = arr[1]
.as_i64()
.or_else(|| arr[1].as_u64().map(|u| u as i64))
.or_else(|| arr[1].as_f64().map(|f| f as i64))?;
let node_state = arr[2].as_bool()?;
let transfer_limit = nonnegative_u64(&arr[3])?;
let sync_limit = nonnegative_u64(&arr[4])?;
let costs = arr[5].as_array()?;
if costs.len() < 3 {
return None;
}
let stamp_cost = u8::try_from(nonnegative_u64(&costs[0])?).ok()?;
let stamp_flex = u8::try_from(nonnegative_u64(&costs[1])?).ok()?;
let peering_cost = u8::try_from(nonnegative_u64(&costs[2])?).ok()?;
// Python's `pn_announce_data_is_valid()` requires the metadata element to
// be a map. Unknown keys and non-binary values are ignored here because
// the typed Rust API can only retain metadata it can represent safely.
let mut metadata = HashMap::new();
for (k, v) in arr[6].as_map()? {
for (k, v) in python_index(&value, 6)?.as_map()? {
if let (Some(key), Some(val)) = (
k.as_u64().and_then(|number| number.try_into().ok()),
v.as_slice().map(|s| s.to_vec()),
@@ -214,9 +429,9 @@ pub fn parse_pn_announce_data(data: &[u8]) -> Option<PropagationNodeAnnounceData
})
}
/// Extract stamp cost from propagation-node announce data.
/// Extract the integer stamp cost from propagation-node announce data.
///
/// Uses [`parse_pn_announce_data`] and its numeric conversion rules.
/// Uses [`parse_pn_announce_data`]; the fractional slot 7 is not read.
pub fn pn_stamp_cost_from_app_data(data: &[u8]) -> Option<u8> {
parse_pn_announce_data(data).map(|p| p.stamp_cost)
}
@@ -226,16 +441,11 @@ pub fn pn_stamp_cost_from_app_data(data: &[u8]) -> Option<u8> {
/// list advertises [`SF_COMPRESSION`].
///
/// `stamp_cost` must be in `1..=254`; out-of-range or `None` values are encoded as nil.
///
/// Names are sanitized and limited to [`MAX_ADVERTISED_NAME_CHARS`] characters.
/// Python reference: `LXMRouter.get_announce_app_data`.
/// The name is encoded unchanged, as Python `LXMRouter.get_announce_app_data` does.
pub fn get_announce_app_data(display_name: Option<&str>, stamp_cost: Option<u8>) -> Vec<u8> {
use rmpv::Value;
let name_val = display_name
.map(|name| sanitize_name(name, MAX_ADVERTISED_NAME_CHARS))
.filter(|name| !name.is_empty())
.map_or(Value::Nil, |name| Value::Binary(name.into_bytes()));
let name_val = display_name.map_or(Value::Nil, |name| Value::Binary(name.as_bytes().to_vec()));
let cost_val = match stamp_cost {
Some(cost) if cost > 0 && cost < 255 => Value::from(cost as u64),
@@ -250,67 +460,93 @@ pub fn get_announce_app_data(display_name: Option<&str>, stamp_cost: Option<u8>)
crate::encode_value(&peer_data)
}
/// Parse delivery-announce `app_data`, returning `(display_name, stamp_cost)`.
///
/// Requires an array with at least two elements; later elements are ignored.
/// A binary UTF-8 name is sanitized and bounded. Unsigned stamp costs are cast
/// to `u8`, retaining the low byte; this does not apply the encoder's `1..=254`
/// filter. Original raw-text announce names are not parsed by this helper.
/// First byte of the MessagePack delivery-announce format (fixarray or array16);
/// anything else is the original raw-name format.
fn is_announce_array_marker(byte: u8) -> bool {
matches!(byte, 0x90..=0x9f | 0xdc)
}
/// The decoded list of MessagePack-format delivery-announce data.
fn announce_list(data: &[u8]) -> Option<Vec<rmpv::Value>> {
match decode_python(data)? {
rmpv::Value::Array(items) => Some(items),
_ => None,
}
}
/// Parse delivery-announce `app_data`, returning `(display_name, stamp_cost)`
/// as [`display_name_from_app_data`] and [`stamp_cost_from_app_data`] return them.
/// Returns `None` for empty data.
pub fn parse_announce_app_data(data: &[u8]) -> Option<(Option<String>, Option<u8>)> {
let value: rmpv::Value = rmpv::decode::read_value(&mut &data[..]).ok()?;
let arr = value.as_array()?;
if arr.len() < 2 {
if data.is_empty() {
return None;
}
let display_name = arr[0]
.as_slice()
.and_then(|b| String::from_utf8(b.to_vec()).ok())
.map(|name| sanitize_name(&name, MAX_ADVERTISED_NAME_CHARS))
.filter(|name| !name.is_empty());
let stamp_cost = arr[1].as_u64().map(|c| c as u8);
Some((display_name, stamp_cost))
Some((
display_name_from_app_data(data),
stamp_cost_from_app_data(data),
))
}
/// Extract just the display name from delivery-announce `app_data`.
///
/// Uses [`parse_announce_app_data`], including its name sanitization and array-only format.
/// Python `display_name_from_app_data`: the raw name with NUL characters and
/// surrounding whitespace removed. Original-format data is decoded as UTF-8.
/// The name is not filtered for display; see [`crate::presentation::sanitize_name`].
pub fn display_name_from_app_data(data: &[u8]) -> Option<String> {
parse_announce_app_data(data).and_then(|(name, _)| name)
let first = *data.first()?;
if !is_announce_array_marker(first) {
return std::str::from_utf8(data).ok().map(str::to_string);
}
let items = announce_list(data)?;
// A str element has no .decode() in Python and yields None.
let rmpv::Value::Binary(bytes) = items.first()? else {
return None;
};
let name = std::str::from_utf8(bytes).ok()?;
Some(crate::presentation::python_strip(&name.replace('\0', "")).to_string())
}
/// Extract just the stamp cost from delivery-announce `app_data`.
///
/// Uses [`parse_announce_app_data`], including its unsigned-to-`u8` cast.
/// Python `stamp_cost_from_app_data`: element 3 when it is an integer, else
/// element 1, as a `u8` when representable. A fractional element 3 is not
/// read; element 1 carries its ceiling.
pub fn stamp_cost_from_app_data(data: &[u8]) -> Option<u8> {
parse_announce_app_data(data).and_then(|(_, cost)| cost)
if !is_announce_array_marker(*data.first()?) {
return None;
}
let items = announce_list(data)?;
if items.len() < 2 {
return None;
}
let cost = match items.get(3) {
Some(rmpv::Value::Integer(n)) if items.len() > 3 => n.as_i64(),
_ => match &items[1] {
rmpv::Value::Integer(n) => n.as_i64(),
rmpv::Value::F64(f) if f.fract() == 0.0 => Some(*f as i64),
rmpv::Value::F32(f) if f.fract() == 0.0 => Some(*f as i64),
_ => None,
},
};
cost.and_then(|c| u8::try_from(c).ok())
}
/// Parse advertised `SF_COMPRESSION` support in delivery-announce `app_data`.
///
/// Legacy 2-element app_data, malformed data, and missing feature lists are
/// treated as unknown. A present feature list is authoritative.
/// Original-format, malformed and list-less data are `Unknown`. A present
/// feature list is authoritative; members compare with Python `==`, so
/// `false` and `0.0` count as `SF_COMPRESSION`.
///
/// Related Python helper: `compression_support_from_app_data`.
pub fn compression_support_state_from_app_data(data: &[u8]) -> CompressionSupport {
let Ok(value) = rmpv::decode::read_value(&mut &data[..]) else {
return CompressionSupport::Unknown;
};
let Some(arr) = value.as_array() else {
return CompressionSupport::Unknown;
};
if arr.len() < 3 {
if !data.first().is_some_and(|b| is_announce_array_marker(*b)) {
return CompressionSupport::Unknown;
}
let Some(features) = arr[2].as_array() else {
let Some(items) = announce_list(data) else {
return CompressionSupport::Unknown;
};
let Some(rmpv::Value::Array(features)) = items.get(2) else {
return CompressionSupport::Unknown;
};
if features
.iter()
.any(|f| f.as_u64() == Some(crate::constants::SF_COMPRESSION as u64))
.any(|f| python_equals_int(f, i64::from(crate::constants::SF_COMPRESSION)))
{
CompressionSupport::Supported
} else {
@@ -318,27 +554,23 @@ pub fn compression_support_state_from_app_data(data: &[u8]) -> CompressionSuppor
}
}
/// Check whether a peer advertises `SF_COMPRESSION` support in its delivery-announce `app_data`.
///
/// Returns true for Supported or Unknown, including empty/malformed input and
/// missing or non-list feature metadata. Only a present feature list without
/// `SF_COMPRESSION` returns false. This boolean default differs from Python
/// helper cases that return `None` or raise a decode error.
/// Python `compression_support_from_app_data` as a boolean: only a present
/// feature list without `SF_COMPRESSION` returns false. Empty or undecodable
/// data, where Python returns `None` or raises, returns true.
pub fn compression_support_from_app_data(data: &[u8]) -> bool {
compression_support_state_from_app_data(data) != CompressionSupport::Unsupported
}
/// Extract the advertised name from propagation-node announce data.
///
/// Reads binary [`PN_META_NAME`] metadata, decodes UTF-8, then sanitizes and
/// bounds the name. Returns `None` if parsing fails or the result is empty.
/// Python `pn_name_from_app_data`: the raw UTF-8 [`PN_META_NAME`] metadata of
/// valid propagation-node announce data, not filtered for display.
pub fn pn_name_from_app_data(data: &[u8]) -> Option<String> {
let parsed = parse_pn_announce_data(data)?;
let name_bytes = parsed.metadata.get(&crate::constants::PN_META_NAME)?;
String::from_utf8(name_bytes.clone())
.ok()
.map(|name| sanitize_name(&name, MAX_ADVERTISED_NAME_CHARS))
.filter(|name| !name.is_empty())
let value = valid_pn_announce(data)?;
let metadata = python_index(&value, 6)?;
let name = python_index(&metadata, usize::from(crate::constants::PN_META_NAME))?;
let rmpv::Value::Binary(bytes) = name else {
return None;
};
String::from_utf8(bytes).ok()
}
/// Outcome of a resource transfer, matching Python `resource_concluded` /
@@ -759,7 +991,7 @@ mod tests {
}
#[test]
fn test_pn_announce_data_rejects_wrapping_policy_values() {
fn test_pn_announce_data_clamps_out_of_range_policy_values() {
use rmpv::Value;
let encode = |transfer_limit: Value, stamp_cost: Value| {
@@ -777,8 +1009,15 @@ mod tests {
packed
};
assert!(parse_pn_announce_data(&encode(Value::from(-1), Value::from(16))).is_none());
assert!(parse_pn_announce_data(&encode(Value::from(10240), Value::from(256))).is_none());
// Python accepts these (int() succeeds); the typed values are clamped.
let negative = parse_pn_announce_data(&encode(Value::from(-1), Value::from(16))).unwrap();
assert_eq!(negative.transfer_limit, 0);
let large = parse_pn_announce_data(&encode(Value::from(10240), Value::from(256))).unwrap();
assert_eq!(large.stamp_cost, 255);
// int(nan) raises in the Python announce handler although validity passes.
let nan = encode(Value::from(10240), Value::F64(f64::NAN));
assert!(pn_announce_data_is_valid(&nan));
assert!(parse_pn_announce_data(&nan).is_none());
}
#[test]
@@ -867,14 +1106,14 @@ mod tests {
}
#[test]
fn test_display_name_from_app_data_sanitizes_untrusted_unicode() {
fn test_display_name_from_app_data_returns_raw_unicode() {
let packed = get_announce_app_data(
Some(" Alice\u{202e}\u{e000}\u{1f680}\nNetwork "),
Some(12),
);
assert_eq!(
display_name_from_app_data(&packed),
Some("AliceNetwork".to_string())
Some("Alice\u{202e}\u{e000}\u{1f680}\nNetwork".to_string())
);
}
+79 -42
View File
@@ -14,6 +14,7 @@ use std::io::Write;
use std::ops::{Deref, DerefMut, Range};
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
pub(crate) mod canonical;
mod draft;
mod field;
mod resumable;
@@ -309,11 +310,9 @@ impl LxMessage {
pub fn verify_signature(&self, key: &rns_crypto::ed25519::Ed25519PublicKey) -> bool {
let mut signed = Vec::with_capacity(self.wire.len() + 32);
signed.extend_from_slice(&self.wire[..32]);
if let Some(body) = first_four_msgpack_array_body(&self.wire[96..]) {
signed.push(0x94);
signed.extend_from_slice(body);
} else {
signed.extend_from_slice(&self.wire[96..]);
match canonical::hashed_payload(&self.wire[96..]) {
Ok(payload) => signed.extend_from_slice(&payload),
Err(_) => return false,
}
signed.extend_from_slice(&self.message_id);
key.verify(&signed, &self.signature()).is_ok()
@@ -354,6 +353,7 @@ impl LxMessage {
if wire.len() < 97 {
return Err(MessageError::TooShort(wire.len()));
}
canonical::validate_leading(&wire[96..])?;
let mut input = &wire[96..];
let count = read_msgpack_array_len(&mut input)?;
if count < 4 {
@@ -400,7 +400,7 @@ impl LxMessage {
};
let destination = wire[..16].try_into().expect("header");
let source = wire[16..32].try_into().expect("header");
let message_id = Self::message_id_from_payload(&destination, &source, &wire[96..]);
let message_id = Self::message_id_from_payload(&destination, &source, &wire[96..])?;
Ok(Self {
wire,
indexes: indexes.into(),
@@ -564,17 +564,12 @@ impl LxMessage {
destination_hash: &[u8; 16],
source_hash: &[u8; 16],
payload: &[u8],
) -> [u8; 32] {
) -> Result<[u8; 32], MessageError> {
let mut hasher = Sha256::new();
hasher.update(destination_hash);
hasher.update(source_hash);
if let Some(body) = first_four_msgpack_array_body(payload) {
hasher.update([0x94]);
hasher.update(body);
} else {
hasher.update(payload);
}
hasher.finalize().into()
hasher.update(canonical::hashed_payload(payload)?);
Ok(hasher.finalize().into())
}
/// Unpack a propagation wrapper `msgpack([timestamp, [lxmf_data, ...]])`, where each entry is
@@ -712,15 +707,18 @@ impl LxMessage {
}
/// Decode an `lxm://` paper URI and return `(destination_hash, encrypted_data)`.
///
/// Follows Python `LXMRouter.ingest_lxm_uri`: the scheme check ignores case,
/// every exact `lxm://` and every `/` is removed, and the rest is decoded with
/// the lenient rules of `base64.urlsafe_b64decode(data + "==")`.
pub fn decode_paper_uri(uri: &str) -> Result<([u8; 16], Vec<u8>), MessageError> {
use base64::Engine;
let data = uri
.strip_prefix("lxm://")
.ok_or_else(|| MessageError::InvalidUri("missing lxm:// prefix".to_string()))?;
let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(data)
.map_err(|e| MessageError::InvalidUri(format!("base64url decode failed: {e}")))?;
if !uri.to_lowercase().starts_with("lxm://") {
return Err(MessageError::InvalidUri(
"missing lxm:// prefix".to_string(),
));
}
let data = uri.replace("lxm://", "").replace('/', "") + "==";
let bytes = python_urlsafe_b64decode(&data)?;
if bytes.len() < LXMF_OVERHEAD {
return Err(MessageError::TooShort(bytes.len()));
@@ -769,11 +767,8 @@ impl LxMessage {
/// Pack the message into a container for file storage.
///
/// Writes a five-element MessagePack array in this order:
/// `[state, lxmf_bytes, transport_encrypted, transport_encryption, method]`.
/// `lxmf_bytes` is binary and `transport_encryption` is a string or nil.
/// Python's `packed_container` writes a named-field map; its file reader
/// does not accept this Rust array layout.
/// Writes the MessagePack map of Python `packed_container`:
/// `{state, lxmf_bytes, transport_encrypted, transport_encryption, method}`.
pub fn pack_container(&self) -> Result<Vec<u8>, MessageError> {
let container = MessageContainerRef {
state: self.state as u8,
@@ -782,7 +777,7 @@ impl LxMessage {
transport_encryption: self.transport_encryption.as_deref(),
method: self.method as u8,
};
rmp_serde::to_vec(&container).map_err(|e| MessageError::PackFailed(e.to_string()))
rmp_serde::to_vec_named(&container).map_err(|e| MessageError::PackFailed(e.to_string()))
}
/// Decode a container array or a map with matching field names, then parse
@@ -931,6 +926,58 @@ fn parse_propagation_wrapper(
Ok((timestamp, entries))
}
/// Python `base64.urlsafe_b64decode` (non-strict `binascii.a2b_base64`):
/// characters outside the alphabet are skipped, and padding only completes a
/// trailing partial quantum.
fn python_urlsafe_b64decode(data: &str) -> Result<Vec<u8>, MessageError> {
// A str argument must encode as ASCII before decoding.
if !data.is_ascii() {
return Err(MessageError::InvalidUri(
"non-ASCII base64 data".to_string(),
));
}
let mut out = Vec::with_capacity(data.len() * 3 / 4);
let (mut quad_pos, mut pads, mut left) = (0u8, 0u8, 0u32);
for byte in data.bytes() {
if byte == b'=' {
if quad_pos >= 2 {
pads = pads.saturating_add(1);
}
continue;
}
let value = match byte {
b'A'..=b'Z' => byte - b'A',
b'a'..=b'z' => byte - b'a' + 26,
b'0'..=b'9' => byte - b'0' + 52,
b'-' | b'+' => 62,
b'_' | b'/' => 63,
_ => continue,
};
pads = 0;
left = (left << 6) | u32::from(value);
quad_pos = (quad_pos + 1) % 4;
match quad_pos {
2 => out.push((left >> 4) as u8),
3 => out.push((left >> 2) as u8),
0 => out.push(left as u8),
_ => {}
}
left &= match quad_pos {
2 => 0x0f,
3 => 0x03,
1 => 0x3f,
_ => 0,
};
}
if quad_pos == 0 || (quad_pos >= 2 && quad_pos + pads >= 4) {
Ok(out)
} else {
Err(MessageError::InvalidUri(
"incorrect base64 padding".to_string(),
))
}
}
fn read_msgpack_array_len(input: &mut &[u8]) -> Result<u32, MessageError> {
let marker = take_msgpack(input, 1)?[0];
match marker {
@@ -1001,20 +1048,10 @@ fn take_msgpack<'a>(input: &mut &'a [u8], length: usize) -> Result<&'a [u8], Mes
Ok(value)
}
fn first_four_msgpack_array_body(payload: &[u8]) -> Option<&[u8]> {
let mut input = payload;
let count = read_msgpack_array_len(&mut input).ok()?;
if count <= 4 {
return None;
}
let body = input;
for _ in 0..4 {
skip_msgpack_value(&mut input, 0).ok()?;
}
Some(&body[..body.len() - input.len()])
}
fn read_msgpack_float(input: &mut &[u8]) -> Result<f64, MessageError> {
if matches!(input.first(), Some(0x00..=0x7f | 0xcc..=0xd3 | 0xe0..=0xff)) {
return Ok(read_msgpack_integer(input)? as f64);
}
match take_msgpack(input, 1)?[0] {
0xca => Ok(f64::from(f32::from_bits(u32::from_be_bytes(
take_msgpack(input, 4)?.try_into().expect("exact length"),
@@ -1023,7 +1060,7 @@ fn read_msgpack_float(input: &mut &[u8]) -> Result<f64, MessageError> {
take_msgpack(input, 8)?.try_into().expect("exact length"),
))),
_ => Err(MessageError::UnpackFailed(
"timestamp is not float".to_string(),
"timestamp is not a number".to_string(),
)),
}
}
+509
View File
@@ -0,0 +1,509 @@
//! MessagePack decoding with the acceptance rules of the umsgpack decoder used
//! by Python LXMF, and its canonical re-encoding (`umsgpack.packb(unpackb(x))`).
use super::MessageError;
use std::borrow::Cow;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
const MAX_DEPTH: usize = 64;
// datetime.min / datetime.max relative to the Unix epoch, in microseconds.
const MIN_TIMESTAMP_MICROS: i128 = -62_135_596_800 * 1_000_000;
const MAX_TIMESTAMP_MICROS: i128 = 253_402_300_799 * 1_000_000 + 999_999;
/// Python value identity of a decoded map key.
#[derive(Debug)]
enum Key {
Nil,
Number(i128),
Float(u64),
NaN,
Str(Vec<u8>),
Bin(Vec<u8>),
Ext(i8, Vec<u8>),
Time(i128),
Tuple(Vec<Key>),
Unhashable,
}
impl Key {
fn same(&self, other: &Key) -> bool {
match (self, other) {
(Key::Nil, Key::Nil) => true,
(Key::Number(a), Key::Number(b)) => a == b,
(Key::Float(a), Key::Float(b)) => a == b,
(Key::Str(a), Key::Str(b)) | (Key::Bin(a), Key::Bin(b)) => a == b,
(Key::Ext(t, a), Key::Ext(u, b)) => t == u && a == b,
(Key::Time(a), Key::Time(b)) => a == b,
(Key::Tuple(a), Key::Tuple(b)) => {
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| x.same(y))
}
_ => false,
}
}
fn hashable(&self) -> bool {
match self {
Key::Unhashable => false,
Key::Tuple(items) => items.iter().all(Key::hashable),
_ => true,
}
}
fn contains_nan(&self) -> bool {
match self {
Key::NaN => true,
Key::Tuple(items) => items.iter().any(Key::contains_nan),
_ => false,
}
}
fn from_float(value: f64) -> Key {
if value.is_nan() {
Key::NaN
} else if value.fract() == 0.0 && value.abs() < 1.0e38 {
Key::Number(value as i128)
} else {
Key::Float(value.to_bits())
}
}
}
// Equality is reflexive for every key that reaches the index (NaN keys never do).
impl PartialEq for Key {
fn eq(&self, other: &Key) -> bool {
self.same(other)
}
}
impl Eq for Key {}
impl Hash for Key {
fn hash<H: Hasher>(&self, state: &mut H) {
match self {
Key::Nil => 0u8.hash(state),
Key::Number(n) => (1u8, n).hash(state),
Key::Float(bits) => (2u8, bits).hash(state),
Key::NaN => 3u8.hash(state),
Key::Str(v) => (4u8, v).hash(state),
Key::Bin(v) => (5u8, v).hash(state),
Key::Ext(t, v) => (6u8, t, v).hash(state),
Key::Time(t) => (7u8, t).hash(state),
Key::Tuple(items) => {
8u8.hash(state);
items.len().hash(state);
for item in items {
item.hash(state);
}
}
Key::Unhashable => 9u8.hash(state),
}
}
}
fn fail(reason: &str) -> MessageError {
MessageError::UnpackFailed(reason.to_string())
}
fn take<'a>(input: &mut &'a [u8], length: usize) -> Result<&'a [u8], MessageError> {
if input.len() < length {
return Err(fail("truncated MessagePack value"));
}
let (value, rest) = input.split_at(length);
*input = rest;
Ok(value)
}
fn be(input: &mut &[u8], width: usize) -> Result<u64, MessageError> {
Ok(take(input, width)?
.iter()
.fold(0u64, |acc, byte| (acc << 8) | u64::from(*byte)))
}
fn emit(out: &mut Option<&mut Vec<u8>>, bytes: &[u8]) {
if let Some(out) = out.as_deref_mut() {
out.extend_from_slice(bytes);
}
}
fn write_int(out: &mut Vec<u8>, value: i128) {
if value < 0 {
if value >= -32 {
out.push(value as i8 as u8);
} else if value >= i128::from(i8::MIN) {
out.push(0xd0);
out.push(value as i8 as u8);
} else if value >= i128::from(i16::MIN) {
out.push(0xd1);
out.extend_from_slice(&(value as i16).to_be_bytes());
} else if value >= i128::from(i32::MIN) {
out.push(0xd2);
out.extend_from_slice(&(value as i32).to_be_bytes());
} else {
out.push(0xd3);
out.extend_from_slice(&(value as i64).to_be_bytes());
}
} else if value < 128 {
out.push(value as u8);
} else if value <= i128::from(u8::MAX) {
out.push(0xcc);
out.push(value as u8);
} else if value <= i128::from(u16::MAX) {
out.push(0xcd);
out.extend_from_slice(&(value as u16).to_be_bytes());
} else if value <= i128::from(u32::MAX) {
out.push(0xce);
out.extend_from_slice(&(value as u32).to_be_bytes());
} else {
out.push(0xcf);
out.extend_from_slice(&(value as u64).to_be_bytes());
}
}
fn write_sized(out: &mut Vec<u8>, length: usize, fix: Option<(u8, usize)>, wide: [u8; 3]) {
match fix {
Some((base, limit)) if length < limit => out.push(base | length as u8),
_ if length <= usize::from(u8::MAX) && wide[0] != 0 => {
out.push(wide[0]);
out.push(length as u8);
}
_ if length <= usize::from(u16::MAX) => {
out.push(wide[1]);
out.extend_from_slice(&(length as u16).to_be_bytes());
}
_ => {
out.push(wide[2]);
out.extend_from_slice(&(length as u32).to_be_bytes());
}
}
}
fn write_ext(out: &mut Vec<u8>, ext_type: i8, data: &[u8]) {
match data.len() {
1 => out.push(0xd4),
2 => out.push(0xd5),
4 => out.push(0xd6),
8 => out.push(0xd7),
16 => out.push(0xd8),
length => write_sized(out, length, None, [0xc7, 0xc8, 0xc9]),
}
out.push(ext_type as u8);
out.extend_from_slice(data);
}
fn timestamp_micros(data: &[u8]) -> Result<i128, MessageError> {
let (seconds, micros) = match data.len() {
4 => (
i128::from(u32::from_be_bytes(data.try_into().expect("length"))),
0,
),
8 => {
let value = u64::from_be_bytes(data.try_into().expect("length"));
(
i128::from(value & 0x3_ffff_ffff),
i128::from(value >> 34) / 1000,
)
}
12 => (
i128::from(i64::from_be_bytes(data[4..12].try_into().expect("length"))),
i128::from(u32::from_be_bytes(data[0..4].try_into().expect("length"))) / 1000,
),
_ => return Err(fail("unsupported MessagePack timestamp")),
};
let total = seconds * 1_000_000 + micros;
if !(MIN_TIMESTAMP_MICROS..=MAX_TIMESTAMP_MICROS).contains(&total) {
return Err(fail("MessagePack timestamp out of range"));
}
Ok(total)
}
fn write_timestamp(out: &mut Vec<u8>, total: i128) {
let seconds = total.div_euclid(1_000_000);
let micros = total.rem_euclid(1_000_000);
if micros == 0 && (0..=i128::from(u32::MAX)).contains(&seconds) {
out.extend_from_slice(&[0xd6, 0xff]);
out.extend_from_slice(&(seconds as u32).to_be_bytes());
} else if (0..(1i128 << 34)).contains(&seconds) {
let value = ((micros as u64 * 1000) << 34) | seconds as u64;
out.extend_from_slice(&[0xd7, 0xff]);
out.extend_from_slice(&value.to_be_bytes());
} else {
out.extend_from_slice(&[0xc7, 0x0c, 0xff]);
out.extend_from_slice(&((micros * 1000) as u32).to_be_bytes());
out.extend_from_slice(&(seconds as i64).to_be_bytes());
}
}
/// Decode one value, writing its canonical encoding to `out` when present.
/// Returns the value's key identity when `want_key` is set.
fn walk(
input: &mut &[u8],
mut out: Option<&mut Vec<u8>>,
want_key: bool,
depth: usize,
) -> Result<Option<Key>, MessageError> {
if depth >= MAX_DEPTH {
return Err(fail("MessagePack nesting exceeds limit"));
}
let marker = take(input, 1)?[0];
let number = |value: i128, out: Option<&mut Vec<u8>>| {
if let Some(out) = out {
write_int(out, value);
}
Ok(want_key.then_some(Key::Number(value)))
};
match marker {
0x00..=0x7f => number(i128::from(marker), out),
0xe0..=0xff => number(i128::from(marker as i8), out),
0xcc => number(i128::from(be(input, 1)?), out),
0xcd => number(i128::from(be(input, 2)?), out),
0xce => number(i128::from(be(input, 4)?), out),
0xcf => number(i128::from(be(input, 8)?), out),
0xd0 => number(i128::from(be(input, 1)? as u8 as i8), out),
0xd1 => number(i128::from(be(input, 2)? as u16 as i16), out),
0xd2 => number(i128::from(be(input, 4)? as u32 as i32), out),
0xd3 => number(i128::from(be(input, 8)? as i64), out),
0xc0 => {
emit(&mut out, &[0xc0]);
Ok(want_key.then_some(Key::Nil))
}
0xc1 => Err(fail("reserved MessagePack marker")),
0xc2 | 0xc3 => {
emit(&mut out, &[marker]);
Ok(want_key.then_some(Key::Number(i128::from(marker == 0xc3))))
}
0xca | 0xcb => {
let value = if marker == 0xca {
f64::from(f32::from_bits(be(input, 4)? as u32))
} else {
f64::from_bits(be(input, 8)?)
};
if let Some(out) = out {
out.push(0xcb);
out.extend_from_slice(&value.to_bits().to_be_bytes());
}
Ok(want_key.then(|| Key::from_float(value)))
}
0xa0..=0xbf | 0xd9..=0xdb => {
let length = match marker {
0xd9 => be(input, 1)?,
0xda => be(input, 2)?,
0xdb => be(input, 4)?,
_ => u64::from(marker & 0x1f),
} as usize;
let data = take(input, length)?;
if std::str::from_utf8(data).is_err() {
return Err(fail("MessagePack string is invalid UTF-8"));
}
if let Some(out) = out {
write_sized(out, length, Some((0xa0, 32)), [0xd9, 0xda, 0xdb]);
out.extend_from_slice(data);
}
Ok(want_key.then(|| Key::Str(data.to_vec())))
}
0xc4..=0xc6 => {
let length = be(input, 1 << (marker - 0xc4))? as usize;
let data = take(input, length)?;
if let Some(out) = out {
write_sized(out, length, None, [0xc4, 0xc5, 0xc6]);
out.extend_from_slice(data);
}
Ok(want_key.then(|| Key::Bin(data.to_vec())))
}
0xc7..=0xc9 | 0xd4..=0xd8 => {
let length = match marker {
0xc7 => be(input, 1)? as usize,
0xc8 => be(input, 2)? as usize,
0xc9 => be(input, 4)? as usize,
_ => 1 << (marker - 0xd4),
};
let ext_type = take(input, 1)?[0] as i8;
let data = take(input, length)?;
if ext_type == -1 {
let total = timestamp_micros(data)?;
if let Some(out) = out {
write_timestamp(out, total);
}
return Ok(want_key.then_some(Key::Time(total)));
}
if let Some(out) = out {
write_ext(out, ext_type, data);
}
Ok(want_key.then(|| Key::Ext(ext_type, data.to_vec())))
}
0x90..=0x9f | 0xdc | 0xdd => {
let count = match marker {
0xdc => be(input, 2)?,
0xdd => be(input, 4)?,
_ => u64::from(marker & 0x0f),
};
if let Some(out) = out.as_deref_mut() {
write_sized(out, count as usize, Some((0x90, 16)), [0, 0xdc, 0xdd]);
}
let mut items = Vec::new();
for _ in 0..count {
let item = walk(input, out.as_deref_mut(), want_key, depth + 1)?;
if let Some(item) = item {
items.push(item);
}
}
Ok(want_key.then_some(Key::Tuple(items)))
}
0x80..=0x8f | 0xde | 0xdf => {
let count = match marker {
0xde => be(input, 2)?,
0xdf => be(input, 4)?,
_ => u64::from(marker & 0x0f),
};
walk_map(input, out, count, depth)?;
Ok(want_key.then_some(Key::Unhashable))
}
}
}
struct Entry {
encoded_key: Vec<u8>,
encoded_value: Vec<u8>,
}
fn walk_map(
input: &mut &[u8],
out: Option<&mut Vec<u8>>,
count: u64,
depth: usize,
) -> Result<(), MessageError> {
let writing = out.is_some();
let mut entries: Vec<Entry> = Vec::new();
let mut index: HashMap<Key, usize> = HashMap::new();
for _ in 0..count {
let is_list = matches!(input.first(), Some(0x90..=0x9f | 0xdc | 0xdd));
let mut encoded_key = Vec::new();
let key = walk(input, writing.then_some(&mut encoded_key), true, depth + 1)?
.expect("key requested");
// Lists become tuples and bypass the duplicate check; later ones overwrite.
if !is_list {
if !key.hashable() {
return Err(fail("unhashable MessagePack map key"));
}
if index.contains_key(&key) {
return Err(fail("duplicate MessagePack map key"));
}
}
let mut encoded_value = Vec::new();
walk(
input,
writing.then_some(&mut encoded_value),
false,
depth + 1,
)?;
if !key.hashable() {
return Err(fail("unhashable MessagePack map key"));
}
let existing = if key.contains_nan() {
None
} else {
index.get(&key).copied()
};
match existing {
Some(position) => entries[position].encoded_value = encoded_value,
None => {
if !key.contains_nan() {
index.insert(key, entries.len());
}
entries.push(Entry {
encoded_key,
encoded_value,
});
}
}
}
if let Some(out) = out {
write_sized(out, entries.len(), Some((0x80, 16)), [0, 0xde, 0xdf]);
for entry in entries {
out.extend_from_slice(&entry.encoded_key);
out.extend_from_slice(&entry.encoded_value);
}
}
Ok(())
}
/// Check that the leading value decodes under the umsgpack rules; trailing bytes are ignored.
pub(crate) fn validate_leading(bytes: &[u8]) -> Result<(), MessageError> {
let mut input = bytes;
walk(&mut input, None, false, 0).map(|_| ())
}
/// Canonical re-encoding of exactly one value.
pub(crate) fn canonicalize(bytes: &[u8]) -> Result<Vec<u8>, MessageError> {
let mut input = bytes;
let mut out = Vec::with_capacity(bytes.len());
walk(&mut input, Some(&mut out), false, 0)?;
if !input.is_empty() {
return Err(fail("trailing MessagePack bytes"));
}
Ok(out)
}
/// The payload bytes Python hashes: the received bytes, or the canonical
/// re-encoding of the first four elements when a stamp is present.
pub(crate) fn hashed_payload(payload: &[u8]) -> Result<Cow<'_, [u8]>, MessageError> {
let mut input = payload;
let count = match take(&mut input, 1)?[0] {
marker @ 0x90..=0x9f => u64::from(marker & 0x0f),
0xdc => be(&mut input, 2)?,
0xdd => be(&mut input, 4)?,
_ => return Err(fail("expected MessagePack array")),
};
if count <= 4 {
return Ok(Cow::Borrowed(payload));
}
let mut out = vec![0x94];
for _ in 0..4 {
walk(&mut input, Some(&mut out), false, 1)?;
}
Ok(Cow::Owned(out))
}
#[cfg(test)]
mod tests {
use super::*;
fn canon(hex_in: &str) -> Result<String, MessageError> {
canonicalize(&hex::decode(hex_in).unwrap()).map(hex::encode)
}
#[test]
fn reencodes_minimally_and_widens_floats() {
assert_eq!(canon("91ca3fc00000").unwrap(), "91cb3ff8000000000000");
assert_eq!(canon("cd0005").unwrap(), "05");
assert_eq!(canon("d9026869").unwrap(), "a26869");
assert_eq!(canon("de00010102").unwrap(), "810102");
assert_eq!(canon("c50001aa").unwrap(), "c401aa");
assert_eq!(canon("c701050a").unwrap(), "d4050a");
assert_eq!(canon("d0ff").unwrap(), "ff");
}
#[test]
fn rejects_duplicates_by_python_equality() {
assert!(canon("820101 0102".replace(' ', "").as_str()).is_err());
assert!(canon("8201 01cb3ff0000000000000 02".replace(' ', "").as_str()).is_err());
assert!(canon("82c301 0102".replace(' ', "").as_str()).is_err());
assert!(canon("82a1610 1c4016102".replace(' ', "").as_str()).is_ok());
assert!(
canon(
"82cb7ff8000000000000 01cb7ff8000000000000 02"
.replace(' ', "")
.as_str()
)
.is_ok()
);
}
#[test]
fn list_keys_overwrite_instead_of_failing() {
assert_eq!(canon("82910101910102").unwrap(), "81910102");
assert!(canon("81918001 01".replace(' ', "").as_str()).is_err());
assert!(canon("818001 01".replace(' ', "").as_str()).is_err());
}
#[test]
fn rejects_invalid_text_and_reserved_marker() {
assert!(canon("a1ff").is_err());
assert!(canon("c1").is_err());
assert!(canon("c7").is_err());
}
}
+7 -1
View File
@@ -188,7 +188,7 @@ impl LxMessageDraft {
) -> Result<(), MessageError> {
self.set_field_value(
id,
FieldValue::MessagePack(EncodedFieldValue::new(bytes.into())?),
FieldValue::MessagePack(EncodedFieldValue::canonical(bytes.into())?),
)
}
pub fn set_field_value(
@@ -197,6 +197,12 @@ impl LxMessageDraft {
value: FieldValue,
) -> Result<(), MessageError> {
let id = id.into();
let value = match value {
FieldValue::MessagePack(v) => FieldValue::MessagePack(EncodedFieldValue::canonical(
Bytes::copy_from_slice(v.encoded()),
)?),
binary => binary,
};
if !self.fields.contains_key(&id) && self.fields.len() >= self.limits.max_top_level_fields {
return Err(MessageError::TooManyFields);
}
+11 -3
View File
@@ -72,6 +72,15 @@ impl EncodedFieldValue {
}
Ok(Self(bytes))
}
/// The value as Python LXMF decodes and re-encodes it; fails where
/// Python's decoder fails (duplicate or unhashable map keys, invalid UTF-8).
pub fn canonical(bytes: Bytes) -> Result<Self, MessageError> {
let canonical = super::canonical::canonicalize(&bytes)?;
if canonical == bytes.as_ref() {
return Ok(Self(bytes));
}
Ok(Self(canonical.into()))
}
pub fn encoded(&self) -> &[u8] {
&self.0
}
@@ -102,7 +111,7 @@ impl<'de> Deserialize<'de> for FieldValue {
}
let mut bytes = Vec::new();
rmpv::encode::write_value(&mut bytes, &value).map_err(serde::de::Error::custom)?;
EncodedFieldValue::new(bytes.into())
EncodedFieldValue::canonical(bytes.into())
.map(Self::MessagePack)
.map_err(serde::de::Error::custom)
}
@@ -115,8 +124,7 @@ pub struct FieldValueRef<'a> {
}
impl<'a> FieldValueRef<'a> {
/// Borrow exactly one structurally valid value without decoding or copying it.
/// Duplicate map keys remain opaque until a recognized schema asks for
/// `unique_map`; binary payloads are never interpreted implicitly.
/// Binary payloads are never interpreted implicitly.
pub fn from_encoded(encoded: &'a [u8]) -> Result<Self, MessageError> {
let mut remaining = encoded;
skip_msgpack_value(&mut remaining, 0)?;
@@ -0,0 +1,16 @@
# Expected outputs of upstream's decode step in LXMRouter.ingest_lxm_uri@1.3.0:
# base64.urlsafe_b64decode(uri.replace("lxm://","").replace("/","")+"==")
import base64, json, random, sys
import RNS, LXMF
assert RNS.__version__ == "1.6.0" and LXMF.__version__ == "1.3.0"
random.seed(1517)
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_+/= .:!\n"
cases = ["", "QUJD", "QUI", "QU", "Q", "QUJD=QUJD", "QU=JD", "=QUJD", "QUJD==", "Q+-_", "QU JD", "QUJD====", "Q=U=J=D"]
for _ in range(400):
cases.append("".join(random.choice(alpha) for _ in range(random.randint(0, 14))))
# One line per case: hex(input) TAB hex(decoded) or "error".
with open(sys.argv[1], "w") as f:
for c in cases:
try: r = base64.urlsafe_b64decode(c + "==").hex()
except Exception: r = "error"
f.write(c.encode().hex() + "\t" + r + "\n")
@@ -0,0 +1,413 @@
51554a44 414243
515549 4142
5155 41
51 error
51554a443d51554a44 414243414243
51553d4a44 414243
3d51554a44 414243
51554a443d3d 414243
512b2d5f 43efbf
5155204a44 414243
51554a443d3d3d3d 414243
513d553d4a3d44 414243
2d436e590a45 error
517662595f4249632d3145495a44 42f6d8fc121cfb510864
42694d472b6c463a 062306fa51
6c48416a316f36763872656d7430 947023d68eaff2b7a6b7
2d error
7620506247426135733d58597764 bcf6c605ae6c5d8c1d
30426974344a68763574203d41 d018ade0986fe6d0
5931455f324b5f2038736a3d 63513fd8affcb2
78653053 c5ed12
78456466743a68 c4475fb6
576e4f482d635f52616873443d77 error
34704f77746d4873316b2e3939 e293b0b661ecd64f7d
3657393d213a e96f
3d4469366e7142622167616230 0e2ea7a816e069bd
79737352 cacb11
734673 b05b
356f43 e680
736665 b1f7
5a2f367241616e31662e0a4c7a54 67feab01a9f57cbcd3
53484b 4872
63 error
424b 04
75685f48695155354f36704431 error
713468526c6c ab885196
2e6d3d49593452547358376f6867 988638453b17ee8860
2f2047312b2f78613355 error
4c42 2c
392e41426a450a333a f4006313
655374574a5776745f error
205635452b356a2f44 57913ee63fc3
4d536b664c2b6753 31291f2fe812
71554c5a765a7449 a942d9bd9b48
31586946722e4c46725968395f d57885acb16b621f7f
4e6d6b662135 error
4244 04
31536f43796f d52a02ca
735065433754 b0f782ed
2e615f33326635696d3162 6bfdf67f98a6d5
2f5f49362e586c664e546a42 fff23a5e57cd4e30
7441454c61426144 b4010b681683
3d484f6b 1ce9
50724f2f51536c39585962214651 error
683669545a316a59 87a8936758d8
62 error
4159512e4a5a64 01840965
6f3821595a794f6b792b33394731 error
6c2e4777763a 946c2f
69383a77476c544a3d43512f20 8bcc0695324243
4169 02
485a6557626441692177325a 1d97966dd022c366
4e35697578642d526465634a78 error
3146752f393965 d45bbff7d7
394321356378 error
57575632 596576
72592d4b4a303470673a38 ad8f8a274e2983
4b6775457758776751525a754e error
58437a50623643316438 5c2ccf6fa0b577
64380a20320a3859644e6a 77cdbc61d363
0a7777706b2d error
384c65426a7334692f555345 f0b7818ece22fd4484
3a65 error
6e3a7035727863712b4d6874666d error
78784f32627455386c error
6f error
7076794b55513a494471 error
2e0a476d344f4b3a630a4a7239 error
6a error
653163627068680a2f435474 7b571ba6187f093b
52787467454c77553a 471b6010bc14
6f694130737a4d3164 error
426a4c6f45635f79 0632e811cff2
514a4b63336b 40929cde
2b6e fa
7321506547217030746a b0f786a74b63
796564494d47504334316567 c9e7483063c2e357a0
76 error
20786374453379674a473048 c5cb44df28091b41
35714c7743 error
59794620756947 63216e88
784f2162 c4e6
213d4545 10
327a5453310a4b db34d2d4
50534b395071424f6a56213659 3d22bd3ea04e8d5e98
48375f6e666c304c34672b452d34 1fbfe77e5d0be20f84fb
45666c7471685a2f7375 11f96daa167fb2
76 error
73 error
7331714c34577a2d b35a8be16cfe
5353425a6c6453 49205995d4
2e4764663a3a35 19d7f9
4a2f51762d37334a3521 error
2d49 f8
4c4b6575 2ca7ae
743848485277 b7c1c747
6d69546d6f38312e6d7a error
6675617876364769577471 7ee6b1bfa1a25ada
205f427775575f5f6b627054683d fc1c2e5bffe46e94e1
38652e706137715437777a f1ea5aeea4fbc3
48562d6a20714445 1d5fa3a831
6947 88
4462526121 0db45a
56464c39586475396d error
2b757953683638722148213858 faec9287af2b1fc5
7a64356b4a306e cdde642749
3d6d7a 9b
32205632634a31746f70 error
6e37684a52 error
5a0a6b 66
56722f582e2030485f48536775 56bfd7d07fc74a0b
6d64363368516b75 99deb785092e
7a error
786d5f4351 error
6133 6b
4156 01
3534796a215263484f2f410a7658 e78ca345c1cefc0bd7
677945667865526c36632f386c2d 83211fc5e465e9cffc97
383051775a3a764e6d67500a4475 f3443066f36680f0ee
676c5277564269725851 8254705418ab5d
473d68376f54 error
3a382d4431576f6d3d684f error
415021 00
21532e3331460a 4b7d45
782e642e63513754514c4a4563 c5d710ed340b2447
385a6e21307821 error
7864686958 error
62374457 6fb0d6
704666694835 a457e21f
2152576f322b error
566d306b473d69576b3d51554e 566d241a25a44143
6258304634336a654a2d516774 error
52 error
736346346b6343493961 b1c17891c088f5
3a4143202b46333d43 002f85dc
346876654c41684d63756a6e7550 e21bde2c084c72e8e7b8
3a206a582b2e4f356b6d 8d7f8ee649
5336652b5051574354466367 4ba7be3d05824c5720
74626d2e733d513058 b5b9ac4345
55422173784f456b206231583448 501b3138491bd57e07
5a4b314252364d620a216e2e6659 64ad4147a31b9df6
58646b3a464953366c 5dd905212ea5
7566656c302b32 b9f7a5d3ed
774b c0
59304471 6340ea
5a error
5357357472736c205a2e6b54 496e6daec95991
470a error
7271 ae
2033795268393668 df2461f7a8
733453640a74696b2b7a3d723161 b3849db6293ecebd5a
5739 5b
6c2e713359544f6775 96add84ce82e
533843612d error
53742f2b6872516161657055 4adffe86b41a69ea54
5a48312b4e6c426f206e696652 647d7e3650689e27d1
3a4a error
34447950 e03c8f
772b535a76486f4350743a3141 c3e499bc7a023edd40
52 error
77414f c003
794d53787a426750687552434b64 c8c4b1cc180f86e44229
4d6b2f37496b 324ffb22
2b3131793132203334 fb5d72d76df8
75214852683a2f470a5463 b87461fc64dc
6735526b 839464
6e error
484d2f5f2f0a3168387438303d2e 1ccfffff587cb7cd
6771537969742f3964303756542e error
46745a5f75563a65 16d67fb957
50 error
313549 d792
6e4b79364955664a 9cacba2147c9
572f31785521 error
33513031537a55354856707773 error
4334452b5663662d4e5a4a5a 0b813e55c7fe359259
36727a eabc
696c4d526b4a4433792d533d59 8a53119090f7cbe498
7653416e56 error
0a7978692b cb18be
6f796e35473149315635 a329f91b523557
4435532d3a6c5f5255725042 0f94be97f454acf0
5f39 ff
6f747331674d674c3932 a2db3580c80bf7
5f66562b74393672483064 fdf57eb7deab1f47
30363d6950 d3a88f
35505934446643650a e4f6380df09e
4b6d372f34546358 2a6effe13717
2f3277 ff6c
217021454c544b5276723a50 error
69357a6664774b4d 8b9cdf77028c
5a58 65
53663671616f2149 49feaa6a82
4c205175300a6c77346b7665 2d0bb4970e24bd
735137543a59552164376c7556 b10ed361477b96e5
703744 a7b0
614579595547785a63764c 684c98506c5972f2
3a51365369795f4f714f3869 43a4a2cbf3aa3bc8
5855 5d
50514f2b5a58 3d03be65
623242 6f60
46316947526d414a4a47355a65 error
3877444c56576b440a4a error
4f4f456f 38e128
4c586e734746425a5521 error
535959 4986
2b764e0a5249660a58 faf35121f5
3630543936 error
6672473d55 7eb194
41686a5372213879682d79384f63 error
5667422d667131750a44 error
705744534d702b a560d2329f
687577 86ec
2164386f2e696b584f725348 77ca229173ab48
65326e75756b2f6b7849 7b69eeba4fe4c4
6c657374 95eb2d
3a744f b4
375267 ed18
6f4c214668 a0b161
795278456b2d5f69 c91c4493efe2
3d372e error
6a397434516530673239 8fdb7841ed20db
38206b44372034576a46 f240fbe168c5
3554393a55433231412d3770 e53f540b6d40fbba
3a6b46 90
6c63 95
4e48496758366d715a53597659 error
21566556 55e5
495442684a3d747a 21306126dc
0a2b693d6e50482f78324b754644 fa29cf1ffc762ae143
734d3d62414a2b4534723a7949 b0c6c027e138af22
6b66534c655759445220535f 91f48b796603452f
4d6a4659795277424943 323158c91c0120
46433a662e4943 error
2d614e713864 f9a36af1
7a4277713777454c4f4a cc1c2aef010b38
4730 1b
66744a412d517347446c3462 7ed240f90b060e5e1b
77 error
6621 error
6f643a4e4f7366 a1d34eb1
50374b73756e495537374a347631 3fb2acba7214efb278bf
32720a da
534137334d642f4e44516f61 480ef731dfcd0d0a1a
636664734a0a4a38656b4f2b354a error
4449706d 0c8a66
705a2b345248204671517a322b63 error
6e305220427a787a 9f4441cf1c
6170363a587774334b34783074 6a9e97c2ddcae31d2d
4376317a34 error
79 error
2d640a49593669596b f9d218ea2624
6968446b0a344447595841317766 error
754221467743552e2b b81170094f
65434d37 78233b
6379354a2b696b41455f453337 error
2e363a740a346432 error
4a error
445075 0cfb
6b694247 922046
4b656b397370520a31456f6651 29e93db294751287d0
6e7165375461645750564c3274 error
5f77437a2b78542145312e6f57 ff00b3fb14c4d685
43652b7121 09efaa
436e3569547056 0a7e624e95
342b2f736e70646f0a765744554b error
692b6b306b743731 8be93492def5
50647478715f68322166 error
333953375258 dfd4bb45
70576474342b3730590a error
37 error
35 error
312078336f2f4d5144657978 d71de8fcc4037b2c
5a484c504d366a384b346c483a 6472cf33a8fc2b8947
2d563d2d616c352f6977 error
5f4375434579 fc2b8213
75753951644176 baef50740b
7430 b7
33476857 dc6856
2d6b706355633443634f fa4a5c51ce0270
544237215f703d516776745253 4c1effa5082fb514
51764e6b46 error
6236624c 6fa6cb
7678 bf
4a2b4f5554 error
4a6d 26
4a66394f304668763a79304f3658 error
313645 d7a1
66707944706942 7e9c83a620
3452532f532f3454 e114bf4bfe13
754d627951382b50 b8c6f243cf8f
4e7650424c52 36f3c12d
742d5f214453675544 b7efc34a0503
50547932625572 3d3cb66d4a
71586e34 a979f8
49456b514f36214a2f465a577547 error
722f af
5248 44
324a3079596b d89d3262
314f6d79666a487973622171 d4e9b27e31f2b1ba
2b375332445f77 fbb4b60ffc
385f30 f3fd
2177574e7266652b622b error
6c2f682d316a2e776f79 error
2e6f4837746b error
3059 d1
5a7739343561626b4f3330 670f78e5a6e43b7d
536e4479 4a70f2
716249 a9b2
2b46345a4a34 f85e1927
33384f57 dfc396
5a58636430 error
496e20765f484876644c5847 227bff1c7bdd2d71
732f747147547a2e b3fb6a193c
307173585320662f436c6945 d2ab1749ffc29621
57656745376f72 59e804ee8a
554f526843335954 50e4610b7613
6e38 9f
6c5a79506c644a6473426e52 959c8f95d25db019d1
2e
4f5973466f78744c337648 398b05a31b4bdef1
77683537524b7355216d354c c21e7b44ab149b92
4d552e4f3637774d6138 error
5275507154573053323d4566 46e3ea4d6d12d847
4850 1c
4d6f33 328d
3a36713a4f662d3162 eaa39ffb56
576d303949634155 5a6d3d21c014
6c4937493d 948ec8
7720394c5a62 error
6b72574455797a622d error
7139574854365343 abd5874fa482
2f304b7055 error
0a6c422d2b36773a7057212b7271 941fbeeb0a56faba
6777343769 error
506b756b6a error
6c7877466b455869552f63552b35 971c059045e253f714fb
55677457692b435a5a54 520b568be09965
30 error
364e72206a32552031 e8dae3d94d
3449203463542e724d750a6d73 e08e1c4eb32e9a
4f21736c6d464544354978 3ac9661440f923
2f397464695230 ffdb5d891d
5f3a error
46 error
5159794c535f5774342f 418c8b4bf5ade3
2b416e7a3957763d463731 f809f3f56bc5ef
76484b585562 bc729751
57 error
617741655a3861396b670a42 6b001e67c6bd9200
3047475f5533656531456e56 d061bf53779ed449d5
4c745a 2ed6
39 error
457579626f7a6a4d 12ec9ba338cc
4b2d5f 2bef
55537a676f68614a4a692d21 512ce0a21689262f
493d3979380a72686e 23dcbcae19
584779596d2d4b484b57693036 error
416668575334 01f8564b
2e6a756e2147 8ee9c6
6b47424d212d594b7a67697a 90604cf982b3822c
397771554b6163 f70a9429a7
4836213a 1f
44474d575a error
7653780a44592f79 bd2c4363fc
50786c6834422d3a6d56503442 3f1961e01fa654fe01
56214b782b686c4951797a2d 54ac7e865210cb3f
53336130596d704c43 error
30 error
2b error
7774 c2
515651762e693a7a2074 41542f8b3b
7049673a7a71724d36756c4f a48833aab33aba53
1
2 51554a44 414243
3 515549 4142
4 5155 41
5 51 error
6 51554a443d51554a44 414243414243
7 51553d4a44 414243
8 3d51554a44 414243
9 51554a443d3d 414243
10 512b2d5f 43efbf
11 5155204a44 414243
12 51554a443d3d3d3d 414243
13 513d553d4a3d44 414243
14 2d436e590a45 error
15 517662595f4249632d3145495a44 42f6d8fc121cfb510864
16 42694d472b6c463a 062306fa51
17 6c48416a316f36763872656d7430 947023d68eaff2b7a6b7
18 2d error
19 7620506247426135733d58597764 bcf6c605ae6c5d8c1d
20
21 30426974344a68763574203d41 d018ade0986fe6d0
22 5931455f324b5f2038736a3d 63513fd8affcb2
23 78653053 c5ed12
24 78456466743a68 c4475fb6
25 576e4f482d635f52616873443d77 error
26 34704f77746d4873316b2e3939 e293b0b661ecd64f7d
27 3657393d213a e96f
28 3d4469366e7142622167616230 0e2ea7a816e069bd
29 79737352 cacb11
30 734673 b05b
31 356f43 e680
32 736665 b1f7
33 5a2f367241616e31662e0a4c7a54 67feab01a9f57cbcd3
34 53484b 4872
35
36 63 error
37 424b 04
38 75685f48695155354f36704431 error
39 713468526c6c ab885196
40 2e6d3d49593452547358376f6867 988638453b17ee8860
41 2f2047312b2f78613355 error
42 4c42 2c
43 392e41426a450a333a f4006313
44
45 655374574a5776745f error
46 205635452b356a2f44 57913ee63fc3
47 4d536b664c2b6753 31291f2fe812
48 71554c5a765a7449 a942d9bd9b48
49 31586946722e4c46725968395f d57885acb16b621f7f
50 4e6d6b662135 error
51 4244 04
52
53 31536f43796f d52a02ca
54 735065433754 b0f782ed
55 2e615f33326635696d3162 6bfdf67f98a6d5
56 2f5f49362e586c664e546a42 fff23a5e57cd4e30
57 7441454c61426144 b4010b681683
58
59 3d484f6b 1ce9
60
61 50724f2f51536c39585962214651 error
62 683669545a316a59 87a8936758d8
63 62 error
64 4159512e4a5a64 01840965
65 6f3821595a794f6b792b33394731 error
66 6c2e4777763a 946c2f
67 69383a77476c544a3d43512f20 8bcc0695324243
68 4169 02
69 485a6557626441692177325a 1d97966dd022c366
70 4e35697578642d526465634a78 error
71 3146752f393965 d45bbff7d7
72 394321356378 error
73 57575632 596576
74 72592d4b4a303470673a38 ad8f8a274e2983
75 4b6775457758776751525a754e error
76 58437a50623643316438 5c2ccf6fa0b577
77 64380a20320a3859644e6a 77cdbc61d363
78 0a7777706b2d error
79 384c65426a7334692f555345 f0b7818ece22fd4484
80
81 3a65 error
82 6e3a7035727863712b4d6874666d error
83 78784f32627455386c error
84 6f error
85 7076794b55513a494471 error
86 2e0a476d344f4b3a630a4a7239 error
87 6a error
88 653163627068680a2f435474 7b571ba6187f093b
89 52787467454c77553a 471b6010bc14
90 6f694130737a4d3164 error
91 426a4c6f45635f79 0632e811cff2
92 514a4b63336b 40929cde
93 2b6e fa
94 7321506547217030746a b0f786a74b63
95 796564494d47504334316567 c9e7483063c2e357a0
96 76 error
97 20786374453379674a473048 c5cb44df28091b41
98 35714c7743 error
99 59794620756947 63216e88
100 784f2162 c4e6
101 213d4545 10
102 327a5453310a4b db34d2d4
103 50534b395071424f6a56213659 3d22bd3ea04e8d5e98
104 48375f6e666c304c34672b452d34 1fbfe77e5d0be20f84fb
105 45666c7471685a2f7375 11f96daa167fb2
106 76 error
107 73 error
108 7331714c34577a2d b35a8be16cfe
109 5353425a6c6453 49205995d4
110 2e4764663a3a35 19d7f9
111 4a2f51762d37334a3521 error
112 2d49 f8
113 4c4b6575 2ca7ae
114 743848485277 b7c1c747
115 6d69546d6f38312e6d7a error
116 6675617876364769577471 7ee6b1bfa1a25ada
117 205f427775575f5f6b627054683d fc1c2e5bffe46e94e1
118 38652e706137715437777a f1ea5aeea4fbc3
119 48562d6a20714445 1d5fa3a831
120 6947 88
121
122
123 4462526121 0db45a
124
125
126 56464c39586475396d error
127
128 2b757953683638722148213858 faec9287af2b1fc5
129 7a64356b4a306e cdde642749
130 3d6d7a 9b
131 32205632634a31746f70 error
132 6e37684a52 error
133 5a0a6b 66
134 56722f582e2030485f48536775 56bfd7d07fc74a0b
135 6d64363368516b75 99deb785092e
136 7a error
137 786d5f4351 error
138 6133 6b
139 4156 01
140 3534796a215263484f2f410a7658 e78ca345c1cefc0bd7
141 677945667865526c36632f386c2d 83211fc5e465e9cffc97
142 383051775a3a764e6d67500a4475 f3443066f36680f0ee
143 676c5277564269725851 8254705418ab5d
144 473d68376f54 error
145 3a382d4431576f6d3d684f error
146
147 415021 00
148 21532e3331460a 4b7d45
149 782e642e63513754514c4a4563 c5d710ed340b2447
150 385a6e21307821 error
151 7864686958 error
152 62374457 6fb0d6
153 704666694835 a457e21f
154 2152576f322b error
155 566d306b473d69576b3d51554e 566d241a25a44143
156 6258304634336a654a2d516774 error
157 52 error
158 736346346b6343493961 b1c17891c088f5
159 3a4143202b46333d43 002f85dc
160 346876654c41684d63756a6e7550 e21bde2c084c72e8e7b8
161 3a206a582b2e4f356b6d 8d7f8ee649
162 5336652b5051574354466367 4ba7be3d05824c5720
163 74626d2e733d513058 b5b9ac4345
164 55422173784f456b206231583448 501b3138491bd57e07
165 5a4b314252364d620a216e2e6659 64ad4147a31b9df6
166 58646b3a464953366c 5dd905212ea5
167 7566656c302b32 b9f7a5d3ed
168 774b c0
169
170 59304471 6340ea
171 5a error
172 5357357472736c205a2e6b54 496e6daec95991
173 470a error
174 7271 ae
175 2033795268393668 df2461f7a8
176 733453640a74696b2b7a3d723161 b3849db6293ecebd5a
177 5739 5b
178 6c2e713359544f6775 96add84ce82e
179 533843612d error
180 53742f2b6872516161657055 4adffe86b41a69ea54
181 5a48312b4e6c426f206e696652 647d7e3650689e27d1
182
183
184 3a4a error
185 34447950 e03c8f
186
187 772b535a76486f4350743a3141 c3e499bc7a023edd40
188 52 error
189
190 77414f c003
191 794d53787a426750687552434b64 c8c4b1cc180f86e44229
192 4d6b2f37496b 324ffb22
193 2b3131793132203334 fb5d72d76df8
194 75214852683a2f470a5463 b87461fc64dc
195 6735526b 839464
196 6e error
197
198 484d2f5f2f0a3168387438303d2e 1ccfffff587cb7cd
199 6771537969742f3964303756542e error
200 46745a5f75563a65 16d67fb957
201 50 error
202 313549 d792
203 6e4b79364955664a 9cacba2147c9
204 572f31785521 error
205 33513031537a55354856707773 error
206 4334452b5663662d4e5a4a5a 0b813e55c7fe359259
207 36727a eabc
208 696c4d526b4a4433792d533d59 8a53119090f7cbe498
209 7653416e56 error
210 0a7978692b cb18be
211 6f796e35473149315635 a329f91b523557
212
213 4435532d3a6c5f5255725042 0f94be97f454acf0
214 5f39 ff
215 6f747331674d674c3932 a2db3580c80bf7
216 5f66562b74393672483064 fdf57eb7deab1f47
217 30363d6950 d3a88f
218 35505934446643650a e4f6380df09e
219 4b6d372f34546358 2a6effe13717
220 2f3277 ff6c
221 217021454c544b5276723a50 error
222 69357a6664774b4d 8b9cdf77028c
223 5a58 65
224 53663671616f2149 49feaa6a82
225 4c205175300a6c77346b7665 2d0bb4970e24bd
226 735137543a59552164376c7556 b10ed361477b96e5
227 703744 a7b0
228 614579595547785a63764c 684c98506c5972f2
229 3a51365369795f4f714f3869 43a4a2cbf3aa3bc8
230 5855 5d
231 50514f2b5a58 3d03be65
232 623242 6f60
233 46316947526d414a4a47355a65 error
234 3877444c56576b440a4a error
235 4f4f456f 38e128
236 4c586e734746425a5521 error
237 535959 4986
238 2b764e0a5249660a58 faf35121f5
239 3630543936 error
240 6672473d55 7eb194
241 41686a5372213879682d79384f63 error
242 5667422d667131750a44 error
243 705744534d702b a560d2329f
244 687577 86ec
245 2164386f2e696b584f725348 77ca229173ab48
246 65326e75756b2f6b7849 7b69eeba4fe4c4
247 6c657374 95eb2d
248 3a744f b4
249 375267 ed18
250 6f4c214668 a0b161
251 795278456b2d5f69 c91c4493efe2
252 3d372e error
253
254 6a397434516530673239 8fdb7841ed20db
255 38206b44372034576a46 f240fbe168c5
256 3554393a55433231412d3770 e53f540b6d40fbba
257 3a6b46 90
258 6c63 95
259 4e48496758366d715a53597659 error
260 21566556 55e5
261 495442684a3d747a 21306126dc
262 0a2b693d6e50482f78324b754644 fa29cf1ffc762ae143
263 734d3d62414a2b4534723a7949 b0c6c027e138af22
264 6b66534c655759445220535f 91f48b796603452f
265 4d6a4659795277424943 323158c91c0120
266 46433a662e4943 error
267 2d614e713864 f9a36af1
268 7a4277713777454c4f4a cc1c2aef010b38
269 4730 1b
270 66744a412d517347446c3462 7ed240f90b060e5e1b
271 77 error
272 6621 error
273 6f643a4e4f7366 a1d34eb1
274 50374b73756e495537374a347631 3fb2acba7214efb278bf
275 32720a da
276 534137334d642f4e44516f61 480ef731dfcd0d0a1a
277 636664734a0a4a38656b4f2b354a error
278 4449706d 0c8a66
279 705a2b345248204671517a322b63 error
280 6e305220427a787a 9f4441cf1c
281 6170363a587774334b34783074 6a9e97c2ddcae31d2d
282 4376317a34 error
283 79 error
284 2d640a49593669596b f9d218ea2624
285 6968446b0a344447595841317766 error
286 754221467743552e2b b81170094f
287 65434d37 78233b
288 6379354a2b696b41455f453337 error
289 2e363a740a346432 error
290 4a error
291 445075 0cfb
292 6b694247 922046
293 4b656b397370520a31456f6651 29e93db294751287d0
294 6e7165375461645750564c3274 error
295 5f77437a2b78542145312e6f57 ff00b3fb14c4d685
296 43652b7121 09efaa
297 436e3569547056 0a7e624e95
298 342b2f736e70646f0a765744554b error
299 692b6b306b743731 8be93492def5
300 50647478715f68322166 error
301 333953375258 dfd4bb45
302 70576474342b3730590a error
303 37 error
304 35 error
305 312078336f2f4d5144657978 d71de8fcc4037b2c
306 5a484c504d366a384b346c483a 6472cf33a8fc2b8947
307 2d563d2d616c352f6977 error
308 5f4375434579 fc2b8213
309 75753951644176 baef50740b
310 7430 b7
311 33476857 dc6856
312 2d6b706355633443634f fa4a5c51ce0270
313 544237215f703d516776745253 4c1effa5082fb514
314 51764e6b46 error
315 6236624c 6fa6cb
316 7678 bf
317 4a2b4f5554 error
318 4a6d 26
319 4a66394f304668763a79304f3658 error
320 313645 d7a1
321 66707944706942 7e9c83a620
322 3452532f532f3454 e114bf4bfe13
323 754d627951382b50 b8c6f243cf8f
324 4e7650424c52 36f3c12d
325 742d5f214453675544 b7efc34a0503
326 50547932625572 3d3cb66d4a
327
328 71586e34 a979f8
329 49456b514f36214a2f465a577547 error
330 722f af
331 5248 44
332 324a3079596b d89d3262
333 314f6d79666a487973622171 d4e9b27e31f2b1ba
334 2b375332445f77 fbb4b60ffc
335 385f30 f3fd
336 2177574e7266652b622b error
337 6c2f682d316a2e776f79 error
338 2e6f4837746b error
339 3059 d1
340
341 5a7739343561626b4f3330 670f78e5a6e43b7d
342 536e4479 4a70f2
343 716249 a9b2
344 2b46345a4a34 f85e1927
345
346 33384f57 dfc396
347 5a58636430 error
348 496e20765f484876644c5847 227bff1c7bdd2d71
349 732f747147547a2e b3fb6a193c
350 307173585320662f436c6945 d2ab1749ffc29621
351 57656745376f72 59e804ee8a
352 554f526843335954 50e4610b7613
353 6e38 9f
354
355 6c5a79506c644a6473426e52 959c8f95d25db019d1
356 2e
357 4f5973466f78744c337648 398b05a31b4bdef1
358 77683537524b7355216d354c c21e7b44ab149b92
359 4d552e4f3637774d6138 error
360 5275507154573053323d4566 46e3ea4d6d12d847
361 4850 1c
362 4d6f33 328d
363 3a36713a4f662d3162 eaa39ffb56
364
365 576d303949634155 5a6d3d21c014
366 6c4937493d 948ec8
367 7720394c5a62 error
368 6b72574455797a622d error
369 7139574854365343 abd5874fa482
370 2f304b7055 error
371 0a6c422d2b36773a7057212b7271 941fbeeb0a56faba
372 6777343769 error
373 506b756b6a error
374 6c7877466b455869552f63552b35 971c059045e253f714fb
375 55677457692b435a5a54 520b568be09965
376 30 error
377 364e72206a32552031 e8dae3d94d
378 3449203463542e724d750a6d73 e08e1c4eb32e9a
379 4f21736c6d464544354978 3ac9661440f923
380 2f397464695230 ffdb5d891d
381 5f3a error
382 46 error
383 5159794c535f5774342f 418c8b4bf5ade3
384 2b416e7a3957763d463731 f809f3f56bc5ef
385 76484b585562 bc729751
386 57 error
387 617741655a3861396b670a42 6b001e67c6bd9200
388 3047475f5533656531456e56 d061bf53779ed449d5
389
390 4c745a 2ed6
391 39 error
392 457579626f7a6a4d 12ec9ba338cc
393 4b2d5f 2bef
394 55537a676f68614a4a692d21 512ce0a21689262f
395 493d3979380a72686e 23dcbcae19
396 584779596d2d4b484b57693036 error
397 416668575334 01f8564b
398 2e6a756e2147 8ee9c6
399 6b47424d212d594b7a67697a 90604cf982b3822c
400 397771554b6163 f70a9429a7
401 4836213a 1f
402
403 44474d575a error
404 7653780a44592f79 bd2c4363fc
405 50786c6834422d3a6d56503442 3f1961e01fa654fe01
406
407 56214b782b686c4951797a2d 54ac7e865210cb3f
408 53336130596d704c43 error
409 30 error
410 2b error
411 7774 c2
412 515651762e693a7a2074 41542f8b3b
413 7049673a7a71724d36756c4f a48833aab33aba53
+113 -21
View File
@@ -22,12 +22,7 @@ fn payload(fields: &[u8], stamp: Option<&[u8]>) -> Vec<u8> {
fn wire(payload: &[u8]) -> Vec<u8> {
let mut signed = vec![1; 16];
signed.extend_from_slice(&[2; 16]);
if let Some(body) = first_four_msgpack_array_body(payload) {
signed.push(0x94);
signed.extend_from_slice(body);
} else {
signed.extend_from_slice(payload);
}
signed.extend_from_slice(&canonical::hashed_payload(payload).unwrap());
let hash = sha256(&signed);
signed.extend_from_slice(&hash);
let mut out = vec![1; 16];
@@ -201,10 +196,7 @@ fn field_id_duplicate_numeric_encodings_rejected() {
vec![0x82, 1, 0xc0, 0xd1, 0, 1, 0xc0],
vec![0x82, 0xcf, 0, 0, 0, 0, 0, 0, 0, 1, 0xc0, 0xcc, 1, 0xc0],
] {
assert!(matches!(
LxMessage::unpack(&wire(&payload(&map, None))),
Err(MessageError::DuplicateField)
));
assert!(LxMessage::unpack(&wire(&payload(&map, None))).is_err());
let mut dto = vec![0x94, 0xcb];
dto.extend_from_slice(&0f64.to_be_bytes());
dto.extend_from_slice(&[0xc4, 0, 0xc4, 0]);
@@ -229,15 +221,20 @@ fn field_id_coherent_replacement_and_binary_is_not_structure() {
assert_eq!(freeze(d).audio_field().unwrap().unwrap().bytes, &[1, 2]);
}
#[test]
fn field_id_opaque_nested_duplicate_map_is_preserved() {
fn field_id_nested_duplicate_map_is_rejected() {
let raw = vec![0x82, 1, 0x01, 0xd1, 0, 1, 0x02];
let mut d = draft();
d.set_msgpack_field(300u64, raw.clone()).unwrap();
let m = freeze(d);
assert_eq!(m.get_field(300u64).unwrap().encoded(), raw);
assert_eq!(
LxMessage::unpack(m.wire_bytes()).unwrap().pack().unwrap(),
m.wire_bytes()
assert!(d.set_msgpack_field(300u64, raw.clone()).is_err());
assert!(
LxMessage::unpack(&wire(&payload(
&[0x81, 0xcd, 1, 44]
.iter()
.copied()
.chain(raw)
.collect::<Vec<_>>(),
None
)))
.is_err()
);
}
#[test]
@@ -584,10 +581,17 @@ fn nested_field_duplicate_schema_reader_rejects_ambiguous_keys() {
vec![0x81, 0xc3, 0],
] {
let mut d = draft();
d.set_msgpack_field(300u64, encoded).unwrap();
let m = freeze(d);
assert!(m.get_field(300u64).unwrap().unique_map().is_err());
assert!(m.verify_signature(&key().public_key()));
let map = vec![0x81, 0xcd, 1, 44].into_iter().chain(encoded.clone());
if encoded[0] == 0x81 {
// A single bool key is valid MessagePack; only the schema reader rejects it.
d.set_msgpack_field(300u64, encoded).unwrap();
let m = freeze(d);
assert!(m.get_field(300u64).unwrap().unique_map().is_err());
assert!(m.verify_signature(&key().public_key()));
} else {
assert!(d.set_msgpack_field(300u64, encoded).is_err());
assert!(LxMessage::unpack(&wire(&payload(&map.collect::<Vec<_>>(), None))).is_err());
}
}
let mut d = draft();
d.set_msgpack_field(300u64, vec![0x82, 0xa1, b'a', 0xc4, 1, 7, 0x01, 0x02])
@@ -845,3 +849,91 @@ fn resumable_form_round_trips_and_rejects_damage() {
);
}
}
#[test]
fn paper_uri_base64_matches_python_urlsafe_b64decode() {
let corpus = include_str!("fixtures/python-urlsafe-b64decode.tsv");
for line in corpus.lines() {
let (input, want) = line.split_once('\t').unwrap();
let data = String::from_utf8(hex::decode(input).unwrap()).unwrap() + "==";
let got = python_urlsafe_b64decode(&data).ok().map(hex::encode);
let want = (want != "error").then(|| want.to_string());
assert_eq!(got, want, "input {data:?}");
}
assert!(python_urlsafe_b64decode("QUJD\u{e9}==").is_err());
}
#[test]
fn paper_uri_accepts_padding_slashes_and_rejects_upper_case_prefix() {
let mut m = freeze(draft());
m.method = DeliveryMethod::Paper;
let uri = m.to_paper_uri(|tail| Ok(tail.to_vec())).unwrap();
for variant in [
format!("{uri}/"),
format!("{uri}=="),
uri.replacen("lxm://", "lxm:///", 1),
] {
let read = LxMessage::from_paper_uri(&variant, |tail| Ok(tail.to_vec())).unwrap();
assert_eq!(read.wire_bytes(), m.wire_bytes(), "{variant}");
}
// Upstream only strips the lower-case prefix, so "LXM:" stays in the base64 input.
let upper = uri.replacen("lxm://", "LXM://", 1);
let decoded = LxMessage::from_paper_uri(&upper, |tail| Ok(tail.to_vec()));
assert!(decoded.map_or(true, |read| read.wire_bytes() != m.wire_bytes()));
}
#[test]
fn integer_timestamp_is_accepted_and_hashed_as_received() {
let mut p = payload(&[0x80], None);
p.splice(1..10, [0xce, 0x65, 0x53, 0xf1, 0x00]);
let m = LxMessage::unpack(&wire(&p)).unwrap();
assert_eq!(m.timestamp(), 1_700_000_000.0);
assert!(m.verify_signature(&key().public_key()));
}
#[test]
fn nested_duplicate_map_keys_are_rejected_on_send_and_receive() {
let mut d = draft();
assert!(
d.set_msgpack_field(2u8, vec![0x82, 0x01, 0x01, 0x01, 0x02])
.is_err()
);
assert!(
d.set_msgpack_field(2u8, vec![0x81, 0x81, 0x01, 0x01, 0x02])
.is_err()
);
let p = payload(&[0x81, 0x02, 0x82, 0x01, 0x01, 0x01, 0x02], None);
assert!(LxMessage::unpack(&wire(&p)).is_err());
}
#[test]
fn msgpack_fields_are_stored_canonically() {
let mut d = draft();
d.set_msgpack_field(2u8, vec![0x91, 0xca, 0x3f, 0xc0, 0, 0])
.unwrap();
assert_eq!(
d.get_field(2u8),
Some(&FieldValue::MessagePack(
EncodedFieldValue::new(Bytes::from_static(&[
0x91, 0xcb, 0x3f, 0xf8, 0, 0, 0, 0, 0, 0
]))
.unwrap()
))
);
}
#[test]
fn container_is_a_named_map() {
let m = freeze(draft());
let value = rmpv::decode::read_value(&mut &m.pack_container().unwrap()[..]).unwrap();
let keys: Vec<_> = value
.as_map()
.unwrap()
.iter()
.map(|(k, _)| k.as_str().unwrap())
.collect();
assert_eq!(
keys,
[
"state",
"lxmf_bytes",
"transport_encrypted",
"transport_encryption",
"method"
]
);
}
+83 -1
View File
@@ -5,7 +5,10 @@ use unicode_normalization::UnicodeNormalization;
/// Maximum retained characters for an advertised LXMF display/node name.
pub const MAX_ADVERTISED_NAME_CHARS: usize = 128;
/// Normalize and bound an untrusted display name.
/// Normalize and bound an untrusted display name for presentation.
///
/// This is an application display policy; the announce helpers in
/// [`crate::handlers`] return names unfiltered, as Python LXMF does.
///
/// Applies NFKC normalization and filters control characters, bidi controls,
/// private-use characters, selected zero-width characters, variation selectors,
@@ -133,6 +136,85 @@ fn is_emoji(codepoint: u32) -> bool {
)
}
/// Python `str.isspace()`: Unicode White_Space plus U+001C..U+001F.
pub fn is_python_space(character: char) -> bool {
character.is_whitespace() || matches!(character, '\u{1c}'..='\u{1f}')
}
/// Python `str.strip()` with no arguments.
pub fn python_strip(text: &str) -> &str {
text.trim_matches(is_python_space)
}
/// The name filter `lxmd --peers` applies (Python `lxmd.sanitize_name`):
/// NFKC, then keep letters, numbers, punctuation and spacing marks, map
/// separators to a space, drop the emoji, control and private-use blocks,
/// collapse whitespace and strip. Truncation is left to the caller.
pub fn sanitize_name_lxmd(input: &str) -> String {
use unicode_general_category::{GeneralCategory as C, get_general_category};
let mut kept = String::new();
for character in input.nfkc() {
let category = get_general_category(character);
let mapped = match category {
C::SpaceSeparator | C::LineSeparator | C::ParagraphSeparator => ' ',
C::UppercaseLetter
| C::LowercaseLetter
| C::TitlecaseLetter
| C::ModifierLetter
| C::OtherLetter
| C::DecimalNumber
| C::LetterNumber
| C::OtherNumber
| C::ConnectorPunctuation
| C::DashPunctuation
| C::OpenPunctuation
| C::ClosePunctuation
| C::InitialPunctuation
| C::FinalPunctuation
| C::OtherPunctuation
| C::SpacingMark => character,
_ => continue,
};
if !is_lxmd_stripped(mapped as u32) {
kept.push(mapped);
}
}
let mut output = String::with_capacity(kept.len());
for word in kept.split(is_python_space).filter(|w| !w.is_empty()) {
if !output.is_empty() {
output.push(' ');
}
output.push_str(word);
}
output
}
// STRIP_BLOCKS_RE, STRIP_CONTROL_RE and STRIP_PRIVATE_RE of Python lxmd.
fn is_lxmd_stripped(codepoint: u32) -> bool {
matches!(
codepoint,
0x1F300..=0x1FAFF
| 0x1F1E0..=0x1F1FF
| 0x2600..=0x27BF
| 0xFE00..=0xFE0F
| 0xE0100..=0xE01EF
| 0x00..=0x08
| 0x0B
| 0x0C
| 0x0E..=0x1F
| 0x7F..=0x9F
| 0x200B..=0x200F
| 0x202A..=0x202E
| 0x2060..=0x206F
| 0xFEFF
| 0xFFF0..=0xFFF8
| 0xD800..=0xDFFF
| 0xE000..=0xFAFF
| 0xFE10..=0xFE2F
| 0xF0000..=0x10FFFF
)
}
#[cfg(test)]
mod tests {
use super::*;
+1 -1
View File
@@ -604,7 +604,7 @@ pub fn format_remote_status(
_ => "never synced".to_string(),
};
let name =
lxmf_core::presentation::sanitize_name(map_str(peer, "name").unwrap_or(""), 46);
lxmf_core::presentation::sanitize_name_lxmd(map_str(peer, "name").unwrap_or(""));
let display_name = if name.chars().count() > 45 {
format!("{}...", name.chars().take(45).collect::<String>())
} else {