destructive_command_guard 0.5.4

An AI coding agent 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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
#![allow(clippy::uninlined_format_args)]
//! Focused coverage for `dcg test` command behavior.

use std::path::{Path, PathBuf};
use std::process::{Command, Output};

/// Path to the dcg binary compiled for this test run.
fn dcg_binary() -> PathBuf {
    let mut path = std::env::current_exe().expect("current_exe");
    path.pop(); // test binary name
    path.pop(); // deps/
    path.push("dcg");
    path
}

fn stdout_text(output: &Output) -> String {
    String::from_utf8_lossy(&output.stdout).to_string()
}

fn stderr_text(output: &Output) -> String {
    String::from_utf8_lossy(&output.stderr).to_string()
}

/// Run dcg with an isolated HOME/XDG config to avoid machine-specific allowlists.
fn run_dcg_isolated(args: &[&str], cwd: Option<&Path>) -> Output {
    let home = tempfile::tempdir().expect("temp home");
    let xdg = home.path().join("xdg");
    std::fs::create_dir_all(&xdg).expect("create xdg config dir");

    let mut cmd = Command::new(dcg_binary());
    cmd.args(args)
        .env("HOME", home.path())
        .env("XDG_CONFIG_HOME", &xdg)
        .env("DCG_ALLOWLIST_SYSTEM_PATH", "");

    if let Some(dir) = cwd {
        cmd.current_dir(dir);
    }

    cmd.output().expect("run dcg")
}

fn parse_json(output: &Output) -> serde_json::Value {
    serde_json::from_str(&stdout_text(output)).expect("stdout should be valid JSON")
}

#[test]
fn test_basic_blocked_command_exits_one() {
    let output = run_dcg_isolated(&["test", "--format", "json", "git reset --hard"], None);

    assert_eq!(
        output.status.code(),
        Some(1),
        "blocked command should exit 1\nstderr: {}",
        stderr_text(&output)
    );

    let json = parse_json(&output);
    assert_eq!(json["decision"], "deny");
}

#[test]
fn test_basic_allowed_command_exits_zero() {
    let output = run_dcg_isolated(&["test", "--format", "json", "ls -la"], None);

    assert_eq!(
        output.status.code(),
        Some(0),
        "allowed command should exit 0\nstderr: {}",
        stderr_text(&output)
    );

    let json = parse_json(&output);
    assert_eq!(json["decision"], "allow");
}

#[test]
fn test_stdout_stderr_redirect_truncate_is_blocked() {
    let output = run_dcg_isolated(&["test", "--format", "json", ": >&/etc/passwd"], None);

    assert_eq!(
        output.status.code(),
        Some(1),
        "`>&word` stdout/stderr truncation should be blocked\nstdout: {}\nstderr: {}",
        stdout_text(&output),
        stderr_text(&output)
    );

    let json = parse_json(&output);
    assert_eq!(json["decision"], "deny");
    assert_eq!(json["pack_id"], "core.filesystem");
    assert_eq!(json["pattern_name"], "redirect-truncate-root-home");
}

#[test]
fn test_allowlist_match_allows_blocked_command() {
    let repo = tempfile::tempdir().expect("temp repo");
    std::fs::create_dir_all(repo.path().join(".git")).expect("create .git marker");
    std::fs::create_dir_all(repo.path().join(".dcg")).expect("create .dcg dir");
    std::fs::write(
        repo.path().join(".dcg").join("allowlist.toml"),
        r#"
[[allow]]
exact_command = "git reset --hard"
reason = "test fixture allowlist entry"
"#,
    )
    .expect("write allowlist");

    let output = run_dcg_isolated(
        &["test", "--format", "json", "git reset --hard"],
        Some(repo.path()),
    );

    assert_eq!(
        output.status.code(),
        Some(0),
        "allowlist match should allow command\nstderr: {}",
        stderr_text(&output)
    );

    let json = parse_json(&output);
    assert_eq!(json["decision"], "allow");
}

#[test]
fn test_json_output_has_expected_fields() {
    let output = run_dcg_isolated(&["test", "--format", "json", "git reset --hard"], None);
    let json = parse_json(&output);

    assert!(json.get("schema_version").is_some());
    assert!(json.get("dcg_version").is_some());
    assert!(json.get("robot_mode").is_some());
    assert!(json.get("command").is_some());
    assert!(json.get("decision").is_some());
}

