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
//! SEC005: Hardcoded Secrets
//!
//! **Rule**: Detect hardcoded secrets, API keys, passwords, and tokens
//!
//! **Why this matters**:
//! Hardcoded secrets in scripts lead to credential leaks when committed to
//! version control. Secrets should be loaded from environment variables or
//! secure secret management systems.
//!
//! **Auto-fix**: Manual review required (not auto-fixable)
//!
//! ## Examples
//!
//! ❌ **HARDCODED SECRET**:
//! ```bash
//! API_KEY="sk-1234567890abcdef"
//! PASSWORD="MyP@ssw0rd"
//! TOKEN="ghp_xxxxxxxxxxxxxxxxxxxx"
//! AWS_SECRET_ACCESS_KEY="AKIAIOSFODNN7EXAMPLE"
//! ```
//!
//! ✅ **USE ENVIRONMENT VARIABLES**:
//! ```bash
//! API_KEY="${API_KEY:-}"
//! PASSWORD="${PASSWORD:-}"
//! TOKEN="${GITHUB_TOKEN:-}"
//! AWS_SECRET_ACCESS_KEY="${AWS_SECRET_ACCESS_KEY:-}"
//! ```

use crate::linter::{Diagnostic, LintResult, Severity, Span};

/// Patterns that indicate hardcoded secrets
const SECRET_PATTERNS: &[(&str, &str)] = &[
    ("API_KEY=", "API key assignment"),
    ("SECRET=", "Secret assignment"),
    ("PASSWORD=", "Password assignment"),
    ("TOKEN=", "Token assignment"),
    ("AWS_SECRET", "AWS secret"),
    ("GITHUB_TOKEN=", "GitHub token"),
    ("PRIVATE_KEY=", "Private key"),
    ("sk-", "OpenAI API key pattern"),
    ("ghp_", "GitHub personal access token"),
    ("gho_", "GitHub OAuth token"),
];

/// Check if a line is a comment
fn is_comment_line(line: &str) -> bool {
    line.trim_start().starts_with('#')
}

/// Extract value after equals sign
fn extract_after_equals(line: &str) -> Option<&str> {
    line.find('=').map(|eq_pos| &line[eq_pos + 1..])
}

/// Check if value is a literal assignment (not $VAR)
fn is_literal_assignment(after_eq: &str) -> bool {
    let trimmed = after_eq.trim_start();
    (trimmed.starts_with('"') && !trimmed.starts_with("\"$")) || trimmed.starts_with('\'')
}

/// Find pattern position in line
fn find_pattern_position(line: &str, pattern: &str) -> Option<usize> {
    line.find(pattern)
}

/// Calculate span for diagnostic
fn calculate_span(line_num: usize, col: usize, line_len: usize, pattern_len: usize) -> Span {
    Span::new(
        line_num + 1,
        col + 1,
        line_num + 1,
        line_len.min(col + pattern_len + 10),
    )
}

/// Create diagnostic for hardcoded secret
fn create_hardcoded_secret_diagnostic(description: &str, span: Span) -> Diagnostic {
    Diagnostic::new(
        "SEC005",
        Severity::Error,
        format!(
            "Hardcoded secret detected: {} - use environment variables",
            description
        ),
        span,
    )
    // NO AUTO-FIX: requires manual review
}

