bashrs 6.66.0

Rust-to-Shell transpiler for deterministic bootstrap scripts
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
#[test]
fn test_suppression_extract_no_comply_prefix() {
    use super::runner;
    // Rule IDs must start with COMPLY-
    let rules = runner::extract_disable_rules("# comply:disable=FOO-001");
    assert_eq!(rules, None);
}

#[test]
fn test_suppression_parse_file_level() {
    use super::runner;
    let content = "#!/bin/sh\n# comply:disable=COMPLY-001\necho hello\n";
    let sup = runner::parse_suppressions(content);
    assert_eq!(sup.file_level, vec!["COMPLY-001".to_string()]);
    assert!(sup.line_level.is_empty());
}

#[test]
fn test_suppression_parse_line_level() {
    use super::runner;
    let content = "#!/bin/sh\necho hello\necho $RANDOM # comply:disable=COMPLY-002\n";
    let sup = runner::parse_suppressions(content);
    assert!(sup.file_level.is_empty());
    assert_eq!(
        sup.line_level.get(&3),
        Some(&vec!["COMPLY-002".to_string()])
    );
}

#[test]
fn test_suppression_file_level_only_first_10_lines() {
    use super::runner;
    // Line 11 is NOT file-level even if it's a comment-only line
    let mut content = String::new();
    for i in 1..=10 {
        content.push_str(&format!("# line {}\n", i));
    }
    content.push_str("# comply:disable=COMPLY-001\n"); // Line 11
    let sup = runner::parse_suppressions(&content);
    assert!(
        sup.file_level.is_empty(),
        "Line 11 should not be file-level"
    );
    assert_eq!(
        sup.line_level.get(&11),
        Some(&vec!["COMPLY-001".to_string()])
    );
}

#[test]
fn test_suppression_file_level_comment_only() {
    use super::runner;
    // Code on same line + in first 10 lines = line-level, not file-level
    let content = "#!/bin/sh\necho foo # comply:disable=COMPLY-001\n";
    let sup = runner::parse_suppressions(content);
    assert!(
        sup.file_level.is_empty(),
        "Inline code comment should not be file-level"
    );
    assert_eq!(
        sup.line_level.get(&2),
        Some(&vec!["COMPLY-001".to_string()])
    );
}

#[test]
fn test_suppression_apply_file_level() {
    use super::rules::{RuleId, RuleResult, Violation};
    use super::runner;
    let sup = runner::Suppressions {
        file_level: vec!["COMPLY-001".to_string()],
        line_level: std::collections::HashMap::new(),
    };
    let result = RuleResult {
        rule: RuleId::Posix,
        passed: false,
        violations: vec![Violation {
            rule: RuleId::Posix,
            line: Some(5),
            message: "bashism detected".to_string(),
        }],
    };
    let suppressed = runner::apply_suppressions(result, &sup);
    assert!(
        suppressed.passed,
        "File-level suppression should clear violations"
    );
    assert!(suppressed.violations.is_empty());
}

#[test]
fn test_suppression_apply_line_level() {
    use super::rules::{RuleId, RuleResult, Violation};
    use super::runner;
    let mut line_level = std::collections::HashMap::new();
    line_level.insert(5, vec!["COMPLY-002".to_string()]);
    let sup = runner::Suppressions {
        file_level: vec![],
        line_level,
    };
    let result = RuleResult {
        rule: RuleId::Determinism,
        passed: false,
        violations: vec![
            Violation {
                rule: RuleId::Determinism,
                line: Some(5),
                message: "non-deterministic on line 5".to_string(),
            },
            Violation {
                rule: RuleId::Determinism,
                line: Some(10),
                message: "non-deterministic on line 10".to_string(),
            },
        ],
    };
    let suppressed = runner::apply_suppressions(result, &sup);
    assert!(!suppressed.passed, "Should still have one violation");
    assert_eq!(suppressed.violations.len(), 1);
    assert_eq!(suppressed.violations[0].line, Some(10));
}

#[test]
fn test_suppression_apply_no_match() {
    use super::rules::{RuleId, RuleResult, Violation};
    use super::runner;
    let sup = runner::Suppressions {
        file_level: vec!["COMPLY-004".to_string()],
        line_level: std::collections::HashMap::new(),
    };
    let result = RuleResult {
        rule: RuleId::Posix,
        passed: false,
        violations: vec![Violation {
            rule: RuleId::Posix,
            line: Some(3),
            message: "violation".to_string(),
        }],
    };
    let suppressed = runner::apply_suppressions(result, &sup);
    assert!(
        !suppressed.passed,
        "Different rule suppression should not affect this rule"
    );
    assert_eq!(suppressed.violations.len(), 1);
}

