mirror of
https://github.com/ratspeak/rsLXMF
synced 2026-11-22 23:10:35 +00:00
lxmf: harden relay replies and crypto storage initialization
This commit is contained in:
1 parent
652dc3cd46
commit
580fe1deab
7 files changed
+396
-40
No files matched your search
@@ -10,7 +10,7 @@ permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
RSLXMF_RSRETICULUM_COMMIT: 817a640ed1e11e3ff3e0ff048d8de13662bfdd78
|
||||
RSLXMF_RSRETICULUM_COMMIT: 8fcf0b678a4bed778b29690b85b378d05684eaf1
|
||||
|
||||
jobs:
|
||||
api-compat:
|
||||
|
||||
@@ -25,7 +25,7 @@ env:
|
||||
PACKAGE_ROOT: rsLXMF
|
||||
LXMF_BINS: lxmd-rs
|
||||
RSLXMF_RSRETICULUM_VERSION: 1.4.0
|
||||
RSLXMF_RSRETICULUM_COMMIT: 817a640ed1e11e3ff3e0ff048d8de13662bfdd78
|
||||
RSLXMF_RSRETICULUM_COMMIT: 8fcf0b678a4bed778b29690b85b378d05684eaf1
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
|
||||
@@ -937,7 +937,9 @@ fn read_msgpack_array_len(input: &mut &[u8]) -> Result<u32, MessageError> {
|
||||
}
|
||||
}
|
||||
|
||||
fn read_msgpack_string_or_binary<'a>(input: &mut &'a [u8]) -> Result<&'a [u8], MessageError> {
|
||||
pub(crate) fn read_msgpack_string_or_binary<'a>(
|
||||
input: &mut &'a [u8],
|
||||
) -> Result<&'a [u8], MessageError> {
|
||||
let marker = take_msgpack(input, 1)?[0];
|
||||
let length = match marker {
|
||||
0xa0..=0xbf => usize::from(marker & 0x1f),
|
||||
@@ -1074,7 +1076,7 @@ fn read_msgpack_integer(input: &mut &[u8]) -> Result<i128, MessageError> {
|
||||
fn read_msgpack_integer_u8_strict(input: &mut &[u8]) -> Result<u8, MessageError> {
|
||||
u8::try_from(read_msgpack_integer(input)?).map_err(|_| MessageError::InvalidByte)
|
||||
}
|
||||
fn skip_msgpack_value(input: &mut &[u8], depth: usize) -> Result<(), MessageError> {
|
||||
pub(crate) fn skip_msgpack_value(input: &mut &[u8], depth: usize) -> Result<(), MessageError> {
|
||||
if depth >= 64 {
|
||||
return Err(MessageError::UnpackFailed(
|
||||
"MessagePack nesting exceeds limit".to_string(),
|
||||
|
||||
@@ -120,6 +120,13 @@ impl PropagationStore {
|
||||
if self.ignored_destinations.contains(&entry.destination_hash) {
|
||||
return false;
|
||||
}
|
||||
self.insert_admitted(entry)
|
||||
}
|
||||
|
||||
/// Account for an entry whose admission policy was checked before its
|
||||
/// durable publication. Later ignore-list changes affect future admissions,
|
||||
/// not a write already accepted under the node's reservation authority.
|
||||
pub(crate) fn insert_admitted(&mut self, entry: PropagationEntry) -> bool {
|
||||
self.total_size += entry.size;
|
||||
self.entries.insert(entry.transient_id, entry);
|
||||
true
|
||||
|
||||
@@ -1705,37 +1705,71 @@ impl PropagationClient {
|
||||
|
||||
/// Phase 1: parse available transient IDs from the server.
|
||||
fn handle_list_response(&mut self, response_data: &[u8]) {
|
||||
let value: rmpv::Value = match Self::decode_response_value(response_data) {
|
||||
Ok(v) => v,
|
||||
let ids = match Self::parse_available_message_ids(response_data) {
|
||||
Ok(ids) => ids,
|
||||
Err(_) => {
|
||||
self.fail();
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(arr) = value.as_array() {
|
||||
self.finish_request(response_data);
|
||||
self.available_messages.clear();
|
||||
for item in arr {
|
||||
if let Some(id_bytes) = item.as_slice()
|
||||
&& id_bytes.len() == 32
|
||||
{
|
||||
self.available_messages.push(id_bytes.to_vec());
|
||||
}
|
||||
}
|
||||
|
||||
if self.available_messages.is_empty() {
|
||||
self.status.state = PropagationClientState::Complete;
|
||||
self.status.progress = 1.0;
|
||||
self.status.result = Some(0);
|
||||
} else {
|
||||
self.send_get_request();
|
||||
}
|
||||
self.finish_request(response_data);
|
||||
self.available_messages = ids;
|
||||
if self.available_messages.is_empty() {
|
||||
self.status.state = PropagationClientState::Complete;
|
||||
self.status.progress = 1.0;
|
||||
self.status.result = Some(0);
|
||||
} else {
|
||||
self.fail();
|
||||
self.send_get_request();
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate the complete borrowed list before reserving only the valid ID
|
||||
/// output. Unknown items are skipped without materializing their containers;
|
||||
/// the advertised array count cannot amplify allocation for nil-heavy lists.
|
||||
fn parse_available_message_ids(response_data: &[u8]) -> Result<Vec<Vec<u8>>, ()> {
|
||||
fn next_id<'a>(input: &mut &'a [u8]) -> Result<Option<&'a [u8]>, ()> {
|
||||
let value = *input;
|
||||
crate::message::skip_msgpack_value(input, 0).map_err(|_| ())?;
|
||||
if !matches!(value.first(), Some(0xa0..=0xbf | 0xc4..=0xc6 | 0xd9..=0xdb)) {
|
||||
return Ok(None);
|
||||
}
|
||||
// Match the previous Value::as_slice behavior for binary and string
|
||||
// bytes, including invalid UTF-8 in a legacy string-encoded ID.
|
||||
let id =
|
||||
crate::message::read_msgpack_string_or_binary(&mut &value[..]).map_err(|_| ())?;
|
||||
Ok((id.len() == 32).then_some(id))
|
||||
}
|
||||
|
||||
if response_data.len() > MAX_RESOURCE_SIZE {
|
||||
return Err(());
|
||||
}
|
||||
let mut input = response_data;
|
||||
let count = rmp::decode::read_array_len(&mut input).map_err(|_| ())? as usize;
|
||||
// Every item needs at least one marker. Check before iteration or any
|
||||
// reservation, including hostile array32 declarations in tiny payloads.
|
||||
if count > input.len() {
|
||||
return Err(());
|
||||
}
|
||||
let items = input;
|
||||
let mut valid_count = 0;
|
||||
for _ in 0..count {
|
||||
valid_count += usize::from(next_id(&mut input)?.is_some());
|
||||
}
|
||||
if !input.is_empty() {
|
||||
return Err(());
|
||||
}
|
||||
let mut ids = Vec::new();
|
||||
ids.try_reserve_exact(valid_count).map_err(|_| ())?;
|
||||
input = items;
|
||||
for _ in 0..count {
|
||||
if let Some(id) = next_id(&mut input)? {
|
||||
ids.push(id.to_vec());
|
||||
}
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// Validate type/count, exact requested TID membership, duplicates and full
|
||||
/// byte budget before publishing any item. Payload ranges borrow one owner.
|
||||
fn handle_get_response_owned(&mut self, response_data: Bytes) {
|
||||
@@ -1912,6 +1946,7 @@ impl PropagationClient {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn decode_response_value(data: &[u8]) -> Result<rmpv::Value, ()> {
|
||||
let mut remaining = data;
|
||||
let value = rmpv::decode::read_value(&mut remaining).map_err(|_| ())?;
|
||||
@@ -1924,8 +1959,8 @@ impl PropagationClient {
|
||||
/// A successful purge is the empty array returned by Rust and Python
|
||||
/// nodes. In particular a peer error code or nil must not advance a cursor.
|
||||
fn handle_purge_response(&mut self, response_data: &[u8]) {
|
||||
if !matches!(Self::decode_response_value(response_data), Ok(rmpv::Value::Array(items)) if items.is_empty())
|
||||
{
|
||||
let mut input = response_data;
|
||||
if rmp::decode::read_array_len(&mut input).ok() != Some(0) || !input.is_empty() {
|
||||
self.fail();
|
||||
return;
|
||||
}
|
||||
@@ -2958,6 +2993,115 @@ mod tests {
|
||||
assert_eq!(client.status.state, PropagationClientState::Complete);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_reply_skips_non_ids_and_preserves_legacy_string_bytes() {
|
||||
let mut reply = Vec::new();
|
||||
rmp::encode::write_array_len(&mut reply, 5).unwrap();
|
||||
rmp::encode::write_bin_len(&mut reply, 32).unwrap();
|
||||
reply.extend_from_slice(&[0xab; 32]);
|
||||
rmp::encode::write_str(&mut reply, &"x".repeat(32)).unwrap();
|
||||
rmp::encode::write_str_len(&mut reply, 32).unwrap();
|
||||
reply.extend_from_slice(&[0xff; 32]);
|
||||
rmp::encode::write_bin_len(&mut reply, 16).unwrap();
|
||||
reply.extend_from_slice(&[0xab; 16]);
|
||||
rmp::encode::write_array_len(&mut reply, 100_000).unwrap();
|
||||
reply.extend(std::iter::repeat_n(0xc0, 100_000));
|
||||
|
||||
let previous = PropagationClient::decode_response_value(&reply).unwrap();
|
||||
let expected = previous
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter_map(|item| {
|
||||
item.as_slice()
|
||||
.filter(|id| id.len() == 32)
|
||||
.map(<[u8]>::to_vec)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
expected,
|
||||
vec![vec![0xab; 32], vec![b'x'; 32], vec![0xff; 32]]
|
||||
);
|
||||
assert_eq!(
|
||||
PropagationClient::parse_available_message_ids(&reply).unwrap(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_reply_rejects_invalid_framing_before_publishing_ids() {
|
||||
let mut prefix = vec![0x92, 0xc4, 32];
|
||||
prefix.extend_from_slice(&[0xab; 32]);
|
||||
let mut truncated_item = prefix.clone();
|
||||
truncated_item.extend_from_slice(&[0xc6, 0xff, 0xff, 0xff, 0xff]);
|
||||
let mut deep_item = prefix;
|
||||
deep_item.extend(std::iter::repeat_n(0x91, 64));
|
||||
deep_item.push(0xc0);
|
||||
for reply in [
|
||||
vec![0xdd, 0xff, 0xff, 0xff, 0xff],
|
||||
vec![0x91, 0xdb, 0xff, 0xff, 0xff, 0xff],
|
||||
vec![0x91, 0xdf, 0xff, 0xff, 0xff, 0xff],
|
||||
vec![0x90, 0xc0],
|
||||
truncated_item,
|
||||
deep_item,
|
||||
] {
|
||||
let (tx, _rx) = mpsc::channel(16);
|
||||
let mut client = PropagationClient::new(tx, None, None);
|
||||
client.status.state = PropagationClientState::ListRequested;
|
||||
client.available_messages = vec![vec![0xcc; 32]];
|
||||
client.handle_list_response(&reply);
|
||||
assert_eq!(client.state(), PropagationClientState::Failed);
|
||||
assert_eq!(client.available_messages, vec![vec![0xcc; 32]]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_reply_accepts_mailboxes_larger_than_a_request_chunk() {
|
||||
let count = MAX_DOWNLOAD_ITEMS * 2 + 3;
|
||||
let mut reply = Vec::new();
|
||||
rmp::encode::write_array_len(&mut reply, count as u32).unwrap();
|
||||
for number in 0..count {
|
||||
let mut id = [0; 32];
|
||||
id[..8].copy_from_slice(&(number as u64).to_be_bytes());
|
||||
rmp::encode::write_bin_len(&mut reply, 32).unwrap();
|
||||
reply.extend_from_slice(&id);
|
||||
}
|
||||
let ids = PropagationClient::parse_available_message_ids(&reply).unwrap();
|
||||
assert_eq!(ids.len(), count);
|
||||
for (number, id) in ids.iter().enumerate() {
|
||||
assert_eq!(&id[..8], &(number as u64).to_be_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn purge_reply_requires_a_complete_empty_array_before_cursor_changes() {
|
||||
let mut nil_heavy = Vec::new();
|
||||
rmp::encode::write_array_len(&mut nil_heavy, 100_000).unwrap();
|
||||
nil_heavy.extend(std::iter::repeat_n(0xc0, 100_000));
|
||||
for reply in [
|
||||
vec![0xdd, 0xff, 0xff, 0xff, 0xff],
|
||||
vec![0x90, 0xc0],
|
||||
vec![0xdc, 0, 0, 0xc0],
|
||||
vec![0xc0],
|
||||
nil_heavy,
|
||||
] {
|
||||
let (tx, _rx) = mpsc::channel(16);
|
||||
let mut client = PropagationClient::new(tx, None, None);
|
||||
client.status.state = PropagationClientState::PurgeRequested;
|
||||
client.received_ids = vec![vec![0xab; 32]];
|
||||
client.handle_purge_response(&reply);
|
||||
assert_eq!(client.state(), PropagationClientState::Failed);
|
||||
assert_eq!(client.received_ids, vec![vec![0xab; 32]]);
|
||||
}
|
||||
for reply in [vec![0x90], vec![0xdc, 0, 0], vec![0xdd, 0, 0, 0, 0]] {
|
||||
let (tx, _rx) = mpsc::channel(16);
|
||||
let mut client = PropagationClient::new(tx, None, None);
|
||||
client.status.state = PropagationClientState::PurgeRequested;
|
||||
client.handle_purge_response(&reply);
|
||||
assert_eq!(client.state(), PropagationClientState::Complete);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_handle_get_response_parses_messages() {
|
||||
let (tx, _rx) = mpsc::channel(16);
|
||||
|
||||
@@ -765,7 +765,10 @@ impl PropagationNode {
|
||||
) -> Option<PropagationStoreWritePlan> {
|
||||
self.reap_retired();
|
||||
let transient_id = entry.transient_id;
|
||||
if self.store.contains(&transient_id) || self.pending_write_ids.contains(&transient_id) {
|
||||
if self.store.is_destination_ignored(&entry.destination_hash)
|
||||
|| self.store.contains(&transient_id)
|
||||
|| self.pending_write_ids.contains(&transient_id)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// Python checks the current store size before inserting and permits
|
||||
@@ -837,7 +840,11 @@ impl PropagationNode {
|
||||
return false;
|
||||
}
|
||||
self.pending_write_bytes = self.pending_write_bytes.saturating_sub(size);
|
||||
let inserted = !self.store.contains(&transient_id) && self.store.insert(persisted.entry);
|
||||
// The exact live reservation already admitted this destination before
|
||||
// publication. A later ignore change must not abandon the committed
|
||||
// object outside the in-memory quota and maintenance accounting.
|
||||
let inserted =
|
||||
!self.store.contains(&transient_id) && self.store.insert_admitted(persisted.entry);
|
||||
if inserted {
|
||||
if let Some(path) = persisted.path {
|
||||
self.object_paths.insert(transient_id, path);
|
||||
@@ -1930,7 +1937,14 @@ pub(crate) mod tests {
|
||||
#[test]
|
||||
fn hosted_node_applies_ignored_destination_policy() {
|
||||
let destination = [0x44; 16];
|
||||
let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]);
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let legacy = dir.path().join("store");
|
||||
let mut node = PropagationNode::with_storage(
|
||||
PropagationNodeConfig::default(),
|
||||
[0xAA; 16],
|
||||
legacy.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
node.ignore_destination(destination);
|
||||
assert!(node.is_destination_ignored(&destination));
|
||||
|
||||
@@ -1938,11 +1952,70 @@ pub(crate) mod tests {
|
||||
blob.extend_from_slice(b"encrypted-lxmf");
|
||||
assert!(!node.accept_blob_fixture(&blob, 0));
|
||||
assert_eq!(node.message_count(), 0);
|
||||
assert!(node.pending_write_ids.is_empty());
|
||||
assert_eq!(node.pending_write_bytes, 0);
|
||||
assert_eq!(
|
||||
std::fs::read_dir(node.storage_path.as_ref().unwrap().join("objects"))
|
||||
.unwrap()
|
||||
.count(),
|
||||
0,
|
||||
"ignored admissions must publish neither objects nor active indexes"
|
||||
);
|
||||
|
||||
drop(node);
|
||||
let mut node =
|
||||
PropagationNode::with_storage(PropagationNodeConfig::default(), [0xAA; 16], legacy)
|
||||
.unwrap();
|
||||
assert_eq!(node.message_count(), 0, "rejected deposits cannot reappear");
|
||||
node.ignore_destination(destination);
|
||||
|
||||
node.unignore_destination(&destination);
|
||||
assert!(node.accept_blob_fixture(&blob, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_store_write_retains_its_admitted_destination_policy() {
|
||||
let destination = [0x44; 16];
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let legacy = dir.path().join("store");
|
||||
let mut node = PropagationNode::with_storage(
|
||||
PropagationNodeConfig::default(),
|
||||
[0xAA; 16],
|
||||
legacy.clone(),
|
||||
)
|
||||
.unwrap();
|
||||
let message = make_signed_message(destination, [0xCC; 16], "", "admitted");
|
||||
let id = message.transient_id.unwrap();
|
||||
let plan = node.plan_fixture(&message).unwrap();
|
||||
|
||||
node.ignore_destination(destination);
|
||||
let persisted = plan.persist().unwrap();
|
||||
assert!(node.commit_store_write(persisted));
|
||||
assert_eq!(node.message_count(), 1);
|
||||
assert_eq!(node.total_size(), message.data.len() + 32);
|
||||
assert_eq!(node.message_get_request(&[id]).len(), 1);
|
||||
|
||||
let mut duplicate = message.data.clone();
|
||||
duplicate.extend_from_slice(&message.stamp);
|
||||
let blob = ValidatedOpaquePropagationBlob::validate(duplicate.into(), 0).unwrap();
|
||||
let PropagationAdmission::CommittedDuplicate(check) = node.plan_opaque_admission(blob)
|
||||
else {
|
||||
panic!("previous admission retains duplicate acknowledgement authority");
|
||||
};
|
||||
check.verify().unwrap();
|
||||
let later = make_signed_message(destination, [0xCC; 16], "", "ignored");
|
||||
assert!(node.plan_fixture(&later).is_none());
|
||||
|
||||
drop(node);
|
||||
let mut node =
|
||||
PropagationNode::with_storage(PropagationNodeConfig::default(), [0xAA; 16], legacy)
|
||||
.unwrap();
|
||||
node.ignore_destination(destination);
|
||||
assert_eq!(node.message_count(), 1);
|
||||
assert_eq!(node.total_size(), message.data.len() + 32);
|
||||
assert_eq!(node.message_get_request(&[id]).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unhandled_count_is_derived_from_live_store_and_peer_handled_set() {
|
||||
let mut node = durable_test_node(PropagationNodeConfig::default(), [0xAA; 16]);
|
||||
|
||||
@@ -63,6 +63,9 @@ use lxmf_tools::lxmd_runtime::{
|
||||
use rns_identity::announce::AnnounceData;
|
||||
use rns_identity::destination::Destination;
|
||||
use rns_identity::identity::Identity;
|
||||
use rns_identity::persistence::{
|
||||
durable_create_dir_all, durable_reconcile, durable_write, validate_durable_storage_directory,
|
||||
};
|
||||
use rns_identity::ratchet::{
|
||||
ReceivedRatchet, clean_received_ratchets_dir, purge_expired_ratchets_in_memory,
|
||||
};
|
||||
@@ -1550,6 +1553,7 @@ struct DaemonCheckpoint {
|
||||
impl DaemonCheckpoint {
|
||||
fn persist(self) -> std::io::Result<()> {
|
||||
let received = self.ratchets.join("received");
|
||||
require_ratchet_directory(&received)?;
|
||||
for (hash, ratchet) in self.received {
|
||||
if !hex::decode(&hash).is_ok_and(|bytes| bytes.len() == 16) {
|
||||
return Err(std::io::Error::other("invalid ratchet destination"));
|
||||
@@ -1757,7 +1761,7 @@ impl LxmdRunner {
|
||||
>,
|
||||
) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
|
||||
let paths = LxmdPaths::new(config_dir);
|
||||
std::fs::create_dir_all(&paths.config_dir)?;
|
||||
require_storage_namespace(&paths)?;
|
||||
|
||||
let identity_path = paths.preferred_identity_path().to_path_buf();
|
||||
let identity = if identity_path.exists() {
|
||||
@@ -1785,8 +1789,6 @@ impl LxmdRunner {
|
||||
&hex::encode(lxmf_dest_hash)[..16],
|
||||
);
|
||||
|
||||
let ratchet_dir = paths.ratchets_dir.clone();
|
||||
std::fs::create_dir_all(&ratchet_dir)?;
|
||||
let wall_now = now_f64() as u64;
|
||||
let delivery_ratchets = DeliveryRatchetState::load_or_initialize(
|
||||
&identity,
|
||||
@@ -1799,7 +1801,6 @@ impl LxmdRunner {
|
||||
// Mirrors Python `Identity._clean_ratchets()`: sweep the directory at
|
||||
// startup so stale entries don't survive a restart.
|
||||
let received_dir = paths.received_ratchets_dir.clone();
|
||||
std::fs::create_dir_all(&received_dir)?;
|
||||
let removed = clean_received_ratchets_dir(&received_dir);
|
||||
if removed > 0 {
|
||||
tracing::info!(removed, "swept expired received-ratchet files at startup");
|
||||
@@ -3866,10 +3867,8 @@ impl LxmdRunner {
|
||||
let path = self
|
||||
.received_ratchets_dir
|
||||
.join(format!("{dest_hex}.ratchet"));
|
||||
let dir = self.received_ratchets_dir.clone();
|
||||
tokio::task::spawn_blocking(move || {
|
||||
std::fs::create_dir_all(&dir).ok();
|
||||
if let Err(e) = rr.save(&path) {
|
||||
if let Err(e) = rr.save_durable(&path) {
|
||||
tracing::warn!("Failed to persist received ratchet: {e}");
|
||||
}
|
||||
});
|
||||
@@ -5492,12 +5491,12 @@ impl LxmdRunner {
|
||||
|
||||
fn save_crypto_state(&self) -> std::io::Result<()> {
|
||||
let ratchet_dir = self.ratchets_dir.clone();
|
||||
std::fs::create_dir_all(&ratchet_dir)?;
|
||||
require_ratchet_directory(&ratchet_dir)?;
|
||||
let received_dir = ratchet_dir.join("received");
|
||||
require_ratchet_directory(&received_dir)?;
|
||||
|
||||
self.delivery_ratchets.save_durable(&self.identity)?;
|
||||
|
||||
let received_dir = ratchet_dir.join("received");
|
||||
std::fs::create_dir_all(&received_dir)?;
|
||||
for (hash_hex, rr) in &self.received_ratchets {
|
||||
let path = received_dir.join(format!("{hash_hex}.ratchet"));
|
||||
if !hex::decode(hash_hex).is_ok_and(|hash| hash.len() == 16) {
|
||||
@@ -5524,6 +5523,85 @@ impl LxmdRunner {
|
||||
}
|
||||
}
|
||||
|
||||
const STORAGE_NAMESPACE_BYTES: &[u8] = b"lxmd-private-namespace-v1\n";
|
||||
|
||||
fn require_ratchet_directory(path: &Path) -> std::io::Result<()> {
|
||||
let metadata = std::fs::symlink_metadata(path)?;
|
||||
if !metadata.is_dir() || metadata.file_type().is_symlink() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidInput,
|
||||
"daemon namespace must contain real directories",
|
||||
));
|
||||
}
|
||||
validate_durable_storage_directory(path).map_err(std::io::Error::other)
|
||||
}
|
||||
|
||||
fn require_storage_namespace(paths: &LxmdPaths) -> std::io::Result<()> {
|
||||
durable_reconcile(
|
||||
&paths.config_dir.join(".lxmd-namespace-ready"),
|
||||
STORAGE_NAMESPACE_BYTES,
|
||||
)
|
||||
.map_err(std::io::Error::other)?;
|
||||
for path in [
|
||||
&paths.config_dir,
|
||||
&paths.storage_dir,
|
||||
&paths.lxmf_storage_dir,
|
||||
&paths.ratchets_dir,
|
||||
&paths.received_ratchets_dir,
|
||||
] {
|
||||
require_ratchet_directory(path)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Establish/reconcile the entire private ratchet namespace before config,
|
||||
/// RNS or daemon storage users open handles. A live runner only validates this
|
||||
/// completed marker and never republishes an existing root on Windows.
|
||||
fn initialize_storage_namespace(config_dir: &Path) -> std::io::Result<()> {
|
||||
let target = std::path::absolute(config_dir)?;
|
||||
if target.join(".lxmd-namespace-ready").try_exists()? {
|
||||
require_storage_namespace(&LxmdPaths::new(&target))?;
|
||||
}
|
||||
let mut anchor = target.parent().ok_or_else(|| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidInput,
|
||||
"daemon config directory needs an outside namespace anchor",
|
||||
)
|
||||
})?;
|
||||
while !anchor.try_exists()? {
|
||||
anchor = anchor.parent().ok_or_else(|| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidInput,
|
||||
"daemon namespace has no existing anchor",
|
||||
)
|
||||
})?;
|
||||
}
|
||||
let digest = hex::encode(rns_crypto::sha::sha256(
|
||||
target.as_os_str().as_encoded_bytes(),
|
||||
));
|
||||
let witness = durable_write(
|
||||
&anchor.join(format!(".lxmd-root-{digest}.witness")),
|
||||
STORAGE_NAMESPACE_BYTES,
|
||||
)
|
||||
.map_err(std::io::Error::other)?;
|
||||
let paths = LxmdPaths::new(&target);
|
||||
for path in [
|
||||
&paths.config_dir,
|
||||
&paths.storage_dir,
|
||||
&paths.lxmf_storage_dir,
|
||||
&paths.ratchets_dir,
|
||||
&paths.received_ratchets_dir,
|
||||
] {
|
||||
durable_create_dir_all(path, &witness).map_err(std::io::Error::other)?;
|
||||
}
|
||||
durable_write(
|
||||
&target.join(".lxmd-namespace-ready"),
|
||||
STORAGE_NAMESPACE_BYTES,
|
||||
)
|
||||
.map_err(std::io::Error::other)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
pub(crate) async fn main() {
|
||||
let args = Args::parse();
|
||||
@@ -5618,6 +5696,10 @@ pub(crate) async fn main() {
|
||||
None
|
||||
};
|
||||
|
||||
if !is_control_command && let Err(error) = initialize_storage_namespace(&config_dir) {
|
||||
tracing::error!(%error, "Failed to establish private daemon storage namespace");
|
||||
std::process::exit(1);
|
||||
}
|
||||
let config_path = config_dir.join("config");
|
||||
let config = match rns_runtime::config::Config::from_file(&config_path) {
|
||||
Ok(c) => c,
|
||||
@@ -6357,6 +6439,49 @@ pub(crate) async fn main() {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn storage_namespace_fresh_restart_and_missing_parent_are_checked() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path().join("fresh/nested/config");
|
||||
initialize_storage_namespace(&root).unwrap();
|
||||
let (tx, _rx) = mpsc::channel(64);
|
||||
let first = LxmdRunner::new(DaemonConfig::default(), &root, tx, None).unwrap();
|
||||
let public = first.delivery_ratchets.ring().current_public_key();
|
||||
assert!(public.is_some());
|
||||
first.save_crypto_state().unwrap();
|
||||
drop(first);
|
||||
initialize_storage_namespace(&root).unwrap();
|
||||
let (tx, _rx) = mpsc::channel(64);
|
||||
let restarted = LxmdRunner::new(DaemonConfig::default(), &root, tx, None).unwrap();
|
||||
assert_eq!(
|
||||
restarted.delivery_ratchets.ring().current_public_key(),
|
||||
public
|
||||
);
|
||||
std::fs::remove_dir(&restarted.received_ratchets_dir).unwrap();
|
||||
assert!(restarted.save_crypto_state().is_err());
|
||||
assert!(!restarted.received_ratchets_dir.exists());
|
||||
drop(restarted);
|
||||
assert!(initialize_storage_namespace(&root).is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn storage_namespace_barrier_failure_prevents_daemon_ratchet_creation() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let root = temp.path().join("config");
|
||||
let paths = LxmdPaths::new(&root);
|
||||
std::fs::create_dir_all(&paths.lxmf_storage_dir).unwrap();
|
||||
std::fs::write(&paths.ratchets_dir, b"preserve namespace blocker").unwrap();
|
||||
assert!(initialize_storage_namespace(&root).is_err());
|
||||
let (tx, _rx) = mpsc::channel(64);
|
||||
assert!(LxmdRunner::new(DaemonConfig::default(), &root, tx, None).is_err());
|
||||
assert_eq!(
|
||||
std::fs::read(&paths.ratchets_dir).unwrap(),
|
||||
b"preserve namespace blocker"
|
||||
);
|
||||
assert!(!paths.ratchet_ring_path.exists());
|
||||
assert!(!root.join("identity").exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn direct_ticket_requires_source_verification_and_survives_restart() {
|
||||
use lxmf_core::constants::FIELD_TICKET;
|
||||
@@ -6365,6 +6490,7 @@ mod tests {
|
||||
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let (tx, _rx) = mpsc::channel(64);
|
||||
initialize_storage_namespace(temp.path()).unwrap();
|
||||
let mut runner = LxmdRunner::new(DaemonConfig::default(), temp.path(), tx, None).unwrap();
|
||||
let deliveries = Arc::new(std::sync::atomic::AtomicUsize::new(0));
|
||||
let observed = deliveries.clone();
|
||||
@@ -6526,6 +6652,7 @@ mod tests {
|
||||
assert!(config.propagation_enabled);
|
||||
let shutdown = ShutdownSignal::new();
|
||||
let rns_config = config_dir.join("rns");
|
||||
initialize_storage_namespace(&config_dir).unwrap();
|
||||
eprintln!("PN_RECEIPT_START initializing Reticulum");
|
||||
let handle = rns_runtime::reticulum::init(
|
||||
Some(rns_config.to_str().unwrap()),
|
||||
@@ -6595,6 +6722,7 @@ mod tests {
|
||||
std::process::id()
|
||||
));
|
||||
let (tx, _rx) = mpsc::channel(64);
|
||||
initialize_storage_namespace(&temp).unwrap();
|
||||
let mut runner = LxmdRunner::new(DaemonConfig::default(), &temp, tx, None).unwrap();
|
||||
runner.ensure_link_delivery();
|
||||
let (send_tx, mut send_rx) = mpsc::channel(8);
|
||||
@@ -7035,6 +7163,7 @@ mod tests {
|
||||
enforce_stamps,
|
||||
..Default::default()
|
||||
};
|
||||
initialize_storage_namespace(&temp).unwrap();
|
||||
let mut runner = LxmdRunner::new(config, &temp, tx, None).expect("runner");
|
||||
let raw = runner.create_announce_packet().expect("delivery announce");
|
||||
let (_, announce) = unpack_announce(&raw);
|
||||
@@ -7413,6 +7542,7 @@ mod tests {
|
||||
std::process::id()
|
||||
));
|
||||
let (tx, _rx) = mpsc::channel::<TransportMessage>(64);
|
||||
initialize_storage_namespace(&temp).unwrap();
|
||||
let mut runner = LxmdRunner::new(DaemonConfig::default(), &temp, tx, None).expect("runner");
|
||||
|
||||
let deliveries = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
Reference in new issue
Block a user