shipsafe 0.1.0

AI-Powered Pre-Deploy Security Gate
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
use crate::config::Config;
use crate::scanners::exec;
use crate::scanners::{Finding, ScanResults, Severity};
use anyhow::Result;
use std::path::Path;
use tokio::process::Command;

pub async fn run(path: &Path, config: &Config) -> Result<ScanResults> {
    // Check if semgrep is available
    if which::which("semgrep").is_err() {
        exec::warn_user(
            &config.lang,
            "semgrep not found — SAST scan skipped. Run 'shipsafe doctor' for install instructions.",
            "semgrep が見つかりません — SAST スキャンをスキップしました。'shipsafe doctor' でインストール方法を確認できます。",
        );
        return Ok(ScanResults::new());
    }

    let output = exec::run_scanner(
        "semgrep",
        || {
            let mut cmd = Command::new("semgrep");
            cmd.arg("scan").arg("--json").arg("--quiet").arg(path);
            build_semgrep_args(&mut cmd, config, path);
            cmd
        },
        config.scanners.timeout_seconds,
        &config.lang,
    )
    .await?;

    let Some(output) = output else {
        return Ok(ScanResults::new());
    };

    let stderr = String::from_utf8_lossy(&output.stderr);
    if !stderr.is_empty() {
        tracing::debug!("semgrep stderr: {}", stderr);
    }

    if !output.status.success() {
        let first = stderr.lines().next().unwrap_or("(no details)");
        exec::warn_user(
            &config.lang,
            &format!("semgrep exited with {}: {}", output.status, first),
            &format!("semgrep が異常終了しました ({}): {}", output.status, first),
        );
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    parse_semgrep_json(&stdout)
}

/// Bundled semgrep rules for AI-generated code patterns, embedded at build
/// time so the distributed binary does not depend on the repo layout.
const AI_GENERATED_CODE_RULES: &[(&str, &str)] = &[
    ("python.yml", include_str!("../../rules/sast/python.yml")),
    (
        "javascript.yml",
        include_str!("../../rules/sast/javascript.yml"),
    ),
    ("rust.yml", include_str!("../../rules/sast/rust.yml")),
    ("go.yml", include_str!("../../rules/sast/go.yml")),
];

/// Materialize the bundled AI-generated-code rules to a temp directory so
/// semgrep can consume them via --config. Each file is written to a unique
/// staging path first and renamed into place so concurrent invocations never
/// observe a partial file.
fn ai_generated_code_rules_path() -> std::io::Result<std::path::PathBuf> {
    use std::sync::atomic::{AtomicUsize, Ordering};
    static STAGING_COUNTER: AtomicUsize = AtomicUsize::new(0);

    let dir = std::env::temp_dir().join(format!(
        "shipsafe-{}-ai-generated-rules",
        env!("CARGO_PKG_VERSION")
    ));
    std::fs::create_dir_all(&dir)?;

    for (name, content) in AI_GENERATED_CODE_RULES {
        let path = dir.join(name);
        let staging = dir.join(format!(
            "{}.{}.{}.staging",
            name,
            std::process::id(),
            STAGING_COUNTER.fetch_add(1, Ordering::Relaxed)
        ));
        std::fs::write(&staging, content)?;
        if let Err(e) = std::fs::rename(&staging, &path) {
            // The rename can fail if the destination is locked (e.g. on
            // Windows while another process reads it). The content is
            // identical for a given version, so an existing destination is
            // safe to reuse.
            let _ = std::fs::remove_file(&staging);
            if !path.is_file() {
                return Err(e);
            }
        }
    }
    Ok(dir)
}

/// True if the file looks like a semgrep rule file (YAML with a top-level
/// `rules:` key). Used when auto-discovering a project's rules/ directory so
/// unrelated YAML never breaks the scan.
fn is_semgrep_rule_file(path: &Path) -> bool {
    let Ok(content) = std::fs::read_to_string(path) else {
        return false;
    };
    content
        .lines()
        .any(|line| line.trim_end() == "rules:" || line.starts_with("rules:"))
}

/// Discover custom semgrep rule files in `<scan-path>/rules/` (recursive).
fn discover_custom_rules(scan_path: &Path) -> Vec<std::path::PathBuf> {
    let rules_dir = scan_path.join("rules");
    if !rules_dir.is_dir() {
        return vec![];
    }
    let mut found: Vec<std::path::PathBuf> = walkdir::WalkDir::new(&rules_dir)
        .into_iter()
        .filter_map(|e| e.ok())
        .filter(|e| {
            e.file_type().is_file()
                && matches!(
                    e.path().extension().and_then(|x| x.to_str()),
                    Some("yml") | Some("yaml")
                )
                && is_semgrep_rule_file(e.path())
        })
        .map(|e| e.into_path())
        .collect();
    found.sort();
    found
}

/// Build semgrep rule config and exclude arguments.
fn build_semgrep_args(cmd: &mut Command, config: &Config, scan_path: &Path) {
    // Add rule configs; default to OWASP Top 10 if none specified
    let rules = &config.scanners.sast.rules;
    if rules.is_empty() {
        cmd.arg("--config").arg("p/owasp-top-ten");
    } else {
        for rule in rules {
            match rule.as_str() {
                "owasp-top-10" => {
                    cmd.arg("--config").arg("p/owasp-top-ten");
                }
                "ai-generated-code" => match ai_generated_code_rules_path() {
                    Ok(path) => {
                        cmd.arg("--config").arg(path);
                    }
                    Err(e) => {
                        tracing::warn!(
                            "failed to materialize bundled ai-generated-code rules, skipping: {}",
                            e
                        );
                    }
                },
                other => {
                    cmd.arg("--config").arg(other);
                }
            }
        }
    }

    // Explicit custom rule files/dirs from .shipsafe.yml
    for rules_path in &config.scanners.sast.rules_paths {
        cmd.arg("--config").arg(rules_path);
    }

    // Auto-discovered rules from the project's rules/ directory
    for rule_file in discover_custom_rules(scan_path) {
        cmd.arg("--config").arg(rule_file);
    }

    // Disabled rule IDs
    for rule_id in &config.scanners.sast.disabled_rules {
        cmd.arg("--exclude-rule").arg(rule_id);
    }

    // Add excludes
    for exclude in &config.scanners.sast.exclude {
        cmd.arg("--exclude").arg(exclude);
    }
}

/// Map semgrep severity string to internal Severity enum.
fn map_severity(s: Option<&str>) -> Severity {
    match s {
        Some("ERROR") => Severity::Critical,
        Some("WARNING") => Severity::Medium,
        Some("INFO") => Severity::Low,
        _ => Severity::Medium,
    }
}

/// Extract CWE from semgrep metadata, handling both string and array values.
fn extract_cwe(metadata: Option<&serde_json::Value>) -> Option<String> {
    let cwe = metadata?.get("cwe")?;
    if let Some(s) = cwe.as_str() {
        return Some(s.to_string());
    }
    if let Some(arr) = cwe.as_array() {
        let cwe_strs: Vec<&str> = arr.iter().filter_map(|v| v.as_str()).collect();
        if !cwe_strs.is_empty() {
            return Some(cwe_strs.join(", "));
        }
    }
    None
}

/// Parse semgrep JSON output and convert to ScanResults.
fn parse_semgrep_json(json_str: &str) -> Result<ScanResults> {
    let mut results = ScanResults::new();

    let json: serde_json::Value = match serde_json::from_str(json_str) {
        Ok(v) => v,
        Err(_) => return Ok(results),
    };

    if let Some(semgrep_results) = json.get("results").and_then(|r| r.as_array()) {
        for result in semgrep_results {
            let severity = map_severity(
                result
                    .get("extra")
                    .and_then(|e| e.get("severity"))
                    .and_then(|s| s.as_str()),
            );

            let metadata = result.get("extra").and_then(|e| e.get("metadata"));

            let finding = Finding {
                id: result
                    .get("check_id")
                    .and_then(|c| c.as_str())
                    .unwrap_or("unknown")
                    .to_string(),
                scanner: "sast".to_string(),
                severity,
                title: result
                    .get("check_id")
                    .and_then(|c| c.as_str())
                    .unwrap_or("")
                    .to_string(),
                description: result
                    .get("extra")
                    .and_then(|e| e.get("message"))
                    .and_then(|m| m.as_str())
                    .unwrap_or("")
                    .to_string(),
                file: result
                    .get("path")
                    .and_then(|p| p.as_str())
                    .unwrap_or("")
                    .to_string(),
                line: result
                    .get("start")
                    .and_then(|s| s.get("line"))
                    .and_then(|l| l.as_u64())
                    .map(|l| l as u32),
                cwe: extract_cwe(metadata),
                cve: None,
                fix_suggestion: result
                    .get("extra")
                    .and_then(|e| e.get("fix"))
                    .and_then(|f| f.as_str())
                    .map(|s| s.to_string()),
            };
            results.findings.push(finding);
        }
    }

    results.recalculate_summary();

    Ok(results)
}

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

    #[test]
    fn test_severity_mapping() {
        assert_eq!(map_severity(Some("ERROR")), Severity::Critical);
        assert_eq!(map_severity(Some("WARNING")), Severity::Medium);
        assert_eq!(map_severity(Some("INFO")), Severity::Low);
        assert_eq!(map_severity(Some("UNKNOWN")), Severity::Medium);
        assert_eq!(map_severity(None), Severity::Medium);
    }

    #[test]
    fn test_extract_cwe_string() {
        let json: serde_json::Value = serde_json::json!({
            "cwe": "CWE-89: SQL Injection"
        });
        assert_eq!(
            extract_cwe(Some(&json)),
            Some("CWE-89: SQL Injection".to_string())
        );
    }

    #[test]
    fn test_extract_cwe_array() {
        let json: serde_json::Value = serde_json::json!({
            "cwe": ["CWE-79: XSS", "CWE-89: SQL Injection"]
        });
        assert_eq!(
            extract_cwe(Some(&json)),
            Some("CWE-79: XSS, CWE-89: SQL Injection".to_string())
        );
    }

    #[test]
    fn test_extract_cwe_missing() {
        let json: serde_json::Value = serde_json::json!({});
        assert_eq!(extract_cwe(Some(&json)), None);
        assert_eq!(extract_cwe(None), None);
    }

    #[test]
    fn test_parse_semgrep_json_with_results() {
        let json_str = r#"{
            "results": [
                {
                    "check_id": "python.lang.security.audit.exec-detected",
                    "path": "app.py",
                    "start": {"line": 42, "col": 1},
                    "end": {"line": 42, "col": 20},
                    "extra": {
                        "severity": "ERROR",
                        "message": "Detected use of exec(). This is dangerous.",
                        "metadata": {
                            "cwe": ["CWE-95: Improper Neutralization"]
                        },
                        "fix": "Use ast.literal_eval() instead."
                    }
                },
                {
                    "check_id": "python.lang.security.audit.logging-warn",
                    "path": "utils.py",
                    "start": {"line": 10, "col": 1},
                    "end": {"line": 10, "col": 30},
                    "extra": {
                        "severity": "WARNING",
                        "message": "Logging sensitive data.",
                        "metadata": {
                            "cwe": "CWE-532"
                        }
                    }
                },
                {
                    "check_id": "python.lang.best-practice.info-rule",
                    "path": "main.py",
                    "start": {"line": 5, "col": 1},
                    "end": {"line": 5, "col": 15},
                    "extra": {
                        "severity": "INFO",
                        "message": "Consider using a constant.",
                        "metadata": {}
                    }
                }
            ]
        }"#;

        let results = parse_semgrep_json(json_str).unwrap();

        assert_eq!(results.findings.len(), 3);
        assert_eq!(results.summary.total, 3);
        assert_eq!(results.summary.critical, 1);
        assert_eq!(results.summary.medium, 1);
        assert_eq!(results.summary.low, 1);

        // Check ERROR -> Critical mapping
        let f0 = &results.findings[0];
        assert_eq!(f0.severity, Severity::Critical);
        assert_eq!(f0.id, "python.lang.security.audit.exec-detected");
        assert_eq!(f0.scanner, "sast");
        assert_eq!(f0.file, "app.py");
        assert_eq!(f0.line, Some(42));
        assert_eq!(f0.cwe, Some("CWE-95: Improper Neutralization".to_string()));
        assert_eq!(
            f0.fix_suggestion,
            Some("Use ast.literal_eval() instead.".to_string())
        );

        // Check WARNING -> Medium mapping
        let f1 = &results.findings[1];
        assert_eq!(f1.severity, Severity::Medium);
        assert_eq!(f1.cwe, Some("CWE-532".to_string()));

        // Check INFO -> Low mapping
        let f2 = &results.findings[2];
        assert_eq!(f2.severity, Severity::Low);
        assert_eq!(f2.cwe, None);
    }

    #[test]
    fn test_parse_semgrep_json_empty_results() {
        let json_str = r#"{"results": []}"#;
        let results = parse_semgrep_json(json_str).unwrap();
        assert_eq!(results.findings.len(), 0);
        assert_eq!(results.summary.total, 0);
    }

    #[test]
    fn test_parse_semgrep_json_invalid() {
        let results = parse_semgrep_json("not valid json").unwrap();
        assert_eq!(results.findings.len(), 0);
    }

    #[test]
    fn test_parse_semgrep_json_missing_fields() {
        let json_str = r#"{
            "results": [
                {
                    "extra": {
                        "severity": "ERROR",
                        "message": "Some issue"
                    }
                }
            ]
        }"#;
        let results = parse_semgrep_json(json_str).unwrap();
        assert_eq!(results.findings.len(), 1);
        assert_eq!(results.findings[0].id, "unknown");
        assert_eq!(results.findings[0].file, "");
        assert_eq!(results.findings[0].line, None);
        assert_eq!(results.findings[0].cwe, None);
    }

    #[test]
    fn test_default_config_has_owasp_rules() {
        let config = Config::default();
        assert!(config
            .scanners
            .sast
            .rules
            .contains(&"owasp-top-10".to_string()));
    }

    /// Helper to extract args from a Command for testing.
    fn get_args(cmd: &Command) -> Vec<String> {
        cmd.as_std()
            .get_args()
            .map(|a| a.to_string_lossy().to_string())
            .collect()
    }

    #[test]
    fn test_empty_rules_defaults_to_owasp_args() {
        let mut config = Config::default();
        config.scanners.sast.rules = vec![];
        config.scanners.sast.exclude = vec![];

        let mut cmd = Command::new("semgrep");
        build_semgrep_args(&mut cmd, &config, Path::new("."));

        let args = get_args(&cmd);
        assert!(args.contains(&"--config".to_string()));
        assert!(args.contains(&"p/owasp-top-ten".to_string()));
    }

    #[test]
    fn test_custom_rules_args() {
        let mut config = Config::default();
        config.scanners.sast.rules = vec!["owasp-top-10".into(), "ai-generated-code".into()];
        config.scanners.sast.exclude = vec!["vendor".into()];

        let mut cmd = Command::new("semgrep");
        build_semgrep_args(&mut cmd, &config, Path::new("."));

        let args = get_args(&cmd);
        assert!(args.contains(&"p/owasp-top-ten".to_string()));
        assert!(args.iter().any(|a| a.ends_with("ai-generated-rules")));
        assert!(args.contains(&"--exclude".to_string()));
        assert!(args.contains(&"vendor".to_string()));
    }

    #[test]
    fn test_rules_paths_and_disabled_rules_args() {
        let mut config = Config::default();
        config.scanners.sast.rules_paths = vec!["./my-rules/".into()];
        config.scanners.sast.disabled_rules = vec!["ai-rust-unsafe-block".into()];

        let mut cmd = Command::new("semgrep");
        build_semgrep_args(&mut cmd, &config, Path::new("."));

        let args = get_args(&cmd);
        assert!(args.contains(&"./my-rules/".to_string()));
        assert!(args.contains(&"--exclude-rule".to_string()));
        assert!(args.contains(&"ai-rust-unsafe-block".to_string()));
    }

    #[test]
    fn test_discover_custom_rules() {
        let dir =
            std::env::temp_dir().join(format!("shipsafe-discover-test-{}", std::process::id()));
        let rules_dir = dir.join("rules");
        std::fs::create_dir_all(&rules_dir).unwrap();
        std::fs::write(
            rules_dir.join("custom.yml"),
            "rules:\n  - id: x\n    pattern: foo\n    message: m\n    languages: [python]\n    severity: ERROR\n",
        )
        .unwrap();
        // Non-rule YAML must be ignored.
        std::fs::write(rules_dir.join("docker-compose.yml"), "services: {}\n").unwrap();
        // Non-YAML files must be ignored.
        std::fs::write(rules_dir.join("README.md"), "rules:\n").unwrap();

        let found = discover_custom_rules(&dir);
        std::fs::remove_dir_all(&dir).ok();

        assert_eq!(found.len(), 1);
        assert!(found[0].ends_with("custom.yml"));
    }

    #[test]
    fn test_discover_custom_rules_no_dir() {
        assert!(discover_custom_rules(Path::new("/nonexistent-shipsafe")).is_empty());
    }

    #[test]
    fn test_ai_generated_code_rules_materialized() {
        let dir = ai_generated_code_rules_path().unwrap();
        assert!(dir.is_dir());

        let python = std::fs::read_to_string(dir.join("python.yml")).unwrap();
        assert!(python.contains("ai-py-hardcoded-credentials"));
        assert!(python.contains("ai-py-sql-injection-concat"));

        let js = std::fs::read_to_string(dir.join("javascript.yml")).unwrap();
        assert!(js.contains("ai-js-dangerously-set-inner-html"));

        let rust = std::fs::read_to_string(dir.join("rust.yml")).unwrap();
        assert!(rust.contains("ai-rust-mem-transmute"));

        let go = std::fs::read_to_string(dir.join("go.yml")).unwrap();
        assert!(go.contains("ai-go-empty-error-check"));
    }
}