#[test]
fn test_suppression_apply_all_lines_suppressed() {
    use super::rules::{RuleId, RuleResult, Violation};
    use super::runner;
    let mut line_level = std::collections::HashMap::new();
    line_level.insert(3, vec!["COMPLY-001".to_string()]);
    line_level.insert(7, vec!["COMPLY-001".to_string()]);
    let sup = runner::Suppressions {
        file_level: vec![],
        line_level,
    };
    let result = RuleResult {
        rule: RuleId::Posix,
        passed: false,
        violations: vec![
            Violation {
                rule: RuleId::Posix,
                line: Some(3),
                message: "v1".to_string(),
            },
            Violation {
                rule: RuleId::Posix,
                line: Some(7),
                message: "v2".to_string(),
            },
        ],
    };
    let suppressed = runner::apply_suppressions(result, &sup);
    assert!(suppressed.passed, "All violations suppressed means passed");
    assert!(suppressed.violations.is_empty());
}

#[test]
fn test_suppression_multiple_rules_on_one_line() {
    use super::runner;
    let rules = runner::extract_disable_rules("# comply:disable=COMPLY-001,COMPLY-002,COMPLY-004");
    assert_eq!(
        rules,
        Some(vec![
            "COMPLY-001".to_string(),
            "COMPLY-002".to_string(),
            "COMPLY-004".to_string(),
        ])
    );
}

#[test]
fn test_suppression_no_suppressions_passthrough() {
    use super::rules::{RuleId, RuleResult, Violation};
    use super::runner;
    let sup = runner::parse_suppressions("#!/bin/sh\necho hello\n");
    let result = RuleResult {
        rule: RuleId::Posix,
        passed: false,
        violations: vec![Violation {
            rule: RuleId::Posix,
            line: Some(2),
            message: "test".to_string(),
        }],
    };
    let suppressed = runner::apply_suppressions(result, &sup);
    assert!(
        !suppressed.passed,
        "No suppressions should leave violations intact"
    );
    assert_eq!(suppressed.violations.len(), 1);
}

// ═══════════════════════════════════════════════════════════════
// Rule metadata tests
// ═══════════════════════════════════════════════════════════════

#[test]
fn test_rule_all_returns_10_rules() {
    assert_eq!(RuleId::all().len(), 10);
}

#[test]
fn test_rule_codes_unique() {
    let codes: Vec<&str> = RuleId::all().iter().map(|r| r.code()).collect();
    let mut unique = codes.clone();
    unique.sort();
    unique.dedup();
    assert_eq!(codes.len(), unique.len(), "Rule codes must be unique");
}

#[test]
fn test_rule_descriptions_non_empty() {
    for rule in RuleId::all() {
        assert!(
            !rule.description().is_empty(),
            "{} has empty description",
            rule.code()
        );
    }
}

#[test]
fn test_rule_applies_to_non_empty() {
    for rule in RuleId::all() {
        assert!(
            !rule.applies_to().is_empty(),
            "{} has no artifact types",
            rule.code()
        );
    }
}

#[test]
fn test_rule_all_weights_consistent() {
    // Verify all() returns rules whose weights match individual weight()
    for rule in RuleId::all() {
        assert!(rule.weight() > 0, "{} has zero weight", rule.code());
    }
}

// ═══════════════════════════════════════════════════════════════
// COMPLY-002 Determinism expansion tests
// ═══════════════════════════════════════════════════════════════

fn sh_artifact() -> Artifact {
    Artifact::new(
        PathBuf::from("test.sh"),
        Scope::Project,
        ArtifactKind::ShellScript,
    )
}

#[test]
fn test_determinism_srandom_detected() {
    let artifact = sh_artifact();
    let result = check_rule(RuleId::Determinism, "echo $SRANDOM\n", &artifact);
    assert!(!result.passed, "$SRANDOM should be non-deterministic");
}

#[test]
fn test_determinism_bashpid_detected() {
    let artifact = sh_artifact();
    let result = check_rule(RuleId::Determinism, "echo $BASHPID\n", &artifact);
    assert!(!result.passed, "$BASHPID should be non-deterministic");
}

#[test]
fn test_determinism_dev_urandom_detected() {
    let artifact = sh_artifact();
    let result = check_rule(
        RuleId::Determinism,
        "dd if=/dev/urandom bs=16 count=1\n",
        &artifact,
    );
    assert!(!result.passed, "/dev/urandom should be non-deterministic");
}

#[test]
fn test_determinism_dev_random_detected() {
    let artifact = sh_artifact();
    let result = check_rule(RuleId::Determinism, "head -c 32 /dev/random\n", &artifact);
    assert!(!result.passed, "/dev/random should be non-deterministic");
}

#[test]
fn test_determinism_mktemp_detected() {
    let artifact = sh_artifact();
    let result = check_rule(RuleId::Determinism, "TMPDIR=$(mktemp -d)\n", &artifact);
    assert!(!result.passed, "mktemp should be non-deterministic");
}

#[test]
fn test_determinism_mktemp_standalone() {
    let artifact = sh_artifact();
    let result = check_rule(RuleId::Determinism, "mktemp /tmp/test.XXXXXX\n", &artifact);
    assert!(
        !result.passed,
        "mktemp standalone should be non-deterministic"
    );
}

