keyhog-core 0.5.43

keyhog-core: shared data model and detector specifications for the KeyHog secret scanner
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
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
//! Scanner findings: the output type for detected secrets with location,
//! confidence, detector metadata, and optional verification status.

// Debt bucket: 16 public items predating the crate floor raising `missing_docs`
// to `warn`. Public output schema; remove once each carries a doc line.
#![allow(missing_docs)]

use serde::ser::SerializeStruct;
use serde::{Deserialize, Serialize, Serializer};
use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;

use crate::{SensitiveString, Severity};

/// SHA-256 digest of a credential.
///
/// This is intentionally distinct from other 32-byte digests in the system
/// (Merkle content hashes, detector-set hashes, verifier cache internals). A
/// credential hash can suppress findings, correlate reports, and cross detector
/// boundaries; keeping it named prevents those contracts from blending into
/// arbitrary `[u8; 32]` arrays.
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[repr(transparent)]
#[serde(transparent)]
pub struct CredentialHash(#[serde(with = "serde_hash_hex")] [u8; 32]);

impl CredentialHash {
    /// All-zero hash used only as a compatibility sentinel for historical test
    /// constructors and old serialized fixtures that omitted real hashes.
    pub const ZERO: Self = Self([0; 32]);

    /// Construct from raw SHA-256 bytes.
    #[inline]
    pub const fn from_bytes(bytes: [u8; 32]) -> Self {
        Self(bytes)
    }

    /// Borrow the raw SHA-256 bytes.
    #[inline]
    pub const fn as_bytes(&self) -> &[u8; 32] {
        &self.0
    }

    /// Return the raw SHA-256 bytes.
    #[inline]
    pub const fn into_bytes(self) -> [u8; 32] {
        self.0
    }

    /// True when this value is the historical all-zero compatibility sentinel.
    #[inline]
    pub const fn is_zero(self) -> bool {
        let mut idx = 0;
        while idx < self.0.len() {
            if self.0[idx] != 0 {
                return false;
            }
            idx += 1;
        }
        true
    }
}

impl From<[u8; 32]> for CredentialHash {
    #[inline]
    fn from(bytes: [u8; 32]) -> Self {
        Self::from_bytes(bytes)
    }
}

impl From<CredentialHash> for [u8; 32] {
    #[inline]
    fn from(hash: CredentialHash) -> Self {
        hash.into_bytes()
    }
}

impl AsRef<[u8; 32]> for CredentialHash {
    #[inline]
    fn as_ref(&self) -> &[u8; 32] {
        self.as_bytes()
    }
}

impl AsRef<[u8]> for CredentialHash {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl std::fmt::Debug for CredentialHash {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&hex_encode(self))
    }
}

/// Borrowed raw-match identity used before report-scope deduplication.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RawMatchDedupKey<'a> {
    pub detector_id: &'a str,
    pub credential: &'a str,
}

/// A raw pattern match before verification or deduplication.
///
/// `entropy` and `confidence` are stored as `f64` but are guaranteed never to
/// be `NaN` (sanitized at construction time). This keeps the manual `Eq` impl
/// reflexive, which downstream code relies on for `HashMap`/`BTreeMap` keys.
///
/// Manual `Debug` impl redacts the `credential` field - the previous
/// derive-`Debug` was a CRITICAL leak vector (any `{:?}` print, panic
/// handler, or `tracing::error!(?match)` would expose plaintext). See
/// audit kimi-wave1 finding 1.1.
#[derive(Clone, Serialize, Deserialize)]
pub struct RawMatch {
    /// Stable detector identifier.
    #[serde(with = "serde_arc_str")]
    pub detector_id: Arc<str>,
    /// Human-readable detector name.
    #[serde(with = "serde_arc_str")]
    pub detector_name: Arc<str>,
    /// Service namespace associated with the detector.
    #[serde(with = "serde_arc_str")]
    pub service: Arc<str>,
    /// Detector severity level.
    pub severity: Severity,
    /// Matched credential bytes before redaction.
    pub credential: SensitiveString,
    /// SHA-256 digest of the credential for allowlisting and deduplication.
    ///
    /// Stored as the raw 32 inline bytes (matching the verifier `CacheKey`),
    /// never the 64-char hex `String`: zero heap, half the per-finding
    /// footprint, no per-match allocation on the pre-dedup hot path. Hex
    /// encoding happens lazily at the serde/reporter boundary only.
    pub credential_hash: CredentialHash,
    /// Companion credential or context value extracted nearby.
    pub companions: std::collections::HashMap<String, String>,
    /// Source location for the match.
    pub location: MatchLocation,
    /// Shannon entropy of the matched credential (0.0 - 8.0). NaN-sanitized.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub entropy: Option<f64>,
    /// Confidence score (0.0 - 1.0). NaN-sanitized at construction.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confidence: Option<f64>,
}

