csaf-core 0.3.3

CSAF storage, validation, sidecar generation, import/export
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 Pierre Gronau, ndaal in Cologne

//! Sidecar hash file generation (SHA-256, SHA-512, and SHA3-512).
//!
//! All sidecar filenames use the hyphenated suffix convention mandated by
//! `CLAUDE.md` ยง"Cryptographic hashes (release + CSAF)":
//!
//! * `.sha-256`   โ€” SHA-2 family, 256-bit
//! * `.sha-512`   โ€” SHA-2 family, 512-bit
//! * `.sha3-512`  โ€” SHA-3 family (Keccak), 512-bit
//!
//! Shipping three orthogonal algorithms gives defence-in-depth against a
//! single-family cryptanalytic break.

use csaf_models::settings::Settings;
use sha2::{Digest as Sha2Digest, Sha256, Sha512};
use sha3::Sha3_512;

use crate::fs::DataDir;

// Keep `generic-array` as a direct dep of this crate (see workspace
// `Cargo.toml` for the rationale). Re-exporting the one type actually
// baked into the SHA digest outputs that we consume keeps `cargo
// machete` happy without growing the public API.
#[doc(hidden)]
pub use generic_array::typenum::Unsigned as _GenericArrayUnsigned;

use crate::error::Result;

/// Generate SHA-256 hex digest for the given bytes.
#[must_use]
pub fn sha256_hex(data: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(data);
    let result = hasher.finalize();
    hex_encode(&result)
}

/// Generate SHA-512 (SHA-2 family) hex digest for the given bytes.
#[must_use]
pub fn sha512_hex(data: &[u8]) -> String {
    let mut hasher = Sha512::new();
    hasher.update(data);
    let result = hasher.finalize();
    hex_encode(&result)
}

/// Generate SHA3-512 hex digest for the given bytes.
#[must_use]
pub fn sha3_512_hex(data: &[u8]) -> String {
    let mut hasher = Sha3_512::new();
    hasher.update(data);
    let result = hasher.finalize();
    hex_encode(&result)
}

/// Generate SHA-256 and SHA3-512 hex digests.
///
/// Preserved for backwards compatibility with 0.2.x callers. New code
/// should prefer [`generate_all_hashes`], which also returns SHA-512.
#[must_use]
pub fn generate_hashes(data: &[u8]) -> (String, String) {
    (sha256_hex(data), sha3_512_hex(data))
}

/// Generate the full SHA-256 / SHA-512 / SHA3-512 triplet in one pass.
#[must_use]
pub fn generate_all_hashes(data: &[u8]) -> (String, String, String) {
    (sha256_hex(data), sha512_hex(data), sha3_512_hex(data))
}

/// Selection of hash sidecar families to emit.
///
/// An options object keeps the writer functions within the parameter
/// budget (CLAUDE.md Pattern 3) and carries the choice from the
/// `Settings` toggles to the writer as one value.
#[derive(Debug, Clone, Copy)]
pub struct SidecarHashes {
    /// Emit the SHA-256 (`.sha-256`) sidecar.
    pub sha256: bool,
    /// Emit the SHA-512 (`.sha-512`) sidecar.
    pub sha512: bool,
    /// Emit the SHA3-512 (`.sha3-512`) sidecar.
    pub sha3_512: bool,
}

impl SidecarHashes {
    /// Build the selection from the matching [`Settings`] toggles.
    #[must_use]
    pub const fn from_settings(settings: &Settings) -> Self {
        Self {
            sha256: settings.sidecar_sha256,
            sha512: settings.sidecar_sha512,
            sha3_512: settings.sidecar_sha3_512,
        }
    }
}