#[test]
fn test_determinism_shuf_detected() {
    let artifact = sh_artifact();
    let result = check_rule(RuleId::Determinism, "shuf -n 1 wordlist.txt\n", &artifact);
    assert!(!result.passed, "shuf should be non-deterministic");
}

#[test]
fn test_determinism_shuf_piped() {
    let artifact = sh_artifact();
    let result = check_rule(RuleId::Determinism, "cat list.txt | shuf\n", &artifact);
    assert!(!result.passed, "piped shuf should be non-deterministic");
}

#[test]
fn test_determinism_clean_script_passes() {
    let artifact = sh_artifact();
    let result = check_rule(
        RuleId::Determinism,
        "#!/bin/sh\necho hello\nmkdir -p /tmp/test\n",
        &artifact,
    );
    assert!(result.passed, "Clean script should be deterministic");
}

// ═══════════════════════════════════════════════════════════════
// COMPLY-003 Idempotency expansion tests
// ═══════════════════════════════════════════════════════════════

#[test]
fn test_idempotency_useradd_unguarded() {
    let artifact = sh_artifact();
    let result = check_rule(RuleId::Idempotency, "useradd deploy\n", &artifact);
    assert!(!result.passed, "useradd without guard is non-idempotent");
}

#[test]
fn test_idempotency_useradd_guarded_ok() {
    let artifact = sh_artifact();
    let result = check_rule(RuleId::Idempotency, "useradd deploy || true\n", &artifact);
    assert!(result.passed, "useradd with || true is guarded");
}

#[test]
fn test_idempotency_groupadd_unguarded() {
    let artifact = sh_artifact();
    let result = check_rule(RuleId::Idempotency, "groupadd www-data\n", &artifact);
    assert!(!result.passed, "groupadd without guard is non-idempotent");
}

#[test]
fn test_idempotency_git_clone_unguarded() {
    let artifact = sh_artifact();
    let result = check_rule(
        RuleId::Idempotency,
        "git clone https://github.com/user/repo.git\n",
        &artifact,
    );
    assert!(
        !result.passed,
        "git clone without dir check is non-idempotent"
    );
}

#[test]
fn test_idempotency_git_clone_guarded_ok() {
    let artifact = sh_artifact();
    let result = check_rule(
        RuleId::Idempotency,
        "if [ ! -d repo ]; then git clone https://github.com/user/repo.git; fi\n",
        &artifact,
    );
    // The git clone is on a line containing "if " so it's guarded
    assert!(result.passed, "git clone with directory check is guarded");
}

#[test]
fn test_idempotency_createdb_unguarded() {
    let artifact = sh_artifact();
    let result = check_rule(RuleId::Idempotency, "createdb myapp\n", &artifact);
    assert!(!result.passed, "createdb without guard is non-idempotent");
}

#[test]
fn test_idempotency_createdb_guarded_ok() {
    let artifact = sh_artifact();
    let result = check_rule(
        RuleId::Idempotency,
        "createdb myapp 2>/dev/null || true\n",
        &artifact,
    );
    assert!(result.passed, "createdb with error suppression is guarded");
}

#[test]
fn test_idempotency_append_to_bashrc() {
    let artifact = sh_artifact();
    let result = check_rule(
        RuleId::Idempotency,
        "echo 'export PATH=/usr/local/bin:$PATH' >> ~/.bashrc\n",
        &artifact,
    );
    assert!(!result.passed, "Appending to .bashrc is non-idempotent");
}

#[test]
fn test_idempotency_append_guarded_grep_ok() {
    let artifact = sh_artifact();
    let result = check_rule(
        RuleId::Idempotency,
        "grep -q '/usr/local/bin' ~/.bashrc || echo 'export PATH=/usr/local/bin:$PATH' >> ~/.bashrc\n",
        &artifact,
    );
    // Contains grep -q guard
    assert!(result.passed, "Append with grep -q guard is idempotent");
}

#[test]
fn test_idempotency_append_to_profile() {
    let artifact = sh_artifact();
    let result = check_rule(
        RuleId::Idempotency,
        "echo 'source /opt/env.sh' >> /etc/profile\n",
        &artifact,
    );
    assert!(
        !result.passed,
        "Appending to /etc/profile is non-idempotent"
    );
}

#[test]
fn test_idempotency_mkdir_with_p_ok() {
    let artifact = sh_artifact();
    let result = check_rule(RuleId::Idempotency, "mkdir -p /tmp/dir\n", &artifact);
    assert!(result.passed, "mkdir -p is idempotent");
}

#[test]
fn test_idempotency_rm_with_f_ok() {
    let artifact = sh_artifact();
    let result = check_rule(RuleId::Idempotency, "rm -f /tmp/file\n", &artifact);
    assert!(result.passed, "rm -f is idempotent");
}