cert-x-gen 1.9.2

Advanced Multi-Language Security Scanning Engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
//! Template search functionality for CERT-X-GEN

// Note: CLI types are defined in main.rs, not in the library
// We'll define the search types here instead
use crate::types::{Severity, TemplateLanguage};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::time::SystemTime;

/// Search arguments structure
#[derive(Debug, Clone)]
pub struct SearchArgs {
    /// Search query string
    pub query: Option<String>,
    /// Filter by template language
    pub language: Option<TemplateLanguage>,
    /// Filter by severity level
    pub severity: Option<Severity>,
    /// Filter by tags (comma-separated)
    pub tags: Option<String>,
    /// Filter by author name
    pub author: Option<String>,
    /// Filter by CWE identifier

    /// CWE identifier if applicable
    pub cwe: Option<String>,
    /// Search in template content
    pub content: bool,
    /// Case-sensitive search
    pub case_sensitive: bool,
    /// Use regex for search
    pub regex: bool,
    /// Maximum number of results
    pub limit: usize,
    /// Output format
    pub format: SearchFormat,
    /// Show detailed results
    pub detailed: bool,
    /// Sort order
    pub sort: SearchSort,
    /// Reverse sort order
    pub reverse: bool,
    /// Output only template IDs
    pub ids_only: bool,
    /// Show search statistics
    pub stats: bool,
}

/// Search output format
#[derive(Debug, Clone, Copy)]
pub enum SearchFormat {
    /// Table format
    Table,
    /// JSON format
    Json,
    /// YAML format
    Yaml,
    /// CSV format
    Csv,
    /// Simple list format
    List,
    /// Detailed format with all metadata
    Detailed,
}

/// Search sort options
#[derive(Debug, Clone, Copy)]
pub enum SearchSort {
    /// Sort by relevance score
    Relevance,
    /// Sort by template name
    Name,
    /// Sort by programming language
    Language,
    /// Sort by severity level
    Severity,
    /// Sort by author name
    Author,
    /// Sort by last modified date
    Date,
    /// Sort by popularity/usage
    Popularity,
}

/// Search result for a template
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchResult {
    /// Template ID
    pub id: String,
    /// Template name
    pub name: String,
    /// Template description
    pub description: String,
    /// Template language
    pub language: TemplateLanguage,
    /// Severity level
    pub severity: Severity,
    /// Author name
    pub author: String,
    /// Template tags
    pub tags: Vec<String>,
    /// Filter by CWE identifier

    /// CWE identifier if applicable
    pub cwe: Option<String>,
    /// File system path to template
    pub file_path: String,
    /// Search relevance score (0.0-1.0)
    pub relevance_score: f64,
    /// Fields that matched the search
    pub match_fields: Vec<String>,
    /// Preview of matching content
    pub content_preview: Option<String>,
}

/// Search statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchStats {
    /// Total number of templates in index
    pub total_templates: usize,
    /// Number of templates matching search
    pub matching_templates: usize,
    /// Template count by language
    pub languages: HashMap<TemplateLanguage, usize>,
    /// Template count by severity
    pub severities: HashMap<Severity, usize>,
    /// Search execution time in milliseconds
    pub search_time_ms: u64,
}

/// Template search engine
#[derive(Debug)]
pub struct TemplateSearchEngine {
    templates: Vec<SearchResult>,
    #[allow(dead_code)]
    index: HashMap<String, Vec<usize>>, // word -> template indices
    #[allow(dead_code)]
    content_index: HashMap<String, Vec<usize>>, // word -> template indices (content)
}

impl TemplateSearchEngine {
    /// Create a new search engine from loaded templates
    pub fn new(templates: Vec<Box<dyn crate::template::Template>>) -> Self {
        let mut search_results = Vec::new();
        let mut index = HashMap::new();
        let mut content_index = HashMap::new();

        for (i, template) in templates.iter().enumerate() {
            let metadata = template.metadata();

            // Create search result
            let search_result = SearchResult {
                id: metadata.id.clone(),
                name: metadata.name.clone(),
                description: metadata.description.clone(),
                language: metadata.language,
                severity: metadata.severity,
                author: metadata.author.name.clone(),
                tags: metadata.tags.clone(),
                cwe: metadata.cwe_ids.first().cloned(),
                file_path: metadata.file_path.to_string_lossy().to_string(),
                relevance_score: 0.0,
                match_fields: Vec::new(),
                content_preview: None,
            };

            // Build search index
            Self::index_template(&search_result, i, &mut index);

            // Build content index if available
            if let Ok(content) = fs::read_to_string(&metadata.file_path) {
                Self::index_content(&content, i, &mut content_index);
            }

            search_results.push(search_result);
        }

        Self {
            templates: search_results,
            index,
            content_index,
        }
    }