impl RawMatch {
    /// Replace NaN floats with `None` so the manual `Eq` impl stays reflexive
    /// and `HashMap`/`BTreeMap` lookups don't trap. Call this on any externally
    /// constructed `RawMatch` (deserialized findings, scanner outputs).
    pub(crate) fn sanitize_floats(mut self) -> Self {
        if self.entropy.is_some_and(f64::is_nan) {
            self.entropy = None;
        }
        if self.confidence.is_some_and(f64::is_nan) {
            self.confidence = None;
        }
        self
    }
}

impl PartialEq for RawMatch {
    fn eq(&self, other: &Self) -> bool {
        // Compare every field; for the f64 options use `total_cmp` semantics so
        // NaN-vs-NaN compares equal. We additionally normalize NaN→None on
        // construction (`sanitize_floats`), but the total-ordering comparison
        // here keeps the impl sound even if a NaN slips through.
        self.detector_id == other.detector_id
            && self.detector_name == other.detector_name
            && self.service == other.service
            && self.severity == other.severity
            && self.credential == other.credential
            && self.credential_hash == other.credential_hash
            && self.companions == other.companions
            && self.location == other.location
            && opt_f64_total_eq(self.entropy, other.entropy)
            && opt_f64_total_eq(self.confidence, other.confidence)
    }
}

impl Eq for RawMatch {}

impl std::fmt::Debug for RawMatch {
    /// Redacted Debug. Replaces `derive(Debug)` which would print the raw
    /// credential plaintext. See kimi-wave1 audit finding 1.1.
    /// `credential_hash` is preserved because it's already a one-way SHA-256.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RawMatch")
            .field("detector_id", &self.detector_id)
            .field("detector_name", &self.detector_name)
            .field("service", &self.service)
            .field("severity", &self.severity)
            .field(
                "credential",
                &format_args!("<redacted {} bytes>", self.credential.len()),
            )
            .field(
                "credential_hash",
                &format_args!("{}", hex_encode(self.credential_hash)),
            )
            .field(
                "companions",
                &format_args!("<{} redacted companions>", self.companions.len()),
            )
            .field("location", &self.location)
            .field("entropy", &self.entropy)
            .field("confidence", &self.confidence)
            .finish()
    }
}

#[inline]
fn opt_f64_total_eq(a: Option<f64>, b: Option<f64>) -> bool {
    match (a, b) {
        (None, None) => true,
        (Some(x), Some(y)) => x.total_cmp(&y) == std::cmp::Ordering::Equal,
        _ => false,
    }
}

#[inline]
fn opt_f64_total_cmp(a: Option<f64>, b: Option<f64>) -> std::cmp::Ordering {
    match (a, b) {
        (None, None) => std::cmp::Ordering::Equal,
        (None, Some(_)) => std::cmp::Ordering::Less,
        (Some(_), None) => std::cmp::Ordering::Greater,
        (Some(x), Some(y)) => x.total_cmp(&y),
    }
}

