destructive_command_guard 0.4.3

A Claude Code hook that blocks destructive commands before they execute
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
#![allow(
    clippy::format_push_string,
    clippy::map_unwrap_or,
    clippy::needless_raw_string_hashes,
    clippy::uninlined_format_args,
    clippy::unnecessary_map_or
)]
//! Integration tests for scan mode extractors
//!
//! These tests verify that each file type extractor correctly identifies
//! and extracts commands from real-world file formats.
//!
//! Related bead: git_safety_guard-l9ig

use std::process::Command;

/// Run dcg scan command and return output
fn run_dcg_scan(args: &[&str]) -> std::process::Output {
    let dcg_bin = std::env::var("DCG_BIN")
        .map(std::path::PathBuf::from)
        .or_else(|_| {
            std::env::var_os("CARGO_BIN_EXE_dcg")
                .map(std::path::PathBuf::from)
                .ok_or(std::env::VarError::NotPresent)
        })
        .unwrap_or_else(|_| {
            let mut path = std::env::current_exe().expect("current_exe");
            path.pop(); // test binary name
            path.pop(); // deps/
            path.push("dcg");
            path
        });

    Command::new(dcg_bin)
        .args(["scan"])
        .args(args)
        .output()
        .expect("Failed to execute dcg")
}

// ============================================================================
// Dockerfile Extractor Integration Tests
// ============================================================================

#[test]
fn scan_dockerfile_extracts_run_commands() {
    let dir = tempfile::tempdir().unwrap();
    let dockerfile = dir.path().join("Dockerfile");
    std::fs::write(
        &dockerfile,
        r#"FROM alpine:3.18
RUN apk add --no-cache curl
RUN git clone https://example.com/repo.git && git reset --hard HEAD~1
COPY . /app
CMD ["./app"]
"#,
    )
    .unwrap();

    let output = run_dcg_scan(&["--paths", dir.path().to_str().unwrap(), "--format", "json"]);

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");

    // Should find the git reset --hard command
    let findings = json["findings"].as_array().unwrap();
    assert!(
        findings.iter().any(|f| f["file"]
            .as_str()
            .map_or(false, |s| s.contains("Dockerfile"))),
        "should have findings from Dockerfile"
    );
    assert!(
        findings.iter().any(|f| {
            f["extracted_command"]
                .as_str()
                .map_or(false, |s| s.contains("git reset"))
        }),
        "should detect git reset command"
    );
}

#[test]
fn scan_dockerfile_multiline_run() {
    let dir = tempfile::tempdir().unwrap();
    let dockerfile = dir.path().join("Dockerfile");
    std::fs::write(
        &dockerfile,
        r#"FROM ubuntu:22.04
RUN apt-get update \
    && apt-get install -y curl \
    && git reset --hard HEAD
"#,
    )
    .unwrap();

    let output = run_dcg_scan(&["--paths", dir.path().to_str().unwrap(), "--format", "json"]);

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let findings = json["findings"].as_array().unwrap();

    assert!(
        !findings.is_empty(),
        "should extract commands from multiline RUN"
    );
}

// ============================================================================
// Makefile Extractor Integration Tests
// ============================================================================

#[test]
fn scan_makefile_extracts_recipe_commands() {
    let dir = tempfile::tempdir().unwrap();
    let makefile = dir.path().join("Makefile");
    std::fs::write(
        &makefile,
        r#"clean:
	rm -rf build/
	git reset --hard

build:
	cargo build --release

deploy:
	git push --force origin main
"#,
    )
    .unwrap();

    let output = run_dcg_scan(&["--paths", dir.path().to_str().unwrap(), "--format", "json"]);

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let findings = json["findings"].as_array().unwrap();

    // Should find git reset --hard and git push --force
    assert!(
        findings
            .iter()
            .any(|f| f["file"].as_str().map_or(false, |s| s.contains("Makefile"))),
        "should have findings from Makefile"
    );
}

#[test]
fn scan_makefile_ignores_variable_assignments() {
    let dir = tempfile::tempdir().unwrap();
    let makefile = dir.path().join("Makefile");
    std::fs::write(
        &makefile,
        r#"CLEANUP_CMD = rm -rf /
DANGER = git reset --hard

clean:
	echo "safe"
"#,
    )
    .unwrap();

    let output = run_dcg_scan(&["--paths", dir.path().to_str().unwrap(), "--format", "json"]);

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let findings = json["findings"].as_array().unwrap();

    // Variable assignments should NOT be extracted as commands
    assert!(
        findings.is_empty()
            || !findings.iter().any(|f| {
                f["command"]
                    .as_str()
                    .map_or(false, |s| s.contains("CLEANUP_CMD"))
            }),
        "should not extract variable assignments"
    );
}