    /// Index a template for search
    fn index_template(
        template: &SearchResult,
        index: usize,
        search_index: &mut HashMap<String, Vec<usize>>,
    ) {
        let text = format!(
            "{} {} {} {} {}",
            template.id,
            template.name,
            template.description,
            template.author,
            template.tags.join(" ")
        );

        for word in Self::extract_words(&text) {
            search_index.entry(word).or_default().push(index);
        }
    }

    /// Index template content for search
    fn index_content(content: &str, index: usize, content_index: &mut HashMap<String, Vec<usize>>) {
        for word in Self::extract_words(content) {
            content_index.entry(word).or_default().push(index);
        }
    }

    /// Extract words from text for indexing
    fn extract_words(text: &str) -> Vec<String> {
        text.split_whitespace()
            .map(|word| word.to_lowercase())
            .filter(|word| word.len() > 2) // Filter out short words
            .collect()
    }

    /// Search templates with the given criteria
    pub fn search(&self, args: &SearchArgs) -> (Vec<SearchResult>, SearchStats) {
        let start_time = SystemTime::now();

        let mut results = self.templates.clone();
        let total_templates = results.len();

        // Apply filters
        results = self.apply_filters(results, args);

        // Apply search query
        if let Some(query) = &args.query {
            results = self.apply_search_query(results, query, args);
        }

        // Sort results
        results = self.sort_results(results, args);

        // Apply limit
        if results.len() > args.limit {
            results.truncate(args.limit);
        }

        // Calculate statistics
        let search_time = start_time.elapsed().unwrap_or_default().as_millis() as u64;
        let stats = self.calculate_stats(&results, total_templates, search_time);

        (results, stats)
    }

    /// Apply filters to search results
    fn apply_filters(
        &self,
        mut results: Vec<SearchResult>,
        args: &SearchArgs,
    ) -> Vec<SearchResult> {
        // Filter by language
        if let Some(language) = &args.language {
            let target_language: TemplateLanguage = *language;
            results.retain(|template| template.language == target_language);
        }

        // Filter by severity
        if let Some(severity) = &args.severity {
            let target_severity: Severity = *severity;
            results.retain(|template| template.severity == target_severity);
        }

        // Filter by tags
        if let Some(tags) = &args.tags {
            let target_tags: Vec<String> = tags.split(',').map(|s| s.trim().to_string()).collect();
            results.retain(|template| target_tags.iter().any(|tag| template.tags.contains(tag)));
        }

        // Filter by author
        if let Some(author) = &args.author {
            results.retain(|template| {
                template
                    .author
                    .to_lowercase()
                    .contains(&author.to_lowercase())
            });
        }

        // Filter by CWE
        if let Some(cwe) = &args.cwe {
            results.retain(|template| template.cwe.as_ref().is_some_and(|t| t.contains(cwe)));
        }

        results
    }