/// Write hash sidecars alongside a CSAF JSON file.
///
/// `rel` is the artefact's path relative to the capability-scoped `dir`
/// (e.g. `2026/001/ndaal-sa-2026-001.json`). Creates `{rel}.sha-256`,
/// `{rel}.sha-512`, and/or `{rel}.sha3-512` inside `dir` per `hashes`,
/// each holding the hex digest, two spaces, and the artefact filename
/// (`shasum`-compatible format). All writes are confined to `dir`.
///
/// # Errors
///
/// Returns an I/O error if file writing fails.
pub fn write_sidecar_files(
    dir: &DataDir,
    rel: &str,
    data: &[u8],
    hashes: SidecarHashes,
) -> Result<()> {
    let filename = rel.rsplit('/').next().unwrap_or(rel);

    if hashes.sha256 {
        dir.write(
            &format!("{rel}.sha-256"),
            format!("{}  {filename}\n", sha256_hex(data)).as_bytes(),
        )?;
    }

    if hashes.sha512 {
        dir.write(
            &format!("{rel}.sha-512"),
            format!("{}  {filename}\n", sha512_hex(data)).as_bytes(),
        )?;
    }

    if hashes.sha3_512 {
        dir.write(
            &format!("{rel}.sha3-512"),
            format!("{}  {filename}\n", sha3_512_hex(data)).as_bytes(),
        )?;
    }

    Ok(())
}

/// Write hash sidecars for an artefact, preserving its full extension.
///
/// Unlike [`write_sidecar_files`], this appends `.sha-256` / `.sha-512` /
/// `.sha3-512` to the artefact's full name (`csaf.redb` โ†’
/// `csaf.redb.sha-256`). `rel` is confined to `dir`; used by the
/// database-dump pipeline and the audit-log exporter. Returns the
/// relative paths actually written (sha-256, sha-512, sha3-512).
///
/// # Errors
///
/// Returns an I/O error if file writing fails.
pub fn write_sidecar_files_for(
    dir: &DataDir,
    rel: &str,
    data: &[u8],
    hashes: SidecarHashes,
) -> Result<Vec<String>> {
    let filename = rel.rsplit('/').next().unwrap_or(rel);
    let mut written = Vec::new();

    if hashes.sha256 {
        let sidecar = format!("{rel}.sha-256");
        dir.write(
            &sidecar,
            format!("{}  {filename}\n", sha256_hex(data)).as_bytes(),
        )?;
        written.push(sidecar);
    }

    if hashes.sha512 {
        let sidecar = format!("{rel}.sha-512");
        dir.write(
            &sidecar,
            format!("{}  {filename}\n", sha512_hex(data)).as_bytes(),
        )?;
        written.push(sidecar);
    }

    if hashes.sha3_512 {
        let sidecar = format!("{rel}.sha3-512");
        dir.write(
            &sidecar,
            format!("{}  {filename}\n", sha3_512_hex(data)).as_bytes(),
        )?;
        written.push(sidecar);
    }

    Ok(written)
}

/// Encode bytes as lowercase hex string.
fn hex_encode(bytes: &[u8]) -> String {
    use std::fmt::Write as _;
    let mut hex = String::with_capacity(bytes.len() * 2);
    for b in bytes {
        let _ = write!(hex, "{b:02x}");
    }
    hex
}

#[cfg(test)]
// Extension comparisons here are intentionally case-sensitive โ€” every
// sidecar filename is produced by our own writer and thus lowercase.
#[allow(clippy::case_sensitive_file_extension_comparisons)]
mod tests {
    use super::*;

    #[test]
    fn test_sha256_known_value() {
        // SHA-256 of empty string
        let hash = sha256_hex(b"");
        assert_eq!(
            hash,
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        );
    }

    #[test]
    fn test_sha256_hello() {
        let hash = sha256_hex(b"hello");
        assert_eq!(
            hash,
            "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
        );
    }

    #[test]
    fn test_sha512_known_value() {
        // SHA-512 of empty string (NIST test vector).
        let hash = sha512_hex(b"");
        assert_eq!(
            hash,
            "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce\
             47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"
        );
    }

    #[test]
    fn test_sha512_hello() {
        let hash = sha512_hex(b"hello");
        assert_eq!(
            hash,
            "9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca7\
             2323c3d99ba5c11d7c7acc6e14b8c5da0c4663475c2e5c3adef46f73bcdec043"
        );
    }

    #[test]
    fn test_sha3_512_known_value() {
        // SHA3-512 of empty string
        let hash = sha3_512_hex(b"");
        assert_eq!(
            hash,
            "a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615\
             b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26"
        );
    }

    #[test]
    fn test_generate_hashes_legacy() {
        let (sha256, sha3) = generate_hashes(b"test data");
        assert_eq!(sha256.len(), 64); // 256 bits = 32 bytes = 64 hex chars
        assert_eq!(sha3.len(), 128); // 512 bits = 64 bytes = 128 hex chars
    }

