1#![forbid(unsafe_code)]
2
3use cribra::{
15 CandidateEvidence, Confidence, DetectionMode, Explanation, Finding, Redaction, Remediation,
16 Rule, ScanReport, Scanner, SensitiveCandidate, SensitiveCandidateKind, Severity,
17 transform::{
18 PseudonymizationOptions, SynthesisOptions, TemplateOptions, pseudonymize, redact,
19 redact_with, synthesize, template, template_with,
20 },
21};
22use wasm_bindgen::{JsError, prelude::*};
23
24fn key32(key: &[u8]) -> Result<[u8; 32], JsError> {
25 key.try_into()
26 .map_err(|_| JsError::new("transformation key must contain exactly 32 bytes"))
27}
28
29fn transform_error(error: impl std::fmt::Display) -> JsError {
30 JsError::new(&error.to_string())
31}
32
33#[wasm_bindgen]
34pub struct ScanEngine {
35 scanner: Scanner,
36}
37
38#[wasm_bindgen]
39impl ScanEngine {
40 #[wasm_bindgen(constructor)]
41 pub fn new() -> Self {
42 Self {
43 scanner: Scanner::default(),
44 }
45 }
46
47 #[wasm_bindgen(js_name = rulesCount)]
48 pub fn rules_count(&self) -> usize {
49 self.scanner.rules_count()
50 }
51
52 pub fn scan(&self, source: &str) -> ScanResult {
53 let mut entries = self.scanner.scan([("source", source)]).into_inner();
54 let (_, source_bytes, report) = entries
55 .pop()
56 .expect("single-source WASM scan must produce exactly one result entry")
57 .into_parts();
58
59 ScanResult {
60 source_bytes,
61 report,
62 }
63 }
64
65 #[wasm_bindgen(js_name = explainFinding)]
71 pub fn explain_finding(
72 &self,
73 result: &ScanResult,
74 index: usize,
75 ) -> Result<ExplanationView, JsError> {
76 let finding = result
77 .report
78 .findings()
79 .get(index)
80 .ok_or_else(|| JsError::new("finding index out of range"))?;
81
82 finding
83 .explanation(&self.scanner)
84 .map(ExplanationView::from)
85 .ok_or_else(|| JsError::new("finding explanation unavailable for this engine"))
86 }
87}
88
89impl Default for ScanEngine {
90 fn default() -> Self {
91 Self::new()
92 }
93}
94
95#[wasm_bindgen]
101pub struct ScanEngineBuilder {
102 include_builtins: bool,
103 include_financial_builtins: bool,
104 include_personal_builtins: bool,
105 rules: Vec<Rule>,
106}
107
108#[wasm_bindgen]
109impl ScanEngineBuilder {
110 #[wasm_bindgen(constructor)]
113 pub fn new(include_builtins: bool) -> Self {
114 Self {
115 include_builtins,
116 include_financial_builtins: false,
117 include_personal_builtins: false,
118 rules: Vec::new(),
119 }
120 }
121
122 #[wasm_bindgen(js_name = addFinancialBuiltins)]
124 pub fn add_financial_builtins(&mut self) {
125 self.include_financial_builtins = true;
126 }
127
128 #[wasm_bindgen(js_name = addPersonalBuiltins)]
130 pub fn add_personal_builtins(&mut self) {
131 self.include_personal_builtins = true;
132 }
133
134 #[wasm_bindgen(js_name = addLiteral)]
136 pub fn add_literal(&mut self, id: &str, value: &str, severity: FindingSeverity) {
137 self.rules
138 .push(Rule::literal(id, value, Severity::from(severity)));
139 }
140
141 #[wasm_bindgen(js_name = addPrefix)]
143 pub fn add_prefix(&mut self, id: &str, value: &str, severity: FindingSeverity) {
144 self.rules
145 .push(Rule::prefix(id, value, Severity::from(severity)));
146 }
147
148 #[wasm_bindgen(js_name = addSuffix)]
150 pub fn add_suffix(&mut self, id: &str, value: &str, severity: FindingSeverity) {
151 self.rules
152 .push(Rule::suffix(id, value, Severity::from(severity)));
153 }
154
155 #[wasm_bindgen(js_name = addPattern)]
160 pub fn add_pattern(
161 &mut self,
162 id: &str,
163 pattern: &str,
164 severity: FindingSeverity,
165 ) -> Result<(), JsError> {
166 self.add_pattern_core(id, pattern, severity)
167 .map_err(|error| JsError::new(&error))
168 }
169
170 #[wasm_bindgen(js_name = customRuleCount)]
172 pub fn custom_rule_count(&self) -> usize {
173 self.rules.len()
174 }
175
176 pub fn build(self) -> Result<ScanEngine, JsError> {
178 self.build_core().map_err(|error| JsError::new(&error))
179 }
180}
181
182impl ScanEngineBuilder {
183 fn add_pattern_core(
185 &mut self,
186 id: &str,
187 pattern: &str,
188 severity: FindingSeverity,
189 ) -> Result<(), String> {
190 let rule = Rule::pattern(id, pattern, Severity::from(severity))
191 .map_err(|error| error.to_string())?;
192 self.rules.push(rule);
193 Ok(())
194 }
195
196 fn build_core(self) -> Result<ScanEngine, String> {
199 let mut builder = Scanner::builder();
200
201 if self.include_builtins {
202 builder = builder.builtins(cribra::builtins::CURRENT);
203 }
204
205 if self.include_financial_builtins {
206 builder = builder.builtins(cribra::builtins::financial::CURRENT);
207 }
208
209 if self.include_personal_builtins {
210 builder = builder.builtins(cribra::builtins::personal::CURRENT);
211 }
212
213 let scanner = builder
214 .rules(self.rules)
215 .build()
216 .map_err(|error| error.to_string())?;
217
218 Ok(ScanEngine { scanner })
219 }
220}
221
222#[wasm_bindgen]
223#[derive(Debug, Clone, Copy, Eq, PartialEq)]
224pub enum FindingSeverity {
225 Info,
226 Low,
227 Medium,
228 High,
229 Critical,
230}
231
232impl From<Severity> for FindingSeverity {
233 fn from(value: Severity) -> Self {
234 match value {
235 Severity::Info => Self::Info,
236 Severity::Low => Self::Low,
237 Severity::Medium => Self::Medium,
238 Severity::High => Self::High,
239 Severity::Critical => Self::Critical,
240 }
241 }
242}
243
244impl From<FindingSeverity> for Severity {
245 fn from(value: FindingSeverity) -> Self {
246 match value {
247 FindingSeverity::Info => Self::Info,
248 FindingSeverity::Low => Self::Low,
249 FindingSeverity::Medium => Self::Medium,
250 FindingSeverity::High => Self::High,
251 FindingSeverity::Critical => Self::Critical,
252 }
253 }
254}
255
256#[wasm_bindgen]
257#[derive(Debug, Clone, Copy, Eq, PartialEq)]
258pub enum FindingConfidence {
259 Low,
260 Medium,
261 High,
262}
263
264impl From<Confidence> for FindingConfidence {
265 fn from(value: Confidence) -> Self {
266 match value {
267 Confidence::Low => Self::Low,
268 Confidence::Medium => Self::Medium,
269 Confidence::High => Self::High,
270 }
271 }
272}
273
274#[wasm_bindgen]
275#[derive(Debug, Clone, Copy, Eq, PartialEq)]
276pub enum RemediationKind {
277 None,
278 RevokeAndRotateCredential,
279 RotateCredential,
280 RotatePassword,
281 ReplacePrivateKey,
282 RemoveSensitiveValue,
283 ReviewSensitiveHash,
284 ReviewPasswordVerifier,
285 Unknown,
286}
287
288impl From<Option<Remediation>> for RemediationKind {
289 fn from(value: Option<Remediation>) -> Self {
290 match value {
291 None => Self::None,
292 Some(Remediation::RevokeAndRotateCredential) => Self::RevokeAndRotateCredential,
293 Some(Remediation::RotateCredential) => Self::RotateCredential,
294 Some(Remediation::RotatePassword) => Self::RotatePassword,
295 Some(Remediation::ReplacePrivateKey) => Self::ReplacePrivateKey,
296 Some(Remediation::RemoveSensitiveValue) => Self::RemoveSensitiveValue,
297 Some(Remediation::ReviewSensitiveHash) => Self::ReviewSensitiveHash,
298 Some(Remediation::ReviewPasswordVerifier) => Self::ReviewPasswordVerifier,
299 Some(_) => Self::Unknown,
300 }
301 }
302}
303
304#[wasm_bindgen]
305#[derive(Debug, Clone, Copy, Eq, PartialEq)]
306pub enum CandidateKind {
307 RecoveryLikeCode,
308 Unknown,
309}
310
311impl From<SensitiveCandidateKind> for CandidateKind {
312 fn from(value: SensitiveCandidateKind) -> Self {
313 match value {
314 SensitiveCandidateKind::RecoveryLikeCode => Self::RecoveryLikeCode,
315 _ => Self::Unknown,
316 }
317 }
318}
319
320#[wasm_bindgen]
321#[derive(Debug, Clone, Copy, Eq, PartialEq)]
322pub enum CandidateEvidenceKind {
323 Structural,
324 Unknown,
325}
326
327impl From<CandidateEvidence> for CandidateEvidenceKind {
328 fn from(value: CandidateEvidence) -> Self {
329 match value {
330 CandidateEvidence::Structural => Self::Structural,
331 _ => Self::Unknown,
332 }
333 }
334}
335
336#[wasm_bindgen]
338#[derive(Debug, Clone, Copy, Eq, PartialEq)]
339pub enum DetectionModeKind {
340 MatcherOnly,
341 Deterministic,
342 Contextual,
343}
344
345impl From<DetectionMode> for DetectionModeKind {
346 fn from(value: DetectionMode) -> Self {
347 match value {
348 DetectionMode::MatcherOnly => Self::MatcherOnly,
349 DetectionMode::Deterministic => Self::Deterministic,
350 DetectionMode::Contextual => Self::Contextual,
351 }
352 }
353}
354
355#[wasm_bindgen]
357#[derive(Debug, Clone, Copy, Eq, PartialEq)]
358pub enum ExplanationKind {
359 Classified,
360 Ambiguous,
361 Unknown,
362}
363
364#[wasm_bindgen]
371pub struct ExplanationView {
372 kind: ExplanationKind,
373 detection_mode: Option<DetectionModeKind>,
374 candidate_evidence: Option<CandidateEvidenceKind>,
375}
376
377impl From<Explanation> for ExplanationView {
378 fn from(explanation: Explanation) -> Self {
379 match explanation {
380 Explanation::Classified(mode) => Self {
381 kind: ExplanationKind::Classified,
382 detection_mode: Some(mode.into()),
383 candidate_evidence: None,
384 },
385 Explanation::Ambiguous(evidence) => Self {
386 kind: ExplanationKind::Ambiguous,
387 detection_mode: None,
388 candidate_evidence: Some(evidence.into()),
389 },
390 _ => Self {
391 kind: ExplanationKind::Unknown,
392 detection_mode: None,
393 candidate_evidence: None,
394 },
395 }
396 }
397}
398
399#[wasm_bindgen]
400impl ExplanationView {
401 #[wasm_bindgen(getter)]
402 pub fn kind(&self) -> ExplanationKind {
403 self.kind
404 }
405
406 #[wasm_bindgen(getter, js_name = detectionMode)]
409 pub fn detection_mode(&self) -> Option<DetectionModeKind> {
410 self.detection_mode
411 }
412
413 #[wasm_bindgen(getter, js_name = candidateEvidence)]
416 pub fn candidate_evidence(&self) -> Option<CandidateEvidenceKind> {
417 self.candidate_evidence
418 }
419}
420
421#[wasm_bindgen]
422pub struct FindingView {
423 rule_id: String,
424 start: usize,
425 end: usize,
426 line: usize,
427 column: usize,
428 severity: FindingSeverity,
429 confidence: FindingConfidence,
430 remediation: RemediationKind,
431}
432
433impl From<&Finding> for FindingView {
434 fn from(finding: &Finding) -> Self {
435 let location = finding.location();
436
437 Self {
438 rule_id: finding.rule_id().as_str().to_owned(),
439 start: location.start(),
440 end: location.end(),
441 line: location.line(),
442 column: location.column(),
443 severity: finding.severity().into(),
444 confidence: finding.confidence().into(),
445 remediation: finding.remediation().into(),
446 }
447 }
448}
449
450#[wasm_bindgen]
451impl FindingView {
452 #[wasm_bindgen(getter, js_name = ruleId)]
453 pub fn rule_id(&self) -> String {
454 self.rule_id.clone()
455 }
456
457 #[wasm_bindgen(getter)]
458 pub fn start(&self) -> usize {
459 self.start
460 }
461
462 #[wasm_bindgen(getter)]
463 pub fn end(&self) -> usize {
464 self.end
465 }
466
467 #[wasm_bindgen(getter)]
468 pub fn line(&self) -> usize {
469 self.line
470 }
471
472 #[wasm_bindgen(getter)]
473 pub fn column(&self) -> usize {
474 self.column
475 }
476
477 #[wasm_bindgen(getter)]
478 pub fn severity(&self) -> FindingSeverity {
479 self.severity
480 }
481
482 #[wasm_bindgen(getter)]
483 pub fn confidence(&self) -> FindingConfidence {
484 self.confidence
485 }
486
487 #[wasm_bindgen(getter)]
488 pub fn remediation(&self) -> RemediationKind {
489 self.remediation
490 }
491}
492
493#[wasm_bindgen]
494pub struct CandidateView {
495 kind: CandidateKind,
496 evidence: CandidateEvidenceKind,
497 start: usize,
498 end: usize,
499 line: usize,
500 column: usize,
501}
502
503impl From<&SensitiveCandidate> for CandidateView {
504 fn from(candidate: &SensitiveCandidate) -> Self {
505 let location = candidate.location();
506
507 Self {
508 kind: candidate.kind().into(),
509 evidence: candidate.evidence().into(),
510 start: location.start(),
511 end: location.end(),
512 line: location.line(),
513 column: location.column(),
514 }
515 }
516}
517
518#[wasm_bindgen]
519impl CandidateView {
520 #[wasm_bindgen(getter)]
521 pub fn kind(&self) -> CandidateKind {
522 self.kind
523 }
524
525 #[wasm_bindgen(getter)]
526 pub fn evidence(&self) -> CandidateEvidenceKind {
527 self.evidence
528 }
529
530 #[wasm_bindgen(getter)]
531 pub fn start(&self) -> usize {
532 self.start
533 }
534
535 #[wasm_bindgen(getter)]
536 pub fn end(&self) -> usize {
537 self.end
538 }
539
540 #[wasm_bindgen(getter)]
541 pub fn line(&self) -> usize {
542 self.line
543 }
544
545 #[wasm_bindgen(getter)]
546 pub fn column(&self) -> usize {
547 self.column
548 }
549}
550
551#[wasm_bindgen]
552pub struct ScanResult {
553 source_bytes: usize,
554 report: ScanReport,
555}
556
557#[wasm_bindgen]
558impl ScanResult {
559 #[wasm_bindgen(getter, js_name = sourceBytes)]
560 pub fn source_bytes(&self) -> usize {
561 self.source_bytes
562 }
563
564 #[wasm_bindgen(js_name = findingCount)]
565 pub fn finding_count(&self) -> usize {
566 self.report.len()
567 }
568
569 #[wasm_bindgen(js_name = candidateCount)]
570 pub fn candidate_count(&self) -> usize {
571 self.report.candidate_len()
572 }
573
574 #[wasm_bindgen(js_name = needsReview)]
575 pub fn needs_review(&self) -> bool {
576 self.report.needs_review()
577 }
578
579 #[wasm_bindgen(js_name = hasCritical)]
580 pub fn has_critical(&self) -> bool {
581 self.report.has_critical()
582 }
583
584 #[wasm_bindgen(js_name = findingAt)]
585 pub fn finding_at(&self, index: usize) -> Result<FindingView, JsError> {
586 self.report
587 .findings()
588 .get(index)
589 .map(FindingView::from)
590 .ok_or_else(|| JsError::new("finding index out of range"))
591 }
592
593 pub fn redact(&self, source: &str) -> Result<String, JsError> {
597 redact(source, &self.report).map_err(transform_error)
598 }
599
600 #[wasm_bindgen(js_name = redactWith)]
604 pub fn redact_with(&self, source: &str, replacement: &str) -> Result<String, JsError> {
605 let redaction = Redaction::new(replacement);
606 redact_with(source, &self.report, &redaction).map_err(transform_error)
607 }
608
609 pub fn template(&self, source: &str) -> Result<String, JsError> {
611 template(source, &self.report).map_err(transform_error)
612 }
613
614 #[wasm_bindgen(js_name = templateWith)]
617 pub fn template_with(
618 &self,
619 source: &str,
620 namespace: &str,
621 numbered: bool,
622 ) -> Result<String, JsError> {
623 let options = TemplateOptions::new()
624 .namespace(namespace)
625 .numbered(numbered);
626
627 template_with(source, &self.report, &options).map_err(transform_error)
628 }
629
630 pub fn pseudonymize(
635 &self,
636 source: &str,
637 key: &[u8],
638 prefix: &str,
639 digest_bytes: usize,
640 ) -> Result<String, JsError> {
641 let options = PseudonymizationOptions::new(key32(key)?)
642 .prefix(prefix)
643 .digest_bytes(digest_bytes);
644
645 pseudonymize(source, &self.report, &options).map_err(transform_error)
646 }
647
648 pub fn synthesize(&self, source: &str, key: &[u8], marker: &str) -> Result<String, JsError> {
653 let options = SynthesisOptions::new(key32(key)?).marker(marker);
654
655 synthesize(source, &self.report, &options).map_err(transform_error)
656 }
657
658 #[wasm_bindgen(js_name = candidateAt)]
659 pub fn candidate_at(&self, index: usize) -> Result<CandidateView, JsError> {
660 self.report
661 .candidates()
662 .get(index)
663 .map(CandidateView::from)
664 .ok_or_else(|| JsError::new("candidate index out of range"))
665 }
666
667 #[wasm_bindgen(js_name = candidateExplanationAt)]
672 pub fn candidate_explanation_at(&self, index: usize) -> Result<ExplanationView, JsError> {
673 self.report
674 .candidates()
675 .get(index)
676 .map(|candidate| ExplanationView::from(candidate.explanation()))
677 .ok_or_else(|| JsError::new("candidate index out of range"))
678 }
679}
680
681#[cfg(test)]
682mod tests {
683 use super::*;
684
685 #[test]
686 fn default_engine_uses_current_builtins() {
687 let engine = ScanEngine::new();
688 assert_eq!(engine.rules_count(), cribra::builtins::CURRENT.len());
689 }
690
691 #[test]
692 fn candidate_only_scan_preserves_review_only_semantics() {
693 let engine = ScanEngine::new();
694 let result = engine.scan("ABCD-EFGH-IJKL-MNOP");
695
696 assert_eq!(result.finding_count(), 0);
697 assert_eq!(result.candidate_count(), 1);
698 assert!(result.needs_review());
699 assert!(!result.has_critical());
700
701 let candidate = CandidateView::from(&result.report.candidates()[0]);
702 assert_eq!(candidate.kind(), CandidateKind::RecoveryLikeCode);
703 assert_eq!(candidate.evidence(), CandidateEvidenceKind::Structural);
704 }
705
706 #[test]
707 fn projected_findings_never_require_source_retention() {
708 let engine = ScanEngine::new();
709 let source = "GITHUB_TOKEN=ghp_AbCdEf0123456789_AbCdEf0123456789";
710 let result = engine.scan(source);
711
712 assert_eq!(result.source_bytes(), source.len());
713 assert_eq!(result.finding_count(), 1);
714 assert_eq!(result.candidate_count(), 0);
715
716 let finding = FindingView::from(&result.report.findings()[0]);
717 assert!(!finding.rule_id().is_empty());
718 assert!(finding.end() > finding.start());
719 assert_eq!(finding.line(), 1);
720 assert!(finding.column() >= 1);
721 }
722
723 #[test]
724 fn remediation_is_projected_only_for_findings() {
725 let engine = ScanEngine::new();
726 let result = engine.scan("GITHUB_TOKEN=ghp_AbCdEf0123456789_AbCdEf0123456789");
727
728 let finding = FindingView::from(&result.report.findings()[0]);
729 assert_ne!(finding.remediation(), RemediationKind::None);
730 }
731
732 #[test]
733 fn classified_explanation_reuses_scanner_detection_authority() {
734 let engine = ScanEngine::new();
735 let result = engine.scan("GITHUB_TOKEN=ghp_AbCdEf0123456789_AbCdEf0123456789");
736
737 let explanation = engine
738 .explain_finding(&result, 0)
739 .expect("finding explanation should resolve against its engine");
740
741 assert_eq!(explanation.kind(), ExplanationKind::Classified);
742 assert!(explanation.detection_mode().is_some());
743 assert_eq!(explanation.candidate_evidence(), None);
744 }
745
746 #[test]
747 fn candidate_explanation_reuses_candidate_evidence_only() {
748 let engine = ScanEngine::new();
749 let result = engine.scan("ABCD-EFGH-IJKL-MNOP");
750
751 let explanation = result
752 .candidate_explanation_at(0)
753 .expect("candidate explanation should exist");
754
755 assert_eq!(explanation.kind(), ExplanationKind::Ambiguous);
756 assert_eq!(explanation.detection_mode(), None);
757 assert_eq!(
758 explanation.candidate_evidence(),
759 Some(CandidateEvidenceKind::Structural)
760 );
761 }
762
763 #[test]
764 fn redact_transforms_findings_without_touching_candidates() {
765 let engine = ScanEngine::new();
766 let source = "GITHUB_TOKEN=ghp_AbCdEf0123456789_AbCdEf0123456789";
767 let result = engine.scan(source);
768
769 let output = result.redact(source).expect("redaction should succeed");
770
771 assert!(!output.contains("ghp_AbCdEf0123456789_AbCdEf0123456789"));
772 assert!(output.contains("[REDACTED]"));
773 }
774
775 #[test]
776 fn template_uses_typed_report_without_serialization() {
777 let engine = ScanEngine::new();
778 let source = "GITHUB_TOKEN=ghp_AbCdEf0123456789_AbCdEf0123456789";
779 let result = engine.scan(source);
780
781 let output = result
782 .template_with(source, "EXAMPLE", true)
783 .expect("template should succeed");
784
785 assert!(output.contains("<EXAMPLE:"));
786 assert!(!output.contains("ghp_AbCdEf0123456789_AbCdEf0123456789"));
787 }
788
789 #[test]
790 fn keyed_transforms_are_deterministic_and_do_not_retain_keys() {
791 let engine = ScanEngine::new();
792 let source = "GITHUB_TOKEN=ghp_AbCdEf0123456789_AbCdEf0123456789";
793 let result = engine.scan(source);
794 let key = [7_u8; 32];
795
796 let first = result
797 .pseudonymize(source, &key, "pseudo_", 16)
798 .expect("pseudonymization should succeed");
799 let second = result
800 .pseudonymize(source, &key, "pseudo_", 16)
801 .expect("pseudonymization should be deterministic");
802 let synthetic = result
803 .synthesize(source, &key, "cribra_synthetic")
804 .expect("synthesis should succeed");
805
806 assert_eq!(first, second);
807 assert!(first.contains("pseudo_"));
808 assert_ne!(synthetic, source);
809 assert!(!synthetic.contains("ghp_AbCdEf0123456789_AbCdEf0123456789"));
810 }
811
812 #[test]
813 fn transforms_leave_candidate_only_source_unchanged() {
814 let engine = ScanEngine::new();
815 let source = "ABCD-EFGH-IJKL-MNOP";
816 let result = engine.scan(source);
817
818 assert_eq!(result.finding_count(), 0);
819 assert_eq!(result.candidate_count(), 1);
820 assert_eq!(result.redact(source).unwrap(), source);
821 assert_eq!(result.template(source).unwrap(), source);
822 }
823
824 #[test]
825 fn typed_builder_supports_all_public_custom_rule_families() {
826 let mut builder = ScanEngineBuilder::new(false);
827 builder.add_literal("custom.literal", "EXACT_SECRET", FindingSeverity::High);
828 builder.add_prefix("custom.prefix", "live_", FindingSeverity::Critical);
829 builder.add_suffix("custom.suffix", "_secret", FindingSeverity::Medium);
830 builder
831 .add_pattern(
832 "custom.pattern",
833 r"\bCUSTOM_[A-Z0-9]{8}\b",
834 FindingSeverity::Low,
835 )
836 .expect("valid custom pattern should compile");
837
838 assert_eq!(builder.custom_rule_count(), 4);
839
840 let engine = builder.build().expect("custom scanner should build");
841 let result = engine.scan("EXACT_SECRET live_ABC123 token_secret CUSTOM_AB12CD34");
842
843 assert_eq!(engine.rules_count(), 4);
844 assert_eq!(result.finding_count(), 4);
845 }
846
847 #[test]
848 fn typed_builder_can_combine_current_builtins_and_custom_rules() {
849 let mut builder = ScanEngineBuilder::new(true);
850 builder.add_literal("custom.literal", "EXACT_SECRET", FindingSeverity::High);
851
852 let engine = builder.build().expect("combined scanner should build");
853
854 assert_eq!(engine.rules_count(), cribra::builtins::CURRENT.len() + 1);
855 assert_eq!(engine.scan("EXACT_SECRET").finding_count(), 1);
856 }
857
858 #[test]
859 fn typed_builder_can_add_financial_builtins_explicitly() {
860 let mut builder = ScanEngineBuilder::new(false);
861 builder.add_financial_builtins();
862
863 let engine = builder.build().expect("financial scanner should build");
864
865 assert_eq!(
866 engine.rules_count(),
867 cribra::builtins::financial::CURRENT.len()
868 );
869
870 assert_eq!(
871 engine.scan("card_number=1234567890123452").finding_count(),
872 1
873 );
874
875 assert_eq!(engine.scan("cvv=123").finding_count(), 1);
876 assert_eq!(engine.scan("123").finding_count(), 0);
877 }
878
879 #[test]
880 fn typed_builder_can_add_personal_builtins_explicitly() {
881 let mut builder = ScanEngineBuilder::new(false);
882 builder.add_personal_builtins();
883
884 let engine = builder.build().expect("personal scanner should build");
885
886 assert_eq!(
887 engine.rules_count(),
888 cribra::builtins::personal::CURRENT.len()
889 );
890
891 assert_eq!(engine.scan("ssn=123-45-6789").finding_count(), 1);
892 assert_eq!(engine.scan("123-45-6789").finding_count(), 0);
893 }
894
895 #[test]
896 fn typed_builder_rejects_invalid_and_empty_capable_patterns() {
897 let mut invalid = ScanEngineBuilder::new(false);
898 assert!(
899 invalid
900 .add_pattern_core("custom.invalid", "(", FindingSeverity::High)
901 .is_err()
902 );
903
904 let mut empty = ScanEngineBuilder::new(false);
905 assert!(
906 empty
907 .add_pattern_core("custom.empty", ".*", FindingSeverity::High)
908 .is_err()
909 );
910 }
911
912 #[test]
913 fn typed_builder_fails_closed_on_duplicate_rule_ids() {
914 let mut builder = ScanEngineBuilder::new(false);
915 builder.add_literal("custom.shared", "FIRST", FindingSeverity::High);
916 builder.add_literal("custom.shared", "SECOND", FindingSeverity::Critical);
917
918 assert!(builder.build_core().is_err());
919 }
920
921 #[test]
922 fn password_verifier_remediation_is_projected_explicitly() {
923 let engine = ScanEngine::new();
924 let result = engine.scan(
925 "alice:$6$abcdefghijklmnop$0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789:20000:0:99999:7:::",
926 );
927
928 assert_eq!(result.finding_count(), 1);
929
930 let finding = FindingView::from(&result.report.findings()[0]);
931
932 assert_eq!(
933 finding.remediation(),
934 RemediationKind::ReviewPasswordVerifier,
935 );
936 }
937}