Skip to main content

cert_x_gen/
types.rs

1//! Core type definitions for CERT-X-GEN
2
3use chrono::{DateTime, Utc};
4use serde::{Deserialize, Serialize};
5use std::collections::{BTreeMap, HashMap};
6use std::net::{IpAddr, SocketAddr};
7use std::path::PathBuf;
8use std::time::Duration;
9use uuid::Uuid;
10
11/// Severity levels for findings
12#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
13#[serde(rename_all = "lowercase")]
14pub enum Severity {
15    /// Informational finding
16    Info,
17    /// Low severity
18    Low,
19    /// Medium severity
20    Medium,
21    /// High severity
22    High,
23    /// Critical severity
24    Critical,
25}
26
27impl Severity {
28    /// Get numeric score for severity
29    pub fn score(&self) -> u8 {
30        match self {
31            Severity::Info => 0,
32            Severity::Low => 1,
33            Severity::Medium => 2,
34            Severity::High => 3,
35            Severity::Critical => 4,
36        }
37    }
38}
39
40impl std::fmt::Display for Severity {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        match self {
43            Severity::Info => write!(f, "info"),
44            Severity::Low => write!(f, "low"),
45            Severity::Medium => write!(f, "medium"),
46            Severity::High => write!(f, "high"),
47            Severity::Critical => write!(f, "critical"),
48        }
49    }
50}
51
52/// Template programming language
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
54#[serde(rename_all = "lowercase")]
55pub enum TemplateLanguage {
56    /// YAML declarative templates
57    Yaml,
58    /// Python procedural templates
59    Python,
60    /// Rust compiled templates
61    Rust,
62    /// Shell script templates
63    Shell,
64    /// JavaScript templates
65    JavaScript,
66    /// C compiled templates
67    C,
68    /// C++ compiled templates
69    Cpp,
70    /// Java compiled templates
71    Java,
72    /// Go compiled templates
73    Go,
74    /// Ruby interpreted templates
75    Ruby,
76    /// Perl interpreted templates
77    Perl,
78    /// PHP interpreted templates
79    Php,
80}
81
82impl std::fmt::Display for TemplateLanguage {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        match self {
85            TemplateLanguage::Yaml => write!(f, "yaml"),
86            TemplateLanguage::Python => write!(f, "python"),
87            TemplateLanguage::Rust => write!(f, "rust"),
88            TemplateLanguage::Shell => write!(f, "shell"),
89            TemplateLanguage::JavaScript => write!(f, "javascript"),
90            TemplateLanguage::C => write!(f, "c"),
91            TemplateLanguage::Cpp => write!(f, "cpp"),
92            TemplateLanguage::Java => write!(f, "java"),
93            TemplateLanguage::Go => write!(f, "go"),
94            TemplateLanguage::Ruby => write!(f, "ruby"),
95            TemplateLanguage::Perl => write!(f, "perl"),
96            TemplateLanguage::Php => write!(f, "php"),
97        }
98    }
99}
100
101/// Supported network protocols
102#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
103#[serde(rename_all = "lowercase")]
104pub enum Protocol {
105    /// HTTP protocol
106    Http,
107    /// HTTPS protocol
108    Https,
109    /// TCP protocol
110    Tcp,
111    /// UDP protocol
112    Udp,
113    /// DNS protocol
114    Dns,
115    /// SSH protocol
116    Ssh,
117    /// FTP protocol
118    Ftp,
119    /// SMTP protocol
120    Smtp,
121    /// SMB protocol
122    Smb,
123    /// RDP protocol
124    Rdp,
125    /// Custom protocol with name
126    Custom(String),
127    /// Local CLI/binary target. `Target::address` carries a filesystem path to a
128    /// locally-built executable rather than a network host. Additive: existing
129    /// network protocols are unchanged, and the `CERT_X_GEN_TARGET_HOST` env
130    /// contract still holds (for a Cli target the "host" is the binary path).
131    Cli,
132}
133
134impl std::fmt::Display for Protocol {
135    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
136        match self {
137            Protocol::Http => write!(f, "http"),
138            Protocol::Https => write!(f, "https"),
139            Protocol::Tcp => write!(f, "tcp"),
140            Protocol::Udp => write!(f, "udp"),
141            Protocol::Dns => write!(f, "dns"),
142            Protocol::Ssh => write!(f, "ssh"),
143            Protocol::Ftp => write!(f, "ftp"),
144            Protocol::Smtp => write!(f, "smtp"),
145            Protocol::Smb => write!(f, "smb"),
146            Protocol::Rdp => write!(f, "rdp"),
147            Protocol::Custom(name) => write!(f, "{}", name),
148            Protocol::Cli => write!(f, "cli"),
149        }
150    }
151}
152
153/// Scan target specification
154#[derive(Debug, Clone, Serialize, Deserialize)]
155pub struct Target {
156    /// Unique target ID
157    pub id: Uuid,
158    /// Target address (IP or hostname)
159    pub address: String,
160    /// Target port (optional)
161    pub port: Option<u16>,
162    /// Protocol to use
163    pub protocol: Protocol,
164    /// Additional metadata
165    pub metadata: HashMap<String, String>,
166}
167
168impl Target {
169    /// Create a new target
170    pub fn new<S: Into<String>>(address: S, protocol: Protocol) -> Self {
171        Self {
172            id: Uuid::new_v4(),
173            address: address.into(),
174            port: None,
175            protocol,
176            metadata: HashMap::new(),
177        }
178    }
179
180    /// Create target with port
181    pub fn with_port<S: Into<String>>(address: S, port: u16, protocol: Protocol) -> Self {
182        Self {
183            id: Uuid::new_v4(),
184            address: address.into(),
185            port: Some(port),
186            protocol,
187            metadata: HashMap::new(),
188        }
189    }
190
191    /// Get full URL or address:port
192    pub fn url(&self) -> String {
193        match &self.protocol {
194            Protocol::Http | Protocol::Https => {
195                let scheme = if self.protocol == Protocol::Https {
196                    "https"
197                } else {
198                    "http"
199                };
200                if let Some(port) = self.port {
201                    format!("{}://{}:{}", scheme, self.address, port)
202                } else {
203                    format!("{}://{}", scheme, self.address)
204                }
205            }
206            _ => {
207                if let Some(port) = self.port {
208                    format!("{}:{}", self.address, port)
209                } else {
210                    self.address.clone()
211                }
212            }
213        }
214    }
215
216    /// Get socket address if possible
217    pub fn socket_addr(&self) -> Option<SocketAddr> {
218        if let Ok(ip) = self.address.parse::<IpAddr>() {
219            Some(SocketAddr::new(ip, self.port.unwrap_or(0)))
220        } else {
221            None
222        }
223    }
224
225    /// Create variants with both HTTP and HTTPS for flexible testing
226    /// This allows a single HTTP template to test both protocols
227    pub fn with_both_schemes(&self) -> Vec<Target> {
228        if matches!(self.protocol, Protocol::Http | Protocol::Https) {
229            vec![
230                Target {
231                    protocol: Protocol::Http,
232                    ..self.clone()
233                },
234                Target {
235                    protocol: Protocol::Https,
236                    ..self.clone()
237                },
238            ]
239        } else {
240            vec![self.clone()]
241        }
242    }
243
244    /// Smart scheme selection based on port
245    pub fn infer_scheme(&self) -> Protocol {
246        match self.port {
247            Some(443) | Some(8443) => Protocol::Https,
248            Some(80) | Some(8080) | Some(8000) => Protocol::Http,
249            _ => self.protocol.clone(),
250        }
251    }
252}
253
254/// Execution context for templates
255#[derive(Debug, Clone, Serialize, Deserialize)]
256pub struct Context {
257    /// Scan ID
258    pub scan_id: Uuid,
259    /// Aggressive mode enabled
260    pub aggressive_mode: bool,
261    /// Stealth mode enabled
262    pub stealth_mode: bool,
263    /// Maximum retries
264    pub max_retries: u32,
265    /// Timeout duration
266    pub timeout: Duration,
267    /// Custom variables
268    pub variables: HashMap<String, String>,
269    /// Rate limit (requests per second)
270    pub rate_limit: Option<u32>,
271    /// Additional ports to scan (added to template defaults)
272    pub additional_ports: Vec<u16>,
273    /// Override ports (replaces template defaults if set)
274    pub override_ports: Option<Vec<u16>>,
275    /// Custom HTTP headers
276    #[serde(default)]
277    pub headers: Vec<(String, String)>,
278    /// Cookies for authenticated scans
279    #[serde(default)]
280    pub cookies: Vec<(String, String)>,
281
282    // --- Structured probe input. All additive and all absent unless the
283    // corresponding flag was passed, so a network scan's template environment
284    // is byte-identical to what it was before these existed.
285    /// Argument vector cxg hands the template to feed the target under test.
286    /// Exposed as `CERT_X_GEN_ARGV` (JSON array). Empty means not supplied.
287    #[serde(default)]
288    pub probe_argv: Vec<String>,
289    /// File whose bytes the template should feed to the target's stdin.
290    /// Exposed as `CERT_X_GEN_STDIN_FILE`.
291    #[serde(default)]
292    pub probe_stdin_file: Option<PathBuf>,
293    /// Directory of seed inputs (corpus) the template may iterate. cxg does
294    /// not mutate or minimise it. Exposed as `CERT_X_GEN_INPUT_DIR`.
295    #[serde(default)]
296    pub probe_input_dir: Option<PathBuf>,
297    /// Environment the template should set on the *target* process, not on
298    /// itself. Exposed as `CERT_X_GEN_TARGET_ENV` (JSON object).
299    #[serde(default)]
300    pub probe_env: Vec<(String, String)>,
301    /// Refuse to run against a `cli://` target whose build carries no
302    /// detectable instrumentation, rather than reporting a "no findings"
303    /// result that reads as a refutation but is not evidence.
304    #[serde(default)]
305    pub require_instrumentation: bool,
306    /// Instrumentation **provenance**: for each binary cxg itself built, the
307    /// labels it verified in the produced artefact, keyed by that binary's
308    /// path.
309    ///
310    /// Populated only by `cxg scan --instrumented-manifest`, and empty
311    /// otherwise -- which is the case that behaves exactly as cxg did before
312    /// this existed. Where a record is present it is used **in preference to
313    /// re-inspecting the file**: cxg passed the flags and read the artefact
314    /// back at build time, and that is better evidence than sniffing the same
315    /// artefact again later. Inspection stays for binaries cxg did not build,
316    /// which is where it belongs.
317    #[serde(default)]
318    pub instrumentation_provenance: BTreeMap<String, Vec<String>>,
319}
320
321impl Default for Context {
322    fn default() -> Self {
323        Self {
324            scan_id: Uuid::new_v4(),
325            aggressive_mode: false,
326            stealth_mode: false,
327            max_retries: 1,
328            timeout: Duration::from_secs(30),
329            variables: HashMap::new(),
330            rate_limit: None,
331            additional_ports: Vec::new(),
332            override_ports: None,
333            headers: Vec::new(),
334            cookies: Vec::new(),
335            probe_argv: Vec::new(),
336            probe_stdin_file: None,
337            probe_input_dir: None,
338            probe_env: Vec::new(),
339            require_instrumentation: false,
340            instrumentation_provenance: BTreeMap::new(),
341        }
342    }
343}
344
345/// Evidence for a finding
346#[derive(Debug, Clone, Serialize, Deserialize)]
347pub struct Evidence {
348    /// HTTP request (if applicable)
349    pub request: Option<String>,
350    /// HTTP response (if applicable)
351    pub response: Option<String>,
352    /// Matched patterns
353    pub matched_patterns: Vec<String>,
354    /// Custom evidence data
355    pub data: HashMap<String, serde_json::Value>,
356    /// Timestamp
357    pub timestamp: DateTime<Utc>,
358}
359
360impl Evidence {
361    /// Create new evidence
362    pub fn new() -> Self {
363        Self {
364            request: None,
365            response: None,
366            matched_patterns: Vec::new(),
367            data: HashMap::new(),
368            timestamp: Utc::now(),
369        }
370    }
371
372    /// Add matched pattern
373    pub fn add_match(&mut self, pattern: String) {
374        self.matched_patterns.push(pattern);
375    }
376
377    /// Add custom data
378    pub fn add_data<K: Into<String>>(&mut self, key: K, value: serde_json::Value) {
379        self.data.insert(key.into(), value);
380    }
381}
382
383impl Default for Evidence {
384    fn default() -> Self {
385        Self::new()
386    }
387}
388
389/// Security finding
390#[derive(Debug, Clone, Serialize, Deserialize)]
391pub struct Finding {
392    /// How the verdict was established in a combined scanner/probe report.
393    #[serde(default, skip_serializing_if = "Option::is_none")]
394    pub verdict_source: Option<String>,
395    /// Unique finding ID
396    pub id: Uuid,
397    /// Target that was scanned
398    pub target: String,
399    /// Template ID that generated this finding
400    pub template_id: String,
401    /// Severity level
402    pub severity: Severity,
403    /// Confidence score (0-100)
404    pub confidence: u8,
405    /// Finding title
406    pub title: String,
407    /// Detailed description
408    pub description: String,
409    /// Evidence
410    pub evidence: Evidence,
411    /// CVE IDs
412    pub cve_ids: Vec<String>,
413    /// CWE IDs
414    pub cwe_ids: Vec<String>,
415    /// CVSS score
416    pub cvss_score: Option<f32>,
417    /// Remediation advice
418    pub remediation: Option<String>,
419    /// References
420    pub references: Vec<String>,
421    /// Tags
422    pub tags: Vec<String>,
423    /// Timestamp
424    pub timestamp: DateTime<Utc>,
425}
426
427impl Finding {
428    /// Create a new finding
429    pub fn new<S: Into<String>>(
430        target: S,
431        template_id: S,
432        severity: Severity,
433        title: S,
434        description: S,
435    ) -> Self {
436        Self {
437            id: Uuid::new_v4(),
438            target: target.into(),
439            template_id: template_id.into(),
440            verdict_source: None,
441            severity,
442            confidence: 90,
443            title: title.into(),
444            description: description.into(),
445            evidence: Evidence::new(),
446            cve_ids: Vec::new(),
447            cwe_ids: Vec::new(),
448            cvss_score: None,
449            remediation: None,
450            references: Vec::new(),
451            tags: Vec::new(),
452            timestamp: Utc::now(),
453        }
454    }
455
456    /// Set confidence
457    pub fn with_confidence(mut self, confidence: u8) -> Self {
458        self.confidence = confidence.min(100);
459        self
460    }
461
462    /// Set evidence
463    pub fn with_evidence(mut self, evidence: Evidence) -> Self {
464        self.evidence = evidence;
465        self
466    }
467
468    /// Add CVE ID
469    pub fn add_cve<S: Into<String>>(mut self, cve_id: S) -> Self {
470        self.cve_ids.push(cve_id.into());
471        self
472    }
473
474    /// Add CWE ID
475    pub fn add_cwe<S: Into<String>>(mut self, cwe_id: S) -> Self {
476        self.cwe_ids.push(cwe_id.into());
477        self
478    }
479
480    /// Set CVSS score
481    pub fn with_cvss_score(mut self, score: f32) -> Self {
482        self.cvss_score = Some(score);
483        self
484    }
485}
486
487/// Outcome of one (template, target) execution.
488///
489/// cxg has always surfaced *findings*. It has never surfaced "this template
490/// ran, exercised the target, and concluded there is no defect" -- which made a
491/// genuine refutation indistinguishable from a template that silently did
492/// nothing. This enum is that missing channel; [`ExecutionRecord`] carries it.
493#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
494#[serde(rename_all = "lowercase")]
495pub enum ExecutionStatus {
496    /// Template ran and produced at least one finding.
497    Confirmed,
498    /// Template ran, exercised the target, and concluded no defect.
499    Refuted,
500    /// Template ran but could not reach a conclusion (setup failure, bad build).
501    Errored,
502    /// Template declined this target (wrong kind, missing precondition, a build
503    /// that could not have revealed the defect).
504    Skipped,
505    /// Template exceeded its wall-clock budget.
506    #[serde(rename = "timed-out")]
507    TimedOut,
508}
509
510impl std::fmt::Display for ExecutionStatus {
511    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
512        let s = match self {
513            ExecutionStatus::Confirmed => "confirmed",
514            ExecutionStatus::Refuted => "refuted",
515            ExecutionStatus::Errored => "errored",
516            ExecutionStatus::Skipped => "skipped",
517            ExecutionStatus::TimedOut => "timed-out",
518        };
519        f.write_str(s)
520    }
521}
522
523impl ExecutionStatus {
524    /// Parse a template-declared status string (case-insensitive).
525    ///
526    /// Returns `None` for anything outside the vocabulary; callers must treat
527    /// that as an unrecognised declaration rather than silently ignoring it.
528    pub fn parse(s: &str) -> Option<Self> {
529        match s.trim().to_lowercase().as_str() {
530            "confirmed" | "confirm" => Some(ExecutionStatus::Confirmed),
531            "refuted" | "refute" | "not-reproduced" => Some(ExecutionStatus::Refuted),
532            "errored" | "error" => Some(ExecutionStatus::Errored),
533            "skipped" | "skip" => Some(ExecutionStatus::Skipped),
534            "timed-out" | "timedout" | "timeout" => Some(ExecutionStatus::TimedOut),
535            _ => None,
536        }
537    }
538
539    /// Every status, in report order. Used by the terminal summary.
540    pub const ALL: [ExecutionStatus; 5] = [
541        ExecutionStatus::Confirmed,
542        ExecutionStatus::Refuted,
543        ExecutionStatus::Skipped,
544        ExecutionStatus::Errored,
545        ExecutionStatus::TimedOut,
546    ];
547}
548
549/// One row of the per-(template, target) execution ledger.
550///
551/// Emitted for every template cxg attempted against every target, including
552/// the ones that produced no findings. `ScanResults.findings` says what was
553/// confirmed; this says what was *refuted*, *skipped* or *errored*, which a
554/// scan reporting zero findings otherwise cannot distinguish.
555#[derive(Debug, Clone, Serialize, Deserialize)]
556pub struct ExecutionRecord {
557    /// Target address (host, or binary path for a `cli://` target)
558    pub target: String,
559    /// Target kind, i.e. the target's protocol (`http`, `cli`, ...)
560    #[serde(default)]
561    pub target_kind: String,
562    /// Template ID
563    pub template_id: String,
564    /// What cxg observed, or what the template declared
565    pub status: ExecutionStatus,
566    /// True when `status` came from the template's own JSON metadata rather
567    /// than being inferred by cxg from the finding count. An operator can
568    /// always tell a template's considered verdict from cxg's default guess.
569    #[serde(default)]
570    pub declared_by_template: bool,
571    /// Number of findings this execution produced
572    pub findings: usize,
573    /// Template process exit code, when the engine observed one
574    #[serde(default)]
575    pub exit_code: Option<i32>,
576    /// Short human-readable reason, template-supplied or cxg-supplied
577    #[serde(default)]
578    pub detail: Option<String>,
579    /// Wall-clock duration in milliseconds
580    #[serde(default)]
581    pub duration_ms: u64,
582}
583
584/// Scan statistics
585#[derive(Debug, Clone, Default, Serialize, Deserialize)]
586pub struct ScanStatistics {
587    /// Total targets scanned
588    pub targets_scanned: usize,
589    /// Total templates executed
590    pub templates_executed: usize,
591    /// Findings by severity
592    pub findings_by_severity: HashMap<Severity, usize>,
593    /// Outbound request attempts, including retries and redirects. Unknown when
594    /// an executed engine cannot observe template networking.
595    pub network_requests: Option<usize>,
596    /// Requests observed by cxg, even when the aggregate total is unknown.
597    #[serde(default)]
598    pub network_requests_measured: usize,
599    /// Total data transferred (bytes)
600    pub data_transferred: u64,
601    /// Scan duration
602    pub duration: Duration,
603    /// Success rate
604    pub success_rate: f64,
605}
606
607/// Scan results
608#[derive(Debug, Clone, Serialize, Deserialize)]
609pub struct ScanResults {
610    /// Native probe reports, refused inputs, and persistent engine session paths.
611    #[serde(default, skip_serializing_if = "Option::is_none")]
612    pub probe_results: Option<serde_json::Value>,
613    /// Scan ID
614    pub scan_id: Uuid,
615    /// Start time
616    pub started_at: DateTime<Utc>,
617    /// Completion time
618    pub completed_at: Option<DateTime<Utc>>,
619    /// Findings
620    pub findings: Vec<Finding>,
621    /// Statistics
622    pub statistics: ScanStatistics,
623    /// Errors encountered
624    pub errors: Vec<String>,
625    /// Per-(template, target) execution ledger. Additive: absent in result
626    /// files written by older versions, defaulted to empty on deserialisation.
627    #[serde(default)]
628    pub executions: Vec<ExecutionRecord>,
629}
630
631impl ScanResults {
632    /// Add discovery outcomes once per file, before any target was selected.
633    /// Such ledger rows have an empty target and use the path as template ID.
634    pub fn add_discovery_issues(&mut self, issues: Vec<crate::template::TemplateLoadIssue>) {
635        for issue in issues {
636            let (status, detail) = if let Some(error) = issue.error {
637                let detail = format!(
638                    "Failed to load template '{}': {}",
639                    issue.path.display(),
640                    error
641                );
642                self.errors.push(detail.clone());
643                (ExecutionStatus::Errored, detail)
644            } else {
645                (ExecutionStatus::Skipped, "skipped-non-template".to_string())
646            };
647            self.executions.push(ExecutionRecord {
648                target: String::new(),
649                target_kind: String::new(),
650                template_id: issue.path.display().to_string(),
651                status,
652                declared_by_template: false,
653                findings: 0,
654                exit_code: None,
655                detail: Some(detail),
656                duration_ms: 0,
657            });
658        }
659    }
660
661    /// Create new scan results
662    pub fn new(scan_id: Uuid) -> Self {
663        Self {
664            scan_id,
665            probe_results: None,
666            started_at: Utc::now(),
667            completed_at: None,
668            findings: Vec::new(),
669            statistics: ScanStatistics::default(),
670            errors: Vec::new(),
671            executions: Vec::new(),
672        }
673    }
674
675    /// Add a finding
676    pub fn add_finding(&mut self, finding: Finding) {
677        *self
678            .statistics
679            .findings_by_severity
680            .entry(finding.severity)
681            .or_insert(0) += 1;
682        self.findings.push(finding);
683    }
684
685    /// Mark scan as complete
686    pub fn complete(&mut self) {
687        self.completed_at = Some(Utc::now());
688        if let Some(completed) = self.completed_at {
689            self.statistics.duration = (completed - self.started_at)
690                .to_std()
691                .unwrap_or(Duration::from_secs(0));
692        }
693    }
694
695    /// Get critical findings
696    pub fn critical_findings(&self) -> Vec<&Finding> {
697        self.findings
698            .iter()
699            .filter(|f| f.severity == Severity::Critical)
700            .collect()
701    }
702
703    /// Get high severity findings
704    pub fn high_findings(&self) -> Vec<&Finding> {
705        self.findings
706            .iter()
707            .filter(|f| f.severity == Severity::High)
708            .collect()
709    }
710}
711
712/// Template metadata
713#[derive(Debug, Clone, Serialize, Deserialize)]
714pub struct TemplateMetadata {
715    /// Template ID
716    pub id: String,
717    /// Template name
718    pub name: String,
719    /// Author information
720    pub author: AuthorInfo,
721    /// Severity
722    pub severity: Severity,
723    /// Description
724    pub description: String,
725    /// CVE IDs
726    #[serde(default)]
727    pub cve_ids: Vec<String>,
728    /// CWE IDs
729    #[serde(default)]
730    pub cwe_ids: Vec<String>,
731    /// CVSS score
732    pub cvss_score: Option<f32>,
733    /// Tags
734    #[serde(default)]
735    pub tags: Vec<String>,
736    /// Template language
737    pub language: TemplateLanguage,
738    /// Template file path
739    #[serde(default)]
740    pub file_path: PathBuf,
741    /// Created date
742    #[serde(default = "default_datetime")]
743    pub created: DateTime<Utc>,
744    /// Last updated
745    #[serde(default = "default_datetime")]
746    pub updated: DateTime<Utc>,
747    /// Version
748    #[serde(default = "default_version")]
749    pub version: String,
750    /// Confidence (0-100)
751    pub confidence: Option<u8>,
752
753    // --- Parameterisation & routing fields (Task 3a) ---
754    /// Context variables required/optional at runtime, parsed from `@context_vars`.
755    /// Each entry: `{ name, is_array, required }`.
756    /// Serialised as a compact string vec: `["auth_token:required", "endpoints[]:required"]`
757    #[serde(default)]
758    pub context_vars: Vec<String>,
759
760    /// Coarse vulnerability class for Bravos pipeline routing, from `@vuln_class`.
761    #[serde(default)]
762    pub vuln_class: Option<String>,
763
764    /// Fine-grained hypothesis routing tags for Bravos `TemplateMatcher`, from `@hypothesis_tags`.
765    #[serde(default)]
766    pub hypothesis_tags: Vec<String>,
767
768    /// Batch group identifier for running context-shape cohorts together, from `@batch_group`.
769    #[serde(default)]
770    pub batch_group: Option<String>,
771
772    /// Whether the template can self-probe for missing context, from `@auto_probe`.
773    #[serde(default)]
774    pub auto_probe: bool,
775
776    /// The template exits non-zero on purpose (a probe whose job is to provoke
777    /// a crash); cxg keeps its stdout instead of treating the exit as a hard
778    /// error. From `@allow_nonzero_exit`.
779    #[serde(default)]
780    pub allow_nonzero_exit: bool,
781
782    /// Oracles the template relies on to decide something is wrong, from
783    /// `@oracles`. Vocabulary: `asan` `ubsan` `msan` `tsan` `signal` `exit`
784    /// `exception` `assert` `timeout` `diff` `property` `detector`. Knowing
785    /// which one a template depends on lets cxg refuse to run it against a
786    /// build that cannot support it.
787    ///
788    /// The template observes the target for all of these but one: `exception`
789    /// is implemented by cxg, which matches the target output the template
790    /// hands back in `metadata.target_output` against the per-language shape
791    /// of an escaped exception. A template declares it the same way as any
792    /// other; nothing changes for a template that does not.
793    #[serde(default)]
794    pub oracles: Vec<String>,
795
796    /// Target kinds the template accepts, from `@target_kinds` (e.g. `cli`,
797    /// `http`). **Empty means no declaration, and a template with no
798    /// declaration runs against every kind** -- which is every template
799    /// written before this annotation existed.
800    #[serde(default)]
801    pub target_kinds: Vec<String>,
802}
803
804/// Author information
805#[derive(Debug, Clone, Serialize, Deserialize)]
806pub struct AuthorInfo {
807    /// Author name
808    pub name: String,
809    /// Author email
810    pub email: Option<String>,
811    /// GitHub username
812    pub github: Option<String>,
813}
814
815// Default functions for serde
816fn default_datetime() -> DateTime<Utc> {
817    Utc::now()
818}
819
820fn default_version() -> String {
821    "1.0".to_string()
822}
823
824#[cfg(test)]
825mod tests {
826    use super::*;
827
828    #[test]
829    fn execution_status_round_trips_through_json() {
830        for status in ExecutionStatus::ALL {
831            let json = serde_json::to_string(&status).unwrap();
832            // The wire form is exactly the Display form, so a consumer reading
833            // the JSON and a human reading the terminal see the same word.
834            assert_eq!(json, format!("\"{}\"", status));
835            let back: ExecutionStatus = serde_json::from_str(&json).unwrap();
836            assert_eq!(back, status);
837        }
838    }
839
840    #[test]
841    fn execution_status_parses_the_declared_vocabulary() {
842        assert_eq!(
843            ExecutionStatus::parse("REFUTED"),
844            Some(ExecutionStatus::Refuted)
845        );
846        assert_eq!(
847            ExecutionStatus::parse(" not-reproduced "),
848            Some(ExecutionStatus::Refuted)
849        );
850        assert_eq!(
851            ExecutionStatus::parse("timeout"),
852            Some(ExecutionStatus::TimedOut)
853        );
854        assert_eq!(ExecutionStatus::parse("refuuted"), None);
855        assert_eq!(ExecutionStatus::parse(""), None);
856    }
857
858    /// A result file written before the ledger existed must still load.
859    #[test]
860    fn scan_results_without_an_executions_field_still_deserialise() {
861        let legacy = r#"{
862            "scan_id": "00000000-0000-0000-0000-000000000000",
863            "started_at": "2026-01-01T00:00:00Z",
864            "completed_at": null,
865            "findings": [],
866            "statistics": {
867                "targets_scanned": 0,
868                "templates_executed": 0,
869                "findings_by_severity": {},
870                "network_requests": 0,
871                "data_transferred": 0,
872                "duration": {"secs": 0, "nanos": 0},
873                "success_rate": 0.0
874            },
875            "errors": []
876        }"#;
877        let results: ScanResults = serde_json::from_str(legacy).unwrap();
878        assert!(results.executions.is_empty());
879    }
880
881    #[test]
882    fn test_severity_ordering() {
883        assert!(Severity::Critical > Severity::High);
884        assert!(Severity::High > Severity::Medium);
885        assert!(Severity::Medium > Severity::Low);
886        assert!(Severity::Low > Severity::Info);
887    }
888
889    #[test]
890    fn test_target_url() {
891        let target = Target::with_port("example.com", 443, Protocol::Https);
892        assert_eq!(target.url(), "https://example.com:443");
893
894        let target = Target::new("example.com", Protocol::Http);
895        assert_eq!(target.url(), "http://example.com");
896    }
897
898    #[test]
899    fn test_finding_creation() {
900        let finding = Finding::new(
901            "192.168.1.1",
902            "CVE-2024-1234",
903            Severity::Critical,
904            "Test Finding",
905            "Test description",
906        );
907        assert_eq!(finding.severity, Severity::Critical);
908        assert_eq!(finding.confidence, 90);
909    }
910}