    #[test]
    fn test_generate_all_hashes_triplet() {
        let (sha256, sha512, sha3) = generate_all_hashes(b"test data");
        assert_eq!(sha256.len(), 64);
        assert_eq!(sha512.len(), 128);
        assert_eq!(sha3.len(), 128);
        // Three distinct digests for the same input.
        assert_ne!(sha256, sha512);
        assert_ne!(sha512, sha3);
        assert_ne!(sha256, sha3);
    }

    #[test]
    fn test_deterministic() {
        let data = b"CSAF document content";
        let (h1_256, h1_512, h1_3) = generate_all_hashes(data);
        let (h2_256, h2_512, h2_3) = generate_all_hashes(data);
        assert_eq!(h1_256, h2_256);
        assert_eq!(h1_512, h2_512);
        assert_eq!(h1_3, h2_3);
    }

    #[test]
    fn test_write_sidecar_files() {
        let dir = tempfile::tempdir().expect("tmpdir failed");
        let data = b"{\"test\": true}";
        let dd = DataDir::open(dir.path()).expect("open base");
        dd.write("test.json", data).expect("write json");

        write_sidecar_files(
            &dd,
            "test.json",
            data,
            SidecarHashes {
                sha256: true,
                sha512: true,
                sha3_512: true,
            },
        )
        .expect("sidecar write failed");

        let sha256_path = dir.path().join("test.json.sha-256");
        let sha512_path = dir.path().join("test.json.sha-512");
        let sha3_path = dir.path().join("test.json.sha3-512");

        assert!(sha256_path.exists());
        assert!(sha512_path.exists());
        assert!(sha3_path.exists());

        let sha256_content = std::fs::read_to_string(&sha256_path).expect("read failed");
        assert!(sha256_content.contains("test.json"));
        assert!(sha256_content.contains("  ")); // GNU format: hash + two spaces + filename

        // Guard against regression to the unhyphenated legacy form.
        assert!(!dir.path().join("test.json.sha256").exists());
        assert!(!dir.path().join("test.json.sha512").exists());
    }

    #[test]
    fn test_write_only_sha256() {
        let dir = tempfile::tempdir().expect("tmpdir failed");
        let data = b"{}";
        let dd = DataDir::open(dir.path()).expect("open base");
        dd.write("test.json", data).expect("write json");

        write_sidecar_files(
            &dd,
            "test.json",
            data,
            SidecarHashes {
                sha256: true,
                sha512: false,
                sha3_512: false,
            },
        )
        .expect("sidecar write failed");

        assert!(dir.path().join("test.json.sha-256").exists());
        assert!(!dir.path().join("test.json.sha-512").exists());
        assert!(!dir.path().join("test.json.sha3-512").exists());
    }

    #[test]
    fn test_write_only_sha512() {
        let dir = tempfile::tempdir().expect("tmpdir failed");
        let data = b"{}";
        let dd = DataDir::open(dir.path()).expect("open base");
        dd.write("test.json", data).expect("write json");

        write_sidecar_files(
            &dd,
            "test.json",
            data,
            SidecarHashes {
                sha256: false,
                sha512: true,
                sha3_512: false,
            },
        )
        .expect("sidecar write failed");

        assert!(!dir.path().join("test.json.sha-256").exists());
        assert!(dir.path().join("test.json.sha-512").exists());
        assert!(!dir.path().join("test.json.sha3-512").exists());
    }