#[test]
fn test_custom_config_is_applied() {
    let temp = tempfile::tempdir().expect("temp dir");
    let config_path = temp.path().join("custom.toml");
    std::fs::write(
        &config_path,
        r#"
[overrides]
allow = ["git reset --hard"]
"#,
    )
    .expect("write config");

    let config_arg = config_path.to_string_lossy().to_string();
    let output = run_dcg_isolated(
        &[
            "test",
            "--format",
            "json",
            "--config",
            config_arg.as_str(),
            "git reset --hard",
        ],
        None,
    );

    assert_eq!(
        output.status.code(),
        Some(0),
        "custom config override should allow command\nstderr: {}",
        stderr_text(&output)
    );

    let json = parse_json(&output);
    assert_eq!(json["decision"], "allow");
}

#[test]
fn test_config_block_override_wins_over_overlapping_allow_override() {
    let temp = tempfile::tempdir().expect("temp dir");
    let config_path = temp.path().join("custom.toml");
    std::fs::write(
        &config_path,
        r#"
[overrides]
allow = ["git reset --hard"]
block = [
  { pattern = "git reset --hard", reason = "explicit config block" },
]
"#,
    )
    .expect("write config");

    let config_arg = config_path.to_string_lossy().to_string();
    let output = run_dcg_isolated(
        &[
            "test",
            "--format",
            "json",
            "--config",
            config_arg.as_str(),
            "git reset --hard",
        ],
        None,
    );

    assert_eq!(
        output.status.code(),
        Some(1),
        "overlapping config block should deny command\nstdout: {}\nstderr: {}",
        stdout_text(&output),
        stderr_text(&output)
    );

    let json = parse_json(&output);
    assert_eq!(json["decision"], "deny");
    assert!(
        stdout_text(&output).contains("explicit config block"),
        "deny output should include config block reason\nstdout: {}\nstderr: {}",
        stdout_text(&output),
        stderr_text(&output)
    );
}

#[test]
fn test_project_config_discovery_is_applied_without_config_flag() {
    let repo = tempfile::tempdir().expect("temp repo");
    std::fs::create_dir_all(repo.path().join(".git")).expect("create .git marker");
    std::fs::write(
        repo.path().join(".dcg.toml"),
        r#"
[overrides]
allow = ["git reset --hard"]
"#,
    )
    .expect("write project config");

    let output = run_dcg_isolated(
        &["test", "--format", "json", "git reset --hard"],
        Some(repo.path()),
    );

    assert_eq!(
        output.status.code(),
        Some(0),
        "project config should allow command\nstderr: {}",
        stderr_text(&output)
    );

    let json = parse_json(&output);
    assert_eq!(json["decision"], "allow");
}

#[test]
fn test_with_packs_enables_extra_pack_detection() {
    let cmd = "aws ec2 terminate-instances --instance-ids i-1234567890abcdef0";

    let baseline = run_dcg_isolated(&["test", "--format", "json", cmd], None);
    assert_eq!(
        baseline.status.code(),
        Some(0),
        "baseline should allow without extra pack\nstderr: {}",
        stderr_text(&baseline)
    );
    let baseline_json = parse_json(&baseline);
    assert_eq!(baseline_json["decision"], "allow");

    let with_pack = run_dcg_isolated(
        &["test", "--format", "json", "--with-packs", "cloud.aws", cmd],
        None,
    );
    assert_eq!(
        with_pack.status.code(),
        Some(1),
        "extra pack should block command\nstderr: {}",
        stderr_text(&with_pack)
    );

    let with_pack_json = parse_json(&with_pack);
    assert_eq!(with_pack_json["decision"], "deny");
    assert_eq!(with_pack_json["pack_id"], "cloud.aws");
}