// ============================================================================
// GitHub Actions Extractor Integration Tests
// ============================================================================

#[test]
fn scan_github_actions_extracts_run_steps() {
    let dir = tempfile::tempdir().unwrap();
    let workflow_dir = dir.path().join(".github").join("workflows");
    std::fs::create_dir_all(&workflow_dir).unwrap();
    let workflow = workflow_dir.join("ci.yml");
    std::fs::write(
        &workflow,
        r#"name: CI
on: [push]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm ci
      - run: git reset --hard HEAD~5
      - run: |
          echo "Building..."
          npm run build
"#,
    )
    .unwrap();

    let output = run_dcg_scan(&["--paths", dir.path().to_str().unwrap(), "--format", "json"]);

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let findings = json["findings"].as_array().unwrap();

    assert!(
        findings
            .iter()
            .any(|f| f["file"].as_str().map_or(false, |s| s.contains("ci.yml"))),
        "should have findings from GitHub Actions workflow"
    );
}

#[test]
fn scan_github_actions_ignores_env_values() {
    let dir = tempfile::tempdir().unwrap();
    let workflow_dir = dir.path().join(".github").join("workflows");
    std::fs::create_dir_all(&workflow_dir).unwrap();
    let workflow = workflow_dir.join("test.yml");
    std::fs::write(
        &workflow,
        r#"name: Test
on: [push]
jobs:
  test:
    runs-on: ubuntu-latest
    env:
      DANGEROUS: "git reset --hard"
    steps:
      - run: echo "safe"
"#,
    )
    .unwrap();

    let output = run_dcg_scan(&["--paths", dir.path().to_str().unwrap(), "--format", "json"]);

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let findings = json["findings"].as_array().unwrap();

    // env: values should NOT trigger findings
    assert!(
        findings.is_empty(),
        "should not flag env variable values as dangerous"
    );
}

// ============================================================================
// GitLab CI Extractor Integration Tests
// ============================================================================

#[test]
fn scan_gitlab_ci_extracts_script_sections() {
    let dir = tempfile::tempdir().unwrap();
    let gitlab_ci = dir.path().join(".gitlab-ci.yml");
    std::fs::write(
        &gitlab_ci,
        r#"stages:
  - build
  - deploy

build:
  stage: build
  script:
    - npm ci
    - npm run build

deploy:
  stage: deploy
  script:
    - git push --force origin main
"#,
    )
    .unwrap();

    let output = run_dcg_scan(&["--paths", dir.path().to_str().unwrap(), "--format", "json"]);

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let findings = json["findings"].as_array().unwrap();

    assert!(
        findings.iter().any(|f| f["file"]
            .as_str()
            .map_or(false, |s| s.contains(".gitlab-ci.yml"))),
        "should have findings from GitLab CI"
    );
}

// ============================================================================
// package.json Extractor Integration Tests
// ============================================================================

#[test]
fn scan_package_json_extracts_scripts() {
    let dir = tempfile::tempdir().unwrap();
    let package_json = dir.path().join("package.json");
    std::fs::write(
        &package_json,
        r#"{
  "name": "test-package",
  "scripts": {
    "clean": "rm -rf dist node_modules",
    "deploy": "git push --force",
    "build": "tsc"
  }
}"#,
    )
    .unwrap();

    let output = run_dcg_scan(&["--paths", dir.path().to_str().unwrap(), "--format", "json"]);

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let findings = json["findings"].as_array().unwrap();

    assert!(
        findings.iter().any(|f| f["file"]
            .as_str()
            .map_or(false, |s| s.contains("package.json"))),
        "should have findings from package.json"
    );
}

#[test]
fn scan_package_json_ignores_description() {
    let dir = tempfile::tempdir().unwrap();
    let package_json = dir.path().join("package.json");
    std::fs::write(
        &package_json,
        r#"{
  "name": "test-package",
  "description": "Uses rm -rf to clean build artifacts",
  "scripts": {
    "build": "tsc"
  }
}"#,
    )
    .unwrap();

    let output = run_dcg_scan(&["--paths", dir.path().to_str().unwrap(), "--format", "json"]);

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let findings = json["findings"].as_array().unwrap();

    // description field should NOT trigger findings
    assert!(
        findings.is_empty(),
        "should not flag description field content"
    );
}

// ============================================================================
// Terraform Extractor Integration Tests
// ============================================================================