    #[test]
    fn test_write_sidecar_files_for_redb() {
        let dir = tempfile::tempdir().expect("tmpdir failed");
        let data = b"dummy-redb-bytes";
        let dd = DataDir::open(dir.path()).expect("open base");
        dd.write("csaf.redb", data).expect("write redb");

        let written = write_sidecar_files_for(
            &dd,
            "csaf.redb",
            data,
            SidecarHashes {
                sha256: true,
                sha512: true,
                sha3_512: true,
            },
        )
        .expect("sidecar write failed");

        assert_eq!(
            written,
            vec![
                "csaf.redb.sha-256".to_string(),
                "csaf.redb.sha-512".to_string(),
                "csaf.redb.sha3-512".to_string(),
            ]
        );
        assert!(dir.path().join("csaf.redb.sha-256").exists());
        assert!(dir.path().join("csaf.redb.sha-512").exists());
        assert!(dir.path().join("csaf.redb.sha3-512").exists());

        let sha_content =
            std::fs::read_to_string(dir.path().join("csaf.redb.sha-256")).expect("read");
        assert!(sha_content.contains("csaf.redb"));
        assert!(sha_content.contains("  "));
        assert!(sha_content.contains(&sha256_hex(data)));

        let sha512_content =
            std::fs::read_to_string(dir.path().join("csaf.redb.sha-512")).expect("read");
        assert!(sha512_content.contains(&sha512_hex(data)));
    }

    #[test]
    fn test_write_sidecar_files_for_skip_sha3() {
        let dir = tempfile::tempdir().expect("tmpdir failed");
        let data = b"dummy-sqlite";
        let dd = DataDir::open(dir.path()).expect("open base");
        dd.write("csaf.sqlite", data).expect("write sqlite");

        let written = write_sidecar_files_for(
            &dd,
            "csaf.sqlite",
            data,
            SidecarHashes {
                sha256: true,
                sha512: true,
                sha3_512: false,
            },
        )
        .expect("sidecar write");
        assert_eq!(
            written,
            vec![
                "csaf.sqlite.sha-256".to_string(),
                "csaf.sqlite.sha-512".to_string(),
            ]
        );
        assert!(!dir.path().join("csaf.sqlite.sha3-512").exists());
    }

    #[test]
    fn test_write_sidecar_files_for_skip_all_but_sha3() {
        let dir = tempfile::tempdir().expect("tmpdir failed");
        let data = b"x";
        let dd = DataDir::open(dir.path()).expect("open base");
        dd.write("evidence.bin", data).expect("write evidence");

        let written = write_sidecar_files_for(
            &dd,
            "evidence.bin",
            data,
            SidecarHashes {
                sha256: false,
                sha512: false,
                sha3_512: true,
            },
        )
        .expect("sidecar write");
        assert_eq!(written, vec!["evidence.bin.sha3-512".to_string()]);
        assert!(dir.path().join("evidence.bin.sha3-512").exists());
    }

    #[test]
    fn test_extension_uses_hyphenated_form_only() {
        // Regression guard for the 0.3.0 rename: no sidecar may ever be
        // emitted with the unhyphenated extensions `.sha256` / `.sha512`.
        let dir = tempfile::tempdir().expect("tmpdir failed");
        let dd = DataDir::open(dir.path()).expect("open base");
        dd.write("payload.json", b"payload").expect("write json");

        write_sidecar_files(
            &dd,
            "payload.json",
            b"payload",
            SidecarHashes {
                sha256: true,
                sha512: true,
                sha3_512: true,
            },
        )
        .expect("sidecar write");

        for entry in std::fs::read_dir(dir.path()).expect("readdir") {
            let name = entry.unwrap().file_name().to_string_lossy().to_string();
            // Only the hyphenated forms are legal.
            assert!(
                name.ends_with(".json")
                    || name.ends_with(".json.sha-256")
                    || name.ends_with(".json.sha-512")
                    || name.ends_with(".json.sha3-512"),
                "unexpected sidecar extension: {name}"
            );
            assert!(
                !(name.ends_with(".sha256") || name.ends_with(".sha512")),
                "legacy unhyphenated form leaked: {name}"
            );
        }
    }

    #[test]
    fn test_sidecar_matches_csaf_file() {
        let json = include_str!("../../../test/csaf/2026/003/ndaal-sa-2026-003.json");
        let (sha256, sha512, sha3) = generate_all_hashes(json.as_bytes());

        // Verify hashes are non-empty and correct length.
        assert_eq!(sha256.len(), 64);
        assert_eq!(sha512.len(), 128);
        assert_eq!(sha3.len(), 128);

        // Verify determinism with same content.
        let (sha256_again, sha512_again, sha3_again) = generate_all_hashes(json.as_bytes());
        assert_eq!(sha256, sha256_again);
        assert_eq!(sha512, sha512_again);
        assert_eq!(sha3, sha3_again);
    }
}