truman-core 0.1.0

Core types, filters, and parallel scanner for Truman secret detection
Documentation
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// Result of (optional) external verification of a secret.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub enum VerifiedResult {
    /// Secret was verified to be real (e.g. live API call succeeded).
    VerifiedTrue,
    /// Verification was inconclusive / not attempted.
    #[default]
    Unverified,
    /// Secret was verified to be false (e.g. live API call rejected it).
    VerifiedFalse,
}

impl VerifiedResult {
    pub fn is_verified(&self) -> bool {
        matches!(self, VerifiedResult::VerifiedTrue)
    }
}

/// Byte-exact position of a secret within a single line.
///
/// * `line` is 1-indexed.
/// * `col_start` / `col_end` are byte indices into `line_text`
///   (`col_end` is end-exclusive, as with Rust ranges / Python slices).
/// * `line_text` is the detection line: the raw file line with only the
///   trailing `\r\n` / `\n` stripped (see `scanner` docs).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Span {
    pub line: u32,
    pub col_start: usize,
    pub col_end: usize,
    pub line_text: String,
}

impl Span {
    pub fn new(line: u32, col_start: usize, col_end: usize, line_text: String) -> Self {
        Self {
            line,
            col_start,
            col_end,
            line_text,
        }
    }

    /// Return the exact matched text `line_text[col_start..col_end]`.
    ///
    /// Returns `None` if the indices are out of bounds or not on UTF-8
    /// character boundaries (defensive; detectors should always emit
    /// valid boundary indices).
    pub fn snippet(&self) -> Option<&str> {
        self.line_text.get(self.col_start..self.col_end)
    }

    /// Length of the match in bytes.
    pub fn len(&self) -> usize {
        self.col_end.saturating_sub(self.col_start)
    }

    pub fn is_empty(&self) -> bool {
        self.col_end <= self.col_start
    }
}

/// Where a finding was located.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Location {
    pub file: PathBuf,
    pub span: Span,
}

/// A single detected potential secret.
///
/// `secret` holds the plaintext and exists for library use only: it is
/// **never serialized** (see `#[serde(skip)]`). `hashed_secret` is the
/// SHA1 hex digest, which is what gets written to output.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Finding {
    pub detector: String,
    pub secret_type: String,
    #[serde(skip)]
    pub secret: String,
    pub hashed_secret: String,
    pub location: Location,
    pub verified: VerifiedResult,
}

impl Finding {
    /// Return a copy with the plaintext removed.
    ///
    /// Since `secret` is `#[serde(skip)]`, plain `serde_json::to_string`
    /// output is already redacted; this helper is for explicitly dropping
    /// the plaintext from memory (e.g. before logging / sending).
    pub fn redacted(&self) -> Self {
        let mut out = self.clone();
        out.secret = String::new();
        out
    }
}

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

    #[test]
    fn snippet_slices_exact_bytes() {
        let span = Span::new(1, 7, 11, "key = \"abcd\"".to_string());
        assert_eq!(span.snippet(), Some("abcd"));
    }

    #[test]
    fn secret_is_skipped_in_json() {
        let f = Finding {
            detector: "Stripe".to_string(),
            secret_type: "Stripe Access Key".to_string(),
            secret: "sk_live_aaaaaaaaaaaaaaaaaaaaaaaa".to_string(),
            hashed_secret: "deadbeef".to_string(),
            location: Location {
                file: PathBuf::from("a.py"),
                span: Span::new(1, 0, 5, "hello".to_string()),
            },
            verified: VerifiedResult::Unverified,
        };
        let v: serde_json::Value = serde_json::to_value(&f).unwrap();
        assert!(v.get("secret").is_none(), "plaintext must not serialize");
        assert_eq!(v["hashed_secret"], "deadbeef");
    }
}