fn companion_map_cmp(
    a: &std::collections::HashMap<String, String>,
    b: &std::collections::HashMap<String, String>,
) -> std::cmp::Ordering {
    if a == b {
        return std::cmp::Ordering::Equal;
    }
    match a.len().cmp(&b.len()) {
        std::cmp::Ordering::Equal => {}
        ordering => return ordering,
    }

    // Companion sets are tiny and this path runs only after every priority key
    // ties. Walk each map in lexical-key order without allocating comparator
    // scratch; the O(n²) selection cost is bounded by companion count and avoids
    // heap traffic inside BinaryHeap/sort comparators.
    let mut a_after: Option<&str> = None;
    let mut b_after: Option<&str> = None;
    for _ in 0..a.len() {
        let Some(a_entry) = a
            .iter()
            .filter(|(key, _)| a_after.is_none_or(|after| key.as_str() > after))
            .min_by(|left, right| left.0.cmp(right.0))
        else {
            return std::cmp::Ordering::Equal;
        };
        let Some(b_entry) = b
            .iter()
            .filter(|(key, _)| b_after.is_none_or(|after| key.as_str() > after))
            .min_by(|left, right| left.0.cmp(right.0))
        else {
            return std::cmp::Ordering::Equal;
        };
        match a_entry.cmp(&b_entry) {
            std::cmp::Ordering::Equal => {
                a_after = Some(a_entry.0.as_str());
                b_after = Some(b_entry.0.as_str());
            }
            ordering => return ordering,
        }
    }
    std::cmp::Ordering::Equal
}

impl PartialOrd for RawMatch {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for RawMatch {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        // Higher confidence first
        // LAW10 (both): recall-safe, a `None` confidence sorts as 0.0 (lowest)
        // for stable display ordering ONLY. Both findings remain in the result
        // set; sort position never drops a finding.
        let self_conf = self.confidence.unwrap_or(0.0); // LAW10: absent confidence => 0.0 for sort/partition ordering only; recall-safe
        let other_conf = other.confidence.unwrap_or(0.0); // LAW10: absent confidence => 0.0 for sort/partition ordering only; recall-safe

        match other_conf.total_cmp(&self_conf) {
            std::cmp::Ordering::Equal => {}
            ord => return ord,
        }

        // Then higher severity first (Critical > High > Medium > Low > Info)
        match other.severity.cmp(&self.severity) {
            std::cmp::Ordering::Equal => {}
            ord => return ord,
        }

        // Then by detector and credential.
        match self.detector_id.cmp(&other.detector_id) {
            std::cmp::Ordering::Equal => {}
            ord => return ord,
        }
        match self.credential.cmp(&other.credential) {
            std::cmp::Ordering::Equal => {}
            ord => return ord,
        }

        // Next by location (offset, then line) so the priority prefix is total
        // with respect to the dedup identity (detector, credential, offset).
        // Without this key, two matches of the same secret at different offsets
        // compare Equal, so when the capped per-chunk match heap
        // (`ScanState::push_match`) evicts among them at `max_matches_per_chunk`,
        // the survivor is chosen by insertion order, which is HashMap-iteration
        // and rayon-thread nondeterministic. A dense, repetitive chunk (e.g. the
        // concat-source throughput corpus) overflows the cap with many such
        // ties, so the finding set flickered run-to-run. Including the location
        // makes eviction content-determined: the kept set is reproducible
        // regardless of marking volume or thread interleaving.
        match self.location.offset.cmp(&other.location.offset) {
            std::cmp::Ordering::Equal => {}
            ord => return ord,
        }
        match self.location.line.cmp(&other.location.line) {
            std::cmp::Ordering::Equal => {}
            ord => return ord,
        }

        // The priority keys above intentionally determine user-visible order.
        // The remaining fields are deterministic identity tiebreakers only:
        // `Ord` must compare Equal exactly when field-wise `Eq` does, otherwise
        // BTree collections and unstable sorts can silently merge or reorder
        // distinct findings.
        self.detector_name
            .cmp(&other.detector_name)
            .then_with(|| self.service.cmp(&other.service))
            .then_with(|| self.credential_hash.cmp(&other.credential_hash))
            .then_with(|| companion_map_cmp(&self.companions, &other.companions))
            .then_with(|| self.location.source.cmp(&other.location.source))
            .then_with(|| self.location.file_path.cmp(&other.location.file_path))
            .then_with(|| self.location.commit.cmp(&other.location.commit))
            .then_with(|| self.location.author.cmp(&other.location.author))
            .then_with(|| self.location.date.cmp(&other.location.date))
            .then_with(|| opt_f64_total_cmp(self.entropy, other.entropy))
            .then_with(|| opt_f64_total_cmp(self.confidence, other.confidence))
    }
}

