vex2pdf 4.0.0

A tool to convert CycloneDX(VEX) JSON or XML documents to PDF reports
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
// Paths to test artifacts and executables
#[allow(unused)]
pub mod paths {
    pub const PATH_TO_EXE: &str = env!("CARGO_BIN_EXE_vex2pdf");
    pub const DEFAULT_WORKING_DIR: &str = env!("CARGO_MANIFEST_DIR");

    pub const REFERENCE_PDFS_DIR: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/tests/test_artifacts/expected_pdfs"
    );

    pub const ERRONEOUS_PDFS_DIR: &str =
        concat!(env!("CARGO_MANIFEST_DIR"), "/tests/test_artifacts/err_pdfs");

    pub const SOURCE_BOMS_PARENT_DIR: &str =
        concat!(env!("CARGO_MANIFEST_DIR"), "/tests/test_artifacts/bom_src");

    pub const SOURCE_BOMS_BASE_ARTIFACTS_DIR: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/tests/test_artifacts/bom_src/run_test"
    );

    pub const SOURCE_BOMS_NOVULNS_ARTIFACTS_DIR: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/tests/test_artifacts/bom_src/run_test_novulns"
    );

    pub const SOURCE_BOMS_XML_ARTIFACTS_DIR: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/tests/test_artifacts/bom_src/run_test_xml"
    );

    pub const BOM_VDR_WITH_INVALID_PROPERTY: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/tests/test_artifacts/bom_src/run_test_invalid/bom_vdr_with_invalid_property.json"
    );

    // Individual test file paths - JSON
    pub const SIMPLE_BOM_PATH: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/tests/test_artifacts/bom_src/run_test/bom_vex_simple_one_vuln.json"
    );

    pub const BOM_VDR_MINIMAL_WITH_VULNS: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/tests/test_artifacts/bom_src/run_test/bom_vdr_minimal_with_vulns.json"
    );

    pub const BOM_VDR_WITH_GHSA_ENTRIES: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/tests/test_artifacts/bom_src/run_test/bom_vdr_with_ghsa_entries.json"
    );

    pub const BOM_VDR_WITH_MANY_VULNS: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/tests/test_artifacts/bom_src/run_test/bom_vdr_with_many_vulns.json"
    );

    pub const BOM_VDR_WITH_MANY_VULNS_TITLES_OVERRIDE: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/tests/test_artifacts/bom_src/run_test/bom_vdr_with_many_vulns_titles_override_cli.json"
    );
    pub const BOM_VDR_WITH_NO_VULNS: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/tests/test_artifacts/bom_src/run_test/bom_vdr_with_no_vulns.json"
    );

    pub const BOM_VDR_WITH_LINKS_AS_VERSIONS: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/tests/test_artifacts/bom_src/run_test/bom_vdr_with_links_as_versions.json"
    );

    pub const BOM_VEX_WITH_LINKS_AS_VERSIONS: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/tests/test_artifacts/bom_src/run_test/bom_vex_with_links_as_versions.json"
    );

    // No vulns test
    pub const BOM_NOVULNS: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/tests/test_artifacts/bom_src/run_test/bom_vdr_with_no_vulns.json"
    );

    // XML test files
    pub const BOM_VDR_SIMPLE_XML: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/tests/test_artifacts/bom_src/run_test_xml/bom_xml_vdr_simple.xml"
    );

    pub const BOM_VEX_SIMPLE_XML: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/tests/test_artifacts/bom_src/run_test_xml/bom_xml_vex_simple.xml"
    );

    pub const SAMPLE_VEX_XML: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/tests/test_artifacts/bom_src/run_test_xml/sample_xml_vex.xml"
    );

    // Analysis test files - JSON
    pub const BOM_VDR_WITH_ANALYSIS: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/tests/test_artifacts/bom_src/run_test/bom_vdr_with_analysis.json"
    );

    // Analysis test files - XML
    pub const BOM_VDR_WITH_ANALYSIS_XML: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/tests/test_artifacts/bom_src/run_test_xml/bom_xml_vdr_with_analysis.xml"
    );

    // Expected PDFs for analysis tests
    pub const EXPECTED_BOM_VDR_WITH_ANALYSIS_PDF: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/tests/test_artifacts/expected_pdfs/bom_vdr_with_analysis.pdf"
    );

    pub const EXPECTED_BOM_VDR_WITH_ANALYSIS_XML_PDF: &str = concat!(
        env!("CARGO_MANIFEST_DIR"),
        "/tests/test_artifacts/expected_pdfs/bom_xml_vdr_with_analysis.pdf"
    );
}