    /// Apply search query to results
    fn apply_search_query(
        &self,
        mut results: Vec<SearchResult>,
        query: &str,
        args: &SearchArgs,
    ) -> Vec<SearchResult> {
        let query_lower = if args.case_sensitive {
            query.to_string()
        } else {
            query.to_lowercase()
        };

        // Create regex if requested
        let regex = if args.regex {
            Regex::new(&query_lower).ok()
        } else {
            None
        };

        // Score and filter results
        for result in &mut results {
            let mut score = 0.0;
            let mut match_fields = Vec::new();

            // Search in basic fields
            let fields = [
                ("id", &result.id),
                ("name", &result.name),
                ("description", &result.description),
                ("author", &result.author),
                ("tags", &result.tags.join(" ")),
            ];

            for (field_name, field_value) in &fields {
                let field_lower: String = if args.case_sensitive {
                    field_value.to_string()
                } else {
                    field_value.to_lowercase()
                };

                if let Some(regex) = &regex {
                    if regex.is_match(&field_lower) {
                        score += 10.0;
                        match_fields.push(field_name.to_string());
                    }
                } else if field_lower.contains(&query_lower) {
                    // Exact match gets higher score
                    if field_lower == query_lower {
                        score += 20.0;
                    } else {
                        score += 5.0;
                    }
                    match_fields.push(field_name.to_string());
                }
            }

            // Search in content if requested
            if args.content {
                if let Ok(content) = fs::read_to_string(&result.file_path) {
                    let content_lower = if args.case_sensitive {
                        content.clone()
                    } else {
                        content.to_lowercase()
                    };

                    if let Some(regex) = &regex {
                        if regex.is_match(&content_lower) {
                            score += 2.0;
                            match_fields.push("content".to_string());

                            // Add content preview
                            if result.content_preview.is_none() {
                                result.content_preview =
                                    Some(self.extract_preview(&content, &query_lower));
                            }
                        }
                    } else if content_lower.contains(&query_lower) {
                        score += 1.0;
                        match_fields.push("content".to_string());

                        // Add content preview
                        if result.content_preview.is_none() {
                            result.content_preview =
                                Some(self.extract_preview(&content, &query_lower));
                        }
                    }
                }
            }

            result.relevance_score = score;
            result.match_fields = match_fields;
        }

        // Filter out results with zero score
        results.retain(|result| result.relevance_score > 0.0);

        results
    }

    /// Extract a preview of content around the search term
    fn extract_preview(&self, content: &str, query: &str) -> String {
        const PREVIEW_LENGTH: usize = 200;

        if let Some(pos) = content.to_lowercase().find(&query.to_lowercase()) {
            let start = pos.saturating_sub(PREVIEW_LENGTH / 2);
            let end = (pos + query.len() + PREVIEW_LENGTH / 2).min(content.len());
            let preview = &content[start..end];

            if start > 0 {
                format!("...{}...", preview)
            } else {
                format!("{}...", preview)
            }
        } else {
            content.chars().take(PREVIEW_LENGTH).collect::<String>() + "..."
        }
    }

    /// Sort results based on the specified criteria
    fn sort_results(&self, mut results: Vec<SearchResult>, args: &SearchArgs) -> Vec<SearchResult> {
        match args.sort {
            SearchSort::Relevance => {
                results.sort_by(|a, b| b.relevance_score.partial_cmp(&a.relevance_score).unwrap());
            }
            SearchSort::Name => {
                results.sort_by(|a, b| a.name.cmp(&b.name));
            }
            SearchSort::Language => {
                results
                    .sort_by(|a, b| format!("{:?}", a.language).cmp(&format!("{:?}", b.language)));
            }
            SearchSort::Severity => {
                results.sort_by(|a, b| {
                    let severity_order = [
                        Severity::Critical,
                        Severity::High,
                        Severity::Medium,
                        Severity::Low,
                        Severity::Info,
                    ];
                    let a_order = severity_order
                        .iter()
                        .position(|&s| s == a.severity)
                        .unwrap_or(5);
                    let b_order = severity_order
                        .iter()
                        .position(|&s| s == b.severity)
                        .unwrap_or(5);
                    a_order.cmp(&b_order)
                });
            }
            SearchSort::Author => {
                results.sort_by(|a, b| a.author.cmp(&b.author));
            }
            SearchSort::Date => {
                // For now, sort by file modification time
                results.sort_by(|a, b| {
                    let a_time = fs::metadata(&a.file_path)
                        .and_then(|m| m.modified())
                        .unwrap_or(SystemTime::UNIX_EPOCH);
                    let b_time = fs::metadata(&b.file_path)
                        .and_then(|m| m.modified())
                        .unwrap_or(SystemTime::UNIX_EPOCH);
                    b_time.cmp(&a_time) // Newest first
                });
            }
            SearchSort::Popularity => {
                // For now, sort by relevance score as a proxy for popularity
                results.sort_by(|a, b| b.relevance_score.partial_cmp(&a.relevance_score).unwrap());
            }
        }

        if args.reverse {
            results.reverse();
        }

        results
    }

