use crate::compare::{
ActionComparison, ComparedFinding, ComparedPolicy, MAX_COMPARED_POLICIES, PolicyBinding,
binding_of, compare_action_policies_with_limits,
};
use crate::config::ConfigSnapshot;
use crate::error::{SecretScanError, SecretScanErrorCode};
use crate::limits::WholeInputLimits;
use crate::registry::DetectorRegistry;
#[derive(Clone, Copy, Debug)]
pub struct ConfigurationSide<'a> {
registry: Result<&'a DetectorRegistry, &'static str>,
policy: ComparedPolicy<'a>,
limits: WholeInputLimits,
digests: Option<(&'a str, &'a str)>,
}
impl<'a> ConfigurationSide<'a> {
#[must_use]
pub fn new(registry: &'a DetectorRegistry, policy: ComparedPolicy<'a>) -> Self {
Self {
registry: Ok(registry),
policy,
limits: WholeInputLimits::default(),
digests: None,
}
}
#[must_use]
pub fn failed(code: &'static str, policy: ComparedPolicy<'a>) -> Self {
Self {
registry: Err(code),
policy,
limits: WholeInputLimits::default(),
digests: None,
}
}
#[must_use]
pub const fn with_limits(mut self, limits: WholeInputLimits) -> Self {
self.limits = limits;
self
}
#[must_use]
pub fn with_snapshot(mut self, snapshot: &'a ConfigSnapshot) -> Self {
self.digests = Some((snapshot.digest(), snapshot.detection_digest()));
self
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SideStatus {
Scanned,
Limited,
Unsupported,
Error,
}
impl SideStatus {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Scanned => "scanned",
Self::Limited => "limited",
Self::Unsupported => "unsupported",
Self::Error => "error",
}
}
fn of(code: &str) -> Self {
match code {
"INPUT_LIMIT_EXCEEDED" | "FINDING_LIMIT_EXCEEDED" => Self::Limited,
"DETECTION_SELECTION_UNSUPPORTED"
| "PII_SELECTOR_UNSUPPORTED"
| "PII_SELECTOR_UNAVAILABLE" => Self::Unsupported,
_ => Self::Error,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ConfigurationResult {
digests: Option<(String, String)>,
binding: PolicyBinding,
scan: Result<ActionComparison, &'static str>,
}
impl ConfigurationResult {
#[must_use]
pub const fn policy(&self) -> &PolicyBinding {
&self.binding
}
#[must_use]
pub fn digest(&self) -> Option<&str> {
self.digests.as_ref().map(|pair| pair.0.as_str())
}
#[must_use]
pub fn detection_digest(&self) -> Option<&str> {
self.digests.as_ref().map(|pair| pair.1.as_str())
}
#[must_use]
pub fn status(&self) -> SideStatus {
self.scan
.as_ref()
.err()
.map_or(SideStatus::Scanned, |code| SideStatus::of(code))
}
#[must_use]
pub fn failure(&self) -> Option<&'static str> {
self.scan.as_ref().err().copied()
}
#[must_use]
pub fn scan(&self) -> Option<&ActionComparison> {
self.scan.as_ref().ok()
}
#[must_use]
pub fn findings(&self) -> &[ComparedFinding] {
self.scan.as_ref().map_or(&[], ActionComparison::findings)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DifferenceKind {
Added,
Removed,
Changed,
Split,
Merged,
Regrouped,
}
impl DifferenceKind {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Added => "added",
Self::Removed => "removed",
Self::Changed => "changed",
Self::Split => "split",
Self::Merged => "merged",
Self::Regrouped => "regrouped",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Correspondence {
Exact,
Overlap,
Ambiguous,
}
impl Correspondence {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Exact => "exact",
Self::Overlap => "overlap",
Self::Ambiguous => "ambiguous",
}
}
}
const CHANGE_NAMES: [&str; 6] = [
"range",
"type",
"detector",
"confidence",
"action",
"reason",
];
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ConfigurationDifference {
kind: DifferenceKind,
base: Vec<usize>,
other: Vec<usize>,
changes: u8,
}
impl ConfigurationDifference {
#[must_use]
pub const fn kind(&self) -> DifferenceKind {
self.kind
}
#[must_use]
pub fn base(&self) -> &[usize] {
&self.base
}
#[must_use]
pub fn other(&self) -> &[usize] {
&self.other
}
#[must_use]
pub const fn correspondence(&self) -> Option<Correspondence> {
match self.kind {
DifferenceKind::Added | DifferenceKind::Removed => None,
DifferenceKind::Changed if self.changes & 1 == 0 => Some(Correspondence::Exact),
DifferenceKind::Changed => Some(Correspondence::Overlap),
_ => Some(Correspondence::Ambiguous),
}
}
#[must_use]
pub const fn change_bits(&self) -> u8 {
self.changes
}
pub fn changes(&self) -> impl Iterator<Item = &'static str> + '_ {
CHANGE_NAMES
.iter()
.enumerate()
.filter(|(bit, _)| self.changes >> bit & 1 == 1)
.map(|(_, name)| *name)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ConfigurationDifferences {
entries: Vec<ConfigurationDifference>,
unchanged: usize,
}
impl ConfigurationDifferences {
#[must_use]
pub fn entries(&self) -> &[ConfigurationDifference] {
&self.entries
}
#[must_use]
pub const fn unchanged(&self) -> usize {
self.unchanged
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ConfigurationComparison {
sides: Vec<ConfigurationResult>,
differences: Vec<Option<ConfigurationDifferences>>,
}
impl ConfigurationComparison {
#[must_use]
pub fn sides(&self) -> &[ConfigurationResult] {
&self.sides
}
#[must_use]
pub fn differences(&self) -> &[Option<ConfigurationDifferences>] {
&self.differences
}
}
pub fn compare_configurations(
input: &str,
sides: &[ConfigurationSide<'_>],
) -> Result<ConfigurationComparison, SecretScanError> {
if sides.is_empty() || sides.len() > MAX_COMPARED_POLICIES {
return Err(SecretScanErrorCode::InvalidOptions.into());
}
let mut results = Vec::with_capacity(sides.len());
for side in sides {
let scan = match side.registry {
Err(code) => Err(code),
Ok(registry) => {
match compare_action_policies_with_limits(
input,
registry,
&[side.policy],
&side.limits,
) {
Ok(comparison) => Ok(comparison),
Err(error) => match error.code() {
SecretScanErrorCode::PolicyFailure
| SecretScanErrorCode::InvalidPolicyAction => return Err(error),
code => Err(code.as_str()),
},
}
}
};
results.push(ConfigurationResult {
binding: binding_of(&side.policy),
digests: side
.digests
.map(|(digest, detection)| (digest.to_owned(), detection.to_owned())),
scan,
});
}
let differences = results
.iter()
.enumerate()
.map(|(index, side)| {
(index > 0 && side.scan.is_ok() && results[0].scan.is_ok())
.then(|| relate(results[0].findings(), side.findings()))
})
.collect();
Ok(ConfigurationComparison {
sides: results,
differences,
})
}
fn relate(base: &[ComparedFinding], other: &[ComparedFinding]) -> ConfigurationDifferences {
let mut spans: Vec<(usize, usize, bool, usize)> = Vec::with_capacity(base.len() + other.len());
for (is_other, side) in [(false, base), (true, other)] {
for (position, compared) in side.iter().enumerate() {
let range = compared.finding().range();
spans.push((range.start(), range.end(), is_other, position));
}
}
spans.sort_unstable();
let mut entries = Vec::new();
let mut unchanged = 0;
let mut start = 0;
while start < spans.len() {
let mut end = spans[start].1;
let mut stop = start + 1;
while stop < spans.len() && spans[stop].0 < end {
end = end.max(spans[stop].1);
stop += 1;
}
let (mut left, mut right) = (Vec::new(), Vec::new());
for &(_, _, is_other, position) in &spans[start..stop] {
if is_other { &mut right } else { &mut left }.push(position);
}
start = stop;
let kind = match (left.len(), right.len()) {
(0, _) => DifferenceKind::Added,
(_, 0) => DifferenceKind::Removed,
(1, 1) => DifferenceKind::Changed,
(1, _) => DifferenceKind::Split,
(_, 1) => DifferenceKind::Merged,
_ => DifferenceKind::Regrouped,
};
let changes = if kind == DifferenceKind::Changed {
changed(&base[left[0]], &other[right[0]])
} else {
0
};
if kind == DifferenceKind::Changed && changes == 0 {
unchanged += 1;
continue;
}
let single = matches!(kind, DifferenceKind::Added | DifferenceKind::Removed);
let members = if kind == DifferenceKind::Added {
&right
} else {
&left
};
if single {
for &position in members {
let (base, other) = match kind {
DifferenceKind::Added => (vec![], vec![position]),
_ => (vec![position], vec![]),
};
entries.push(ConfigurationDifference {
kind,
base,
other,
changes,
});
}
} else {
entries.push(ConfigurationDifference {
kind,
base: left,
other: right,
changes,
});
}
}
ConfigurationDifferences { entries, unchanged }
}
fn changed(base: &ComparedFinding, other: &ComparedFinding) -> u8 {
let (a, b) = (base.finding(), other.finding());
let (x, y) = (&base.decisions()[0], &other.decisions()[0]);
[
a.range() != b.range(),
a.type_name() != b.type_name(),
a.detector() != b.detector(),
a.confidence() != b.confidence(),
x.action() != y.action(),
x.basis() != y.basis(),
]
.iter()
.enumerate()
.fold(0, |bits, (bit, differs)| bits | u8::from(*differs) << bit)
}