// Utility functions for test assertions, we allow unused because tests expand and as such these functions maybe used temporarily for debugging purposes

#[allow(unused)]
pub mod utils {
    use std::borrow::Cow;
    use std::fs;
    use std::path::Path;
    use std::string::String;

    /// Check if byte output contains the expected text
    pub fn contains_text(bytes: &[u8], text: &str) -> bool {
        String::from_utf8_lossy(bytes).contains(text)
    }

    /// Convert bytes to string (lossy conversion for non-UTF8)
    pub fn bytes_to_str(bytes: &[u8]) -> Cow<'_, str> {
        String::from_utf8_lossy(bytes)
    }

    /// Assert that output contains expected text with helpful error message
    pub fn assert_output_contains(bytes: &[u8], text: &str) {
        let output = String::from_utf8_lossy(bytes);
        assert!(
            output.contains(text),
            "\n\nAssertion failed: output does not contain expected text\n\
             Expected to find: \"{}\"\n\
             Actual output:\n{}\n",
            text,
            output
        );
    }

    /// Assert that a PDF file was created and is valid
    pub fn assert_pdf_created(pdf_path: &Path) {
        assert!(pdf_path.exists(), "PDF file not created at: {:?}", pdf_path);

        let metadata = fs::metadata(pdf_path).expect("Failed to read PDF metadata");
        assert!(metadata.len() > 0, "PDF file is empty");

        let contents = fs::read(pdf_path).expect("Failed to read PDF file");
        assert!(
            contents.starts_with(b"%PDF-"),
            "File is not a valid PDF (missing PDF header)"
        );
    }

    /// Strip timestamp and dynamic ID-related lines from PDF content for comparison
    fn strip_pdf_timestamps(content: &str) -> String {
        content
            .lines()
            .filter(|line| {
                // Filter out timestamp-related lines and dynamic IDs
                !line.contains("CreateDate")
                    && !line.contains("ModifyDate")
                    && !line.contains("MetadataDate")
                    && !line.contains("CreationDate")
                    && !line.contains("ModDate")
                    && !line.contains("InstanceID")  // XMP metadata UUID
                    && !line.contains("DocumentID")  // XMP document UUID
                    && !line.contains("/ID[") // PDF document IDs
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// Compare PDF content ignoring timestamps
    /// On failure, copies the generated PDF to err_pdfs directory for debugging
    ///
    /// # Release Mode Behavior
    /// In release mode, content comparison is skipped because PDF libraries optimize
    /// differently, resulting in binary differences that don't indicate test failures.
    /// Only PDF creation is verified in release mode.
    pub fn assert_pdf_content_similar(generated: &Path, expected: &Path) {
        // Skip content comparison in release mode due to PDF library optimization differences
        #[cfg(not(debug_assertions))]
        {
            eprintln!(
                "ℹ️  Release mode: Skipping PDF content comparison for {:?}",
                generated.file_name().unwrap_or_default()
            );
            return;
        }

        #[cfg(debug_assertions)]
        {
            let gen_content = fs::read(generated).expect("Failed to read generated PDF");
            let exp_content = fs::read(expected).expect("Failed to read expected PDF");

            let gen_content_str = String::from_utf8_lossy(&gen_content);
            let exp_content_str = String::from_utf8_lossy(&exp_content);

            let gen_stripped = strip_pdf_timestamps(&gen_content_str);
            let exp_stripped = strip_pdf_timestamps(&exp_content_str);

            if gen_stripped != exp_stripped {
                // Copy failed PDF and stripped content to err_pdfs for post-mortem analysis
                let err_dir = Path::new(super::paths::ERRONEOUS_PDFS_DIR);
                if let Err(e) = fs::create_dir_all(err_dir) {
                    eprintln!("Warning: Failed to create err_pdfs directory: {}", e);
                }

                if let Some(filename) = generated.file_name() {
                    let stem = generated.file_stem().unwrap().to_str().unwrap();

                    // Copy the failed PDF
                    let err_pdf_path = err_dir.join(filename);
                    if let Err(e) = fs::copy(generated, &err_pdf_path) {
                        eprintln!("Warning: Failed to copy failed PDF to err_pdfs: {}", e);
                    } else {
                        eprintln!("\n⚠️  Failed PDF copied to: {:?}", err_pdf_path);
                    }

                    // Write stripped generated content
                    let gen_stripped_path =
                        err_dir.join(format!("{}_generated_raw_dump.txt", stem));
                    if let Err(e) = fs::write(&gen_stripped_path, &gen_stripped) {
                        eprintln!("Warning: Failed to write generated stripped content: {}", e);
                    } else {
                        eprintln!("📄 Generated (stripped) saved to: {:?}", gen_stripped_path);
                    }

                    // Write stripped expected content
                    let exp_stripped_path = err_dir.join(format!("{}_expected_raw_dump.txt", stem));
                    if let Err(e) = fs::write(&exp_stripped_path, &exp_stripped) {
                        eprintln!("Warning: Failed to write expected stripped content: {}", e);
                    } else {
                        eprintln!("📄 Expected (stripped) saved to: {:?}", exp_stripped_path);
                    }
                }

                // Panic with minimal output (no binary gibberish)
                panic!(
                    "\n\nPDF content differs (timestamps excluded)\n\
                 Generated: {:?}\n\
                 Expected: {:?}\n\
                 \n\
                 Debug files saved to {:?}:\n\
                 - *.pdf (failed PDF)\n\
                 - *_generated.txt (stripped generated content)\n\
                 - *_expected.txt (stripped expected content)\n\
                 \n\
                 Run: diff {:?}/*_generated.txt {:?}/*_expected.txt\n",
                    generated,
                    expected,
                    super::paths::ERRONEOUS_PDFS_DIR,
                    super::paths::ERRONEOUS_PDFS_DIR,
                    super::paths::ERRONEOUS_PDFS_DIR
                );
            }
        }
    }

    /// Normalize PDF content by stripping dynamic elements (timestamps, IDs)
    /// This is the same normalization used by assert_pdf_content_similar
    pub fn normalize_pdf_content(pdf_path: &Path) -> String {
        let content = fs::read(pdf_path).expect("Failed to read PDF file");
        let content_str = String::from_utf8_lossy(&content);
        strip_pdf_timestamps(&content_str)
    }

    /// Calculate BLAKE3 checksum of normalized PDF content
    pub fn calculate_normalized_checksum(pdf_path: &Path) -> String {
        let normalized = normalize_pdf_content(pdf_path);
        let hash = blake3::hash(normalized.as_bytes());
        hash.to_hex().to_string()
    }

    /// Assert that a generated PDF's normalized checksum matches the expected checksum
    /// from the checksums file. This validates PDF content while ignoring dynamic elements.
    pub fn assert_pdf_checksum_matches(generated_pdf: &Path) {
        let checksums_path = Path::new(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/tests/test_artifacts/expected_pdfs_chksums.txt"
        ));

        let checksums_content =
            fs::read_to_string(checksums_path).expect("Failed to read checksums file");

        let pdf_filename = generated_pdf
            .file_name()
            .expect("Failed to get PDF filename")
            .to_str()
            .expect("Invalid filename");

        // Find the expected checksum for this PDF
        let expected_checksum = checksums_content
            .lines()
            .find(|line| line.ends_with(pdf_filename))
            .map(|line| line.split_whitespace().next().unwrap())
            .unwrap_or_else(|| panic!("No checksum found for {} in checksums file", pdf_filename));

        // Calculate the checksum of the generated PDF
        let actual_checksum = calculate_normalized_checksum(generated_pdf);

        if actual_checksum != expected_checksum {
            // Copy failed PDF to err_pdfs for debugging
            let err_dir = Path::new(super::paths::ERRONEOUS_PDFS_DIR);
            if let Err(e) = fs::create_dir_all(err_dir) {
                eprintln!("Warning: Failed to create err_pdfs directory: {}", e);
            }

            if let Some(filename) = generated_pdf.file_name() {
                let err_pdf_path = err_dir.join(filename);
                if let Err(e) = fs::copy(generated_pdf, &err_pdf_path) {
                    eprintln!("Warning: Failed to copy failed PDF to err_pdfs: {}", e);
                } else {
                    eprintln!("\n⚠️  Failed PDF copied to: {:?}", err_pdf_path);
                }
            }

            panic!(
                "\n\nPDF checksum mismatch for: {}\n\
                 Expected: {}\n\
                 Actual:   {}\n\
                 \n\
                 The generated PDF differs from the expected content.\n\
                 Failed PDF copied to {:?} for inspection.\n",
                pdf_filename,
                expected_checksum,
                actual_checksum,
                super::paths::ERRONEOUS_PDFS_DIR
            );
        }
    }

    /// Helper function to count PDF files in a directory
    pub fn count_pdf_files(dir: &Path) -> usize {
        std::fs::read_dir(dir)
            .expect("Failed to read directory")
            .filter_map(|entry| entry.ok())
            .filter(|entry| {
                let path = entry.path();
                path.is_file()
                    && path
                        .extension()
                        .and_then(|ext| ext.to_str())
                        .map(|ext| ext == "pdf")
                        .unwrap_or(false)
            })
            .count()
    }

    /// Helper function to count processable files (.json and .xml) in a directory
    pub fn count_processable_files(dir: &Path) -> usize {
        std::fs::read_dir(dir)
            .expect("Failed to read directory")
            .filter_map(|entry| entry.ok())
            .filter(|entry| {
                let path = entry.path();
                path.is_file()
                    && path
                        .extension()
                        .and_then(|ext| ext.to_str())
                        .map(|ext| ext == "json" || ext == "xml")
                        .unwrap_or(false)
            })
            .count()
    }

    /// Helper function to assert the number of PDF files created
    pub fn assert_pdf_count(dir: &Path, expected: usize) {
        let actual = count_pdf_files(dir);
        assert_eq!(
            actual, expected,
            "Expected {} PDFs but found {} in directory: {:?}",
            expected, actual, dir
        );
    }

    /// Helper function to copy all files from source directory to destination directory
    pub fn copy_directory_files(
        src_dir: &Path,
        dest_dir: &Path,
        ignore_file_names_containing: Option<Vec<&str>>,
    ) -> std::io::Result<usize> {
        let mut count = 0;
        for entry in std::fs::read_dir(src_dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_file() {
                let file_name = path.file_name().unwrap();
                let file_name_str = file_name.to_str().unwrap_or_default();

                // Check if file should be ignored
                let should_ignore = ignore_file_names_containing
                    .as_ref()
                    .map(|patterns| patterns.iter().any(|pat| file_name_str.contains(pat)))
                    .unwrap_or(false);

                if should_ignore {
                    continue; // Skip this file
                }

                std::fs::copy(&path, dest_dir.join(file_name))?;
                count += 1;
            }
        }
        Ok(count)
    }
}