    /// Calculate search statistics
    fn calculate_stats(
        &self,
        results: &[SearchResult],
        total_templates: usize,
        search_time_ms: u64,
    ) -> SearchStats {
        let mut languages = HashMap::new();
        let mut severities = HashMap::new();

        for result in results {
            *languages.entry(result.language).or_insert(0) += 1;
            *severities.entry(result.severity).or_insert(0) += 1;
        }

        SearchStats {
            total_templates,
            matching_templates: results.len(),
            languages,
            severities,
            search_time_ms,
        }
    }
}

/// Format search results for output
#[derive(Debug)]
pub struct SearchResultFormatter;

impl SearchResultFormatter {
    /// Format search results based on the specified format
    pub fn format_results(
        results: &[SearchResult],
        stats: &SearchStats,
        format: SearchFormat,
        detailed: bool,
        ids_only: bool,
    ) -> String {
        match format {
            SearchFormat::Table => Self::format_table(results, stats, detailed),
            SearchFormat::Json => Self::format_json(results, stats),
            SearchFormat::Yaml => Self::format_yaml(results, stats),
            SearchFormat::Csv => Self::format_csv(results),
            SearchFormat::List => Self::format_list(results, ids_only),
            SearchFormat::Detailed => Self::format_detailed(results, stats),
        }
    }

    /// Format results as a table
    fn format_table(results: &[SearchResult], stats: &SearchStats, detailed: bool) -> String {
        let mut output = String::new();

        // Add statistics
        output.push_str(&format!(
            "Found {} templates ({} total)\n",
            stats.matching_templates, stats.total_templates
        ));
        output.push_str(&format!("Search time: {}ms\n\n", stats.search_time_ms));

        if results.is_empty() {
            output.push_str("No templates found matching your criteria.\n");
            return output;
        }

        if detailed {
            // Detailed table format
            output.push_str("┌─────────────────────────────────────────────────────────────────────────────────────────────────┐\n");
            output.push_str("│ Template Search Results                                                                        │\n");
            output.push_str("├─────────────────────────────────────────────────────────────────────────────────────────────────┤\n");

            for result in results {
                output.push_str(&format!(
                    "│ ID: {:<20} │ Name: {:<30} │ Language: {:<10} │ Severity: {:<8} │\n",
                    result.id,
                    result.name,
                    format!("{:?}", result.language),
                    format!("{:?}", result.severity)
                ));
                output.push_str(&format!(
                    "│ Author: {:<18} │ Tags: {:<40} │ Score: {:<8.2} │\n",
                    result.author,
                    result.tags.join(", "),
                    result.relevance_score
                ));
                if !result.match_fields.is_empty() {
                    output.push_str(&format!(
                        "│ Matched in: {:<66} │\n",
                        result.match_fields.join(", ")
                    ));
                }
                if let Some(preview) = &result.content_preview {
                    output.push_str(&format!(
                        "│ Preview: {:<68} │\n",
                        preview.chars().take(70).collect::<String>()
                    ));
                }
                output.push_str("├─────────────────────────────────────────────────────────────────────────────────────────────────┤\n");
            }
            output.push_str("└─────────────────────────────────────────────────────────────────────────────────────────────────┘\n");
        } else {
            // Simple table format
            output.push_str("┌─────────────────────────────────────────────────────────────────────────────────────────────────┐\n");
            output.push_str("│ ID                    │ Name                          │ Language   │ Severity │ Score │\n");
            output.push_str("├─────────────────────────────────────────────────────────────────────────────────────────────────┤\n");

            for result in results {
                output.push_str(&format!(
                    "│ {:<20} │ {:<28} │ {:<10} │ {:<8} │ {:<5.2} │\n",
                    result.id,
                    result.name.chars().take(28).collect::<String>(),
                    format!("{:?}", result.language),
                    format!("{:?}", result.severity),
                    result.relevance_score
                ));
            }
            output.push_str("└─────────────────────────────────────────────────────────────────────────────────────────────────┘\n");
        }

        output
    }

    /// Format results as JSON
    fn format_json(results: &[SearchResult], stats: &SearchStats) -> String {
        let data = serde_json::json!({
            "statistics": stats,
            "results": results
        });
        serde_json::to_string_pretty(&data).unwrap_or_else(|_| "{}".to_string())
    }

