use std::sync::{Arc, OnceLock};
pub use crate::detectors::selected::*;
use crate::detectors::{BUILT_IN_PACKS, LiteralMatcher};
use crate::error::{SecretScanError, SecretScanErrorCode};
use crate::registry::compile_matcher;
use crate::sha256::{sha256, to_hex};
use crate::types::is_identifier;
#[derive(Clone, Debug)]
pub struct Composition {
name: String,
pii: bool,
selected: Vec<SelectedDetector>,
id: String,
prefilter: OnceLock<Option<Arc<LiteralMatcher>>>,
}
impl Composition {
pub fn new<I>(name: &str, pii: bool, selected: I) -> Result<Self, SecretScanError>
where
I: IntoIterator<Item = SelectedDetector>,
{
let selected: Vec<SelectedDetector> = selected.into_iter().collect();
if !is_identifier(name) || selected.is_empty() {
return Err(SecretScanErrorCode::InvalidDetector.into());
}
let mut previous: Option<usize> = None;
for detector in &selected {
let position = BUILT_IN_PACKS.iter().position(|(id, _)| *id == detector.id);
match (previous, position) {
(_, None) => return Err(SecretScanErrorCode::InvalidDetector.into()),
(Some(before), Some(now)) if now <= before => {
return Err(SecretScanErrorCode::InvalidDetector.into());
}
_ => previous = position,
}
}
let mut document = String::from("{\"include\":[");
for (index, detector) in selected.iter().enumerate() {
if index > 0 {
document.push(',');
}
document.push('"');
document.push_str(detector.id);
document.push('"');
}
document.push_str("],\"name\":\"");
document.push_str(name);
document.push_str("\",\"pii\":\"");
document.push_str(if pii { "all" } else { "none" });
document.push_str("\",\"schema\":\"composition/v1\"}");
let id = format!("custom:{}", to_hex(&sha256(document.as_bytes())));
Ok(Self {
name: name.to_owned(),
pii,
selected,
id,
prefilter: OnceLock::new(),
})
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub fn id(&self) -> &str {
&self.id
}
#[must_use]
pub const fn pii(&self) -> bool {
self.pii
}
pub fn ids(&self) -> impl Iterator<Item = &str> {
self.selected.iter().map(|detector| detector.id)
}
#[must_use]
pub fn len(&self) -> usize {
self.selected.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.selected.is_empty()
}
pub(crate) fn selected(&self) -> &[SelectedDetector] {
&self.selected
}
pub(crate) fn prefilter(&self) -> Option<Arc<LiteralMatcher>> {
self.prefilter
.get_or_init(|| {
compile_matcher(
self.selected
.iter()
.map(|detector| detector.required.as_ref())
.collect(),
)
.map(Arc::new)
})
.clone()
}
}