bc-envelope-pattern 0.14.0

Pattern matcher for Gordian Envelope
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
mod common;

use bc_envelope::prelude::*;
use bc_envelope_pattern::{Matcher, Pattern, format_paths};
use indoc::indoc;

#[test]
fn test_subject_pattern() {
    let envelope = Envelope::new("Alice");

    let any_subject_pat = Pattern::any_subject();
    let matching_paths = any_subject_pat.paths(&envelope);

    // expected-text-output-rubric:
    #[rustfmt::skip]
    let expected_1 = indoc! {r#"
        13941b48 LEAF "Alice"
    "#}.trim();
    assert_actual_expected!(format_paths(&matching_paths), expected_1);

    let envelope_with_assertions = envelope.add_assertion("knows", "Bob");
    let matching_paths = any_subject_pat.paths(&envelope_with_assertions);
    // expected-text-output-rubric:
    #[rustfmt::skip]
    let expected_2 = indoc! {r#"
        8955db5e NODE "Alice" [ "knows": "Bob" ]
            13941b48 LEAF "Alice"
    "#}.trim();
    assert_actual_expected!(format_paths(&matching_paths), expected_2);

    let text_subject_pat = Pattern::subject(Pattern::any_text());
    let matching_paths = text_subject_pat.paths(&envelope);
    assert_actual_expected!(format_paths(&matching_paths), expected_1);
    let matching_paths = text_subject_pat.paths(&envelope_with_assertions);
    assert_actual_expected!(format_paths(&matching_paths), expected_2);

    let number_subject_pat = Pattern::subject(Pattern::any_number());
    let matching_paths = number_subject_pat.paths(&envelope);
    assert!(matching_paths.is_empty());
    let matching_paths = number_subject_pat.paths(&envelope_with_assertions);
    assert!(matching_paths.is_empty());
}

#[test]
fn test_wrapped_pattern() {
    // Does not match non-wrapped subjects.
    let envelope = Envelope::new(42);
    assert!(!Pattern::wrapped().matches(&envelope));

    // Matches a wrapped envelope with any subject.
    let wrapped_envelope = envelope.wrap();
    let paths = Pattern::unwrap().paths(&wrapped_envelope);
    // expected-text-output-rubric:
    #[rustfmt::skip]
    let expected = indoc! {r#"
        58b1ac6a WRAPPED { 42 }
            7f83f7bd LEAF 42
    "#}.trim();
    assert_actual_expected!(format_paths(&paths), expected);

    // The matched paths include the assertion.
    let wrapped_envelope_with_assertion =
        wrapped_envelope.add_assertion("an", "assertion");
    let paths = Pattern::unwrap().paths(&wrapped_envelope_with_assertion);
    // expected-text-output-rubric:
    #[rustfmt::skip]
    let expected = indoc! {r#"
        169aba00 NODE { 42 } [ "an": "assertion" ]
            7f83f7bd LEAF 42
    "#}.trim();
    assert_actual_expected!(format_paths(&paths), expected);

    let wrapped_twice = wrapped_envelope_with_assertion.wrap();
    // Matching a wrapped envelope with assertions returns a path where the
    // first element is the original wrapped envelope including assertions,
    // and the second element is the still-wrapped subject.
    let paths = Pattern::unwrap().paths(&wrapped_twice);
    // expected-text-output-rubric:
    #[rustfmt::skip]
    let expected = indoc! {r#"
        52d47c15 WRAPPED { { 42 } [ "an": "assertion" ] }
            169aba00 NODE { 42 } [ "an": "assertion" ]
    "#}.trim();
    assert_actual_expected!(format_paths(&paths), expected);

    let wrapped_twice_pattern =
        Pattern::traverse(vec![Pattern::unwrap(), Pattern::unwrap()]);
    let paths = wrapped_twice_pattern.paths(&wrapped_twice);
    // expected-text-output-rubric:
    #[rustfmt::skip]
    let expected = indoc! {r#"
        52d47c15 WRAPPED { { 42 } [ "an": "assertion" ] }
            169aba00 NODE { 42 } [ "an": "assertion" ]
                7f83f7bd LEAF 42
    "#}.trim();
    assert_actual_expected!(format_paths(&paths), expected);
}

#[test]
fn test_assertion_pattern() {
    let envelope_without_assertions = Envelope::new("Alice");

    // Does not match envelopes without assertions.
    assert!(!Pattern::any_assertion().matches(&envelope_without_assertions));

    let envelope_with_assertions = envelope_without_assertions
        .add_assertion("knows", "Bob")
        .add_assertion("worksWith", "Charlie");

    // Returns a path for each assertion in the envelope.
    let paths = Pattern::any_assertion().paths(&envelope_with_assertions);
    // expected-text-output-rubric:
    #[rustfmt::skip]
    let expected = indoc! {r#"
        78d666eb ASSERTION "knows": "Bob"
        c269cf0a ASSERTION "worksWith": "Charlie"
    "#}.trim();
    assert_actual_expected!(format_paths(&paths), expected);
}

#[test]
fn test_assertion_predicate_pattern() {
    let envelope = Envelope::new("Alice")
        .add_assertion("knows", "Bob")
        .add_assertion("knows", "Charlie")
        .add_assertion("worksWith", "David");

    // Returns a path for each assertion with a predicate that matches
    // the specified pattern.
    let paths = Pattern::assertion_with_predicate(Pattern::text("knows"))
        .paths(&envelope);
    // expected-text-output-rubric:
    #[rustfmt::skip]
    let expected = indoc! {r#"
        78d666eb ASSERTION "knows": "Bob"
        7af83724 ASSERTION "knows": "Charlie"
    "#}.trim();
    assert_actual_expected!(format_paths(&paths), expected);

    let pattern = Pattern::traverse(vec![
        Pattern::assertion_with_predicate(Pattern::text("knows")),
        Pattern::any_object(),
    ]);
    let paths = pattern.paths(&envelope);
    // expected-text-output-rubric:
    #[rustfmt::skip]
    let expected = indoc! {r#"
        78d666eb ASSERTION "knows": "Bob"
            13b74194 LEAF "Bob"
        7af83724 ASSERTION "knows": "Charlie"
            ee8e3b02 LEAF "Charlie"
    "#}.trim();
    assert_actual_expected!(format_paths(&paths), expected);
}

#[test]
fn test_digest_pattern() {
    let envelope = Envelope::new("Hello, World!");
    let digest = envelope.digest();
    let prefix = digest.data()[..4].to_vec(); // First 4 bytes

    // Test exact digest matching
    assert!(Pattern::digest(digest).matches(&envelope));
    assert!(!Pattern::digest(Digest::from_data([0; 32])).matches(&envelope));

    // Test hex prefix matching
    assert!(Pattern::digest_prefix(prefix).matches(&envelope));
    assert!(
        !Pattern::digest_prefix(vec![0xff, 0xff, 0xff, 0xff])
            .matches(&envelope)
    );

    // Test with envelope that has assertions
    let envelope_with_assertions =
        envelope.clone().add_assertion("test", "value");
    let digest_with_assertions = envelope_with_assertions.digest();

    assert!(!Pattern::digest(digest).matches(&envelope_with_assertions));
    assert!(
        Pattern::digest(digest_with_assertions)
            .matches(&envelope_with_assertions)
    );

    // Test paths
    let paths = Pattern::digest(digest).paths(&envelope);
    // expected-text-output-rubric:
    #[rustfmt::skip]
    let expected = indoc! {r#"
        0a852327 LEAF "Hello, World!"
    "#}.trim();
    assert_actual_expected!(format_paths(&paths), expected);

    // No match should return empty paths
    let paths = Pattern::digest(Digest::from_data([0; 32])).paths(&envelope);
    assert!(paths.is_empty());
}

#[test]
fn test_digest_pattern_binary_regex() {
    let envelope = Envelope::new("Hello, World!");
    let digest = envelope.digest();
    let digest_bytes = digest.data();

    // IMPORTANT: Binary regex patterns must use the (?s-u) flags to work
    // correctly with arbitrary bytes:
    // - (?s) allows '.' to match newline characters (like 0x0a)
    // - (?-u) disables unicode mode so '.' matches any byte, not just valid
    //   UTF-8 sequences
    // Without these flags, patterns like ^.{32}$ will fail on digest bytes
    // containing newlines or invalid UTF-8 sequences (which are common in
    // SHA-256 digests).

    // Test regex matching any 32 bytes (should match any valid digest)
    // NOTE: Need (?s-u) flags to handle all bytes including newlines and
    // invalid UTF-8
    let any_32_bytes_regex =
        regex::bytes::Regex::new(r"(?s-u)^.{32}$").unwrap();
    assert!(
        Pattern::digest_binary_regex(any_32_bytes_regex).matches(&envelope)
    );

    // Test regex that shouldn't match (all zeros, 32 bytes)
    let all_zeros_regex =
        regex::bytes::Regex::new(r"(?s-u)^\x00{32}$").unwrap();
    assert!(!Pattern::digest_binary_regex(all_zeros_regex).matches(&envelope));

    // Test regex matching specific byte values using hex escapes
    let first_byte_hex = format!(r"(?s-u)^\x{:02x}", digest_bytes[0]);
    let starts_with_first_byte =
        regex::bytes::Regex::new(&first_byte_hex).unwrap();
    assert!(
        Pattern::digest_binary_regex(starts_with_first_byte).matches(&envelope)
    );

    // Test regex for exact first two bytes
    let first_two_bytes_pattern =
        format!(r"(?s-u)^\x{:02x}\x{:02x}", digest_bytes[0], digest_bytes[1]);
    let exact_first_two =
        regex::bytes::Regex::new(&first_two_bytes_pattern).unwrap();
    assert!(Pattern::digest_binary_regex(exact_first_two).matches(&envelope));

    // Test regex matching any byte in range (should match digests with varied
    // byte values)
    let any_byte_range =
        regex::bytes::Regex::new(r"(?s-u)[\x00-\xFF]").unwrap();
    assert!(Pattern::digest_binary_regex(any_byte_range).matches(&envelope));

    // Test complex pattern - match digests that start with a non-zero byte
    let non_zero_start =
        regex::bytes::Regex::new(r"(?s-u)^[\x01-\xFF]").unwrap();
    let should_match = digest_bytes[0] != 0;
    assert_eq!(
        Pattern::digest_binary_regex(non_zero_start).matches(&envelope),
        should_match
    );

    // Test paths for matching regex
    let paths = Pattern::digest_binary_regex(
        regex::bytes::Regex::new(r"(?s-u)^.{32}$").unwrap(),
    )
    .paths(&envelope);
    // expected-text-output-rubric:
    #[rustfmt::skip]
    let expected = indoc! {r#"
        0a852327 LEAF "Hello, World!"
    "#}.trim();
    assert_actual_expected!(format_paths(&paths), expected);

    // Test paths for non-matching regex
    let paths = Pattern::digest_binary_regex(
        regex::bytes::Regex::new(r"(?s-u)^\x00{32}$").unwrap(),
    )
    .paths(&envelope);
    assert!(paths.is_empty());

    // Test with different envelope to ensure digest changes
    let envelope2 = Envelope::new("Different content");
    let digest2 = envelope2.digest();

    // Verify the digests are actually different
    assert_ne!(digest.data(), digest2.data());

    // Test a pattern that matches both (any 32 bytes)
    let any_digest_regex = regex::bytes::Regex::new(r"(?s-u)^.{32}$").unwrap();
    assert!(
        Pattern::digest_binary_regex(any_digest_regex.clone())
            .matches(&envelope)
    );
    assert!(Pattern::digest_binary_regex(any_digest_regex).matches(&envelope2));

    // Test pattern that matches based on content
    // Looking for digests containing specific byte sequences
    let contains_aa = regex::bytes::Regex::new(r"(?s-u)\xaa").unwrap();
    let envelope1_has_aa = digest_bytes.contains(&0xaa);
    assert_eq!(
        Pattern::digest_binary_regex(contains_aa.clone()).matches(&envelope),
        envelope1_has_aa
    );

    let digest2_bytes = digest2.data();
    let envelope2_has_aa = digest2_bytes.contains(&0xaa);
    assert_eq!(
        Pattern::digest_binary_regex(contains_aa).matches(&envelope2),
        envelope2_has_aa
    );

    // Test edge cases with different digest patterns
    let pattern_32_ascending =
        regex::bytes::Regex::new(r"(?s-u)^[\x00-\x1F]{32}$").unwrap();
    let has_low_bytes = digest_bytes.iter().all(|&b| b <= 0x1F);
    assert_eq!(
        Pattern::digest_binary_regex(pattern_32_ascending).matches(&envelope),
        has_low_bytes
    );

    // Test pattern that looks for high-bit bytes
    let pattern_high_bit =
        regex::bytes::Regex::new(r"(?s-u)[\x80-\xFF]").unwrap();
    let has_high_bit = digest_bytes.iter().any(|&b| b >= 0x80);
    assert_eq!(
        Pattern::digest_binary_regex(pattern_high_bit).matches(&envelope),
        has_high_bit
    );

    // Test envelope with assertions (should match differently)
    let envelope_with_assertions =
        envelope.clone().add_assertion("test", "value");
    let digest_with_assertions = envelope_with_assertions.digest();

    // Should still match 32-byte pattern
    let universal_pattern = regex::bytes::Regex::new(r"(?s-u)^.{32}$").unwrap();
    assert!(
        Pattern::digest_binary_regex(universal_pattern)
            .matches(&envelope_with_assertions)
    );

    // But digests should be different
    assert_ne!(digest.data(), digest_with_assertions.data());
}

#[test]
fn test_node_pattern() {
    // Test with leaf (non-node) envelope
    let leaf_envelope = Envelope::new("Just a leaf");
    assert!(!Pattern::any_node().matches(&leaf_envelope));
    assert!(
        !Pattern::node_with_assertions_range(1..=3).matches(&leaf_envelope)
    );
    assert!(!Pattern::node_with_assertions_count(1).matches(&leaf_envelope));

    // Test with single assertion node
    let single_assertion_envelope =
        Envelope::new("Alice").add_assertion("knows", "Bob");
    assert!(Pattern::any_node().matches(&single_assertion_envelope));
    assert!(
        Pattern::node_with_assertions_range(1..=3)
            .matches(&single_assertion_envelope)
    );
    assert!(
        Pattern::node_with_assertions_count(1)
            .matches(&single_assertion_envelope)
    );
    assert!(
        !Pattern::node_with_assertions_count(2)
            .matches(&single_assertion_envelope)
    );

    // Test with multiple assertions node
    let multi_assertion_envelope = single_assertion_envelope
        .add_assertion("age", 25)
        .add_assertion("city", "New York");
    assert!(Pattern::any_node().matches(&multi_assertion_envelope));
    assert!(
        Pattern::node_with_assertions_range(1..=5)
            .matches(&multi_assertion_envelope)
    );
    assert!(
        Pattern::node_with_assertions_count(3)
            .matches(&multi_assertion_envelope)
    );
    assert!(
        !Pattern::node_with_assertions_count(2)
            .matches(&multi_assertion_envelope)
    );
    assert!(
        !Pattern::node_with_assertions_range(4..=5)
            .matches(&multi_assertion_envelope)
    );

    // Test paths
    let paths = Pattern::any_node().paths(&single_assertion_envelope);
    // expected-text-output-rubric:
    #[rustfmt::skip]
    let expected = indoc! {r#"
        8955db5e NODE "Alice" [ "knows": "Bob" ]
    "#}.trim();
    assert_actual_expected!(format_paths(&paths), expected);
}

#[test]
fn test_obscured_pattern() {
    let original_envelope = Envelope::new("Secret data");

    // Test with elided envelope
    let elided_envelope = original_envelope.elide();
    assert!(Pattern::obscured().matches(&elided_envelope));
    assert!(Pattern::elided().matches(&elided_envelope));
    assert!(!Pattern::encrypted().matches(&elided_envelope));
    assert!(!Pattern::compressed().matches(&elided_envelope));

    // Test with original (non-obscured) envelope
    assert!(!Pattern::obscured().matches(&original_envelope));
    assert!(!Pattern::elided().matches(&original_envelope));
    assert!(!Pattern::encrypted().matches(&original_envelope));
    assert!(!Pattern::compressed().matches(&original_envelope));

    // Test paths for elided envelope
    let paths = Pattern::elided().paths(&elided_envelope);
    #[rustfmt::skip]
    let expected = format!(
        "{} ELIDED",
        elided_envelope.short_id(DigestDisplayFormat::Short)
    );
    assert_actual_expected!(format_paths(&paths), expected);

    // No match should return empty paths
    let paths = Pattern::elided().paths(&original_envelope);
    assert!(paths.is_empty());

    {
        use bc_components::SymmetricKey;

        // Test with encrypted envelope
        let key = SymmetricKey::new();
        let encrypted_envelope =
            original_envelope.encrypt_subject(&key).unwrap();
        assert!(Pattern::obscured().matches(&encrypted_envelope));
        assert!(Pattern::encrypted().matches(&encrypted_envelope));
        assert!(!Pattern::elided().matches(&encrypted_envelope));
        assert!(!Pattern::compressed().matches(&encrypted_envelope));
    }

    {
        // Test with compressed envelope
        let compressed_envelope = original_envelope.compress().unwrap();
        assert!(Pattern::obscured().matches(&compressed_envelope));
        assert!(Pattern::compressed().matches(&compressed_envelope));
        assert!(!Pattern::elided().matches(&compressed_envelope));
        assert!(!Pattern::encrypted().matches(&compressed_envelope));
    }
}