    /// Format results as YAML
    fn format_yaml(results: &[SearchResult], stats: &SearchStats) -> String {
        serde_yaml::to_string(&serde_json::json!({
            "statistics": stats,
            "results": results
        }))
        .unwrap_or_else(|_| "".to_string())
    }

    /// Format results as CSV
    fn format_csv(results: &[SearchResult]) -> String {
        let mut output = String::new();
        output
            .push_str("ID,Name,Description,Language,Severity,Author,Tags,CWE,Score,Match Fields\n");

        for result in results {
            output.push_str(&format!(
                "{},{},{},{},{},{},{},{},{},{}\n",
                result.id,
                result.name,
                result.description.replace(',', ";"),
                format!("{:?}", result.language),
                format!("{:?}", result.severity),
                result.author,
                result.tags.join(";"),
                result.cwe.as_deref().unwrap_or(""),
                result.relevance_score,
                result.match_fields.join(";")
            ));
        }

        output
    }

    /// Format results as a simple list
    fn format_list(results: &[SearchResult], ids_only: bool) -> String {
        let mut output = String::new();

        if ids_only {
            for result in results {
                output.push_str(&format!("{}\n", result.id));
            }
        } else {
            for result in results {
                output.push_str(&format!(
                    "{} - {} ({:?}, {:?})\n",
                    result.id, result.name, result.language, result.severity
                ));
            }
        }

        output
    }

    /// Format results with detailed information
    fn format_detailed(results: &[SearchResult], stats: &SearchStats) -> String {
        let mut output = String::new();

        // Add statistics
        output.push_str(&format!(
            "Search Statistics:\n\
            - Total templates: {}\n\
            - Matching templates: {}\n\
            - Search time: {}ms\n\n",
            stats.total_templates, stats.matching_templates, stats.search_time_ms
        ));

        // Add language breakdown
        if !stats.languages.is_empty() {
            output.push_str("Languages:\n");
            for (language, count) in &stats.languages {
                output.push_str(&format!("  - {:?}: {}\n", language, count));
            }
            output.push('\n');
        }

        // Add severity breakdown
        if !stats.severities.is_empty() {
            output.push_str("Severities:\n");
            for (severity, count) in &stats.severities {
                output.push_str(&format!("  - {:?}: {}\n", severity, count));
            }
            output.push('\n');
        }

        // Add detailed results
        for (i, result) in results.iter().enumerate() {
            output.push_str(&format!(
                "Result {}: {}\n\
                ===================\n\
                ID: {}\n\
                Name: {}\n\
                Description: {}\n\
                Language: {:?}\n\
                Severity: {:?}\n\
                Author: {}\n\
                Tags: {}\n\
                CWE: {}\n\
                File: {}\n\
                Relevance Score: {:.2}\n\
                Match Fields: {}\n",
                i + 1,
                result.name,
                result.id,
                result.name,
                result.description,
                result.language,
                result.severity,
                result.author,
                result.tags.join(", "),
                result.cwe.as_deref().unwrap_or("N/A"),
                result.file_path,
                result.relevance_score,
                result.match_fields.join(", ")
            ));

            if let Some(preview) = &result.content_preview {
                output.push_str(&format!("Content Preview: {}\n", preview));
            }

            output.push('\n');
        }

        output
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_search_engine_creation() {
        // This would need actual template data to test
        // For now, just test that the struct can be created
        let engine = TemplateSearchEngine {
            templates: Vec::new(),
            index: HashMap::new(),
            content_index: HashMap::new(),
        };
        assert_eq!(engine.templates.len(), 0);
    }

    #[test]
    fn test_word_extraction() {
        let text = "SQL injection detection template";
        let words = TemplateSearchEngine::extract_words(text);
        assert!(words.contains(&"sql".to_string()));
        assert!(words.contains(&"injection".to_string()));
        assert!(words.contains(&"detection".to_string()));
        assert!(words.contains(&"template".to_string()));
    }

    #[test]
    fn test_content_preview_extraction() {
        let engine = TemplateSearchEngine {
            templates: Vec::new(),
            index: HashMap::new(),
            content_index: HashMap::new(),
        };

        let content = "This is a long content with the word injection in the middle of the text and more content after it";
        let query = "injection";
        let preview = engine.extract_preview(content, query);

        assert!(preview.contains("injection"));
        assert!(preview.len() <= 200 + 6); // 200 chars + "..."
    }
}