1use std::{error::Error, fmt, sync::Arc};
12
13use regex::Regex;
14
15use crate::{remediation::Remediation, severity::Severity, validators::dispatch::ValidatorKind};
16
17#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
34#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
35pub struct RuleId(Arc<str>);
36
37impl RuleId {
38 #[must_use]
40 pub fn as_str(&self) -> &str {
41 &self.0
42 }
43}
44
45impl AsRef<str> for RuleId {
46 fn as_ref(&self) -> &str {
47 self.as_str()
48 }
49}
50
51impl From<&str> for RuleId {
52 fn from(value: &str) -> Self {
53 Self(Arc::from(value))
54 }
55}
56
57impl From<String> for RuleId {
58 fn from(value: String) -> Self {
59 Self(Arc::from(value))
60 }
61}
62
63impl From<Box<str>> for RuleId {
64 fn from(value: Box<str>) -> Self {
65 Self(Arc::from(value))
66 }
67}
68
69impl From<Arc<str>> for RuleId {
70 fn from(value: Arc<str>) -> Self {
71 Self(value)
72 }
73}
74
75impl fmt::Display for RuleId {
76 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
77 formatter.write_str(self.as_str())
78 }
79}
80
81#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
85#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
86#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
87pub enum RuleKind {
88 Literal,
90
91 Prefix,
96
97 Suffix,
102
103 Pattern,
105}
106
107#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
117pub struct RuleSpec {
118 id: &'static str,
119 kind: RuleKind,
120 value: &'static str,
121 severity: Severity,
122 validator: ValidatorKind,
123 remediation: Option<Remediation>,
124 capture: Option<&'static str>,
125}
126
127impl RuleSpec {
128 #[must_use]
130 pub const fn literal(id: &'static str, literal: &'static str, severity: Severity) -> Self {
131 Self {
132 id,
133 kind: RuleKind::Literal,
134 value: literal,
135 severity,
136 validator: ValidatorKind::None,
137 remediation: None,
138 capture: None,
139 }
140 }
141
142 #[must_use]
144 pub const fn prefix(id: &'static str, prefix: &'static str, severity: Severity) -> Self {
145 Self {
146 id,
147 kind: RuleKind::Prefix,
148 value: prefix,
149 severity,
150 validator: ValidatorKind::None,
151 remediation: None,
152 capture: None,
153 }
154 }
155
156 #[must_use]
158 pub const fn suffix(id: &'static str, suffix: &'static str, severity: Severity) -> Self {
159 Self {
160 id,
161 kind: RuleKind::Suffix,
162 value: suffix,
163 severity,
164 validator: ValidatorKind::None,
165 remediation: None,
166 capture: None,
167 }
168 }
169
170 #[must_use]
175 pub const fn pattern(id: &'static str, pattern: &'static str, severity: Severity) -> Self {
176 Self {
177 id,
178 kind: RuleKind::Pattern,
179 value: pattern,
180 severity,
181 validator: ValidatorKind::None,
182 remediation: None,
183 capture: None,
184 }
185 }
186
187 pub(crate) const fn captured_pattern(
194 id: &'static str,
195 pattern: &'static str,
196 capture: &'static str,
197 severity: Severity,
198 ) -> Self {
199 Self {
200 id,
201 kind: RuleKind::Pattern,
202 value: pattern,
203 severity,
204 validator: ValidatorKind::None,
205 remediation: None,
206 capture: Some(capture),
207 }
208 }
209
210 #[must_use]
212 pub const fn id(self) -> &'static str {
213 self.id
214 }
215
216 #[must_use]
218 pub const fn kind(self) -> RuleKind {
219 self.kind
220 }
221
222 #[must_use]
224 pub const fn value(self) -> &'static str {
225 self.value
226 }
227
228 #[must_use]
230 pub const fn severity(self) -> Severity {
231 self.severity
232 }
233
234 #[must_use]
236 pub const fn remediation(self) -> Option<Remediation> {
237 self.remediation
238 }
239
240 #[must_use]
242 pub const fn with_remediation(mut self, remediation: Remediation) -> Self {
243 self.remediation = Some(remediation);
244 self
245 }
246
247 pub(crate) const fn with_validator(mut self, validator: ValidatorKind) -> Self {
252 self.validator = validator;
253 self
254 }
255
256 pub fn to_rule(self) -> Result<Rule, RuleError> {
263 let rule = match (self.kind, self.capture) {
264 (RuleKind::Literal, None) => Rule::literal(self.id, self.value, self.severity),
265 (RuleKind::Prefix, None) => Rule::prefix(self.id, self.value, self.severity),
266 (RuleKind::Suffix, None) => Rule::suffix(self.id, self.value, self.severity),
267 (RuleKind::Pattern, None) => Rule::pattern(self.id, self.value, self.severity)?,
268 (RuleKind::Pattern, Some(capture)) => {
269 Rule::captured_pattern(self.id, self.value, capture, self.severity)?
270 }
271 (_, Some(_)) => unreachable!("only pattern specifications support captures"),
272 };
273
274 let rule = if let Some(remediation) = self.remediation {
275 rule.with_remediation(remediation)
276 } else {
277 rule
278 };
279
280 Ok(rule.with_validator(self.validator))
281 }
282}
283
284#[derive(Debug, Clone)]
286pub(crate) enum Matcher {
287 Literal(Box<str>),
288 Prefix(Box<str>),
289 Suffix(Box<str>),
290 Pattern {
291 regex: Regex,
292 capture: Option<usize>,
293 },
294}
295
296#[derive(Debug, Clone)]
306pub struct Rule {
307 pub(crate) id: RuleId,
308 pub(crate) severity: Severity,
309 pub(crate) validator: ValidatorKind,
310 pub(crate) matcher: Matcher,
311 pub(crate) remediation: Option<Remediation>,
312}
313
314impl Rule {
315 #[must_use]
319 pub fn literal(
320 id: impl Into<RuleId>,
321 literal: impl Into<Box<str>>,
322 severity: Severity,
323 ) -> Self {
324 Self {
325 id: id.into(),
326 severity,
327 validator: ValidatorKind::None,
328 matcher: Matcher::Literal(literal.into()),
329 remediation: None,
330 }
331 }
332
333 #[must_use]
339 pub fn prefix(id: impl Into<RuleId>, prefix: impl Into<Box<str>>, severity: Severity) -> Self {
340 Self {
341 id: id.into(),
342 severity,
343 validator: ValidatorKind::None,
344 matcher: Matcher::Prefix(prefix.into()),
345 remediation: None,
346 }
347 }
348
349 #[must_use]
354 pub fn suffix(id: impl Into<RuleId>, suffix: impl Into<Box<str>>, severity: Severity) -> Self {
355 Self {
356 id: id.into(),
357 severity,
358 validator: ValidatorKind::None,
359 matcher: Matcher::Suffix(suffix.into()),
360 remediation: None,
361 }
362 }
363
364 pub fn pattern(
377 id: impl Into<RuleId>,
378 pattern: impl AsRef<str>,
379 severity: Severity,
380 ) -> Result<Self, RuleError> {
381 let pattern = Regex::new(pattern.as_ref()).map_err(RuleError::InvalidPattern)?;
382
383 Ok(Self {
384 id: id.into(),
385 severity,
386 validator: ValidatorKind::None,
387 remediation: None,
388 matcher: Matcher::Pattern {
389 regex: pattern,
390 capture: None,
391 },
392 })
393 }
394
395 pub(crate) fn captured_pattern(
401 id: impl Into<RuleId>,
402 pattern: impl AsRef<str>,
403 capture: impl AsRef<str>,
404 severity: Severity,
405 ) -> Result<Self, RuleError> {
406 let regex = Regex::new(pattern.as_ref()).map_err(RuleError::InvalidPattern)?;
407 let capture_name = capture.as_ref();
408 let capture_index = regex
409 .capture_names()
410 .position(|name| name == Some(capture_name))
411 .ok_or_else(|| RuleError::MissingCaptureGroup {
412 name: capture_name.into(),
413 })?;
414
415 Ok(Self {
416 id: id.into(),
417 severity,
418 validator: ValidatorKind::None,
419 remediation: None,
420 matcher: Matcher::Pattern {
421 regex,
422 capture: Some(capture_index),
423 },
424 })
425 }
426
427 pub(crate) const fn with_validator(mut self, validator: ValidatorKind) -> Self {
433 self.validator = validator;
434 self
435 }
436
437 #[must_use]
439 pub fn id(&self) -> &RuleId {
440 &self.id
441 }
442
443 #[must_use]
445 pub const fn severity(&self) -> Severity {
446 self.severity
447 }
448
449 #[must_use]
451 pub const fn remediation(&self) -> Option<Remediation> {
452 self.remediation
453 }
454
455 #[must_use]
457 pub fn with_remediation(mut self, remediation: Remediation) -> Self {
458 self.remediation = Some(remediation);
459 self
460 }
461}
462
463impl fmt::Display for Rule {
464 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
465 self.id.fmt(formatter)
466 }
467}
468
469#[derive(Debug)]
474pub enum RuleError {
475 InvalidPattern(regex::Error),
477
478 MissingCaptureGroup {
481 name: Box<str>,
483 },
484}
485
486impl fmt::Display for RuleError {
487 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
488 match self {
489 Self::InvalidPattern(error) => write!(formatter, "invalid rule pattern: {error}"),
490 Self::MissingCaptureGroup { name } => {
491 write!(formatter, "missing named capture group `{name}`")
492 }
493 }
494 }
495}
496
497impl Error for RuleError {
498 fn source(&self) -> Option<&(dyn Error + 'static)> {
499 match self {
500 Self::InvalidPattern(error) => Some(error),
501 Self::MissingCaptureGroup { .. } => None,
502 }
503 }
504}
505
506#[cfg(test)]
507mod tests {
508 use super::*;
509
510 #[test]
511 fn rule_id_supports_owned_and_borrowed_strings() {
512 let borrowed = RuleId::from("borrowed");
513 let owned = RuleId::from(String::from("owned"));
514
515 assert_eq!(borrowed.as_str(), "borrowed");
516 assert_eq!(owned.as_str(), "owned");
517 }
518
519 #[test]
520 fn static_literal_spec_converts_to_owned_rule() {
521 let rule = RuleSpec::literal("literal", "SECRET", Severity::High)
522 .to_rule()
523 .expect("literal specification should convert");
524
525 assert_eq!(rule.id().as_str(), "literal");
526 assert_eq!(rule.severity(), Severity::High);
527 }
528
529 #[test]
530 fn static_spec_preserves_internal_validator() {
531 let rule = RuleSpec::prefix("github", "ghp_", Severity::Critical)
532 .with_validator(ValidatorKind::GitHub)
533 .to_rule()
534 .expect("prefix specification should convert");
535
536 assert_eq!(rule.validator, ValidatorKind::GitHub);
537 }
538
539 #[test]
540 fn captured_pattern_resolves_named_group_once() {
541 let rule = RuleSpec::captured_pattern(
542 "assignment",
543 r#"KEY=(?P<value>[A-Za-z0-9_]+)"#,
544 "value",
545 Severity::High,
546 )
547 .to_rule()
548 .expect("named capture should resolve");
549
550 assert!(matches!(
551 rule.matcher,
552 Matcher::Pattern {
553 capture: Some(1),
554 ..
555 }
556 ));
557 }
558
559 #[test]
560 fn captured_pattern_rejects_missing_named_group() {
561 let error = RuleSpec::captured_pattern(
562 "assignment",
563 r#"KEY=([A-Za-z0-9_]+)"#,
564 "value",
565 Severity::High,
566 )
567 .to_rule()
568 .expect_err("missing capture should fail");
569
570 assert!(matches!(error, RuleError::MissingCaptureGroup { .. }));
571 }
572
573 #[test]
574 fn invalid_pattern_is_rejected_during_rule_construction() {
575 let error =
576 Rule::pattern("invalid", "(", Severity::High).expect_err("invalid regex should fail");
577
578 assert!(matches!(error, RuleError::InvalidPattern(_)));
579 }
580}