#[test]
fn test_with_packs_checks_railway_api_curl_payloads() {
    let cmd = r#"curl https://backboard.railway.app/graphql/v2 --data-binary '{"query":"mutation($in: VariableUpsertInput!){variableUpsert(input:$in)}","variables":{"in":{"name":"DATABASE_PUBLIC_URL","value":"postgres://prod"}}}'"#;

    let output = run_dcg_isolated(
        &[
            "test",
            "--format",
            "json",
            "--with-packs",
            "platform.railway",
            cmd,
        ],
        None,
    );

    assert_eq!(
        output.status.code(),
        Some(1),
        "Railway API variable upsert should be blocked\nstdout: {}\nstderr: {}",
        stdout_text(&output),
        stderr_text(&output)
    );

    let json = parse_json(&output);
    assert_eq!(json["decision"], "deny");
    assert_eq!(json["pack_id"], "platform.railway");
    assert_eq!(json["pattern_name"], "railway-api-database-variable-upsert");
}

#[test]
fn test_with_packs_checks_railway_api_backup_restore_payloads() {
    let cmd = r#"curl https://backboard.railway.app/graphql/v2 -d '{"query":"mutation { volumeInstanceBackupRestore(input:{volumeInstanceId:\"v\", backupId:\"b\"}) }"}'"#;

    let output = run_dcg_isolated(
        &[
            "test",
            "--format",
            "json",
            "--with-packs",
            "platform.railway",
            cmd,
        ],
        None,
    );

    assert_eq!(
        output.status.code(),
        Some(1),
        "Railway API volume backup restore should be blocked\nstdout: {}\nstderr: {}",
        stdout_text(&output),
        stderr_text(&output)
    );

    let json = parse_json(&output);
    assert_eq!(json["decision"], "deny");
    assert_eq!(json["pack_id"], "platform.railway");
    assert_eq!(json["pattern_name"], "railway-api-volume-backup-restore");
}

#[test]
fn test_with_packs_checks_railway_api_token_header_payloads() {
    let cmd = r#"curl https://api.example.com/graphql -H "Authorization: Bearer $RAILWAY_API_TOKEN" --data-binary '{"query":"mutation { projectDelete(id:\"p\") }"}'"#;

    let output = run_dcg_isolated(
        &[
            "test",
            "--format",
            "json",
            "--with-packs",
            "platform.railway",
            cmd,
        ],
        None,
    );

    assert_eq!(
        output.status.code(),
        Some(1),
        "Railway API mutation authenticated by token header should be blocked\nstdout: {}\nstderr: {}",
        stdout_text(&output),
        stderr_text(&output)
    );

    let json = parse_json(&output);
    assert_eq!(json["decision"], "deny");
    assert_eq!(json["pack_id"], "platform.railway");
    assert_eq!(json["pattern_name"], "railway-api-project-delete");
}

#[test]
fn test_with_packs_checks_railway_api_project_access_token_payloads() {
    let cmd = r#"curl https://api.example.com/graphql -H "Project-Access-Token: $PROJECT_ACCESS_TOKEN" --data-binary '{"query":"mutation { projectDelete(id:\"p\") }"}'"#;

    let output = run_dcg_isolated(
        &[
            "test",
            "--format",
            "json",
            "--with-packs",
            "platform.railway",
            cmd,
        ],
        None,
    );

    assert_eq!(
        output.status.code(),
        Some(1),
        "Railway API mutation authenticated by Project-Access-Token should be blocked\nstdout: {}\nstderr: {}",
        stdout_text(&output),
        stderr_text(&output)
    );

    let json = parse_json(&output);
    assert_eq!(json["decision"], "deny");
    assert_eq!(json["pack_id"], "platform.railway");
    assert_eq!(json["pattern_name"], "railway-api-project-delete");
}

#[test]
fn test_with_packs_checks_railway_api_multiline_payloads() {
    let cmd = "curl https://backboard.railway.app/graphql/v2 --data-binary '{\n\"query\":\"mutation { projectDelete(id:\\\"p\\\") }\"\n}'";

    let output = run_dcg_isolated(
        &[
            "test",
            "--format",
            "json",
            "--with-packs",
            "platform.railway",
            cmd,
        ],
        None,
    );

    assert_eq!(
        output.status.code(),
        Some(1),
        "Railway API mutation inside multiline payload should be blocked\nstdout: {}\nstderr: {}",
        stdout_text(&output),
        stderr_text(&output)
    );

    let json = parse_json(&output);
    assert_eq!(json["decision"], "deny");
    assert_eq!(json["pack_id"], "platform.railway");
    assert_eq!(json["pattern_name"], "railway-api-project-delete");
}

