ddex-builder 0.4.5

Deterministic DDEX XML builder with smart normalization
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//! Tests for DB-C14N/1.0 canonicalization

use super::*;
use crate::determinism::DeterminismConfig;

#[cfg(test)]
mod tests {
    use super::*;

    fn create_test_canonicalizer() -> DB_C14N {
        let config = DeterminismConfig::default();
        DB_C14N::new(config)
    }

    fn create_test_canonicalizer_with_version(version: &str) -> DB_C14N {
        let config = DeterminismConfig::default();
        DB_C14N::with_version(config, version.to_string())
    }

    #[test]
    fn test_xml_declaration() {
        let canonicalizer = create_test_canonicalizer();
        let input = r#"<?xml version="1.0" encoding="UTF-8"?>
<root>test</root>"#;

        let result = canonicalizer.canonicalize(input).unwrap();
        assert!(result.starts_with("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"));
    }

    #[test]
    fn test_attribute_sorting() {
        let canonicalizer = create_test_canonicalizer();
        let input = r#"<?xml version="1.0" encoding="UTF-8"?>
<root z="z" a="a" m="m">test</root>"#;

        let result = canonicalizer.canonicalize(input).unwrap();
        // Attributes should be sorted alphabetically
        assert!(result.contains(r#"<root a="a" m="m" z="z">"#));
    }

    #[test]
    fn test_whitespace_normalization() {
        let canonicalizer = create_test_canonicalizer();
        let input = r#"<?xml version="1.0" encoding="UTF-8"?>
<root>
    
    test content   
    
</root>"#;

        let result = canonicalizer.canonicalize(input).unwrap();
        // Should normalize whitespace to single space
        assert!(result.contains("test content"));
    }

    #[test]
    fn test_indentation() {
        let canonicalizer = create_test_canonicalizer();
        let input = r#"<?xml version="1.0" encoding="UTF-8"?>
<root><child>content</child></root>"#;

        let result = canonicalizer.canonicalize(input).unwrap();
        let lines: Vec<&str> = result.lines().collect();

        // Should have 2-space indentation
        assert!(lines.iter().any(|line| line.starts_with("  <child>")));
    }

    #[test]
    fn test_no_trailing_whitespace() {
        let canonicalizer = create_test_canonicalizer();
        let input = r#"<?xml version="1.0" encoding="UTF-8"?>
<root>
  <child>content</child>
</root>"#;

        let result = canonicalizer.canonicalize(input).unwrap();
        // No line should end with whitespace
        for line in result.lines() {
            assert_eq!(
                line,
                line.trim_end(),
                "Line has trailing whitespace: '{}'",
                line
            );
        }
    }

    #[test]
    fn test_ern_version_detection() {
        let canonicalizer = create_test_canonicalizer();

        // Test ERN 3.8.2 detection
        assert_eq!(
            canonicalizer
                .detect_version(r#"<root xmlns="http://ddex.net/xml/ern/382">test</root>"#),
            "3.8.2"
        );

        // Test ERN 4.2 detection
        assert_eq!(
            canonicalizer.detect_version(r#"<root xmlns="http://ddex.net/xml/ern/42">test</root>"#),
            "4.2"
        );

        // Test ERN 4.3 detection
        assert_eq!(
            canonicalizer.detect_version(r#"<root xmlns="http://ddex.net/xml/ern/43">test</root>"#),
            "4.3"
        );
    }

    #[test]
    fn test_namespace_prefix_locking_43() {
        let canonicalizer = create_test_canonicalizer_with_version("4.3");
        let input = r#"<?xml version="1.0" encoding="UTF-8"?>
<root xmlns:ddex="http://ddex.net/xml/ern/43" xmlns:avs="http://ddex.net/xml/avs">
  <ddex:Release>test</ddex:Release>
</root>"#;

        let result = canonicalizer.canonicalize(input).unwrap();
        // Should use locked prefix 'ern' instead of 'ddex'
        assert!(result.contains(r#"xmlns:ern="http://ddex.net/xml/ern/43""#));
    }

    #[test]
    fn test_element_ordering_message_header() {
        let canonicalizer = create_test_canonicalizer();
        let input = r#"<?xml version="1.0" encoding="UTF-8"?>
<MessageHeader>
  <MessageSender>sender</MessageSender>
  <MessageId>id</MessageId>
  <MessageType>type</MessageType>
</MessageHeader>"#;

        let result = canonicalizer.canonicalize(input).unwrap();
        let lines: Vec<&str> = result.lines().collect();

        // Find positions of elements
        let id_pos = lines
            .iter()
            .position(|l| l.contains("<MessageId>"))
            .unwrap();
        let type_pos = lines
            .iter()
            .position(|l| l.contains("<MessageType>"))
            .unwrap();
        let sender_pos = lines
            .iter()
            .position(|l| l.contains("<MessageSender>"))
            .unwrap();

        // Should be in canonical order: Id, Type, Sender
        assert!(id_pos < type_pos);
        assert!(type_pos < sender_pos);
    }

    #[test]
    fn test_deterministic_output() {
        let canonicalizer = create_test_canonicalizer();
        let input = r#"<?xml version="1.0" encoding="UTF-8"?>
<root z="z" a="a">
  <child2>content2</child2>
  <child1>content1</child1>
</root>"#;

        // Run canonicalization multiple times
        let result1 = canonicalizer.canonicalize(input).unwrap();
        let result2 = canonicalizer.canonicalize(input).unwrap();
        let result3 = canonicalizer.canonicalize(input).unwrap();

        // Should be byte-identical
        assert_eq!(result1, result2);
        assert_eq!(result2, result3);
    }

    #[test]
    fn test_canonical_hash() {
        let canonicalizer = create_test_canonicalizer();
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<root>test</root>"#;

        let canonical = canonicalizer.canonicalize(xml).unwrap();
        let hash1 = canonicalizer.canonical_hash(&canonical).unwrap();
        let hash2 = canonicalizer.canonical_hash(&canonical).unwrap();

        // Same content should produce same hash
        assert_eq!(hash1, hash2);
        assert_eq!(hash1.len(), 64); // SHA-256 hex string
    }

    #[test]
    fn test_empty_elements() {
        let canonicalizer = create_test_canonicalizer();
        let input = r#"<?xml version="1.0" encoding="UTF-8"?>
<root>
  <empty/>
  <also-empty></also-empty>
</root>"#;

        let result = canonicalizer.canonicalize(input).unwrap();
        // Should handle empty elements correctly
        assert!(result.contains("<empty/>") || result.contains("<empty></empty>"));
    }

    #[test]
    fn test_comments_preservation() {
        let canonicalizer = create_test_canonicalizer();
        let input = r#"<?xml version="1.0" encoding="UTF-8"?>
<root>
  <!-- This is a comment -->
  <child>content</child>
</root>"#;

        let result = canonicalizer.canonicalize(input).unwrap();
        // Comments should be preserved
        assert!(result.contains("<!-- This is a comment -->"));
    }

    #[test]
    fn test_complex_ddex_structure() {
        let canonicalizer = create_test_canonicalizer();
        let input = r#"<?xml version="1.0" encoding="UTF-8"?>
<ern:NewReleaseMessage xmlns:ern="http://ddex.net/xml/ern/43" xmlns:avs="http://ddex.net/xml/avs">
  <MessageHeader>
    <MessageSender>sender</MessageSender>
    <MessageId>MSG123</MessageId>
    <MessageType>NewReleaseMessage</MessageType>
    <MessageCreatedDateTime>2023-01-01T00:00:00Z</MessageCreatedDateTime>
  </MessageHeader>
  <ReleaseList>
    <Release>
      <ReleaseId>
        <GRid>A123456789</GRid>
      </ReleaseId>
      <ReferenceTitle>
        <TitleText>Test Album</TitleText>
      </ReferenceTitle>
    </Release>
  </ReleaseList>
</ern:NewReleaseMessage>"#;

        let result = canonicalizer.canonicalize(input).unwrap();

        // Should maintain structure and apply canonicalization
        assert!(result.starts_with("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"));
        assert!(result.contains("<MessageHeader>"));
        assert!(result.contains("<Release>"));

        // Should have proper indentation
        assert!(result.contains("  <MessageHeader>"));
        assert!(result.contains("    <MessageId>"));
    }

    #[test]
    fn test_round_trip_fidelity() {
        let canonicalizer = create_test_canonicalizer();
        let input = r#"<?xml version="1.0" encoding="UTF-8"?>
<root attr="value">
  <child>content</child>
</root>"#;

        // Canonicalize once
        let canonical1 = canonicalizer.canonicalize(input).unwrap();

        // Canonicalize the result again
        let canonical2 = canonicalizer.canonicalize(&canonical1).unwrap();

        // Should be identical (idempotent)
        assert_eq!(canonical1, canonical2);
    }

    #[test]
    fn test_line_ending_normalization() {
        let canonicalizer = create_test_canonicalizer();

        // Test different line ending types
        let input_crlf = "<root>\r\n  <child>content</child>\r\n</root>";
        let input_cr = "<root>\r  <child>content</child>\r</root>";
        let input_lf = "<root>\n  <child>content</child>\n</root>";

        let result_crlf = canonicalizer.canonicalize(input_crlf).unwrap();
        let result_cr = canonicalizer.canonicalize(input_cr).unwrap();
        let result_lf = canonicalizer.canonicalize(input_lf).unwrap();

        // All should normalize to LF
        assert!(!result_crlf.contains("\r\n"));
        assert!(!result_cr.contains("\r"));
        assert!(result_lf.contains("\n"));

        // Results should be structurally identical
        assert_eq!(result_crlf, result_lf);
        assert_eq!(result_cr, result_lf);
    }

    #[test]
    fn test_attribute_escaping() {
        let canonicalizer = create_test_canonicalizer();
        let input = r#"<?xml version="1.0" encoding="UTF-8"?>
<root attr="&quot;quoted&quot; &amp; escaped">
  <child>&lt;content&gt;</child>
</root>"#;

        let result = canonicalizer.canonicalize(input).unwrap();

        // Should properly escape/unescape content
        assert!(result.contains("&quot;") || result.contains("\""));
        assert!(result.contains("&amp;") || result.contains("&"));
        assert!(result.contains("&lt;") || result.contains("<"));
        assert!(result.contains("&gt;") || result.contains(">"));
    }
}

#[cfg(test)]
mod integration_tests {
    use super::*;
    use insta::assert_snapshot;

    #[test]
    fn test_ern_43_canonicalization_snapshot() {
        let canonicalizer = create_test_canonicalizer_with_version("4.3");
        let input = r#"<?xml version="1.0" encoding="UTF-8"?>
<ern:NewReleaseMessage xmlns:ern="http://ddex.net/xml/ern/43" xmlns:avs="http://ddex.net/xml/avs" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <MessageHeader>
    <MessageSender>TestSender</MessageSender>
    <MessageRecipient>TestRecipient</MessageRecipient>
    <MessageId>MSG_001</MessageId>
    <MessageType>NewReleaseMessage</MessageType>
    <MessageCreatedDateTime>2023-12-01T10:00:00Z</MessageCreatedDateTime>
    <MessageControlType>LiveMessage</MessageControlType>
  </MessageHeader>
  <ReleaseList>
    <Release>
      <ReleaseDetailsByTerritory>
        <TerritoryCode>Worldwide</TerritoryCode>
      </ReleaseDetailsByTerritory>
      <ReleaseId>
        <GRid>A1234567890123456789</GRid>
      </ReleaseId>
      <ReferenceTitle>
        <TitleText>Sample Release Title</TitleText>
      </ReferenceTitle>
      <ReleaseReference>REL_001</ReleaseReference>
    </Release>
  </ReleaseList>
</ern:NewReleaseMessage>"#;

        let result = canonicalizer.canonicalize(input).unwrap();
        assert_snapshot!(result);
    }

    #[test]
    fn test_byte_identical_output() {
        let canonicalizer = create_test_canonicalizer();
        let input = r#"<?xml version="1.0" encoding="UTF-8"?>
<test xmlns:z="urn:z" xmlns:a="urn:a" z:attr="z" a:attr="a">
  <z:element>content</z:element>
  <a:element>content</a:element>
</test>"#;

        let result1 = canonicalizer.canonicalize(input).unwrap();
        let result2 = canonicalizer.canonicalize(input).unwrap();

        // Convert to bytes for exact comparison
        let bytes1 = result1.as_bytes();
        let bytes2 = result2.as_bytes();

        assert_eq!(
            bytes1, bytes2,
            "Canonicalization must be deterministic at byte level"
        );
    }

    /// Regression test for text content preservation bug
    /// This test ensures that text content is not lost during canonicalization
    #[test]
    fn test_text_content_preservation_regression() {
        let canonicalizer = create_test_canonicalizer();

        // Test various text content scenarios
        let test_cases = vec![
            // Simple text content
            (
                r#"<?xml version="1.0"?><root>Hello World</root>"#,
                "Hello World",
            ),
            // Text with whitespace that should be normalized but preserved
            (
                r#"<?xml version="1.0"?><root>  Multiple   spaces  </root>"#,
                "Multiple   spaces",
            ),
            // Text with newlines that should be normalized
            (
                r#"<?xml version="1.0"?>
<root>
  Line 1
  Line 2
</root>"#,
                "Line 1 Line 2",
            ),
        ];

        for (input, expected_text) in test_cases {
            let result = canonicalizer.canonicalize(input).unwrap();

            // Parse the result to check that text content is preserved
            assert!(
                result.contains(expected_text),
                "Text content '{}' not found in canonicalized output: {}",
                expected_text,
                result
            );
        }

        // Special test for mixed content - check that text nodes exist separately
        let mixed_input = r#"<?xml version="1.0"?><root>Before<child>nested</child>After</root>"#;
        let mixed_result = canonicalizer.canonicalize(mixed_input).unwrap();

        // For mixed content, we should find both text portions and the nested element
        assert!(
            mixed_result.contains("Before"),
            "Mixed content 'Before' text not preserved"
        );
        assert!(
            mixed_result.contains("After"),
            "Mixed content 'After' text not preserved"
        );
        assert!(
            mixed_result.contains("<child>nested</child>"),
            "Mixed content child element not preserved"
        );
    }

    /// Regression test for mixed content preservation
    #[test]
    fn test_mixed_content_preservation_regression() {
        let canonicalizer = create_test_canonicalizer();

        let input = r#"<?xml version="1.0" encoding="UTF-8"?>
<root>
  <!-- Comment before -->
  <element1>Text 1</element1>
  Some text between elements
  <!-- Comment middle -->  
  <element2>Text 2</element2>
  More text after
  <!-- Comment after -->
</root>"#;

        let result = canonicalizer.canonicalize(input).unwrap();

        // Verify all components are preserved
        assert!(
            result.contains("<!-- Comment before -->"),
            "Comment before not preserved"
        );
        assert!(
            result.contains("<!-- Comment middle -->"),
            "Comment middle not preserved"
        );
        assert!(
            result.contains("<!-- Comment after -->"),
            "Comment after not preserved"
        );
        assert!(result.contains("Text 1"), "Element text 1 not preserved");
        assert!(result.contains("Text 2"), "Element text 2 not preserved");
        assert!(
            result.contains("Some text between elements"),
            "Interstitial text not preserved"
        );
        assert!(
            result.contains("More text after"),
            "Trailing text not preserved"
        );
    }
}