/// Check for hardcoded secrets
pub fn check(source: &str) -> LintResult {
    if source.is_empty() { return LintResult::new(); }
    // Contract: safety-classifier-v1.yaml precondition (pv codegen)
    contract_pre_classify_secrets!(source);
    let mut result = LintResult::new();

    for (line_num, line) in source.lines().enumerate() {
        if is_comment_line(line) {
            continue;
        }

        // Check each secret pattern
        for (pattern, description) in SECRET_PATTERNS {
            if line.contains(pattern) {
                if let Some(after_eq) = extract_after_equals(line) {
                    if is_literal_assignment(after_eq) {
                        // This looks like a hardcoded secret
                        if let Some(col) = find_pattern_position(line, pattern) {
                            let span = calculate_span(line_num, col, line.len(), pattern.len());
                            let diag = create_hardcoded_secret_diagnostic(description, span);
                            result.add(diag);
                            break; // Only report once per line
                        }
                    }
                }
            }
        }
    }

    result
}

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

    // ===== Manual Property Tests =====

    #[test]
    fn prop_sec005_comments_never_diagnosed() {
        // Property: Comment lines should never produce diagnostics
        let test_cases = vec![
            "# API_KEY=\"sk-1234567890abcdef\"",
            "  # PASSWORD='MyP@ssw0rd'",
            "\t# TOKEN=\"ghp_xxxxxxxxxxxxxxxxxxxx\"",
        ];

        for code in test_cases {
            let result = check(code);
            assert_eq!(result.diagnostics.len(), 0);
        }
    }

    #[test]
    fn prop_sec005_env_vars_never_diagnosed() {
        // Property: Environment variable assignments should never be diagnosed
        let test_cases = vec![
            "API_KEY=\"${API_KEY:-}\"",
            "PASSWORD=\"${PASSWORD:-}\"",
            "TOKEN=\"${GITHUB_TOKEN:-}\"",
            "SECRET=\"${SECRET:-default}\"",
        ];

        for code in test_cases {
            let result = check(code);
            assert_eq!(result.diagnostics.len(), 0);
        }
    }

    #[test]
    fn prop_sec005_variable_expansions_never_diagnosed() {
        // Property: Variable expansions should never be diagnosed
        let test_cases = vec![
            "API_KEY=\"$MY_API_KEY\"",
            "PASSWORD=\"$MY_PASSWORD\"",
            "TOKEN=\"$GITHUB_TOKEN\"",
            "SECRET=\"$MY_SECRET\"",
        ];

        for code in test_cases {
            let result = check(code);
            assert_eq!(result.diagnostics.len(), 0);
        }
    }

    #[test]
    fn prop_sec005_hardcoded_literals_always_diagnosed() {
        // Property: Hardcoded secret literals should always be diagnosed
        let test_cases = vec![
            "API_KEY=\"sk-1234567890abcdef\"",
            "PASSWORD='MyP@ssw0rd'",
            "TOKEN=\"ghp_xxxxxxxxxxxxxxxxxxxx\"",
            "SECRET=\"my-secret-value\"",
            "AWS_SECRET_ACCESS_KEY=\"AKIAIOSFODNN7EXAMPLE\"",
        ];

        for code in test_cases {
            let result = check(code);
            assert_eq!(result.diagnostics.len(), 1, "Should diagnose: {}", code);
            assert!(result.diagnostics[0].message.contains("Hardcoded secret"));
        }
    }

    #[test]
    fn prop_sec005_diagnostic_code_always_sec005() {
        // Property: All diagnostics must have code \"SEC005\"
        let code = "API_KEY=\"sk-123\"\nPASSWORD='pass123'";
        let result = check(code);

        for diagnostic in &result.diagnostics {
            assert_eq!(&diagnostic.code, "SEC005");
        }
    }

    #[test]
    fn prop_sec005_diagnostic_severity_always_error() {
        // Property: All diagnostics must be Error severity
        let code = "SECRET=\"hardcoded-secret\"";
        let result = check(code);

        for diagnostic in &result.diagnostics {
            assert_eq!(diagnostic.severity, Severity::Error);
        }
    }

    #[test]
    fn prop_sec005_no_auto_fix_provided() {
        // Property: SEC005 should never provide auto-fix (security concern)
        let test_cases = vec![
            "API_KEY=\"sk-123\"",
            "PASSWORD='pass'",
            "TOKEN=\"ghp_xxx\"",
            "SECRET=\"secret\"",
        ];

        for code in test_cases {
            let result = check(code);
            if !result.diagnostics.is_empty() {
                for diag in &result.diagnostics {
                    assert!(
                        diag.fix.is_none(),
                        "SEC005 should not provide auto-fix for: {}",
                        code
                    );
                }
            }
        }
    }

    #[test]
    fn prop_sec005_one_diagnostic_per_line() {
        // Property: Only one diagnostic per line (breaks after first match)
        let code = "API_KEY=\"sk-123\" PASSWORD='pass'"; // Multiple secrets in one line
        let result = check(code);
        assert_eq!(
            result.diagnostics.len(),
            1,
            "Should only diagnose once per line"
        );
    }

    #[test]
    fn prop_sec005_multiple_lines_all_diagnosed() {
        // Property: Multiple lines with secrets should all be diagnosed
        let code = "API_KEY=\"sk-123\"\nPASSWORD='pass'\nTOKEN=\"ghp_xxx\"";
        let result = check(code);
        assert_eq!(result.diagnostics.len(), 3);
    }

    #[test]
    fn prop_sec005_empty_source_no_diagnostics() {
        // Property: Empty source should produce no diagnostics
        let result = check("");
        assert_eq!(result.diagnostics.len(), 0);
    }

    // ===== Original Unit Tests =====

    #[test]
    fn test_SEC005_detects_hardcoded_api_key() {
        let script = r#"API_KEY="sk-1234567890abcdef""#;
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 1);
        let diag = &result.diagnostics[0];
        assert_eq!(diag.code, "SEC005");
        assert_eq!(diag.severity, Severity::Error);
        assert!(diag.message.contains("Hardcoded"));
    }

    #[test]
    fn test_SEC005_detects_hardcoded_password() {
        let script = "PASSWORD='MyP@ssw0rd'";
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 1);
    }

    #[test]
    fn test_SEC005_detects_github_token() {
        let script = r#"TOKEN="ghp_xxxxxxxxxxxxxxxxxxxx""#;
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 1);
    }

    #[test]
    fn test_SEC005_no_warning_env_var() {
        let script = r#"API_KEY="${API_KEY:-}""#;
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_SEC005_no_warning_variable_expansion() {
        let script = "PASSWORD=\"$MY_PASSWORD\"";
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_SEC005_no_warning_comment() {
        let script = r#"# API_KEY="secret123""#;
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 0);
    }

    #[test]
    fn test_SEC005_no_auto_fix() {
        let script = r#"SECRET="my-secret-value""#;
        let result = check(script);

        assert_eq!(result.diagnostics.len(), 1);
        let diag = &result.diagnostics[0];
        assert!(diag.fix.is_none(), "SEC005 should not provide auto-fix");
    }

    // ===== Mutation Coverage Tests - Following SEC001 pattern (100% kill rate) =====

    #[test]
    fn test_mutation_sec005_calculate_span_start_col_exact() {
        // MUTATION: Line 70:9 - replace + with * in line_num + 1
        // MUTATION: Line 71:9 - replace + with * in col + 1
        let bash_code = r#"API_KEY="sk-1234567890abcdef""#;
        let result = check(bash_code);
        assert_eq!(result.diagnostics.len(), 1);
        let span = result.diagnostics[0].span;
        // API_KEY starts at column 1 (0-indexed), span should be col + 1
        assert_eq!(
            span.start_col, 1,
            "Start column must use col + 1, not col * 1"
        );
    }

    #[test]
    fn test_mutation_sec005_calculate_span_line_num_exact() {
        // MUTATION: Line 70:9 - replace + with * in line_num + 1
        // Tests line number calculation for multiline input
        let bash_code = "# comment\nAPI_KEY=\"sk-1234567890abcdef\"";
        let result = check(bash_code);
        assert_eq!(result.diagnostics.len(), 1);
        // With +1: line 2
        // With *1: line 0
        assert_eq!(
            result.diagnostics[0].span.start_line, 2,
            "Line number must use +1, not *1"
        );
    }

    #[test]
    fn test_mutation_sec005_calculate_span_end_col_complex() {
        // MUTATION: Line 73:9 - arithmetic mutations in line_len.min(col + pattern_len + 10)
        // Tests end column calculation with min() function
        let bash_code = r#"API_KEY="sk-123""#;
        let result = check(bash_code);
        assert_eq!(result.diagnostics.len(), 1);
        let span = result.diagnostics[0].span;
        // Verify end column is calculated correctly
        // API_KEY is at column 0, pattern_len is 8 ("API_KEY="), +10 padding
        // Should be min(line_len, col + pattern_len + 10)
        assert!(
            span.end_col > span.start_col,
            "End column must be greater than start column"
        );
        assert!(
            span.end_col <= bash_code.len(),
            "End column must not exceed line length"
        );
    }

    #[test]
    fn test_mutation_sec005_column_with_leading_whitespace() {
        // Tests column calculations with offset
        let bash_code = r#"    SECRET="hardcoded""#;
        let result = check(bash_code);
        assert_eq!(result.diagnostics.len(), 1);
        let span = result.diagnostics[0].span;
        // SECRET starts at column 5 (4 spaces + 1)
        assert_eq!(span.start_col, 5, "Must account for leading whitespace");
    }

    #[test]
    fn test_mutation_sec005_multiple_patterns_first_detected() {
        // Tests that column tracking works correctly when multiple patterns exist
        let bash_code = r#"PASSWORD="pass123""#;
        let result = check(bash_code);
        assert_eq!(result.diagnostics.len(), 1);
        let span = result.diagnostics[0].span;
        // PASSWORD starts at column 1
        assert_eq!(span.start_col, 1, "Should detect first pattern correctly");
    }
}