1use crate::detectors::built_in_ids;
17use crate::error::SecretScanErrorCode;
18use crate::json::{self, Value};
19use crate::types::is_identifier;
20
21const DETECTOR_IDS_MAX: usize = 256;
23pub(crate) const PII_ADAPTER_ID: &str = "pii-domain";
25
26#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
27pub(crate) enum Mode {
28 #[default]
29 All,
30 Include,
31 Exclude,
32}
33
34#[derive(Clone, Debug, Default, PartialEq, Eq)]
51pub struct DetectionSelection {
52 pub(crate) mode: Mode,
53 ids: Vec<String>,
54}
55
56impl DetectionSelection {
57 #[must_use]
59 pub const fn all() -> Self {
60 Self {
61 mode: Mode::All,
62 ids: Vec::new(),
63 }
64 }
65
66 #[must_use]
68 pub fn include<I, S>(ids: I) -> Self
69 where
70 I: IntoIterator<Item = S>,
71 S: Into<String>,
72 {
73 Self {
74 mode: Mode::Include,
75 ids: ids.into_iter().map(Into::into).collect(),
76 }
77 }
78
79 #[must_use]
82 pub fn exclude<I, S>(ids: I) -> Self
83 where
84 I: IntoIterator<Item = S>,
85 S: Into<String>,
86 {
87 Self {
88 mode: Mode::Exclude,
89 ids: ids.into_iter().map(Into::into).collect(),
90 }
91 }
92
93 pub fn from_json(json: &str) -> Result<Self, DetectionConfigError> {
105 let value = json::parse(json).ok_or(DetectionConfigError::class(CLASS_WRONG_TYPE, None))?;
106 selection_from_value(&value).map_err(Fault::error)
107 }
108
109 #[must_use]
112 pub fn is_all(&self) -> bool {
113 self.mode == Mode::All || (self.mode == Mode::Exclude && self.ids.is_empty())
114 }
115
116 #[must_use]
118 pub const fn mode(&self) -> &'static str {
119 match self.mode {
120 Mode::All => "all-included",
121 Mode::Include => "include",
122 Mode::Exclude => "exclude",
123 }
124 }
125
126 pub fn ids(&self) -> impl Iterator<Item = &str> {
128 self.ids.iter().map(String::as_str)
129 }
130}
131
132pub(crate) const CLASS_UNKNOWN_FIELD: &str = "UNKNOWN_FIELD";
133pub(crate) const CLASS_WRONG_TYPE: &str = "WRONG_TYPE";
134pub(crate) const CLASS_TOO_MANY: &str = "TOO_MANY_DETECTOR_IDS";
135pub(crate) const CLASS_IDENTIFIER: &str = "INVALID_IDENTIFIER";
136pub(crate) const CLASS_UNSUPPORTED: &str = "DETECTION_SELECTION_UNSUPPORTED";
137pub(crate) const CLASS_DUPLICATE: &str = "DUPLICATE_DETECTOR_ID";
138pub(crate) const CLASS_NOT_SELECTABLE: &str = "DETECTOR_NOT_SELECTABLE";
139pub(crate) const CLASS_NOT_INCLUDED: &str = "DETECTOR_NOT_INCLUDED";
140pub(crate) const CLASS_UNKNOWN_ID: &str = "UNKNOWN_DETECTOR_ID";
141pub(crate) const CLASS_CONFLICT: &str = "DETECTION_SELECTOR_CONFLICT";
142pub(crate) const CLASS_EMPTY: &str = "EMPTY_DETECTION_SET";
143
144#[derive(Clone, Copy, Debug, PartialEq, Eq)]
154pub struct DetectionConfigError {
155 code: SecretScanErrorCode,
156 class: &'static str,
157 index: Option<usize>,
158}
159
160impl DetectionConfigError {
161 const fn class(class: &'static str, index: Option<usize>) -> Self {
162 let code = if matches!(class.as_bytes(), b"EMPTY_DETECTION_SET") {
163 SecretScanErrorCode::EmptyDetectionSet
164 } else {
165 SecretScanErrorCode::InvalidDetectionConfig
166 };
167 Self { code, class, index }
168 }
169
170 #[must_use]
173 pub const fn code(self) -> SecretScanErrorCode {
174 self.code
175 }
176
177 #[must_use]
179 pub const fn class_name(self) -> &'static str {
180 self.class
181 }
182
183 #[must_use]
186 pub const fn index(self) -> Option<usize> {
187 self.index
188 }
189}
190
191impl std::fmt::Display for DetectionConfigError {
192 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
193 formatter.write_str(self.code.message())
194 }
195}
196
197impl std::error::Error for DetectionConfigError {}
198
199impl From<DetectionConfigError> for crate::SecretScanError {
200 fn from(error: DetectionConfigError) -> Self {
201 error.code.into()
202 }
203}
204
205#[derive(Clone, Copy)]
208pub(crate) struct Fault {
209 pub(crate) class: &'static str,
210 array: Option<&'static str>,
211 index: Option<usize>,
212}
213
214impl Fault {
215 const fn new(class: &'static str) -> Self {
216 Self {
217 class,
218 array: None,
219 index: None,
220 }
221 }
222
223 const fn at(class: &'static str, array: &'static str, index: usize) -> Self {
224 Self {
225 class,
226 array: Some(array),
227 index: Some(index),
228 }
229 }
230
231 const fn error(self) -> DetectionConfigError {
232 DetectionConfigError::class(self.class, self.index)
233 }
234
235 pub(crate) fn path(self) -> String {
236 match (self.array, self.index) {
237 (None, Some(index)) if self.class == CLASS_UNKNOWN_FIELD => {
239 format!("detection.@{index}")
240 }
241 (Some(array), Some(index)) => format!("detection.{array}[{index}]"),
242 (Some(array), None) => format!("detection.{array}"),
243 _ => "detection".to_owned(),
244 }
245 }
246}
247
248pub(crate) fn selection_from_value(value: &Value) -> Result<DetectionSelection, Fault> {
251 let Value::Object(members) = value else {
252 return Err(Fault::new(CLASS_WRONG_TYPE));
253 };
254 let mut include: Option<&Value> = None;
255 let mut exclude: Option<&Value> = None;
256 for (position, (name, member)) in members.iter().enumerate() {
257 match name.as_str() {
258 "include" => include = Some(member),
259 "exclude" => exclude = Some(member),
260 _ => {
261 return Err(Fault {
262 class: CLASS_UNKNOWN_FIELD,
263 array: None,
264 index: Some(position),
265 });
266 }
267 }
268 }
269 let list = |member: &Value, array: &'static str| -> Result<Vec<String>, Fault> {
270 let Value::Array(items) = member else {
271 return Err(Fault {
272 class: CLASS_WRONG_TYPE,
273 array: Some(array),
274 index: None,
275 });
276 };
277 let mut ids = Vec::with_capacity(items.len().min(DETECTOR_IDS_MAX));
278 for (index, item) in items.iter().enumerate() {
279 let Value::Str(id) = item else {
280 return Err(Fault::at(CLASS_WRONG_TYPE, array, index));
281 };
282 ids.push(id.clone());
283 }
284 if ids.len() > DETECTOR_IDS_MAX {
285 return Err(Fault {
286 class: CLASS_TOO_MANY,
287 array: Some(array),
288 index: None,
289 });
290 }
291 if let Some(index) = ids.iter().position(|id| !is_identifier(id)) {
292 return Err(Fault::at(CLASS_IDENTIFIER, array, index));
293 }
294 Ok(ids)
295 };
296 match (include, exclude) {
297 (Some(_), Some(_)) => Err(Fault::new(CLASS_CONFLICT)),
298 (Some(member), None) => Ok(DetectionSelection::include(list(member, "include")?)),
299 (None, Some(member)) => Ok(DetectionSelection::exclude(list(member, "exclude")?)),
300 (None, None) => Ok(DetectionSelection::all()),
301 }
302}
303
304pub(crate) struct PlanEntry<'a> {
306 pub(crate) id: &'a str,
307 pub(crate) built_in: bool,
309}
310
311pub(crate) fn plan_selection(
319 selection: &DetectionSelection,
320 entries: &[PlanEntry<'_>],
321) -> Result<Vec<bool>, DetectionConfigError> {
322 let included: Vec<&str> = entries
323 .iter()
324 .filter(|entry| entry.built_in)
325 .map(|entry| entry.id)
326 .collect();
327 let named = judge(selection, &included, |id| {
328 id == PII_ADAPTER_ID
329 || entries
330 .iter()
331 .any(|entry| !entry.built_in && entry.id == id)
332 })
333 .map_err(Fault::error)?;
334 let keep: Vec<bool> = entries
335 .iter()
336 .map(|entry| {
337 !entry.built_in
338 || match selection.mode {
339 Mode::All => true,
340 Mode::Include => named.contains(&entry.id),
341 Mode::Exclude => !named.contains(&entry.id),
342 }
343 })
344 .collect();
345 if selection.mode != Mode::All && !keep.iter().any(|kept| *kept) {
346 return Err(DetectionConfigError::class(CLASS_EMPTY, None));
347 }
348 Ok(keep)
349}
350
351pub(crate) fn judge<'a>(
354 selection: &'a DetectionSelection,
355 included: &[&str],
356 not_selectable: impl Fn(&str) -> bool,
357) -> Result<Vec<&'a str>, Fault> {
358 let array = match selection.mode {
359 Mode::Exclude => "exclude",
360 _ => "include",
361 };
362 let mut named: Vec<&str> = Vec::new();
365 for (index, id) in selection.ids.iter().enumerate() {
366 let id = id.as_str();
367 let class = if named.contains(&id) {
368 CLASS_DUPLICATE
369 } else if included.contains(&id) {
370 named.push(id);
371 continue;
372 } else if not_selectable(id) {
373 CLASS_NOT_SELECTABLE
374 } else if built_in_ids().any(|known| known == id) {
375 CLASS_NOT_INCLUDED
376 } else {
377 CLASS_UNKNOWN_ID
378 };
379 return Err(Fault::at(class, array, index));
380 }
381 Ok(named)
382}
383
384impl DetectionSelection {
385 pub(crate) fn enabled_of<'a>(&self, included: &[&'a str]) -> Result<Vec<&'a str>, Fault> {
389 let named = judge(self, included, |id| id == PII_ADAPTER_ID)?;
390 Ok(included
391 .iter()
392 .copied()
393 .filter(|id| match self.mode {
394 Mode::All => true,
395 Mode::Include => named.contains(id),
396 Mode::Exclude => !named.contains(id),
397 })
398 .collect())
399 }
400}