Compare commits

...
Author SHA1 Message Date
dcb98132e2 Merge branch 'main' into wt/t_fc02d8b6
All checks were successful
ci / test (pull_request) Successful in 3m2s
2026-09-12 04:11:00 +00:00
4457c7330c Merge pull request 'sanitize peer chat/control/bidi before store and TUI render' (#21) from wt/t_6ddd495e into main
All checks were successful
ci / test (push) Successful in 3m42s
Reviewed-on: #21
2026-09-12 03:59:46 +00:00
0a888eced5 Merge branch 'main' into wt/t_6ddd495e
Some checks failed
ci / test (pull_request) Failing after 2m29s
2026-09-12 03:58:53 +00:00
f9395ee070 Merge pull request 'fix(protocol): domain-separate loc/prf/inv/rcp signatures' (#20) from wt/t_ce5649ac into main
All checks were successful
ci / test (push) Successful in 2m27s
Reviewed-on: #20
2026-09-12 03:53:43 +00:00
Sirius DevOps
818cf5922f
ci: retrigger Pi runner after shared target lock
All checks were successful
ci / test (pull_request) Successful in 2m43s
Previous PR run waited on the cargo build-dir lock then compiled
tests against a stale rlib missing sanitize.
2026-09-11 23:46:54 -04:00
Sirius DevOps
e3738c51f7
[verified] sanitize peer chat/control/bidi before store and TUI render
Some checks failed
ci / test (pull_request) Failing after 2m2s
Strip C0 (except tab/newline), DEL, C1, and bidi/format marks at ingest
and render; keep ZWJ; lossy UTF-8 stays U+FFFD. Reject the same set in
fil names. Docs match the policy.
2026-09-11 23:42:48 -04:00
Sirius DevOps
c8e69732c7
fix(protocol): domain-separate loc/prf/inv/rcp signatures
All checks were successful
ci / test (pull_request) Successful in 2m30s
Sign application frames as tag || 0x00 || fields (onionwire-loc-v1,
onionwire-prf-v1, onionwire-inv-v1, onionwire-rcp-v1). Verify accepts
that form first, then the legacy untagged LF-joined layout. Encode still
emits only the tagged signature; wire prefixes and field layout are
unchanged.

Older builds verify untagged bytes only, so they reject new tagged
signatures (fail closed). Mixed-version fleets break outbound app frames
from a new sender to an old receiver until both sides are updated.
2026-09-11 23:42:41 -04:00
13 changed files with 552 additions and 21 deletions

View file

@ -144,6 +144,20 @@ Chat MUST NOT begin with three lowercase ASCII letters and a space.
Hex on the wire is lowercase on encode; decode accepts either case. No `0x`
prefix.
### Application-frame signatures
`loc`, `prf`, `inv`, and `rcp` each carry an ed25519 signature over the
**fields**, not the 4-byte typed prefix. Encode MUST sign the domain-separated
form (type tag, then each field, `0x00` separators). Verify MUST accept that
form and, for mixed-version peers, the legacy untagged LF-joined layout.
Anything else fails closed. Do not emit the legacy layout.
The invite string is separate and keeps `onionwire-invite-v1` (see Invite).
Older builds verify only the untagged bytes, so they reject tagged signatures
(fail closed, no downgrade). Mixed-version fleets break outbound application
frames from a new sender to an old receiver until both sides are updated.
### `loc ` — locator update
Sent when the sender rotated their onion and the receiver is reachable.
@ -155,7 +169,18 @@ loc <onion>\n<ts>\n<sig_hex>
- `onion` — v3 onion (56 base32 `a-z2-7` chars + `.onion`)
- `ts` — unix seconds, decimal ASCII
- `sig_hex` — 64-byte ed25519, 128 hex chars
- signed bytes: `onion || LF || ascii(ts)` (the `loc ` prefix is **not** signed)
- the `loc ` prefix is **not** signed
**Current signature (encode this):**
```
ed25519_sign(identity_sk,
"onionwire-loc-v1" || 0x00 || onion || 0x00 || ascii(ts))
```
**Legacy accept:** a signature over `onion || LF || ascii(ts)` is still
accepted on verify so old loc frames verify. New loc frames MUST use the
domain-separated form. Do not emit legacy.
Apply only if **all** of:
@ -175,7 +200,18 @@ prf <display_name>\n<bio>\n<xmr_addr>\n<ts>\n<sig_hex>
Limits: name ≤ 64 bytes, bio ≤ 512 bytes. No newlines in those fields.
`xmr_addr` may be empty; if non-empty it MUST be a checksummed Monero address
(see invoices). Signed bytes: the four fields joined by LF (no `prf ` prefix).
(see invoices). The `prf ` prefix is **not** signed.
**Current signature (encode this):**
```
ed25519_sign(identity_sk,
"onionwire-prf-v1" || 0x00 || name || 0x00 || bio || 0x00 || xmr_addr || 0x00 || ascii(ts))
```
**Legacy accept:** a signature over the four fields joined by LF is still
accepted on verify. New profile frames MUST use the domain-separated form.
Do not emit legacy.
Apply only for an existing friend, valid signature, newer `ts`. Not a public
profile. Not a directory.
@ -188,7 +224,18 @@ inv <amount_atomic>\n<address>\n<memo>\n<ts>\n<sig_hex>
`amount_atomic` is decimal piconero (integer string, > 0). `address` is a
Monero mainnet/stagenet standard, subaddress, or integrated address with a
valid Keccak checksum. Signed bytes: the four fields joined by LF.
valid Keccak checksum. The `inv ` prefix is **not** signed.
**Current signature (encode this):**
```
ed25519_sign(identity_sk,
"onionwire-inv-v1" || 0x00 || amount_atomic || 0x00 || address || 0x00 || memo || 0x00 || ascii(ts))
```
**Legacy accept:** a signature over the four fields joined by LF is still
accepted on verify. New invoices MUST use the domain-separated form. Do not
emit legacy.
The frame is a signed claim, not a payment.
@ -198,6 +245,19 @@ The frame is a signed claim, not a payment.
rcp <txid>\n<amount_atomic>\n<address>\n<ts>\n<sig_hex>
```
The `rcp ` prefix is **not** signed.
**Current signature (encode this):**
```
ed25519_sign(identity_sk,
"onionwire-rcp-v1" || 0x00 || txid || 0x00 || amount_atomic || 0x00 || address || 0x00 || ascii(ts))
```
**Legacy accept:** a signature over the four fields joined by LF is still
accepted on verify. New receipts MUST use the domain-separated form. Do not
emit legacy.
Signature proves which friend sent the claim. It does **not** prove money
moved. Local `verified=1` only if a user-hosted `monero-wallet-rpc` returns
one transfer row with the same non-empty `txid`, `amount`, and `address`
@ -221,7 +281,7 @@ fil <xfer_id_hex>\n<filename>\n<sha256_hex>\n<idx>/<total>\n<raw bytes>
```
- `xfer_id` — 16 random bytes (32 hex)
- `filename` — 1–128 bytes, no `/`, NUL, newline, `.`, or `..`
- `filename` — 1–128 bytes, no `/`, NUL, newline, `.`, or `..`; no C0/C1 controls or bidi/format marks (U+202A–U+202E, U+2066–U+2069, U+200E, U+200F, U+200B, U+200C)
- `sha256` — SHA-256 of the **entire** file (64 hex), repeated on every chunk
- `idx` is 0-based; `total` ≥ 1; `idx < total`
- last line is raw chunk bytes (not hex), length chosen so the framed Noise
@ -233,7 +293,13 @@ is a chat line `[file] name (N bytes)`, never the raw frame.
### Chat
UTF-8 (this implementation does not enforce UTF-8). Displayed as a line.
UTF-8 is not enforced for chat text: invalid bytes become U+FFFD (the
implementation does not drop the row). Control and bidi formatting
characters are stripped at ingest and at render: C0 0x00–0x1F except
tab and newline, DEL (0x7F), C1 U+0080–U+009F, U+202A–U+202E,
U+2066–U+2069, U+200E, U+200F, U+200B, U+200C. U+200D (ZWJ) is kept
so emoji sequences stay intact. `fil ` filenames must not contain
those characters (tab and newline included). Displayed as a line.
No length limit beyond the frame cap.
## Invite (out of band)

View file

@ -52,6 +52,17 @@ intentional clearnet socket is optional `monero-wallet-rpc` on **loopback TCP**
Do not add STUN/ICE/WebRTC, a DHT, SOCKS/C-tor fallback, or “direct TCP when
the onion is slow.” Those are the Tox-over-Tor leak class.
## Peer text is untrusted display data
Chat bodies and `fil ` names come from a Noise peer, not from the local user.
They are display data, not terminal commands. A friend (or anyone who stole
that session) can put ESC/CSI/OSC, C1 controls, or bidi overrides in a
payload. OnionWire strips those at ingest (so sqlite history is clean) and
again at TUI render (so rows written before this rule stay inert). Filenames
that contain the same characters are rejected, not rewritten. This is a
UI-redressing / terminal-injection boundary, not a confidentiality control:
the peer already knows the plaintext they sent.
## Out of v1
Prosody, XMPP, s2s, MAM, carbons, outbox, multi-device, DHT / name server,

View file

@ -12,6 +12,7 @@ use rand::RngCore;
use sha2::{Digest, Sha256};
use crate::frame;
use crate::sanitize;
pub type Result<T> = std::result::Result<T, Error>;
@ -79,6 +80,7 @@ pub fn safe_name(name: &str) -> Result<&str> {
|| name.contains('\n')
|| name == ".."
|| name == "."
|| name.chars().any(sanitize::is_control_or_bidi)
{
return Err(Error("bad file name".into()));
}

View file

@ -9,6 +9,7 @@ pub mod pay;
pub mod profile;
pub mod qr;
pub mod ratelimit;
pub mod sanitize;
pub mod session;
mod store;
pub mod tui;

View file

@ -27,7 +27,7 @@ pub fn sign(identity_sk: &[u8], onion: &str, ts: i64) -> Result<Loc> {
.try_into()
.map_err(|_| Error("identity secret key must be 32 bytes".into()))?;
let sk = SigningKey::from_bytes(&sk_bytes);
let sig = sk.sign(&sign_msg(onion, ts)).to_bytes().to_vec();
let sig = sk.sign(&sign_msg_v2(onion, ts)).to_bytes().to_vec();
Ok(Loc {
onion: onion.to_string(),
ts,
@ -50,8 +50,12 @@ pub fn verify(identity_pk: &[u8], loc: &Loc) -> bool {
let Ok(vk) = VerifyingKey::from_bytes(&pk) else {
return false;
};
vk.verify(&sign_msg(&loc.onion, loc.ts), &Signature::from_bytes(&sig))
let signature = Signature::from_bytes(&sig);
vk.verify(&sign_msg_v2(&loc.onion, loc.ts), &signature)
.is_ok()
|| vk
.verify(&sign_msg_v1(&loc.onion, loc.ts), &signature)
.is_ok()
}
pub fn encode(loc: &Loc) -> Vec<u8> {
@ -77,13 +81,29 @@ pub fn decode(pt: &[u8]) -> Option<Loc> {
Some(Loc { onion, ts, sig })
}
fn sign_msg(onion: &str, ts: i64) -> Vec<u8> {
fn sign_msg_v2(onion: &str, ts: i64) -> Vec<u8> {
tagged(
b"onionwire-loc-v1",
&[onion.as_bytes(), ts.to_string().as_bytes()],
)
}
fn sign_msg_v1(onion: &str, ts: i64) -> Vec<u8> {
let mut msg = Vec::from(onion.as_bytes());
msg.push(b'\n');
msg.extend_from_slice(ts.to_string().as_bytes());
msg
}
fn tagged(tag: &[u8], fields: &[&[u8]]) -> Vec<u8> {
let mut msg = Vec::from(tag);
for f in fields {
msg.push(0);
msg.extend_from_slice(f);
}
msg
}
fn to_hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}

View file

@ -18,6 +18,7 @@ use crate::pay;
use crate::profile;
use crate::qr;
use crate::ratelimit::TokenBucket;
use crate::sanitize;
use crate::session::{self, Keys};
use crate::store::{Friend, FriendProfile, Message, PaymentWrite, Store};
use crate::wallet::{self, Wallet};
@ -638,7 +639,11 @@ impl Node {
store
.lock()
.map_err(|e| e.to_string())?
.append_message(&sess.peer_identity, "in", &pt)
.append_message(
&sess.peer_identity,
"in",
sanitize::display_text(&pt).as_bytes(),
)
.map_err(|e| e.to_string())?;
Ok(())
}
@ -673,7 +678,11 @@ impl Node {
self.store
.lock()
.map_err(|e| e.to_string())?
.append_message(peer, "in", file::chat_line(name, nbytes).as_bytes())
.append_message(
peer,
"in",
sanitize::display_text(file::chat_line(name, nbytes).as_bytes()).as_bytes(),
)
.map_err(|e| e.to_string())?;
}
Ok(())

View file

@ -179,7 +179,10 @@ pub fn sign_invoice(
ts: i64,
) -> Result<Invoice> {
check_invoice_fields(amount_atomic, address, memo)?;
let sig = sign_bytes(identity_sk, &inv_sign_msg(amount_atomic, address, memo, ts))?;
let sig = sign_bytes(
identity_sk,
&inv_sign_msg_v2(amount_atomic, address, memo, ts),
)?;
Ok(Invoice {
amount_atomic: amount_atomic.to_string(),
address: address.to_string(),
@ -195,7 +198,11 @@ pub fn verify_invoice(identity_pk: &[u8], inv: &Invoice) -> bool {
}
verify_bytes(
identity_pk,
&inv_sign_msg(&inv.amount_atomic, &inv.address, &inv.memo, inv.ts),
&inv_sign_msg_v2(&inv.amount_atomic, &inv.address, &inv.memo, inv.ts),
&inv.sig,
) || verify_bytes(
identity_pk,
&inv_sign_msg_v1(&inv.amount_atomic, &inv.address, &inv.memo, inv.ts),
&inv.sig,
)
}
@ -243,7 +250,10 @@ pub fn sign_receipt(
ts: i64,
) -> Result<Receipt> {
check_receipt_fields(txid, amount_atomic, address)?;
let sig = sign_bytes(identity_sk, &rcp_sign_msg(txid, amount_atomic, address, ts))?;
let sig = sign_bytes(
identity_sk,
&rcp_sign_msg_v2(txid, amount_atomic, address, ts),
)?;
Ok(Receipt {
txid: txid.to_string(),
amount_atomic: amount_atomic.to_string(),
@ -259,7 +269,11 @@ pub fn verify_receipt(identity_pk: &[u8], rcp: &Receipt) -> bool {
}
verify_bytes(
identity_pk,
&rcp_sign_msg(&rcp.txid, &rcp.amount_atomic, &rcp.address, rcp.ts),
&rcp_sign_msg_v2(&rcp.txid, &rcp.amount_atomic, &rcp.address, rcp.ts),
&rcp.sig,
) || verify_bytes(
identity_pk,
&rcp_sign_msg_v1(&rcp.txid, &rcp.amount_atomic, &rcp.address, rcp.ts),
&rcp.sig,
)
}
@ -316,7 +330,19 @@ fn check_receipt_fields(txid: &str, amount_atomic: &str, address: &str) -> Resul
check_address(address)
}
fn inv_sign_msg(amount_atomic: &str, address: &str, memo: &str, ts: i64) -> Vec<u8> {
fn inv_sign_msg_v2(amount_atomic: &str, address: &str, memo: &str, ts: i64) -> Vec<u8> {
tagged(
b"onionwire-inv-v1",
&[
amount_atomic.as_bytes(),
address.as_bytes(),
memo.as_bytes(),
ts.to_string().as_bytes(),
],
)
}
fn inv_sign_msg_v1(amount_atomic: &str, address: &str, memo: &str, ts: i64) -> Vec<u8> {
let mut msg = Vec::from(amount_atomic.as_bytes());
msg.push(b'\n');
msg.extend_from_slice(address.as_bytes());
@ -327,7 +353,19 @@ fn inv_sign_msg(amount_atomic: &str, address: &str, memo: &str, ts: i64) -> Vec<
msg
}
fn rcp_sign_msg(txid: &str, amount_atomic: &str, address: &str, ts: i64) -> Vec<u8> {
fn rcp_sign_msg_v2(txid: &str, amount_atomic: &str, address: &str, ts: i64) -> Vec<u8> {
tagged(
b"onionwire-rcp-v1",
&[
txid.as_bytes(),
amount_atomic.as_bytes(),
address.as_bytes(),
ts.to_string().as_bytes(),
],
)
}
fn rcp_sign_msg_v1(txid: &str, amount_atomic: &str, address: &str, ts: i64) -> Vec<u8> {
let mut msg = Vec::from(txid.as_bytes());
msg.push(b'\n');
msg.extend_from_slice(amount_atomic.as_bytes());
@ -338,6 +376,15 @@ fn rcp_sign_msg(txid: &str, amount_atomic: &str, address: &str, ts: i64) -> Vec<
msg
}
fn tagged(tag: &[u8], fields: &[&[u8]]) -> Vec<u8> {
let mut msg = Vec::from(tag);
for f in fields {
msg.push(0);
msg.extend_from_slice(f);
}
msg
}
fn sign_bytes(identity_sk: &[u8], msg: &[u8]) -> Result<Vec<u8>> {
let sk_bytes: [u8; 32] = identity_sk
.try_into()

View file

@ -43,7 +43,7 @@ pub fn sign(
.map_err(|_| Error("identity secret key must be 32 bytes".into()))?;
let sk = SigningKey::from_bytes(&sk_bytes);
let sig = sk
.sign(&sign_msg(display_name, bio, xmr_addr, ts))
.sign(&sign_msg_v2(display_name, bio, xmr_addr, ts))
.to_bytes()
.to_vec();
Ok(Profile {
@ -73,11 +73,18 @@ pub fn verify(identity_pk: &[u8], prf: &Profile) -> bool {
let Ok(vk) = VerifyingKey::from_bytes(&pk) else {
return false;
};
let signature = Signature::from_bytes(&sig);
vk.verify(
&sign_msg(&prf.display_name, &prf.bio, &prf.xmr_addr, prf.ts),
&Signature::from_bytes(&sig),
&sign_msg_v2(&prf.display_name, &prf.bio, &prf.xmr_addr, prf.ts),
&signature,
)
.is_ok()
|| vk
.verify(
&sign_msg_v1(&prf.display_name, &prf.bio, &prf.xmr_addr, prf.ts),
&signature,
)
.is_ok()
}
pub fn encode(prf: &Profile) -> Vec<u8> {
@ -131,7 +138,19 @@ fn check_fields(display_name: &str, bio: &str, xmr_addr: &str) -> Result<()> {
Ok(())
}
fn sign_msg(display_name: &str, bio: &str, xmr_addr: &str, ts: i64) -> Vec<u8> {
fn sign_msg_v2(display_name: &str, bio: &str, xmr_addr: &str, ts: i64) -> Vec<u8> {
tagged(
b"onionwire-prf-v1",
&[
display_name.as_bytes(),
bio.as_bytes(),
xmr_addr.as_bytes(),
ts.to_string().as_bytes(),
],
)
}
fn sign_msg_v1(display_name: &str, bio: &str, xmr_addr: &str, ts: i64) -> Vec<u8> {
let mut msg = Vec::from(display_name.as_bytes());
msg.push(b'\n');
msg.extend_from_slice(bio.as_bytes());
@ -142,6 +161,15 @@ fn sign_msg(display_name: &str, bio: &str, xmr_addr: &str, ts: i64) -> Vec<u8> {
msg
}
fn tagged(tag: &[u8], fields: &[&[u8]]) -> Vec<u8> {
let mut msg = Vec::from(tag);
for f in fields {
msg.push(0);
msg.extend_from_slice(f);
}
msg
}
fn to_hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}

44
src/sanitize.rs Normal file
View file

@ -0,0 +1,44 @@
//! Strip terminal/UI-injection characters from untrusted peer text.
//!
//! Chat is not required to be valid UTF-8 (invalid bytes become U+FFFD).
//! After lossy decode, these code points are removed:
//! - C0 0x00–0x1F except `\t` and `\n`, plus DEL (0x7F)
//! - C1 U+0080–U+009F
//! - bidi/format: U+202A–U+202E, U+2066–U+2069, U+200E, U+200F
//! - zero-width: U+200B (ZWSP), U+200C (ZWNJ)
//!
//! U+200D (ZWJ) is kept so emoji ZWJ sequences stay intact.
use std::borrow::Cow;
pub fn display_text(bytes: &[u8]) -> Cow<'_, str> {
match std::str::from_utf8(bytes) {
Ok(s) if !s.chars().any(is_stripped) => Cow::Borrowed(s),
Ok(s) => Cow::Owned(filter_stripped(s)),
Err(_) => Cow::Owned(filter_stripped(&String::from_utf8_lossy(bytes))),
}
}
/// True for C0/C1 controls and bidi/format marks (including `\t`/`\n`).
pub fn is_control_or_bidi(c: char) -> bool {
matches!(
c,
'\0'..='\u{1f}'
| '\u{7f}'
| '\u{80}'..='\u{9f}'
| '\u{202a}'..='\u{202e}'
| '\u{2066}'..='\u{2069}'
| '\u{200e}'
| '\u{200f}'
| '\u{200b}'
| '\u{200c}'
)
}
fn is_stripped(c: char) -> bool {
c != '\t' && c != '\n' && is_control_or_bidi(c)
}
fn filter_stripped(s: &str) -> String {
s.chars().filter(|c| !is_stripped(*c)).collect()
}

View file

@ -10,6 +10,7 @@ use ratatui::{DefaultTerminal, Frame};
use crate::node::Node;
use crate::qr::{self, QrPayload};
use crate::sanitize;
use crate::store::{Friend, FriendProfile};
const C_ACCENT: Color = Color::Rgb(232, 165, 75);
@ -1458,7 +1459,7 @@ impl App {
.iter()
.map(|m| {
let side = if m.dir == "out" { "you" } else { "them" };
format!("{side}: {}", String::from_utf8_lossy(&m.plaintext))
format!("{side}: {}", sanitize::display_text(&m.plaintext))
})
.collect(),
Err(e) => vec![e],

200
tests/app_sig.rs Normal file
View file

@ -0,0 +1,200 @@
//! Domain-separated application-frame signatures (loc/prf/inv/rcp).
//!
//! Encode still emits typed prefixes and LF-joined fields. Only the signed
//! bytes change: tagged `0x00`-separated form on emit, dual-accept of the
//! legacy untagged LF layout on verify.
use ed25519_dalek::{Signer, SigningKey};
use onionwire::loc::{self, Loc};
use onionwire::pay::{self, Invoice, Receipt};
use onionwire::profile::{self, Profile};
use rand::rngs::OsRng;
const MAINNET_STD: &str = "4AdUndXHHZ6cfufTMvppY6JwXNouMBzSkbLYfpAV5Usx3skxNgYeYTRj5UzqtReoS44qo9mtmXCqY45DJ852K5Jv2684Rge";
fn keypair() -> (SigningKey, [u8; 32]) {
let sk = SigningKey::generate(&mut OsRng);
let pk = sk.verifying_key().to_bytes();
(sk, pk)
}
#[test]
fn tagged_loc_roundtrip() {
let (sk, pk) = keypair();
let loc = loc::sign(&sk.to_bytes(), "abc.onion", 42).unwrap();
let parsed = loc::decode(&loc::encode(&loc)).expect("loc frame");
assert!(loc::verify(&pk, &parsed));
assert_eq!(parsed.onion, "abc.onion");
assert_eq!(parsed.ts, 42);
}
#[test]
fn tagged_prf_roundtrip() {
let (sk, pk) = keypair();
let prf = profile::sign(&sk.to_bytes(), "Ali", "hi", "", 2_000_000_000).unwrap();
let parsed = profile::decode(&profile::encode(&prf)).expect("prf frame");
assert!(profile::verify(&pk, &parsed));
assert_eq!(parsed.display_name, "Ali");
assert_eq!(parsed.bio, "hi");
assert_eq!(parsed.xmr_addr, "");
assert_eq!(parsed.ts, 2_000_000_000);
}
#[test]
fn tagged_inv_roundtrip() {
let (sk, pk) = keypair();
let inv = pay::sign_invoice(&sk.to_bytes(), "120000000000", MAINNET_STD, "coffee", 42).unwrap();
let parsed = pay::decode_invoice(&pay::encode_invoice(&inv)).expect("inv frame");
assert!(pay::verify_invoice(&pk, &parsed));
assert_eq!(parsed.amount_atomic, "120000000000");
assert_eq!(parsed.address, MAINNET_STD);
assert_eq!(parsed.memo, "coffee");
assert_eq!(parsed.ts, 42);
}
#[test]
fn tagged_rcp_roundtrip() {
let (sk, pk) = keypair();
let rcp = pay::sign_receipt(&sk.to_bytes(), "deadbeef", "1", MAINNET_STD, 99).unwrap();
let parsed = pay::decode_receipt(&pay::encode_receipt(&rcp)).expect("rcp frame");
assert!(pay::verify_receipt(&pk, &parsed));
assert_eq!(parsed.txid, "deadbeef");
assert_eq!(parsed.amount_atomic, "1");
assert_eq!(parsed.address, MAINNET_STD);
assert_eq!(parsed.ts, 99);
}
#[test]
fn legacy_untagged_loc_still_verifies() {
let (sk, pk) = keypair();
let onion = "abc.onion";
let ts = 42i64;
let mut msg = Vec::from(onion.as_bytes());
msg.push(b'\n');
msg.extend_from_slice(ts.to_string().as_bytes());
let loc = Loc {
onion: onion.into(),
ts,
sig: sk.sign(&msg).to_bytes().to_vec(),
};
assert!(
loc::verify(&pk, &loc),
"legacy loc LF layout must still verify"
);
}
#[test]
fn legacy_untagged_prf_still_verifies() {
let (sk, pk) = keypair();
let ts = 2_000_000_000i64;
let mut msg = Vec::from(b"Ali".as_slice());
msg.push(b'\n');
msg.extend_from_slice(b"hi");
msg.push(b'\n');
msg.extend_from_slice(b"");
msg.push(b'\n');
msg.extend_from_slice(ts.to_string().as_bytes());
let prf = Profile {
display_name: "Ali".into(),
bio: "hi".into(),
xmr_addr: String::new(),
ts,
sig: sk.sign(&msg).to_bytes().to_vec(),
};
assert!(
profile::verify(&pk, &prf),
"legacy prf LF layout must still verify"
);
}
#[test]
fn legacy_untagged_inv_still_verifies() {
let (sk, pk) = keypair();
let ts = 42i64;
let mut msg = Vec::from(b"1".as_slice());
msg.push(b'\n');
msg.extend_from_slice(MAINNET_STD.as_bytes());
msg.push(b'\n');
msg.extend_from_slice(b"coffee");
msg.push(b'\n');
msg.extend_from_slice(ts.to_string().as_bytes());
let inv = Invoice {
amount_atomic: "1".into(),
address: MAINNET_STD.into(),
memo: "coffee".into(),
ts,
sig: sk.sign(&msg).to_bytes().to_vec(),
};
assert!(
pay::verify_invoice(&pk, &inv),
"legacy inv LF layout must still verify"
);
}
#[test]
fn legacy_untagged_rcp_still_verifies() {
let (sk, pk) = keypair();
let ts = 99i64;
let mut msg = Vec::from(b"deadbeef".as_slice());
msg.push(b'\n');
msg.extend_from_slice(b"1");
msg.push(b'\n');
msg.extend_from_slice(MAINNET_STD.as_bytes());
msg.push(b'\n');
msg.extend_from_slice(ts.to_string().as_bytes());
let rcp = Receipt {
txid: "deadbeef".into(),
amount_atomic: "1".into(),
address: MAINNET_STD.into(),
ts,
sig: sk.sign(&msg).to_bytes().to_vec(),
};
assert!(
pay::verify_receipt(&pk, &rcp),
"legacy rcp LF layout must still verify"
);
}
/// prf and rcp both sign four fields. Without a type tag, a profile whose
/// fields are also a valid receipt (name=txid, bio=amount, xmr=address)
/// verifies as a receipt under the same key.
#[test]
fn prf_signature_does_not_verify_as_rcp() {
let (sk, pk) = keypair();
let ts = 42i64;
let prf = profile::sign(&sk.to_bytes(), "deadbeef", "1", MAINNET_STD, ts).unwrap();
assert!(profile::verify(&pk, &prf));
let rcp = Receipt {
txid: "deadbeef".into(),
amount_atomic: "1".into(),
address: MAINNET_STD.into(),
ts,
sig: prf.sig.clone(),
};
assert!(
!pay::verify_receipt(&pk, &rcp),
"prf-shaped payload must not verify as rcp"
);
}
/// inv field order is amount/address/memo/ts; rcp is txid/amount/address/ts.
/// Reinterpret the invoice fields in order as a receipt and the signature
/// must not verify (and field checks fail closed on a non-decimal amount).
#[test]
fn inv_signature_does_not_verify_as_rcp() {
let (sk, pk) = keypair();
let ts = 42i64;
let inv = pay::sign_invoice(&sk.to_bytes(), "1", MAINNET_STD, MAINNET_STD, ts).unwrap();
assert!(pay::verify_invoice(&pk, &inv));
let rcp = Receipt {
txid: "1".into(),
amount_atomic: MAINNET_STD.into(),
address: MAINNET_STD.into(),
ts,
sig: inv.sig.clone(),
};
assert!(
!pay::verify_receipt(&pk, &rcp),
"inv-shaped payload must not verify as rcp"
);
}

View file

@ -37,6 +37,15 @@ fn name_with_dotdot_or_slash_rejected() {
assert!(file::safe_name("ok.txt").is_ok());
}
#[test]
fn name_with_bidi_or_controls_rejected() {
assert!(file::safe_name("ok.txt").is_ok());
assert!(file::safe_name("safe.txt\u{202e}gpj.exe").is_err());
assert!(file::safe_name("a\u{1b}b.txt").is_err());
assert!(file::safe_name("a\u{009b}b.txt").is_err());
assert!(file::safe_name("a\tb.txt").is_err());
}
#[test]
fn oversize_rejected_before_send() {
let too_big = vec![0u8; MAX_BYTES + 1];

93
tests/sanitize.rs Normal file
View file

@ -0,0 +1,93 @@
//! Peer-supplied chat text is untrusted display data.
//! Controls and bidi formatting must not reach the store or the terminal.
use onionwire::Store;
use onionwire::sanitize::display_text;
#[test]
fn csi_sequence_is_stripped() {
let raw = b"hello \x1b[31mred\x1b[0m world";
let out = display_text(raw);
assert!(
!out.as_bytes().contains(&0x1b),
"ESC must not survive: {out:?}"
);
assert_eq!(&*out, "hello [31mred[0m world");
}
#[test]
fn osc_sequence_is_stripped() {
let raw = b"hi \x1b]0;pwned\x07 there";
let out = display_text(raw);
assert!(!out.as_bytes().contains(&0x1b));
assert!(out.contains("hi"));
assert!(out.contains("there"));
}
#[test]
fn bidi_override_is_stripped() {
let raw = "safe.txt\u{202e}gpj.exe".as_bytes();
let out = display_text(raw);
assert!(!out.contains('\u{202e}'));
assert_eq!(&*out, "safe.txtgpj.exe");
}
#[test]
fn c0_removed_except_newline_and_tab() {
let raw = b"a\x00b\x07c\td\ne\x7ff";
let out = display_text(raw);
assert_eq!(&*out, "abc\td\nef");
}
#[test]
fn c1_controls_stripped() {
let s = format!("x{}y", '\u{009b}'); // CSI in C1
let out = display_text(s.as_bytes());
assert_eq!(&*out, "xy");
}
#[test]
fn ordinary_unicode_untouched() {
let raw = "café 日本語 😀 👨‍👩‍👧‍👦".as_bytes();
let out = display_text(raw);
assert_eq!(&*out, "café 日本語 😀 👨‍👩‍👧‍👦");
}
#[test]
fn invalid_utf8_becomes_fffd_not_dropped() {
let raw = b"ok\xffmore";
let out = display_text(raw);
assert!(out.contains('\u{fffd}'));
assert!(out.starts_with("ok"));
assert!(out.ends_with("more"));
}
#[test]
fn isolate_and_marks_stripped() {
let raw = "a\u{2066}b\u{2069}c\u{200e}d\u{200f}e\u{200b}f".as_bytes();
let out = display_text(raw);
assert_eq!(&*out, "abcdef");
}
#[test]
fn chat_csi_stored_and_rendered_without_esc() {
let dir = tempfile::tempdir().unwrap();
let store = Store::open_at_with_passphrase(dir.path(), "sanitize-test").unwrap();
let mut pk = [0u8; 32];
pk[0] = 1;
store.upsert_friend(&pk, "b.onion", None).unwrap();
let wire = b"hi \x1b[2J\x1b[H wipe";
let stored = display_text(wire);
store.append_message(&pk, "in", stored.as_bytes()).unwrap();
let msgs = store.list_messages(&pk).unwrap();
assert_eq!(msgs.len(), 1);
assert!(
!msgs[0].plaintext.contains(&0x1b),
"stored history must not keep ESC"
);
let rendered = format!("them: {}", display_text(&msgs[0].plaintext));
assert!(!rendered.as_bytes().contains(&0x1b));
assert!(rendered.contains("hi"));
assert!(rendered.contains("wipe"));
}