/// Where a credential was found: file path, line number, commit, and author.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct MatchLocation {
    /// Logical source backend, such as `filesystem` or `git`.
    #[serde(with = "serde_arc_str")]
    pub source: Arc<str>,
    /// File path, object key, or logical path when available.
    ///
    /// Paths stored here must be valid UTF-8. Source implementations that see
    /// non-UTF-8 paths should encode them into a reversible escaped string
    /// before constructing a [`MatchLocation`].
    #[serde(with = "serde_arc_str_opt")]
    pub file_path: Option<Arc<str>>,
    /// One-based line number when known.
    pub line: Option<usize>,
    /// Byte offset from the start of the source chunk.
    pub offset: usize,
    /// Commit identifier for history-derived matches.
    #[serde(with = "serde_arc_str_opt")]
    pub commit: Option<Arc<str>>,
    /// Commit author when available.
    #[serde(with = "serde_arc_str_opt")]
    pub author: Option<Arc<str>>,
    /// Commit timestamp when available.
    #[serde(with = "serde_arc_str_opt")]
    pub date: Option<Arc<str>>,
}

/// A finding after verification - the final output.
#[derive(Debug, Clone, Deserialize)]
pub struct VerifiedFinding {
    /// Stable detector identifier.
    #[serde(with = "serde_arc_str")]
    pub detector_id: Arc<str>,
    /// Human-readable detector name.
    #[serde(with = "serde_arc_str")]
    pub detector_name: Arc<str>,
    /// Service namespace associated with the detector.
    #[serde(with = "serde_arc_str")]
    pub service: Arc<str>,
    /// Detector severity level.
    pub severity: Severity,
    /// Redacted version of the credential for reporting.
    pub credential_redacted: Cow<'static, str>,
    /// SHA-256 digest of the original credential for internal correlation.
    /// Raw 32 inline bytes; hex-encoded lazily at the serde/reporter boundary.
    pub credential_hash: CredentialHash,
    /// Redacted companion credentials or context values extracted nearby.
    ///
    /// Companion values follow the same boundary rule as the primary
    /// credential: reports may expose a safe preview, never plaintext.
    #[serde(default)]
    pub companions_redacted: HashMap<String, String>,
    /// Source location for the match.
    pub location: MatchLocation,
    /// Verification result.
    pub verification: VerificationResult,
    /// Additional provider-specific metadata (e.g. account ID, scope).
    pub metadata: HashMap<String, String>,
    /// Additional duplicate locations found for this credential.
    pub additional_locations: Vec<MatchLocation>,
    /// Shannon entropy measured by the detection path, when available.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub entropy: Option<f64>,
    /// Confidence score (0.0 - 1.0) combining entropy, keyword proximity, file type, etc.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confidence: Option<f64>,
}

impl VerifiedFinding {
    /// Construct the report-safe view of a deduplicated match.
    ///
    /// This is the single conversion boundary for verifier and skipped paths:
    /// every new report field must be initialized here, while callers retain
    /// ownership of policy-specific severity and verification decisions.
    pub fn from_deduped(
        group: crate::DedupedMatch,
        severity: Severity,
        verification: VerificationResult,
        metadata: HashMap<String, String>,
    ) -> Self {
        Self {
            detector_id: group.detector_id,
            detector_name: group.detector_name,
            service: group.service,
            severity,
            credential_redacted: crate::redact(&group.credential),
            credential_hash: group.credential_hash,
            companions_redacted: redact_companions(&group.companions),
            location: group.primary_location,
            verification,
            metadata,
            additional_locations: group.additional_locations,
            entropy: group.entropy,
            confidence: group.confidence,
        }
    }
}

