csaf-core 0.3.1

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
// 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 std::path::Path;

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

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))
}

/// Write sidecar hash files alongside a CSAF JSON file.
///
/// Creates `{path}.sha-256`, `{path}.sha-512`, and/or `{path}.sha3-512`
/// files containing the hex digest followed by two spaces and the
/// filename (GNU coreutils format).
///
/// # Errors
///
/// Returns an I/O error if file writing fails.
pub fn write_sidecar_files(
    json_path: &Path,
    data: &[u8],
    write_sha256: bool,
    write_sha512: bool,
    write_sha3_512: bool,
) -> Result<()> {
    let filename = json_path
        .file_name()
        .map(|f| f.to_string_lossy().to_string())
        .unwrap_or_default();

    if write_sha256 {
        let hash = sha256_hex(data);
        let sidecar_path = json_path.with_extension("json.sha-256");
        let content = format!("{hash}  {filename}\n");
        std::fs::write(&sidecar_path, content)?;
    }

    if write_sha512 {
        let hash = sha512_hex(data);
        let sidecar_path = json_path.with_extension("json.sha-512");
        let content = format!("{hash}  {filename}\n");
        std::fs::write(&sidecar_path, content)?;
    }

    if write_sha3_512 {
        let hash = sha3_512_hex(data);
        let sidecar_path = json_path.with_extension("json.sha3-512");
        let content = format!("{hash}  {filename}\n");
        std::fs::write(&sidecar_path, content)?;
    }

    Ok(())
}

/// Write sidecar hash files for a file with any extension.
///
/// Unlike [`write_sidecar_files`] โ€” which hard-codes `.json.sha-256` /
/// `.json.sha-512` / `.json.sha3-512` โ€” this helper preserves the file's
/// full extension and appends `.sha-256` / `.sha-512` / `.sha3-512`,
/// e.g. `csaf.redb` โ†’ `csaf.redb.sha-256`. Used by the database dump
/// pipeline to hash `.redb` and `.sqlite` dumps, and by the audit-log
/// exporter for `.md` / `.csv` / `.json` / `.sarif` payloads.
///
/// Returns the sidecar paths that were actually written (in order:
/// sha-256, sha-512, sha3-512).
///
/// # Errors
///
/// Returns an I/O error if file writing fails.
#[allow(clippy::type_complexity)]
pub fn write_sidecar_files_for(
    file_path: &Path,
    data: &[u8],
    write_sha256: bool,
    write_sha512: bool,
    write_sha3_512: bool,
) -> Result<(
    Option<std::path::PathBuf>,
    Option<std::path::PathBuf>,
    Option<std::path::PathBuf>,
)> {
    let filename = file_path
        .file_name()
        .map(|f| f.to_string_lossy().to_string())
        .unwrap_or_default();

    let mut sha256_path = None;
    let mut sha512_path = None;
    let mut sha3_path = None;

    if write_sha256 {
        let hash = sha256_hex(data);
        let mut sidecar = file_path.as_os_str().to_owned();
        sidecar.push(".sha-256");
        let sidecar_path = std::path::PathBuf::from(sidecar);
        let content = format!("{hash}  {filename}\n");
        std::fs::write(&sidecar_path, content)?;
        sha256_path = Some(sidecar_path);
    }

    if write_sha512 {
        let hash = sha512_hex(data);
        let mut sidecar = file_path.as_os_str().to_owned();
        sidecar.push(".sha-512");
        let sidecar_path = std::path::PathBuf::from(sidecar);
        let content = format!("{hash}  {filename}\n");
        std::fs::write(&sidecar_path, content)?;
        sha512_path = Some(sidecar_path);
    }

    if write_sha3_512 {
        let hash = sha3_512_hex(data);
        let mut sidecar = file_path.as_os_str().to_owned();
        sidecar.push(".sha3-512");
        let sidecar_path = std::path::PathBuf::from(sidecar);
        let content = format!("{hash}  {filename}\n");
        std::fs::write(&sidecar_path, content)?;
        sha3_path = Some(sidecar_path);
    }

    Ok((sha256_path, sha512_path, sha3_path))
}

/// 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 json_path = dir.path().join("test.json");
        let data = b"{\"test\": true}";
        std::fs::write(&json_path, data).expect("write failed");

        write_sidecar_files(&json_path, data, true, true, 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 json_path = dir.path().join("test.json");
        let data = b"{}";
        std::fs::write(&json_path, data).expect("write failed");

        write_sidecar_files(&json_path, data, true, false, 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 json_path = dir.path().join("test.json");
        let data = b"{}";
        std::fs::write(&json_path, data).expect("write failed");

        write_sidecar_files(&json_path, data, false, true, 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 redb_path = dir.path().join("csaf.redb");
        let data = b"dummy-redb-bytes";
        std::fs::write(&redb_path, data).expect("write failed");

        let (s256, s512, s3) = write_sidecar_files_for(&redb_path, data, true, true, true)
            .expect("sidecar write failed");

        let s256 = s256.expect("sha256 path");
        let s512 = s512.expect("sha512 path");
        let s3 = s3.expect("sha3 path");
        assert_eq!(s256.file_name().unwrap(), "csaf.redb.sha-256");
        assert_eq!(s512.file_name().unwrap(), "csaf.redb.sha-512");
        assert_eq!(s3.file_name().unwrap(), "csaf.redb.sha3-512");
        assert!(s256.exists());
        assert!(s512.exists());
        assert!(s3.exists());

        let sha_content = std::fs::read_to_string(&s256).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(&s512).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 path = dir.path().join("csaf.sqlite");
        let data = b"dummy-sqlite";
        std::fs::write(&path, data).expect("write failed");

        let (s256, s512, s3) =
            write_sidecar_files_for(&path, data, true, true, false).expect("sidecar write");
        assert!(s256.is_some());
        assert!(s512.is_some());
        assert!(s3.is_none());
        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 path = dir.path().join("evidence.bin");
        let data = b"x";
        std::fs::write(&path, data).expect("write failed");

        let (s256, s512, s3) =
            write_sidecar_files_for(&path, data, false, false, true).expect("sidecar write");
        assert!(s256.is_none());
        assert!(s512.is_none());
        assert!(s3.is_some());
        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 path = dir.path().join("payload.json");
        std::fs::write(&path, b"payload").expect("write failed");

        write_sidecar_files(&path, b"payload", true, true, 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);
    }
}