348 lines
11 KiB
Rust
348 lines
11 KiB
Rust
//! Presentation-neutral domain values shared by analysis adapters.
|
|
|
|
use std::{fmt, ops::Range, path::PathBuf};
|
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
/// Stable identifier for a detection rule.
|
|
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
|
pub struct RuleId(String);
|
|
|
|
impl RuleId {
|
|
/// Construct a rule identifier from validated configuration text.
|
|
pub fn new(value: impl Into<String>) -> Self {
|
|
Self(value.into())
|
|
}
|
|
|
|
/// Construct a rule identifier from a static, trusted value.
|
|
pub fn from_static(value: &'static str) -> Self {
|
|
Self(value.to_owned())
|
|
}
|
|
|
|
/// Return the identifier as text.
|
|
pub fn as_str(&self) -> &str {
|
|
&self.0
|
|
}
|
|
}
|
|
|
|
impl fmt::Display for RuleId {
|
|
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
self.0.fmt(formatter)
|
|
}
|
|
}
|
|
|
|
/// Broad family of evidence reported by a rule.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
|
#[serde(rename_all = "kebab-case")]
|
|
pub enum Category {
|
|
/// Suspicious typography or character usage.
|
|
Typography,
|
|
/// Repeated or templated writing style.
|
|
Style,
|
|
/// Prompt, response, or assistant scaffolding left in the source.
|
|
PromptLeakage,
|
|
/// Low-care patterns specific to source code.
|
|
SourceCode,
|
|
}
|
|
|
|
impl Category {
|
|
/// Return the stable kebab-case presentation name.
|
|
pub const fn as_str(self) -> &'static str {
|
|
match self {
|
|
Self::Typography => "typography",
|
|
Self::Style => "style",
|
|
Self::PromptLeakage => "prompt-leakage",
|
|
Self::SourceCode => "source-code",
|
|
}
|
|
}
|
|
}
|
|
|
|
impl fmt::Display for Category {
|
|
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
formatter.write_str(self.as_str())
|
|
}
|
|
}
|
|
|
|
/// Review severity attached to an individual configured finding.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
|
#[serde(rename_all = "lowercase")]
|
|
pub enum FindingSeverity {
|
|
/// Informational signal worth considering during review.
|
|
Advice,
|
|
/// Stronger signal that should be reviewed before acceptance.
|
|
Warning,
|
|
/// Definite policy violation under the selected configuration.
|
|
Error,
|
|
}
|
|
|
|
impl FindingSeverity {
|
|
/// Return the stable lowercase presentation name.
|
|
pub const fn as_str(self) -> &'static str {
|
|
match self {
|
|
Self::Advice => "advice",
|
|
Self::Warning => "warning",
|
|
Self::Error => "error",
|
|
}
|
|
}
|
|
}
|
|
|
|
impl fmt::Display for FindingSeverity {
|
|
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
formatter.write_str(self.as_str())
|
|
}
|
|
}
|
|
|
|
/// Confidence that configured low-care signals are present.
|
|
///
|
|
/// This is deliberately not an AI-authorship probability.
|
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
|
|
pub struct Confidence(u8);
|
|
|
|
impl Confidence {
|
|
/// Construct a confidence value, clamping values above 100.
|
|
pub const fn from_score(score: u8) -> Self {
|
|
Self(if score > 100 { 100 } else { score })
|
|
}
|
|
|
|
/// Return the normalized score in the inclusive range `0..=100`.
|
|
pub const fn score(self) -> u8 {
|
|
self.0
|
|
}
|
|
}
|
|
|
|
/// Named interpretation of a non-empty analysis score.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
|
#[serde(rename_all = "kebab-case")]
|
|
pub enum ConfidenceBand {
|
|
/// Evidence exists but remains below the configured low threshold.
|
|
BelowThreshold,
|
|
/// Score meets the configured low threshold.
|
|
Low,
|
|
/// Score meets the configured medium threshold.
|
|
Medium,
|
|
/// Score meets the configured high threshold.
|
|
High,
|
|
}
|
|
|
|
impl ConfidenceBand {
|
|
/// Return the stable kebab-case presentation name.
|
|
pub const fn as_str(self) -> &'static str {
|
|
match self {
|
|
Self::BelowThreshold => "below-threshold",
|
|
Self::Low => "low",
|
|
Self::Medium => "medium",
|
|
Self::High => "high",
|
|
}
|
|
}
|
|
}
|
|
|
|
impl fmt::Display for ConfidenceBand {
|
|
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
formatter.write_str(self.as_str())
|
|
}
|
|
}
|
|
|
|
/// Identity of the exact source snapshot being analyzed.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub enum SourceId {
|
|
/// Content supplied through standard input.
|
|
Stdin,
|
|
/// A regular file on disk.
|
|
File(PathBuf),
|
|
/// A member contained in an archive file.
|
|
ArchiveMember {
|
|
/// Path of the outer archive.
|
|
archive: PathBuf,
|
|
/// Path-like member name stored in the archive.
|
|
member: PathBuf,
|
|
},
|
|
}
|
|
|
|
impl fmt::Display for SourceId {
|
|
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
match self {
|
|
Self::Stdin => formatter.write_str("<stdin>"),
|
|
Self::File(path) => path.display().fmt(formatter),
|
|
Self::ArchiveMember { archive, member } => {
|
|
write!(formatter, "{}::{}", archive.display(), member.display())
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A non-overlapping replacement against an analyzed source snapshot.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct TextEdit {
|
|
/// Zero-based, half-open UTF-8 byte range to replace.
|
|
pub byte_span: Range<usize>,
|
|
/// Text to insert in place of the range.
|
|
pub replacement: String,
|
|
}
|
|
|
|
/// One explainable piece of evidence produced by a detection rule.
|
|
#[derive(Debug, Clone, PartialEq)]
|
|
pub struct Finding {
|
|
/// Stable rule identifier.
|
|
pub rule_id: RuleId,
|
|
/// Evidence family.
|
|
pub category: Category,
|
|
/// Configured review severity.
|
|
pub severity: FindingSeverity,
|
|
/// Concise description of the observed signal.
|
|
pub message: String,
|
|
/// Optional remediation or review guidance.
|
|
pub help: Option<String>,
|
|
/// Zero-based, half-open UTF-8 byte range in the analyzed source.
|
|
pub byte_span: Range<usize>,
|
|
/// Exact source text covered by `byte_span`.
|
|
pub matched_text: String,
|
|
/// Configured evidence weight before aggregate normalization.
|
|
pub weight: f64,
|
|
/// Optional safe replacement for this finding.
|
|
pub fix: Option<TextEdit>,
|
|
}
|
|
|
|
/// Complete deterministic analysis of one source snapshot.
|
|
#[derive(Debug, Clone, Default, PartialEq)]
|
|
pub struct Analysis {
|
|
/// Findings sorted by source offset and rule identifier.
|
|
pub findings: Vec<Finding>,
|
|
/// Aggregate confidence that configured signals are present.
|
|
pub confidence: Confidence,
|
|
/// Named score band, or no verdict when no evidence was found.
|
|
pub confidence_band: Option<ConfidenceBand>,
|
|
}
|
|
|
|
impl Analysis {
|
|
/// Summarize score, named band, and severity counts without consuming findings.
|
|
pub fn summary(&self) -> AnalysisSummary {
|
|
AnalysisSummary {
|
|
confidence_score: self.confidence.score(),
|
|
confidence_band: self.confidence_band,
|
|
findings: SeverityCounts::from_findings(&self.findings),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Compact deterministic summary of one completed analysis.
|
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
|
pub struct AnalysisSummary {
|
|
/// Normalized evidence score in `0..=100`.
|
|
pub confidence_score: u8,
|
|
/// Named band, or no verdict when the source has no evidence.
|
|
pub confidence_band: Option<ConfidenceBand>,
|
|
/// Finding totals grouped by configured severity.
|
|
pub findings: SeverityCounts,
|
|
}
|
|
|
|
/// Finding counts grouped by configured presentation severity.
|
|
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
|
pub struct SeverityCounts {
|
|
/// Informational findings.
|
|
pub advice: usize,
|
|
/// Warning findings.
|
|
pub warnings: usize,
|
|
/// Error findings.
|
|
pub errors: usize,
|
|
}
|
|
|
|
impl SeverityCounts {
|
|
/// Return the total number of findings across severities.
|
|
pub const fn total(self) -> usize {
|
|
self.advice + self.warnings + self.errors
|
|
}
|
|
|
|
fn from_findings(findings: &[Finding]) -> Self {
|
|
let mut counts = Self::default();
|
|
for finding in findings {
|
|
match finding.severity {
|
|
FindingSeverity::Advice => counts.advice += 1,
|
|
FindingSeverity::Warning => counts.warnings += 1,
|
|
FindingSeverity::Error => counts.errors += 1,
|
|
}
|
|
}
|
|
counts
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn confidence_is_bounded() {
|
|
assert_eq!(Confidence::from_score(0).score(), 0);
|
|
assert_eq!(Confidence::from_score(73).score(), 73);
|
|
assert_eq!(Confidence::from_score(255).score(), 100);
|
|
}
|
|
|
|
#[test]
|
|
fn source_id_display_distinguishes_all_source_kinds() {
|
|
assert_eq!(SourceId::Stdin.to_string(), "<stdin>");
|
|
assert_eq!(
|
|
SourceId::File(PathBuf::from("article.md")).to_string(),
|
|
"article.md"
|
|
);
|
|
assert_eq!(
|
|
SourceId::ArchiveMember {
|
|
archive: PathBuf::from("bundle.zip"),
|
|
member: PathBuf::from("docs/article.md"),
|
|
}
|
|
.to_string(),
|
|
"bundle.zip::docs/article.md"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn rule_id_has_stable_text_and_ordering() {
|
|
let first = RuleId::new("alpha-rule");
|
|
let second = RuleId::from_static("beta-rule");
|
|
|
|
assert_eq!(first.as_str(), "alpha-rule");
|
|
assert_eq!(first.to_string(), "alpha-rule");
|
|
assert!(first < second);
|
|
}
|
|
|
|
#[test]
|
|
fn analysis_summary_counts_severity_without_removing_findings() {
|
|
let analysis = Analysis {
|
|
findings: vec![
|
|
Finding {
|
|
rule_id: RuleId::from_static("advice-rule"),
|
|
category: Category::Style,
|
|
severity: FindingSeverity::Advice,
|
|
message: "advice".to_owned(),
|
|
help: None,
|
|
byte_span: 0..1,
|
|
matched_text: "a".to_owned(),
|
|
weight: 1.0,
|
|
fix: None,
|
|
},
|
|
Finding {
|
|
rule_id: RuleId::from_static("warning-rule"),
|
|
category: Category::PromptLeakage,
|
|
severity: FindingSeverity::Warning,
|
|
message: "warning".to_owned(),
|
|
help: None,
|
|
byte_span: 2..3,
|
|
matched_text: "b".to_owned(),
|
|
weight: 10.0,
|
|
fix: None,
|
|
},
|
|
],
|
|
confidence: Confidence::from_score(32),
|
|
confidence_band: Some(ConfidenceBand::Low),
|
|
};
|
|
|
|
let summary = analysis.summary();
|
|
|
|
assert_eq!(analysis.findings.len(), 2);
|
|
assert_eq!(summary.confidence_score, 32);
|
|
assert_eq!(summary.confidence_band, Some(ConfidenceBand::Low));
|
|
assert_eq!(summary.findings.advice, 1);
|
|
assert_eq!(summary.findings.warnings, 1);
|
|
assert_eq!(summary.findings.errors, 0);
|
|
assert_eq!(summary.findings.total(), analysis.findings.len());
|
|
}
|
|
}
|