impl Serialize for VerifiedFinding {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let remediation =
            crate::auto_fix::remediation_for(&self.detector_id, &self.service, self.severity);
        let mut field_count = 12;
        if self.entropy.is_some() {
            field_count += 1;
        }
        if self.confidence.is_some() {
            field_count += 1;
        }
        let mut state = serializer.serialize_struct("VerifiedFinding", field_count)?;
        state.serialize_field("detector_id", self.detector_id.as_ref())?;
        state.serialize_field("detector_name", self.detector_name.as_ref())?;
        state.serialize_field("service", self.service.as_ref())?;
        state.serialize_field("severity", &self.severity)?;
        state.serialize_field("credential_redacted", self.credential_redacted.as_ref())?;
        state.serialize_field("credential_hash", &hex_encode(self.credential_hash))?;
        let sorted_companions: BTreeMap<&str, &str> = self
            .companions_redacted
            .iter()
            .map(|(key, value)| (key.as_str(), value.as_str()))
            .collect();
        state.serialize_field("companions_redacted", &sorted_companions)?;
        state.serialize_field("location", &self.location)?;
        state.serialize_field("verification", &self.verification)?;
        let sorted_metadata: BTreeMap<&str, &str> = self
            .metadata
            .iter()
            .map(|(key, value)| (key.as_str(), value.as_str()))
            .collect();
        state.serialize_field("metadata", &sorted_metadata)?;
        state.serialize_field("additional_locations", &self.additional_locations)?;
        if let Some(entropy) = self.entropy {
            state.serialize_field("entropy", &entropy)?;
        }
        if let Some(confidence) = self.confidence {
            state.serialize_field("confidence", &confidence)?;
        }
        state.serialize_field("remediation", &remediation)?;
        state.end()
    }
}

/// Result of live verification: whether the credential is active, revoked, or untested.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum VerificationResult {
    /// Credential is active and verified by the provider.
    Live,
    /// Credential is valid but has been explicitly revoked or disabled.
    Revoked,
    /// Credential was rejected by the provider (invalid password/token).
    Dead,
    /// Provider returned a rate-limit error (e.g. 429).
    RateLimited,
    /// Verification failed due to network error or timeout.
    Error(String),
    /// Detector does not support live verification.
    Unverifiable,
    /// Verification was not attempted (e.g. disabled via flag).
    Skipped,
}

impl RawMatch {
    /// Get the raw-match correlation key used before report scope is applied.
    ///
    /// This intentionally excludes location. Window/raw-span dedup uses
    /// `(detector, credential, offset)` in the scanner, while report grouping
    /// applies `DedupScope` in `core::dedup`.
    pub(crate) fn deduplication_key(&self) -> RawMatchDedupKey<'_> {
        RawMatchDedupKey {
            detector_id: &self.detector_id,
            credential: &self.credential,
        }
    }

    /// Convert into a serialization-safe DTO that never carries the plaintext
    /// credential. Use this anywhere a `RawMatch` would otherwise be written
    /// to disk, sent over the network, or rendered into a user-visible
    /// report. See kimi-wave1 audit finding 2.1 (`scan_system.rs` JSON exfil).
    pub fn to_redacted(&self) -> RedactedFinding {
        RedactedFinding {
            detector_id: self.detector_id.clone(),
            detector_name: self.detector_name.clone(),
            service: self.service.clone(),
            severity: self.severity,
            credential_redacted: crate::redact(&self.credential),
            credential_hash: self.credential_hash,
            companions_redacted: redact_companions(&self.companions),
            location: self.location.clone(),
            entropy: self.entropy,
            confidence: self.confidence,
        }
    }
}

/// Redact every companion value at the process boundary.
///
/// Keeping this transformation centralized prevents verifier, offline scan,
/// and serialization paths from accidentally diverging on companion safety.
pub fn redact_companions(
    companions: &std::collections::HashMap<String, String>,
) -> std::collections::HashMap<String, String> {
    companions
        .iter()
        .map(|(key, value)| (key.clone(), crate::redact(value).into_owned()))
        .collect()
}

