From f1db53bd251a6cdd362871a2b545b92d4eabd6c3 Mon Sep 17 00:00:00 2001 From: Carlos Santos Date: Mon, 28 Sep 2026 14:09:48 -0300 Subject: [PATCH] Encode literal + and match keys case-insensitively Two independent BIP21 round-trip bugs, both reachable from a wallet scanning an ordinary QR code and both silent (no parse error, no indication anything was lost): - Serializing a decoded value that contains a literal '+' wrote it back out unescaped. RFC 3986 permits that, but many BIP21 readers apply the application/x-www-form-urlencoded convention where '+' means space, so a re-emitted URI could hand such a reader a space where the sender wrote a plus. Always percent-encode '+' as %2B on output; this crate never decodes it as a space either way, so nothing about parsing changes. - Top-level keys (amount, label, message) and the req- prefix check were matched against the parameter key verbatim. QR codes in alphanumeric mode are uppercase-only, so a wallet scanning '?AMOUNT=1&PJ=...' got a URI that parsed successfully with amount, and every extras parameter, silently dropped. Match case- insensitively instead, and hand the lowercased key to Extras deserialization so an implementation matching a literal lowercase key (payjoin's PayjoinExtras, for example) needs no change of its own to see it. The zero-copy deserialize_borrowed path is kept for the common already-lowercase case; only a key containing an uppercase byte pays for the clone that deserialize_temp needs. Both are covered by new tests, and neither changes on-the-wire behavior for lowercase input. --- src/de.rs | 36 ++++++++++++++++--- src/lib.rs | 104 ++++++++++++++++++++++++++++++++++++++++++++++++++++- src/ser.rs | 11 ++++-- 3 files changed, 143 insertions(+), 8 deletions(-) diff --git a/src/de.rs b/src/de.rs index 9a44b77..16ec139 100644 --- a/src/de.rs +++ b/src/de.rs @@ -58,7 +58,26 @@ impl<'a, T: DeserializeParams<'a>> Uri<'a, bitcoin::address::NetworkUnchecked, T .ok_or_else(|| Error::Uri(UriError(UriErrorInner::MissingEquals(param.to_owned()))))?; let key = ¶m[..pos]; let value = ¶m[(pos + 1)..]; - match key { + // BIP 21 / BIP 321 keys are case-insensitive. QR codes in + // alphanumeric mode are uppercase-only, so wallets do scan + // URIs shaped like `?AMOUNT=1&PJ=...`; matching `key` + // verbatim silently drops every parameter in that shape + // instead of erroring. Extras get the lowercased key too, so + // an `Extras` impl matching "pj"/"pjos" literally does not + // need its own case handling to see "PJ"/"PJOS". + // + // The common case is already-lowercase input, so only + // allocate when `key` actually contains an uppercase ASCII + // byte; that keeps the zero-copy `deserialize_borrowed` path + // for the common case instead of always paying for a clone + // via `deserialize_temp`. + let lower_key = if key.bytes().any(|b| b.is_ascii_uppercase()) { + Some(key.to_ascii_lowercase()) + } else { + None + }; + let matched_key = lower_key.as_deref().unwrap_or(key); + match matched_key { "amount" => { if amount.is_some() { return Err(Error::Uri(UriError(UriErrorInner::DuplicateParameter(key.to_owned())))); @@ -80,11 +99,18 @@ impl<'a, T: DeserializeParams<'a>> Uri<'a, bitcoin::address::NetworkUnchecked, T let message_decoder = Param::decode(value).map_err(Error::percent_decode_static("message"))?; message = Some(message_decoder); }, - extra_key => { + _ => { let decoder = Param::decode(value).map_err(Error::percent_decode(key))?; - let is_known = deserializer.deserialize_borrowed(extra_key, decoder).map_err(Error::Extras)?; - if is_known == ParamKind::Unknown && extra_key.starts_with("req-") { - return Err(Error::Uri(UriError(UriErrorInner::UnknownRequiredParameter(extra_key.to_owned())))); + let is_known = match &lower_key { + // Not borrowed from the source string, so this + // must go through `deserialize_temp` rather than + // `deserialize_borrowed` (which requires a `key` + // borrowed for `'de`). + Some(lower_key) => deserializer.deserialize_temp(lower_key, decoder).map_err(Error::Extras)?, + None => deserializer.deserialize_borrowed(key, decoder).map_err(Error::Extras)?, + }; + if is_known == ParamKind::Unknown && matched_key.starts_with("req-") { + return Err(Error::Uri(UriError(UriErrorInner::UnknownRequiredParameter(key.to_owned())))); } }, } diff --git a/src/lib.rs b/src/lib.rs index 7a37b7e..458bb07 100755 --- a/src/lib.rs +++ b/src/lib.rs @@ -345,7 +345,8 @@ impl SerializeParams for &NoExtras { #[cfg(test)] mod tests { - use crate::Uri; + use crate::{de, Param, Uri}; + use crate::de::{DeserializationError, DeserializationState, DeserializeParams}; use alloc::string::ToString; use alloc::borrow::Cow; use core::convert::TryInto; @@ -503,4 +504,105 @@ mod tests { let uri = duplicate_message.parse::>(); assert!(uri.is_err()); } + + #[test] + fn a_literal_plus_round_trips_as_percent_2b() { + // `a%2Bb` decodes to the literal string "a+b" (RFC 3986: '+' is not + // special). Re-serializing must escape that '+' back to `%2B`, or a + // reader that treats '+' as a space (the application/x-www-form- + // urlencoded convention, which many BIP21 wallets mistakenly apply) + // will see "a b" instead. + let input = "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?label=a%2Bb"; + let uri = input.parse::>().unwrap().require_network(bitcoin::Network::Bitcoin).unwrap(); + let label: alloc::borrow::Cow<'_, str> = uri.label.clone().unwrap().try_into().unwrap(); + assert_eq!(label, "a+b"); + assert_eq!(uri.to_string(), input); + } + + #[test] + fn a_bare_plus_in_input_is_never_treated_as_a_space() { + // A literal, unencoded '+' in the input must decode to '+', never to + // a space, and must round-trip as `%2B` per the previous test. + let input = "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?label=a+b"; + let uri = input.parse::>().unwrap().require_network(bitcoin::Network::Bitcoin).unwrap(); + let label: alloc::borrow::Cow<'_, str> = uri.label.clone().unwrap().try_into().unwrap(); + assert_eq!(label, "a+b"); + assert_eq!(uri.to_string(), "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?label=a%2Bb"); + } + + /// A minimal `Extras` that only knows the lowercase key `pj`, the same + /// way a real extension (such as payjoin's `PayjoinExtras`) matches its + /// own parameter names. It exists to prove that case-insensitive + /// matching for known top-level keys and `req-` does not require any + /// change on the `Extras` implementor's side: `bitcoin_uri` already + /// normalizes the key it hands to `deserialize_temp`/`deserialize_borrowed`. + #[derive(Debug, Default, Clone)] + struct PjLike { + pj: Option, + } + + impl DeserializationError for PjLike { + type Error = core::convert::Infallible; + } + + impl DeserializeParams<'_> for PjLike { + type DeserializationState = PjLikeState; + } + + #[derive(Debug, Default, Clone)] + struct PjLikeState { + pj: Option, + } + + impl DeserializationState<'_> for PjLikeState { + type Value = PjLike; + + fn is_param_known(&self, key: &str) -> bool { + key == "pj" + } + + fn deserialize_temp(&mut self, key: &str, value: Param<'_>) -> Result { + if key == "pj" { + let value: alloc::string::String = value.try_into().unwrap(); + self.pj = Some(value); + Ok(de::ParamKind::Known) + } else { + Ok(de::ParamKind::Unknown) + } + } + + fn finalize(self) -> Result { + Ok(PjLike { pj: self.pj }) + } + } + + #[test] + fn an_uppercase_known_extra_param_is_still_recognized() { + // A QR code in alphanumeric mode is uppercase-only, so wallets do + // scan URIs shaped like this. Before the fix, `PJ` did not match the + // lowercase-only `PjLike` extras and was silently dropped, with no + // error and no indication the payjoin parameter was ever there. + // + // Bech32 (BIP 173) is defined to accept an address in all-uppercase + // form; legacy base58 addresses are not (base58 is case-sensitive, + // so uppercasing one breaks its checksum), which is why this uses a + // bech32 address rather than the base58 one the other tests share. + let input = "BITCOIN:BC1QW508D6QEJXTDG4Y5R3ZARVARY0C5XW7KV8F3T4?PJ=HTTPS://EXAMPLE.COM"; + let uri = input + .parse::>() + .unwrap() + .require_network(bitcoin::Network::Bitcoin) + .unwrap(); + assert_eq!(uri.extras.pj.as_deref(), Some("HTTPS://EXAMPLE.COM")); + } + + #[test] + fn an_uppercase_unclaimed_req_key_is_still_rejected() { + // Lowercase `req-` is already rejected by `required_not_understood` + // above; this is the same guarantee for the uppercase shape a QR + // code in alphanumeric mode produces. + let input = "bitcoin:1andreas3batLhQa2FawWjeyjCqyBzypd?REQ-SOMETHINGYOUDONTUNDERSTAND=50"; + let uri = input.parse::>(); + assert!(uri.is_err()); + } } diff --git a/src/ser.rs b/src/ser.rs index 9451097..6594d98 100644 --- a/src/ser.rs +++ b/src/ser.rs @@ -79,6 +79,9 @@ impl fmt::Write for EqSignChecker<'_, W> { /// > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" /// > / "*" / "+" / "," / ";" / "=" /// > ``` +/// +/// `+` is a `sub-delim` and would be legal unescaped, but is percent-encoded +/// here anyway: see the comment on `.remove(b'+')`'s absence below. const ASCII_SET: percent_encoding_rfc3986::AsciiSet = percent_encoding_rfc3986::NON_ALPHANUMERIC // allow non-alphanumeric characters from `unreserved` .remove(b'-') @@ -86,14 +89,18 @@ const ASCII_SET: percent_encoding_rfc3986::AsciiSet = percent_encoding_rfc3986:: .remove(b'_') .remove(b'~') // allow non-alphanumeric characters from `sub-delims` excluding bip-21 - // separators ("&", and "=") + // separators ("&", and "=") and excluding '+': RFC 3986 permits a + // literal '+' unescaped in a query, but many BIP21 readers apply the + // application/x-www-form-urlencoded convention where '+' decodes to a + // space. Always percent-encoding '+' as %2B keeps re-emitted URIs safe + // for those readers even though this crate itself never does that + // decoding. .remove(b'!') .remove(b'$') .remove(b'\'') .remove(b'(') .remove(b')') .remove(b'*') - .remove(b'+') .remove(b',') .remove(b';') // allow pchar extra chars