#[test]
fn test_with_packs_checks_railway_function_delete() {
    let output = run_dcg_isolated(
        &[
            "test",
            "--format",
            "json",
            "--with-packs",
            "platform.railway",
            "railway functions delete --function prod-worker --yes",
        ],
        None,
    );

    assert_eq!(
        output.status.code(),
        Some(1),
        "Railway function deletion should be blocked\nstdout: {}\nstderr: {}",
        stdout_text(&output),
        stderr_text(&output)
    );

    let json = parse_json(&output);
    assert_eq!(json["decision"], "deny");
    assert_eq!(json["pack_id"], "platform.railway");
    assert_eq!(json["pattern_name"], "railway-function-delete");
}

#[test]
fn test_with_packs_checks_gcloud_alpha_storage_delete() {
    let output = run_dcg_isolated(
        &[
            "test",
            "--format",
            "json",
            "--with-packs",
            "storage.gcs",
            "gcloud alpha --project prod storage buckets delete gs://prod-bucket --quiet",
        ],
        None,
    );

    assert_eq!(
        output.status.code(),
        Some(1),
        "gcloud alpha storage bucket deletion should be blocked\nstdout: {}\nstderr: {}",
        stdout_text(&output),
        stderr_text(&output)
    );

    let json = parse_json(&output);
    assert_eq!(json["decision"], "deny");
    assert_eq!(json["pack_id"], "storage.gcs");
    assert_eq!(json["pattern_name"], "gcloud-storage-buckets-delete");
}

#[test]
fn test_test_subcommand_help_text_includes_key_flags() {
    let output = run_dcg_isolated(&["help", "test"], None);
    let combined = format!("{}{}", stdout_text(&output), stderr_text(&output));

    assert!(
        matches!(output.status.code(), Some(0) | Some(2)),
        "help should exit with clap help code\nstdout: {}\nstderr: {}",
        stdout_text(&output),
        stderr_text(&output)
    );
    assert!(combined.contains("Usage: dcg test [OPTIONS] <COMMAND>"));
    assert!(combined.contains("--config"));
    assert!(combined.contains("--with-packs"));
    assert!(combined.contains("--format"));
    assert!(combined.contains("--heredoc-scan"));
}

#[test]
fn test_subcommand_help_flag_is_not_hijacked_by_top_level_help() {
    let output = run_dcg_isolated(&["simulate", "--help"], None);
    let combined = format!("{}{}", stdout_text(&output), stderr_text(&output));

    assert_eq!(
        output.status.code(),
        Some(0),
        "subcommand help should use clap's help exit code\nstdout: {}\nstderr: {}",
        stdout_text(&output),
        stderr_text(&output)
    );
    assert!(combined.contains("Usage: dcg simulate [OPTIONS]"));
    assert!(combined.contains("--max-command-bytes"));
}

#[test]
fn test_update_version_flag_is_not_hijacked_by_top_level_version() {
    let output = run_dcg_isolated(&["update", "--version", "v0.2.0", "--help"], None);
    let combined = format!("{}{}", stdout_text(&output), stderr_text(&output));

    assert_eq!(
        output.status.code(),
        Some(0),
        "update --version plus help should show update help, not top-level version\nstdout: {}\nstderr: {}",
        stdout_text(&output),
        stderr_text(&output)
    );
    assert!(combined.contains("Usage: dcg update [OPTIONS]"));
    assert!(combined.contains("--version <VERSION>"));
    assert!(!stdout_text(&output).starts_with(env!("CARGO_PKG_VERSION")));
}

#[test]
fn test_verbose_output_includes_diagnostics() {
    let output = run_dcg_isolated(&["test", "--verbose", "git reset --hard"], None);
    let stdout = stdout_text(&output);

    assert_eq!(
        output.status.code(),
        Some(1),
        "blocked command should exit 1 in verbose mode\nstderr: {}",
        stderr_text(&output)
    );
    assert!(
        stdout.contains("Reason:"),
        "expected Reason in verbose output"
    );
    assert!(
        stdout.contains("Result: BLOCKED"),
        "expected blocked result in verbose output"
    );
}