#[test]
fn scan_terraform_extracts_local_exec() {
    let dir = tempfile::tempdir().unwrap();
    let terraform = dir.path().join("main.tf");
    std::fs::write(
        &terraform,
        r#"resource "null_resource" "cleanup" {
  provisioner "local-exec" {
    command = "rm -rf /tmp/build && git reset --hard"
  }
}
"#,
    )
    .unwrap();

    let output = run_dcg_scan(&["--paths", dir.path().to_str().unwrap(), "--format", "json"]);

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let findings = json["findings"].as_array().unwrap();

    assert!(
        findings
            .iter()
            .any(|f| f["file"].as_str().map_or(false, |s| s.contains("main.tf"))),
        "should have findings from Terraform local-exec"
    );
}

// ============================================================================
// Docker Compose Extractor Integration Tests
// ============================================================================

#[test]
fn scan_docker_compose_extracts_command() {
    let dir = tempfile::tempdir().unwrap();
    let compose = dir.path().join("docker-compose.yml");
    std::fs::write(
        &compose,
        r#"services:
  app:
    image: alpine
    command: sh -c "git reset --hard && ./start.sh"
"#,
    )
    .unwrap();

    let output = run_dcg_scan(&["--paths", dir.path().to_str().unwrap(), "--format", "json"]);

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    eprintln!("stdout: {}", stdout);
    eprintln!("stderr: {}", stderr);
    eprintln!("dir path: {}", dir.path().display());
    let json: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let findings = json["findings"].as_array().unwrap();

    assert!(
        findings.iter().any(|f| f["file"]
            .as_str()
            .map_or(false, |s| s.contains("docker-compose.yml"))),
        "should have findings from docker-compose.yml: findings={:?}",
        findings
    );
}

#[test]
fn scan_docker_compose_ignores_environment() {
    let dir = tempfile::tempdir().unwrap();
    let compose = dir.path().join("docker-compose.yml");
    std::fs::write(
        &compose,
        r#"services:
  app:
    image: alpine
    environment:
      DANGER: "git reset --hard"
    command: echo safe
"#,
    )
    .unwrap();

    let output = run_dcg_scan(&["--paths", dir.path().to_str().unwrap(), "--format", "json"]);

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let findings = json["findings"].as_array().unwrap();

    // environment values should NOT trigger findings
    assert!(
        findings.is_empty(),
        "should not flag environment variable values"
    );
}

// ============================================================================
// Multi-File Repository Integration Test
// ============================================================================

#[test]
fn scan_multi_format_repository() {
    let dir = tempfile::tempdir().unwrap();

    // Create shell script
    let shell = dir.path().join("deploy.sh");
    std::fs::write(&shell, "#!/bin/bash\ngit push --force\n").unwrap();

    // Create Dockerfile
    let dockerfile = dir.path().join("Dockerfile");
    std::fs::write(&dockerfile, "FROM alpine\nRUN git reset --hard\n").unwrap();

    // Create Makefile
    let makefile = dir.path().join("Makefile");
    std::fs::write(&makefile, "deploy:\n\tgit push --force\n").unwrap();

    // Create GitHub Actions
    let workflow_dir = dir.path().join(".github").join("workflows");
    std::fs::create_dir_all(&workflow_dir).unwrap();
    let workflow = workflow_dir.join("ci.yml");
    std::fs::write(
        &workflow,
        "jobs:\n  build:\n    steps:\n      - run: git reset --hard\n",
    )
    .unwrap();

    let output = run_dcg_scan(&["--paths", dir.path().to_str().unwrap(), "--format", "json"]);

    let stdout = String::from_utf8_lossy(&output.stdout);
    let json: serde_json::Value = serde_json::from_str(&stdout).expect("valid JSON");
    let summary = &json["summary"];

    // Should scan multiple file types
    assert!(
        summary["files_scanned"].as_u64().unwrap() >= 4,
        "should scan at least 4 files"
    );

    let findings = json["findings"].as_array().unwrap();
    assert!(
        !findings.is_empty(),
        "should have findings across multiple file types"
    );
}

// ============================================================================
// Performance Test
// ============================================================================

#[test]
fn scan_performance_large_dockerfile() {
    let dir = tempfile::tempdir().unwrap();
    let dockerfile = dir.path().join("Dockerfile");

    // Generate large Dockerfile with many RUN commands
    let mut content = String::from("FROM alpine\n");
    for i in 0..500 {
        content.push_str(&format!("RUN echo step{}\n", i));
    }
    content.push_str("RUN git reset --hard\n");
    std::fs::write(&dockerfile, &content).unwrap();

    let start = std::time::Instant::now();
    let output = run_dcg_scan(&["--paths", dir.path().to_str().unwrap(), "--format", "json"]);
    let elapsed = start.elapsed();

    assert!(output.status.success() || !output.status.success()); // Either outcome is fine
    assert!(
        elapsed.as_millis() < 5000,
        "scanning large Dockerfile should complete in < 5s"
    );
}