/// Redacted, disk-safe view of a `RawMatch`. Carries only the SHA-256 hash
/// and a "first4...last4" preview, never the plaintext credential. This is
/// the only finding shape that should ever leave keyhog's process boundary.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RedactedFinding {
    #[serde(with = "serde_arc_str")]
    pub detector_id: Arc<str>,
    #[serde(with = "serde_arc_str")]
    pub detector_name: Arc<str>,
    #[serde(with = "serde_arc_str")]
    pub service: Arc<str>,
    pub severity: Severity,
    pub credential_redacted: Cow<'static, str>,
    /// SHA-256 digest as raw 32 inline bytes; hex-encoded at the serde boundary.
    pub credential_hash: CredentialHash,
    pub companions_redacted: HashMap<String, String>,
    pub location: MatchLocation,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub entropy: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confidence: Option<f64>,
}

/// Lower-case hex of digest bytes. The only place the hex string is materialized
/// for `CredentialHash` values (reporters, Debug).
#[inline]
pub fn hex_encode(bytes: impl AsRef<[u8]>) -> String {
    hex::encode(bytes.as_ref())
}

/// SHA-256 of a string as the `CredentialHash` domain type. This is the single
/// source for credential hashing across the workspace (scanner, dedup,
/// telemetry); hex encoding is a separate step at the serde/reporter boundary
/// via [`hex_encode`], keeping the pre-dedup hot path zero-heap.
#[inline]
pub fn sha256_hash(s: &str) -> CredentialHash {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(s.as_bytes());
    CredentialHash::from_bytes(hasher.finalize().into())
}

/// Serde adapter keeping the on-wire shape of `credential_hash` a 64-char
/// lower-case hex string while the in-memory field is raw `[u8; 32]`. This
/// preserves the documented JSON/JSONL/baseline/SARIF format (`.credential_hash`
/// consumers, `keyhogignore` `hash:` entries) with zero heap on the hot path.
pub(crate) mod serde_hash_hex {
    use std::borrow::Cow;

    use serde::{Deserialize, Deserializer, Serializer};

    pub(crate) fn serialize<S>(val: &[u8; 32], serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&super::hex_encode(val))
    }

    pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<[u8; 32], D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = Cow::<'de, str>::deserialize(deserializer)?;
        if s.len() != crate::git_lfs::SHA256_HEX_LEN {
            return Err(serde::de::Error::invalid_length(
                s.len(),
                &"64-char hex SHA-256 digest",
            ));
        }
        let mut bytes = [0_u8; 32];
        hex::decode_to_slice(s.as_bytes(), &mut bytes).map_err(serde::de::Error::custom)?;
        Ok(bytes)
    }
}

/// Convert a borrowed-or-owned string into an `Arc<str>` without an extra copy
/// when the value is already owned. Single owner shared by `serde_arc_str` and
/// `serde_arc_str_opt` deserialization.
#[inline]
fn arc_from_cow(value: Cow<'_, str>) -> Arc<str> {
    match value {
        Cow::Borrowed(value) => Arc::from(value),
        Cow::Owned(value) => Arc::from(value),
    }
}

pub(crate) mod serde_arc_str {
    use serde::{Deserialize, Deserializer, Serialize, Serializer};
    use std::borrow::Cow;
    use std::sync::Arc;

    pub(crate) fn serialize<S>(val: &Arc<str>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        val.as_ref().serialize(serializer)
    }

    pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Arc<str>, D::Error>
    where
        D: Deserializer<'de>,
    {
        Cow::<'de, str>::deserialize(deserializer).map(super::arc_from_cow)
    }
}

pub(crate) mod serde_arc_str_opt {
    use serde::{Deserialize, Deserializer, Serialize, Serializer};
    use std::borrow::Cow;
    use std::sync::Arc;

    pub(crate) fn serialize<S>(val: &Option<Arc<str>>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        val.as_ref().map(|s| s.as_ref()).serialize(serializer)
    }

    pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Option<Arc<str>>, D::Error>
    where
        D: Deserializer<'de>,
    {
        Option::<Cow<'de, str>>::deserialize(deserializer).map(|opt| opt.map(super::arc_from_cow))
    }
}

// Tests live in `tests/unit/finding_arc_str_serde_roundtrip.rs` (KH-GAP-004: no
// inline test modules in `src/`). The `arc_from_cow` deserialize helper is
// exercised end-to-end through the public `RawMatch` serde round-trip (its
// `Arc<str>` fields use `serde_arc_str`, which calls it).