lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

terms_decode.rs (12357B)


      1 #![cfg(feature = "terms")]
      2 use radroots_protocol::terms::{EncodedTerms, TermsWireError, decode};
      3 use serde_json::{Value, json};
      4 
      5 fn fixtures() -> Value {
      6     serde_json::from_str(include_str!("fixtures/terms_wire.v1.json")).unwrap()
      7 }
      8 
      9 #[test]
     10 fn profile_keys_require_the_approved_lowercase_spelling() {
     11     let original = example(0);
     12     let mut accepted = Vec::new();
     13     for path in [
     14         "/buyer",
     15         "/seller",
     16         "/lines/0/source/coordinate/author",
     17         "/lines/0/product/producer",
     18     ] {
     19         let mut altered = original.clone();
     20         let key = altered
     21             .pointer(path)
     22             .unwrap()
     23             .as_str()
     24             .unwrap()
     25             .to_ascii_uppercase();
     26         *altered.pointer_mut(path).unwrap() = json!(key);
     27         if decode(&bytes(&altered)).is_ok() {
     28             accepted.push(path);
     29         }
     30     }
     31     assert!(
     32         accepted.is_empty(),
     33         "noncanonical profile keys accepted: {accepted:?}"
     34     );
     35 }
     36 
     37 #[test]
     38 fn empty_tagged_snapshot_alternatives_reject_extra_fields() {
     39     let original = example(2);
     40     let mut accepted = Vec::new();
     41     for path in [
     42         "/lines/0/option/price",
     43         "/lines/0/option/supply",
     44         "/lines/0/option/unit/contents",
     45     ] {
     46         let mut value = original.clone();
     47         value
     48             .pointer_mut(path)
     49             .unwrap()
     50             .as_object_mut()
     51             .unwrap()
     52             .insert("unexpected".into(), Value::Null);
     53         if decode(&bytes(&value)).is_ok() {
     54             accepted.push(path);
     55         }
     56     }
     57     assert!(
     58         accepted.is_empty(),
     59         "unknown fields accepted by empty tagged alternatives: {accepted:?}"
     60     );
     61 }
     62 fn example(index: usize) -> Value {
     63     serde_json::from_str(fixtures()["vectors"][index]["wire"].as_str().unwrap()).unwrap()
     64 }
     65 fn bytes(value: &Value) -> Vec<u8> {
     66     serde_json::to_vec(value).unwrap()
     67 }
     68 
     69 #[test]
     70 fn independently_authored_complete_terms_decode_and_reencode_without_changed_bytes_or_digests() {
     71     for vector in fixtures()["vectors"].as_array().unwrap() {
     72         let wire = vector["wire"].as_str().unwrap();
     73         let terms = decode(wire.as_bytes()).unwrap();
     74         let encoded = EncodedTerms::capture(&terms).unwrap();
     75         assert_eq!(encoded.protected_wire(), wire.as_bytes());
     76         assert_eq!(
     77             encoded.digest().to_string(),
     78             vector["terms_digest"].as_str().unwrap()
     79         );
     80         let pretty =
     81             serde_json::to_string_pretty(&serde_json::from_str::<Value>(wire).unwrap()).unwrap();
     82         if pretty.len() <= 16_384 {
     83             assert_eq!(
     84                 EncodedTerms::capture(&decode(pretty.as_bytes()).unwrap())
     85                     .unwrap()
     86                     .digest(),
     87                 encoded.digest()
     88             );
     89         }
     90     }
     91 }
     92 
     93 #[test]
     94 fn every_terms_object_boundary_is_closed_required_and_object_only() {
     95     for (index, paths) in [
     96         (
     97             0,
     98             vec![
     99                 "",
    100                 "/lines/0",
    101                 "/lines/0/source",
    102                 "/lines/0/source/coordinate",
    103                 "/lines/0/product",
    104                 "/lines/0/option",
    105                 "/lines/0/option/unit",
    106                 "/lines/0/option/unit/contents",
    107                 "/lines/0/option/unit/contents/quantity",
    108                 "/lines/0/option/price",
    109                 "/lines/0/option/price/rate",
    110                 "/lines/0/option/price/tiers/0",
    111                 "/lines/0/option/price/tiers/0/rate",
    112                 "/lines/0/option/supply",
    113                 "/lines/0/option/supply/window",
    114                 "/lines/0/price",
    115                 "/lines/0/price/rate",
    116                 "/lines/0/maximum_line_total",
    117                 "/fulfillment/0",
    118                 "/fulfillment/0/terms",
    119                 "/fulfillment/0/terms/window",
    120                 "/fulfillment_charge",
    121                 "/maximum_total",
    122                 "/supply",
    123             ],
    124         ),
    125         (
    126             1,
    127             vec![
    128                 "/lines/0/option/price",
    129                 "/lines/0/option/price/rate",
    130                 "/lines/0/option/price/maximum_per_sale_unit_total",
    131                 "/lines/0/price",
    132                 "/lines/0/price/rate",
    133                 "/lines/0/price/maximum_total",
    134                 "/supply",
    135                 "/supply/expected_window",
    136             ],
    137         ),
    138     ] {
    139         let original = example(index);
    140         for path in paths {
    141             let fields = original.pointer(path).unwrap().as_object().unwrap();
    142             let mut positional = original.clone();
    143             *positional.pointer_mut(path).unwrap() =
    144                 Value::Array(fields.values().cloned().collect());
    145             assert!(
    146                 decode(&bytes(&positional)).is_err(),
    147                 "positional {index}:{path}"
    148             );
    149             let mut extra = original.clone();
    150             extra
    151                 .pointer_mut(path)
    152                 .unwrap()
    153                 .as_object_mut()
    154                 .unwrap()
    155                 .insert("unexpected".into(), json!(null));
    156             assert!(decode(&bytes(&extra)).is_err(), "unknown {index}:{path}");
    157             for key in fields.keys() {
    158                 let mut missing = original.clone();
    159                 missing
    160                     .pointer_mut(path)
    161                     .unwrap()
    162                     .as_object_mut()
    163                     .unwrap()
    164                     .remove(key);
    165                 assert!(
    166                     decode(&bytes(&missing)).is_err(),
    167                     "missing {index}:{path}/{key}"
    168                 );
    169                 // Duplicate the field in its exact object before inserting it
    170                 // into the surrounding fixture; no Value parser may erase it.
    171                 let object = if path.is_empty() {
    172                     serde_json::to_string(&original).unwrap()
    173                 } else {
    174                     serde_json::to_string(original.pointer(path).unwrap()).unwrap()
    175                 };
    176                 let duplicate = format!(
    177                     "{{{}:{},{}",
    178                     serde_json::to_string(key).unwrap(),
    179                     serde_json::to_string(&fields[key]).unwrap(),
    180                     &object[1..]
    181                 );
    182                 let mut template = original.clone();
    183                 *template.pointer_mut(path).unwrap() = json!("__TERMS_NEGATIVE_TARGET__");
    184                 let altered = serde_json::to_string(&template)
    185                     .unwrap()
    186                     .replace("\"__TERMS_NEGATIVE_TARGET__\"", &duplicate);
    187                 assert!(
    188                     decode(altered.as_bytes()).is_err(),
    189                     "duplicate {index}:{path}/{key}"
    190                 );
    191             }
    192         }
    193     }
    194 }
    195 
    196 #[test]
    197 fn private_text_decodes_escaped_unicode_without_normalizing_it_or_omitting_explicit_nulls() {
    198     let original = example(0);
    199     let wire = serde_json::to_string(&original).unwrap();
    200     let escaped = wire.replace("🥬", r"\uD83E\uDD6C").replace("Å", r"\u00c5");
    201     assert_ne!(wire, escaped);
    202     assert_eq!(
    203         EncodedTerms::capture(&decode(wire.as_bytes()).unwrap())
    204             .unwrap()
    205             .digest(),
    206         EncodedTerms::capture(&decode(escaped.as_bytes()).unwrap())
    207             .unwrap()
    208             .digest()
    209     );
    210     for (path, value) in [
    211         ("/fulfillment/0/terms/address", json!(true)),
    212         ("/fulfillment/0/terms/contact", json!(12)),
    213         ("/lines/0/source_lot_label", json!(false)),
    214         ("/fulfillment/0/terms/instructions", json!("a".repeat(2049))),
    215     ] {
    216         let mut invalid = original.clone();
    217         *invalid.pointer_mut(path).unwrap() = value;
    218         assert!(decode(&bytes(&invalid)).is_err(), "{path}");
    219     }
    220 }
    221 
    222 #[test]
    223 fn domain_invariants_and_unsupported_profiles_never_become_silent_fallbacks() {
    224     let original = example(0);
    225     for (path, value) in [
    226         ("/buyer", original["seller"].clone()),
    227         ("/lines/0/amount", json!("0")),
    228         ("/lines/0/option_id", json!("00".repeat(32))),
    229         ("/lines/0/source/coordinate/kind", json!(95938)),
    230         (
    231             "/lines/0/source/coordinate/author",
    232             original["buyer"].clone(),
    233         ),
    234         ("/lines/0/price/discount_bps", json!(10001)),
    235         ("/lines/0/maximum_line_total/minor", json!("438")),
    236         ("/maximum_total/minor", json!("465")),
    237         ("/fulfillment_charge/exponent", json!(0)),
    238         ("/fulfillment/0/terms/window/end", json!("300")),
    239         (
    240             "/fulfillment/0/terms/window/timezone",
    241             json!("invalid/zone"),
    242         ),
    243         ("/lines/0/price/rate/minor", json!(150)),
    244         ("/lines/0/price/basis", json!(1)),
    245     ] {
    246         let mut invalid = original.clone();
    247         *invalid.pointer_mut(path).unwrap() = value;
    248         assert!(decode(&bytes(&invalid)).is_err(), "{path}");
    249     }
    250     for path in [
    251         "/cancellation",
    252         "/rounding",
    253         "/supply/type",
    254         "/lines/0/price/type",
    255         "/lines/0/option/price/type",
    256         "/lines/0/option/supply/type",
    257         "/lines/0/option/unit/type",
    258         "/lines/0/option/unit/contents/type",
    259         "/lines/0/option/unit/contents/quantity/unit",
    260         "/fulfillment/0/terms/mode",
    261     ] {
    262         let mut unknown = original.clone();
    263         *unknown.pointer_mut(path).unwrap() = json!("future_profile");
    264         assert!(
    265             matches!(
    266                 decode(&bytes(&unknown)),
    267                 Err(TermsWireError::UnsupportedProfile)
    268             ),
    269             "{path}"
    270         );
    271     }
    272     let mut variable = example(1);
    273     variable["lines"][0]["price"]["measurement_unit"] = json!("future_unit");
    274     assert!(matches!(
    275         decode(&bytes(&variable)),
    276         Err(TermsWireError::UnsupportedProfile)
    277     ));
    278 }
    279 
    280 #[test]
    281 fn public_snapshot_alternatives_preserve_explicit_values_without_invented_defaults() {
    282     for unit in ["g", "kg", "mL", "L", "each"] {
    283         let mut value = example(0);
    284         value["lines"][0]["product"]["producer"] = Value::Null;
    285         value["lines"][0]["product"]["origin_summary"] = Value::Null;
    286         value["lines"][0]["option"]["unit"] = json!({"type":"measured","unit":unit});
    287         value["lines"][0]["option"]["supply"] = json!({"type":"available","amount":"0"});
    288         let terms = decode(&bytes(&value)).unwrap();
    289         let output: Value =
    290             serde_json::from_slice(EncodedTerms::capture(&terms).unwrap().protected_wire())
    291                 .unwrap();
    292         assert_eq!(output, value);
    293         value["lines"][0]["option"]["unit"]["unit"] = json!("future_unit");
    294         assert!(matches!(
    295             decode(&bytes(&value)),
    296             Err(TermsWireError::UnsupportedProfile)
    297         ));
    298     }
    299     for unit in ["g", "kg", "mL", "L"] {
    300         let mut value = example(1);
    301         value["lines"][0]["price"]["measurement_unit"] = json!(unit);
    302         let terms = decode(&bytes(&value)).unwrap();
    303         let output: Value =
    304             serde_json::from_slice(EncodedTerms::capture(&terms).unwrap().protected_wire())
    305                 .unwrap();
    306         assert_eq!(output, value);
    307     }
    308 }
    309 
    310 #[test]
    311 fn byte_depth_and_collection_budgets_bound_terms_before_domain_materialization() {
    312     let fixture = fixtures();
    313     let exact = fixture["vectors"]
    314         .as_array()
    315         .unwrap()
    316         .iter()
    317         .find(|v| v["name"] == "exact_content_limit")
    318         .unwrap()["wire"]
    319         .as_str()
    320         .unwrap();
    321     assert!(decode(exact.as_bytes()).is_ok());
    322     assert!(matches!(
    323         decode(format!("{exact} ").as_bytes()),
    324         Err(TermsWireError::LimitExceeded)
    325     ));
    326     let original = example(0);
    327     for (field, count) in [("lines", 33), ("fulfillment", 9)] {
    328         let mut invalid = original.clone();
    329         invalid[field] = Value::Array(vec![Value::Null; count]);
    330         assert!(decode(&bytes(&invalid)).is_err());
    331     }
    332     for field in ["lines", "fulfillment"] {
    333         let mut invalid = original.clone();
    334         let duplicate = invalid[field][0].clone();
    335         invalid[field].as_array_mut().unwrap().push(duplicate);
    336         assert!(decode(&bytes(&invalid)).is_err());
    337     }
    338     let too_deep = format!("{}0{}", "[".repeat(17), "]".repeat(17));
    339     assert!(matches!(
    340         decode(too_deep.as_bytes()),
    341         Err(TermsWireError::LimitExceeded)
    342     ));
    343     for raw in [b"{".as_slice(), b"[]", b"null", b"\xff"] {
    344         assert!(decode(raw).is_err());
    345     }
    346 }