lxmf: require durable propagation acceptance and immutable messages

This commit is contained in:
DeFiDude committed 2026-10-13 00:32:49 -06:00
1 parent 74dc13f687
commit 66e22cb41f
49 files changed
+13493 -4983

No files matched your search

+1 -1
View File
@@ -10,7 +10,7 @@ permissions:
contents: read
env:
RSLXMF_RSRETICULUM_COMMIT: 799e946ac997f388395fec4e8c49ea55a03e5bc8
RSLXMF_RSRETICULUM_COMMIT: 817a640ed1e11e3ff3e0ff048d8de13662bfdd78
jobs:
api-compat:
+2 -2
View File
@@ -24,8 +24,8 @@ env:
RELEASE_TAG: ${{ github.event.inputs.tag_name || github.ref_name }}
PACKAGE_ROOT: rsLXMF
LXMF_BINS: lxmd-rs
RSLXMF_RSRETICULUM_VERSION: 1.3.0
RSLXMF_RSRETICULUM_COMMIT: 799e946ac997f388395fec4e8c49ea55a03e5bc8
RSLXMF_RSRETICULUM_VERSION: 1.4.0
RSLXMF_RSRETICULUM_COMMIT: 817a640ed1e11e3ff3e0ff048d8de13662bfdd78
jobs:
verify:
+9
View File
@@ -2,6 +2,15 @@
## Unreleased
## 1.4.0 - 2026-10-12
- Preserve each signed message exactly as received, including binary text and custom fields, and reject ambiguous field definitions.
- Remove downloaded messages from a propagation node only after the receiving application confirms durable acceptance. Failed items remain available for retry.
- Keep propagation messages encrypted in storage, quarantine untrusted legacy entries, and require storage recovery before a node becomes available.
- Keep stamps, encryption, and ticket state consistent across retries and restarts, and reject undecipherable messages instead of treating them as plaintext.
- Bound background delivery work, keep node downloads responsive during storage operations, and defer excess downloads without dropping valid messages during busy periods.
- Updated message construction and delivery APIs and require rsReticulum `~1.4.0`. This source-breaking release uses the `~1.4.0` compatibility line.
## 1.3.0 - 2026-10-12
### Added
Generated
+29 -14
View File
@@ -138,7 +138,7 @@ version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f"
dependencies = [
"objc2",
"objc2 0.5.2",
]
[[package]]
@@ -643,11 +643,13 @@ checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
[[package]]
name = "lxmf-core"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"base64",
"bytes",
"hex",
"jni",
"objc2 0.6.5",
"proptest",
"rand 0.8.5",
"rmp",
@@ -670,7 +672,7 @@ dependencies = [
[[package]]
name = "lxmf-tools"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"base64",
"bytes",
@@ -688,6 +690,7 @@ dependencies = [
"tokio",
"tracing",
"tracing-subscriber",
"zeroize",
]
[[package]]
@@ -783,6 +786,15 @@ dependencies = [
"objc2-encode",
]
[[package]]
name = "objc2"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"
dependencies = [
"objc2-encode",
]
[[package]]
name = "objc2-core-bluetooth"
version = "0.2.2"
@@ -790,7 +802,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a644b62ffb826a5277f536cf0f701493de420b13d40e700c452c36567771111"
dependencies = [
"bitflags 2.11.0",
"objc2",
"objc2 0.5.2",
"objc2-foundation",
]
@@ -809,7 +821,7 @@ dependencies = [
"bitflags 2.11.0",
"block2",
"libc",
"objc2",
"objc2 0.5.2",
]
[[package]]
@@ -1052,7 +1064,7 @@ dependencies = [
[[package]]
name = "rns-crypto"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"aes",
"cbc",
@@ -1070,9 +1082,10 @@ dependencies = [
[[package]]
name = "rns-identity"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"hex",
"libc",
"rand 0.8.5",
"rmp-serde",
"rmpv",
@@ -1080,6 +1093,7 @@ dependencies = [
"rns-wire",
"serde",
"serde_bytes",
"sha2",
"thiserror 2.0.18",
"tracing",
"windows-sys 0.61.2",
@@ -1088,7 +1102,7 @@ dependencies = [
[[package]]
name = "rns-interface"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"bytes",
"hex",
@@ -1097,7 +1111,7 @@ dependencies = [
"libc",
"md-5",
"mio",
"objc2",
"objc2 0.5.2",
"objc2-core-bluetooth",
"objc2-foundation",
"rand 0.8.5",
@@ -1117,7 +1131,7 @@ dependencies = [
[[package]]
name = "rns-link"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"hex",
"rand 0.8.5",
@@ -1132,7 +1146,7 @@ dependencies = [
[[package]]
name = "rns-protocol"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"bzip2",
"hex",
@@ -1141,6 +1155,7 @@ dependencies = [
"rns-crypto",
"rns-link",
"rns-wire",
"serde",
"thiserror 2.0.18",
"tokio",
"tracing",
@@ -1148,7 +1163,7 @@ dependencies = [
[[package]]
name = "rns-runtime"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"bytes",
"hex",
@@ -1175,7 +1190,7 @@ dependencies = [
[[package]]
name = "rns-transport"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"bytes",
"hex",
@@ -1194,7 +1209,7 @@ dependencies = [
[[package]]
name = "rns-wire"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"rns-crypto",
"sha2",
+11 -11
View File
@@ -6,25 +6,25 @@ members = [
]
[workspace.package]
version = "1.3.0"
version = "1.4.0"
edition = "2024"
license = "AGPL-3.0-or-later"
rust-version = "1.89"
[workspace.dependencies]
# Reticulum crates from a sibling rsReticulum checkout during development.
rns-crypto = { path = "../rsReticulum/crates/rns-crypto", version = "~1.3.0" }
rns-wire = { path = "../rsReticulum/crates/rns-wire", version = "~1.3.0" }
rns-identity = { path = "../rsReticulum/crates/rns-identity", version = "~1.3.0" }
rns-link = { path = "../rsReticulum/crates/rns-link", version = "~1.3.0" }
rns-protocol = { path = "../rsReticulum/crates/rns-protocol", version = "~1.3.0" }
rns-transport = { path = "../rsReticulum/crates/rns-transport", version = "~1.3.0" }
rns-runtime = { path = "../rsReticulum/crates/rns-runtime", version = "~1.3.0" }
rns-interface = { path = "../rsReticulum/crates/rns-interface", version = "~1.3.0" }
rns-crypto = { path = "../rsReticulum/crates/rns-crypto", version = "~1.4.0" }
rns-wire = { path = "../rsReticulum/crates/rns-wire", version = "~1.4.0" }
rns-identity = { path = "../rsReticulum/crates/rns-identity", version = "~1.4.0" }
rns-link = { path = "../rsReticulum/crates/rns-link", version = "~1.4.0" }
rns-protocol = { path = "../rsReticulum/crates/rns-protocol", version = "~1.4.0" }
rns-transport = { path = "../rsReticulum/crates/rns-transport", version = "~1.4.0" }
rns-runtime = { path = "../rsReticulum/crates/rns-runtime", version = "~1.4.0" }
rns-interface = { path = "../rsReticulum/crates/rns-interface", version = "~1.4.0" }
# Workspace LXMF crates
lxmf-core = { path = "crates/lxmf-core", version = "1.3.0" }
lxmf-tools = { path = "crates/lxmf-tools", version = "1.3.0" }
lxmf-core = { path = "crates/lxmf-core", version = "~1.4.0" }
lxmf-tools = { path = "crates/lxmf-tools", version = "~1.4.0" }
# Encoding
base64 = "0.22"
+155 -15
View File
@@ -79,6 +79,12 @@ dependencies = [
"cipher",
]
[[package]]
name = "cesu8"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"
[[package]]
name = "cfg-if"
version = "1.0.4"
@@ -95,6 +101,16 @@ dependencies = [
"inout",
]
[[package]]
name = "combine"
version = "4.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e"
dependencies = [
"bytes",
"memchr",
]
[[package]]
name = "const-oid"
version = "0.9.6"
@@ -264,6 +280,48 @@ dependencies = [
"generic-array",
]
[[package]]
name = "jni"
version = "0.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6df18c2e3db7e453d3c6ac5b3e9d5182664d28788126d39b91f2d1e22b017ec"
dependencies = [
"cesu8",
"combine",
"jni-sys 0.3.1",
"log",
"thiserror 1.0.69",
"walkdir",
]
[[package]]
name = "jni-sys"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"
dependencies = [
"jni-sys 0.4.1",
]
[[package]]
name = "jni-sys"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"
dependencies = [
"jni-sys-macros",
]
[[package]]
name = "jni-sys-macros"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"
dependencies = [
"quote",
"syn 2.0.119",
]
[[package]]
name = "libbz2-rs-sys"
version = "0.2.5"
@@ -285,13 +343,21 @@ dependencies = [
"scopeguard",
]
[[package]]
name = "log"
version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
[[package]]
name = "lxmf-core"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"base64",
"bytes",
"hex",
"jni",
"objc2",
"rand",
"rmp",
"rmp-serde",
@@ -304,7 +370,7 @@ dependencies = [
"rns-wire",
"serde",
"sha2",
"thiserror",
"thiserror 2.0.20",
"tokio",
"tracing",
"unicode-normalization",
@@ -317,6 +383,12 @@ dependencies = [
"lxmf-core",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "mio"
version = "1.2.3"
@@ -337,6 +409,21 @@ dependencies = [
"autocfg",
]
[[package]]
name = "objc2"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"
dependencies = [
"objc2-encode",
]
[[package]]
name = "objc2-encode"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
[[package]]
name = "once_cell"
version = "1.21.4"
@@ -474,11 +561,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a4e1d4b9b938a26d2996af33229f0ca0956c652c1375067f0b45291c1df8417"
dependencies = [
"rmp",
"serde",
"serde_bytes",
]
[[package]]
name = "rns-crypto"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"aes",
"cbc",
@@ -489,16 +578,17 @@ dependencies = [
"rand_core",
"sha2",
"subtle",
"thiserror",
"thiserror 2.0.20",
"x25519-dalek",
"zeroize",
]
[[package]]
name = "rns-identity"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"hex",
"libc",
"rand",
"rmp-serde",
"rmpv",
@@ -506,7 +596,8 @@ dependencies = [
"rns-wire",
"serde",
"serde_bytes",
"thiserror",
"sha2",
"thiserror 2.0.20",
"tracing",
"windows-sys",
"zeroize",
@@ -514,7 +605,7 @@ dependencies = [
[[package]]
name = "rns-link"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"hex",
"rand",
@@ -522,14 +613,14 @@ dependencies = [
"rns-crypto",
"rns-identity",
"rns-wire",
"thiserror",
"thiserror 2.0.20",
"tracing",
"zeroize",
]
[[package]]
name = "rns-protocol"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"bzip2",
"hex",
@@ -538,14 +629,15 @@ dependencies = [
"rns-crypto",
"rns-link",
"rns-wire",
"thiserror",
"serde",
"thiserror 2.0.20",
"tokio",
"tracing",
]
[[package]]
name = "rns-transport"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"bytes",
"hex",
@@ -557,18 +649,18 @@ dependencies = [
"rns-wire",
"serde",
"subtle",
"thiserror",
"thiserror 2.0.20",
"tokio",
"tracing",
]
[[package]]
name = "rns-wire"
version = "1.3.0"
version = "1.4.0"
dependencies = [
"rns-crypto",
"sha2",
"thiserror",
"thiserror 2.0.20",
]
[[package]]
@@ -580,6 +672,15 @@ dependencies = [
"semver",
]
[[package]]
name = "same-file"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
dependencies = [
"winapi-util",
]
[[package]]
name = "scopeguard"
version = "1.2.0"
@@ -716,13 +817,33 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
dependencies = [
"thiserror-impl 1.0.69",
]
[[package]]
name = "thiserror"
version = "2.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec86235f5fcc2a73650310756d2ac5b138a5780bbbdfae3eeccec992c435ba4f"
dependencies = [
"thiserror-impl",
"thiserror-impl 2.0.20",
]
[[package]]
name = "thiserror-impl"
version = "1.0.69"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
@@ -837,12 +958,31 @@ version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "walkdir"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
dependencies = [
"same-file",
"winapi-util",
]
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "winapi-util"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys",
]
[[package]]
name = "windows-link"
version = "0.2.1"
+29
View File
@@ -57,3 +57,32 @@ pub mod delivery_ownership {
});
}
}
/// Reviewed immutable construction, full-width keys and source-bound verification.
pub mod immutable_messages {
use lxmf_core::message_api::{
DeliveryMethod, FieldId, LxMessage, LxMessageDraft, MessageError, RecipientStamp,
VerifiedLxMessage,
};
pub fn with_external_signer<F, E>(signer: F) -> Result<LxMessage, MessageError>
where
F: FnOnce(&[u8]) -> Result<[u8; 64], E>,
E: std::fmt::Display,
{
let mut draft =
LxMessageDraft::new([1; 16], [2; 16], "title", "content", DeliveryMethod::Direct)?;
draft.set_field(FieldId::from(u64::MAX), vec![1, 2])?;
draft.set_msgpack_field(FieldId::from(i64::MIN), vec![0x91, 0x01])?;
let signed = draft.sign_with(signer)?;
let _id = signed.message_id();
signed.finalize(Some(RecipientStamp::Ticket([0; 16])))
}
pub fn inspect<'a>(
message: &'a LxMessage,
public_key: &[u8; 64],
) -> Result<VerifiedLxMessage<'a>, MessageError> {
let _same_owner = message.wire_owned();
let _custom = message.fields().get(u64::MAX);
message.verify(public_key)
}
}
+162
View File
@@ -0,0 +1,162 @@
# 1.4 source migration (unreleased)
Messages now retain the exact signed bytes received or finalized for sending.
Verification, storage, and delivery metadata cannot change those bytes. The
`message_api` and `message` module paths export the same types.
## Construct, sign, then finalize
```rust
use lxmf_core::message_api::{DeliveryMethod, LxMessageDraft};
use rns_crypto::ed25519::Ed25519PrivateKey;
let mut draft = LxMessageDraft::new(
[0x11; 16], [0x22; 16], "Hello", "A message", DeliveryMethod::Direct,
)?;
draft.set_field(0x105_u64, vec![1, 2, 3])?;
// When using a router, prepare and durably commit its reply-ticket intent here.
let signed = draft.sign(&Ed25519PrivateKey::generate())?;
let stamp = signed.generate_recipient_stamp()?;
let message = signed.finalize(stamp)?;
let bytes = message.wire_bytes();
# Ok::<(), lxmf_core::message_api::MessageError>(())
```
Use `sign_with` for an external or hardware signer. Both signing methods consume
the draft. Signing refuses a router-prepared ticket whose persistence intent is
still pending. `SignedLxMessage` exposes the stable message ID for recipient
stamp work, but cannot be sent. `finalize(None)` explicitly chooses no recipient
stamp. A finalized message has no content setters, signing method, or assignable
hash/signature/stamp. To change content, construct a new draft and explicitly
copy the desired fields; reply tickets and authentication state are not copied
implicitly. Propagation encryption/stamps belong to their separate send owner.
## Read the immutable message
| Previous access | Replacement |
| --- | --- |
| `message.destination_hash`, `source_hash` | `destination_hash()`, `source_hash()` |
| `message.hash` or `message.message_id` | `message_id()`; always present |
| `message.signature` | `signature()`; always present |
| `message.title`, `content` | `title_text()`, `content_text()` return `Cow<str>`; `*_bytes()` preserve exact bytes |
| `message.timestamp` | `timestamp()` |
| `message.fields`, `msgpack_field_ids` | `fields()` and coherent `FieldValueRef` |
| `message.stamp` | `recipient_stamp()` |
| `message.signature_validated` | successful source-bound `verify` capability |
| `message.wire_payload` | `wire_bytes()` for the complete image |
Mutable delivery metadata remains available through `MessageMetadata` and
field access (`message.method`, `message.progress`, etc.). It cannot alter
content or create authentication authority.
`wire_bytes()` borrows the complete image; `wire_owned()` cheaply shares its
ownership for asynchronous writes. `pack()` explicitly copies it into a Vec.
`pack_payload()` copies the original payload. `unpack_owned(Bytes, limits)`
takes ownership without copying; `unpack(&[u8])` makes a convenience copy.
Container and paper exports preserve these bytes. Repeated verification is pure.
`verify(&full_reticulum_public_key)` checks that the complete 64-byte public key
binds the claimed `lxmf.delivery` source, then verifies the signature. It returns
a private-construction `VerifiedLxMessage` for sender-authorized operations such
as ticket learning. `verify_signature(&ed25519_key)` remains available for
detached diagnostics, but does not establish source identity. Parsing and an
unknown sender are not authenticated-sender status.
## Fields and profiles
`FieldId` preserves integers from `i64::MIN` through `u64::MAX`. Nonnegative IDs
serialize as MessagePack unsigned64; negative IDs as signed64. Equivalent
positive signed and unsigned integer encodings compare equal. Outer duplicate
IDs are rejected, including alternative encodings of the same number. IDs above
255 and negative IDs remain custom keys and never alias a standard field.
`set_field` emits a binary value. `set_msgpack_field` accepts exactly one validated
encoded MessagePack value. `set_field_value` accepts their coherent `FieldValue`
representation. `FieldValueRef::encoded()` exposes exact encoded bytes;
`as_binary()` unwraps only binary. Binary bytes that happen to look like a map
or array do not become structured values. Recognized schema readers can use
`unique_map()` to reject duplicate integer/text keys before acting; unknown
nested values remain opaque. `MessagePayload` is a semantic DTO, not an archive
or signature source.
The host default profile permits 4,096 outer fields and 134,217,727 complete
wire bytes. Use `new_with_limits` and `unpack_owned` with the same explicit
`MessageDecodeLimits` when selecting another local policy. Construction checks
count and exact size before signing and finalization, including stamp framing.
These are parser/construction ceilings, not transport promises: Resource segment
limits, metadata, encryption and propagation wrapping impose separate admission
checks. The embedded profile retains 64 fields and depth8; host-valid custom
messages are not automatically compatible with every device.
Old corrupted files are never silently repaired or re-signed. A hash-shaped
filename that disagrees with its decoded message ID returns a distinct error;
the file is retained. Restore original bytes from a trusted backup when available.
Unknown sender keys cannot establish whether an old signature is valid.
Use the reviewed compatible minor line (for example `~1.4.0`) or an exact source
revision when migrating dependents together. A default caret requirement permits
subsequent minor lines. Do not mix dependent code still using mutable messages
with this API.
## Router, propagation, and asynchronous ownership
`prepare_outbound(&mut draft)` returns an `OutboundTicketIntent`; persist it
through the intended durable state store before signing. A pending intent blocks
the exact draft's signer. `submit_signed` takes a `SignedLxMessage` and handles
recipient-stamp work before finalization; `defer_stamp` and the deferred map also
own signed messages. The former mutable `get_stamp` work belongs to
`SignedLxMessage::generate_recipient_stamp`, while frozen-message stamp checks
are read-only and return a result for the current policy.
`learn_ticket_from_inbound` takes a successful `VerifiedLxMessage`. When a worker
must retain authentication across an asynchronous handoff, use `to_owned()` and
later `OwnedVerifiedLxMessage::as_verified()`. The owned capability shares the
original bytes and does not expose mutable authenticated state.
Replace `pack_propagated_encrypted*` with `PropagationEnvelope` in the
`propagation_send` module. It owns the frozen message, encrypted blob, exact TID
and PN stamp. Reuse that envelope for retries; regenerate only the work whose
policy changed. The old message `transient_id` and `propagation_stamp` fields no
longer exist. `PendingDelivery.message` is a retained delivery owner that can
release payload bytes when an idle Link only needs metadata/receipt state.
Replace `take_received_messages` with `take_downloaded_messages`. Keep each
leased image and admission token until validation and durable local commit;
resolve the token with the explicit disposition and durable receipt. A fetched
message or Resource proof is not permission to purge remote data.
Hosted propagation accepts a validated opaque encrypted/stamped blob through
`ValidatedOpaquePropagationBlob` and `plan_opaque_admission`, followed by the
plan's durable persistence and exact commit. Plain `accept_message`,
`accept_propagated_blob`, their old planning variants and sync plaintext
admission are removed: plaintext signatures are not relay storage authority.
Use a durable node store and follow the [relay store migration](relay-store-v2.md).
A nondurable `PropagationNode::new` cannot acknowledge relay storage.
Hosted `/get` handlers must use the bounded deferred request API in
`rns_runtime::LinkManager`, after installing its exact endpoint dispatch handle.
Check the handler registration result. Retain `DeferredRequestResponder` inside
the actual blocking worker through store planning, durable purge and verified
file reads; cancellation of an async caller must not detach uncharged I/O.
Pass `response_byte_limit()` to both `handle_get_request_bounded` and
`into_response_with_served_count_bounded`, using the configured propagation
transfer ceiling when registering the handler. These methods reject malformed
requests before purge, deduplicate wants, preserve complete-message accounting
and build one bounded response. An absent client limit still obeys the local
ceiling. The runtime fences responses to the original Link generation and keeps
Resource credits until the transfer releases its data. `Sent` acknowledges
queue acceptance or Resource initiation, not remote delivery.
`unpack_propagation_wrapper_owned(Bytes, limit)` returns shared `Bytes` payloads
and checks framing/counts before allocation. The Vec-returning compatibility
helper still copies explicitly. `FieldValueRef::from_encoded` validates exactly
one borrowed value, and `as_text` accepts UTF8 MessagePack text only; binary data
is not silently interpreted. Use `unique_map` before acting on recognized map
keys. Text/media projections borrow where possible; repaired UTF8 allocates only
the exact replacement length.
The API ledger retains its original compatibility floor and lists exact removed
rendered lines. Metadata fields moved under `MessageMetadata` retain ordinary
field access through Deref; duplicate `message_api` snapshot paths describe the
same type migration. No unrelated API removal is waived.
+130
View File
@@ -0,0 +1,130 @@
# Relay store migration
Relay nodes now admit only validated opaque propagation data to a durable store.
A packet proof follows complete validation and acknowledged durable admission.
Resource completion still means transport completion; it does not certify the
receiver's application storage. Ordinary message archives are separate from
relay storage and must never be copied into it.
## Startup and recovery
A new store can initialize automatically. An existing legacy directory requires
explicit offline migration. An incomplete migration, invalid committed record,
unsupported filesystem, or unavailable storage prevents hosting. Daemons fail
startup when required relay storage is unavailable. Applications retain the
user's hosting preference but show hosting as unavailable until recovery succeeds.
There is no automatic in-memory fallback for a durable host.
Stop every process that can write the store, including service supervisors and
scheduled restarts. Then run the candidate daemon against the correct config:
```sh
lxmd-rs --config /path/to/config --migrate-propagation-store --relay-writers-stopped
```
Check `lxmd-rs --help` for the config-path option supported by your build. The
writer-stopped flag is an explicit assertion that supervisors have been stopped.
The tool also holds the store's OS lock and refuses when it finds another known
Ratspeak/LXMF daemon process, or cannot enumerate processes. Older binaries do not
honor the new lock; manually restarting one while migration runs is unsupported.
The process-name check cannot discover every renamed or custom relay program.
On iOS and Android, use the application's inbox recovery action for its private
store. The app first stops and joins its hosting and sync workers. Recovery
checks native application ownership and takes the same exclusive store lock;
it does not run the desktop process-list command or accept arbitrary external
directories. iOS recovery is restricted to the main app's private data container,
excluding extensions and shared app groups. Android recovery additionally
requires an exclusive app UID, the default app process, and no declared secondary
processes. Shared storage, shared UIDs and unverified ownership remain unavailable
for automatic recovery. Keep the original files and resolve the ownership or
storage error before retrying; do not remove the guard or copy archives into the
live store.
The migrator inventories relative paths, lengths and SHA-256 hashes before
moving anything. Symbolic links, special files, changed inventory and conflicting
unowned destinations stop migration without overwriting originals. It preserves
the legacy directory as `<store>.legacy-quarantine`, writes a regular-file guard
at the old path, and creates `<store>.v2`. The sibling `<store>.migration` journal
records every transition. Interrupted runs resume through the same command;
do not remove journals or guards to force startup. Windows directory publication
uses recorded sibling moves rather than inferring durability from existence.
The completion report gives the number and size of preserved files. Legacy
files are not offered, served, or counted as live relay messages. Their apparent
encryption shape, filename, previous app version, or old directory location does
not establish opaque-ingress provenance. Migration never automatically deletes
or expires the archive.
## Explicitly trusted recovery
Recovery requires independent, per-entry evidence of the original opaque
propagation ingress. A directory-wide assertion is insufficient. An operator
can supply a MessagePack named-map `TrustedRecoveryManifest` with these fields:
| Field | Value |
| --- | --- |
| `version` | `2` |
| `provenance` | Nonempty explanation of the independently checked evidence |
| `entries` | Array of the exact authorized records |
| Entry `archive_relative_path` | Relative path from the committed inventory |
| Entry `content_hash` | SHA-256 of the complete stored bytes, as 32 integer bytes |
| Entry `transient_id` | SHA-256 of destination+ciphertext, excluding a trailing PN stamp |
| Entry `stamped` | Whether the file includes the 32-byte PN stamp |
| Entry `stored_at` | Finite, nonnegative receipt timestamp |
Use the exported Rust structs and `rmp_serde::to_vec_named` to encode the record.
Review the manifest and independently record its SHA-256. Supply that approved
digest separately; merely hashing an unreviewed manifest does not establish trust.
```sh
lxmd-rs --config /path/to/config --migrate-propagation-store --relay-writers-stopped \
--recover-propagation-manifest /path/to/recovery.msgpack \
--recovery-manifest-sha256 APPROVED_SHA256_HEX
```
The importer checks the complete archive against its committed inventory, every
selected path/hash/TID, ciphertext framing, positive plaintext rejection, actual
stamp strength, and current size/quota policy before publication. Unstamped
recovery requires both explicit provenance and a zero minimum stamp policy.
Entries without evidence remain quarantined. Repeating the exact approved import
is idempotent; it cannot replace a different first accepted image. A failed IO
can leave a valid subset committed, so retain the manifest and retry.
## Library integration
Use `PropagationNode::with_storage` for a durable host. Keep readiness bound to
the active identity generation and drain the old generation's workers before
opening or migrating its store. `begin_offline_migration` returns the retained
writer-exclusion guard used by both migration and trusted recovery.
Mobile embeddings use `begin_ios_container_migration` or
`begin_android_container_migration` on the corresponding target. The Android
function takes the attached worker's JNI environment and real platform Context;
it obtains package, UID, component and data-directory metadata from the framework.
Neither API accepts a caller-provided container root or a flag to bypass ownership
checks. Hold the identity/session lifecycle guard through the actual blocking
operation and restart, including after the invoking UI task is canceled. An app
that launches additional native relay writers must stop and join those writers
too; the container boundary does not replace ownership of current-process work.
For ingress, validate a complete packet batch before writing anything, then use
`plan_opaque_admission`. Run `Reserved(plan).persist()` on a blocking worker and
commit its returned capability to that same node. Await `Pending` outside the
bounded storage-worker slots. `CommittedDuplicate(check)` is only a plan: call
`check.verify()` on a blocking worker before treating it as durable. Keep the
original typed Link receipt alive through all these operations. A dropped worker
result yields no proof; retry reuses the first complete indexed image.
The private format publishes an immutable object and provenance record, then a
per-TID active index. Unindexed remnants are never served. A durable deletion
intent revokes eligibility before cleanup; restart resumes cleanup. Purge and
maintenance operate on a particular admission path, so a stale plan cannot
delete a later admission of the same TID. Resolve `GetServePlan` and maintenance
plans off the actor; a failed purge intent cannot return an empty success array.
The old-path guard prevents ordinary reopening of that exact legacy directory.
It cannot revoke objects already held in an old process or prevent an old daemon
from using another path or its in-memory fallback. If rolling back software,
keep **both relay hosting and propagation sync disabled**. Preserve the archive,
journal, guard and v2 store; never copy them back to the legacy layout.
File diff suppressed because it is too large. Load diff
+5
View File
@@ -72,6 +72,7 @@ pub fn lxmf_tools::daemon::PythonLxmdConfig::from_config(&rns_runtime::config::C
pub fn lxmf_tools::daemon::create_router(&lxmf_tools::daemon::DaemonConfig) -> lxmf_core::router::LxmRouter
pub fn lxmf_tools::daemon::create_router_with_transport(&lxmf_tools::daemon::DaemonConfig, tokio::sync::mpsc::bounded::Sender<rns_transport::messages::TransportMessage>) -> lxmf_core::router::LxmRouter
pub fn lxmf_tools::daemon::execute_on_inbound(&str, &str) -> core::io::error::Result<()>
pub fn lxmf_tools::daemon::execute_on_inbound_with_event(&str, &str, &str) -> core::io::error::Result<()>
pub fn lxmf_tools::daemon::persist_inbound_and_execute(&std::path::Path, &[u8], core::option::Option<&str>) -> core::io::error::Result<()>
pub mod lxmf_tools::lxmd_cli
pub enum lxmf_tools::lxmd_cli::SendMethod
@@ -84,10 +85,14 @@ pub struct lxmf_tools::lxmd_cli::Args
pub lxmf_tools::lxmd_cli::Args::config: core::option::Option<alloc::string::String>
pub lxmf_tools::lxmd_cli::Args::exampleconfig: bool
pub lxmf_tools::lxmd_cli::Args::identity: core::option::Option<std::path::PathBuf>
pub lxmf_tools::lxmd_cli::Args::migrate_propagation_store: bool
pub lxmf_tools::lxmd_cli::Args::on_inbound: core::option::Option<alloc::string::String>
pub lxmf_tools::lxmd_cli::Args::peers: bool
pub lxmf_tools::lxmd_cli::Args::propagation_node: bool
pub lxmf_tools::lxmd_cli::Args::quiet: u8
pub lxmf_tools::lxmd_cli::Args::recover_propagation_manifest: core::option::Option<std::path::PathBuf>
pub lxmf_tools::lxmd_cli::Args::recovery_manifest_sha256: core::option::Option<alloc::string::String>
pub lxmf_tools::lxmd_cli::Args::relay_writers_stopped: bool
pub lxmf_tools::lxmd_cli::Args::remote: core::option::Option<alloc::string::String>
pub lxmf_tools::lxmd_cli::Args::rnsconfig: core::option::Option<alloc::string::String>
pub lxmf_tools::lxmd_cli::Args::send: core::option::Option<alloc::vec::Vec<alloc::string::String>>
+50 -15
View File
@@ -4,7 +4,7 @@
"packages": [
{
"name": "lxmf-core",
"version": "1.3.0",
"version": "1.4.0",
"rustVersion": "1.89",
"edition": "2024",
"features": {},
@@ -95,7 +95,9 @@
"requirement": "^1",
"optional": false,
"defaultFeatures": true,
"features": [],
"features": [
"with-serde"
],
"sourceKind": "registry"
},
{
@@ -103,7 +105,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -114,7 +116,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -125,7 +127,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -136,7 +138,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -147,7 +149,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -158,7 +160,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -233,12 +235,34 @@
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "jni",
"rename": null,
"kind": null,
"target": "cfg(target_os = \"android\")",
"requirement": "^0.19",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "objc2",
"rename": null,
"kind": null,
"target": "cfg(target_os = \"ios\")",
"requirement": "^0.6",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
}
]
},
{
"name": "lxmf-tools",
"version": "1.3.0",
"version": "1.4.0",
"rustVersion": "1.89",
"edition": "2024",
"features": {},
@@ -306,7 +330,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "^1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -328,7 +352,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -339,7 +363,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -350,7 +374,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [
@@ -363,7 +387,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -374,7 +398,7 @@
"rename": null,
"kind": null,
"target": null,
"requirement": "~1.3.0",
"requirement": "~1.4.0",
"optional": false,
"defaultFeatures": true,
"features": [],
@@ -425,6 +449,17 @@
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
},
{
"name": "zeroize",
"rename": null,
"kind": null,
"target": null,
"requirement": "^1",
"optional": false,
"defaultFeatures": true,
"features": [],
"sourceKind": "registry"
}
]
}
+75 -5
View File
@@ -24,8 +24,8 @@
"tier": "candidate-stable",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/lxmf-core.txt",
"itemCount": 1647,
"sha256": "b7b1d52406e2c97a204a5fb567abc6a216733594a7abd63797ff55a70d8d3b73"
"itemCount": 2208,
"sha256": "e25c207398c8124dbd73cd800d2eb53d5f5615ae47485e654dc39c56d955f653"
},
{
"name": "lxmf-tools",
@@ -33,8 +33,78 @@
"tier": "tool-internal",
"compatibility": "reviewed-snapshot",
"snapshot": "api/snapshots/lxmf-tools.txt",
"itemCount": 185,
"sha256": "0427d0fab38f8061cbf7f11b701f29f438490478f133524b0a8e4e7cfe6f3924"
"itemCount": 190,
"sha256": "c8591cf56d1d315da43ecab8149057447ff02726fa371e01439a4106be45976f"
}
]
],
"approvedBreakingChanges": {
"releaseLine": "1.4",
"migrationGuide": "api/migrations/1.4.md",
"removed": {
"lxmf-core": [
"pub fn lxmf_core::message::LxMessage::compute_hash(&mut self) -> core::result::Result<[u8; 32], lxmf_core::message::MessageError>",
"pub fn lxmf_core::message::LxMessage::get_field(&self, u8) -> core::option::Option<&alloc::vec::Vec<u8>>",
"pub fn lxmf_core::message::LxMessage::get_stamp(&mut self) -> core::option::Option<alloc::vec::Vec<u8>>",
"pub fn lxmf_core::message::LxMessage::new([u8; 16], [u8; 16], &str, &str, lxmf_core::constants::DeliveryMethod) -> Self",
"pub fn lxmf_core::message::LxMessage::pack_propagated_encrypted<F>(&mut self, F) -> core::result::Result<(alloc::vec::Vec<u8>, lxmf_core::types::PropagationTransientId), lxmf_core::message::MessageError> where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result<alloc::vec::Vec<u8>, lxmf_core::message::MessageError>",
"pub fn lxmf_core::message::LxMessage::pack_propagated_encrypted_with_stamp<F>(&mut self, F, u8) -> core::result::Result<(alloc::vec::Vec<u8>, lxmf_core::types::PropagationTransientId, u32), lxmf_core::message::MessageError> where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result<alloc::vec::Vec<u8>, lxmf_core::message::MessageError>",
"pub fn lxmf_core::message::LxMessage::set_audio_field(&mut self, u8, &[u8]) -> core::result::Result<(), lxmf_core::message::MessageError>",
"pub fn lxmf_core::message::LxMessage::set_field(&mut self, u8, alloc::vec::Vec<u8>)",
"pub fn lxmf_core::message::LxMessage::set_file_attachment_field(&mut self, &str, &[u8]) -> core::result::Result<(), lxmf_core::message::MessageError>",
"pub fn lxmf_core::message::LxMessage::set_image_field(&mut self, &str, &[u8]) -> core::result::Result<(), lxmf_core::message::MessageError>",
"pub fn lxmf_core::message::LxMessage::set_msgpack_field(&mut self, u8, alloc::vec::Vec<u8>) -> core::result::Result<(), lxmf_core::message::MessageError>",
"pub fn lxmf_core::message::LxMessage::sign(&mut self, &rns_crypto::ed25519::Ed25519PrivateKey) -> core::result::Result<(), lxmf_core::message::MessageError>",
"pub fn lxmf_core::message::LxMessage::sign_with<F, E>(&mut self, F) -> core::result::Result<(), lxmf_core::message::MessageError> where F: core::ops::function::FnOnce(&[u8]) -> core::result::Result<[u8; 64], E>, E: core::fmt::Display",
"pub fn lxmf_core::message::LxMessage::validate_stamp_with_tickets(&mut self, u8, core::option::Option<&[alloc::vec::Vec<u8>]>) -> bool",
"pub fn lxmf_core::message::LxMessage::verify(&mut self, &rns_crypto::ed25519::Ed25519PublicKey) -> bool",
"pub fn lxmf_core::propagation_client::PropagationClient::take_received_messages(&mut self) -> alloc::vec::Vec<alloc::vec::Vec<u8>>",
"pub fn lxmf_core::propagation_node::PropagationNode::accept_message(&mut self, &lxmf_core::message::LxMessage) -> bool",
"pub fn lxmf_core::propagation_node::PropagationNode::accept_propagated_blob(&mut self, &[u8], u8) -> bool",
"pub fn lxmf_core::propagation_node::PropagationNode::plan_accept_message(&mut self, &lxmf_core::message::LxMessage) -> core::option::Option<lxmf_core::propagation_node::PropagationStoreWritePlan>",
"pub fn lxmf_core::propagation_node::PropagationNode::plan_accept_propagated_blob(&mut self, &[u8], u8) -> core::option::Option<lxmf_core::propagation_node::PropagationStoreWritePlan>",
"pub fn lxmf_core::propagation_sync::PropagationSyncTask::accept_message(&mut self, &lxmf_core::message::LxMessage) -> bool",
"pub fn lxmf_core::router::LxmRouter::defer_stamp(&mut self, lxmf_core::message::LxMessage) -> core::option::Option<lxmf_core::message::LxMessage>",
"pub fn lxmf_core::router::LxmRouter::learn_ticket_from_inbound(&mut self, &lxmf_core::message::LxMessage) -> bool",
"pub fn lxmf_core::router::LxmRouter::prepare_outbound(&mut self, &mut lxmf_core::message::LxMessage) -> core::result::Result<(), lxmf_core::router::TicketPreparationError>",
"pub lxmf_core::link_delivery::PendingDelivery::message: lxmf_core::message::LxMessage",
"pub lxmf_core::message::LxMessage::auto_compress: bool",
"pub lxmf_core::message::LxMessage::callbacks: lxmf_core::message::MessageCallbacks",
"pub lxmf_core::message::LxMessage::content: alloc::string::String",
"pub lxmf_core::message::LxMessage::delivery_attempts: u32",
"pub lxmf_core::message::LxMessage::destination_hash: [u8; 16]",
"pub lxmf_core::message::LxMessage::fields: alloc::collections::btree::map::BTreeMap<u8, alloc::vec::Vec<u8>>",
"pub lxmf_core::message::LxMessage::hash: core::option::Option<[u8; 32]>",
"pub lxmf_core::message::LxMessage::include_ticket: bool",
"pub lxmf_core::message::LxMessage::incoming: bool",
"pub lxmf_core::message::LxMessage::last_delivery_attempt: f64",
"pub lxmf_core::message::LxMessage::message_id: core::option::Option<[u8; 32]>",
"pub lxmf_core::message::LxMessage::method: lxmf_core::constants::DeliveryMethod",
"pub lxmf_core::message::LxMessage::msgpack_field_ids: alloc::collections::btree::set::BTreeSet<u8>",
"pub lxmf_core::message::LxMessage::next_delivery_attempt: f64",
"pub lxmf_core::message::LxMessage::outbound_ticket: core::option::Option<[u8; 16]>",
"pub lxmf_core::message::LxMessage::progress: f64",
"pub lxmf_core::message::LxMessage::propagation_stamp: core::option::Option<[u8; 32]>",
"pub lxmf_core::message::LxMessage::ratchet_id: core::option::Option<[u8; 32]>",
"pub lxmf_core::message::LxMessage::representation: lxmf_core::constants::DeliveryRepresentation",
"pub lxmf_core::message::LxMessage::signature: core::option::Option<[u8; 64]>",
"pub lxmf_core::message::LxMessage::signature_validated: bool",
"pub lxmf_core::message::LxMessage::source_blackholed: bool",
"pub lxmf_core::message::LxMessage::source_hash: [u8; 16]",
"pub lxmf_core::message::LxMessage::stamp: core::option::Option<alloc::vec::Vec<u8>>",
"pub lxmf_core::message::LxMessage::stamp_cost: core::option::Option<u8>",
"pub lxmf_core::message::LxMessage::stamp_value: core::option::Option<u16>",
"pub lxmf_core::message::LxMessage::state: lxmf_core::constants::MessageState",
"pub lxmf_core::message::LxMessage::timestamp: f64",
"pub lxmf_core::message::LxMessage::title: alloc::string::String",
"pub lxmf_core::message::LxMessage::transient_id: core::option::Option<lxmf_core::types::PropagationTransientId>",
"pub lxmf_core::message::LxMessage::transport_encrypted: bool",
"pub lxmf_core::message::LxMessage::transport_encryption: core::option::Option<alloc::string::String>",
"pub lxmf_core::message::LxMessage::unverified_reason: core::option::Option<lxmf_core::constants::UnverifiedReason>",
"pub lxmf_core::message::LxMessage::wire_payload: core::option::Option<alloc::vec::Vec<u8>>",
"pub lxmf_core::message::MessagePayload::fields: alloc::collections::btree::map::BTreeMap<u8, alloc::vec::Vec<u8>>",
"pub lxmf_core::message::MessagePayload::msgpack_field_ids: alloc::collections::btree::set::BTreeSet<u8>",
"pub lxmf_core::router::LxmRouter::pending_deferred_stamps: std::collections::hash::map::HashMap<[u8; 32], lxmf_core::message::LxMessage>"
]
}
}
}
+7 -1
View File
@@ -21,13 +21,19 @@ bytes = { workspace = true }
tracing = { workspace = true }
rmp = { workspace = true }
rmp-serde = { workspace = true }
rmpv = { workspace = true }
rmpv = { workspace = true, features = ["with-serde"] }
serde = { workspace = true }
sha2 = { workspace = true }
rand = { workspace = true }
hex = { workspace = true }
unicode-normalization = { workspace = true }
[target.'cfg(target_os = "ios")'.dependencies]
objc2 = "0.6"
[target.'cfg(target_os = "android")'.dependencies]
jni = "0.19"
[dev-dependencies]
tempfile = { workspace = true }
proptest = { workspace = true }
+9 -10
View File
@@ -1,21 +1,20 @@
//! Construct, sign, pack, and inspect an LXMF message through the canonical API.
use lxmf_core::message_api::{DeliveryMethod, LxMessage, MessageState};
//! Construct, sign, freeze, and inspect a message through the canonical API.
use lxmf_core::message_api::{DeliveryMethod, LxMessage, LxMessageDraft, MessageState};
use rns_crypto::ed25519::Ed25519PrivateKey;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut message = LxMessage::new(
let mut draft = LxMessageDraft::new(
[0x11; 16],
[0x22; 16],
"Hello",
"LXMF from Rust",
DeliveryMethod::Direct,
);
message.sign(&Ed25519PrivateKey::generate())?;
let packed = message.pack()?;
let unpacked = LxMessage::unpack(&packed)?;
assert_eq!(unpacked.title, "Hello");
)?;
draft.set_field(0x105_u64, vec![1, 2, 3])?;
let message = draft.sign(&Ed25519PrivateKey::generate())?.finalize(None)?;
let unpacked = LxMessage::unpack(message.wire_bytes())?;
assert_eq!(unpacked.title_text(), "Hello");
assert_eq!(unpacked.state, MessageState::Generating);
assert_eq!(unpacked.wire_bytes(), message.wire_bytes());
Ok(())
}
+618
View File
@@ -0,0 +1,618 @@
//! Durable propagation-download admission and non-purging retry policy.
//!
//! A transport Resource proof is not an application receipt. The trusted local
//! adapter implements [`DurableAdmissionBackend`] and commits its body/effects
//! and receipt together before a download token can authorize remote deletion.
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, OnceLock};
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use tokio::sync::{OwnedSemaphorePermit, Semaphore, mpsc};
pub const MAX_DOWNLOAD_ITEMS: usize = 4096;
pub const MAX_RETAINED_DOWNLOAD_BYTES: usize = 134_217_727;
pub const MAX_PROCESSING_BYTES: usize = 256 * 1024 * 1024;
pub const MAX_PROCESSORS: usize = 4;
pub const POLICY_RECEIPT_LIFETIME: u64 = 90 * 86400;
/// Exact remote and local ownership of a ciphertext transient ID.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct AdmissionScope {
pub identity: [u8; 16],
pub node: [u8; 16],
pub transient_id: [u8; 32],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DurableDisposition {
Committed,
Duplicate,
PolicyDiscard,
UserDeleted,
}
/// Persisted effect identity. A duplicate need not have the same complete wire
/// hash: the optional recipient stamp is excluded from the signed message ID.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AdmissionRecord {
pub scope: AdmissionScope,
pub message_id: [u8; 32],
pub received_wire_hash: [u8; 32],
pub stored_message_wire_hash: Option<[u8; 32]>,
pub disposition: DurableDisposition,
pub committed_at: u64,
}
/// Verified local purge authority with its finite policy lifetime. Adapters
/// supply these only after checking the referenced durable effect.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DurableHave {
pub transient_id: [u8; 32],
pub expires_at: Option<u64>,
}
impl DurableHave {
pub fn from_record(record: &AdmissionRecord) -> Self {
Self {
transient_id: record.scope.transient_id,
expires_at: matches!(
record.disposition,
DurableDisposition::PolicyDiscard | DurableDisposition::UserDeleted
)
.then(|| record.committed_at.saturating_add(POLICY_RECEIPT_LIFETIME)),
}
}
pub fn active(self, now: u64) -> bool {
self.expires_at.is_none_or(|expiry| now < expiry)
}
}
#[derive(Debug, thiserror::Error)]
pub enum AdmissionError {
#[error("admission was not committed: {0}")]
NotCommitted(String),
#[error("admission publication is uncertain; reconcile all durability barriers: {0}")]
CommitUncertain(String),
#[error("durable disposition ledger is full")]
DispositionLedgerFull,
#[error("admission scope does not match the downloaded ciphertext")]
WrongScope,
}
/// Trusted persistence adapter boundary. Implementations must atomically commit
/// the receipt with the message/effect, or reference a previously durable effect.
/// In particular, returning a record after a failed/uncertain filesystem or SQL
/// commit violates this contract. SQLite implementations use the dedicated FULL
/// connection; file implementations use the intent/body/commit journal.
pub trait DurableAdmissionBackend {
fn commit(self) -> Result<AdmissionRecord, AdmissionError>;
}
#[derive(Debug)]
pub struct DurableAdmissionReceipt {
record: AdmissionRecord,
}
impl DurableAdmissionReceipt {
pub fn commit(backend: impl DurableAdmissionBackend) -> Result<Self, AdmissionError> {
Ok(Self {
record: backend.commit()?,
})
}
pub fn record(&self) -> &AdmissionRecord {
&self.record
}
}
/// Persisted, deterministic epochs; never reset these to a process generation.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct AdmissionEpochs {
pub policy: [u8; 32],
pub keys: [u8; 32],
pub budget: [u8; 32],
pub storage_health: [u8; 32],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SuppressionReason {
Malformed,
WrongDestination,
InvalidSignature,
InvalidStamp,
DecryptionFailed,
TooLarge,
MissingKey,
StorageUnavailable,
StorageBusy,
Quota,
WorkerUnavailable,
DispositionLedgerFull,
Cancelled,
}
impl SuppressionReason {
pub fn is_transient(self) -> bool {
matches!(
self,
Self::MissingKey
| Self::StorageUnavailable
| Self::StorageBusy
| Self::Quota
| Self::WorkerUnavailable
| Self::DispositionLedgerFull
| Self::Cancelled
)
}
fn epoch_matches(self, before: AdmissionEpochs, now: AdmissionEpochs) -> bool {
match self {
Self::DecryptionFailed | Self::MissingKey => before.keys == now.keys,
Self::InvalidSignature => before.keys == now.keys && before.policy == now.policy,
Self::TooLarge => before.budget == now.budget,
Self::StorageUnavailable
| Self::StorageBusy
| Self::Quota
| Self::DispositionLedgerFull => before.storage_health == now.storage_health,
_ => before.policy == now.policy,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SuppressionRecord {
pub scope: AdmissionScope,
pub reason: SuppressionReason,
pub epochs: AdmissionEpochs,
pub attempts: u16,
pub last_failure: u64,
pub next_retry: u64,
pub expires_at: u64,
}
impl SuppressionRecord {
pub fn active(&self, now: u64, epochs: AdmissionEpochs) -> bool {
now < self.expires_at
&& now < self.next_retry
&& self.reason.epoch_matches(self.epochs, epochs)
}
}
/// Quotas bound metadata independently of message bytes. Full ledgers preserve
/// existing entries and pause new wants, rather than evicting into a retry loop.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SuppressionLedger {
records: HashMap<AdmissionScope, SuppressionRecord>,
}
impl SuppressionLedger {
pub const PER_NODE: usize = 4096;
pub const PER_IDENTITY: usize = 16384;
pub const GLOBAL: usize = 65536;
/// Restore typed rows only after duplicate and quota validation. Never
/// silently overwrite persisted scope decisions during hydration.
pub fn from_records(
records: impl IntoIterator<Item = SuppressionRecord>,
) -> Result<Self, AdmissionError> {
let mut ledger = Self::default();
let mut identities = HashMap::<[u8; 16], usize>::new();
let mut nodes = HashMap::<([u8; 16], [u8; 16]), usize>::new();
for record in records {
if ledger.records.contains_key(&record.scope) {
return Err(AdmissionError::NotCommitted(
"duplicate suppression scope".into(),
));
}
if record.attempts == 0
|| record.next_retry < record.last_failure
|| record.expires_at <= record.last_failure
|| record.expires_at > record.last_failure.saturating_add(30 * 86400)
{
return Err(AdmissionError::NotCommitted(
"invalid suppression interval".into(),
));
}
let identity = identities.entry(record.scope.identity).or_default();
let node = nodes
.entry((record.scope.identity, record.scope.node))
.or_default();
if ledger.records.len() >= Self::GLOBAL
|| *identity >= Self::PER_IDENTITY
|| *node >= Self::PER_NODE
{
return Err(AdmissionError::DispositionLedgerFull);
}
*identity += 1;
*node += 1;
ledger.records.insert(record.scope, record);
}
Ok(ledger)
}
pub fn records(&self) -> impl Iterator<Item = &SuppressionRecord> {
self.records.values()
}
pub fn get(&self, scope: &AdmissionScope) -> Option<&SuppressionRecord> {
self.records.get(scope)
}
pub fn remove(&mut self, scope: &AdmissionScope) {
self.records.remove(scope);
}
pub fn prune(&mut self, now: u64, epochs: AdmissionEpochs) {
self.records.retain(|_, record| {
now < record.expires_at && record.reason.epoch_matches(record.epochs, epochs)
});
}
pub fn saturated(&self, identity: [u8; 16], node: [u8; 16]) -> bool {
self.records.len() >= Self::GLOBAL
|| self
.records
.keys()
.filter(|k| k.identity == identity)
.count()
>= Self::PER_IDENTITY
|| self
.records
.keys()
.filter(|k| k.identity == identity && k.node == node)
.count()
>= Self::PER_NODE
}
pub fn record_failure(
&mut self,
scope: AdmissionScope,
reason: SuppressionReason,
epochs: AdmissionEpochs,
now: u64,
) -> Result<&SuppressionRecord, AdmissionError> {
self.prune(now, epochs);
if !self.records.contains_key(&scope) && self.saturated(scope.identity, scope.node) {
return Err(AdmissionError::DispositionLedgerFull);
}
let attempts = self
.records
.get(&scope)
.filter(|r| r.reason == reason)
.map_or(1, |r| r.attempts.saturating_add(1));
let (next_retry, expires_at) = if reason.is_transient() {
let base = (60u64 << attempts.saturating_sub(1).min(6)).min(3600);
// Stable +/-10% jitter avoids synchronized retries after restart.
let jitter =
u16::from_be_bytes([scope.transient_id[0], scope.transient_id[1]]) as u64 % 21;
(
now.saturating_add(base * (90 + jitter) / 100),
now.saturating_add(86400),
)
} else {
(
now.saturating_add(30 * 86400),
now.saturating_add(30 * 86400),
)
};
self.records.insert(
scope,
SuppressionRecord {
scope,
reason,
epochs,
attempts,
last_failure: now,
next_retry,
expires_at,
},
);
Ok(&self.records[&scope])
}
}
#[derive(Debug)]
pub enum DownloadAdmissionOutcome {
Accepted(DurableAdmissionReceipt),
Rejected(SuppressionReason),
}
pub(crate) struct AdmissionResolution {
pub generation: u64,
pub scope: AdmissionScope,
pub outcome: DownloadAdmissionOutcome,
}
/// Single-use, generation-bound authority. Dropping it reports a retryable
/// failure; cancelling its client generation cannot cancel a blocking commit.
pub struct DownloadAdmissionToken {
scope: AdmissionScope,
generation: u64,
current_generation: Arc<AtomicU64>,
tx: Option<mpsc::UnboundedSender<AdmissionResolution>>,
}
impl std::fmt::Debug for DownloadAdmissionToken {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DownloadAdmissionToken")
.field("scope", &self.scope)
.field("generation", &self.generation)
.finish_non_exhaustive()
}
}
impl DownloadAdmissionToken {
pub(crate) fn new(
scope: AdmissionScope,
generation: u64,
current_generation: Arc<AtomicU64>,
tx: mpsc::UnboundedSender<AdmissionResolution>,
) -> Self {
Self {
scope,
generation,
current_generation,
tx: Some(tx),
}
}
pub fn scope(&self) -> AdmissionScope {
self.scope
}
/// Check immediately after durable commit before publishing current-generation effects.
/// Cancellation cannot stop an in-flight commit or release its memory lease.
pub fn is_current(&self) -> bool {
self.current_generation.load(Ordering::Acquire) == self.generation
}
pub fn resolve(mut self, outcome: DownloadAdmissionOutcome) -> Result<(), AdmissionError> {
if let DownloadAdmissionOutcome::Accepted(receipt) = &outcome
&& receipt.record.scope != self.scope
{
return Err(AdmissionError::WrongScope);
}
if !self.is_current() {
self.tx.take();
return Err(AdmissionError::NotCommitted(
"download generation was revoked".into(),
));
}
let tx = self.tx.take().ok_or_else(|| {
AdmissionError::NotCommitted("download authority already consumed".into())
})?;
tx.send(AdmissionResolution {
generation: self.generation,
scope: self.scope,
outcome,
})
.map_err(|_| AdmissionError::NotCommitted("download consumer is closed".into()))?;
// The client rechecks the exact generation while consuming. This result
// reports enqueue only; adapters need their lifecycle gate around any
// current-generation UI effects, not an atomic-cancellation promise.
if !self.is_current() {
return Err(AdmissionError::NotCommitted(
"download generation was revoked".into(),
));
}
Ok(())
}
}
impl Drop for DownloadAdmissionToken {
fn drop(&mut self) {
if let Some(tx) = self.tx.take() {
let _ = tx.send(AdmissionResolution {
generation: self.generation,
scope: self.scope,
outcome: DownloadAdmissionOutcome::Rejected(SuppressionReason::Cancelled),
});
}
}
}
#[derive(Debug)]
pub struct DownloadedPropagationMessage {
data: Bytes,
token: DownloadAdmissionToken,
}
impl DownloadedPropagationMessage {
pub(crate) fn new(data: Bytes, token: DownloadAdmissionToken) -> Self {
Self { data, token }
}
pub fn data(&self) -> &Bytes {
&self.data
}
pub fn scope(&self) -> AdmissionScope {
self.token.scope
}
pub fn into_parts(self) -> (Bytes, DownloadAdmissionToken) {
(self.data, self.token)
}
}
fn raw_budget() -> &'static Arc<Semaphore> {
static BUDGET: OnceLock<Arc<Semaphore>> = OnceLock::new();
BUDGET.get_or_init(|| Arc::new(Semaphore::new(MAX_RETAINED_DOWNLOAD_BYTES)))
}
struct RetainedResponse {
bytes: Bytes,
_credit: OwnedSemaphorePermit,
}
impl AsRef<[u8]> for RetainedResponse {
fn as_ref(&self) -> &[u8] {
&self.bytes
}
}
/// Credit follows every Bytes clone/slice, including payloads in cancelled
/// blocking workers. Moving a response out of the client never releases it.
pub(crate) fn retain_response(
bytes: Bytes,
local_limit: usize,
) -> Result<Bytes, SuppressionReason> {
if bytes.len() > local_limit.min(MAX_RETAINED_DOWNLOAD_BYTES) {
return Err(SuppressionReason::TooLarge);
}
let credit = raw_budget()
.clone()
.try_acquire_many_owned(bytes.len() as u32)
.map_err(|_| SuppressionReason::WorkerUnavailable)?;
Ok(Bytes::from_owner(RetainedResponse {
bytes,
_credit: credit,
}))
}
/// Full peak reservation is obtained before decrypting while raw ciphertext is
/// retained separately. Never wait for a partial reservation while holding the
/// parent response. This bounds Rust-owned buffers, not SQLite's native heap.
fn processing_budget() -> &'static Arc<Semaphore> {
static BYTES: OnceLock<Arc<Semaphore>> = OnceLock::new();
BYTES.get_or_init(|| Arc::new(Semaphore::new(MAX_PROCESSING_BYTES)))
}
/// Additional explicitly bounded adapter state, sharing the processing byte
/// budget without taking a second worker slot. Admission is always nonblocking.
pub struct ProcessingMemoryLease {
_bytes: OwnedSemaphorePermit,
}
impl ProcessingMemoryLease {
pub fn try_acquire(amount: usize) -> Result<Self, SuppressionReason> {
if amount > MAX_PROCESSING_BYTES {
return Err(SuppressionReason::TooLarge);
}
Ok(Self {
_bytes: processing_budget()
.clone()
.try_acquire_many_owned(amount as u32)
.map_err(|_| SuppressionReason::WorkerUnavailable)?,
})
}
}
pub struct ProcessingLease {
_bytes: OwnedSemaphorePermit,
_worker: OwnedSemaphorePermit,
}
impl ProcessingLease {
pub fn try_acquire(cipher_len: usize) -> Result<Self, SuppressionReason> {
static WORKERS: OnceLock<Arc<Semaphore>> = OnceLock::new();
let amount = cipher_len
.checked_mul(4)
.and_then(|v| v.checked_add(128 * 1024 + 256))
.filter(|v| *v <= MAX_PROCESSING_BYTES)
.ok_or(SuppressionReason::TooLarge)?;
let bytes = processing_budget()
.clone()
.try_acquire_many_owned(amount as u32)
.map_err(|_| SuppressionReason::WorkerUnavailable)?;
let worker = WORKERS
.get_or_init(|| Arc::new(Semaphore::new(MAX_PROCESSORS)))
.clone()
.try_acquire_owned()
.map_err(|_| SuppressionReason::WorkerUnavailable)?;
Ok(Self {
_bytes: bytes,
_worker: worker,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
fn scope(n: u8) -> AdmissionScope {
AdmissionScope {
identity: [1; 16],
node: [2; 16],
transient_id: [n; 32],
}
}
#[test]
fn resolution_rejects_revoked_generation_and_closed_consumer() {
let generation = Arc::new(AtomicU64::new(1));
let (tx, mut rx) = mpsc::unbounded_channel();
let token = DownloadAdmissionToken::new(scope(1), 1, generation.clone(), tx.clone());
generation.store(2, Ordering::Release);
assert!(
token
.resolve(DownloadAdmissionOutcome::Rejected(
SuppressionReason::Cancelled
))
.is_err()
);
assert!(rx.try_recv().is_err());
let token = DownloadAdmissionToken::new(scope(2), 2, generation, tx);
drop(rx);
assert!(
token
.resolve(DownloadAdmissionOutcome::Rejected(
SuppressionReason::Cancelled
))
.is_err()
);
}
#[test]
fn permanent_failures_revalidate_on_epoch_change_or_expiry() {
let mut ledger = SuppressionLedger::default();
let epoch = AdmissionEpochs::default();
let r = ledger
.record_failure(scope(1), SuppressionReason::DecryptionFailed, epoch, 100)
.unwrap();
assert!(r.active(101, epoch));
let mut changed = epoch;
changed.keys[0] = 1;
assert!(!r.active(101, changed));
assert!(!r.active(100 + 30 * 86400, epoch));
assert!(rmp_serde::to_vec(r).unwrap().len() <= 512);
}
#[test]
fn temporary_storage_failure_is_retryable_and_bounded() {
let mut ledger = SuppressionLedger::default();
for _ in 0..20 {
ledger
.record_failure(
scope(1),
SuppressionReason::StorageBusy,
AdmissionEpochs::default(),
100,
)
.unwrap();
}
let r = ledger.get(&scope(1)).unwrap();
assert!((3340..=4060).contains(&r.next_retry));
assert_eq!(r.expires_at, 86500);
}
#[test]
fn full_node_ledger_does_not_evict_existing_suppression() {
let mut ledger = SuppressionLedger::default();
for n in 0..SuppressionLedger::PER_NODE {
let mut s = scope(0);
s.transient_id[..8].copy_from_slice(&(n as u64).to_be_bytes());
ledger
.record_failure(
s,
SuppressionReason::Malformed,
AdmissionEpochs::default(),
100,
)
.unwrap();
}
assert!(
ledger
.record_failure(
scope(255),
SuppressionReason::Malformed,
AdmissionEpochs::default(),
100
)
.is_err()
);
assert_eq!(ledger.records().count(), SuppressionLedger::PER_NODE);
}
#[test]
fn impossible_processing_size_rejects_without_partial_wait() {
assert!(matches!(
ProcessingLease::try_acquire(MAX_PROCESSING_BYTES),
Err(SuppressionReason::TooLarge)
));
}
}
+599
View File
@@ -0,0 +1,599 @@
//! File adapter for lxmd's durable download receipts and hook outbox.
//! The original ciphertext TID is journaled before publishing decrypted bytes.
use crate::admission::*;
use bytes::Bytes;
use rns_identity::persistence::{
DurableCommitPhase, DurableWriteError, durable_create_dir_all, durable_reconcile,
durable_remove, durable_write,
};
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
path::{Path, PathBuf},
sync::{Arc, Mutex},
};
#[derive(Debug, Clone, Serialize, Deserialize)]
struct AdmissionIntent {
version: u8,
admission_id: [u8; 32],
record: AdmissionRecord,
body_path: Option<PathBuf>,
hook_event: Option<[u8; 32]>,
}
/// One atomic logical commit publishes both the receipt and pending hook event.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct AdmissionCommit {
intent: AdmissionIntent,
hook_completed: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct UserDeletedMessage {
version: u8,
identity: [u8; 16],
message_id: [u8; 32],
deleted_at: u64,
}
struct Inner {
journal: PathBuf,
bodies: PathBuf,
committed: HashMap<AdmissionScope, AdmissionCommit>,
deleted: HashMap<([u8; 16], [u8; 32]), UserDeletedMessage>,
}
#[derive(Clone)]
pub struct FileAdmissionStore {
inner: Arc<Mutex<Inner>>,
}
fn error(e: DurableWriteError) -> AdmissionError {
match e.phase {
DurableCommitPhase::NotCommitted => AdmissionError::NotCommitted(e.to_string()),
_ => AdmissionError::CommitUncertain(e.to_string()),
}
}
fn other(e: impl std::fmt::Display) -> AdmissionError {
AdmissionError::NotCommitted(e.to_string())
}
fn encode<T: Serialize>(value: &T) -> Result<Vec<u8>, AdmissionError> {
rmp_serde::to_vec_named(value).map_err(other)
}
fn read_bounded(path: &Path, limit: usize) -> Result<Vec<u8>, AdmissionError> {
use std::io::Read;
let mut bytes = Vec::new();
std::fs::File::open(path)
.map_err(other)?
.take(limit as u64 + 1)
.read_to_end(&mut bytes)
.map_err(other)?;
if bytes.len() > limit {
return Err(other("admission artifact exceeds limit"));
}
Ok(bytes)
}
fn admission_id(scope: &AdmissionScope) -> Result<[u8; 32], AdmissionError> {
Ok(rns_crypto::sha::full_hash(&encode(scope)?))
}
impl FileAdmissionStore {
/// Parent is the daemon's already configured state directory. A strict
/// outside bootstrap receipt witnesses creation of journal/body directories.
pub fn open(state_dir: &Path, bodies: &Path) -> Result<Self, AdmissionError> {
let journal = state_dir.join("download-admission-v1");
let parent = state_dir
.ancestors()
.find(|parent| {
bodies.starts_with(parent) && *parent != bodies && parent.parent().is_some()
})
.ok_or_else(|| other("admission state and bodies need a private common ancestor"))?;
let scope = encode(&(1u8, state_dir, bodies))?;
let bootstrap_path = parent.join(format!(
"download-admission-{}.bootstrap",
hex::encode(rns_crypto::sha::full_hash(&scope))
));
let bootstrap = durable_write(&bootstrap_path, &scope).map_err(error)?;
durable_create_dir_all(&journal, &bootstrap).map_err(error)?;
durable_create_dir_all(bodies, &bootstrap).map_err(error)?;
let mut inner = Inner {
journal,
bodies: bodies.to_owned(),
committed: HashMap::new(),
deleted: HashMap::new(),
};
inner.recover()?;
Ok(Self {
inner: Arc::new(Mutex::new(inner)),
})
}
pub fn prepare(
&self,
mut record: AdmissionRecord,
wire: Bytes,
run_hook: bool,
) -> FileAdmissionCommit {
// The caller cannot mislabel the incoming image even for a duplicate.
record.received_wire_hash = rns_crypto::sha::full_hash(&wire);
FileAdmissionCommit {
store: self.clone(),
record,
wire,
run_hook,
}
}
/// Durable visible receipts remain while their referenced message exists;
/// invisible policy/TID accelerators expire after the local90-day policy.
pub fn haves(&self, identity: [u8; 16], node: [u8; 16], now: u64) -> Vec<Vec<u8>> {
let inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
inner
.committed
.values()
.filter(|c| {
c.intent.record.scope.identity == identity
&& c.intent.record.scope.node == node
&& live(&c.intent.record, now)
})
.map(|c| c.intent.record.scope.transient_id.to_vec())
.collect()
}
pub fn durable_haves(
&self,
identity: [u8; 16],
node: [u8; 16],
now: u64,
) -> Vec<super::admission::DurableHave> {
let inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
inner
.committed
.values()
.filter(|c| {
c.intent.record.scope.identity == identity
&& c.intent.record.scope.node == node
&& live(&c.intent.record, now)
})
.map(|c| super::admission::DurableHave::from_record(&c.intent.record))
.collect()
}
/// Explicit user deletion is a permanent message-ID decision, separate
/// from expiring per-node TID accelerators. No filesystem absence is treated
/// as user authorization. Removing this tombstone requires explicit reset.
pub fn mark_user_deleted(
&self,
identity: [u8; 16],
message_id: [u8; 32],
now: u64,
) -> Result<(), AdmissionError> {
let mut inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
let tombstone = UserDeletedMessage {
version: 1,
identity,
message_id,
deleted_at: now,
};
let path = inner.journal.join(format!(
"{}-{}.deleted",
hex::encode(identity),
hex::encode(message_id)
));
let witness = durable_write(&path, &encode(&tombstone)?).map_err(error)?;
inner.deleted.insert((identity, message_id), tombstone);
let targets = inner
.committed
.iter()
.filter(|(_, c)| {
c.intent.record.scope.identity == identity
&& c.intent.record.message_id == message_id
})
.map(|(scope, c)| (*scope, c.clone()))
.collect::<Vec<_>>();
for (scope, mut commit) in targets {
commit.intent.body_path = None;
commit.intent.hook_event = None;
commit.hook_completed = true;
commit.intent.record.disposition = DurableDisposition::UserDeleted;
commit.intent.record.stored_message_wire_hash = None;
commit.intent.record.committed_at = now;
durable_write(
&inner.intent_path(&commit.intent.admission_id),
&encode(&commit.intent)?,
)
.map_err(error)?;
durable_write(
&inner.commit_path(&commit.intent.admission_id),
&encode(&commit)?,
)
.map_err(error)?;
inner.committed.insert(scope, commit);
}
durable_remove(
&inner
.bodies
.join(format!("{}.lxm", hex::encode(message_id))),
&witness,
)
.map_err(error)?;
Ok(())
}
/// Prune only expired invisible TID receipts. Visible archive authority and
/// permanent UserDeleted message decisions are retained independently.
pub fn maintain(&self, now: u64) -> Result<usize, AdmissionError> {
let mut inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
let expired = inner
.committed
.iter()
.filter(|(_, c)| !live(&c.intent.record, now))
.map(|(scope, c)| (*scope, c.intent.admission_id))
.collect::<Vec<_>>();
if expired.is_empty() {
return Ok(0);
}
let witness = durable_write(
&inner.journal.join("receipt-pruning-v1"),
&encode(&(1u8, &expired))?,
)
.map_err(error)?;
let mut removed = 0;
for (scope, id) in expired {
durable_remove(&inner.intent_path(&id), &witness).map_err(error)?;
durable_remove(&inner.commit_path(&id), &witness).map_err(error)?;
inner.committed.remove(&scope);
removed += 1;
}
Ok(removed)
}
pub fn pending_hooks(&self) -> Vec<([u8; 32], PathBuf)> {
let inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
inner
.committed
.values()
.filter(|c| !c.hook_completed)
.filter_map(|c| Some((c.intent.hook_event?, c.intent.body_path.clone()?)))
.collect()
}
pub fn complete_hook(&self, event: [u8; 32]) -> Result<(), AdmissionError> {
let mut inner = self.inner.lock().unwrap_or_else(|p| p.into_inner());
let Some(scope) = inner
.committed
.iter()
.find_map(|(s, c)| (c.intent.hook_event == Some(event)).then_some(*s))
else {
return Ok(());
};
let mut updated = inner.committed[&scope].clone();
updated.hook_completed = true;
durable_write(
&inner.commit_path(&updated.intent.admission_id),
&encode(&updated)?,
)
.map_err(error)?;
inner.committed.insert(scope, updated);
Ok(())
}
}
fn live(record: &AdmissionRecord, now: u64) -> bool {
!matches!(
record.disposition,
DurableDisposition::PolicyDiscard | DurableDisposition::UserDeleted
) || now.saturating_sub(record.committed_at) < POLICY_RECEIPT_LIFETIME
}
pub struct FileAdmissionCommit {
store: FileAdmissionStore,
record: AdmissionRecord,
wire: Bytes,
run_hook: bool,
}
impl DurableAdmissionBackend for FileAdmissionCommit {
fn commit(self) -> Result<AdmissionRecord, AdmissionError> {
let mut inner = self.store.inner.lock().unwrap_or_else(|p| p.into_inner());
let parsed = crate::message::LxMessage::unpack_owned(self.wire.clone(), Default::default())
.map_err(other)?;
if parsed.message_id() != self.record.message_id {
return Err(other("admission message identity mismatch"));
}
if let Some(existing) = inner.committed.get(&self.record.scope) {
if existing.intent.record.received_wire_hash != self.record.received_wire_hash {
return Err(other("ciphertext TID receipt wire mismatch"));
}
if !inner
.deleted
.contains_key(&(self.record.scope.identity, self.record.message_id))
&& live(&existing.intent.record, self.record.committed_at)
&& matches!(
existing.intent.record.disposition,
DurableDisposition::Committed | DurableDisposition::Duplicate
)
&& self.record.disposition == DurableDisposition::Committed
{
inner.validate_body(&existing.intent)?;
let mut duplicate = existing.intent.record.clone();
duplicate.disposition = DurableDisposition::Duplicate;
return Ok(duplicate);
}
}
let mut record = self.record;
if inner
.deleted
.contains_key(&(record.scope.identity, record.message_id))
{
record.disposition = DurableDisposition::UserDeleted;
}
let invisible = matches!(
record.disposition,
DurableDisposition::PolicyDiscard | DurableDisposition::UserDeleted
);
if invisible {
let existing = inner.committed.values().filter(|c| {
matches!(
c.intent.record.disposition,
DurableDisposition::PolicyDiscard | DurableDisposition::UserDeleted
) && live(&c.intent.record, record.committed_at)
});
let global = existing.clone().count();
let identity = existing
.filter(|c| c.intent.record.scope.identity == record.scope.identity)
.count();
if global >= 65536 || identity >= 16384 {
return Err(AdmissionError::DispositionLedgerFull);
}
}
let body_path = (!invisible).then(|| {
inner
.bodies
.join(format!("{}.lxm", hex::encode(record.message_id)))
});
let mut body = None;
let mut newly_visible = false;
if let Some(path) = &body_path {
match std::fs::metadata(path) {
Ok(_) => {
let existing = read_bounded(path, rns_protocol::resource::MAX_RESOURCE_SIZE)?;
// Keep the first immutable archive. Same message ID can have
// a different fifth-stamp image; record both hashes.
let parsed = crate::message::LxMessage::unpack(&existing).map_err(other)?;
if parsed.message_id() != record.message_id {
return Err(other("existing archive has a different message ID"));
}
record.stored_message_wire_hash = Some(rns_crypto::sha::full_hash(&existing));
record.disposition = DurableDisposition::Duplicate;
body = Some(Bytes::from(existing));
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
record.stored_message_wire_hash = Some(record.received_wire_hash);
newly_visible = true;
body = Some(self.wire.clone());
}
Err(e) => return Err(other(e)),
}
}
let admission_id = admission_id(&record.scope)?;
let intent = AdmissionIntent {
version: 1,
admission_id,
record: record.clone(),
body_path,
hook_event: (self.run_hook && newly_visible).then_some(admission_id),
};
durable_write(&inner.intent_path(&admission_id), &encode(&intent)?).map_err(error)?;
if let (Some(path), Some(body)) = (&intent.body_path, body) {
if newly_visible {
durable_write(path, &body).map_err(error)?;
} else {
durable_reconcile(path, &body).map_err(error)?;
}
}
let commit = AdmissionCommit {
intent,
hook_completed: false,
};
durable_write(&inner.commit_path(&admission_id), &encode(&commit)?).map_err(error)?;
inner.committed.insert(record.scope, commit);
Ok(record)
}
}
impl Inner {
fn intent_path(&self, id: &[u8; 32]) -> PathBuf {
self.journal.join(format!("{}.intent", hex::encode(id)))
}
fn commit_path(&self, id: &[u8; 32]) -> PathBuf {
self.journal.join(format!("{}.commit", hex::encode(id)))
}
fn validate_body(&self, intent: &AdmissionIntent) -> Result<(), AdmissionError> {
if intent.version != 1 || admission_id(&intent.record.scope)? != intent.admission_id {
return Err(other("unknown admission journal version or identity"));
}
if self
.deleted
.contains_key(&(intent.record.scope.identity, intent.record.message_id))
&& intent.record.disposition != DurableDisposition::UserDeleted
{
return Err(other("message was explicitly deleted"));
}
if let Some(path) = &intent.body_path {
if path.parent() != Some(self.bodies.as_path())
|| path.file_name().and_then(|n| n.to_str())
!= Some(format!("{}.lxm", hex::encode(intent.record.message_id)).as_str())
{
return Err(other("admission archive path escapes configured inbox"));
}
let body = read_bounded(path, rns_protocol::resource::MAX_RESOURCE_SIZE)?;
if Some(rns_crypto::sha::full_hash(&body)) != intent.record.stored_message_wire_hash {
return Err(other("admission archive content mismatch"));
}
// A previous CommitUncertain becomes authoritative only after all
// native barriers succeed again, never merely after readback.
durable_reconcile(path, &body).map_err(error)?;
} else if !matches!(
intent.record.disposition,
DurableDisposition::PolicyDiscard | DurableDisposition::UserDeleted
) {
return Err(other("visible admission is missing its archive"));
}
Ok(())
}
fn recover(&mut self) -> Result<(), AdmissionError> {
// Stream directory passes: directory size must not itself allocate an
// unbounded vector. Malformed artifacts remain private and unavailable.
for file in std::fs::read_dir(&self.journal).map_err(other)? {
let path = file.map_err(other)?.path();
if path.extension().and_then(|s| s.to_str()) != Some("deleted") {
continue;
}
let data = read_bounded(&path, 2048)?;
let tombstone: UserDeletedMessage = rmp_serde::from_slice(&data).map_err(other)?;
if tombstone.version != 1
|| path.file_name().and_then(|s| s.to_str())
!= Some(
format!(
"{}-{}.deleted",
hex::encode(tombstone.identity),
hex::encode(tombstone.message_id)
)
.as_str(),
)
{
return Err(other("invalid user deletion tombstone"));
}
let witness = durable_reconcile(&path, &data).map_err(error)?;
durable_remove(
&self
.bodies
.join(format!("{}.lxm", hex::encode(tombstone.message_id))),
&witness,
)
.map_err(error)?;
self.deleted
.insert((tombstone.identity, tombstone.message_id), tombstone);
}
for file in std::fs::read_dir(&self.journal).map_err(other)? {
let path = file.map_err(other)?.path();
if path.extension().and_then(|s| s.to_str()) != Some("commit") {
continue;
}
let result = (|| {
let data = read_bounded(&path, 16 * 1024)?;
let commit: AdmissionCommit = rmp_serde::from_slice(&data).map_err(other)?;
if path != self.commit_path(&commit.intent.admission_id) {
return Err(other("commit filename mismatch"));
}
self.validate_body(&commit.intent)?;
durable_reconcile(&path, &data).map_err(error)?;
Ok(commit)
})();
match result {
Ok(commit) => {
self.committed.insert(commit.intent.record.scope, commit);
}
Err(error) => {
tracing::warn!(%error,path=%path.display(),"unavailable admission preserved without purge authority")
}
}
}
for file in std::fs::read_dir(&self.journal).map_err(other)? {
let path = file.map_err(other)?.path();
if path.extension().and_then(|s| s.to_str()) != Some("intent") {
continue;
}
let result = (|| {
let data = read_bounded(&path, 16 * 1024)?;
let intent: AdmissionIntent = rmp_serde::from_slice(&data).map_err(other)?;
if path != self.intent_path(&intent.admission_id) {
return Err(other("intent filename mismatch"));
}
if self
.committed
.get(&intent.record.scope)
.is_some_and(|c| c.intent.record == intent.record)
{
return Ok(None);
}
self.validate_body(&intent)?;
durable_reconcile(&path, &data).map_err(error)?;
let commit = AdmissionCommit {
intent,
hook_completed: false,
};
durable_write(
&self.commit_path(&commit.intent.admission_id),
&encode(&commit)?,
)
.map_err(error)?;
Ok(Some(commit))
})();
match result {
Ok(Some(commit)) => {
self.committed.insert(commit.intent.record.scope, commit);
}
Ok(None) => {}
Err(error) => {
tracing::warn!(%error,path=%path.display(),"uncommitted admission preserved without purge authority")
}
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn committed_receipt_survives_reopen_and_hook_is_in_same_commit() {
let temp = tempfile::tempdir().unwrap();
let bodies = temp.path().join("messages");
let store = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
let message = crate::message::test_message(
[1; 16],
[2; 16],
"",
"body",
crate::constants::DeliveryMethod::Propagated,
);
let scope = AdmissionScope {
identity: [3; 16],
node: [4; 16],
transient_id: [5; 32],
};
let record = AdmissionRecord {
scope,
message_id: message.message_id(),
received_wire_hash: [0; 32],
stored_message_wire_hash: None,
disposition: DurableDisposition::Committed,
committed_at: 100,
};
let receipt = DurableAdmissionReceipt::commit(store.prepare(
record,
Bytes::copy_from_slice(message.wire_bytes()),
true,
))
.unwrap();
assert_eq!(
receipt.record().received_wire_hash,
rns_crypto::sha::full_hash(message.wire_bytes())
);
drop(store);
let recovered = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
assert_eq!(
recovered.haves(scope.identity, scope.node, 101),
vec![scope.transient_id.to_vec()]
);
assert_eq!(recovered.pending_hooks().len(), 1);
recovered
.complete_hook(recovered.pending_hooks()[0].0)
.unwrap();
assert!(recovered.pending_hooks().is_empty());
}
}
+26 -7
View File
@@ -87,7 +87,7 @@ impl DeliveryRatchetState {
let format = loaded.format();
let ring = loaded.into_ring();
if format == RatchetRingFormat::LegacyRust {
match ring.save_verified(&ring_path, identity) {
match ring.save_verified_durable(&ring_path, identity) {
Ok(()) => tracing::info!(
path = %ring_path.display(),
"migrated legacy Rust ratchet ring to canonical format"
@@ -145,7 +145,7 @@ impl DeliveryRatchetState {
if ring.is_empty() && ring_file_trusted && control_file_trusted {
let prepared = ring.prepare_rotation_at(wall_now as f64);
match prepared.ring().save_verified(&ring_path, identity) {
match prepared.ring().save_verified_durable(&ring_path, identity) {
Ok(()) => {
ring.commit_prepared_rotation(prepared);
control = control.with_rotation_at(wall_now);
@@ -161,7 +161,7 @@ impl DeliveryRatchetState {
if control_file_trusted
&& (!control_existed || control_changed)
&& let Err(error) = control.save_verified(&control_path, identity)
&& let Err(error) = control.save_verified_durable(&control_path, identity)
{
tracing::warn!(
path = %control_path.display(),
@@ -241,7 +241,10 @@ impl DeliveryRatchetState {
let mut ratchet_public = self.ring.current_public_key();
if rotation_due && self.ring_file_trusted {
let prepared = self.ring.prepare_rotation_at(wall_now as f64);
match prepared.ring().save_verified(&self.ring_path, identity) {
match prepared
.ring()
.save_verified_durable(&self.ring_path, identity)
{
Ok(()) => {
ratchet_public = Some(prepared.public_key());
candidate_control = candidate_control.with_rotation_at(wall_now);
@@ -256,7 +259,7 @@ impl DeliveryRatchetState {
}
candidate_control
.save_verified(&self.control_path, identity)
.save_verified_durable(&self.control_path, identity)
.map_err(|source| DeliveryRatchetError::PersistControl {
path: self.control_path.clone(),
source,
@@ -293,17 +296,33 @@ impl DeliveryRatchetState {
/// never overwritten by this operation.
pub fn save(&self, identity: &Identity) {
if self.ring_file_trusted
&& let Err(error) = self.ring.save_verified(&self.ring_path, identity)
&& let Err(error) = self.ring.save_verified_durable(&self.ring_path, identity)
{
tracing::warn!(%error, "failed to save ratchet ring");
}
if self.control_file_trusted
&& let Err(error) = self.control.save_verified(&self.control_path, identity)
&& let Err(error) = self
.control
.save_verified_durable(&self.control_path, identity)
{
tracing::warn!(%error, "failed to save ratchet control state");
}
}
/// Checked strict checkpoint. Invalid files discovered during load remain
/// untouched and prevent a successful checkpoint claim.
pub fn save_durable(&self, identity: &Identity) -> std::io::Result<()> {
if !self.ring_file_trusted || !self.control_file_trusted {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"ratchet checkpoint contains untrusted state",
));
}
self.ring.save_verified_durable(&self.ring_path, identity)?;
self.control
.save_verified_durable(&self.control_path, identity)
}
pub fn ring_path(&self) -> &Path {
&self.ring_path
}
+9 -1
View File
@@ -43,6 +43,8 @@ pub(crate) fn now_f64() -> f64 {
.as_secs_f64()
}
pub mod admission;
pub mod admission_store;
pub mod constants;
pub mod delivery_ratchet;
pub mod discovery_stamper;
@@ -58,6 +60,8 @@ pub mod propagation_admission;
pub mod propagation_client;
pub mod propagation_node;
pub mod propagation_offer;
pub mod propagation_send;
pub mod propagation_store_v2;
pub mod propagation_sync;
pub mod router;
pub mod stamper;
@@ -74,7 +78,11 @@ pub mod message_api {
pub use crate::constants::{
DeliveryMethod, DeliveryRepresentation, MessageState, UnverifiedReason,
};
pub use crate::message::{AudioField, LxMessage, MessageError};
pub use crate::message::{
AudioField, EncodedFieldValue, FieldId, FieldMapKey, FieldValue, FieldValueRef, Fields,
LxMessage, LxMessageDraft, MessageDecodeLimits, MessageError, MessageMetadata,
OwnedVerifiedLxMessage, RecipientStamp, SignedLxMessage, UniqueFieldMap, VerifiedLxMessage,
};
pub use crate::types::{DestinationHash, IdentityHash, MessageId};
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+404
View File
@@ -0,0 +1,404 @@
//! Checked mutable construction followed by consuming signature/finalization.
use super::*;
use rns_crypto::ed25519::Ed25519PrivateKey;
/// Mutable outbound semantics. This type cannot be submitted as a wire message.
/// ```compile_fail
/// use lxmf_core::message::LxMessageDraft;
/// fn send_unsigned(draft: LxMessageDraft) { let _ = draft.wire_bytes(); }
/// ```
#[derive(Debug, Clone)]
pub struct LxMessageDraft {
destination: [u8; 16],
source: [u8; 16],
title: Bytes,
content: Bytes,
timestamp: f64,
fields: BTreeMap<FieldId, FieldValue>,
limits: MessageDecodeLimits,
pub metadata: MessageMetadata,
pub include_ticket: bool,
pub outbound_ticket: Option<[u8; 16]>,
pub stamp_cost: Option<u8>,
ticket_barrier: Option<Arc<()>>,
}
impl Deref for LxMessageDraft {
type Target = MessageMetadata;
fn deref(&self) -> &Self::Target {
&self.metadata
}
}
impl DerefMut for LxMessageDraft {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.metadata
}
}
/// Frozen signed body awaiting its optional recipient stamp. Not a sendable type.
#[derive(Debug)]
pub struct SignedLxMessage {
message: LxMessage,
outbound_ticket: Option<[u8; 16]>,
stamp_cost: Option<u8>,
}
impl Deref for SignedLxMessage {
type Target = MessageMetadata;
fn deref(&self) -> &Self::Target {
&self.message.metadata
}
}
impl DerefMut for SignedLxMessage {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.message.metadata
}
}
impl LxMessageDraft {
pub fn new(
destination: [u8; 16],
source: [u8; 16],
title: &str,
content: &str,
method: DeliveryMethod,
) -> Result<Self, MessageError> {
Self::new_with_limits(
destination,
source,
title,
content,
method,
MessageDecodeLimits::default(),
)
}
pub fn new_with_limits(
destination: [u8; 16],
source: [u8; 16],
title: &str,
content: &str,
method: DeliveryMethod,
limits: MessageDecodeLimits,
) -> Result<Self, MessageError> {
limits.check_wire(
title
.len()
.checked_add(content.len())
.and_then(|n| n.checked_add(110))
.ok_or_else(|| MessageError::PackFailed("length overflow".into()))?,
)?;
let draft = Self {
destination,
source,
title: Bytes::copy_from_slice(title.as_bytes()),
content: Bytes::copy_from_slice(content.as_bytes()),
timestamp: SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs_f64(),
fields: BTreeMap::new(),
limits,
metadata: MessageMetadata {
method,
..MessageMetadata::default()
},
include_ticket: false,
outbound_ticket: None,
stamp_cost: None,
ticket_barrier: None,
};
draft.checked_wire_len()?;
Ok(draft)
}
pub fn destination_hash(&self) -> [u8; 16] {
self.destination
}
pub fn source_hash(&self) -> [u8; 16] {
self.source
}
pub fn timestamp(&self) -> f64 {
self.timestamp
}
pub fn title_bytes(&self) -> &[u8] {
&self.title
}
pub fn content_bytes(&self) -> &[u8] {
&self.content
}
pub fn fields(&self) -> &BTreeMap<FieldId, FieldValue> {
&self.fields
}
pub(crate) fn mark_ticket_pending(&mut self, owner: Arc<()>) {
self.ticket_barrier = Some(owner);
}
pub(crate) fn release_ticket_barrier(&mut self, owner: &Arc<()>) -> bool {
if self
.ticket_barrier
.as_ref()
.is_some_and(|pending| Arc::ptr_eq(pending, owner))
{
self.ticket_barrier = None;
true
} else {
false
}
}
pub fn get_field(&self, id: impl Into<FieldId>) -> Option<&FieldValue> {
self.fields.get(&id.into())
}
pub fn set_timestamp(&mut self, value: f64) -> Result<(), MessageError> {
if !value.is_finite() {
return Err(MessageError::PackFailed(
"nonfinite outbound timestamp".into(),
));
}
self.timestamp = value;
Ok(())
}
pub fn set_title(&mut self, value: &str) -> Result<(), MessageError> {
self.set_text(value, true)
}
pub fn set_content(&mut self, value: &str) -> Result<(), MessageError> {
self.set_text(value, false)
}
fn set_text(&mut self, value: &str, title: bool) -> Result<(), MessageError> {
self.limits.check_wire(value.len())?;
let next = Bytes::copy_from_slice(value.as_bytes());
let old = if title {
std::mem::replace(&mut self.title, next)
} else {
std::mem::replace(&mut self.content, next)
};
if let Err(e) = self.checked_wire_len() {
if title {
self.title = old
} else {
self.content = old
};
return Err(e);
}
Ok(())
}
pub fn set_field(
&mut self,
id: impl Into<FieldId>,
bytes: impl Into<Bytes>,
) -> Result<(), MessageError> {
self.set_field_value(id, FieldValue::Binary(bytes.into()))
}
pub fn set_msgpack_field(
&mut self,
id: impl Into<FieldId>,
bytes: impl Into<Bytes>,
) -> Result<(), MessageError> {
self.set_field_value(
id,
FieldValue::MessagePack(EncodedFieldValue::new(bytes.into())?),
)
}
pub fn set_field_value(
&mut self,
id: impl Into<FieldId>,
value: FieldValue,
) -> Result<(), MessageError> {
let id = id.into();
if !self.fields.contains_key(&id) && self.fields.len() >= self.limits.max_top_level_fields {
return Err(MessageError::TooManyFields);
}
let old = self.fields.insert(id, value);
if let Err(e) = self.checked_wire_len() {
match old {
Some(v) => {
self.fields.insert(id, v);
}
None => {
self.fields.remove(&id);
}
};
return Err(e);
}
Ok(())
}
pub fn remove_field(&mut self, id: impl Into<FieldId>) -> Option<FieldValue> {
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)
}
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)
}
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)
}
/// Exact unsigned payload, for diagnostics; it is not a transmittable message.
pub fn pack_payload(&self) -> Result<Vec<u8>, MessageError> {
let size = self.checked_wire_len()?;
let mut out = Vec::with_capacity(size - 96);
self.write_payload(&mut out)?;
Ok(out)
}
pub fn checked_wire_len(&self) -> Result<usize, MessageError> {
if self.fields.len() > self.limits.max_top_level_fields {
return Err(MessageError::TooManyFields);
}
let mut counter = CountingWriter::default();
self.write_payload(&mut counter)?;
let len = counter
.bytes
.checked_add(96)
.ok_or_else(|| packed("length overflow"))?;
self.limits.check_wire(len)?;
Ok(len)
}
fn write_payload<W: Write>(&self, out: &mut W) -> Result<(), MessageError> {
rmp::encode::write_array_len(out, 4).map_err(packed)?;
rmp::encode::write_f64(out, self.timestamp).map_err(packed)?;
write_bin(out, &self.title)?;
write_bin(out, &self.content)?;
rmp::encode::write_map_len(out, length(self.fields.len())?).map_err(packed)?;
for (id, value) in &self.fields {
if id.as_i128() >= 0 {
rmp::encode::write_uint(out, u64::try_from(id.as_i128()).map_err(packed)?)
.map_err(packed)?;
} else {
rmp::encode::write_sint(out, i64::try_from(id.as_i128()).map_err(packed)?)
.map_err(packed)?;
}
match value {
FieldValue::Binary(b) => write_bin(out, b)?,
FieldValue::MessagePack(v) => out.write_all(v.encoded()).map_err(packed)?,
}
}
Ok(())
}
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>
where
F: FnOnce(&[u8]) -> Result<[u8; 64], E>,
E: std::fmt::Display,
{
if self.ticket_barrier.is_some() {
return Err(MessageError::TicketNotCommitted);
}
let size = self.checked_wire_len()?;
let mut signed = Vec::with_capacity(size);
signed.extend_from_slice(&self.destination);
signed.extend_from_slice(&self.source);
self.write_payload(&mut signed)?;
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)?;
message.metadata = self.metadata;
message.incoming = false;
message.state = MessageState::Outbound;
Ok(SignedLxMessage {
message,
outbound_ticket: self.outbound_ticket,
stamp_cost: self.stamp_cost,
})
}
}
impl SignedLxMessage {
pub fn timestamp(&self) -> f64 {
self.message.timestamp()
}
/// Complete no-stamp wire length; finalization can add a recipient stamp.
pub fn packed_len(&self) -> Result<usize, MessageError> {
self.message.packed_len()
}
/// Signed payload length, without exposing sendable bytes before finalization.
pub fn payload_len(&self) -> usize {
self.message.wire_bytes().len() - 96
}
pub fn title_bytes(&self) -> &[u8] {
self.message.title_bytes()
}
pub fn content_bytes(&self) -> &[u8] {
self.message.content_bytes()
}
pub fn title_text(&self) -> std::borrow::Cow<'_, str> {
self.message.title_text()
}
pub fn content_text(&self) -> std::borrow::Cow<'_, str> {
self.message.content_text()
}
pub fn message_id(&self) -> [u8; 32] {
self.message.message_id()
}
pub fn destination_hash(&self) -> [u8; 16] {
self.message.destination_hash()
}
pub fn source_hash(&self) -> [u8; 16] {
self.message.source_hash()
}
pub fn fields(&self) -> Fields<'_> {
self.message.fields()
}
pub fn stamp_cost(&self) -> Option<u8> {
self.stamp_cost
}
pub fn outbound_ticket(&self) -> Option<[u8; 16]> {
self.outbound_ticket
}
/// Compute the optional recipient stamp without changing the signed body.
pub fn generate_recipient_stamp(&self) -> Result<Option<RecipientStamp>, MessageError> {
if let Some(ticket) = self.outbound_ticket {
let mut material = [0u8; 48];
material[..16].copy_from_slice(&ticket);
material[16..].copy_from_slice(&self.message_id());
return Ok(Some(RecipientStamp::Ticket(truncated_hash(&material))));
}
let Some(cost) = self.stamp_cost else {
return Ok(None);
};
crate::stamper::generate_stamp(&self.message_id(), cost, STAMP_WORKBLOCK_EXPAND_ROUNDS)
.map(|(stamp, _)| Some(RecipientStamp::ProofOfWork(stamp)))
.ok_or_else(|| packed("recipient stamp generation failed"))
}
pub fn finalize(self, stamp: Option<RecipientStamp>) -> Result<LxMessage, MessageError> {
let Some(stamp) = stamp else {
return Ok(self.message);
};
let size = self
.message
.wire
.len()
.checked_add(2 + stamp.as_bytes().len())
.ok_or_else(|| packed("length overflow"))?;
self.message.limits.check_wire(size)?;
let mut wire = Vec::with_capacity(size);
wire.extend_from_slice(&self.message.wire);
wire[96] = 0x95;
write_bin(&mut wire, stamp.as_bytes())?;
let mut message = LxMessage::unpack_owned(wire.into(), self.message.limits)?;
debug_assert_eq!(message.message_id, self.message.message_id);
message.metadata = self.message.metadata;
Ok(message)
}
}
fn packed(error: impl std::fmt::Display) -> MessageError {
MessageError::PackFailed(error.to_string())
}
fn length(value: usize) -> Result<u32, MessageError> {
u32::try_from(value).map_err(packed)
}
fn write_bin<W: Write>(out: &mut W, bytes: &[u8]) -> Result<(), MessageError> {
rmp::encode::write_bin_len(out, length(bytes.len())?).map_err(packed)?;
out.write_all(bytes).map_err(packed)
}
+341
View File
@@ -0,0 +1,341 @@
//! Full-width LXMF field keys and coherent binary/structured values.
use super::{MessageError, read_msgpack_binary, skip_msgpack_value};
use bytes::Bytes;
use serde::{Deserialize, Serialize};
use std::{fmt, ops::Range};
/// A MessagePack integer field key, preserving the complete signed/unsigned domain.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FieldId(i128);
impl FieldId {
pub const fn as_i128(self) -> i128 {
self.0
}
pub fn as_standard(self) -> Option<u8> {
u8::try_from(self.0).ok()
}
}
macro_rules! field_from { ($($t:ty),*) => { $(impl From<$t> for FieldId { fn from(v:$t)->Self { Self(i128::from(v)) } })* }; }
field_from!(u8, u16, u32, u64, i8, i16, i32, i64);
impl TryFrom<i128> for FieldId {
type Error = MessageError;
fn try_from(v: i128) -> Result<Self, Self::Error> {
if v < i128::from(i64::MIN) || v > i128::from(u64::MAX) {
return Err(MessageError::InvalidFieldId);
}
Ok(Self(v))
}
}
impl Serialize for FieldId {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
if self.0 >= 0 {
s.serialize_u64(u64::try_from(self.0).map_err(serde::ser::Error::custom)?)
} else {
s.serialize_i64(i64::try_from(self.0).map_err(serde::ser::Error::custom)?)
}
}
}
impl<'de> Deserialize<'de> for FieldId {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct V;
impl serde::de::Visitor<'_> for V {
type Value = FieldId;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("a signed or unsigned 64-bit integer")
}
fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<FieldId, E> {
Ok(v.into())
}
fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<FieldId, E> {
Ok(v.into())
}
fn visit_i128<E: serde::de::Error>(self, v: i128) -> Result<FieldId, E> {
FieldId::try_from(v).map_err(E::custom)
}
fn visit_u128<E: serde::de::Error>(self, v: u128) -> Result<FieldId, E> {
u64::try_from(v).map(FieldId::from).map_err(E::custom)
}
}
d.deserialize_any(V)
}
}
/// One structurally valid encoded MessagePack value. Storage cannot be mutated.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EncodedFieldValue(Bytes);
impl EncodedFieldValue {
pub fn new(bytes: Bytes) -> Result<Self, MessageError> {
let mut remaining = bytes.as_ref();
skip_msgpack_value(&mut remaining, 0)?;
if !remaining.is_empty() {
return Err(MessageError::UnpackFailed("trailing field bytes".into()));
}
Ok(Self(bytes))
}
pub fn encoded(&self) -> &[u8] {
&self.0
}
}
/// A binary byte string or a native structured MessagePack value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FieldValue {
Binary(Bytes),
MessagePack(EncodedFieldValue),
}
impl Serialize for FieldValue {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
match self {
Self::Binary(b) => s.serialize_bytes(b),
Self::MessagePack(v) => {
let value = rmpv::decode::read_value(&mut v.encoded())
.map_err(serde::ser::Error::custom)?;
value.serialize(s)
}
}
}
}
impl<'de> Deserialize<'de> for FieldValue {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let value = rmpv::Value::deserialize(d)?;
if let rmpv::Value::Binary(b) = value {
return Ok(Self::Binary(b.into()));
}
let mut bytes = Vec::new();
rmpv::encode::write_value(&mut bytes, &value).map_err(serde::de::Error::custom)?;
EncodedFieldValue::new(bytes.into())
.map(Self::MessagePack)
.map_err(serde::de::Error::custom)
}
}
/// Borrowed exact encoded field value. Binary is never inferred to be structure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FieldValueRef<'a> {
pub(super) encoded: &'a [u8],
}
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.
pub fn from_encoded(encoded: &'a [u8]) -> Result<Self, MessageError> {
let mut remaining = encoded;
skip_msgpack_value(&mut remaining, 0)?;
if !remaining.is_empty() {
return Err(MessageError::UnpackFailed("trailing field bytes".into()));
}
Ok(Self { encoded })
}
/// Exact UTF-8 MessagePack text, without accepting a binary value as text.
pub fn as_text(self) -> Option<&'a str> {
if !matches!(self.encoded.first(), Some(0xa0..=0xbf | 0xd9..=0xdb)) {
return None;
}
let mut input = self.encoded;
let bytes = super::read_msgpack_string_or_binary(&mut input).ok()?;
if !input.is_empty() {
return None;
}
std::str::from_utf8(bytes).ok()
}
pub fn encoded(self) -> &'a [u8] {
self.encoded
}
pub fn as_binary(self) -> Option<&'a [u8]> {
let mut value = self.encoded;
let bytes = read_msgpack_binary(&mut value).ok()?;
value.is_empty().then_some(bytes)
}
/// Owned explicit copy, for constructing a new message deliberately.
pub fn to_owned(self) -> FieldValue {
match self.as_binary() {
Some(b) => FieldValue::Binary(Bytes::copy_from_slice(b)),
None => {
FieldValue::MessagePack(EncodedFieldValue(Bytes::copy_from_slice(self.encoded)))
}
}
}
}
#[derive(Debug, Clone)]
pub(super) struct FieldIndex {
pub id: FieldId,
pub range: Range<usize>,
}
const _: () = assert!(std::mem::size_of::<FieldIndex>() <= 32);
/// Numeric-key ordered view; original field wire order stays in the message.
#[derive(Debug, Clone, Copy)]
pub struct Fields<'a> {
pub(super) wire: &'a [u8],
pub(super) indexes: &'a [FieldIndex],
}
impl<'a> Fields<'a> {
pub fn get(self, id: impl Into<FieldId>) -> Option<FieldValueRef<'a>> {
let id = id.into();
self.indexes
.binary_search_by_key(&id, |entry| entry.id)
.ok()
.map(|i| FieldValueRef {
encoded: &self.wire[self.indexes[i].range.clone()],
})
}
pub fn contains(self, id: impl Into<FieldId>) -> bool {
self.get(id).is_some()
}
pub fn len(self) -> usize {
self.indexes.len()
}
pub fn is_empty(self) -> bool {
self.indexes.is_empty()
}
pub fn iter(self) -> impl ExactSizeIterator<Item = (FieldId, FieldValueRef<'a>)> {
self.indexes.iter().map(move |entry| {
(
entry.id,
FieldValueRef {
encoded: &self.wire[entry.range.clone()],
},
)
})
}
}
pub(super) mod map_serde {
use super::*;
use std::collections::BTreeMap;
pub fn serialize<S: serde::Serializer>(
map: &BTreeMap<FieldId, FieldValue>,
s: S,
) -> Result<S::Ok, S::Error> {
map.serialize(s)
}
pub fn deserialize<'de, D: serde::Deserializer<'de>>(
d: D,
) -> Result<BTreeMap<FieldId, FieldValue>, D::Error> {
struct V;
impl<'de> serde::de::Visitor<'de> for V {
type Value = BTreeMap<FieldId, FieldValue>;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("unique integer fields")
}
fn visit_map<A: serde::de::MapAccess<'de>>(
self,
mut access: A,
) -> Result<Self::Value, A::Error> {
let mut map = BTreeMap::new();
while let Some(key) = access.next_key::<FieldId>()? {
if map.len()
>= super::super::MessageDecodeLimits::default().max_top_level_fields
{
return Err(serde::de::Error::custom("too many fields"));
}
if map.contains_key(&key) {
return Err(serde::de::Error::custom("duplicate field ID"));
}
let value = access.next_value()?;
map.insert(key, value);
}
Ok(map)
}
}
d.deserialize_map(V)
}
}
/// Validated schema-map keys. Integer encodings normalize; text is exact UTF-8.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum FieldMapKey<'a> {
Integer(FieldId),
Text(&'a str),
}
/// Borrowed map values with a compact sorted key-offset index.
///
/// Intended for recognized reaction/chat/game schemas. Unknown structured fields
/// remain opaque and need not request this semantic validation. The index uses
/// four bytes per entry (at most twice the encoded field size), with no value copies.
#[derive(Debug)]
pub struct UniqueFieldMap<'a> {
encoded: &'a [u8],
offsets: Vec<u32>,
}
impl<'a> FieldValueRef<'a> {
pub fn unique_map(self) -> Result<UniqueFieldMap<'a>, MessageError> {
let mut input = self.encoded;
let count = super::read_msgpack_map_len(&mut input)? as usize;
if count > input.len() / 2 {
return Err(MessageError::UnpackFailed(
"impossible nested map count".into(),
));
}
let mut offsets = Vec::new();
offsets
.try_reserve_exact(count)
.map_err(|_| MessageError::UnpackFailed("nested map index allocation".into()))?;
for _ in 0..count {
offsets.push(
u32::try_from(self.encoded.len() - input.len())
.map_err(|_| MessageError::InvalidFieldId)?,
);
read_map_key(&mut input)?;
skip_msgpack_value(&mut input, 0)?;
}
if !input.is_empty() {
return Err(MessageError::UnpackFailed(
"trailing nested map bytes".into(),
));
}
let key_at = |offset: &u32| {
read_map_key(&mut &self.encoded[*offset as usize..])
.expect("validated immutable map key")
};
offsets.sort_unstable_by(|a, b| key_at(a).cmp(&key_at(b)));
if offsets
.windows(2)
.any(|pair| key_at(&pair[0]) == key_at(&pair[1]))
{
return Err(MessageError::DuplicateField);
}
Ok(UniqueFieldMap {
encoded: self.encoded,
offsets,
})
}
}
impl<'a> UniqueFieldMap<'a> {
pub fn len(&self) -> usize {
self.offsets.len()
}
pub fn is_empty(&self) -> bool {
self.offsets.is_empty()
}
pub fn get(&self, key: FieldMapKey<'_>) -> Option<FieldValueRef<'a>> {
let index = self
.offsets
.binary_search_by(|offset| {
read_map_key(&mut &self.encoded[*offset as usize..])
.expect("validated map key")
.cmp(&key)
})
.ok()?;
let mut input = &self.encoded[self.offsets[index] as usize..];
read_map_key(&mut input).ok()?;
let value = input;
skip_msgpack_value(&mut input, 0).ok()?;
Some(FieldValueRef {
encoded: &value[..value.len() - input.len()],
})
}
}
fn read_map_key<'a>(input: &mut &'a [u8]) -> Result<FieldMapKey<'a>, MessageError> {
if input
.first()
.is_some_and(|marker| matches!(*marker,0xa0..=0xbf|0xd9..=0xdb))
{
let text = super::read_msgpack_string_or_binary(input)?;
Ok(FieldMapKey::Text(std::str::from_utf8(text).map_err(
|_| MessageError::UnpackFailed("map key is not UTF-8".into()),
)?))
} else {
Ok(FieldMapKey::Integer(FieldId::try_from(
super::read_msgpack_integer(input)?,
)?))
}
}
@@ -0,0 +1 @@
/�äxîÒÝfPpVJך�*uÁ”qPp÷_I#D‰H®8
+733
View File
@@ -0,0 +1,733 @@
use super::*;
use rns_crypto::ed25519::Ed25519PrivateKey;
fn key() -> Ed25519PrivateKey {
Ed25519PrivateKey::from_bytes(&[7; 32])
}
fn draft() -> LxMessageDraft {
LxMessageDraft::new([1; 16], [2; 16], "title", "content", DeliveryMethod::Direct).unwrap()
}
fn freeze(draft: LxMessageDraft) -> LxMessage {
draft.sign(&key()).unwrap().finalize(None).unwrap()
}
fn payload(fields: &[u8], stamp: Option<&[u8]>) -> Vec<u8> {
let mut p = vec![if stamp.is_some() { 0x95 } else { 0x94 }];
rmp::encode::write_f64(&mut p, 1_700_000_000.).unwrap();
p.extend_from_slice(&[0xc4, 1, b'T', 0xc4, 1, b'C']);
p.extend_from_slice(fields);
if let Some(s) = stamp {
p.extend_from_slice(s);
}
p
}
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);
}
let hash = sha256(&signed);
signed.extend_from_slice(&hash);
let mut out = vec![1; 16];
out.extend_from_slice(&[2; 16]);
out.extend_from_slice(&key().sign(&signed));
out.extend_from_slice(payload);
out
}
#[test]
fn signed_body_finalization_defaults_and_states() {
let d = draft();
assert!(d.timestamp() > 0.);
assert_eq!(d.state, MessageState::Generating);
assert!(d.auto_compress);
assert!(!d.source_blackholed);
let signed = d.sign(&key()).unwrap();
let id = signed.message_id();
let mut m = signed.finalize(None).unwrap();
assert_eq!(m.state, MessageState::Outbound);
assert_eq!(m.message_id(), id);
let before = m.wire_owned();
m.mark_sending();
m.mark_sent();
m.mark_delivered();
assert_eq!(m.state, MessageState::Delivered);
m.mark_failed();
assert_eq!(m.state, MessageState::Failed);
m.mark_rejected();
assert_eq!(m.state, MessageState::Rejected);
assert_eq!(m.wire_bytes(), before.as_ref());
}
#[test]
fn received_wire_identity_repeated_verification_and_ownership() {
let mut p = payload(&[0x82, 0x0f, 0x01, 0x0c, 0x92, 0x00, 0xc4, 0x00], None);
// A retained noncanonical f32 timestamp cannot be reencoded as f64.
p.splice(1..10, [0xca, 0x3f, 0x80, 0x00, 0x00]);
let wire = Bytes::from(wire(&p));
let ptr = wire.as_ptr();
let mut m = LxMessage::unpack_owned(wire.clone(), MessageDecodeLimits::default()).unwrap();
assert_eq!(m.wire_bytes().as_ptr(), ptr);
let id = m.message_id();
assert!(m.verify_signature(&key().public_key()));
assert!(m.verify_signature(&key().public_key()));
assert_eq!(m.pack().unwrap(), wire);
assert_eq!(m.pack_payload().unwrap(), p);
assert_eq!(m.message_id(), id);
m.method = DeliveryMethod::Propagated;
m.progress = 0.8;
assert_eq!(m.clone().wire_bytes().as_ptr(), ptr);
assert_eq!(m.pack().unwrap(), wire);
let restored = LxMessage::unpack_container(&m.pack_container().unwrap()).unwrap();
assert_eq!(restored.wire_bytes(), wire);
assert_eq!(restored.message_id(), id);
assert!(restored.verify_signature(&key().public_key()));
}
#[test]
fn received_wire_identity_real_python_reordered_vector() {
// Emitted by Python LXMF 1.0.1: renderer precedes the subsequently added reply ticket.
let raw = include_bytes!("fixtures/python-reordered.bin");
let public = include_bytes!("fixtures/python-reordered-public.bin");
let key =
rns_crypto::ed25519::Ed25519PublicKey::from_bytes(public.as_slice().try_into().unwrap())
.unwrap();
let m = LxMessage::unpack(raw).unwrap();
assert!(m.verify_signature(&key));
assert!(m.verify_signature(&key));
assert_eq!(m.pack().unwrap(), raw);
let restored = LxMessage::unpack_container(&m.pack_container().unwrap()).unwrap();
assert_eq!(restored.wire_bytes(), raw);
assert_eq!(restored.message_id(), m.message_id());
assert!(restored.verify_signature(&key));
}
#[test]
fn received_wire_identity_source_binding() {
let identity = rns_identity::identity::Identity::from_private_key(&[7; 64]).unwrap();
let source = rns_identity::destination::Destination::hash_from_name_and_identity(
"lxmf.delivery",
Some(&identity.hash),
);
let d = LxMessageDraft::new([1; 16], source, "", "", DeliveryMethod::Direct).unwrap();
let m = freeze(d);
assert!(m.verify(&identity.get_public_key()).is_ok());
assert!(m.verify(&identity.get_public_key()).is_ok());
let mut altered = identity.get_public_key();
altered[..32].fill(8);
assert!(matches!(
m.verify(&altered),
Err(MessageError::SourceMismatch)
));
let wrong_source = freeze(draft());
assert!(wrong_source.verify_signature(&key().public_key()));
assert!(matches!(
wrong_source.verify(&identity.get_public_key()),
Err(MessageError::SourceMismatch)
));
assert!(!m.verify_signature(&Ed25519PrivateKey::from_bytes(&[9; 32]).public_key()));
}
#[test]
fn owned_verification_retains_exact_source_and_shared_wire_after_handoff() {
let identity = rns_identity::identity::Identity::from_private_key(&[7; 64]).unwrap();
let source = rns_identity::destination::Destination::hash_from_name_and_identity(
"lxmf.delivery",
Some(&identity.hash),
);
let message = freeze(
LxMessageDraft::new([1; 16], source, "title", "content", DeliveryMethod::Direct).unwrap(),
);
let pointer = message.wire_bytes().as_ptr();
let hash = message.message_id();
let owned = message
.verify(&identity.get_public_key())
.unwrap()
.to_owned();
drop(message);
let verified = owned.as_verified();
assert_eq!(verified.message().wire_bytes().as_ptr(), pointer);
assert_eq!(verified.message().message_id(), hash);
assert_eq!(verified.source_public_key(), &identity.get_public_key());
assert_eq!(verified.message().source_hash(), source);
}
#[test]
fn field_id_entire_domain_and_serde_roundtrip() {
let values = [
i64::MIN as i128,
-1,
0,
255,
256,
i64::MAX as i128,
i64::MAX as i128 + 1,
u64::MAX as i128,
];
let mut d = draft();
for v in values {
let id = FieldId::try_from(v).unwrap();
let bytes = rmp_serde::to_vec(&id).unwrap();
let decoded: FieldId = rmp_serde::from_slice(&bytes).unwrap();
assert_eq!(decoded, id);
d.set_field(id, vec![42]).unwrap();
}
let m = freeze(d);
for v in values {
assert_eq!(
m.get_field(FieldId::try_from(v).unwrap())
.unwrap()
.as_binary(),
Some(&[42][..])
);
}
assert!(FieldId::try_from(i64::MIN as i128 - 1).is_err());
assert!(FieldId::try_from(u64::MAX as i128 + 1).is_err());
assert!(FieldId::from(256u64).as_standard().is_none());
assert_eq!(FieldId::from(1u64), FieldId::from(1i64));
}
#[test]
fn field_id_never_aliases_native_ids() {
let mut d = draft();
d.set_field(0x105u64, vec![1]).unwrap();
d.set_field(0x10cu64, vec![2]).unwrap();
d.set_field(-1i64, vec![3]).unwrap();
let m = freeze(d);
assert!(!m.fields().contains(5u8));
assert!(!m.fields().contains(12u8));
assert!(!m.fields().contains(255u8));
assert_eq!(m.fields().len(), 3);
}
#[test]
fn field_id_duplicate_numeric_encodings_rejected() {
for map in [
vec![0x82, 1, 0xc0, 1, 0xc0],
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)
));
let mut dto = vec![0x94, 0xcb];
dto.extend_from_slice(&0f64.to_be_bytes());
dto.extend_from_slice(&[0xc4, 0, 0xc4, 0]);
dto.extend_from_slice(&map);
assert!(rmp_serde::from_slice::<MessagePayload>(&dto).is_err());
}
}
#[test]
fn field_id_coherent_replacement_and_binary_is_not_structure() {
let mut d = draft();
d.set_msgpack_field(FIELD_AUDIO, vec![0x92, 0x10, 0xc4, 0])
.unwrap();
d.set_field(FIELD_AUDIO, vec![0x92, 0x10, 0xc4, 0]).unwrap();
let m = freeze(d);
let value = m.get_field(FIELD_AUDIO).unwrap();
assert_eq!(value.as_binary(), Some(&[0x92, 0x10, 0xc4, 0][..]));
assert!(m.audio_field().is_err());
assert!(LxMessage::unpack(m.wire_bytes()).is_ok());
let mut d = draft();
d.set_field(FIELD_AUDIO, vec![0]).unwrap();
d.set_audio_field(0x10, &[1, 2]).unwrap();
assert_eq!(freeze(d).audio_field().unwrap().unwrap().bytes, &[1, 2]);
}
#[test]
fn field_id_opaque_nested_duplicate_map_is_preserved() {
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()
);
}
#[test]
fn field_id_profile_counts_inbound_and_outbound() {
let mut d = draft();
for i in 0..4096u64 {
d.set_field(i, Bytes::new()).unwrap();
}
d.set_field(0u64, vec![1]).unwrap();
assert!(matches!(
d.set_field(4096u64, Bytes::new()),
Err(MessageError::TooManyFields)
));
let m = freeze(d);
assert_eq!(m.fields().len(), 4096);
let smaller = MessageDecodeLimits {
max_top_level_fields: 4095,
..MessageDecodeLimits::default()
};
assert!(matches!(
LxMessage::unpack_owned(m.wire_owned(), smaller),
Err(MessageError::TooManyFields)
));
let profile = MessageDecodeLimits {
max_top_level_fields: 1,
..MessageDecodeLimits::default()
};
let mut d =
LxMessageDraft::new_with_limits([1; 16], [2; 16], "", "", DeliveryMethod::Direct, profile)
.unwrap();
d.set_field(1u8, vec![]).unwrap();
assert!(d.set_field(FIELD_TICKET, vec![]).is_err());
d.set_field(1u8, vec![2]).unwrap();
assert_eq!(freeze(d).fields().len(), 1);
let map = [0xdf, 0xff, 0xff, 0xff, 0xff];
assert!(LxMessage::unpack(&wire(&payload(&map, None))).is_err());
}
#[test]
fn signed_body_finalization_enforces_exact_stamp_limit() {
let base = freeze(draft()).wire_bytes().len();
let mut profile = MessageDecodeLimits {
max_wire_bytes: base,
max_top_level_fields: 4096,
};
let d = LxMessageDraft::new_with_limits(
[1; 16],
[2; 16],
"title",
"content",
DeliveryMethod::Direct,
profile,
)
.unwrap();
assert!(matches!(
d.sign(&key())
.unwrap()
.finalize(Some(RecipientStamp::Ticket([1; 16]))),
Err(MessageError::TooLarge { .. })
));
profile.max_wire_bytes = base + 18;
let d = LxMessageDraft::new_with_limits(
[1; 16],
[2; 16],
"title",
"content",
DeliveryMethod::Direct,
profile,
)
.unwrap();
assert_eq!(
d.sign(&key())
.unwrap()
.finalize(Some(RecipientStamp::Ticket([1; 16])))
.unwrap()
.wire_bytes()
.len(),
base + 18
);
}
#[test]
fn signed_body_finalization_stamp_preserves_id_and_signature() {
let mut d = draft();
d.set_timestamp(1700000000.).unwrap();
let no_stamp = freeze(d.clone());
for stamp in [
RecipientStamp::Ticket([3; 16]),
RecipientStamp::ProofOfWork([4; 32]),
] {
let m = d
.clone()
.sign(&key())
.unwrap()
.finalize(Some(stamp))
.unwrap();
assert_eq!(m.message_id(), no_stamp.message_id());
assert_eq!(m.signature(), no_stamp.signature());
assert!(m.verify_signature(&key().public_key()));
assert_eq!(m.recipient_stamp(), Some(&stamp));
assert_eq!(
LxMessage::unpack(m.wire_bytes()).unwrap().message_id(),
no_stamp.message_id()
);
}
}
#[test]
fn recipient_stamp_array_range_and_malformed_dispositions() {
for (element, valid) in [
(vec![0], true),
(vec![0xcc, 255], true),
(vec![0xd1, 0, 255], true),
(vec![0xff], false),
(vec![0xcd, 1, 0], false),
(vec![0xcf, 255, 255, 255, 255, 255, 255, 255, 255], false),
] {
let mut stamp = vec![0xdc, 0, 16];
for _ in 0..16 {
stamp.extend_from_slice(&element);
}
let bytes = wire(&payload(&[0x80], Some(&stamp)));
let m = LxMessage::unpack(&bytes).unwrap();
assert_eq!(m.recipient_stamp().is_some(), valid);
assert_eq!(m.wire_bytes(), bytes);
assert!(m.verify_signature(&key().public_key()));
if !valid {
assert!(!m.validate_stamp_with_tickets(0, None));
}
}
for stamp in [vec![0xc0], vec![0x91, 0], vec![0xc4, 1, 0], vec![0xa0]] {
let m = LxMessage::unpack(&wire(&payload(&[0x80], Some(&stamp)))).unwrap();
assert!(m.recipient_stamp().is_none());
}
for stamp in [vec![], vec![0xc4], {
let mut s = vec![0xdc, 0, 16];
s.extend_from_slice(&[0xc0; 16]);
s
}] {
assert!(LxMessage::unpack(&wire(&payload(&[0x80], Some(&stamp)))).is_err());
}
}
#[test]
fn recipient_ticket_stamp_and_missing_stamp_policy() {
let mut d = draft();
d.outbound_ticket = Some([3; 16]);
let signed = d.sign(&key()).unwrap();
let stamp = signed.generate_recipient_stamp().unwrap();
let m = signed.finalize(stamp).unwrap();
assert!(m.validate_stamp_with_tickets(255, Some(&[vec![3; 16]])));
assert_eq!(
m.validated_stamp_value(255, Some(&[vec![3; 16]])),
Some(COST_TICKET)
);
assert!(!m.validate_stamp_with_tickets(1, Some(&[vec![4; 16]])));
assert!(!freeze(draft()).validate_stamp_with_tickets(0, None));
let signed = draft().sign(&key()).unwrap();
assert_eq!(signed.generate_recipient_stamp().unwrap(), None);
}
#[test]
fn signed_body_finalization_matches_semantic_dto() {
let mut d = draft();
d.set_timestamp(1700000000.).unwrap();
d.set_field(256u64, vec![1, 2]).unwrap();
d.set_msgpack_field(-1i64, vec![0x92, 1, 0xc4, 0]).unwrap();
let dto = MessagePayload {
timestamp: d.timestamp(),
title: "title".into(),
content: "content".into(),
fields: d.fields().clone(),
stamp: None,
};
let encoded = rmp_serde::to_vec(&dto).unwrap();
assert_eq!(d.pack_payload().unwrap(), encoded);
let decoded: MessagePayload = rmp_serde::from_slice(&encoded).unwrap();
assert_eq!(decoded.fields, dto.fields);
}
#[test]
fn native_attachments_borrow_exact_image_and_clone() {
let data = vec![0xa5; 2 * 1024 * 1024];
let mut d = draft();
d.set_audio_field(AM_OPUS_OGG, &data).unwrap();
d.set_image_field("webp", &[2, 3]).unwrap();
d.set_file_attachment_field("test.bin", &[4, 5]).unwrap();
let m = freeze(d);
let audio = m.audio_field().unwrap().unwrap();
assert_eq!(audio.bytes, data);
let start = m.wire_bytes().as_ptr() as usize;
assert!((start..start + m.wire_bytes().len()).contains(&(audio.bytes.as_ptr() as usize)));
assert_eq!(m.clone().wire_bytes().as_ptr(), m.wire_bytes().as_ptr());
assert_eq!(
m.image_attachment().unwrap(),
Some(("webp".into(), &[2, 3][..]))
);
assert_eq!(
m.first_file_attachment().unwrap(),
Some(("test.bin".into(), &[4, 5][..]))
);
assert_eq!(m.packed_len().unwrap(), m.pack().unwrap().len());
assert!(m.verify_signature(&key().public_key()));
assert_eq!(
m.audio_field().unwrap().unwrap().bytes.as_ptr(),
audio.bytes.as_ptr()
);
}
#[test]
fn native_audio_shape_and_optional_failure() {
for malformed in [
vec![0xc0],
vec![0x91, 0x10],
vec![0x93, 0x10, 0xc4, 0, 0xc0],
vec![0x92, 0xff, 0xc4, 0],
vec![0x92, 0xcd, 1, 0, 0xc4, 0],
vec![0x92, 0xc0, 0xc4, 0],
vec![0x92, 0x10, 0xa0],
] {
let mut d = draft();
d.set_msgpack_field(FIELD_AUDIO, malformed).unwrap();
let m = freeze(d);
assert!(m.audio_field().is_err());
assert_eq!(m.content_text(), "content");
assert!(m.verify_signature(&key().public_key()));
}
let mut d = draft();
assert!(
d.set_msgpack_field(FIELD_AUDIO, vec![0x92, 0x10, 0xc4])
.is_err()
);
assert!(
d.set_msgpack_field(FIELD_AUDIO, vec![0x92, 0x10, 0xc4, 0, 0xc0])
.is_err()
);
d.set_msgpack_field(FIELD_AUDIO, vec![0x92, 0xcd, 0, 255, 0xc4, 0])
.unwrap();
assert_eq!(freeze(d).audio_field().unwrap().unwrap().mode, 255);
}
#[test]
fn received_wire_identity_paper_and_opportunistic_use_exact_tail() {
let mut m = freeze(draft());
m.method = DeliveryMethod::Paper;
let uri = m.to_paper_uri(|tail| Ok(tail.to_vec())).unwrap();
assert!(uri.starts_with("lxm://"));
let read = LxMessage::from_paper_uri(&uri, |tail| Ok(tail.to_vec())).unwrap();
assert_eq!(read.wire_bytes(), m.wire_bytes());
assert!(read.verify_signature(&key().public_key()));
assert_eq!(
m.pack_opportunistic_encrypted(|tail| Ok(tail.to_vec()))
.unwrap(),
m.wire_bytes()[16..]
);
assert!(LxMessage::decode_paper_uri("not-uri").is_err());
assert!(LxMessage::decode_paper_uri("lxm://!!").is_err());
m.method = DeliveryMethod::Direct;
assert!(m.to_paper_uri(|b| Ok(b.to_vec())).is_err());
}
#[test]
fn received_wire_identity_file_and_method_roundtrips() {
let dir = tempfile::tempdir().unwrap();
let mut m = freeze(draft());
m.state = MessageState::Delivered;
m.transport_encrypted = true;
m.transport_encryption = Some("ECIES".into());
for method in [
DeliveryMethod::Direct,
DeliveryMethod::Propagated,
DeliveryMethod::Paper,
DeliveryMethod::Opportunistic,
] {
m.method = method;
let path = m.write_to_directory(dir.path().to_str().unwrap()).unwrap();
let read = LxMessage::read_from_file(&path).unwrap();
assert_eq!(read.method, method);
assert_eq!(read.state, MessageState::Delivered);
assert_eq!(read.wire_bytes(), m.wire_bytes());
assert_eq!(read.transport_encryption, m.transport_encryption);
assert!(read.verify_signature(&key().public_key()));
}
}
#[test]
fn message_callbacks_and_compression_metadata_do_not_mutate_wire() {
use std::sync::atomic::{AtomicUsize, Ordering};
let mut m = freeze(draft());
let before = m.wire_owned();
let calls = Arc::new(AtomicUsize::new(0));
let c = calls.clone();
m.register_delivery_callback(move |_| {
c.fetch_add(1, Ordering::SeqCst);
});
let c = calls.clone();
m.register_failed_callback(move |_| {
c.fetch_add(10, Ordering::SeqCst);
});
m.mark_delivered();
m.mark_failed();
assert_eq!(calls.load(Ordering::SeqCst), 11);
m.determine_compression_support(None);
assert!(m.auto_compress);
m.determine_compression_support(Some(&[0x93, 0xc0, 0xc0, 0x90]));
assert!(!m.auto_compress);
assert_eq!(m.wire_bytes(), before);
}
#[test]
fn propagation_wrapper_compatibility_and_bounds() {
let entry = vec![1; LxMessage::MIN_PROPAGATION_ENTRY_SIZE];
let entries = [entry.as_slice()];
let encoded = rmp_serde::to_vec(&PropagationWrapperRef {
timestamp: 1.,
entries: &entries,
})
.unwrap();
assert_eq!(
LxMessage::unpack_propagation_wrapper(&encoded).unwrap().1,
vec![entry]
);
assert!(LxMessage::unpack_propagation_wrapper_bounded(&encoded, encoded.len()).is_ok());
assert!(LxMessage::unpack_propagation_wrapper_bounded(&encoded, encoded.len() - 1).is_err());
assert_eq!(
LxMessage::compute_propagation_transient_id(&encoded),
full_hash(&encoded)
);
}
#[test]
fn received_wire_identity_bounds_and_invalid_utf8_preserved() {
for len in 0..97 {
assert!(LxMessage::unpack(&vec![0; len]).is_err());
}
let mut p = payload(&[0x80], None);
p[12] = 255;
let raw = wire(&p);
let m = LxMessage::unpack(&raw).unwrap();
assert_eq!(m.title_bytes(), &[255]);
assert_eq!(m.title_text(), "\u{fffd}");
assert_eq!(m.wire_bytes(), raw);
assert!(m.verify_signature(&key().public_key()));
let limits = MessageDecodeLimits {
max_wire_bytes: raw.len() - 1,
..MessageDecodeLimits::default()
};
assert!(LxMessage::unpack_owned(raw.into(), limits).is_err());
}
#[test]
fn nested_field_duplicate_schema_reader_rejects_ambiguous_keys() {
for encoded in [
vec![0x82, 0xa1, b'a', 1, 0xa1, b'a', 2],
vec![0x82, 1, 0, 0xd1, 0, 1, 1],
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 mut d = draft();
d.set_msgpack_field(300u64, vec![0x82, 0xa1, b'a', 0xc4, 1, 7, 0x01, 0x02])
.unwrap();
let m = freeze(d);
let map = m.get_field(300u64).unwrap().unique_map().unwrap();
assert_eq!(map.len(), 2);
assert_eq!(
map.get(FieldMapKey::Text("a")).unwrap().as_binary(),
Some(&[7][..])
);
assert_eq!(
map.get(FieldMapKey::Integer(1u8.into())).unwrap().encoded(),
&[2]
);
}
#[test]
fn signed_body_finalization_ticket_barrier_blocks_signer() {
let owner = Arc::new(());
let mut d = draft();
d.mark_ticket_pending(owner.clone());
assert!(!d.release_ticket_barrier(&Arc::new(())));
assert!(matches!(
d.clone()
.sign_with(|_| -> Result<[u8; 64], &str> { panic!("uncommitted signer called") }),
Err(MessageError::TicketNotCommitted)
));
assert!(d.release_ticket_barrier(&owner));
assert!(!d.release_ticket_barrier(&owner));
assert!(d.sign(&key()).is_ok());
}
#[test]
fn lossy_projection_uses_exact_capacity_and_preserves_utf8_replacement() {
for bytes in [
b"".as_slice(),
b"valid \xf0\x9f\xa6\x80".as_slice(),
b"\xff\xff\xff".as_slice(),
b"a\xf0\x90\x80".as_slice(),
b"a\xed\xa0\x80b\xc0\x80c".as_slice(),
] {
let actual = bounded_lossy_text(bytes);
assert_eq!(actual, String::from_utf8_lossy(bytes));
match actual {
Cow::Borrowed(text) => assert_eq!(text.as_ptr(), bytes.as_ptr()),
Cow::Owned(text) => assert_eq!(text.capacity(), text.len()),
}
}
let bytes = vec![0xff; 1024 * 1024];
let repaired = bounded_lossy_text(&bytes).into_owned();
assert_eq!(repaired.len(), bytes.len() * 3);
assert_eq!(repaired.capacity(), repaired.len());
}
proptest::proptest! {
#[test]
fn bounded_lossy_projection_matches_standard(bytes in proptest::collection::vec(proptest::prelude::any::<u8>(), 0..4096)) {
let actual = bounded_lossy_text(&bytes);
proptest::prop_assert_eq!(&actual, &String::from_utf8_lossy(&bytes));
if let Cow::Owned(text) = actual {
proptest::prop_assert_eq!(text.capacity(), text.len());
proptest::prop_assert!(text.len() <= 3 * bytes.len());
}
}
}
#[test]
fn borrowed_encoded_field_validates_shape_without_copy_or_implicit_conversion() {
let encoded = b"\xa4text";
let field = FieldValueRef::from_encoded(encoded).unwrap();
assert_eq!(field.encoded().as_ptr(), encoded.as_ptr());
assert_eq!(field.as_text(), Some("text"));
assert!(field.as_binary().is_none());
assert!(
FieldValueRef::from_encoded(b"\xc4\x04text")
.unwrap()
.as_text()
.is_none()
);
assert!(
FieldValueRef::from_encoded(b"\xa1\xff")
.unwrap()
.as_text()
.is_none()
);
for invalid in [b"".as_slice(), b"\xa5text", b"\xa4text\xc0", b"\x81\x01"] {
assert!(FieldValueRef::from_encoded(invalid).is_err());
}
let duplicate = FieldValueRef::from_encoded(b"\x82\x01\x02\xcc\x01\x03").unwrap();
assert!(matches!(
duplicate.unique_map(),
Err(MessageError::DuplicateField)
));
}
#[test]
fn owned_propagation_wrapper_shares_binary_and_preserves_legacy_byte_arrays() {
let entry = vec![0xff; LxMessage::MIN_PROPAGATION_ENTRY_SIZE];
let entries = [entry.as_slice()];
let binary = Bytes::from(
rmp_serde::to_vec(&PropagationWrapperRef {
timestamp: 1.,
entries: &entries,
})
.unwrap(),
);
let (_, decoded) =
LxMessage::unpack_propagation_wrapper_owned(binary.clone(), binary.len()).unwrap();
assert_eq!(decoded[0].as_ref(), entry);
assert_eq!(
decoded[0].as_ptr(),
binary[binary.len() - entry.len()..].as_ptr()
);
drop(binary);
assert_eq!(decoded[0].as_ref(), entry);
let legacy = rmp_serde::to_vec(&(1.0, vec![entry.clone()])).unwrap();
assert_eq!(
LxMessage::unpack_propagation_wrapper_bounded(&legacy, legacy.len())
.unwrap()
.1,
vec![entry]
);
}
#[test]
fn bounded_propagation_wrapper_rejects_forged_counts_and_lengths_before_allocation() {
let forged_count = [0x92, 0x01, 0xdd, 0xff, 0xff, 0xff, 0xff];
assert!(
LxMessage::unpack_propagation_wrapper_owned(
Bytes::copy_from_slice(&forged_count),
usize::MAX
)
.is_err()
);
for marker in [0xdd, 0xc6] {
let mut forged_length = vec![0x92, 0x01, 0x91, marker, 0xff, 0xff, 0xff, 0xff];
forged_length.resize(1024, 0);
assert!(LxMessage::unpack_propagation_wrapper_bounded(&forged_length, 1024).is_err());
}
let mut trailing = rmp_serde::to_vec(&(1.0, Vec::<Vec<u8>>::new())).unwrap();
trailing.push(0);
assert!(LxMessage::unpack_propagation_wrapper_bounded(&trailing, trailing.len()).is_err());
}
+166 -50
View File
@@ -34,52 +34,75 @@ pub struct PersistedNodeStats {
pub unpeered_propagation_rx_bytes: u64,
}
/// Atomically write `data` to `path`: unique tmp file + flush + fsync + rename.
///
/// Tmp name is `<path>.tmp.<pid>.<16 random hex>` so concurrent writers (or
/// other processes) never collide; the tmp file is unlinked on error. An fsync
/// failure is logged as a warning and is non-fatal, matching Python
/// `LXMessage.write_to_directory` — LXMessage.py:674-696 (1.0.1).
/// Publish exact bytes through the strict platform durability boundary.
/// CommitUncertain remains an error: readback alone cannot authorize a receipt.
pub fn write_file_atomic(path: &Path, data: &[u8]) -> io::Result<()> {
use std::io::Write;
rns_identity::persistence::durable_write(path, data)
.map(|_| ())
.map_err(io::Error::other)
}
let random: [u8; 8] = rand::random();
let tmp_name = format!(
"{}.tmp.{}.{}",
path.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default(),
std::process::id(),
hex::encode(random)
);
let tmp = path.with_file_name(tmp_name);
/// Suppression state cannot authorize a remote purge. Adapters nevertheless
/// persist it before allowing the next automatic wants selection.
pub fn save_suppression(
dir: &Path,
ledger: &crate::admission::SuppressionLedger,
) -> io::Result<()> {
write_mpk(&dir.join("propagation_suppression_v1"), ledger)
}
let result = (|| {
let mut file = fs::File::create(&tmp)?;
file.write_all(data)?;
file.flush()?;
if let Err(e) = file.sync_all() {
tracing::warn!(
"Error while waiting for persist fsync for {}: {e}",
tmp.display()
);
}
drop(file);
fs::rename(&tmp, path)
})();
if result.is_err()
&& tmp.exists()
&& let Err(e) = fs::remove_file(&tmp)
{
tracing::error!(
"Error while cleaning temporary file {} for {}: {e}",
tmp.display(),
path.display()
);
pub fn load_suppression(dir: &Path) -> io::Result<crate::admission::SuppressionLedger> {
// Preserve the existing one-field wrapper while rejecting duplicate keys,
// mismatched embedded scope and quota violations before hydration.
#[derive(serde::Deserialize)]
struct Wire {
#[serde(deserialize_with = "suppression_records")]
records: Vec<crate::admission::SuppressionRecord>,
}
let wire: Option<Wire> =
read_mpk_bounded(&dir.join("propagation_suppression_v1"), 65536 * 512 + 4096)?;
crate::admission::SuppressionLedger::from_records(
wire.map_or_else(Vec::new, |wire| wire.records),
)
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
}
fn suppression_records<'de, D: serde::Deserializer<'de>>(
deserializer: D,
) -> Result<Vec<crate::admission::SuppressionRecord>, D::Error> {
struct Records;
impl<'de> serde::de::Visitor<'de> for Records {
type Value = Vec<crate::admission::SuppressionRecord>;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("bounded unique suppression map")
}
fn visit_map<M: serde::de::MapAccess<'de>>(
self,
mut map: M,
) -> Result<Self::Value, M::Error> {
let mut seen = std::collections::HashSet::new();
let mut records = Vec::new();
while let Some((scope,record))=map.next_entry::<crate::admission::AdmissionScope,crate::admission::SuppressionRecord>()? {
if scope!=record.scope || !seen.insert(scope) || records.len()>=crate::admission::SuppressionLedger::GLOBAL {
return Err(serde::de::Error::custom("invalid suppression scope or capacity"));
}
records.push(record);
}
Ok(records)
}
}
deserializer.deserialize_map(Records)
}
result
pub fn save_node_policies(
dir: &Path,
policies: &HashMap<[u8; 16], crate::propagation_send::AdvertisedNodePolicy>,
) -> io::Result<()> {
write_mpk(&dir.join("propagation_node_policies_v1"), policies)
}
pub fn load_node_policies(
dir: &Path,
) -> io::Result<HashMap<[u8; 16], crate::propagation_send::AdvertisedNodePolicy>> {
Ok(read_mpk(&dir.join("propagation_node_policies_v1"))?.unwrap_or_default())
}
fn write_mpk<T: serde::Serialize>(path: &Path, value: &T) -> io::Result<()> {
@@ -92,15 +115,33 @@ fn write_mpk<T: serde::Serialize>(path: &Path, value: &T) -> io::Result<()> {
}
fn read_mpk<T: serde::de::DeserializeOwned>(path: &Path) -> io::Result<Option<T>> {
match fs::read(path) {
Ok(bytes) => {
let value = rmp_serde::from_slice(&bytes)
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
Ok(Some(value))
}
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e),
read_mpk_bounded(path, 64 * 1024 * 1024)
}
fn read_mpk_bounded<T: serde::de::DeserializeOwned>(
path: &Path,
limit: usize,
) -> io::Result<Option<T>> {
use std::io::Read;
let file = match fs::File::open(path) {
Ok(file) => file,
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(error) => return Err(error),
};
let mut bytes = Vec::new();
file.take(limit as u64 + 1).read_to_end(&mut bytes)?;
if bytes.len() > limit {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"router state exceeds bounded capacity",
));
}
// Allocation-free structural walk precedes serde's collection size hints.
// It also rejects trailing roots, deep nesting and truncated huge lengths.
let encoded = crate::message::EncodedFieldValue::new(bytes.into())
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?;
rmp_serde::from_slice(encoded.encoded())
.map(Some)
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))
}
pub fn save_stamp_costs(dir: &Path, costs: &HashMap<[u8; 16], StampCostEntry>) -> io::Result<()> {
@@ -111,8 +152,83 @@ pub fn load_stamp_costs(dir: &Path) -> io::Result<HashMap<[u8; 16], StampCostEnt
Ok(read_mpk(&dir.join(STAMP_COSTS_FILE))?.unwrap_or_default())
}
/// Process-local revision of a captured ticket state. All production ticket
/// writes pass through the same path coordinator, so a delayed checkpoint can
/// never replace a ticket that a newer signing intent already committed.
#[derive(Debug, Clone)]
pub(crate) struct TicketPersistenceSnapshot {
revision: u64,
snapshot: std::sync::Arc<TicketStoreSnapshot>,
}
impl TicketPersistenceSnapshot {
pub(crate) fn capture(snapshot: TicketStoreSnapshot) -> Self {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(1);
// Rust 1.99 renamed this operation; keep the identical Rust 1.89 API.
#[allow(deprecated)]
let revision = NEXT
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_add(1))
.expect("ticket checkpoint revision exhausted");
Self {
revision,
snapshot: std::sync::Arc::new(snapshot),
}
}
pub(crate) fn save(&self, dir: &Path, required: Option<&Ticket>) -> io::Result<()> {
use std::sync::{Mutex, OnceLock};
struct Latest {
revision: u64,
committed: bool,
}
static WRITERS: OnceLock<Mutex<HashMap<std::path::PathBuf, Latest>>> = OnceLock::new();
fs::create_dir_all(dir)?;
let path = fs::canonicalize(dir)?.join(TICKETS_FILE);
let mut writers = WRITERS
.get_or_init(|| Mutex::new(HashMap::new()))
.lock()
.map_err(|_| io::Error::other("ticket persistence coordinator unavailable"))?;
if !writers.contains_key(&path) && writers.len() >= 4096 {
return Err(io::Error::other("ticket persistence path quota exhausted"));
}
let latest = writers.entry(path.clone()).or_insert(Latest {
revision: self.revision,
committed: false,
});
if self.revision < latest.revision {
if !latest.committed {
return Err(io::Error::other(
"newer ticket checkpoint is uncertain and must be retried",
));
}
if let Some(required) = required {
let (stored, _) = load_tickets(dir)?;
if !stored.inbound.contains(required) {
return Err(io::Error::other(
"newer ticket state no longer contains this signing intent",
));
}
}
return Ok(());
}
if required.is_some_and(|required| !self.snapshot.inbound.contains(required)) {
return Err(io::Error::other(
"ticket snapshot does not contain this signing intent",
));
}
latest.revision = self.revision;
latest.committed = false;
// Even an uncertain publication raises the revision floor. Older
// snapshots fail closed until this or a newly captured current state
// reestablishes the strict barrier. No failed payload is retained by
// this bounded process-wide metadata coordinator.
write_mpk(&path, &*self.snapshot)?;
latest.committed = true;
Ok(())
}
}
pub fn save_tickets(dir: &Path, tickets: &TicketStoreSnapshot) -> io::Result<()> {
write_mpk(&dir.join(TICKETS_FILE), tickets)
TicketPersistenceSnapshot::capture(tickets.clone()).save(dir, None)
}
#[derive(serde::Deserialize)]
+33
View File
@@ -11,6 +11,23 @@ pub const MAX_ADVERTISED_NAME_CHARS: usize = 128;
/// codepoints, collapses all Unicode whitespace to one ASCII space, and is
/// truncated by Unicode scalar values rather than UTF-8 bytes.
pub fn sanitize_name(input: &str, max_chars: usize) -> String {
let mut output = sanitize_name_pass(input, max_chars);
let rounds = output.nfkd().count().saturating_add(2);
for _ in 0..rounds {
let next = sanitize_name_pass(&output, max_chars);
if next == output {
return output;
}
output = next;
}
debug_assert!(
false,
"name normalization exceeded its derived stabilization bound"
);
String::new()
}
fn sanitize_name_pass(input: &str, max_chars: usize) -> String {
if max_chars == 0 {
return String::new();
}
@@ -146,6 +163,22 @@ mod tests {
assert_eq!(sanitize_name("A B", 3), "A B");
}
#[test]
fn normalization_reaches_fixed_point_after_filtered_separators() {
for input in [
"A\u{0000}\u{030A}",
"e\u{034f}\u{0301}",
"o\u{200d}\u{0308}",
] {
for limit in 0..8 {
let once = sanitize_name(input, limit);
assert_eq!(sanitize_name(&once, limit), once);
assert_eq!(once.nfkc().collect::<String>(), once);
}
}
assert_eq!(sanitize_name("™", 128), "TM");
}
proptest! {
#[test]
fn arbitrary_utf8_is_bounded_and_idempotent(input in ".*", limit in 0usize..256) {
File diff suppressed because it is too large. Load diff
+394 -89
View File
@@ -1,4 +1,5 @@
//! In-process encrypted peers: every emitted packet is checked at the real MTU.
use super::tests::{downloaded_bytes, fixture_download};
use super::*;
use rmpv::Value;
use rns_wire::{context::PacketContext as Context, flags::PacketType};
@@ -15,6 +16,8 @@ struct Peer {
drop_hmu: bool,
drop_request: bool,
retries: usize,
admission_dir: tempfile::TempDir,
admitted: Vec<Vec<u8>>,
}
impl Peer {
@@ -44,9 +47,52 @@ impl Peer {
drop_hmu: false,
drop_request: false,
retries: 0,
admission_dir: tempfile::tempdir().unwrap(),
admitted: Vec::new(),
}
}
/// Protocol-unit-test recipient seam. The simulated decryptor maps each
/// opaque response to distinct actually signed bytes; FileAdmissionStore
/// must commit them before the client is allowed to send its purge.
fn accept_downloads(&mut self) {
use crate::admission::{
AdmissionRecord, DownloadAdmissionOutcome, DurableAdmissionReceipt, DurableDisposition,
};
let store = crate::admission_store::FileAdmissionStore::open(
self.admission_dir.path(),
&self.admission_dir.path().join("messages"),
)
.unwrap();
for downloaded in self.client.take_downloaded_messages() {
let (data, token) = downloaded.into_parts();
let scope = token.scope();
let message = crate::message::test_message(
[1; 16],
[2; 16],
&hex::encode(scope.transient_id),
"simulated recipient decryption",
crate::constants::DeliveryMethod::Propagated,
);
let record = AdmissionRecord {
scope,
message_id: message.message_id(),
received_wire_hash: rns_crypto::sha::full_hash(message.wire_bytes()),
stored_message_wire_hash: None,
disposition: DurableDisposition::Committed,
committed_at: 100,
};
let receipt =
DurableAdmissionReceipt::commit(store.prepare(record, message.wire_owned(), false))
.unwrap();
self.admitted.push(data.to_vec());
token
.resolve(DownloadAdmissionOutcome::Accepted(receipt))
.unwrap();
}
self.client.poll_admissions();
}
fn inject(&mut self, context: Context, payload: &[u8]) {
let raw = PropagationClient::link_packet_bytes(
self.link.link_id,
@@ -65,6 +111,7 @@ impl Peer {
self.client
.event_tx
.try_send(DestinationEvent::InboundPacket {
interface_owner: None,
raw: raw.into(),
interface_id: 7,
metrics: Default::default(),
@@ -279,19 +326,20 @@ impl Peer {
}
}
fn blob(index: usize) -> Vec<u8> {
let mut data = (0u64..5)
.flat_map(|v| rns_crypto::sha::full_hash(&v.to_be_bytes()))
.collect::<Vec<_>>();
data[..8].copy_from_slice(&(index as u64).to_be_bytes());
data
}
fn ids(n: usize) -> Vec<Vec<u8>> {
(0..n)
.map(|i| rns_crypto::sha::full_hash(&(i as u64).to_be_bytes()).to_vec())
.map(|i| rns_crypto::sha::full_hash(&blob(i)).to_vec())
.collect()
}
fn blobs(n: usize) -> Vec<Vec<u8>> {
(0..n)
.map(|i| {
let mut data = ids(5).concat();
data[..8].copy_from_slice(&(i as u64).to_be_bytes());
data
})
.collect()
(0..n).map(blob).collect()
}
fn binary_list(items: &[Vec<u8>]) -> Value {
Value::Array(items.iter().cloned().map(Value::Binary).collect())
@@ -353,12 +401,22 @@ fn fifty_downloaded_messages_survive_get_and_purge_resource_round_trip() {
assert_eq!(request.as_array().unwrap()[0], binary_list(&wants));
peer.response(get_id, binary_list(&messages), true);
assert_eq!(peer.client.received_count(), 50);
assert_eq!(
peer.client.state(),
PropagationClientState::AwaitingAdmission
);
peer.accept_downloads();
let (purge_id, request, _) = peer.request(true);
assert_eq!(request, Value::Array(vec![Value::Nil, binary_list(&wants)]));
peer.response(purge_id, empty(), true);
assert_eq!(peer.client.state(), PropagationClientState::Complete);
assert_eq!(peer.client.transfer_status().result, Some(50));
assert_eq!(peer.client.take_received_messages(), messages);
let counts = peer.client.transfer_status().admission;
assert_eq!(counts.downloaded, 50);
assert_eq!(counts.committed, 50);
assert_eq!(counts.rejected, 0);
assert_eq!(counts.retryable, 0);
assert_eq!(peer.admitted, messages);
assert_eq!(peer.resource_requests, 2);
assert_eq!(peer.client.unread_bytes, 0);
}
@@ -381,6 +439,7 @@ fn early_response_retires_sender_and_ignores_late_proof_cancel_and_receipt() {
.resource
.resource_hash;
peer.response(old_id, binary_list(&blobs(1)), false);
peer.accept_downloads();
let new_request = peer.client.request.as_ref().unwrap();
assert_ne!(old_id, new_request.id);
let generation = new_request.generation;
@@ -450,23 +509,23 @@ fn purge_errors_never_complete_or_advance_chunk() {
#[test]
fn capacity_failure_precedes_publication_purge_and_cursor_advance() {
let mut peer = Peer::new();
peer.client.unread_limit = 100;
peer.client.received_messages.push(vec![1; 20]);
peer.client.unread_bytes = 20;
peer.client.available_messages = ids(2);
peer.client.unread_limit = 80;
let retained = vec![fixture_download(&peer.client, vec![1; 20])];
let over_limit = vec![vec![2; 60], vec![3; 30]];
peer.client.available_messages = over_limit
.iter()
.map(|bytes| rns_crypto::sha::full_hash(bytes).to_vec())
.collect();
peer.client.send_get_request();
let (id, _, _) = peer.request(true);
peer.response(id, binary_list(&[vec![2; 60], vec![3; 30]]), false);
peer.response(id, binary_list(&over_limit), false);
assert_eq!(peer.client.state(), PropagationClientState::Failed);
assert_eq!(peer.client.pending_wants.len(), 2);
assert!(peer.client.received_ids.is_empty());
assert_eq!(peer.client.received_messages, vec![vec![1; 20]]);
assert_eq!(peer.client.unread_bytes, 20);
assert!(peer.client.received_messages.is_empty());
assert_eq!(peer.client.unread_bytes, 0);
assert_eq!(downloaded_bytes(&retained), vec![vec![1; 20]]);
assert!(peer.rx.try_recv().is_err(), "overflow must not queue purge");
assert!(!peer.client.start_download());
peer.client.cancel_download();
assert!(!peer.client.start_download());
assert_eq!(peer.client.take_received_messages(), vec![vec![1; 20]]);
}
#[test]
@@ -525,33 +584,37 @@ fn oversized_logical_sets_advance_after_empty_and_partial_chunks() {
peer.client.available_messages = selected.clone();
peer.client.available_messages.push(selected[0].clone());
peer.client.send_get_request();
let first = peer.client.request.as_ref().unwrap();
let RequestKind::Get(first_count) = first.kind else {
panic!()
};
assert!(first_count < 30_840);
assert!(
first
.outbound
.as_ref()
.unwrap()
.resource
.advertisement_data_size
<= MAX_EFFICIENT_SIZE
);
let id = first.id;
// Correlated early empty response skips the complete requested chunk.
peer.response(id, empty(), false);
let RequestKind::Get(tail_count) = peer.client.request.as_ref().unwrap().kind else {
panic!()
};
assert_eq!(first_count + tail_count, 30_840);
let tail = peer.client.request.as_ref().unwrap().id;
peer.response(tail, binary_list(&blobs(1)), false);
let mut consumed = 0;
loop {
let request = peer.client.request.as_ref().unwrap();
let RequestKind::Get(count) = request.kind else {
panic!("get chunk expected")
};
assert!(count <= crate::admission::MAX_DOWNLOAD_ITEMS);
assert!(count > 0);
if let Some(transfer) = &request.outbound {
assert!(transfer.resource.advertisement_data_size <= MAX_EFFICIENT_SIZE);
}
let id = request.id;
if consumed + count < 30_840 {
peer.response(id, empty(), false);
consumed += count;
continue;
}
assert_eq!(consumed + count, 30_840);
peer.response(id, binary_list(&[blob(consumed)]), false);
break;
}
assert!(peer.client.pending_wants.is_empty());
assert!(peer.client.received_ids.is_empty());
assert_eq!(
peer.client.state(),
PropagationClientState::AwaitingAdmission
);
peer.accept_downloads();
assert_eq!(peer.client.received_ids.len(), 1);
let purge = peer.client.request.as_ref().unwrap().id;
peer.response(purge, empty(), false);
let id = peer.client.request.as_ref().unwrap().id;
peer.response(id, empty(), false);
assert_eq!(peer.client.state(), PropagationClientState::Complete);
assert_eq!(peer.client.transfer_status().result, Some(1));
}
@@ -563,18 +626,20 @@ fn known_haves_chunks_complete_and_retain_policy_skips_only_known_haves() {
peer.client.available_messages = selected.clone();
peer.client.replace_local_message_ids(selected);
peer.client.send_get_request();
let RequestKind::Haves(first) = peer.client.request.as_ref().unwrap().kind else {
panic!()
};
assert!(first < 30_840);
let id = peer.client.request.as_ref().unwrap().id;
peer.response(id, empty(), false);
assert_eq!(peer.client.pending_haves.len(), 30_840 - first);
let id = peer.client.request.as_ref().unwrap().id;
peer.response(id, empty(), false);
assert!(peer.client.pending_haves.is_empty());
let mut chunks = 0;
while !peer.client.pending_haves.is_empty() {
let request = peer.client.request.as_ref().unwrap();
let RequestKind::Haves(count) = request.kind else {
panic!("haves chunk expected")
};
assert!(count > 0 && count <= crate::admission::MAX_DOWNLOAD_ITEMS);
let id = request.id;
peer.response(id, empty(), false);
chunks += 1;
assert!(chunks <= 8);
}
assert_eq!(chunks, 8);
assert_eq!(peer.client.state(), PropagationClientState::Complete);
let mut peer = Peer::new();
peer.client.available_messages = ids(2);
peer.client.replace_local_message_ids(ids(1));
@@ -583,7 +648,12 @@ fn known_haves_chunks_complete_and_retain_policy_skips_only_known_haves() {
let (id, data, _) = peer.request(true);
assert_eq!(data.as_array().unwrap()[0], binary_list(&ids(2)[1..]));
assert_eq!(data.as_array().unwrap()[1], empty());
peer.response(id, binary_list(&blobs(1)), false);
peer.response(id, binary_list(&[blob(1)]), false);
assert_eq!(
peer.client.state(),
PropagationClientState::AwaitingAdmission
);
peer.accept_downloads();
assert!(matches!(
peer.client.request.as_ref().unwrap().kind,
RequestKind::Purge(1)
@@ -604,15 +674,21 @@ fn hashmap_updates_and_split_responses_keep_exact_request_identity() {
assert_eq!(peer.client.state(), PropagationClientState::Complete);
let mut peer = Peer::new();
peer.client.available_messages = ids(1);
let blob = vec![0x5a; MAX_EFFICIENT_SIZE + 100];
peer.client.available_messages = vec![rns_crypto::sha::full_hash(&blob).to_vec()];
peer.client.set_delivery_limit(2000.0);
peer.client.send_get_request();
let (id, _, _) = peer.request(true);
let blob = vec![0x5a; MAX_EFFICIENT_SIZE + 100];
peer.response(id, binary_list(std::slice::from_ref(&blob)), true);
assert_eq!(peer.client.received_messages, vec![blob]);
assert_eq!(peer.client.state(), PropagationClientState::PurgeRequested);
assert_eq!(downloaded_bytes(&peer.client.received_messages), vec![blob]);
assert_eq!(
peer.client.state(),
PropagationClientState::AwaitingAdmission
);
assert!(peer.client.inbound_split_resources.is_empty());
peer.accept_downloads();
assert_eq!(peer.client.state(), PropagationClientState::PurgeRequested);
}
#[test]
@@ -777,10 +853,9 @@ fn advertisement_requires_matching_request_id_and_response_direction() {
}
#[test]
fn malformed_batch_is_atomic_and_preserves_prior_results() {
fn malformed_batch_is_atomic_and_preserves_external_payload_owners() {
let mut peer = Peer::new();
peer.client.received_messages.push(vec![0xab; 20]);
peer.client.unread_bytes = 20;
let retained = vec![fixture_download(&peer.client, vec![0xab; 20])];
peer.client.available_messages = ids(2);
peer.client.send_get_request();
let (id, _, _) = peer.request(true);
@@ -790,14 +865,15 @@ fn malformed_batch_is_atomic_and_preserves_prior_results() {
false,
);
assert_eq!(peer.client.state(), PropagationClientState::Failed);
assert_eq!(peer.client.received_messages, vec![vec![0xab; 20]]);
assert_eq!(peer.client.unread_bytes, 20);
assert_eq!(downloaded_bytes(&retained), vec![vec![0xab; 20]]);
assert!(peer.client.received_messages.is_empty());
assert_eq!(peer.client.unread_bytes, 0);
assert!(peer.client.received_ids.is_empty());
assert_eq!(peer.client.pending_wants.len(), 2);
}
#[test]
fn accepted_results_survive_purge_failure_cancel_and_disconnect_until_drained() {
fn durable_results_survive_purge_failure_and_external_owners_survive_cancellation() {
for failure in 0..3 {
let mut peer = Peer::new();
let messages = blobs(50);
@@ -806,31 +882,55 @@ fn accepted_results_survive_purge_failure_cancel_and_disconnect_until_drained()
let (id, _, _) = peer.request(true);
peer.response(id, binary_list(&messages), true);
assert_eq!(peer.client.received_count(), 50);
match failure {
0 => {
let (id, _, _) = peer.request(true);
peer.response(id, Value::from(0xf0), false);
peer.client.tick();
}
1 => peer.client.cancel_download(),
_ => {
assert_eq!(
peer.client.state(),
PropagationClientState::AwaitingAdmission
);
if failure == 0 {
peer.accept_downloads();
let (id, _, _) = peer.request(true);
peer.response(id, Value::from(0xf0), false);
peer.client.tick();
assert_eq!(peer.admitted, messages);
assert_eq!(peer.client.local_messages.len(), 50);
let store = crate::admission_store::FileAdmissionStore::open(
peer.admission_dir.path(),
&peer.admission_dir.path().join("messages"),
)
.unwrap();
assert_eq!(store.haves([0; 16], [0xe8; 16], 101).len(), 50);
} else {
let downloaded = peer.client.take_downloaded_messages();
if failure == 1 {
peer.client.cancel_download();
} else {
let teardown = peer.link.teardown(CloseReason::DestinationClosed).unwrap();
peer.inject(Context::LinkClose, &teardown);
}
assert!(peer.client.received_messages.is_empty());
assert_eq!(downloaded_bytes(&downloaded), messages);
assert!(
downloaded
.iter()
.all(|item| !item.scope().transient_id.iter().all(|b| *b == 0))
);
for item in downloaded {
let (_, token) = item.into_parts();
assert!(!token.is_current());
}
peer.client.poll_admissions();
assert!(peer.client.local_messages.is_empty());
assert!(peer.client.received_ids.is_empty());
assert!(peer.client.start_download());
assert!(peer.client.take_downloaded_messages().is_empty());
}
assert!(!peer.client.start_download());
assert_eq!(peer.client.take_received_messages(), messages);
assert_eq!(peer.client.unread_bytes, 0);
assert!(peer.client.start_download());
assert!(peer.client.take_received_messages().is_empty());
}
}
#[test]
fn transport_result_deadline_is_finite_and_retains_results() {
let mut peer = Peer::new();
peer.client.received_messages.push(vec![0x33; 10]);
peer.client.unread_bytes = 10;
let retained = vec![fixture_download(&peer.client, vec![0x33; 10])];
peer.client.received_ids = ids(50);
peer.client.send_purge_request();
let pending = peer.client.pending_endpoint_sends.last_mut().unwrap();
@@ -838,8 +938,11 @@ fn transport_result_deadline_is_finite_and_retains_results() {
peer.client.tick();
assert_eq!(peer.client.state(), PropagationClientState::Failed);
assert!(peer.client.request.is_none());
assert!(!peer.client.start_download());
assert_eq!(peer.client.take_received_messages(), vec![vec![0x33; 10]]);
assert_eq!(downloaded_bytes(&retained), vec![vec![0x33; 10]]);
for item in retained {
let (_, token) = item.into_parts();
assert!(!token.is_current());
}
}
#[test]
@@ -924,7 +1027,7 @@ fn slow_segment_gets_a_fresh_proof_admission_deadline() {
let (context, proof, _) = peer.packet();
assert_eq!(context, Context::ResourcePrf);
assert!(sender.handle_proof(&proof));
assert_eq!(peer.client.received_messages, messages);
assert_eq!(downloaded_bytes(&peer.client.received_messages), messages);
}
#[test]
@@ -934,6 +1037,7 @@ fn response_resource_before_request_proof_retires_only_its_sender() {
peer.client.send_get_request();
let (id, _, proof) = peer.request(false);
peer.response(id, binary_list(&blobs(50)), true);
peer.accept_downloads();
let successor = peer.client.request.as_ref().unwrap().id;
let generation = peer.client.request.as_ref().unwrap().generation;
peer.inject(Context::ResourcePrf, &proof.unwrap());
@@ -942,11 +1046,11 @@ fn response_resource_before_request_proof_retires_only_its_sender() {
let (id, _, _) = peer.request(true);
peer.response(id, empty(), false);
assert_eq!(peer.client.state(), PropagationClientState::Complete);
assert_eq!(peer.client.received_count(), 50);
assert_eq!(peer.admitted.len(), 50);
}
#[test]
fn full_then_closed_transport_fails_request_without_losing_accepted_results() {
fn full_then_closed_transport_fails_request_without_releasing_external_payload() {
let mut peer = Peer::new();
while peer
.client
@@ -954,8 +1058,7 @@ fn full_then_closed_transport_fails_request_without_losing_accepted_results() {
.try_send(TransportMessage::DeregisterDestination { hash: [0; 16] })
.is_ok()
{}
peer.client.received_messages.push(vec![1; 12]);
peer.client.unread_bytes = 12;
let retained = vec![fixture_download(&peer.client, vec![1; 12])];
peer.client.received_ids = ids(50);
peer.client.send_purge_request();
assert_eq!(peer.client.pending_transport.len(), 1);
@@ -964,5 +1067,207 @@ fn full_then_closed_transport_fails_request_without_losing_accepted_results() {
peer.client.tick();
assert_eq!(peer.client.state(), PropagationClientState::Failed);
assert!(peer.client.request.is_none());
assert_eq!(peer.client.take_received_messages(), vec![vec![1; 12]]);
assert_eq!(downloaded_bytes(&retained), vec![vec![1; 12]]);
}
#[test]
fn expired_durable_haves_are_downloaded_instead_of_purged() {
use crate::admission::DurableHave;
let mut peer = Peer::new();
let expired = [0x81; 32];
let visible = [0x82; 32];
peer.client.replace_durable_haves([
DurableHave {
transient_id: expired,
expires_at: Some(0),
},
DurableHave {
transient_id: visible,
expires_at: None,
},
]);
peer.client.available_messages = vec![expired.to_vec(), visible.to_vec()];
peer.client.send_get_request();
let (id, request, _) = peer.request(true);
assert_eq!(
request,
Value::Array(vec![Value::Nil, binary_list(&[visible.to_vec()])])
);
assert!(!peer.client.local_messages.contains(expired.as_slice()));
peer.response(id, empty(), false);
let (_, request, _) = peer.request(true);
assert_eq!(
request.as_array().unwrap()[0],
binary_list(&[expired.to_vec()])
);
}
#[test]
fn expiry_preserves_the_counted_request_and_prunes_the_next_purge() {
use crate::admission::DurableHave;
let mut peer = Peer::new();
let all = ids(MAX_DOWNLOAD_ITEMS + 1);
let expires_later: [u8; 32] = all.last().unwrap().as_slice().try_into().unwrap();
peer.client
.replace_durable_haves(all.iter().map(|id| DurableHave {
transient_id: id.as_slice().try_into().unwrap(),
expires_at: None,
}));
peer.client.available_messages = all.clone();
peer.client.send_get_request();
let (id, request, _) = peer.request(true);
assert_eq!(
request.as_array().unwrap()[1].as_array().unwrap().len(),
MAX_DOWNLOAD_ITEMS
);
assert!(matches!(
peer.client.request.as_ref().unwrap().kind,
RequestKind::Haves(MAX_DOWNLOAD_ITEMS)
));
peer.client
.local_message_expiry
.insert(expires_later.to_vec(), 1);
peer.client.prune_expired_haves(1);
// The in-flight response still accounts for exactly its original prefix.
assert_eq!(
peer.client
.pending_haves
.iter()
.cloned()
.collect::<Vec<_>>(),
all
);
assert!(
!peer
.client
.local_messages
.contains(expires_later.as_slice())
);
peer.response(id, empty(), false);
assert!(peer.client.pending_haves.is_empty());
assert_eq!(peer.client.state(), PropagationClientState::Complete);
assert!(
peer.rx.is_empty(),
"expired tail must not produce another purge"
);
// Fresh accepted receipts use the same last-moment check before purge.
peer.client.received_ids = vec![expires_later.to_vec()];
peer.client.send_next_chunk();
assert!(peer.client.received_ids.is_empty());
assert!(peer.rx.is_empty());
}
#[test]
fn discard_receipts_expire_after_ninety_days_and_visible_receipts_do_not() {
use crate::admission::{AdmissionRecord, AdmissionScope, DurableDisposition, DurableHave};
for disposition in [
DurableDisposition::Committed,
DurableDisposition::Duplicate,
DurableDisposition::PolicyDiscard,
DurableDisposition::UserDeleted,
] {
let record = AdmissionRecord {
scope: AdmissionScope {
identity: [1; 16],
node: [2; 16],
transient_id: [3; 32],
},
message_id: [4; 32],
received_wire_hash: [5; 32],
stored_message_wire_hash: None,
disposition,
committed_at: 100,
};
let have = DurableHave::from_record(&record);
if matches!(
disposition,
DurableDisposition::PolicyDiscard | DurableDisposition::UserDeleted
) {
assert_eq!(have.expires_at, Some(100 + 90 * 86400));
assert!(have.active(100 + 90 * 86400 - 1));
assert!(!have.active(100 + 90 * 86400));
} else {
assert_eq!(have.expires_at, None);
assert!(have.active(u64::MAX));
}
}
}
#[test]
fn stale_suppression_checkpoint_cannot_acknowledge_newer_pruning_or_epochs() {
use crate::admission::{AdmissionEpochs, AdmissionScope, SuppressionLedger, SuppressionReason};
for expired in [true, false] {
let mut peer = Peer::new();
let mut ledger = SuppressionLedger::default();
let epochs = AdmissionEpochs::default();
let at = if expired { 0 } else { crate::now_f64() as u64 };
ledger
.record_failure(
AdmissionScope {
identity: [1; 16],
node: [2; 16],
transient_id: [3; 32],
},
SuppressionReason::InvalidStamp,
epochs,
at,
)
.unwrap();
peer.client.set_suppression_ledger(ledger, epochs);
let checkpoint = peer.client.suppression_revision();
if expired {
peer.client.prune_suppression();
} else {
peer.client.update_admission_epochs(AdmissionEpochs {
policy: [1; 32],
..epochs
});
}
peer.client.suppression_persist_failed = true;
assert_eq!(peer.client.suppression_ledger().records().count(), 0);
assert_ne!(peer.client.suppression_revision(), checkpoint);
assert!(!peer.client.acknowledge_suppression_persistence(checkpoint));
assert!(peer.client.suppression_persistence_pending());
assert!(peer.client.suppression_persist_failed);
assert!(
peer.client
.acknowledge_suppression_persistence(peer.client.suppression_revision())
);
assert!(!peer.client.suppression_persistence_pending());
assert!(!peer.client.suppression_persist_failed);
assert_eq!(peer.client.suppression_ledger().records().count(), 0);
}
}
#[test]
fn rejected_and_retryable_download_counts_never_become_purge_authority() {
use crate::admission::{DownloadAdmissionOutcome, SuppressionReason};
let mut peer = Peer::new();
let messages = blobs(2);
peer.client.available_messages = ids(2);
peer.client.send_get_request();
let (id, _, _) = peer.request(true);
peer.response(id, binary_list(&messages), false);
for (item, reason) in peer.client.take_downloaded_messages().into_iter().zip([
SuppressionReason::InvalidSignature,
SuppressionReason::MissingKey,
]) {
let (_, token) = item.into_parts();
token
.resolve(DownloadAdmissionOutcome::Rejected(reason))
.unwrap();
}
peer.client.poll_admissions();
let counts = peer.client.transfer_status().admission;
assert_eq!(counts.downloaded, 2);
assert_eq!(counts.rejected, 2);
assert_eq!(counts.retryable, 1);
assert_eq!(
counts.committed + counts.duplicate + counts.policy_discarded + counts.user_deleted,
0
);
assert!(peer.client.local_messages.is_empty());
assert!(peer.client.received_ids.is_empty());
assert!(peer.rx.is_empty(), "no durable acceptance means no purge");
}
File diff suppressed because it is too large. Load diff
+292
View File
@@ -0,0 +1,292 @@
//! Shared propagation preparation for daemon and embedding applications.
use crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN;
use crate::message::{LxMessage, MessageError};
use bytes::Bytes;
use std::sync::atomic::AtomicBool;
pub const NODE_METADATA_MAX_AGE: f64 = 45.0 * 86400.0;
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub struct AdvertisedNodePolicy {
pub stamp_cost: u8,
pub transfer_limit_kb: f64,
pub recorded_at: f64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MissingPropagationInput {
NodeIdentity,
NodePath,
NodePolicy,
RecipientIdentity,
}
#[derive(Debug, Clone, Copy)]
pub struct PreparedNode {
pub node: [u8; 16],
pub policy: AdvertisedNodePolicy,
}
/// Identity and policy freshness are required; the recipient itself may be
/// offline. Only a missing recipient key warrants recipient path discovery.
pub fn propagation_readiness(
node: [u8; 16],
node_identity_known: bool,
node_path_known: bool,
policy: Option<AdvertisedNodePolicy>,
recipient_identity_known: bool,
now: f64,
) -> Result<PreparedNode, MissingPropagationInput> {
if !node_identity_known {
return Err(MissingPropagationInput::NodeIdentity);
}
if !node_path_known {
return Err(MissingPropagationInput::NodePath);
}
let policy = policy
.filter(|p| {
p.recorded_at.is_finite()
&& p.recorded_at <= now
&& now - p.recorded_at < NODE_METADATA_MAX_AGE
&& p.transfer_limit_kb.is_finite()
&& p.transfer_limit_kb >= 0.
})
.ok_or(MissingPropagationInput::NodePolicy)?;
if !recipient_identity_known {
return Err(MissingPropagationInput::RecipientIdentity);
}
Ok(PreparedNode { node, policy })
}
/// One send-owned encryption result. Retrying changes only the outer timestamp
/// and (when required cost rises) the PN stamp, never ciphertext or transient ID.
#[derive(Debug, Clone)]
pub struct PropagationEnvelope {
message: LxMessage,
ciphertext: Bytes,
transient_id: [u8; 32],
encryption_binding: [u8; 32],
stamp: [u8; 32],
stamp_value: u32,
required_cost: u8,
}
impl PropagationEnvelope {
pub fn new<F>(
message: LxMessage,
encryption_binding: [u8; 32],
required_cost: u8,
encrypt: F,
) -> Result<Self, MessageError>
where
F: FnOnce(&[u8]) -> Result<Vec<u8>, MessageError>,
{
Self::new_cancellable(
message,
encryption_binding,
required_cost,
encrypt,
&AtomicBool::new(false),
)
}
pub fn new_cancellable<F>(
message: LxMessage,
encryption_binding: [u8; 32],
required_cost: u8,
encrypt: F,
cancel: &AtomicBool,
) -> Result<Self, MessageError>
where
F: FnOnce(&[u8]) -> Result<Vec<u8>, MessageError>,
{
let encrypted = encrypt(&message.wire_bytes()[16..])?;
let mut ciphertext = Vec::with_capacity(16 + encrypted.len());
ciphertext.extend_from_slice(&message.destination_hash());
ciphertext.extend_from_slice(&encrypted);
let transient_id = rns_crypto::sha::full_hash(&ciphertext);
let (stamp, generated_value) = crate::stamper::generate_stamp_cancellable(
&transient_id,
required_cost,
STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
cancel,
)
.ok_or_else(|| MessageError::PackFailed("PN stamp generation failed".into()))?;
// The general stamper's cost-zero shortcut reports the required lower
// bound. Envelopes carry the measured value used by strict relay ingress.
let stamp_value = if required_cost == 0 {
crate::stamper::stamp_value(
&crate::stamper::stamp_workblock(&transient_id, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN),
&stamp,
)
} else {
generated_value
};
if cancel.load(std::sync::atomic::Ordering::Acquire) {
return Err(MessageError::PackFailed(
"PN stamp generation cancelled".into(),
));
}
Ok(Self {
message,
ciphertext: ciphertext.into(),
transient_id,
encryption_binding,
stamp,
stamp_value,
required_cost,
})
}
pub fn message(&self) -> &LxMessage {
&self.message
}
pub fn transient_id(&self) -> [u8; 32] {
self.transient_id
}
pub fn ciphertext(&self) -> &Bytes {
&self.ciphertext
}
pub fn stamp(&self) -> &[u8; 32] {
&self.stamp
}
pub fn stamp_value(&self) -> u32 {
self.stamp_value
}
pub fn matches(&self, message: &LxMessage, encryption_binding: &[u8; 32]) -> bool {
self.message.wire_bytes() == message.wire_bytes()
&& &self.encryption_binding == encryption_binding
}
/// Call immediately before dispatch with refreshed advertised policy.
pub fn pack_for(
&mut self,
node: PreparedNode,
timestamp: f64,
) -> Result<Vec<u8>, MessageError> {
self.pack_for_cancellable(node, timestamp, &AtomicBool::new(false))
}
pub fn pack_for_cancellable(
&mut self,
node: PreparedNode,
timestamp: f64,
cancel: &AtomicBool,
) -> Result<Vec<u8>, MessageError> {
if !timestamp.is_finite() {
return Err(MessageError::PackFailed(
"propagation timestamp must be finite".into(),
));
}
if self.stamp_value < u32::from(node.policy.stamp_cost) {
(self.stamp, self.stamp_value) = crate::stamper::generate_stamp_cancellable(
&self.transient_id,
node.policy.stamp_cost,
STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
cancel,
)
.ok_or_else(|| MessageError::PackFailed("PN stamp regeneration failed".into()))?;
}
self.required_cost = node.policy.stamp_cost;
let blob_len = self
.ciphertext
.len()
.checked_add(32)
.ok_or_else(|| MessageError::PackFailed("PN envelope size overflow".into()))?;
let bin_header = if blob_len < 256 {
2
} else if blob_len < 65536 {
3
} else {
5
};
let packed_len = blob_len
.checked_add(11 + bin_header)
.ok_or_else(|| MessageError::PackFailed("PN wrapper size overflow".into()))?;
let limit = (node.policy.transfer_limit_kb * 1000.).floor();
let resource_limit = rns_protocol::resource::MAX_EFFICIENT_SIZE
.checked_mul(rns_protocol::resource::MAX_SEGMENTS)
.unwrap_or(0);
if packed_len as f64 > limit || packed_len > resource_limit {
return Err(MessageError::TooLarge {
size: packed_len,
limit: (limit as usize).min(resource_limit),
});
}
let mut out = Vec::with_capacity(packed_len);
rmp::encode::write_array_len(&mut out, 2).expect("Vec writer");
rmp::encode::write_f64(&mut out, timestamp).expect("Vec writer");
rmp::encode::write_array_len(&mut out, 1).expect("Vec writer");
rmp::encode::write_bin_len(
&mut out,
u32::try_from(blob_len)
.map_err(|_| MessageError::PackFailed("PN blob too large".into()))?,
)
.expect("Vec writer");
out.extend_from_slice(&self.ciphertext);
out.extend_from_slice(&self.stamp);
debug_assert_eq!(out.len(), packed_len);
Ok(out)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::constants::DeliveryMethod;
use crate::message::LxMessageDraft;
#[test]
fn offline_recipient_key_is_sufficient_and_zero_cost_is_explicit() {
let policy = AdvertisedNodePolicy {
stamp_cost: 0,
transfer_limit_kb: 256.,
recorded_at: 100.,
};
assert!(propagation_readiness([1; 16], true, true, Some(policy), true, 101.).is_ok());
assert_eq!(
propagation_readiness([1; 16], true, true, None, true, 101.).unwrap_err(),
MissingPropagationInput::NodePolicy
);
assert_eq!(
propagation_readiness([1; 16], true, true, Some(policy), false, 101.).unwrap_err(),
MissingPropagationInput::RecipientIdentity
);
}
#[test]
fn retry_and_cost_increase_keep_ciphertext_and_transient_id() {
let key = rns_crypto::ed25519::Ed25519PrivateKey::from_bytes(&[3; 32]);
let msg = LxMessageDraft::new([1; 16], [2; 16], "", "test", DeliveryMethod::Propagated)
.unwrap()
.sign(&key)
.unwrap()
.finalize(None)
.unwrap();
let mut envelope = PropagationEnvelope::new(msg, [4; 32], 0, |p| Ok(p.to_vec())).unwrap();
let before = envelope.ciphertext.clone();
let tid = envelope.transient_id();
assert_eq!(
envelope.stamp_value(),
crate::stamper::stamp_value(
&crate::stamper::stamp_workblock(&tid, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN),
envelope.stamp(),
)
);
let mut prepared = PreparedNode {
node: [5; 16],
policy: AdvertisedNodePolicy {
stamp_cost: 0,
transfer_limit_kb: 256.,
recorded_at: 100.,
},
};
let first = envelope.pack_for(prepared, 101.).unwrap();
prepared.policy.stamp_cost = 4;
let next = envelope.pack_for(prepared, 102.).unwrap();
assert_eq!(envelope.ciphertext(), &before);
assert_eq!(envelope.transient_id(), tid);
assert!(envelope.stamp_value() >= 4);
assert_ne!(first, next);
assert!(
crate::stamper::stamp_value(
&crate::stamper::stamp_workblock(&tid, STAMP_WORKBLOCK_EXPAND_ROUNDS_PN),
envelope.stamp()
) >= 4
);
}
}
@@ -0,0 +1,456 @@
//! Provenance-gated relay storage and conservative offline migration.
//!
//! Private local manifests record accepted opaque ingress. They are not an
//! encryption oracle, and old files acquire no authority from their names or
//! apparent envelope shape. Callers exclude external writers from these paths.
#[cfg(target_os = "android")]
mod android_container;
mod migration;
#[cfg(any(target_os = "ios", target_os = "android", test))]
mod mobile;
#[cfg(target_os = "android")]
pub use mobile::begin_android_container_migration;
#[cfg(target_os = "ios")]
pub use mobile::begin_ios_container_migration;
mod offline;
mod recovery;
pub(crate) use migration::open_locked_store;
pub use migration::{
MigrationReport, QuarantineSummary, migrate_store_offline, open_store, quarantine_summary,
};
pub use offline::{OfflineMigrationGuard, begin_offline_migration};
pub use recovery::{
RecoveryEntry, RecoveryPolicy, RecoveryReport, TrustedRecoveryManifest,
import_trusted_recovery_manifest,
};
use rns_identity::persistence::{durable_reconcile, durable_remove, durable_write};
use serde::{Deserialize, Serialize};
use std::fs::{self, File};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
const TOMBSTONE: &[u8] =
b"LXMF relay store moved to v2; legacy hosting and sync must remain disabled.\n";
const FORMAT: &[u8] = b"LXMF opaque relay store v2; objects and per-entry provenance\n";
const MAX_MANIFEST_BYTES: usize = 4096;
static STORE_MUTATION_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[derive(Debug, thiserror::Error)]
#[error(
"MigrationRequired: stop all legacy relay writers and run explicit offline store migration"
)]
pub struct MigrationRequired;
pub fn is_migration_required(error: &io::Error) -> bool {
error
.get_ref()
.is_some_and(|inner| inner.is::<MigrationRequired>())
}
fn err(error: impl std::fmt::Display) -> io::Error {
io::Error::other(error.to_string())
}
fn invalid(message: &'static str) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, message)
}
fn sibling(path: &Path, suffix: &str) -> io::Result<PathBuf> {
let mut name = path
.file_name()
.ok_or_else(|| invalid("store path has no file name"))?
.to_os_string();
name.push(suffix);
Ok(path.with_file_name(name))
}
fn read_bounded(path: &Path, maximum: usize) -> io::Result<Vec<u8>> {
let metadata = fs::symlink_metadata(path)?;
if !metadata.is_file() || metadata.file_type().is_symlink() || metadata.len() > maximum as u64 {
return Err(invalid("store record is not a bounded regular file"));
}
let mut data = Vec::new();
File::open(path)?
.take(maximum as u64 + 1)
.read_to_end(&mut data)?;
if data.len() > maximum {
return Err(invalid("store record grew beyond its bound"));
}
Ok(data)
}
fn canonical_legacy(path: &Path) -> io::Result<PathBuf> {
let parent = path
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or(Path::new("."));
let parent = fs::canonicalize(parent)?;
let name = path
.file_name()
.ok_or_else(|| invalid("store path has no file name"))?;
if name == "." || name == ".." {
return Err(invalid("invalid store path"));
}
let path = parent.join(name);
if fs::symlink_metadata(&path).is_ok_and(|m| m.file_type().is_symlink()) {
return Err(invalid("store root cannot be a symbolic link"));
}
Ok(path)
}
pub(crate) fn manifest_path(path: &Path) -> PathBuf {
sibling(path, ".entry").expect("validated object path")
}
pub(crate) fn deletion_path(path: &Path) -> PathBuf {
sibling(path, ".delete").expect("validated object path")
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
pub enum OpaqueIngress {
ValidatedPropagation,
TrustedRecovery,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
enum AdmissionProtocol {
StampedPropagation,
ExplicitTrustedRecovery,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
enum PublicationState {
Committed,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct EntryManifest {
pub version: u8,
admission_id: [u8; 16],
pub transient_id: [u8; 32],
pub content_hash: [u8; 32],
pub destination: [u8; 16],
pub size: usize,
pub stamp_value: u8,
pub stored_at: f64,
pub stamped: bool,
pub origin: OpaqueIngress,
protocol: AdmissionProtocol,
publication: PublicationState,
}
impl EntryManifest {
pub(crate) fn from_entry(entry: &crate::propagation::PropagationEntry, bytes: &[u8]) -> Self {
Self {
version: 2,
admission_id: rand::random(),
transient_id: entry.transient_id,
content_hash: rns_crypto::sha::full_hash(bytes),
destination: entry.destination_hash,
size: bytes.len(),
stamp_value: entry.stamp_value,
stored_at: entry.stored_at,
stamped: entry.stamped,
origin: OpaqueIngress::ValidatedPropagation,
protocol: AdmissionProtocol::StampedPropagation,
publication: PublicationState::Committed,
}
}
pub(crate) fn validate(&self, data: &[u8]) -> bool {
let tail = if self.stamped { 32 } else { 0 };
self.version == 2
&& self.stored_at.is_finite()
&& self.stored_at >= 0.0
&& self.size <= rns_protocol::resource::MAX_RESOURCE_SIZE
&& data.len() == self.size
&& data.len() > 16 + tail
&& data[..16] == self.destination
&& rns_crypto::sha::full_hash(data) == self.content_hash
&& rns_crypto::sha::full_hash(&data[..data.len() - tail]) == self.transient_id
&& matches!(
(self.origin, self.protocol),
(
OpaqueIngress::ValidatedPropagation,
AdmissionProtocol::StampedPropagation
) | (
OpaqueIngress::TrustedRecovery,
AdmissionProtocol::ExplicitTrustedRecovery
)
)
&& (self.origin == OpaqueIngress::TrustedRecovery || self.stamped)
}
pub(crate) fn filename(&self) -> String {
format!(
"{}_{}",
self.entry().filename(),
hex::encode(self.admission_id)
)
}
pub(crate) fn entry(&self) -> crate::propagation::PropagationEntry {
let mut entry = crate::propagation::PropagationEntry::new(
self.transient_id,
self.transient_id,
self.destination,
self.size,
self.stamp_value,
);
entry.stored_at = self.stored_at;
entry.stamped = self.stamped;
entry
}
}
pub(crate) fn read_manifest(path: &Path) -> io::Result<(EntryManifest, Vec<u8>)> {
let encoded = read_bounded(&manifest_path(path), MAX_MANIFEST_BYTES)?;
let meta: EntryManifest = rmp_serde::from_slice(&encoded).map_err(err)?;
if meta.filename() != path.file_name().and_then(|s| s.to_str()).unwrap_or("") {
return Err(invalid(
"relay object filename does not match its provenance record",
));
}
Ok((meta, encoded))
}
#[derive(Debug, Serialize, Deserialize)]
struct ActiveIndex {
version: u8,
object: String,
manifest_hash: [u8; 32],
}
fn index_path(object: &Path, id: &[u8; 32]) -> io::Result<PathBuf> {
Ok(object
.parent()
.ok_or_else(|| invalid("object has no parent"))?
.join(format!("{}.active", hex::encode(id))))
}
fn check_index(object: &Path, meta: &EntryManifest, encoded: &[u8]) -> io::Result<()> {
let index: ActiveIndex = rmp_serde::from_slice(&read_bounded(
&index_path(object, &meta.transient_id)?,
MAX_MANIFEST_BYTES,
)?)
.map_err(err)?;
if index.version != 2
|| index.object != meta.filename()
|| index.manifest_hash != rns_crypto::sha::full_hash(encoded)
{
return Err(invalid(
"object is not the active committed relay admission",
));
}
Ok(())
}
pub(crate) fn indexed_object(index_path: &Path) -> io::Result<PathBuf> {
let index: ActiveIndex =
rmp_serde::from_slice(&read_bounded(index_path, MAX_MANIFEST_BYTES)?).map_err(err)?;
if index.version != 2
|| Path::new(&index.object).components().count() != 1
|| !matches!(
Path::new(&index.object).components().next(),
Some(std::path::Component::Normal(_))
)
{
return Err(invalid("invalid relay active index"));
}
let object = index_path
.parent()
.ok_or_else(|| invalid("active index has no parent"))?
.join(index.object);
let (meta, encoded) = read_manifest(&object)?;
if self::index_path(&object, &meta.transient_id)? != index_path {
return Err(invalid("relay index TID mismatch"));
}
check_index(&object, &meta, &encoded)?;
Ok(object)
}
/// Publish object, provenance, then its per-TID commit index. A cancelled
/// in-memory callback cannot cause retry to replace the first committed image.
pub(crate) fn publish_object(
object: &Path,
meta: &EntryManifest,
data: &[u8],
) -> io::Result<(EntryManifest, PathBuf)> {
let _guard = STORE_MUTATION_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let index = index_path(object, &meta.transient_id)?;
match fs::symlink_metadata(&index) {
Ok(_) => {
let existing = indexed_object(&index)?;
let (first, encoded) = read_manifest(&existing)?;
let retained = read_validated_file(&existing)?;
durable_reconcile(&existing, &retained).map_err(err)?;
durable_reconcile(&manifest_path(&existing), &encoded).map_err(err)?;
let index_bytes = read_bounded(&index, MAX_MANIFEST_BYTES)?;
durable_reconcile(&index, &index_bytes).map_err(err)?;
return Ok((first, existing));
}
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
Err(e) => return Err(e),
}
if !meta.validate(data)
|| object.file_name().and_then(|s| s.to_str()) != Some(meta.filename().as_str())
{
return Err(invalid("invalid relay publication"));
}
let encoded = rmp_serde::to_vec_named(meta).map_err(err)?;
durable_write(object, data).map_err(err)?;
durable_write(&manifest_path(object), &encoded).map_err(err)?;
let active = ActiveIndex {
version: 2,
object: meta.filename(),
manifest_hash: rns_crypto::sha::full_hash(&encoded),
};
durable_write(&index, &rmp_serde::to_vec_named(&active).map_err(err)?).map_err(err)?;
Ok((meta.clone(), object.to_owned()))
}
/// Verify the complete indexed admission and renew all three publication
/// barriers. Serialize against retirement so successful return has a concrete
/// committed point, even when a purge was prepared concurrently.
pub(crate) fn verify_committed_object(path: &Path) -> io::Result<()> {
let _guard = STORE_MUTATION_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let (meta, encoded) = read_manifest(path)?;
let data = read_validated_file(path)?;
durable_reconcile(path, &data).map_err(err)?;
durable_reconcile(&manifest_path(path), &encoded).map_err(err)?;
let index = index_path(path, &meta.transient_id)?;
let bytes = read_bounded(&index, MAX_MANIFEST_BYTES)?;
durable_reconcile(&index, &bytes).map_err(err)?;
check_index(path, &meta, &encoded)
}
/// Both the manifest and complete bytes are checked at the final read boundary.
/// An unresolved durable deletion always defeats a previously prepared read.
pub(crate) fn read_validated_file(path: &Path) -> io::Result<Vec<u8>> {
read_validated_file_bounded(path, rns_protocol::resource::MAX_RESOURCE_SIZE)
}
/// Refuse oversized metadata before allocating or opening the payload. The
/// caller can therefore reserve its complete GET response budget first.
pub(crate) fn read_validated_file_bounded(path: &Path, maximum: usize) -> io::Result<Vec<u8>> {
if fs::symlink_metadata(deletion_path(path)).is_ok() {
return Err(invalid("relay object has a pending durable deletion"));
}
let (meta, encoded) = read_manifest(path)?;
check_index(path, &meta, &encoded)?;
if meta.size > maximum.min(rns_protocol::resource::MAX_RESOURCE_SIZE) {
return Err(invalid("relay object exceeds Resource capacity"));
}
let data = read_bounded(path, meta.size)?;
if !meta.validate(&data) {
return Err(invalid("relay object changed after validated admission"));
}
if fs::symlink_metadata(deletion_path(path)).is_ok() {
return Err(invalid("relay object retired while being read"));
}
check_index(path, &meta, &encoded)?;
Ok(data)
}
#[derive(Debug, Serialize, Deserialize)]
struct DeletionRecord {
version: u8,
object: String,
content_hash: [u8; 32],
transient_id: [u8; 32],
}
/// The durable deletion intent is committed before either indexed file is
/// removed. Keep it across every uncertain cleanup; startup resumes cleanup
/// before loading any active objects.
pub(crate) fn retire_object(path: &Path) -> io::Result<()> {
retire_object_inner(path, false)
}
fn retire_object_inner(path: &Path, fail_after_intent: bool) -> io::Result<()> {
let _guard = STORE_MUTATION_LOCK
.lock()
.unwrap_or_else(|e| e.into_inner());
let marker = deletion_path(path);
let encoded = match read_bounded(&marker, MAX_MANIFEST_BYTES) {
Ok(encoded) => encoded,
Err(e) if e.kind() == io::ErrorKind::NotFound => {
let (meta, _) = read_manifest(path)?;
let record = DeletionRecord {
version: 2,
object: path
.file_name()
.and_then(|s| s.to_str())
.ok_or_else(|| invalid("invalid object name"))?
.to_string(),
content_hash: meta.content_hash,
transient_id: meta.transient_id,
};
rmp_serde::to_vec_named(&record).map_err(err)?
}
Err(e) => return Err(e),
};
let record: DeletionRecord = rmp_serde::from_slice(&encoded).map_err(err)?;
if record.version != 2
|| Path::new(&record.object).components().count() != 1
|| path.file_name().and_then(|s| s.to_str()) != Some(&record.object)
{
return Err(invalid("deletion record path mismatch"));
}
let witness = durable_write(&marker, &encoded).map_err(err)?;
if fail_after_intent {
return Err(io::Error::other(
"injected interruption after durable deletion intent",
));
}
let cleanup = (|| -> io::Result<()> {
let index = index_path(path, &record.transient_id)?;
if let Ok(active) = indexed_object(&index)
&& active == path
{
durable_remove(&index, &witness).map_err(err)?;
}
durable_remove(path, &witness).map_err(err)?;
durable_remove(&manifest_path(path), &witness).map_err(err)?;
// A separate, retained FORMAT witness may retire the journal only once both
// removals have acknowledged barriers. Failure leaves the journal reusable.
let root = path
.parent()
.and_then(Path::parent)
.ok_or_else(|| invalid("object outside v2 objects directory"))?;
let format = durable_reconcile(&root.join("FORMAT"), FORMAT).map_err(err)?;
durable_remove(&marker, &format).map_err(err)?;
Ok(())
})();
if let Err(error) = cleanup {
tracing::warn!(%error, "committed relay deletion retains pending cleanup evidence");
}
Ok(())
}
pub(crate) fn reconcile_deletions(root: &Path) -> io::Result<()> {
for entry in fs::read_dir(root.join("objects"))? {
let path = entry?.path();
if path.extension().and_then(|s| s.to_str()) != Some("delete") {
continue;
}
let object = path.with_extension("");
retire_object(&object)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn deletion_intent_survives_interruption_and_revokes_all_read_authority() {
let temp = tempfile::tempdir().unwrap();
let legacy = temp.path().join("store");
let root = open_store(&legacy).unwrap();
let mut data = [2; 16].to_vec();
data.extend_from_slice(
&rns_identity::identity::Identity::new()
.encrypt(b"private payload", None)
.unwrap(),
);
let tid = rns_crypto::sha::full_hash(&data);
data.extend_from_slice(&[0; 32]);
let mut entry = crate::propagation::PropagationEntry::new(tid, tid, [2; 16], data.len(), 0);
entry.stamped = true;
let meta = EntryManifest::from_entry(&entry, &data);
let object = root.join("objects").join(meta.filename());
publish_object(&object, &meta, &data).unwrap();
assert_eq!(read_validated_file(&object).unwrap(), data);
assert!(retire_object_inner(&object, true).is_err());
assert!(object.exists());
assert!(deletion_path(&object).exists());
assert!(read_validated_file(&object).is_err());
assert!(verify_committed_object(&object).is_err());
open_store(&legacy).unwrap();
assert!(!object.exists());
assert!(!index_path(&object, &tid).unwrap().exists());
assert!(!deletion_path(&object).exists());
}
}
@@ -0,0 +1,207 @@
//! Android framework metadata, rather than process-list visibility or guessed
//! /data prefixes, establishes a single-package private-container boundary.
use super::*;
use jni::{
JNIEnv,
objects::{JObject, JString, JValue},
};
use std::os::unix::fs::MetadataExt;
fn take_string(env: &JNIEnv<'_>, value: JObject<'_>) -> io::Result<String> {
if value.is_null() {
return Err(invalid("Android application metadata is missing"));
}
let result: String = env.get_string(JString::from(value)).map_err(err)?.into();
env.delete_local_ref(value).map_err(err)?;
Ok(result)
}
pub(super) fn private_root<'a>(env: &JNIEnv<'a>, context: JObject<'a>) -> io::Result<PathBuf> {
let result = private_root_inner(env, context);
// Return a Rust failure without leaving an unrelated pending Java exception
// on the embedding application's worker thread.
if result.is_err() && env.exception_check().unwrap_or(true) {
let _ = env.exception_clear();
}
result
}
fn private_root_inner<'a>(env: &JNIEnv<'a>, context: JObject<'a>) -> io::Result<PathBuf> {
if context.is_null()
|| !env
.is_instance_of(context, "android/content/Context")
.map_err(err)?
{
return Err(invalid(
"an initialized Android application context is required",
));
}
let uid = env
.call_static_method("android/os/Process", "myUid", "()I", &[])
.map_err(err)?
.i()
.map_err(err)?;
if uid < 0 || uid % 100_000 < 10_000 {
return Err(invalid(
"relay recovery requires a private Android application UID",
));
}
let manager = env
.call_method(
context,
"getPackageManager",
"()Landroid/content/pm/PackageManager;",
&[],
)
.map_err(err)?
.l()
.map_err(err)?;
let packages = env
.call_method(
manager,
"getPackagesForUid",
"(I)[Ljava/lang/String;",
&[JValue::Int(uid)],
)
.map_err(err)?
.l()
.map_err(err)?;
if packages.is_null() || env.get_array_length(packages.into_inner()).map_err(err)? != 1 {
return Err(invalid(
"shared or unknown Android UID cannot authorize relay migration",
));
}
let package = take_string(
env,
env.get_object_array_element(packages.into_inner(), 0)
.map_err(err)?,
)?;
let context_package = take_string(
env,
env.call_method(context, "getPackageName", "()Ljava/lang/String;", &[])
.map_err(err)?
.l()
.map_err(err)?,
)?;
if package != context_package {
return Err(invalid("Android context does not own this application UID"));
}
let mut cmdline = Vec::new();
File::open("/proc/self/cmdline")?
.take(4097)
.read_to_end(&mut cmdline)?;
if cmdline.len() > 4096 || cmdline.split(|b| *b == 0).next() != Some(package.as_bytes()) {
return Err(invalid(
"relay migration is restricted to the default Android app process",
));
}
let package_string = env.new_string(&package).map_err(err)?;
// Resolve all four component classes, including disabled declarations. A
// secondary process can own the same private UID even if it is not running.
const FLAGS: i32 = 1 | 2 | 4 | 8 | 512;
let info = env
.call_method(
manager,
"getPackageInfo",
"(Ljava/lang/String;I)Landroid/content/pm/PackageInfo;",
&[JValue::Object(package_string.into()), JValue::Int(FLAGS)],
)
.map_err(err)?
.l()
.map_err(err)?;
if !env
.get_field(info, "sharedUserId", "Ljava/lang/String;")
.map_err(err)?
.l()
.map_err(err)?
.is_null()
{
return Err(invalid(
"sharedUserId applications cannot authorize relay migration",
));
}
let application = env
.get_field(
info,
"applicationInfo",
"Landroid/content/pm/ApplicationInfo;",
)
.map_err(err)?
.l()
.map_err(err)?;
if env
.get_field(application, "uid", "I")
.map_err(err)?
.i()
.map_err(err)?
!= uid
{
return Err(invalid("Android application UID changed"));
}
let process = take_string(
env,
env.get_field(application, "processName", "Ljava/lang/String;")
.map_err(err)?
.l()
.map_err(err)?,
)?;
if process != package {
return Err(invalid(
"custom Android application process is not qualified",
));
}
for (field, signature) in [
("activities", "[Landroid/content/pm/ActivityInfo;"),
("receivers", "[Landroid/content/pm/ActivityInfo;"),
("services", "[Landroid/content/pm/ServiceInfo;"),
("providers", "[Landroid/content/pm/ProviderInfo;"),
] {
let components = env
.get_field(info, field, signature)
.map_err(err)?
.l()
.map_err(err)?;
if components.is_null() {
continue;
}
let count = env.get_array_length(components.into_inner()).map_err(err)?;
if !(0..=4096).contains(&count) {
return Err(invalid(
"Android component inventory exceeds migration bound",
));
}
for index in 0..count {
let component = env
.get_object_array_element(components.into_inner(), index)
.map_err(err)?;
let process = take_string(
env,
env.get_field(component, "processName", "Ljava/lang/String;")
.map_err(err)?
.l()
.map_err(err)?,
)?;
env.delete_local_ref(component).map_err(err)?;
if process != package {
return Err(invalid(
"multi-process Android apps cannot authorize relay migration",
));
}
}
env.delete_local_ref(components).map_err(err)?;
}
let root = fs::canonicalize(take_string(
env,
env.get_field(application, "dataDir", "Ljava/lang/String;")
.map_err(err)?
.l()
.map_err(err)?,
)?)?;
let metadata = fs::metadata(&root)?;
if !metadata.is_dir() || metadata.uid() != uid as u32 || metadata.mode() & 0o022 != 0 {
return Err(invalid(
"Android data directory lacks exclusive application ownership",
));
}
Ok(root)
}
@@ -0,0 +1,466 @@
use super::*;
use rns_identity::persistence::{
DurableFileReceipt, durable_create_dir_all, durable_reconcile_hash, durable_rename_directory,
};
use sha2::{Digest, Sha256};
use std::collections::BTreeSet;
const MAX_INVENTORY: usize = 65_536;
const MAX_JOURNAL: usize = 32 * 1024 * 1024;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub(super) struct InventoryEntry {
pub path: PathBuf,
pub bytes: u64,
pub hash: Option<[u8; 32]>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct MigrationJournal {
version: u8,
legacy: PathBuf,
archive: PathBuf,
v2: PathBuf,
inventory: Vec<InventoryEntry>,
had_legacy: bool,
phase: u8,
renewal: Option<PathBuf>,
renewal_sequence: u64,
}
#[derive(Debug, Clone)]
pub struct MigrationReport {
pub store: PathBuf,
pub quarantine: QuarantineSummary,
}
#[derive(Debug, Clone)]
pub struct QuarantineSummary {
pub files: usize,
pub bytes: u64,
pub reason: &'static str,
}
fn summary(j: &MigrationJournal) -> QuarantineSummary {
QuarantineSummary {
files: j.inventory.iter().filter(|e| e.hash.is_some()).count(),
bytes: j
.inventory
.iter()
.fold(0u64, |n, e| n.saturating_add(e.bytes)),
reason: "Preserved legacy files have no trusted per-entry opaque-ingress provenance",
}
}
fn encode(j: &MigrationJournal) -> io::Result<Vec<u8>> {
let encoded = rmp_serde::to_vec_named(j).map_err(err)?;
if encoded.len() > MAX_JOURNAL {
return Err(invalid("migration inventory exceeds journal bound"));
}
Ok(encoded)
}
fn paths(legacy: &Path) -> io::Result<(PathBuf, PathBuf, PathBuf)> {
Ok((
sibling(legacy, ".migration")?,
sibling(legacy, ".legacy-quarantine")?,
sibling(legacy, ".v2")?,
))
}
fn save(j: &MigrationJournal) -> io::Result<DurableFileReceipt> {
durable_write(&paths(&j.legacy)?.0, &encode(j)?).map_err(err)
}
fn read_journal(legacy: &Path) -> io::Result<MigrationJournal> {
let (path, archive, v2) = paths(legacy)?;
let j: MigrationJournal =
rmp_serde::from_slice(&read_bounded(&path, MAX_JOURNAL)?).map_err(err)?;
if j.version != 2
|| j.phase > 4
|| j.legacy != legacy
|| j.archive != archive
|| j.v2 != v2
|| j.inventory.len() > MAX_INVENTORY
{
return Err(invalid("migration journal path/version/phase mismatch"));
}
let mut unique = BTreeSet::new();
for entry in &j.inventory {
if !safe_relative(&entry.path) || !unique.insert(entry.path.clone()) {
return Err(invalid("invalid inventory path"));
}
}
if let Some(path) = &j.renewal
&& *path != sibling(&archive, &format!(".renewal-{}", j.renewal_sequence))?
{
return Err(invalid("directory renewal path mismatch"));
}
Ok(j)
}
pub fn quarantine_summary(legacy: &Path) -> io::Result<QuarantineSummary> {
Ok(summary(&read_journal(&canonical_legacy(legacy)?)?))
}
fn safe_relative(path: &Path) -> bool {
!path.as_os_str().is_empty()
&& path.as_os_str().len() <= 4096
&& path.components().count() <= 32
&& path
.components()
.all(|p| matches!(p, std::path::Component::Normal(_)))
}
fn hash_file(path: &Path) -> io::Result<(u64, [u8; 32])> {
let before = fs::symlink_metadata(path)?;
if !before.is_file() || before.file_type().is_symlink() {
return Err(invalid("legacy inventory contains a nonregular file"));
}
let mut file = File::open(path)?;
let mut hash = Sha256::new();
let mut count = 0u64;
let mut buffer = [0; 8192];
loop {
let n = file.read(&mut buffer)?;
if n == 0 {
break;
}
count = count
.checked_add(n as u64)
.ok_or_else(|| invalid("legacy size overflow"))?;
hash.update(&buffer[..n]);
}
let after = file.metadata()?;
if count != before.len() || after.len() != count || before.modified()? != after.modified()? {
return Err(invalid("legacy file changed during inventory"));
}
Ok((count, hash.finalize().into()))
}
fn inventory(root: &Path) -> io::Result<Vec<InventoryEntry>> {
let metadata = fs::symlink_metadata(root)?;
if !metadata.is_dir() || metadata.file_type().is_symlink() {
return Err(invalid("legacy root is not a real directory"));
}
let mut todo = vec![PathBuf::new()];
let mut result = Vec::new();
while let Some(relative) = todo.pop() {
for entry in fs::read_dir(root.join(&relative))? {
let entry = entry?;
let relative = relative.join(entry.file_name());
if !safe_relative(&relative) || result.len() >= MAX_INVENTORY {
return Err(invalid("legacy inventory exceeds safe path/count bound"));
}
let m = fs::symlink_metadata(entry.path())?;
if m.file_type().is_symlink() {
return Err(invalid(
"legacy symbolic links require explicit operator recovery",
));
}
if m.is_dir() {
result.push(InventoryEntry {
path: relative.clone(),
bytes: 0,
hash: None,
});
todo.push(relative);
} else if m.is_file() {
let (bytes, hash) = hash_file(&entry.path())?;
result.push(InventoryEntry {
path: relative,
bytes,
hash: Some(hash),
});
} else {
return Err(invalid(
"legacy special files require explicit operator recovery",
));
}
}
}
result.sort_by(|a, b| a.path.cmp(&b.path));
Ok(result)
}
fn verify_inventory(root: &Path, j: &MigrationJournal) -> io::Result<()> {
if inventory(root)? != j.inventory {
return Err(invalid(
"legacy inventory changed; preserve original and investigate before recovery",
));
}
Ok(())
}
/// Startup only initializes a truly absent store. An incomplete journal or
/// historical directory requires the explicit offline recovery path.
pub fn open_store(legacy: &Path) -> io::Result<PathBuf> {
Ok(open_locked_store(legacy)?.0)
}
pub(crate) fn open_locked_store(legacy: &Path) -> io::Result<(PathBuf, File)> {
let legacy = canonical_legacy(legacy)?;
let lock = offline::lock_store(&legacy)?;
let (journal, archive, v2) = paths(&legacy)?;
if journal.exists() {
let j = read_journal(&legacy)?;
if j.phase != 4 || j.renewal.is_some() {
return Err(io::Error::other(MigrationRequired));
}
verify_published(&j)?;
reconcile_deletions(&v2)?;
return Ok((v2, lock));
}
if fs::symlink_metadata(&legacy).is_ok()
|| fs::symlink_metadata(&archive).is_ok()
|| fs::symlink_metadata(&v2).is_ok()
{
return Err(io::Error::other(MigrationRequired));
}
let j = MigrationJournal {
version: 2,
legacy: legacy.clone(),
archive,
v2,
inventory: Vec::new(),
had_legacy: false,
phase: 0,
renewal: None,
renewal_sequence: 0,
};
save(&j)?;
let report = run(j, None)?;
Ok((report.store, lock))
}
fn verify_published(j: &MigrationJournal) -> io::Result<()> {
if read_bounded(&j.legacy, 256)? != TOMBSTONE
|| read_bounded(&j.v2.join("FORMAT"), 256)? != FORMAT
{
return Err(invalid("v2 format or old-path guard mismatch"));
}
let objects = fs::symlink_metadata(j.v2.join("objects"))?;
if !objects.is_dir() || objects.file_type().is_symlink() {
return Err(invalid("v2 objects directory invalid"));
}
durable_reconcile(&j.legacy, TOMBSTONE).map_err(err)?;
durable_reconcile(&j.v2.join("FORMAT"), FORMAT).map_err(err)?;
Ok(())
}
/// The guard binds both path and verified writer exclusion. Neither a retry nor
/// operator approval promotes any legacy object without independent provenance.
pub fn migrate_store_offline(guard: &OfflineMigrationGuard) -> io::Result<MigrationReport> {
migrate(&guard.legacy, None)
}
fn migrate(legacy: &Path, fault: Option<u8>) -> io::Result<MigrationReport> {
let canonical = canonical_legacy(legacy)?;
let legacy = canonical.as_path();
let (journal, archive, v2) = paths(legacy)?;
let j = if journal.exists() {
read_journal(legacy)?
} else {
if archive.exists() || v2.exists() {
return Err(invalid(
"unowned archive/v2 path already exists; refusing overwrite",
));
}
let had_legacy = fs::symlink_metadata(legacy).is_ok();
let inventory = if had_legacy {
inventory(legacy)?
} else {
Vec::new()
};
let j = MigrationJournal {
version: 2,
legacy: legacy.to_owned(),
archive,
v2,
inventory,
had_legacy,
phase: 0,
renewal: None,
renewal_sequence: 0,
};
save(&j)?;
fail(fault, 0)?;
j
};
run(j, fault)
}
fn fail(fault: Option<u8>, stage: u8) -> io::Result<()> {
if fault == Some(stage) {
Err(io::Error::other(format!(
"injected migration boundary {stage}"
)))
} else {
Ok(())
}
}
/// Re-publish a renamed archive through two fresh sibling transitions. This is
/// valid on Windows WRITE_THROUGH and avoids pretending existing directories
/// can be acknowledged by a generic file flush. Every recovery target is journaled.
fn renew_archive(j: &mut MigrationJournal, fault: Option<u8>) -> io::Result<()> {
if let Some(temporary) = j.renewal.clone() {
match (j.archive.exists(), temporary.exists()) {
(false, true) => {
verify_inventory(&temporary, j)?;
let witness = save(j)?;
durable_rename_directory(&temporary, &j.archive, &witness).map_err(err)?;
fail(fault, 6)?;
j.renewal = None;
save(j)?;
return Ok(());
}
(true, false) => {
j.renewal = None;
}
_ => {
return Err(invalid(
"ambiguous archive renewal state; originals preserved",
));
}
}
}
verify_inventory(&j.archive, j)?;
j.renewal_sequence = j
.renewal_sequence
.checked_add(1)
.ok_or_else(|| invalid("renewal generation exhausted"))?;
let temporary = sibling(&j.archive, &format!(".renewal-{}", j.renewal_sequence))?;
if fs::symlink_metadata(&temporary).is_ok() {
return Err(invalid("recovery target already exists"));
}
j.renewal = Some(temporary.clone());
let witness = save(j)?;
durable_rename_directory(&j.archive, &temporary, &witness).map_err(err)?;
fail(fault, 5)?;
// Rewrite the journal after the first acknowledged move; if this write is
// uncertain the existing intent still describes both permitted locations.
let witness = save(j)?;
durable_rename_directory(&temporary, &j.archive, &witness).map_err(err)?;
fail(fault, 6)?;
j.renewal = None;
save(j)?;
Ok(())
}
fn run(mut j: MigrationJournal, fault: Option<u8>) -> io::Result<MigrationReport> {
if j.had_legacy {
if j.legacy.is_dir() {
if j.phase != 0 || j.archive.exists() || j.renewal.is_some() {
return Err(invalid("ambiguous legacy archive state"));
}
verify_inventory(&j.legacy, &j)?;
// Renew barriers for every retained file before its directory move.
for entry in j.inventory.iter().filter(|e| e.hash.is_some()) {
let maximum = usize::try_from(entry.bytes).map_err(err)?;
durable_reconcile_hash(&j.legacy.join(&entry.path), entry.hash.unwrap(), maximum)
.map_err(err)?;
}
let witness = save(&j)?;
durable_rename_directory(&j.legacy, &j.archive, &witness).map_err(err)?;
fail(fault, 1)?;
} else {
renew_archive(&mut j, fault)?;
}
verify_inventory(&j.archive, &j)?;
} else if j.archive.exists() || j.renewal.is_some() {
return Err(invalid("unexpected archive for a fresh store"));
}
if j.phase < 1 {
j.phase = 1;
save(&j)?;
}
match fs::symlink_metadata(&j.legacy) {
Ok(_) if read_bounded(&j.legacy, 256)? != TOMBSTONE => {
return Err(invalid("unknown old-path guard"));
}
Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e),
_ => {}
}
durable_write(&j.legacy, TOMBSTONE).map_err(err)?;
fail(fault, 2)?;
if j.phase < 2 {
j.phase = 2;
save(&j)?;
}
let witness = save(&j)?;
durable_create_dir_all(&j.v2, &witness).map_err(err)?;
durable_create_dir_all(&j.v2.join("objects"), &witness).map_err(err)?;
durable_write(&j.v2.join("FORMAT"), FORMAT).map_err(err)?;
fail(fault, 3)?;
if j.phase < 3 {
j.phase = 3;
save(&j)?;
}
verify_published(&j)?;
j.phase = 4;
save(&j)?;
fail(fault, 4)?;
Ok(MigrationReport {
store: j.v2.clone(),
quarantine: summary(&j),
})
}
pub(super) fn verified_archive(
guard: &OfflineMigrationGuard,
) -> io::Result<(PathBuf, PathBuf, Vec<InventoryEntry>)> {
let j = read_journal(&guard.legacy)?;
if j.phase != 4 || j.renewal.is_some() {
return Err(io::Error::other(MigrationRequired));
}
verify_published(&j)?;
verify_inventory(&j.archive, &j)?;
Ok((j.archive, j.v2, j.inventory))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn migration_preserves_inventory_and_never_promotes_legacy_bytes() {
let temp = tempfile::tempdir().unwrap();
let legacy = temp.path().join("store");
fs::create_dir(&legacy).unwrap();
fs::write(legacy.join("opaque"), [3; 200]).unwrap();
fs::write(legacy.join("plaintext"), b"private message").unwrap();
assert!(is_migration_required(&open_store(&legacy).unwrap_err()));
let report = migrate(&legacy, None).unwrap();
assert_eq!(report.quarantine.files, 2);
assert_eq!(
fs::read(
sibling(&legacy, ".legacy-quarantine")
.unwrap()
.join("plaintext")
)
.unwrap(),
b"private message"
);
assert_eq!(
fs::read_dir(report.store.join("objects")).unwrap().count(),
0
);
assert!(open_store(&legacy).is_ok());
}
#[test]
fn every_migration_and_renewal_boundary_resumes_without_losing_originals() {
for stage in 0..=6 {
let temp = tempfile::tempdir().unwrap();
let legacy = temp.path().join("store");
fs::create_dir(&legacy).unwrap();
fs::write(legacy.join("message"), b"untouched").unwrap();
if stage >= 5 {
assert!(migrate(&legacy, Some(1)).is_err());
}
assert!(migrate(&legacy, Some(stage)).is_err());
let report = migrate(&legacy, None).unwrap();
assert_eq!(report.quarantine.files, 1);
assert_eq!(
fs::read(
sibling(&legacy, ".legacy-quarantine")
.unwrap()
.join("message")
)
.unwrap(),
b"untouched"
);
assert!(open_store(&legacy).is_ok());
}
}
#[test]
fn changed_inventory_and_unowned_targets_fail_without_overwrite() {
let temp = tempfile::tempdir().unwrap();
let legacy = temp.path().join("store");
fs::create_dir(&legacy).unwrap();
fs::write(legacy.join("message"), b"original").unwrap();
assert!(migrate(&legacy, Some(0)).is_err());
fs::write(legacy.join("message"), b"changed").unwrap();
assert!(migrate(&legacy, None).is_err());
assert!(legacy.is_dir());
let other = temp.path().join("other");
fs::create_dir(sibling(&other, ".v2").unwrap()).unwrap();
assert!(open_store(&other).is_err());
assert!(!other.exists());
}
}
@@ -0,0 +1,167 @@
//! Restricted app-container migration authority. This is not an arbitrary-path
//! alternative to the desktop process probe. All current host workers must be
//! joined by the application before acquisition; the same v2 OS lock additionally
//! rejects live current hosts. iOS's main-app/container lifecycle excludes an
//! older installed bundle from concurrently owning this private data container.
use super::*;
fn contained_store(legacy: &Path, root: &Path) -> io::Result<PathBuf> {
let root = fs::canonicalize(root)?;
let legacy = canonical_legacy(legacy)?;
let parent = legacy
.parent()
.ok_or_else(|| invalid("store has no parent"))?;
if parent == root || !parent.starts_with(&root) {
return Err(invalid(
"relay migration requires a nested private app-container path",
));
}
Ok(legacy)
}
/// Acquire migration authority only inside the current native iOS main app's
/// private data container. App groups, extensions, external directories, and
/// command-line processes are refused. No caller-supplied root or skip flag is
/// accepted. Hold the application's identity/session lifecycle guard, stop all
/// hosted and sync writers, and join their actual workers before calling this.
#[cfg(target_os = "ios")]
pub fn begin_ios_container_migration(legacy: &Path) -> io::Result<offline::OfflineMigrationGuard> {
let root = native_ios_container()?;
let legacy = contained_store(legacy, &root)?;
let lock = offline::lock_store(&legacy)?;
Ok(offline::OfflineMigrationGuard {
legacy,
_lock: lock,
})
}
/// Acquire migration authority for the platform Context's single-package,
/// single-process private Android data directory. Shared UIDs, declared remote
/// processes, mismatched contexts and external/group-writable roots are refused.
/// The caller must hold its lifecycle guard and join all hosted/sync writers;
/// the returned guard also retains the same OS lock used by current v2 hosts.
#[cfg(target_os = "android")]
pub fn begin_android_container_migration<'a>(
legacy: &Path,
env: &jni::JNIEnv<'a>,
context: jni::objects::JObject<'a>,
) -> io::Result<offline::OfflineMigrationGuard> {
let root = android_container::private_root(env, context)?;
let legacy = contained_store(legacy, &root)?;
let lock = offline::lock_store(&legacy)?;
Ok(offline::OfflineMigrationGuard {
legacy,
_lock: lock,
})
}
#[cfg(target_os = "ios")]
fn native_ios_container() -> io::Result<PathBuf> {
use objc2::{
msg_send,
rc::autoreleasepool,
runtime::{AnyClass, AnyObject},
};
use std::ffi::CStr;
#[link(name = "Foundation", kind = "framework")]
unsafe extern "C" {
fn NSHomeDirectory() -> *mut AnyObject;
}
// SAFETY: both values are Foundation NSStrings, alive for the surrounding
// autorelease pool; UTF8String is copied before leaving that pool.
unsafe fn string(value: *mut AnyObject) -> io::Result<String> {
if value.is_null() {
return Err(invalid("native app-container metadata unavailable"));
}
let bytes: *const std::ffi::c_char = unsafe { msg_send![value, UTF8String] };
if bytes.is_null() {
return Err(invalid("native app-container path unavailable"));
}
unsafe { CStr::from_ptr(bytes) }
.to_str()
.map(str::to_owned)
.map_err(err)
}
autoreleasepool(|_| {
let class = AnyClass::get(c"NSBundle").ok_or_else(|| invalid("NSBundle unavailable"))?;
// SAFETY: documented synchronous Foundation getters, no ownership transfer.
let bundle: *mut AnyObject = unsafe { msg_send![class, mainBundle] };
if bundle.is_null() {
return Err(invalid("native main app bundle unavailable"));
}
let path: *mut AnyObject = unsafe { msg_send![bundle, bundlePath] };
let identifier: *mut AnyObject = unsafe { msg_send![bundle, bundleIdentifier] };
let bundle_path = PathBuf::from(unsafe { string(path)? });
if bundle_path.extension().and_then(|s| s.to_str()) != Some("app")
|| unsafe { string(identifier)? }.is_empty()
{
return Err(invalid("relay migration requires an iOS main application"));
}
let root = fs::canonicalize(unsafe { string(NSHomeDirectory())? })?;
if !ios_data_container_path(&root) {
return Err(invalid(
"native home is not a private iOS app data container",
));
}
Ok(root)
})
}
// The native home API, not this shape alone, supplies authority. Reject future
// unknown layouts instead of silently certifying a shared or group container.
#[cfg(any(target_os = "ios", test))]
fn ios_data_container_path(root: &Path) -> bool {
let Some(id) = root.file_name().and_then(|s| s.to_str()) else {
return false;
};
let valid_id = id.len() == 36
&& id.bytes().enumerate().all(|(index, byte)| {
if [8, 13, 18, 23].contains(&index) {
byte == b'-'
} else {
byte.is_ascii_hexdigit()
}
});
valid_id
&& root
.parent()
.is_some_and(|p| p.ends_with("Containers/Data/Application"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn private_container_policy_rejects_groups_siblings_and_root_store() {
assert!(ios_data_container_path(Path::new(
"/private/var/mobile/Containers/Data/Application/01234567-89AB-CDEF-0123-456789abcdef"
)));
assert!(ios_data_container_path(Path::new(
"/sim/device/data/Containers/Data/Application/01234567-89AB-CDEF-0123-456789abcdef"
)));
assert!(!ios_data_container_path(Path::new(
"/private/var/mobile/Containers/Shared/AppGroup/01234567-89AB-CDEF-0123-456789abcdef"
)));
assert!(!ios_data_container_path(Path::new(
"/private/var/mobile/Containers/Bundle/Application/01234567-89AB-CDEF-0123-456789abcdef"
)));
let temp = tempfile::tempdir().unwrap();
let root = temp.path().join("private");
let nested = root.join("Library/state");
fs::create_dir_all(&nested).unwrap();
assert!(contained_store(&nested.join("relay"), &root).is_ok());
assert!(contained_store(&root.join("relay"), &root).is_err());
assert!(contained_store(&temp.path().join("relay"), &root).is_err());
}
#[cfg(unix)]
#[test]
fn private_container_policy_rejects_symlink_escape() {
let temp = tempfile::tempdir().unwrap();
let root = temp.path().join("private");
let outside = temp.path().join("external");
fs::create_dir_all(&root).unwrap();
fs::create_dir_all(&outside).unwrap();
std::os::unix::fs::symlink(&outside, root.join("escape")).unwrap();
assert!(contained_store(&root.join("escape/relay"), &root).is_err());
}
}
@@ -0,0 +1,165 @@
use super::*;
use std::process::{Command, Stdio};
/// Holds the same OS lock as every v2 host. Legacy binaries ignore this lock;
/// the mandatory supervisor assertion and known-process probe address that gap.
pub struct OfflineMigrationGuard {
pub(super) legacy: PathBuf,
pub(super) _lock: File,
}
pub(super) fn lock_store(legacy: &Path) -> io::Result<File> {
let mut options = fs::OpenOptions::new();
options.read(true).write(true).create(true).truncate(false);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let path = sibling(legacy, ".store-lock")?;
if fs::symlink_metadata(&path).is_ok_and(|m| !m.is_file() || m.file_type().is_symlink()) {
return Err(invalid("invalid relay store lock"));
}
let lock = options.open(path)?;
rns_identity::persistence::try_lock_exclusive(&lock)?;
Ok(lock)
}
/// The adapter must first stop its own hosting workers and service auto-restart.
/// This probes known app/daemon names and refuses if process enumeration fails.
/// Manually launching an old binary during migration remains unsupported.
pub fn begin_offline_migration(
legacy: &Path,
supervisor_writers_stopped: bool,
) -> io::Result<OfflineMigrationGuard> {
if !supervisor_writers_stopped {
return Err(invalid(
"stop relay writers and their service supervisors before migration",
));
}
let legacy = canonical_legacy(legacy)?;
let lock = lock_store(&legacy)?;
refuse_known_relay_processes()?;
Ok(OfflineMigrationGuard {
legacy,
_lock: lock,
})
}
fn known_name(value: &str) -> bool {
let value = value
.trim_matches('"')
.rsplit(['/', '\\'])
.next()
.unwrap_or(value)
.to_ascii_lowercase();
matches!(
value.as_str(),
"ratspeak" | "ratspeak.exe" | "lxmd" | "lxmd.py" | "lxmd-rs" | "lxmd-rs.exe"
)
}
fn refuse_known_relay_processes() -> io::Result<()> {
#[cfg(unix)]
let mut command = {
let mut c = Command::new("ps");
c.args(["-axo", "pid=,comm=,args="]);
c
};
#[cfg(windows)]
let mut command = {
let mut c = Command::new("tasklist");
c.args(["/FO", "CSV", "/NH"]);
c
};
#[cfg(not(any(unix, windows)))]
return Err(io::Error::new(
io::ErrorKind::Unsupported,
"process exclusion cannot be verified on this platform",
));
#[cfg(any(unix, windows))]
{
command.stdout(Stdio::piped()).stderr(Stdio::null());
let mut child = command.spawn()?;
let mut output = Vec::new();
let read = child
.stdout
.take()
.ok_or_else(|| invalid("process probe has no output"))?
.take(4 * 1024 * 1024 + 1)
.read_to_end(&mut output);
if read.is_err() || output.len() > 4 * 1024 * 1024 {
let _ = child.kill();
let _ = child.wait();
return Err(invalid("process inventory exceeds safe bound"));
}
if !child.wait()?.success() {
return Err(invalid(
"process enumeration unavailable; relay writer exclusion unverified",
));
}
let listing = std::str::from_utf8(&output).map_err(err)?;
check_listing(listing, std::process::id(), cfg!(windows))
}
}
fn check_listing(listing: &str, own_pid: u32, windows: bool) -> io::Result<()> {
for line in listing.lines().filter(|l| !l.trim().is_empty()) {
if windows {
let fields: Vec<_> = line.trim_matches('"').split("\",\"").collect();
if fields.len() < 2 {
return Err(invalid("unrecognized process inventory"));
}
let pid: u32 = fields[1].parse().map_err(err)?;
if pid != own_pid && known_name(fields[0]) {
return Err(invalid("a known relay app/daemon is still running"));
}
} else {
let mut fields = line.split_whitespace();
let pid: u32 = fields
.next()
.ok_or_else(|| invalid("missing process ID"))?
.parse()
.map_err(err)?;
let Some(comm) = fields.next() else {
return Err(invalid("missing process name"));
};
if pid == own_pid {
continue;
}
// For interpreted daemons, inspect only the executable/script prefix,
// not arbitrary argument text belonging to shells or other programs.
let python = comm
.rsplit('/')
.next()
.is_some_and(|c| c.starts_with("python"));
if known_name(comm) || (python && fields.take(3).any(known_name)) {
return Err(invalid("a known relay app/daemon is still running"));
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn known_process_probe_is_fail_closed_and_excludes_only_own_pid() {
assert!(
check_listing(
"7 /Applications/Ratspeak /Applications/Ratspeak\n",
8,
false
)
.is_err()
);
assert!(
check_listing(
"7 /Applications/Ratspeak /Applications/Ratspeak\n",
7,
false
)
.is_ok()
);
assert!(check_listing("9 python3 python3 /usr/bin/lxmd --service\n", 7, false).is_err());
assert!(check_listing("oops", 7, false).is_err());
assert!(check_listing("\"lxmd-rs.exe\",\"9\",\"Console\"", 7, true).is_err());
}
}
@@ -0,0 +1,330 @@
use super::*;
use std::collections::{HashMap, HashSet};
/// A local owner's independently verified ingress record. The approved manifest
/// digest is supplied separately by the recovery UI/CLI; a location or blanket
/// 'recover all' action is never an origin assertion.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrustedRecoveryManifest {
pub version: u8,
pub provenance: String,
pub entries: Vec<RecoveryEntry>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RecoveryEntry {
pub archive_relative_path: PathBuf,
pub content_hash: [u8; 32],
pub transient_id: [u8; 32],
pub stamped: bool,
pub stored_at: f64,
}
#[derive(Debug, Clone, Copy)]
pub struct RecoveryPolicy {
pub maximum_store_bytes: usize,
pub maximum_message_bytes: usize,
pub minimum_stamp_cost: u8,
}
#[derive(Debug, Clone, Copy)]
pub struct RecoveryReport {
pub imported: usize,
pub already_present: usize,
}
fn validate(
record: &RecoveryEntry,
bytes: &[u8],
minimum_stamp_cost: u8,
) -> io::Result<EntryManifest> {
let tail = if record.stamped { 32 } else { 0 };
if bytes.len() < 112 + tail
|| !record.stored_at.is_finite()
|| record.stored_at < 0.0
|| rns_crypto::sha::full_hash(bytes) != record.content_hash
{
return Err(invalid("recovery content hash/length/time mismatch"));
}
let opaque = &bytes[..bytes.len() - tail];
if !(opaque.len() - 16 - 32 - rns_crypto::TOKEN_OVERHEAD).is_multiple_of(16)
|| rns_crypto::sha::full_hash(opaque) != record.transient_id
{
return Err(invalid("recovery envelope/TID mismatch"));
}
if crate::message::LxMessage::unpack(opaque).is_ok()
|| crate::message::LxMessage::unpack(bytes).is_ok()
{
return Err(invalid(
"raw plaintext LXMF is never eligible for relay recovery",
));
}
let stamp_value = if record.stamped {
let stamp: &[u8; 32] = bytes[bytes.len() - 32..].try_into().map_err(err)?;
let workblock = crate::stamper::stamp_workblock(
&record.transient_id,
crate::constants::STAMP_WORKBLOCK_EXPAND_ROUNDS_PN,
);
let value = crate::stamper::stamp_value(&workblock, stamp).min(255) as u8;
if value < minimum_stamp_cost {
return Err(invalid("recovered stamp does not meet node policy"));
}
value
} else {
if minimum_stamp_cost > 0 {
return Err(invalid("unstamped recovery does not meet node policy"));
}
0
};
let mut destination = [0; 16];
destination.copy_from_slice(&bytes[..16]);
let mut entry = crate::propagation::PropagationEntry::new(
record.transient_id,
record.transient_id,
destination,
bytes.len(),
stamp_value,
);
entry.stored_at = record.stored_at;
entry.stamped = record.stamped;
let mut manifest = EntryManifest::from_entry(&entry, bytes);
manifest.origin = OpaqueIngress::TrustedRecovery;
manifest.protocol = AdmissionProtocol::ExplicitTrustedRecovery;
Ok(manifest)
}
/// Import exact positively attested archive entries under the same offline
/// guard. Every entry is checked before the first write, then rechecked at its
/// publication boundary. Partial IO completion is restart-safe and idempotent.
pub fn import_trusted_recovery_manifest(
guard: &OfflineMigrationGuard,
path: &Path,
approved_manifest_sha256: [u8; 32],
policy: RecoveryPolicy,
) -> io::Result<RecoveryReport> {
let encoded = read_bounded(path, 32 * 1024 * 1024)?;
if rns_crypto::sha::full_hash(&encoded) != approved_manifest_sha256 {
return Err(invalid("recovery manifest changed after approval"));
}
let recovery: TrustedRecoveryManifest = rmp_serde::from_slice(&encoded).map_err(err)?;
if recovery.version != 2
|| recovery.provenance.trim().is_empty()
|| recovery.provenance.len() > 4096
|| recovery.entries.len() > 65_536
{
return Err(invalid("invalid trusted recovery manifest"));
}
let (archive, root, inventory) = migration::verified_archive(guard)?;
let known: HashMap<_, _> = inventory
.into_iter()
.filter_map(|e| e.hash.map(|h| (e.path, (e.bytes, h))))
.collect();
let mut existing = HashMap::new();
let mut total = 0usize;
reconcile_deletions(&root)?;
for file in fs::read_dir(root.join("objects"))? {
let path = file?.path();
if path.extension().and_then(|s| s.to_str()) != Some("active") {
continue;
}
let object = indexed_object(&path)?;
let (meta, _) = read_manifest(&object)?;
let bytes = read_validated_file(&object)?;
total = total
.checked_add(bytes.len())
.ok_or_else(|| invalid("relay size overflow"))?;
if existing
.insert(meta.transient_id, meta.content_hash)
.is_some()
{
return Err(invalid("duplicate active relay TID"));
}
}
let maximum = policy
.maximum_message_bytes
.min(rns_protocol::resource::MAX_RESOURCE_SIZE);
let mut selected = HashSet::new();
let mut plans = Vec::new();
let mut already_present = 0;
for record in &recovery.entries {
if !selected.insert(record.transient_id) {
return Err(invalid("duplicate recovery TID"));
}
let Some((length, hash)) = known.get(&record.archive_relative_path) else {
return Err(invalid(
"recovery entry is outside the committed legacy inventory",
));
};
if *hash != record.content_hash || *length > maximum as u64 {
return Err(invalid("recovery inventory hash/size mismatch"));
}
let bytes = read_bounded(&archive.join(&record.archive_relative_path), maximum)?;
let meta = validate(record, &bytes, policy.minimum_stamp_cost)?;
if let Some(hash) = existing.get(&record.transient_id) {
if *hash != record.content_hash {
return Err(invalid(
"recovery would replace the first accepted relay image",
));
}
already_present += 1;
continue;
}
total = total
.checked_add(bytes.len())
.ok_or_else(|| invalid("relay size overflow"))?;
if total > policy.maximum_store_bytes {
return Err(invalid(
"trusted recovery exceeds active relay storage quota",
));
}
plans.push((record, meta));
}
let mut imported = 0;
for (record, meta) in plans {
let bytes = read_bounded(&archive.join(&record.archive_relative_path), maximum)?;
validate(record, &bytes, policy.minimum_stamp_cost)?;
let object = root.join("objects").join(meta.filename());
if object.exists() && read_bounded(&object, maximum)? != bytes {
return Err(invalid("recovery object target contains different bytes"));
}
publish_object(&object, &meta, &bytes)?;
imported += 1;
}
Ok(RecoveryReport {
imported,
already_present,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn guard(legacy: &Path) -> OfflineMigrationGuard {
let legacy = canonical_legacy(legacy).unwrap();
let lock = offline::lock_store(&legacy).unwrap();
OfflineMigrationGuard {
legacy,
_lock: lock,
}
}
fn write_manifest(path: &Path, manifest: &TrustedRecoveryManifest) -> [u8; 32] {
let bytes = rmp_serde::to_vec_named(manifest).unwrap();
fs::write(path, &bytes).unwrap();
rns_crypto::sha::full_hash(&bytes)
}
fn policy() -> RecoveryPolicy {
RecoveryPolicy {
maximum_store_bytes: 8192,
maximum_message_bytes: 4096,
minimum_stamp_cost: 0,
}
}
fn record(bytes: &[u8], name: &str) -> RecoveryEntry {
RecoveryEntry {
archive_relative_path: name.into(),
content_hash: rns_crypto::sha::full_hash(bytes),
transient_id: rns_crypto::sha::full_hash(bytes),
stamped: false,
stored_at: 1.0,
}
}
#[test]
fn only_exact_approved_inventory_entries_are_imported_and_retry_is_idempotent() {
let temp = tempfile::tempdir().unwrap();
let legacy = temp.path().join("store");
fs::create_dir(&legacy).unwrap();
let recipient = rns_identity::identity::Identity::new();
let mut bytes = [2; 16].to_vec();
bytes.extend_from_slice(
&recipient
.encrypt(b"private recovery payload", None)
.unwrap(),
);
fs::write(legacy.join("opaque"), &bytes).unwrap();
fs::write(legacy.join("unknown"), b"never infer eligibility").unwrap();
let offline = guard(&legacy);
let report = migrate_store_offline(&offline).unwrap();
assert_eq!(report.quarantine.files, 2);
assert_eq!(
fs::read_dir(report.store.join("objects")).unwrap().count(),
0
);
let manifest = TrustedRecoveryManifest {
version: 2,
provenance: "operator verified original opaque ingress record #42".into(),
entries: vec![record(&bytes, "opaque")],
};
let path = temp.path().join("recovery.msgpack");
let hash = write_manifest(&path, &manifest);
assert!(import_trusted_recovery_manifest(&offline, &path, [0; 32], policy()).is_err());
let first = import_trusted_recovery_manifest(&offline, &path, hash, policy()).unwrap();
assert_eq!((first.imported, first.already_present), (1, 0));
let retry = import_trusted_recovery_manifest(&offline, &path, hash, policy()).unwrap();
assert_eq!((retry.imported, retry.already_present), (0, 1));
assert_eq!(
fs::read_dir(report.store.join("objects")).unwrap().count(),
3
);
assert_eq!(
fs::read(
sibling(&legacy, ".legacy-quarantine")
.unwrap()
.join("unknown")
)
.unwrap(),
b"never infer eligibility"
);
drop(offline);
let reopened = crate::propagation_node::PropagationNode::with_storage(
crate::propagation_node::PropagationNodeConfig::default(),
[1; 16],
legacy,
)
.unwrap();
assert_eq!(reopened.message_count(), 1);
assert_eq!(
fs::read(&reopened.plan_message_reads(&[rns_crypto::sha::full_hash(&bytes)])[0].path)
.unwrap(),
bytes
);
}
#[test]
fn plaintext_or_outside_inventory_recovery_cannot_publish_any_entry() {
let temp = tempfile::tempdir().unwrap();
let legacy = temp.path().join("store");
fs::create_dir(&legacy).unwrap();
let message = crate::message::test_message(
[2; 16],
[3; 16],
"Private",
"Do not relay cleartext",
crate::constants::DeliveryMethod::Direct,
);
let bytes = message.wire_bytes();
fs::write(legacy.join("plaintext"), bytes).unwrap();
let offline = guard(&legacy);
let report = migrate_store_offline(&offline).unwrap();
let path = temp.path().join("recovery.msgpack");
let mut manifest = TrustedRecoveryManifest {
version: 2,
provenance: "inaccurate assertion does not override positive plaintext decode".into(),
entries: vec![record(bytes, "plaintext")],
};
let hash = write_manifest(&path, &manifest);
assert!(import_trusted_recovery_manifest(&offline, &path, hash, policy()).is_err());
manifest.entries[0].archive_relative_path = "../plaintext".into();
let hash = write_manifest(&path, &manifest);
assert!(import_trusted_recovery_manifest(&offline, &path, hash, policy()).is_err());
assert_eq!(
fs::read_dir(report.store.join("objects")).unwrap().count(),
0
);
assert_eq!(
fs::read(
sibling(&legacy, ".legacy-quarantine")
.unwrap()
.join("plaintext")
)
.unwrap(),
bytes
);
}
}
+232 -139
View File
@@ -136,6 +136,9 @@ pub struct PropagationSyncTask {
pub propagation_node: Arc<Mutex<PropagationNode>>,
link: Option<Link>,
link_id: Option<[u8; 16]>,
link_request_result: Option<
oneshot::Receiver<Result<(), rns_transport::link_messages::LinkRequestDispatchError>>,
>,
attached_interface: Option<InterfaceId>,
pending_endpoint_bind: Option<PendingEndpointBind>,
pending_endpoint_sends: Vec<PendingEndpointSend>,
@@ -189,6 +192,7 @@ impl PropagationSyncTask {
))),
link: None,
link_id: None,
link_request_result: None,
attached_interface: None,
pending_endpoint_bind: None,
pending_endpoint_sends: Vec::new(),
@@ -248,6 +252,7 @@ impl PropagationSyncTask {
)?)),
link: None,
link_id: None,
link_request_result: None,
attached_interface: None,
pending_endpoint_bind: None,
pending_endpoint_sends: Vec::new(),
@@ -303,6 +308,7 @@ impl PropagationSyncTask {
propagation_node,
link: None,
link_id: None,
link_request_result: None,
attached_interface: None,
pending_endpoint_bind: None,
pending_endpoint_sends: Vec::new(),
@@ -648,17 +654,28 @@ impl PropagationSyncTask {
self.link_establishment_rate = None;
}
pub fn accept_message(&mut self, msg: &crate::message::LxMessage) -> bool {
self.propagation_node
.lock()
.map(|mut node| node.accept_message(msg))
.unwrap_or(false)
}
/// Drain inbound events from transport.
///
/// `known_identities` maps dest_hash_hex -> 64-byte public key, used for link proof validation.
fn poll_link_request(&mut self) {
let Some(mut receiver) = self.link_request_result.take() else {
return;
};
match receiver.try_recv() {
Ok(Ok(())) => {}
Ok(Err(error)) => {
tracing::warn!(%error,"Link request rejected by transport");
self.state = SyncTaskState::Failed;
}
Err(oneshot::error::TryRecvError::Closed) => {
self.state = SyncTaskState::Failed;
}
Err(oneshot::error::TryRecvError::Empty) => self.link_request_result = Some(receiver),
}
}
pub fn drain_events(&mut self, known_identities: &HashMap<String, [u8; 64]>) {
self.poll_link_request();
self.poll_endpoint_control();
let mut events = Vec::new();
while let Ok(event) = self.event_rx.try_recv() {
@@ -671,7 +688,10 @@ impl PropagationSyncTask {
self.handle_link_closed(link_id, None);
}
DestinationEvent::InboundPacket {
raw, interface_id, ..
raw,
interface_id,
interface_owner,
..
} => {
let (header, data_offset) = match rns_wire::header::PacketHeader::unpack(&raw) {
Ok(h) => h,
@@ -724,11 +744,12 @@ impl PropagationSyncTask {
let ed25519_bytes: [u8; 32] = pub_key[32..64].try_into().unwrap();
if let Ok(verify_key) = Ed25519PublicKey::from_bytes(&ed25519_bytes)
{
self.handle_link_proof(
self.handle_link_proof_with_owner(
data,
&verify_key,
&ed25519_bytes,
interface_id,
interface_owner,
);
}
}
@@ -918,12 +939,23 @@ impl PropagationSyncTask {
verified
}
#[cfg(test)]
fn handle_link_proof(
&mut self,
proof_data: &[u8],
verify_key: &Ed25519PublicKey,
ed25519_pub: &[u8; 32],
interface_id: InterfaceId,
) {
self.handle_link_proof_with_owner(proof_data, verify_key, ed25519_pub, interface_id, None)
}
fn handle_link_proof_with_owner(
&mut self,
proof_data: &[u8],
verify_key: &Ed25519PublicKey,
ed25519_pub: &[u8; 32],
interface_id: InterfaceId,
interface_owner: Option<rns_transport::InterfaceOwnerId>,
) {
let proof_result = match self.link.as_mut() {
Some(link) => link.validate_proof(proof_data, verify_key, ed25519_pub),
@@ -956,6 +988,7 @@ impl PropagationSyncTask {
let (result_tx, result_rx) = oneshot::channel();
if !self.queue_transport(TransportMessage::BindLinkEndpoint {
binding: LinkEndpointBinding {
interface_owner,
link_id,
interface_id,
role: LinkEndpointRole::Initiator,
@@ -1084,6 +1117,7 @@ impl PropagationSyncTask {
}
pub fn tick(&mut self) {
self.poll_link_request();
if !self.flush_pending_transport() && self.state != SyncTaskState::Idle {
self.state = SyncTaskState::Failed;
}
@@ -1428,15 +1462,21 @@ impl PropagationSyncTask {
let mut raw = header.pack();
raw.extend_from_slice(&request_data);
if !self.queue_transport(TransportMessage::Outbound(OutboundRequest {
raw: Bytes::from(raw),
destination_hash: node_hash,
})) {
let (request_tx, request_rx) = oneshot::channel();
if !self.queue_transport(TransportMessage::SendLinkRequest {
request: OutboundRequest {
raw: Bytes::from(raw),
destination_hash: node_hash,
},
result_tx: request_tx,
}) {
tracing::warn!("propagation sync transport closed before Link request");
self.state = SyncTaskState::Failed;
return false;
}
self.link_request_result = Some(request_rx);
let mut peer = LxmPeer::new(node_hash);
peer.begin_sync();
@@ -1720,6 +1760,9 @@ impl PropagationSyncTask {
/// Python LXMPeer.py:540-542.
fn cleanup_sync(&mut self) {
self.link_request_result = None;
self.pending_transport
.retain(|message| !matches!(message, TransportMessage::SendLinkRequest { .. }));
// No transfer packet should survive the attempt it belongs to. The
// teardown and deregistration below form a new ordered tail. Preserve
// a teardown already emitted by Link::tick() when it closed the link.
@@ -1801,11 +1844,38 @@ impl PropagationSyncTask {
#[cfg(test)]
mod tests {
use super::*;
fn test_task(tx: mpsc::Sender<TransportMessage>, dest: [u8; 16]) -> PropagationSyncTask {
PropagationSyncTask::with_shared_node(
tx,
Arc::new(Mutex::new(
crate::propagation_node::tests::durable_test_node(
PropagationNodeConfig::default(),
dest,
),
)),
)
}
impl PropagationSyncTask {
fn accept_fixture(
&mut self,
message: &crate::propagation_node::tests::OpaqueFixture,
) -> bool {
self.propagation_node
.lock()
.unwrap()
.accept_fixture(message)
}
}
fn next_link_request(rx: &mut mpsc::Receiver<TransportMessage>) -> OutboundRequest {
while let Ok(message) = rx.try_recv() {
match message {
TransportMessage::Outbound(request) => return request,
TransportMessage::SendLinkRequest { request, result_tx } => {
let _ = result_tx.send(Ok(()));
return request;
}
TransportMessage::SendLinkEndpoint {
request, result_tx, ..
} => {
@@ -1918,7 +1988,7 @@ mod tests {
let (tx, mut rx) = mpsc::channel(4);
let (initiator, responder) = active_link_pair([0x42; 16]);
let link_id = initiator.link_id;
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.link_id = Some(link_id);
task.link = Some(initiator);
task.attached_interface = Some(0);
@@ -1960,6 +2030,7 @@ mod tests {
let encrypted = responder.encrypt(plaintext).unwrap();
task.event_tx
.try_send(DestinationEvent::InboundPacket {
interface_owner: None,
raw: link_data_packet(link_id, context, &encrypted),
interface_id: 0,
metrics: Default::default(),
@@ -1990,7 +2061,7 @@ mod tests {
request.extend_from_slice(&resource_hash);
request.extend_from_slice(&requested_hash);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.link_id = Some(link_id);
task.link = Some(initiator);
task.attached_interface = Some(0);
@@ -2051,7 +2122,7 @@ mod tests {
request.extend_from_slice(&transfer.resource.map_hashes[hashmap_len - 1]);
request.extend_from_slice(&resource_hash);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.link_id = Some(link_id);
task.link = Some(initiator);
task.attached_interface = Some(0);
@@ -2097,7 +2168,7 @@ mod tests {
request.extend_from_slice(&transfer.resource.map_hashes[0]);
request.extend_from_slice(&resource_hash);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.link_id = Some(link_id);
task.link = Some(initiator);
task.attached_interface = Some(0);
@@ -2146,7 +2217,7 @@ mod tests {
.unwrap();
let transfer = transfers.pop_front().unwrap();
let resource_hash = transfer.resource.resource_hash;
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.link_id = Some(link_id);
task.link = Some(initiator);
task.attached_interface = Some(0);
@@ -2213,7 +2284,7 @@ mod tests {
assert_eq!(reassembled, payload);
let (tx, _rx) = mpsc::channel(4);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.state = SyncTaskState::Transferring;
task.node_dest_hash = Some([0x43; 16]);
task.active_transfer = transfers.pop_front();
@@ -2263,7 +2334,7 @@ mod tests {
#[test]
fn test_sync_task_creation() {
let (tx, _rx) = mpsc::channel(16);
let task = PropagationSyncTask::new(tx, [0xAA; 16]);
let task = test_task(tx, [0xAA; 16]);
assert_eq!(task.state, SyncTaskState::Idle);
assert_eq!(task.message_count(), 0);
}
@@ -2271,7 +2342,7 @@ mod tests {
#[test]
fn test_set_node() {
let (tx, _rx) = mpsc::channel(16);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
assert!(task.node_dest_hash.is_none());
task.set_node([0xBB; 16]);
@@ -2281,45 +2352,46 @@ mod tests {
#[test]
fn test_accept_message() {
let (tx, _rx) = mpsc::channel(16);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let mut msg = crate::message::LxMessage::new(
let _key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let msg = crate::propagation_node::tests::opaque_message(
[0xBB; 16],
[0xCC; 16],
"Test",
"sync test content",
crate::constants::DeliveryMethod::Propagated,
);
msg.sign(&key).unwrap();
assert!(task.accept_message(&msg));
assert!(task.accept_fixture(&msg));
assert_eq!(task.message_count(), 1);
}
#[test]
fn test_shared_node_store_is_live() {
let (tx, mut rx) = mpsc::channel(64);
let shared_node = Arc::new(Mutex::new(PropagationNode::new(
PropagationNodeConfig::default(),
[0xAA; 16],
)));
let shared_node = Arc::new(Mutex::new(
crate::propagation_node::tests::durable_test_node(
PropagationNodeConfig::default(),
[0xAA; 16],
),
));
let mut task = PropagationSyncTask::with_shared_node(tx, shared_node.clone());
task.set_node([0xBB; 16]);
make_sync_due(&mut task);
assert_eq!(task.message_count(), 0);
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let mut msg = crate::message::LxMessage::new(
let _key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let msg = crate::propagation_node::tests::opaque_message(
[0xBB; 16],
[0xCC; 16],
"Test",
"shared node content",
crate::constants::DeliveryMethod::Propagated,
);
msg.sign(&key).unwrap();
assert!(shared_node.lock().unwrap().accept_message(&msg));
assert!(shared_node.lock().unwrap().accept_fixture(&msg));
assert_eq!(task.message_count(), 1);
task.tick();
@@ -2333,7 +2405,7 @@ mod tests {
#[test]
fn test_idle_no_node_configured() {
let (tx, _rx) = mpsc::channel(16);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.tick();
assert_eq!(task.state, SyncTaskState::Idle);
}
@@ -2341,7 +2413,7 @@ mod tests {
#[test]
fn test_idle_no_messages() {
let (tx, _rx) = mpsc::channel(16);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.set_node([0xBB; 16]);
make_sync_due(&mut task);
task.tick();
@@ -2351,20 +2423,20 @@ mod tests {
#[test]
fn test_starts_sync_when_ready() {
let (tx, mut rx) = mpsc::channel(64);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.set_node([0xBB; 16]);
make_sync_due(&mut task);
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let mut msg = crate::message::LxMessage::new(
let _key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let msg = crate::propagation_node::tests::opaque_message(
[0xBB; 16],
[0xCC; 16],
"Test",
"content",
crate::constants::DeliveryMethod::Propagated,
);
msg.sign(&key).unwrap();
task.accept_message(&msg);
task.accept_fixture(&msg);
task.tick();
assert_eq!(task.state, SyncTaskState::Establishing);
@@ -2376,26 +2448,29 @@ mod tests {
TransportMessage::RegisterDestination { .. }
));
let outbound = rx.try_recv();
assert!(matches!(outbound.unwrap(), TransportMessage::Outbound(_)));
assert!(matches!(
outbound.unwrap(),
TransportMessage::SendLinkRequest { .. }
));
}
#[test]
fn test_sync_timeout() {
let (tx, _rx) = mpsc::channel(64);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.set_node([0xBB; 16]);
make_sync_due(&mut task);
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let mut msg = crate::message::LxMessage::new(
let _key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let msg = crate::propagation_node::tests::opaque_message(
[0xBB; 16],
[0xCC; 16],
"Test",
"content",
crate::constants::DeliveryMethod::Propagated,
);
msg.sign(&key).unwrap();
task.accept_message(&msg);
task.accept_fixture(&msg);
task.tick();
assert_eq!(task.state, SyncTaskState::Establishing);
@@ -2423,7 +2498,7 @@ mod tests {
link_keys,
)
.unwrap();
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.link = Some(initiator);
task.link_id = Some(link_id);
task.attached_interface = Some(0);
@@ -2456,7 +2531,7 @@ mod tests {
link_keys,
)
.unwrap();
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.link = Some(initiator);
task.link_id = Some(link_id);
task.attached_interface = Some(0);
@@ -2484,7 +2559,7 @@ mod tests {
let (tx, mut rx) = mpsc::channel(1);
tx.try_send(TransportMessage::DeregisterDestination { hash: [0x01; 16] })
.unwrap();
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
assert!(task.request_sync_now([0xBB; 16]));
assert_eq!(task.pending_transport.len(), 2);
@@ -2500,7 +2575,7 @@ mod tests {
task.tick();
assert!(matches!(
rx.try_recv().unwrap(),
TransportMessage::Outbound(_)
TransportMessage::SendLinkRequest { .. }
));
assert!(task.pending_transport.is_empty());
}
@@ -2510,7 +2585,7 @@ mod tests {
let (tx, _rx) = mpsc::channel(1);
tx.try_send(TransportMessage::DeregisterDestination { hash: [0; 16] })
.unwrap();
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.state = SyncTaskState::Offering;
for index in 0..PropagationSyncTask::PENDING_TRANSPORT_LIMIT {
assert!(
@@ -2541,7 +2616,7 @@ mod tests {
let responder_public = responder_key.public_key();
let (_responder, proof) =
Link::new_responder(&request_data, &responder_key, node_hash, 1).unwrap();
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.node_dest_hash = Some(node_hash);
task.link_id = Some(link.link_id);
task.link = Some(link);
@@ -2580,7 +2655,7 @@ mod tests {
.unwrap();
let transfer = transfers.pop_front().unwrap();
let resource_hash = transfer.resource.resource_hash;
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.link_id = Some(link_id);
task.link = Some(initiator);
task.attached_interface = Some(4);
@@ -2590,6 +2665,7 @@ mod tests {
let encrypted = responder.encrypt(&resource_hash).unwrap();
task.event_tx
.try_send(DestinationEvent::InboundPacket {
interface_owner: None,
raw: link_data_packet(
link_id,
rns_wire::context::PacketContext::ResourceRcl,
@@ -2608,23 +2684,27 @@ mod tests {
#[test]
fn test_cleanup_deregisters() {
let (tx, mut rx) = mpsc::channel(64);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.set_node([0xBB; 16]);
make_sync_due(&mut task);
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let mut msg = crate::message::LxMessage::new(
let _key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let msg = crate::propagation_node::tests::opaque_message(
[0xBB; 16],
[0xCC; 16],
"Test",
"content",
crate::constants::DeliveryMethod::Propagated,
);
msg.sign(&key).unwrap();
task.accept_message(&msg);
task.accept_fixture(&msg);
task.tick();
while rx.try_recv().is_ok() {}
while let Ok(message) = rx.try_recv() {
if let TransportMessage::SendLinkRequest { result_tx, .. } = message {
let _ = result_tx.send(Ok(()));
}
}
task.state = SyncTaskState::Complete;
task.tick();
@@ -2636,7 +2716,7 @@ mod tests {
#[test]
fn rejected_endpoint_send_fails_the_sync_owner() {
let (tx, mut rx) = mpsc::channel(64);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
let link_id = [0xD8; 16];
task.link_id = Some(link_id);
task.state = SyncTaskState::Offering;
@@ -2662,7 +2742,7 @@ mod tests {
#[test]
fn test_authenticated_remote_link_close_fails_and_cleans_up() {
let (tx, mut rx) = mpsc::channel(64);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
let node_hash = [0xE3; 16];
let (link, mut responder_link) = active_link_pair(node_hash);
let link_id = link.link_id;
@@ -2681,6 +2761,7 @@ mod tests {
.expect("remote active link emits authenticated teardown");
task.event_tx
.try_send(DestinationEvent::InboundPacket {
interface_owner: None,
raw: link_data_packet(
link_id,
rns_wire::context::PacketContext::LinkClose,
@@ -2704,7 +2785,7 @@ mod tests {
#[test]
fn test_unauthenticated_link_close_is_ignored() {
let (tx, _rx) = mpsc::channel(64);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
let node_hash = [0xE4; 16];
let (link, _responder_link) = active_link_pair(node_hash);
let link_id = link.link_id;
@@ -2716,6 +2797,7 @@ mod tests {
task.event_tx
.try_send(DestinationEvent::InboundPacket {
interface_owner: None,
raw: link_data_packet(link_id, rns_wire::context::PacketContext::LinkClose, &[0u8]),
interface_id: 0,
metrics: Default::default(),
@@ -2730,7 +2812,7 @@ mod tests {
#[test]
fn test_handle_offer_response_have_all() {
let (tx, _rx) = mpsc::channel(16);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.set_node([0xBB; 16]);
task.state = SyncTaskState::AwaitingResponse;
@@ -2741,21 +2823,23 @@ mod tests {
#[test]
fn empty_policy_selection_completes_without_sending_offer_request() {
let (tx, mut rx) = mpsc::channel(16);
let shared_node = Arc::new(Mutex::new(PropagationNode::new(
PropagationNodeConfig::default(),
[0xAA; 16],
)));
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let mut message = crate::message::LxMessage::new(
let shared_node = Arc::new(Mutex::new(
crate::propagation_node::tests::durable_test_node(
PropagationNodeConfig::default(),
[0xAA; 16],
),
));
let _key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let message = crate::propagation_node::tests::opaque_message(
[0xBB; 16],
[0xCC; 16],
"Test",
"already handled",
crate::constants::DeliveryMethod::Propagated,
);
message.sign(&key).unwrap();
let transient_id = message.transient_id.unwrap();
assert!(shared_node.lock().unwrap().accept_message(&message));
assert!(shared_node.lock().unwrap().accept_fixture(&message));
let node_hash = [0xDD; 16];
let (link, _responder) = active_link_pair(node_hash);
@@ -2780,21 +2864,23 @@ mod tests {
#[tokio::test(flavor = "current_thread")]
async fn production_policy_preparation_runs_through_bounded_worker() {
let (tx, mut rx) = mpsc::channel(16);
let shared_node = Arc::new(Mutex::new(PropagationNode::new(
PropagationNodeConfig::default(),
[0xAA; 16],
)));
let key = Ed25519PrivateKey::generate();
let mut message = crate::message::LxMessage::new(
let shared_node = Arc::new(Mutex::new(
crate::propagation_node::tests::durable_test_node(
PropagationNodeConfig::default(),
[0xAA; 16],
),
));
let _key = Ed25519PrivateKey::generate();
let message = crate::propagation_node::tests::opaque_message(
[0xBB; 16],
[0xCC; 16],
"Test",
"already handled async",
crate::constants::DeliveryMethod::Propagated,
);
message.sign(&key).unwrap();
let transient_id = message.transient_id.unwrap();
assert!(shared_node.lock().unwrap().accept_message(&message));
assert!(shared_node.lock().unwrap().accept_fixture(&message));
let node_hash = [0xDD; 16];
let mut task = PropagationSyncTask::with_shared_node(tx, shared_node);
@@ -2823,21 +2909,23 @@ mod tests {
fn terminal_offer_filters_are_exposed_and_complete_without_wire_offer() {
let (tx, mut rx) = mpsc::channel(16);
let node_hash = [0xDD; 16];
let shared_node = Arc::new(Mutex::new(PropagationNode::new(
PropagationNodeConfig::default(),
[0xAA; 16],
)));
let shared_node = Arc::new(Mutex::new(
crate::propagation_node::tests::durable_test_node(
PropagationNodeConfig::default(),
[0xAA; 16],
),
));
let low = vec![0x11; 64];
let oversized = vec![0x22; 700];
assert!(shared_node.lock().unwrap().accept_propagated_blob(&low, 9));
assert!(shared_node.lock().unwrap().accept_blob_fixture(&low, 0));
assert!(
shared_node
.lock()
.unwrap()
.accept_propagated_blob(&oversized, 20)
.accept_blob_fixture(&oversized, 2)
);
let mut policy = OutboundOfferPolicy::unrestricted(node_hash);
policy.minimum_stamp_cost = 10;
policy.minimum_stamp_cost = 1;
policy.propagation_transfer_limit = Some(0.5);
let mut task = PropagationSyncTask::with_shared_node(tx, shared_node);
task.set_node(node_hash);
@@ -2861,7 +2949,8 @@ mod tests {
#[test]
fn have_all_exposes_every_offered_id_for_authoritative_persistence() {
let dir = std::env::temp_dir().join("lxmf_sync_have_all_persist");
let temporary = tempfile::tempdir().unwrap();
let dir = temporary.path().join("store");
let _ = std::fs::remove_dir_all(&dir);
let node_hash = [0xBB; 16];
let node = PropagationNode::with_storage(
@@ -2871,17 +2960,17 @@ mod tests {
)
.unwrap();
let shared_node = Arc::new(Mutex::new(node));
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let _key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
for content in ["first", "second"] {
let mut message = crate::message::LxMessage::new(
let message = crate::propagation_node::tests::opaque_message(
[0xCC; 16],
[0xDD; 16],
"Test",
content,
crate::constants::DeliveryMethod::Propagated,
);
message.sign(&key).unwrap();
assert!(shared_node.lock().unwrap().accept_message(&message));
assert!(shared_node.lock().unwrap().accept_fixture(&message));
}
let policy = OutboundOfferPolicy::unrestricted(node_hash);
let offered = {
@@ -2907,7 +2996,8 @@ mod tests {
#[test]
fn want_some_is_intersected_with_offer_and_marks_complement_handled() {
let dir = std::env::temp_dir().join("lxmf_sync_want_some_bound");
let temporary = tempfile::tempdir().unwrap();
let dir = temporary.path().join("store");
let _ = std::fs::remove_dir_all(&dir);
let node_hash = [0xBB; 16];
let node = PropagationNode::with_storage(
@@ -2917,17 +3007,17 @@ mod tests {
)
.unwrap();
let shared_node = Arc::new(Mutex::new(node));
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let _key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
for content in ["first", "second"] {
let mut message = crate::message::LxMessage::new(
let message = crate::propagation_node::tests::opaque_message(
[0xCC; 16],
[0xDD; 16],
"Test",
content,
crate::constants::DeliveryMethod::Propagated,
);
message.sign(&key).unwrap();
assert!(shared_node.lock().unwrap().accept_message(&message));
assert!(shared_node.lock().unwrap().accept_fixture(&message));
}
let policy = OutboundOfferPolicy::unrestricted(node_hash);
let offered = {
@@ -2959,7 +3049,7 @@ mod tests {
#[test]
fn test_handle_offer_response_error() {
let (tx, _rx) = mpsc::channel(16);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.set_node([0xBB; 16]);
task.state = SyncTaskState::AwaitingResponse;
@@ -2970,21 +3060,21 @@ mod tests {
#[test]
fn test_handle_offer_response_want_all_no_storage() {
let (tx, _rx) = mpsc::channel(16);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.set_node([0xBB; 16]);
task.state = SyncTaskState::AwaitingResponse;
// In-memory store -- message_get_request returns empty, so WantAll -> Complete.
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let mut msg = crate::message::LxMessage::new(
let _key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let msg = crate::propagation_node::tests::opaque_message(
[0xBB; 16],
[0xCC; 16],
"Test",
"content",
crate::constants::DeliveryMethod::Propagated,
);
msg.sign(&key).unwrap();
task.accept_message(&msg);
task.accept_fixture(&msg);
task.handle_offer_response(OfferResponse::WantAll);
assert_eq!(task.state, SyncTaskState::Complete);
@@ -2993,7 +3083,7 @@ mod tests {
#[test]
fn test_handle_offer_response_want_some() {
let (tx, _rx) = mpsc::channel(16);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.set_node([0xBB; 16]);
task.state = SyncTaskState::AwaitingResponse;
@@ -3004,7 +3094,8 @@ mod tests {
#[test]
fn test_handle_offer_response_want_some_with_storage() {
let dir = std::env::temp_dir().join("lxmf_test_sync_want_some");
let temporary = tempfile::tempdir().unwrap();
let dir = temporary.path().join("store");
let _ = std::fs::remove_dir_all(&dir);
let (tx, _rx) = mpsc::channel(16);
@@ -3012,17 +3103,17 @@ mod tests {
task.set_node([0xBB; 16]);
task.state = SyncTaskState::AwaitingResponse;
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let mut msg = crate::message::LxMessage::new(
let _key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let msg = crate::propagation_node::tests::opaque_message(
[0xBB; 16],
[0xCC; 16],
"Test",
"want some content",
crate::constants::DeliveryMethod::Propagated,
);
msg.sign(&key).unwrap();
let tid = msg.transient_id.unwrap();
task.accept_message(&msg);
task.accept_fixture(&msg);
let policy = OutboundOfferPolicy::unrestricted([0xBB; 16]);
task.propagation_node
@@ -3048,23 +3139,24 @@ mod tests {
#[test]
fn want_all_builds_one_timestamped_resource_batch_and_waits_for_proof() {
let dir = std::env::temp_dir().join("lxmf_test_sync_one_batch");
let temporary = tempfile::tempdir().unwrap();
let dir = temporary.path().join("store");
let _ = std::fs::remove_dir_all(&dir);
let node_hash = [0xBB; 16];
let (tx, _rx) = mpsc::channel(16);
let mut task = PropagationSyncTask::with_storage(tx, [0xAA; 16], dir.clone()).unwrap();
task.set_node(node_hash);
let key = Ed25519PrivateKey::generate();
let _key = Ed25519PrivateKey::generate();
for content in ["one", "two"] {
let mut message = crate::message::LxMessage::new(
let message = crate::propagation_node::tests::opaque_message(
[0xCC; 16],
[0xDD; 16],
"Test",
content,
crate::constants::DeliveryMethod::Propagated,
);
message.sign(&key).unwrap();
assert!(task.accept_message(&message));
assert!(task.accept_fixture(&message));
}
let policy = OutboundOfferPolicy::unrestricted(node_hash);
task.propagation_node
@@ -3092,22 +3184,23 @@ mod tests {
#[test]
fn vanished_requested_file_fails_retryably_for_peer_backoff() {
let dir = std::env::temp_dir().join("lxmf_test_sync_vanished_batch");
let temporary = tempfile::tempdir().unwrap();
let dir = temporary.path().join("store");
let _ = std::fs::remove_dir_all(&dir);
let node_hash = [0xBB; 16];
let (tx, _rx) = mpsc::channel(16);
let mut task = PropagationSyncTask::with_storage(tx, [0xAA; 16], dir.clone()).unwrap();
task.set_node(node_hash);
let key = Ed25519PrivateKey::generate();
let mut message = crate::message::LxMessage::new(
let _key = Ed25519PrivateKey::generate();
let message = crate::propagation_node::tests::opaque_message(
[0xCC; 16],
[0xDD; 16],
"Test",
"vanish",
crate::constants::DeliveryMethod::Propagated,
);
message.sign(&key).unwrap();
assert!(task.accept_message(&message));
assert!(task.accept_fixture(&message));
let policy = OutboundOfferPolicy::unrestricted(node_hash);
let (generation, reads) = {
let mut node = task.propagation_node.lock().unwrap();
@@ -3153,22 +3246,22 @@ mod tests {
#[test]
fn test_peer_created_on_sync_start() {
let (tx, _rx) = mpsc::channel(64);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.set_node([0xBB; 16]);
make_sync_due(&mut task);
assert!(task.peer().is_none());
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let mut msg = crate::message::LxMessage::new(
let _key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let msg = crate::propagation_node::tests::opaque_message(
[0xBB; 16],
[0xCC; 16],
"Test",
"content",
crate::constants::DeliveryMethod::Propagated,
);
msg.sign(&key).unwrap();
task.accept_message(&msg);
task.accept_fixture(&msg);
task.tick();
assert_eq!(task.state, SyncTaskState::Establishing);
@@ -3181,7 +3274,7 @@ mod tests {
#[test]
fn request_sync_now_starts_without_waiting_for_interval() {
let (tx, _rx) = mpsc::channel(64);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.request_sync_now([0xBB; 16]);
@@ -3194,7 +3287,7 @@ mod tests {
#[test]
fn active_sync_rejects_different_request_without_mutating_target_or_policy() {
let (tx, _rx) = mpsc::channel(64);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
let policy_a = OutboundOfferPolicy::unrestricted([0xA1; 16]);
let policy_b = OutboundOfferPolicy::unrestricted([0xB2; 16]);
@@ -3207,7 +3300,7 @@ mod tests {
#[test]
fn cancel_peer_sync_clears_active_pending_and_session_state() {
let (tx, _rx) = mpsc::channel(64);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
let peer_hash = [0xA1; 16];
assert!(task.request_sync_now_with_policy(OutboundOfferPolicy::unrestricted(peer_hash)));
task.handled_updates.push([0x44; 32]);
@@ -3233,7 +3326,7 @@ mod tests {
#[test]
fn terminal_results_advance_generation_only_on_success_and_must_be_drained() {
let (tx, _rx) = mpsc::channel(64);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.node_dest_hash = Some([0xA1; 16]);
task.active_offer_generation = Some(7);
task.generation_exhausted = false;
@@ -3277,7 +3370,7 @@ mod tests {
#[test]
fn terminal_result_carries_python_peer_accounting_deltas() {
let (tx, _rx) = mpsc::channel(64);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.node_dest_hash = Some([0xC3; 16]);
task.offered_count = 11;
task.outgoing_count = 7;
@@ -3307,7 +3400,7 @@ mod tests {
let (_responder, proof_data) =
Link::new_responder(&request_data, &responder_key, node_hash, 1).unwrap();
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
let local_key = Ed25519PrivateKey::generate();
let mut local_pub = [0x33; 64];
local_pub[32..].copy_from_slice(&local_key.public_key().to_bytes());
@@ -3318,16 +3411,16 @@ mod tests {
task.peer = Some(LxmPeer::new(node_hash));
task.state = SyncTaskState::Establishing;
let message_key = Ed25519PrivateKey::generate();
let mut message = crate::message::LxMessage::new(
let _message_key = Ed25519PrivateKey::generate();
let message = crate::propagation_node::tests::opaque_message(
[0xCC; 16],
[0xDD; 16],
"Test",
"identify ordering",
crate::constants::DeliveryMethod::Propagated,
);
message.sign(&message_key).unwrap();
assert!(task.accept_message(&message));
assert!(task.accept_fixture(&message));
task.offer_policy = Some(OutboundOfferPolicy::unrestricted(node_hash));
task.handle_link_proof(&proof_data, &responder_pub, &responder_pub.to_bytes(), 0);
@@ -3359,20 +3452,20 @@ mod tests {
#[test]
fn test_peer_cleared_on_cleanup() {
let (tx, mut rx) = mpsc::channel(64);
let mut task = PropagationSyncTask::new(tx, [0xAA; 16]);
let mut task = test_task(tx, [0xAA; 16]);
task.set_node([0xBB; 16]);
make_sync_due(&mut task);
let key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let mut msg = crate::message::LxMessage::new(
let _key = rns_crypto::ed25519::Ed25519PrivateKey::generate();
let msg = crate::propagation_node::tests::opaque_message(
[0xBB; 16],
[0xCC; 16],
"Test",
"content",
crate::constants::DeliveryMethod::Propagated,
);
msg.sign(&key).unwrap();
task.accept_message(&msg);
task.accept_fixture(&msg);
task.tick();
while rx.try_recv().is_ok() {}
File diff suppressed because it is too large. Load diff
+18 -1
View File
@@ -96,6 +96,20 @@ pub fn stamp_iteration_cap(cost: u8) -> Option<u64> {
/// [`stamp_iteration_cap`]; returns `None` when the cap is exhausted or the
/// cost is unsatisfiable.
pub fn generate_stamp(material: &[u8], cost: u8, expand_rounds: usize) -> Option<([u8; 32], u32)> {
generate_stamp_cancellable(material, cost, expand_rounds, &AtomicBool::new(false))
}
/// Synchronous bounded worker entry. Cancellation revokes work without claiming
/// that an async task abort stopped this closure or released its byte owners.
pub fn generate_stamp_cancellable(
material: &[u8],
cost: u8,
expand_rounds: usize,
cancel: &AtomicBool,
) -> Option<([u8; 32], u32)> {
if cancel.load(Ordering::Acquire) {
return None;
}
if cost == 0 {
return Some(([0u8; 32], 0));
}
@@ -107,7 +121,10 @@ pub fn generate_stamp(material: &[u8], cost: u8, expand_rounds: usize) -> Option
base_hasher.update(&workblock);
let mut rng = rand::thread_rng();
for _ in 0..max_iterations {
for iteration in 0..max_iterations {
if iteration % 1000 == 0 && cancel.load(Ordering::Acquire) {
return None;
}
let stamp = rand_bytes_from(&mut rng);
let value = stamp_value_from_base(&base_hasher, &stamp);
if value >= cost as u32 {
+560
View File
@@ -0,0 +1,560 @@
//! Focused public-boundary regressions for durable propagation delivery.
use lxmf_core::admission::*;
use lxmf_core::admission_store::FileAdmissionStore;
use lxmf_core::constants::DeliveryMethod;
use lxmf_core::message::{LxMessage, LxMessageDraft, RecipientStamp};
use lxmf_core::propagation_send::*;
use rns_crypto::{ed25519::Ed25519PrivateKey, sha::full_hash};
// These tests deliberately exhaust the shared production admission budget.
// Exclude only other budget-exhaustion fixtures, without changing its limits.
static PROCESSING_BUDGET_TEST: std::sync::Mutex<()> = std::sync::Mutex::new(());
fn message(stamp: Option<RecipientStamp>) -> LxMessage {
let mut draft = LxMessageDraft::new(
[1; 16],
[2; 16],
"title",
"body",
DeliveryMethod::Propagated,
)
.unwrap();
draft.set_timestamp(100.).unwrap();
draft
.sign(&Ed25519PrivateKey::from_bytes(&[3; 32]))
.unwrap()
.finalize(stamp)
.unwrap()
}
fn scope(n: u8) -> AdmissionScope {
AdmissionScope {
identity: [4; 16],
node: [5; 16],
transient_id: [n; 32],
}
}
fn record(msg: &LxMessage, n: u8, time: u64, disposition: DurableDisposition) -> AdmissionRecord {
AdmissionRecord {
scope: scope(n),
message_id: msg.message_id(),
received_wire_hash: full_hash(msg.wire_bytes()),
stored_message_wire_hash: None,
disposition,
committed_at: time,
}
}
fn commit(
store: &FileAdmissionStore,
msg: &LxMessage,
n: u8,
time: u64,
disposition: DurableDisposition,
) -> DurableAdmissionReceipt {
DurableAdmissionReceipt::commit(store.prepare(
record(msg, n, time, disposition),
msg.wire_owned(),
true,
))
.unwrap()
}
#[test]
fn duplicate_stamp_images_keep_first_archive_and_one_hook_across_restart() {
let temp = tempfile::tempdir().unwrap();
let bodies = temp.path().join("messages");
let store = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
let first = message(None);
let second = message(Some(RecipientStamp::ProofOfWork([7; 32])));
assert_eq!(first.message_id(), second.message_id());
assert_ne!(first.wire_bytes(), second.wire_bytes());
commit(&store, &first, 1, 100, DurableDisposition::Committed);
let duplicate = commit(&store, &second, 2, 101, DurableDisposition::Committed);
assert_eq!(
duplicate.record().disposition,
DurableDisposition::Duplicate
);
assert_eq!(
duplicate.record().received_wire_hash,
full_hash(second.wire_bytes())
);
assert_eq!(
duplicate.record().stored_message_wire_hash,
Some(full_hash(first.wire_bytes()))
);
assert_eq!(
std::fs::read(bodies.join(format!("{}.lxm", hex::encode(first.message_id())))).unwrap(),
first.wire_bytes()
);
assert_eq!(store.pending_hooks().len(), 1);
drop(store);
let reopened = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
assert_eq!(
reopened.haves(scope(1).identity, scope(1).node, 102).len(),
2
);
assert_eq!(reopened.pending_hooks().len(), 1);
let event = reopened.pending_hooks()[0].0;
reopened.complete_hook(event).unwrap();
drop(reopened);
assert!(
FileAdmissionStore::open(temp.path(), &bodies)
.unwrap()
.pending_hooks()
.is_empty()
);
}
#[test]
fn published_body_intent_recovers_original_tid_after_missing_commit() {
let temp = tempfile::tempdir().unwrap();
let bodies = temp.path().join("messages");
let store = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
let msg = message(None);
commit(&store, &msg, 9, 100, DurableDisposition::Committed);
drop(store);
let dir = temp.path().join("download-admission-v1");
for file in std::fs::read_dir(&dir).unwrap() {
let path = file.unwrap().path();
if path.extension().is_some_and(|s| s == "commit") {
std::fs::remove_file(path).unwrap();
}
}
let recovered = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
assert_eq!(
recovered.haves(scope(9).identity, scope(9).node, 101),
vec![scope(9).transient_id.to_vec()]
);
assert_eq!(recovered.pending_hooks().len(), 1);
}
#[test]
fn damaged_archive_never_becomes_purge_authority_on_restart() {
let temp = tempfile::tempdir().unwrap();
let bodies = temp.path().join("messages");
let store = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
let msg = message(None);
commit(&store, &msg, 1, 100, DurableDisposition::Committed);
drop(store);
let archive = bodies.join(format!("{}.lxm", hex::encode(msg.message_id())));
std::fs::write(&archive, b"preserved corrupt evidence").unwrap();
let reopened = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
assert!(
reopened
.haves(scope(1).identity, scope(1).node, 101)
.is_empty()
);
assert!(reopened.pending_hooks().is_empty());
assert_eq!(
std::fs::read(archive).unwrap(),
b"preserved corrupt evidence"
);
}
#[test]
fn expired_policy_receipt_is_revalidated_and_user_deletion_outlives_tid_receipts() {
let temp = tempfile::tempdir().unwrap();
let bodies = temp.path().join("messages");
let store = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
let msg = message(None);
commit(&store, &msg, 1, 100, DurableDisposition::PolicyDiscard);
assert!(
!bodies
.join(format!("{}.lxm", hex::encode(msg.message_id())))
.exists()
);
let now = 101 + POLICY_RECEIPT_LIFETIME;
assert!(
store
.haves(scope(1).identity, scope(1).node, now)
.is_empty()
);
assert_eq!(
commit(&store, &msg, 1, now, DurableDisposition::Committed)
.record()
.disposition,
DurableDisposition::Committed
);
store
.mark_user_deleted(scope(1).identity, msg.message_id(), now + 1)
.unwrap();
assert!(store.pending_hooks().is_empty());
assert_eq!(
store.maintain(now + 2 + POLICY_RECEIPT_LIFETIME).unwrap(),
1
);
drop(store);
let reopened = FileAdmissionStore::open(temp.path(), &bodies).unwrap();
assert_eq!(
commit(
&reopened,
&msg,
2,
now + 3 + POLICY_RECEIPT_LIFETIME,
DurableDisposition::Committed
)
.record()
.disposition,
DurableDisposition::UserDeleted
);
assert!(
!bodies
.join(format!("{}.lxm", hex::encode(msg.message_id())))
.exists()
);
}
#[test]
fn suppression_retries_transient_failures_and_revalidates_epoch_changes() {
let mut ledger = SuppressionLedger::default();
let epoch = AdmissionEpochs::default();
ledger
.record_failure(scope(1), SuppressionReason::DecryptionFailed, epoch, 100)
.unwrap();
assert!(ledger.get(&scope(1)).unwrap().active(101, epoch));
let mut new = epoch;
new.keys[0] = 1;
assert!(!ledger.get(&scope(1)).unwrap().active(101, new));
for _ in 0..20 {
ledger
.record_failure(scope(2), SuppressionReason::StorageBusy, epoch, 100)
.unwrap();
}
let retry = ledger.get(&scope(2)).unwrap();
assert!((3340..=4060).contains(&retry.next_retry));
assert!(!retry.active(retry.next_retry, epoch));
let wire = rmp_serde::to_vec(&ledger).unwrap();
let restored: SuppressionLedger = rmp_serde::from_slice(&wire).unwrap();
assert_eq!(restored.records().count(), 2);
}
#[test]
fn processing_admission_fails_promptly_without_partial_credit_deadlock() {
let _exclusive = PROCESSING_BUDGET_TEST.lock().unwrap();
assert!(matches!(
ProcessingLease::try_acquire(usize::MAX),
Err(SuppressionReason::TooLarge)
));
let workers = (0..MAX_PROCESSORS)
.map(|_| ProcessingLease::try_acquire(100).unwrap())
.collect::<Vec<_>>();
assert!(matches!(
ProcessingLease::try_acquire(100),
Err(SuppressionReason::WorkerUnavailable)
));
drop(workers);
assert!(ProcessingLease::try_acquire(100).is_ok());
}
#[test]
fn propagation_retry_keeps_ciphertext_and_tid_when_cost_rises() {
let msg = message(None);
let mut envelope = PropagationEnvelope::new(msg, [6; 32], 0, |p| Ok(p.to_vec())).unwrap();
let initial = envelope.ciphertext().clone();
let tid = envelope.transient_id();
let policy = AdvertisedNodePolicy {
stamp_cost: 0,
transfer_limit_kb: 256.,
recorded_at: 100.,
};
let mut ready = propagation_readiness([8; 16], true, true, Some(policy), true, 101.).unwrap();
envelope.pack_for(ready, 101.).unwrap();
ready.policy.stamp_cost = 4;
envelope.pack_for(ready, 102.).unwrap();
assert_eq!(envelope.ciphertext(), &initial);
assert_eq!(envelope.transient_id(), tid);
assert!(envelope.stamp_value() >= 4);
assert_eq!(
propagation_readiness([8; 16], true, true, None, true, 101.).unwrap_err(),
MissingPropagationInput::NodePolicy
);
assert!(propagation_readiness([8; 16], true, true, Some(policy), true, 101.).is_ok());
}
#[test]
fn reply_ticket_cannot_sign_before_its_exact_durable_intent() {
let temp = tempfile::tempdir().unwrap();
let mut router = lxmf_core::router::LxmRouter::new(Default::default());
let mut draft =
LxMessageDraft::new([1; 16], [2; 16], "", "ticket", DeliveryMethod::Direct).unwrap();
draft.include_ticket = true;
let intent = router.prepare_outbound(&mut draft).unwrap();
assert!(intent.requires_persistence());
assert!(
draft
.clone()
.sign(&Ed25519PrivateKey::from_bytes(&[3; 32]))
.is_err()
);
let mut other =
LxMessageDraft::new([3; 16], [2; 16], "", "other", DeliveryMethod::Direct).unwrap();
other.include_ticket = true;
assert!(matches!(
router.prepare_outbound(&mut other),
Err(lxmf_core::router::TicketPreparationError::PendingPersistence)
));
intent.persist(temp.path(), &mut draft).unwrap();
let msg = draft
.sign(&Ed25519PrivateKey::from_bytes(&[3; 32]))
.unwrap()
.finalize(None)
.unwrap();
assert!(
msg.fields()
.get(lxmf_core::constants::FIELD_TICKET)
.is_some()
);
let loaded = lxmf_core::persist::load_tickets(temp.path()).unwrap();
assert!(!loaded.0.inbound.is_empty());
assert!(router.prepare_outbound(&mut other).is_ok());
}
#[test]
fn suppression_hydration_rejects_duplicate_scopes_and_node_quota() {
let mut ledger = SuppressionLedger::default();
let row = ledger
.record_failure(
scope(1),
SuppressionReason::InvalidSignature,
AdmissionEpochs::default(),
100,
)
.unwrap()
.clone();
assert!(SuppressionLedger::from_records([row.clone(), row.clone()]).is_err());
let mut keys = row.epochs;
keys.keys[0] = 1;
assert!(!row.active(101, keys));
let mut policy = row.epochs;
policy.policy[0] = 1;
assert!(!row.active(101, policy));
let rows = (0..=SuppressionLedger::PER_NODE).map(|index| {
let mut value = row.clone();
value.scope.transient_id[..8].copy_from_slice(&(index as u64).to_be_bytes());
value
});
assert!(matches!(
SuppressionLedger::from_records(rows),
Err(AdmissionError::DispositionLedgerFull)
));
assert_eq!(
SuppressionLedger::from_records([row])
.unwrap()
.records()
.count(),
1
);
}
#[test]
fn adapter_processing_memory_shares_peak_budget_without_second_worker() {
let _exclusive = PROCESSING_BUDGET_TEST.lock().unwrap();
let worker = ProcessingLease::try_acquire(1).unwrap();
assert!(matches!(
ProcessingMemoryLease::try_acquire(MAX_PROCESSING_BYTES),
Err(SuppressionReason::WorkerUnavailable)
));
let extra = ProcessingMemoryLease::try_acquire(8 * 1024 * 1024).unwrap();
drop(extra);
drop(worker);
let all = ProcessingMemoryLease::try_acquire(MAX_PROCESSING_BYTES).unwrap();
assert!(matches!(
ProcessingLease::try_acquire(1),
Err(SuppressionReason::WorkerUnavailable)
));
drop(all);
assert!(ProcessingLease::try_acquire(1).is_ok());
}
fn reject_link_request(
receiver: &mut tokio::sync::mpsc::Receiver<rns_transport::messages::TransportMessage>,
) {
use rns_transport::messages::TransportMessage;
while let Ok(message) = receiver.try_recv() {
if let TransportMessage::SendLinkRequest { result_tx, .. } = message {
result_tx
.send(Err(
rns_transport::link_messages::LinkRequestDispatchError::Capacity(
rns_transport::InterfaceCapacityError::LinkCapacityUnavailable {
interface_id: 7,
clear_mtu: 499,
required: 500,
},
),
))
.unwrap();
return;
}
}
panic!("exact Link request dispatch channel was not staged");
}
#[test]
fn link_capacity_failure_reaches_all_three_initiators_before_establishment_timeout() {
use lxmf_core::link_delivery::{DeliveryResult, LinkDeliveryManager};
use lxmf_core::propagation_client::{PropagationClient, PropagationClientState};
use lxmf_core::propagation_sync::{PeerSyncTerminalState, PropagationSyncTask};
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
let mut delivery = LinkDeliveryManager::new(tx.clone(), None, None);
delivery.start_delivery(message(None), [3; 16], 1).unwrap();
reject_link_request(&mut rx);
assert!(delivery.tick().iter().any(
|result| matches!(result,DeliveryResult::Failed {reason,..} if reason.contains("499"))
));
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
let mut client = PropagationClient::new(tx, None, None);
client.set_propagation_node([3; 16]);
assert!(client.start_download());
reject_link_request(&mut rx);
client.tick();
assert_eq!(
client.transfer_status().state,
PropagationClientState::Failed
);
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
let mut sync = PropagationSyncTask::new(tx, [8; 16]);
assert!(sync.request_sync_now([3; 16]));
reject_link_request(&mut rx);
sync.tick();
assert_eq!(
sync.take_terminal_peer_result().unwrap().state,
PeerSyncTerminalState::Failed
);
}
#[test]
fn canceled_download_closes_exact_request_admission_reply() {
let (tx, mut rx) = tokio::sync::mpsc::channel(32);
let mut client = lxmf_core::propagation_client::PropagationClient::new(tx, None, None);
client.set_propagation_node([3; 16]);
assert!(client.start_download());
client.cancel_download();
let mut found = false;
while let Ok(message) = rx.try_recv() {
if let rns_transport::messages::TransportMessage::SendLinkRequest { result_tx, .. } =
message
{
assert!(result_tx.is_closed());
found = true;
}
}
assert!(found);
}
#[test]
fn stale_checkpoint_cannot_erase_ticket_after_signing_intent_commit() {
let temp = tempfile::tempdir().unwrap();
let mut router = lxmf_core::router::LxmRouter::new(Default::default());
let stale = router.state_snapshot();
let mut draft =
LxMessageDraft::new([1; 16], [2; 16], "", "ticket", DeliveryMethod::Direct).unwrap();
draft.include_ticket = true;
let intent = router.prepare_outbound(&mut draft).unwrap();
intent.persist(temp.path(), &mut draft).unwrap();
let committed = lxmf_core::persist::load_tickets(temp.path()).unwrap().0;
assert_eq!(committed.inbound.len(), 1);
stale.save_state(temp.path()).unwrap();
assert_eq!(
lxmf_core::persist::load_tickets(temp.path()).unwrap().0,
committed
);
// A newer checkpoint can commit while a draft is waiting for its exact
// intent. The old intent verifies that its ticket is still present.
drop(draft);
let mut next =
LxMessageDraft::new([4; 16], [2; 16], "", "next", DeliveryMethod::Direct).unwrap();
next.include_ticket = true;
let intent = router.prepare_outbound(&mut next).unwrap();
router.state_snapshot().save_state(temp.path()).unwrap();
intent.persist(temp.path(), &mut next).unwrap();
assert!(next.sign(&Ed25519PrivateKey::from_bytes(&[3; 32])).is_ok());
assert_eq!(
lxmf_core::persist::load_tickets(temp.path())
.unwrap()
.0
.inbound
.len(),
2
);
}
#[test]
fn suppression_checkpoint_rejects_duplicate_scope_and_truncated_allocation_claim() {
let temp = tempfile::tempdir().unwrap();
let mut ledger = SuppressionLedger::default();
ledger
.record_failure(
scope(1),
SuppressionReason::Malformed,
AdmissionEpochs::default(),
100,
)
.unwrap();
lxmf_core::persist::save_suppression(temp.path(), &ledger).unwrap();
assert_eq!(
lxmf_core::persist::load_suppression(temp.path())
.unwrap()
.records()
.count(),
1
);
let path = temp.path().join("propagation_suppression_v1");
let bytes = std::fs::read(&path).unwrap();
let mut value = rmpv::decode::read_value(&mut bytes.as_slice()).unwrap();
let rmpv::Value::Array(fields) = &mut value else {
panic!("ledger wrapper")
};
let rmpv::Value::Map(rows) = &mut fields[0] else {
panic!("ledger records")
};
rows.push(rows[0].clone());
let mut duplicate = Vec::new();
rmpv::encode::write_value(&mut duplicate, &value).unwrap();
std::fs::write(&path, duplicate).unwrap();
assert!(lxmf_core::persist::load_suppression(temp.path()).is_err());
std::fs::write(&path, [0x91, 0xdf, 0xff, 0xff, 0xff, 0xff]).unwrap();
assert!(lxmf_core::persist::load_suppression(temp.path()).is_err());
}
#[test]
fn strict_ratchet_checkpoints_round_trip_and_surface_failed_publication() {
use rns_identity::{
announce_state::RatchetControlState,
identity::Identity,
ratchet::{RatchetRing, ReceivedRatchet},
};
let temp = tempfile::tempdir().unwrap();
let identity = Identity::new();
let mut ring = RatchetRing::new();
let public = ring.rotate_at(100.);
let ring_path = temp.path().join("ring");
ring.save_verified_durable(&ring_path, &identity).unwrap();
assert_eq!(
RatchetRing::load_verified(&ring_path, &identity)
.unwrap()
.ring()
.current_public_key(),
Some(public)
);
let control = RatchetControlState::new(identity.hash, [2; 16])
.prepare_announce(100)
.unwrap()
.unwrap();
let control_path = temp.path().join("control");
control
.save_verified_durable(&control_path, &identity)
.unwrap();
assert_eq!(
RatchetControlState::load_verified(&control_path, &identity, [2; 16]).unwrap(),
control
);
let received = ReceivedRatchet::new_at(public, 100.);
let received_path = temp.path().join("received");
received.save_durable(&received_path).unwrap();
assert_eq!(
ReceivedRatchet::load(&received_path).unwrap().ratchet_pub,
public
);
let blocker = temp.path().join("not-a-directory");
std::fs::write(&blocker, b"preserve").unwrap();
assert!(
ring.save_verified_durable(&blocker.join("ring"), &identity)
.is_err()
);
assert!(
control
.save_verified_durable(&blocker.join("control"), &identity)
.is_err()
);
assert!(received.save_durable(&blocker.join("received")).is_err());
assert_eq!(std::fs::read(blocker).unwrap(), b"preserve");
}
+243
View File
@@ -0,0 +1,243 @@
use bytes::Bytes;
use lxmf_core::propagation_node::{
PropagationAdmission, PropagationAdmissionOutcome, PropagationNode, PropagationNodeConfig,
ValidatedOpaquePropagationBlob,
};
use rmpv::Value;
fn payload(destination: [u8; 16]) -> Bytes {
let recipient = rns_identity::identity::Identity::new();
let mut bytes = destination.to_vec();
bytes.extend_from_slice(&recipient.encrypt(b"private test payload", None).unwrap());
bytes.extend_from_slice(&[0; 32]);
bytes.into()
}
fn validated(bytes: Bytes) -> ValidatedOpaquePropagationBlob {
ValidatedOpaquePropagationBlob::validate(bytes, 0).unwrap()
}
fn request(wants: Option<Vec<[u8; 32]>>, haves: Option<Vec<[u8; 32]>>) -> Vec<u8> {
let ids = |value: Option<Vec<[u8; 32]>>| {
value
.map(|v| Value::Array(v.into_iter().map(|id| Value::Binary(id.to_vec())).collect()))
.unwrap_or(Value::Nil)
};
encode(&Value::Array(vec![ids(wants), ids(haves)]))
}
fn reserve(
node: &mut PropagationNode,
bytes: Bytes,
) -> lxmf_core::propagation_node::PropagationStoreWritePlan {
match node.plan_opaque_admission(validated(bytes)) {
PropagationAdmission::Reserved(plan) => *plan,
other => panic!("expected new admission: {other:?}"),
}
}
#[tokio::test]
async fn duplicate_waits_for_exact_commit_and_rechecks_retained_files() {
let dir = tempfile::tempdir().unwrap();
let old = dir.path().join("store");
let mut node =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], old.clone())
.unwrap();
let bytes = payload([2; 16]);
let tid = validated(bytes.clone()).transient_id();
let plan = reserve(&mut node, bytes.clone());
let PropagationAdmission::Pending(waiter) =
node.plan_opaque_admission(validated(bytes.clone()))
else {
panic!("duplicate must coalesce")
};
let task = tokio::spawn(waiter.wait());
tokio::task::yield_now().await;
assert!(!task.is_finished());
assert!(node.commit_store_write(plan.persist().unwrap()));
assert_eq!(task.await.unwrap(), PropagationAdmissionOutcome::Committed);
let PropagationAdmission::CommittedDuplicate(check) =
node.plan_opaque_admission(validated(bytes.clone()))
else {
panic!("committed duplicate")
};
check.verify().unwrap();
let path = node.plan_message_reads(&[tid]).pop().unwrap().path;
std::fs::write(&path, b"corruption").unwrap();
let PropagationAdmission::CommittedDuplicate(check) =
node.plan_opaque_admission(validated(bytes))
else {
panic!("duplicate requires file check")
};
assert!(check.verify().is_err());
drop(node);
assert!(PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], old).is_err());
}
#[tokio::test]
async fn cancelled_reservation_releases_waiters_without_authority_and_can_retry() {
let dir = tempfile::tempdir().unwrap();
let mut node = PropagationNode::with_storage(
PropagationNodeConfig::default(),
[1; 16],
dir.path().join("store"),
)
.unwrap();
let bytes = payload([2; 16]);
let plan = reserve(&mut node, bytes.clone());
let PropagationAdmission::Pending(waiter) =
node.plan_opaque_admission(validated(bytes.clone()))
else {
panic!("duplicate must coalesce")
};
drop(plan);
assert_eq!(waiter.wait().await, PropagationAdmissionOutcome::Failed);
let retry = reserve(&mut node, bytes);
assert!(node.commit_store_write(retry.persist().unwrap()));
}
#[tokio::test]
async fn lost_persisted_callback_reuses_first_image_and_restart_has_one_admission() {
let dir = tempfile::tempdir().unwrap();
let legacy = dir.path().join("store");
let mut node =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], legacy.clone())
.unwrap();
let bytes = payload([2; 16]);
let tid = validated(bytes.clone()).transient_id();
let plan = reserve(&mut node, bytes.clone());
let PropagationAdmission::Pending(waiter) =
node.plan_opaque_admission(validated(bytes.clone()))
else {
panic!("duplicate must coalesce")
};
drop(plan.persist().unwrap());
assert_eq!(waiter.wait().await, PropagationAdmissionOutcome::Failed);
let objects = legacy.with_extension("v2").join("objects");
let first_files: std::collections::BTreeSet<_> = std::fs::read_dir(&objects)
.unwrap()
.map(|entry| entry.unwrap().file_name())
.collect();
assert_eq!(first_files.len(), 3);
let plan = reserve(&mut node, bytes.clone());
assert!(node.commit_store_write(plan.persist().unwrap()));
let retry_files: std::collections::BTreeSet<_> = std::fs::read_dir(&objects)
.unwrap()
.map(|entry| entry.unwrap().file_name())
.collect();
assert_eq!(retry_files, first_files);
drop(node);
let reopened =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], legacy).unwrap();
assert_eq!(reopened.message_count(), 1);
assert_eq!(
std::fs::read(&reopened.plan_message_reads(&[tid])[0].path).unwrap(),
bytes
);
}
#[test]
fn purge_cannot_report_success_when_its_durable_intent_cannot_be_published() {
let dir = tempfile::tempdir().unwrap();
let legacy = dir.path().join("store");
let mut node =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], legacy.clone())
.unwrap();
let destination = [2; 16];
let bytes = payload(destination);
let tid = validated(bytes.clone()).transient_id();
let plan = reserve(&mut node, bytes.clone());
assert!(node.commit_store_write(plan.persist().unwrap()));
let objects = legacy.with_extension("v2").join("objects");
let unavailable = legacy.with_extension("v2").join("temporarily-unavailable");
std::fs::rename(&objects, &unavailable).unwrap();
assert_eq!(
node.handle_get_request(&request(None, Some(vec![tid])), &destination)
.into_response(),
encode(&Value::Nil)
);
assert!(node.contains(&tid));
std::fs::rename(&unavailable, &objects).unwrap();
assert_eq!(
node.handle_get_request(&request(None, Some(vec![tid])), &destination)
.into_response(),
encode(&Value::Array(vec![]))
);
drop(node);
let reopened =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], legacy).unwrap();
assert!(!reopened.contains(&tid));
}
#[test]
fn purge_is_durable_before_success_and_old_plan_cannot_delete_readmission() {
let dir = tempfile::tempdir().unwrap();
let old = dir.path().join("store");
let destination = [2; 16];
let mut node =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], old.clone())
.unwrap();
let bytes = payload(destination);
let tid = validated(bytes.clone()).transient_id();
let plan = reserve(&mut node, bytes.clone());
assert!(node.commit_store_write(plan.persist().unwrap()));
let old_path = node.plan_message_reads(&[tid]).pop().unwrap().path;
let stale = node.handle_get_request(&request(None, Some(vec![tid])), &destination);
let purge = node.handle_get_request(&request(None, Some(vec![tid])), &destination);
assert_eq!(purge.into_response(), encode(&Value::Array(vec![])));
assert!(!node.contains(&tid));
assert!(!old_path.exists());
let replacement = reserve(&mut node, bytes.clone());
assert!(node.commit_store_write(replacement.persist().unwrap()));
let new_path = node.plan_message_reads(&[tid]).pop().unwrap().path;
assert_ne!(old_path, new_path);
// The old plan fails or sees an already completed retirement; it cannot
// gain authority over the distinct new admission path.
let _ = stale.into_response();
assert!(node.contains(&tid));
assert_eq!(std::fs::read(&new_path).unwrap(), bytes);
drop(node);
let reopened =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], old).unwrap();
assert!(reopened.contains(&tid));
}
#[test]
fn foreign_purge_has_no_effect_and_maintenance_publishes_retirement_off_lock() {
let dir = tempfile::tempdir().unwrap();
let config = PropagationNodeConfig {
max_storage: 0,
..Default::default()
};
let mut node =
PropagationNode::with_storage(config, [1; 16], dir.path().join("store")).unwrap();
let bytes = payload([2; 16]);
let tid = validated(bytes.clone()).transient_id();
let plan = reserve(&mut node, bytes);
assert!(node.commit_store_write(plan.persist().unwrap()));
node.handle_get_request(&request(None, Some(vec![tid])), &[3; 16])
.into_response();
assert!(node.contains(&tid));
let maintenance = node.plan_maintenance();
assert!(!maintenance.is_empty());
assert!(node.contains(&tid));
maintenance.persist().unwrap();
assert!(!node.contains(&tid));
assert!(node.create_offer([4; 16], None).is_empty());
}
#[test]
fn legacy_trees_and_second_live_host_cannot_be_opened_implicitly() {
let dir = tempfile::tempdir().unwrap();
let old = dir.path().join("legacy");
std::fs::create_dir(&old).unwrap();
std::fs::write(old.join("private"), b"plaintext").unwrap();
assert!(
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], old.clone())
.is_err()
);
assert_eq!(std::fs::read(old.join("private")).unwrap(), b"plaintext");
let fresh = dir.path().join("fresh");
let node =
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], fresh.clone())
.unwrap();
assert!(
PropagationNode::with_storage(PropagationNodeConfig::default(), [1; 16], fresh).is_err()
);
drop(node);
}
fn encode(value: &Value) -> Vec<u8> {
let mut out = Vec::new();
rmpv::encode::write_value(&mut out, value).unwrap();
out
}
+1
View File
@@ -24,6 +24,7 @@ hex = { workspace = true }
base64 = { workspace = true }
serde_json = { workspace = true }
rmpv = { workspace = true }
zeroize = "1"
[dev-dependencies]
tempfile = { workspace = true }
File diff suppressed because it is too large. Load diff
+16 -1
View File
@@ -404,6 +404,16 @@ pub fn create_router_with_transport(
/// argument rather than interpolating into a shell string, so untrusted path
/// contents cannot inject shell metacharacters.
pub fn execute_on_inbound(command: &str, message_path: &str) -> std::io::Result<()> {
execute_on_inbound_with_event(command, message_path, "")
}
/// Durable propagation outbox events may replay after a crash. Hooks can use
/// this stable identifier for their own idempotency boundary.
pub fn execute_on_inbound_with_event(
command: &str,
message_path: &str,
event_id: &str,
) -> std::io::Result<()> {
use std::process::Command;
let parts = split_command_line(command)?;
@@ -416,10 +426,15 @@ pub fn execute_on_inbound(command: &str, message_path: &str) -> std::io::Result<
cmd.arg(arg);
}
cmd.arg(message_path);
if !event_id.is_empty() {
cmd.env("LXMF_EVENT_ID", event_id);
}
let status = cmd.status()?;
if !status.success() {
tracing::warn!("on_inbound command exited with status: {}", status);
return Err(std::io::Error::other(format!(
"on_inbound command exited with status: {status}"
)));
}
Ok(())
}
+17
View File
@@ -46,6 +46,23 @@ pub struct Args {
#[arg(short = 'p', long = "propagation-node")]
pub propagation_node: bool,
/// Quarantine the legacy relay store and initialize the separate v2 store.
/// Run only after stopping all old relay writers and their auto-restart jobs.
#[arg(long, requires = "relay_writers_stopped")]
pub migrate_propagation_store: bool,
/// Confirm all legacy app/daemon relay writers are stopped for migration.
#[arg(long, requires = "migrate_propagation_store")]
pub relay_writers_stopped: bool,
/// Import an independently verified legacy opaque-ingress recovery manifest.
#[arg(long, requires_all = ["migrate_propagation_store", "recovery_manifest_sha256"])]
pub recover_propagation_manifest: Option<PathBuf>,
/// Separately approved SHA-256 of the exact recovery manifest file.
#[arg(long, requires = "recover_propagation_manifest")]
pub recovery_manifest_sha256: Option<String>,
/// Executable to run when a message is received, overriding config.
#[arg(short = 'i', long = "on-inbound", value_name = "PATH")]
pub on_inbound: Option<String>,
+5 -1
View File
@@ -97,7 +97,7 @@ def validate_metadata(
) -> list[dict[str, object]]:
require_keys(
config, {"schemaVersion", "tool", "baseline", "compatibilityFloor", "packages"},
"metadata",
"metadata", {"approvedBreakingChanges"},
)
if config["schemaVersion"] != 2:
fail("unsupported api-stability schema")
@@ -111,6 +111,10 @@ def validate_metadata(
"compatibility floor",
)
if "approvedBreakingChanges" in config:
require_keys(config["approvedBreakingChanges"],
{"releaseLine", "migrationGuide", "removed"}, "approved break")
tool = config.get("tool")
if not isinstance(tool, dict):
fail("tool contract is missing")
+57 -7
View File
@@ -1,9 +1,10 @@
#!/usr/bin/env python3
"""Reject removals from the reviewed public-API compatibility floor."""
"""Reject unapproved removals from the retained public-API compatibility floor."""
from __future__ import annotations
import json
import re
import subprocess
import sys
from pathlib import Path
@@ -45,6 +46,48 @@ def load_floor_ledger(commit: str) -> dict[str, object]:
fail(f"cannot read API ledger at compatibility floor {commit}")
def approved_removals(ledger: dict[str, object], version: str) -> dict[str, set[str]]:
"""A breaking release allows exact reviewed lines, never a blanket waiver."""
record = ledger.get("approvedBreakingChanges")
if record is None:
return {}
if not isinstance(record, dict) or set(record) != {"releaseLine", "migrationGuide", "removed"}:
fail("approved break needs releaseLine, migrationGuide and exact removed lines")
release_line = record["releaseLine"]
if not isinstance(release_line, str) or not re.fullmatch(r"\d+\.\d+", release_line):
fail("approved break release line is invalid")
if version.split(".")[:2] != release_line.split("."):
fail("approved break does not match the current workspace release line")
guide = record["migrationGuide"]
if not isinstance(guide, str) or not guide.startswith("api/migrations/"):
fail("approved break must link a public API migration guide")
guide_path = (ROOT / guide).resolve()
if not guide_path.is_relative_to(ROOT / "api/migrations") or not guide_path.is_file():
fail("approved break migration guide is missing or outside its directory")
removed = record["removed"]
packages = {package["name"] for package in ledger["packages"]}
if not isinstance(removed, dict) or not removed or not set(removed).issubset(packages):
fail("approved removals must name existing packages")
result = {}
for package, lines in removed.items():
if (not isinstance(lines, list) or not lines
or not all(isinstance(line, str) and line.strip() for line in lines)
or len(set(lines)) != len(lines)):
fail("approved removals must be unique nonempty exact API lines")
result[package] = set(lines)
return result
def validate_removed(package: str, removed: set[str], approved: dict[str, set[str]]) -> None:
allowed = approved.get(package, set())
if removed != allowed:
for line in sorted(removed - allowed):
print(f"unapproved removal: {line}", file=sys.stderr)
for line in sorted(allowed - removed):
print(f"unused removal approval: {line}", file=sys.stderr)
fail(f"{package} removals differ from the exact approved migration")
def main() -> None:
metadata = subprocess.run(
[sys.executable, "tools/check-api-baseline.py", "--metadata-only"], cwd=ROOT
@@ -52,6 +95,16 @@ def main() -> None:
if metadata.returncode != 0:
fail("snapshot metadata is invalid")
ledger = json.loads(LEDGER_PATH.read_text(encoding="utf-8"))
metadata_result = subprocess.run(
["cargo", "metadata", "--locked", "--no-deps", "--format-version", "1"],
cwd=ROOT, capture_output=True, text=True,
)
if metadata_result.returncode:
fail("cannot resolve workspace release version")
versions = {package["version"] for package in json.loads(metadata_result.stdout)["packages"]}
if len(versions) != 1:
fail("workspace release versions disagree")
approved = approved_removals(ledger, versions.pop())
floor = ledger.get("compatibilityFloor", {}).get("evidenceCommit")
if not isinstance(floor, str):
fail("api/stability.json has no compatibility-floor commit")
@@ -79,12 +132,9 @@ def main() -> None:
if removed:
for line in removed:
print(f"- {line}", file=sys.stderr)
if total_removed:
fail(
f"{total_removed} public API lines were removed from the compatibility floor; "
"the current policy permits additions only"
)
print(f"api compatibility: additive-only (+{total_added}, -0)")
validate_removed(package["name"], set(removed), approved)
print(f"api compatibility: checked (+{total_added}, -{total_removed}); "
"unapproved removals forbidden")
if __name__ == "__main__":