Compare commits

..
6 Commits
9 changed files with 221 additions and 68 deletions

No files matched your search

+1 -1
View File
@@ -10,7 +10,7 @@ permissions:
contents: read
env:
RSLXMF_RSRETICULUM_COMMIT: 5e35c9f9d9f40d44846aaa5e11009e03490511d3
RSLXMF_RSRETICULUM_COMMIT: f6d0d698dd7e6edc180f9c3697ab1c873571f372
jobs:
api-compat:
+1 -1
View File
@@ -25,7 +25,7 @@ env:
PACKAGE_ROOT: rsLXMF
LXMF_BINS: lxmd-rs
RSLXMF_RSRETICULUM_VERSION: 1.5.1
RSLXMF_RSRETICULUM_COMMIT: 5e35c9f9d9f40d44846aaa5e11009e03490511d3
RSLXMF_RSRETICULUM_COMMIT: f6d0d698dd7e6edc180f9c3697ab1c873571f372
jobs:
verify:
Generated
+8 -36
View File
@@ -145,15 +145,6 @@ dependencies = [
"generic-array",
]
[[package]]
name = "block2"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f"
dependencies = [
"objc2 0.5.2",
]
[[package]]
name = "bytes"
version = "1.11.1"
@@ -731,7 +722,7 @@ dependencies = [
"bytes",
"hex",
"jni",
"objc2 0.6.5",
"objc2",
"proptest",
"rand 0.8.5",
"rmp",
@@ -891,22 +882,6 @@ dependencies = [
"libm",
]
[[package]]
name = "objc-sys"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310"
[[package]]
name = "objc2"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46a785d4eeff09c14c487497c162e92766fbb3e4059a71840cecc03d9a50b804"
dependencies = [
"objc-sys",
"objc2-encode",
]
[[package]]
name = "objc2"
version = "0.6.5"
@@ -918,12 +893,11 @@ dependencies = [
[[package]]
name = "objc2-core-bluetooth"
version = "0.2.2"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a644b62ffb826a5277f536cf0f701493de420b13d40e700c452c36567771111"
checksum = "79b30b9eacc37434a61377866f68b27acef9fa5496f25cc9ca8b2549032e0394"
dependencies = [
"bitflags 2.11.0",
"objc2 0.5.2",
"objc2",
"objc2-foundation",
]
@@ -935,14 +909,12 @@ checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
[[package]]
name = "objc2-foundation"
version = "0.2.2"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8"
checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
dependencies = [
"bitflags 2.11.0",
"block2",
"libc",
"objc2 0.5.2",
"objc2",
]
[[package]]
@@ -1258,7 +1230,7 @@ dependencies = [
"libc",
"md-5",
"mio",
"objc2 0.5.2",
"objc2",
"objc2-core-bluetooth",
"objc2-foundation",
"rand 0.8.5",
+4
View File
@@ -1012,8 +1012,10 @@ pub fn lxmf_core::message::SignedLxMessage::content_text(&self) -> alloc::borrow
pub fn lxmf_core::message::SignedLxMessage::destination_hash(&self) -> [u8; 16]
pub fn lxmf_core::message::SignedLxMessage::fields(&self) -> lxmf_core::message::Fields<'_>
pub fn lxmf_core::message::SignedLxMessage::finalize(self, core::option::Option<lxmf_core::message::RecipientStamp>) -> core::result::Result<lxmf_core::message::LxMessage, lxmf_core::message::MessageError>
pub fn lxmf_core::message::SignedLxMessage::first_file_attachment(&self) -> core::result::Result<core::option::Option<(alloc::string::String, &[u8])>, lxmf_core::message::MessageError>
pub fn lxmf_core::message::SignedLxMessage::generate_recipient_stamp(&self) -> core::result::Result<core::option::Option<lxmf_core::message::RecipientStamp>, lxmf_core::message::MessageError>
pub fn lxmf_core::message::SignedLxMessage::generate_recipient_stamp_with(&self, &rns_identity::stamps::StampControl) -> core::result::Result<core::option::Option<lxmf_core::message::RecipientStamp>, lxmf_core::message::MessageError>
pub fn lxmf_core::message::SignedLxMessage::image_attachment(&self) -> core::result::Result<core::option::Option<(alloc::string::String, &[u8])>, lxmf_core::message::MessageError>
pub fn lxmf_core::message::SignedLxMessage::into_unstamped(self) -> lxmf_core::message::LxMessage
pub fn lxmf_core::message::SignedLxMessage::message_id(&self) -> [u8; 32]
pub fn lxmf_core::message::SignedLxMessage::outbound_ticket(&self) -> core::option::Option<[u8; 16]>
@@ -1308,8 +1310,10 @@ pub fn lxmf_core::message::SignedLxMessage::content_text(&self) -> alloc::borrow
pub fn lxmf_core::message::SignedLxMessage::destination_hash(&self) -> [u8; 16]
pub fn lxmf_core::message::SignedLxMessage::fields(&self) -> lxmf_core::message::Fields<'_>
pub fn lxmf_core::message::SignedLxMessage::finalize(self, core::option::Option<lxmf_core::message::RecipientStamp>) -> core::result::Result<lxmf_core::message::LxMessage, lxmf_core::message::MessageError>
pub fn lxmf_core::message::SignedLxMessage::first_file_attachment(&self) -> core::result::Result<core::option::Option<(alloc::string::String, &[u8])>, lxmf_core::message::MessageError>
pub fn lxmf_core::message::SignedLxMessage::generate_recipient_stamp(&self) -> core::result::Result<core::option::Option<lxmf_core::message::RecipientStamp>, lxmf_core::message::MessageError>
pub fn lxmf_core::message::SignedLxMessage::generate_recipient_stamp_with(&self, &rns_identity::stamps::StampControl) -> core::result::Result<core::option::Option<lxmf_core::message::RecipientStamp>, lxmf_core::message::MessageError>
pub fn lxmf_core::message::SignedLxMessage::image_attachment(&self) -> core::result::Result<core::option::Option<(alloc::string::String, &[u8])>, lxmf_core::message::MessageError>
pub fn lxmf_core::message::SignedLxMessage::into_unstamped(self) -> lxmf_core::message::LxMessage
pub fn lxmf_core::message::SignedLxMessage::message_id(&self) -> [u8; 32]
pub fn lxmf_core::message::SignedLxMessage::outbound_ticket(&self) -> core::option::Option<[u8; 16]>
+2 -2
View File
@@ -24,8 +24,8 @@
"tier": "candidate-stable",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/lxmf-core.txt",
"itemCount": 2454,
"sha256": "3a2d30b180fcb995be7b08d50997f6c243081456e0993b3668742a4db68283c3"
"itemCount": 2458,
"sha256": "93bd001beb46ae13e2ece84d355e9fd4ffc8198029233de3a397b1a645b77651"
},
{
"name": "lxmf-tools",
+53 -26
View File
@@ -169,23 +169,38 @@ impl LxMessageDraft {
id: impl Into<FieldId>,
bytes: impl Into<Bytes>,
) -> Result<(), MessageError> {
self.set_field_value(
id,
FieldValue::MessagePack(EncodedFieldValue::canonical(bytes.into())?),
)
let value = EncodedFieldValue::canonical(bytes.into())?;
self.insert_field(id.into(), FieldValue::MessagePack(value))
}
pub fn set_field_value(
&mut self,
id: impl Into<FieldId>,
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()),
)?),
FieldValue::MessagePack(v) => {
FieldValue::MessagePack(EncodedFieldValue::canonical(v.into_bytes())?)
}
binary => binary,
};
self.insert_field(id.into(), value)
}
/// Encode one of this crate's media fields at its exact size, once.
fn set_media_field<T: serde::Serialize>(
&mut self,
id: FieldId,
value: &T,
bytes: usize,
name: usize,
) -> Result<(), MessageError> {
self.limits.check_wire(bytes)?;
// Two array headers, a str header and a bin header: at most 12 bytes.
let mut encoded = Vec::with_capacity(bytes + name + 12);
rmp_serde::encode::write(&mut encoded, value).map_err(packed)?;
let value = EncodedFieldValue::trusted(encoded.into());
self.insert_field(id, FieldValue::MessagePack(value))
}
fn insert_field(&mut self, id: FieldId, value: FieldValue) -> Result<(), MessageError> {
if !self.fields.contains_key(&id) && self.fields.len() >= self.limits.max_top_level_fields {
return Err(MessageError::TooManyFields);
}
@@ -207,24 +222,25 @@ impl LxMessageDraft {
self.fields.remove(&id.into())
}
pub fn set_image_field(&mut self, format: &str, bytes: &[u8]) -> Result<(), MessageError> {
self.limits.check_wire(bytes.len())?;
let encoded = rmp_serde::to_vec(&ImageFieldRef { format, bytes }).map_err(packed)?;
self.set_msgpack_field(FIELD_IMAGE, encoded)
let value = ImageFieldRef { format, bytes };
self.set_media_field(FIELD_IMAGE.into(), &value, bytes.len(), format.len())
}
pub fn set_audio_field(&mut self, mode: u8, bytes: &[u8]) -> Result<(), MessageError> {
self.limits.check_wire(bytes.len())?;
let encoded = rmp_serde::to_vec(&AudioFieldRef { mode, bytes }).map_err(packed)?;
self.set_msgpack_field(FIELD_AUDIO, encoded)
let value = AudioFieldRef { mode, bytes };
self.set_media_field(FIELD_AUDIO.into(), &value, bytes.len(), 0)
}
pub fn set_file_attachment_field(
&mut self,
file_name: &str,
bytes: &[u8],
) -> Result<(), MessageError> {
self.limits.check_wire(bytes.len())?;
let encoded =
rmp_serde::to_vec(&FileAttachmentsFieldRef { file_name, bytes }).map_err(packed)?;
self.set_msgpack_field(FIELD_FILE_ATTACHMENTS, encoded)
let value = FileAttachmentsFieldRef { file_name, bytes };
self.set_media_field(
FIELD_FILE_ATTACHMENTS.into(),
&value,
bytes.len(),
file_name.len(),
)
}
/// Exact unsigned payload, for diagnostics; it is not a transmittable message.
pub fn pack_payload(&self) -> Result<Vec<u8>, MessageError> {
@@ -270,7 +286,7 @@ impl LxMessageDraft {
pub fn sign(self, key: &Ed25519PrivateKey) -> Result<SignedLxMessage, MessageError> {
self.sign_with(|bytes| Ok::<_, std::convert::Infallible>(key.sign(bytes)))
}
pub fn sign_with<F, E>(self, sign: F) -> Result<SignedLxMessage, MessageError>
pub fn sign_with<F, E>(mut self, sign: F) -> Result<SignedLxMessage, MessageError>
where
F: FnOnce(&[u8]) -> Result<[u8; 64], E>,
E: std::fmt::Display,
@@ -280,16 +296,19 @@ impl LxMessageDraft {
signed.extend_from_slice(&self.destination);
signed.extend_from_slice(&self.source);
self.write_payload(&mut signed)?;
// The payload now lives in `signed` alone.
self.fields.clear();
let id = sha256(&signed);
signed.extend_from_slice(&id);
let signature = sign(&signed).map_err(packed)?;
let mut wire = Vec::with_capacity(size);
wire.extend_from_slice(&self.destination);
wire.extend_from_slice(&self.source);
wire.extend_from_slice(&signature);
wire.extend_from_slice(&signed[32..signed.len() - 32]);
drop(signed);
let mut message = LxMessage::unpack_owned(wire.into(), self.limits)?;
// The wire in place: drop the id and open the signature after the
// two hashes. `size` is exactly the wire length, so nothing moves.
let payload_end = signed.len() - 32;
signed.truncate(payload_end);
signed.resize(size, 0);
signed.copy_within(32..payload_end, 96);
signed[32..96].copy_from_slice(&signature);
let mut message = LxMessage::unpack_owned(signed.into(), self.limits)?;
message.metadata = self.metadata;
message.incoming = false;
message.state = MessageState::Outbound;
@@ -353,6 +372,14 @@ impl SignedLxMessage {
pub fn fields(&self) -> Fields<'_> {
self.message.fields()
}
/// The first file attachment's name and bytes, borrowed from the wire.
pub fn first_file_attachment(&self) -> Result<Option<(String, &[u8])>, MessageError> {
self.message.first_file_attachment()
}
/// The image field's format and bytes, borrowed from the wire.
pub fn image_attachment(&self) -> Result<Option<(String, &[u8])>, MessageError> {
self.message.image_attachment()
}
/// The signed, unstamped message, for failing it without a stamp.
pub fn into_unstamped(self) -> LxMessage {
self.message
+7
View File
@@ -84,6 +84,13 @@ impl EncodedFieldValue {
pub fn encoded(&self) -> &[u8] {
&self.0
}
/// For this crate's encoders, whose output is canonical by construction.
pub(crate) fn trusted(bytes: Bytes) -> Self {
Self(bytes)
}
pub(crate) fn into_bytes(self) -> Bytes {
self.0
}
}
/// A binary byte string or a native structured MessagePack value.
#[derive(Debug, Clone, PartialEq, Eq)]
+62
View File
@@ -962,3 +962,65 @@ fn container_is_a_named_map() {
]
);
}
/// Media fields are written once at their size, and the bytes are the
/// canonical encoding the generic msgpack path produces.
#[test]
fn media_fields_encode_canonically_in_one_pass() {
for (name, len) in [
("a.bin", 3usize),
(&"n".repeat(40) as &str, 300),
("é.jpg", 70_000),
] {
let bytes: Vec<u8> = (0..len).map(|i| i as u8).collect();
let mut d = draft();
d.set_file_attachment_field(name, &bytes).unwrap();
d.set_image_field(name, &bytes).unwrap();
d.set_audio_field(7, &bytes).unwrap();
let reference = [
(
FIELD_FILE_ATTACHMENTS,
rmp_serde::to_vec(&FileAttachmentsFieldRef {
file_name: name,
bytes: &bytes,
}),
),
(
FIELD_IMAGE,
rmp_serde::to_vec(&ImageFieldRef {
format: name,
bytes: &bytes,
}),
),
(
FIELD_AUDIO,
rmp_serde::to_vec(&AudioFieldRef {
mode: 7,
bytes: &bytes,
}),
),
];
for (id, encoded) in reference {
let encoded = canonical::canonicalize(&encoded.unwrap()).unwrap();
let Some(FieldValue::MessagePack(value)) = d.get_field(id) else {
panic!("field {id} missing");
};
assert_eq!(
value.encoded(),
encoded.as_slice(),
"field {id}, {len} bytes"
);
}
}
}
/// The wire built in place is `destination, source, signature, payload`,
/// signed over `destination, source, payload, id`.
#[test]
fn signing_builds_the_wire_in_place() {
let mut d = draft();
d.set_file_attachment_field("f", &[9; 5000]).unwrap();
let payload = d.pack_payload().unwrap();
let message = freeze(d);
assert_eq!(message.wire_bytes(), wire(&payload).as_slice());
}
+83 -2
View File
@@ -433,6 +433,27 @@ impl PropagationClient {
self.delivery_limit = Some(limit_kb);
}
/// The largest response a node keeping to upstream's accounting can send.
/// Only a message `/get` spends the delivery limit (LXMRouter.py
/// `message_get_request`); the ID list is unbounded there. The Link response
/// adds its request id.
fn response_size_limit(&self) -> usize {
const RESPONSE_FRAMING: usize = 64;
if !matches!(
self.request.as_ref().map(|request| request.kind),
Some(RequestKind::Get(..))
) {
return MAX_RESOURCE_SIZE;
}
self.delivery_limit
.filter(|limit| limit.is_finite() && *limit > 0.0)
.map_or(MAX_RESOURCE_SIZE, |limit| {
((limit * 1000.0) as usize)
.saturating_add(RESPONSE_FRAMING)
.min(MAX_RESOURCE_SIZE)
})
}
/// Trust this ID as a durable local have, with no expiry. It may authorize
/// remote purge on the next download cycle unless retention is enabled.
/// The caller must establish the durable local effect; this method does not verify it.
@@ -1469,10 +1490,19 @@ impl PropagationClient {
return;
}
let response_limit = self.response_size_limit();
if adv.data_size > response_limit {
tracing::warn!(
size = adv.data_size,
limit = response_limit,
"propagation node offered a response above the delivery limit"
);
self.fail();
return;
}
if adv.flags.is_request
|| !adv.flags.encrypted
|| adv.flags.has_metadata
|| adv.data_size > MAX_RESOURCE_SIZE
|| adv.total_segments == 0
|| adv.segment_index == 0
|| adv.segment_index > adv.total_segments
@@ -1814,6 +1844,7 @@ impl PropagationClient {
route: Option<SegmentRoute>,
metadata: Option<Vec<u8>>,
) {
let response_limit = self.response_size_limit();
let Some(response) = self
.request
.as_mut()
@@ -1824,7 +1855,7 @@ impl PropagationClient {
let Some(total) = response
.assembled_bytes
.checked_add(assembled.len())
.filter(|total| *total <= MAX_RESOURCE_SIZE && *total <= response.data_size)
.filter(|total| *total <= response_limit && *total <= response.data_size)
else {
self.fail();
return;
@@ -3768,6 +3799,56 @@ mod tests {
assert!(client.status.progress >= first_progress);
}
/// A node keeping to the delivery limit never sends more than the limit
/// plus framing, so a larger offer fails the sync before any part arrives.
/// The ID list is not bounded by it.
#[test]
fn get_response_above_the_delivery_limit_is_refused_when_offered() {
for (kind, payload_len, accepted) in [
(RequestKind::Get(0, 0), 2_064, true),
(RequestKind::Get(0, 0), 2_065, false),
(RequestKind::List, 2_065, true),
] {
let (tx, _rx) = mpsc::channel(64);
let mut client = PropagationClient::new(tx, None, None);
client.set_delivery_limit(2.0);
let (initiator, responder) = active_link_pair([0xE4; 16]);
client.link_id = Some(initiator.link_id);
client.link = Some(initiator);
client.status.state = kind.state();
client.request = Some(PendingRequest {
link_id: client.link_id.unwrap(),
generation: 1,
id: [0x45; 16],
kind,
sender_active: false,
outbound: None,
response: None,
waiting_since: Some(Instant::now()),
timeout: Duration::from_secs(60),
});
let mut sender = OutboundTransfer::new_encrypted(
vec![0xAB; payload_len],
false,
Duration::from_millis(50),
responder.session_keys().unwrap(),
)
.unwrap();
sender.resource.flags.is_response = true;
sender.resource.request_id = Some(vec![0x45; 16]);
let TransferAction::SendAdvertisement(advertisement) = sender.tick() else {
panic!("expected a Resource advertisement");
};
client.handle_resource_advertisement(&responder.encrypt(&advertisement).unwrap());
let state = client.status.state;
assert_eq!(
state == PropagationClientState::Receiving,
accepted,
"{kind:?} {payload_len}: {state:?}"
);
}
}
#[test]
fn resource_response_is_not_published_when_its_proof_cannot_be_retained() {
let (tx, mut rx) = mpsc::channel(64);