-
Notifications
You must be signed in to change notification settings - Fork 908
Expand file tree
/
Copy pathworkspace_audit.zig
More file actions
1627 lines (1418 loc) · 57.7 KB
/
Copy pathworkspace_audit.zig
File metadata and controls
1627 lines (1418 loc) · 57.7 KB
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const std = @import("std");
const std_compat = @import("compat");
const fs_compat = @import("fs_compat.zig");
const json_util = @import("json_util.zig");
const admin_output = @import("admin_output.zig");
const scrub = @import("providers/scrub.zig");
const util = @import("util.zig");
const process_util = @import("tools/process_util.zig");
const audit_types = @import("audit/types.zig");
const audit_envelope = @import("audit/envelope.zig");
const Allocator = std.mem.Allocator;
const MAX_SCAN_FILE_BYTES: u64 = 256 * 1024;
const MAX_PREVIEW_CHARS: usize = 160;
const MAX_DIFF_BYTES: usize = 512 * 1024;
const skipped_dirs = [_][]const u8{
".git",
".zig-cache",
"zig-cache",
"zig-out",
"zig-pkg",
"node_modules",
"vendor",
"dist",
"build",
"target",
};
const ignored_path_prefixes = [_][]const u8{
".git/",
".zig-cache/",
"zig-cache/",
"zig-out/",
"zig-pkg/",
"node_modules/",
"vendor/",
"dist/",
"build/",
"target/",
"coverage/",
};
const token_prefixes = [_][]const u8{
"sk-",
"xoxb-",
"xoxp-",
"ghp_",
"gho_",
"ghs_",
"ghu_",
"glpat-",
"AKIA",
};
pub const Severity = audit_types.Severity;
pub const Confidence = audit_types.Confidence;
pub const FailureThreshold = audit_types.FailureThreshold;
pub const FindingSource = audit_types.FindingSource;
pub const TriageMode = audit_types.TriageMode;
pub const Finding = audit_types.Finding;
pub const Report = audit_types.Report;
pub const TriageStats = audit_types.TriageStats;
pub const Options = struct {
workspace_dir: []const u8,
json: bool = false,
staged: bool = false,
commit: ?[]const u8 = null,
range: ?[]const u8 = null,
fail_on: FailureThreshold = .high,
only_secrets: bool = false,
exclude_patterns: []const []const u8 = &.{},
collect_triage_context: bool = false,
};
pub const AuditError = error{
NotGitRepository,
GitUnavailable,
GitDiffFailed,
InvalidHistoryTarget,
};
const DetectedRule = struct {
severity: Severity,
confidence: Confidence,
rule: []const u8,
detected_value: ?[]const u8 = null,
assignment_key: ?[]const u8 = null,
assignment_operator: ?[]const u8 = null,
};
const PathCategory = enum {
config,
code,
docs,
vendor_like,
neutral,
};
/// Scan-only command helper. LLM triage is orchestrated by the CLI layer so
/// this detector module stays provider-free and deterministic.
pub fn run(allocator: Allocator, options: Options) !u8 {
const resolved_workspace = try fs_compat.realpathAllocPath(allocator, options.workspace_dir);
defer allocator.free(resolved_workspace);
var report = try buildReport(allocator, resolved_workspace, options);
defer report.deinit(allocator);
const rendered = try renderReport(allocator, report, options.fail_on, options.json, null);
defer allocator.free(rendered);
try admin_output.writeStdoutBytes(rendered);
if (rendered.len == 0 or rendered[rendered.len - 1] != '\n') {
try admin_output.writeStdoutBytes("\n");
}
return if (report.exceedsThreshold(options.fail_on)) 1 else 0;
}
pub fn buildReport(allocator: Allocator, workspace_dir: []const u8, options: Options) !Report {
const repo_root = try resolveRepoRoot(allocator, workspace_dir);
var findings: std.ArrayListUnmanaged(Finding) = .empty;
errdefer {
for (findings.items) |*finding| finding.deinit(allocator);
findings.deinit(allocator);
if (repo_root) |root| allocator.free(root);
}
if (options.commit) |commit| {
const diff = try readCommitDiff(allocator, workspace_dir, commit);
defer allocator.free(diff);
try scanGitHistoryDiff(allocator, diff, options, &findings);
} else if (options.range) |range| {
const diff = try readRangeDiff(allocator, workspace_dir, range);
defer allocator.free(diff);
try scanGitHistoryDiff(allocator, diff, options, &findings);
} else if (options.staged) {
const diff = try readStagedDiff(allocator, workspace_dir);
defer allocator.free(diff);
try scanStagedDiff(allocator, diff, options, &findings);
} else {
try scanWorkspaceFiles(allocator, workspace_dir, workspace_dir, options, &findings);
}
var report = Report{
.workspace_dir = workspace_dir,
.repo_root = repo_root,
.findings = try findings.toOwnedSlice(allocator),
.scanned_source = if (options.commit != null or options.range != null)
.git_history
else if (options.staged)
.git_staged_diff
else
.workspace_file,
};
for (report.findings) |finding| {
switch (finding.severity) {
.medium => report.medium_count += 1,
.high => report.high_count += 1,
.critical => report.critical_count += 1,
}
}
return report;
}
fn resolveRepoRoot(allocator: Allocator, cwd: []const u8) !?[]u8 {
const result = process_util.run(allocator, &.{ "git", "rev-parse", "--show-toplevel" }, .{
.cwd = cwd,
.max_output_bytes = 32 * 1024,
}) catch |err| switch (err) {
error.FileNotFound => return null,
else => return err,
};
defer result.deinit(allocator);
if (!result.success) {
if (containsText(result.stderr, "not a git repository") or containsText(result.stderr, "not recognized as an internal or external command")) {
return null;
}
if (containsText(result.stderr, "No such file or directory")) return null;
if (containsText(result.stderr, "command not found")) return null;
return null;
}
const trimmed = std.mem.trim(u8, result.stdout, " \r\n\t");
if (trimmed.len == 0) return null;
return try allocator.dupe(u8, trimmed);
}
fn readStagedDiff(allocator: Allocator, cwd: []const u8) ![]u8 {
const version = process_util.run(allocator, &.{ "git", "--version" }, .{
.cwd = cwd,
.max_output_bytes = 16 * 1024,
}) catch |err| switch (err) {
error.FileNotFound => return AuditError.GitUnavailable,
else => return err,
};
defer version.deinit(allocator);
if (!version.success) return AuditError.GitUnavailable;
const result = process_util.run(allocator, &.{ "git", "diff", "--cached", "--unified=0", "--no-color", "--", "." }, .{
.cwd = cwd,
.max_output_bytes = MAX_DIFF_BYTES,
}) catch |err| switch (err) {
error.FileNotFound => return AuditError.GitUnavailable,
else => return err,
};
defer allocator.free(result.stderr);
if (!result.success) {
defer allocator.free(result.stdout);
if (containsText(result.stderr, "not a git repository")) return AuditError.NotGitRepository;
return AuditError.GitDiffFailed;
}
return result.stdout;
}
fn readCommitDiff(allocator: Allocator, cwd: []const u8, commit: []const u8) ![]u8 {
if (commit.len == 0) return AuditError.InvalidHistoryTarget;
const version = process_util.run(allocator, &.{ "git", "--version" }, .{
.cwd = cwd,
.max_output_bytes = 16 * 1024,
}) catch |err| switch (err) {
error.FileNotFound => return AuditError.GitUnavailable,
else => return err,
};
defer version.deinit(allocator);
if (!version.success) return AuditError.GitUnavailable;
const result = process_util.run(allocator, &.{ "git", "show", "--format=", "--unified=0", "--no-color", commit, "--", "." }, .{
.cwd = cwd,
.max_output_bytes = MAX_DIFF_BYTES,
}) catch |err| switch (err) {
error.FileNotFound => return AuditError.GitUnavailable,
else => return err,
};
defer allocator.free(result.stderr);
if (!result.success) {
defer allocator.free(result.stdout);
if (containsText(result.stderr, "not a git repository")) return AuditError.NotGitRepository;
return AuditError.GitDiffFailed;
}
return result.stdout;
}
fn readRangeDiff(allocator: Allocator, cwd: []const u8, range: []const u8) ![]u8 {
if (range.len == 0 or std.mem.indexOf(u8, range, "..") == null) return AuditError.InvalidHistoryTarget;
const version = process_util.run(allocator, &.{ "git", "--version" }, .{
.cwd = cwd,
.max_output_bytes = 16 * 1024,
}) catch |err| switch (err) {
error.FileNotFound => return AuditError.GitUnavailable,
else => return err,
};
defer version.deinit(allocator);
if (!version.success) return AuditError.GitUnavailable;
const result = process_util.run(allocator, &.{ "git", "diff", "--unified=0", "--no-color", range, "--", "." }, .{
.cwd = cwd,
.max_output_bytes = MAX_DIFF_BYTES,
}) catch |err| switch (err) {
error.FileNotFound => return AuditError.GitUnavailable,
else => return err,
};
defer allocator.free(result.stderr);
if (!result.success) {
defer allocator.free(result.stdout);
if (containsText(result.stderr, "not a git repository")) return AuditError.NotGitRepository;
return AuditError.GitDiffFailed;
}
return result.stdout;
}
fn scanWorkspaceFiles(
allocator: Allocator,
root_dir: []const u8,
current_dir: []const u8,
options: Options,
findings: *std.ArrayListUnmanaged(Finding),
) !void {
var dir = try std_compat.fs.openDirAbsolute(current_dir, .{ .iterate = true });
defer dir.close();
var it = dir.iterate();
while (try it.next()) |entry| {
if (shouldSkipEntry(entry.name, entry.kind)) continue;
const child_path = try std_compat.fs.path.join(allocator, &.{ current_dir, entry.name });
defer allocator.free(child_path);
switch (entry.kind) {
.directory => try scanWorkspaceFiles(allocator, root_dir, child_path, options, findings),
.file => try scanWorkspaceFile(allocator, root_dir, child_path, options, findings),
else => {},
}
}
}
fn scanWorkspaceFile(
allocator: Allocator,
root_dir: []const u8,
file_path: []const u8,
options: Options,
findings: *std.ArrayListUnmanaged(Finding),
) !void {
const rel_path = try std_compat.fs.path.relative(allocator, root_dir, file_path);
defer allocator.free(rel_path);
if (shouldIgnorePath(rel_path, options.exclude_patterns)) return;
const contents = fs_compat.readFileAlloc(std_compat.fs.cwd(), allocator, file_path, MAX_SCAN_FILE_BYTES) catch |err| switch (err) {
error.StreamTooLong => return,
error.FileNotFound => return,
else => return err,
};
defer allocator.free(contents);
if (isProbablyBinary(contents)) return;
try scanText(allocator, rel_path, contents, .workspace_file, options, findings);
}
fn scanStagedDiff(
allocator: Allocator,
diff: []const u8,
options: Options,
findings: *std.ArrayListUnmanaged(Finding),
) !void {
var current_file: ?[]const u8 = null;
var current_line: ?usize = null;
var it = std.mem.splitScalar(u8, diff, '\n');
while (it.next()) |raw_line| {
const line = std_compat.mem.trimRight(u8, raw_line, "\r");
if (std.mem.startsWith(u8, line, "+++ ")) {
current_file = parseDiffPath(line);
current_line = null;
continue;
}
if (std.mem.startsWith(u8, line, "@@")) {
current_line = parseAddedHunkStart(line);
continue;
}
if (current_file == null or current_line == null) continue;
if (line.len == 0) continue;
switch (line[0]) {
'+' => {
if (std.mem.startsWith(u8, line, "+++")) continue;
try scanDiffLine(allocator, current_file.?, current_line.?, line[1..], options, findings);
current_line.? += 1;
},
' ' => current_line.? += 1,
else => {},
}
}
}
fn scanGitHistoryDiff(
allocator: Allocator,
diff: []const u8,
options: Options,
findings: *std.ArrayListUnmanaged(Finding),
) !void {
var current_file: ?[]const u8 = null;
var current_line: ?usize = null;
var it = std.mem.splitScalar(u8, diff, '\n');
while (it.next()) |raw_line| {
const line = std_compat.mem.trimRight(u8, raw_line, "\r");
if (std.mem.startsWith(u8, line, "+++ ")) {
current_file = parseDiffPath(line);
current_line = null;
continue;
}
if (std.mem.startsWith(u8, line, "@@")) {
current_line = parseAddedHunkStart(line);
continue;
}
if (current_file == null or current_line == null) continue;
if (line.len == 0) continue;
switch (line[0]) {
'+' => {
if (std.mem.startsWith(u8, line, "+++")) continue;
try scanHistoryLine(allocator, current_file.?, current_line.?, line[1..], options, findings);
current_line.? += 1;
},
' ' => current_line.? += 1,
else => {},
}
}
}
fn scanDiffLine(
allocator: Allocator,
path: []const u8,
line_no: usize,
line: []const u8,
options: Options,
findings: *std.ArrayListUnmanaged(Finding),
) !void {
if (shouldIgnorePath(path, options.exclude_patterns)) return;
if (detectLine(path, line, .git_staged_diff)) |rule| {
try appendFinding(allocator, findings, options, rule, path, line_no, .git_staged_diff, line);
}
}
fn scanHistoryLine(
allocator: Allocator,
path: []const u8,
line_no: usize,
line: []const u8,
options: Options,
findings: *std.ArrayListUnmanaged(Finding),
) !void {
if (shouldIgnorePath(path, options.exclude_patterns)) return;
if (detectLine(path, line, .git_history)) |rule| {
try appendFinding(allocator, findings, options, rule, path, line_no, .git_history, line);
}
}
fn scanText(
allocator: Allocator,
path: []const u8,
text: []const u8,
source: FindingSource,
options: Options,
findings: *std.ArrayListUnmanaged(Finding),
) !void {
var line_no: usize = 1;
var start: usize = 0;
while (start <= text.len) {
const end = std.mem.indexOfScalarPos(u8, text, start, '\n') orelse text.len;
const line = std_compat.mem.trimRight(u8, text[start..end], "\r");
if (detectLine(path, line, source)) |rule| {
try appendFinding(allocator, findings, options, rule, path, line_no, source, line);
}
if (end == text.len) break;
start = end + 1;
line_no += 1;
}
}
fn detectLine(path: []const u8, line: []const u8, source: FindingSource) ?DetectedRule {
if (line.len == 0) return null;
const path_category = classifyPath(path);
if (containsPrivateKeyMarker(line)) {
return .{ .severity = .critical, .confidence = .high, .rule = "private_key_block" };
}
if (findCredentialUrl(line)) |credential_url| {
return .{
.severity = .high,
.confidence = if (path_category == .docs or path_category == .code) .medium else .high,
.rule = "credential_in_url",
.detected_value = credential_url,
};
}
if (matchSecretAssignment(line)) |assignment| {
return classifySecretAssignment(path, line, path_category, assignment);
}
if (findTokenPrefixedValue(line)) |token| {
return .{
.severity = .high,
.confidence = if (source == .git_staged_diff or source == .git_history or path_category == .config)
.high
else
.medium,
.rule = "hardcoded_token",
.detected_value = token,
};
}
if (detectHighEntropyCandidate(path, line, source)) |rule| return rule;
return null;
}
const AssignmentMatch = struct {
key: []const u8,
value: []const u8,
quoted: bool,
keyword_score: u8,
strong_keyword: bool,
operator: []const u8,
};
fn matchSecretAssignment(line: []const u8) ?AssignmentMatch {
const sep_idx = findAssignmentSeparator(line) orelse return null;
const lhs = std.mem.trim(u8, line[0..sep_idx], " \t\"'`");
const key = extractAssignmentKey(lhs) orelse return null;
const key_traits = analyzeSecretKeyName(key);
if (key_traits.score == 0) return null;
const operator: []const u8 = if (line[sep_idx] == ':') ":" else "=";
var pos = sep_idx + 1;
while (pos < line.len and (line[pos] == ' ' or line[pos] == '"' or line[pos] == '\'')) pos += 1;
if (pos >= line.len) return null;
const quoted = pos > sep_idx + 1 and (line[pos - 1] == '"' or line[pos - 1] == '\'');
const value_start = pos;
var value_end = value_start;
while (value_end < line.len) : (value_end += 1) {
const ch = line[value_end];
if (ch == '"' or ch == '\'' or ch == ',' or ch == '#' or ch == ' ' or ch == '\t' or ch == ';') break;
}
if (value_end <= value_start) return null;
return .{
.key = key,
.value = line[value_start..value_end],
.quoted = quoted,
.keyword_score = key_traits.score,
.strong_keyword = key_traits.strong,
.operator = operator,
};
}
fn normalizeValue(value: []const u8) []const u8 {
return std.mem.trim(u8, value, " \t\"'");
}
fn isHighRiskKeyword(keyword: []const u8) bool {
return eqlIgnoreCase(keyword, "password") or eqlIgnoreCase(keyword, "passwd");
}
fn containsPrivateKeyMarker(line: []const u8) bool {
return std.mem.indexOf(u8, line, "-----BEGIN ") != null and std.mem.indexOf(u8, line, "PRIVATE KEY-----") != null;
}
fn findCredentialUrl(line: []const u8) ?[]const u8 {
const scheme_idx = std.mem.indexOf(u8, line, "://") orelse return null;
var url_start = scheme_idx;
while (url_start > 0 and isUrlSchemeChar(line[url_start - 1])) : (url_start -= 1) {}
var url_end = scheme_idx + 3;
while (url_end < line.len) : (url_end += 1) {
switch (line[url_end]) {
' ', '\t', '"', '\'', '`', ',', ';' => break,
else => {},
}
}
const rest = line[scheme_idx + 3 ..];
const authority_end = firstIndexAny(rest, "/?# \t\"'`,;") orelse rest.len;
const authority = rest[0..authority_end];
const at_idx = std.mem.indexOfScalar(u8, authority, '@') orelse return null;
const userinfo = authority[0..at_idx];
if (std.mem.indexOfScalar(u8, userinfo, ':') == null) return null;
return line[url_start..url_end];
}
fn isUrlSchemeChar(ch: u8) bool {
return std.ascii.isAlphanumeric(ch) or ch == '+' or ch == '-' or ch == '.';
}
fn findTokenPrefixedValue(text: []const u8) ?[]const u8 {
for (token_prefixes) |prefix| {
if (std.mem.indexOf(u8, text, prefix)) |idx| {
const end = tokenEnd(text, idx + prefix.len);
if (end > idx + prefix.len) {
const token = text[idx..end];
if (!looksPlaceholder(token)) return token;
}
}
}
return null;
}
fn tokenEnd(text: []const u8, start: usize) usize {
var end = start;
while (end < text.len) : (end += 1) {
const ch = text[end];
if (!(std.ascii.isAlphanumeric(ch) or ch == '-' or ch == '_' or ch == '.' or ch == ':')) break;
}
return end;
}
fn looksPlaceholder(text: []const u8) bool {
const trimmed = normalizeValue(text);
if (trimmed.len == 0) return true;
if (std.mem.startsWith(u8, trimmed, "${") or std.mem.startsWith(u8, trimmed, "{{") or std.mem.startsWith(u8, trimmed, "<")) return true;
if (indexOfIgnoreCase(trimmed, "example") != null) return true;
if (indexOfIgnoreCase(trimmed, "placeholder") != null) return true;
if (indexOfIgnoreCase(trimmed, "replace") != null) return true;
if (indexOfIgnoreCase(trimmed, "changeme") != null) return true;
if (indexOfIgnoreCase(trimmed, "dummy") != null) return true;
if (indexOfIgnoreCase(trimmed, "sample") != null) return true;
if (indexOfIgnoreCase(trimmed, "fake") != null) return true;
if (indexOfIgnoreCase(trimmed, "test") != null) return true;
if (eqlIgnoreCase(trimmed, "null") or eqlIgnoreCase(trimmed, "false") or eqlIgnoreCase(trimmed, "true")) return true;
return false;
}
fn appendFinding(
allocator: Allocator,
findings: *std.ArrayListUnmanaged(Finding),
options: Options,
rule: DetectedRule,
path: []const u8,
line_no: usize,
source: FindingSource,
raw_preview: []const u8,
) !void {
if (options.only_secrets and rule.severity.rank() < Severity.high.rank()) return;
const collect = options.collect_triage_context;
const raw_line: ?[]u8 = if (collect) try allocator.dupe(u8, raw_preview) else null;
errdefer if (raw_line) |v| allocator.free(v);
const detected_value: ?[]u8 = if (collect and rule.detected_value != null) try allocator.dupe(u8, rule.detected_value.?) else null;
errdefer if (detected_value) |v| allocator.free(v);
const assignment_key: ?[]u8 = if (collect and rule.assignment_key != null) try allocator.dupe(u8, rule.assignment_key.?) else null;
errdefer if (assignment_key) |v| allocator.free(v);
const assignment_operator: ?[]u8 = if (collect and rule.assignment_operator != null) try allocator.dupe(u8, rule.assignment_operator.?) else null;
errdefer if (assignment_operator) |v| allocator.free(v);
const rule_owned = try allocator.dupe(u8, rule.rule);
errdefer allocator.free(rule_owned);
const path_owned = try allocator.dupe(u8, path);
errdefer allocator.free(path_owned);
const preview_owned = try buildPreview(allocator, raw_preview);
errdefer allocator.free(preview_owned);
try findings.append(allocator, .{
.severity = rule.severity,
.confidence = rule.confidence,
.rule = rule_owned,
.path = path_owned,
.line = line_no,
.source = source,
.preview = preview_owned,
.raw_line = raw_line,
.detected_value = detected_value,
.assignment_key = assignment_key,
.assignment_operator = assignment_operator,
});
}
fn buildPreview(allocator: Allocator, raw: []const u8) ![]u8 {
const scrubbed = try scrub.scrubSecretPatterns(allocator, raw);
if (scrubbed.len <= MAX_PREVIEW_CHARS) return scrubbed;
const preview = util.previewUtf8(scrubbed, MAX_PREVIEW_CHARS);
const out = try std.fmt.allocPrint(allocator, "{s}...", .{preview.slice});
allocator.free(scrubbed);
return out;
}
fn shouldSkipEntry(name: []const u8, kind: std_compat.fs.File.Kind) bool {
if (kind == .directory) {
for (skipped_dirs) |dir_name| {
if (std.mem.eql(u8, name, dir_name)) return true;
}
}
return false;
}
fn shouldIgnorePath(path: []const u8, exclude_patterns: []const []const u8) bool {
for (ignored_path_prefixes) |prefix| {
if (std.mem.startsWith(u8, path, prefix)) return true;
}
for (exclude_patterns) |pattern| {
if (pattern.len == 0) continue;
if (std.mem.indexOf(u8, path, pattern) != null) return true;
}
return false;
}
fn isProbablyBinary(bytes: []const u8) bool {
if (bytes.len == 0) return false;
if (std.mem.indexOfScalar(u8, bytes, 0) != null) return true;
var suspicious: usize = 0;
for (bytes) |ch| {
if (ch < 0x09) suspicious += 1;
}
return suspicious > 8;
}
fn parseDiffPath(line: []const u8) ?[]const u8 {
if (std.mem.startsWith(u8, line, "+++ b/")) return line[6..];
return null;
}
fn parseAddedHunkStart(line: []const u8) ?usize {
const plus_idx = std.mem.indexOfScalar(u8, line, '+') orelse return null;
var end = plus_idx + 1;
while (end < line.len and std.ascii.isDigit(line[end])) : (end += 1) {}
if (end == plus_idx + 1) return null;
return std.fmt.parseInt(usize, line[plus_idx + 1 .. end], 10) catch null;
}
fn containsText(haystack: []const u8, needle: []const u8) bool {
return std.mem.indexOf(u8, haystack, needle) != null;
}
fn classifyPath(path: []const u8) PathCategory {
if (std.mem.startsWith(u8, path, "vendor/") or
std.mem.startsWith(u8, path, "zig-pkg/") or
std.mem.startsWith(u8, path, "node_modules/"))
{
return .vendor_like;
}
if (isDocumentationPath(path)) return .docs;
if (isConfigLikePath(path)) return .config;
if (isCodePath(path)) return .code;
return .neutral;
}
fn classifySecretAssignment(
path: []const u8,
line: []const u8,
path_category: PathCategory,
assignment: AssignmentMatch,
) ?DetectedRule {
const value = normalizeValue(assignment.value);
if (value.len == 0 or looksPlaceholder(value)) return null;
const token_value = findTokenPrefixedValue(value);
const known_token = token_value != null;
const opaque_value = looksOpaqueSecretValue(value);
const expression = looksLikeExpression(value) and !known_token and !opaque_value;
const high_risk_keyword = assignment.strong_keyword or assignment.keyword_score >= 4 or isHighRiskKeyword(assignment.key);
if (expression or looksLikeAccessorLine(line)) return null;
switch (path_category) {
.vendor_like => {
if (!known_token and assignment.keyword_score < 4) return null;
},
.docs => {
if (!known_token and !opaque_value and assignment.keyword_score < 2 and value.len < 12) return null;
},
.code => {
if (!known_token and !opaque_value and !assignment.quoted and assignment.keyword_score < 2 and value.len < 12) return null;
},
.config => {
if (!known_token and !opaque_value and !high_risk_keyword and assignment.keyword_score < 2 and value.len < 8) {
return null;
}
},
.neutral => {
if (!known_token and !opaque_value and !high_risk_keyword and assignment.keyword_score < 2 and value.len < 12) {
return null;
}
},
}
const severity: Severity = if (known_token or high_risk_keyword or assignment.keyword_score >= 3 or (path_category == .config and opaque_value))
.high
else
.medium;
const confidence: Confidence = if (known_token)
.high
else switch (path_category) {
.config => if (opaque_value or high_risk_keyword or assignment.keyword_score >= 3) .medium else .low,
.neutral => if (opaque_value or high_risk_keyword or assignment.keyword_score >= 3) .medium else .low,
.code => if (high_risk_keyword or assignment.keyword_score >= 3) .medium else .low,
.docs => .low,
.vendor_like => .medium,
};
return .{
.severity = severity,
.confidence = confidence,
.rule = if (std.mem.indexOf(u8, path, ".env") != null) "env_secret_assignment" else "secret_assignment",
.detected_value = token_value orelse value,
.assignment_key = assignment.key,
.assignment_operator = assignment.operator,
};
}
const SecretKeyTraits = struct {
score: u8,
strong: bool,
};
fn findAssignmentSeparator(line: []const u8) ?usize {
for (line, 0..) |ch, idx| {
switch (ch) {
'=' => return idx,
':' => {
if (idx + 2 < line.len and line[idx + 1] == '/' and line[idx + 2] == '/') continue;
return idx;
},
else => {},
}
}
return null;
}
fn extractAssignmentKey(lhs: []const u8) ?[]const u8 {
var trimmed = std.mem.trim(u8, lhs, " \t\"'`");
if (trimmed.len == 0) return null;
if (startsWithIgnoreCase(trimmed, "export ")) {
trimmed = std_compat.mem.trimLeft(u8, trimmed[7..], " \t");
}
var end = trimmed.len;
while (end > 0 and !isIdentifierChar(trimmed[end - 1])) : (end -= 1) {}
if (end == 0) return null;
var start = end;
while (start > 0 and isIdentifierChar(trimmed[start - 1])) : (start -= 1) {}
if (start == end) return null;
return trimmed[start..end];
}
fn analyzeSecretKeyName(key: []const u8) SecretKeyTraits {
var score: u8 = 0;
var strong = false;
var start: usize = 0;
while (start < key.len) {
while (start < key.len and !std.ascii.isAlphanumeric(key[start])) : (start += 1) {}
if (start >= key.len) break;
var end = start;
while (end < key.len and std.ascii.isAlphanumeric(key[end])) : (end += 1) {}
const component = key[start..end];
const component_score = scoreSecretKeyComponent(component);
score +|= component_score.score;
strong = strong or component_score.strong;
start = end + 1;
}
return .{ .score = score, .strong = strong };
}
const ComponentScore = struct {
score: u8,
strong: bool,
};
fn scoreSecretKeyComponent(component: []const u8) ComponentScore {
if (component.len == 0) return .{ .score = 0, .strong = false };
if (eqlIgnoreCase(component, "token") or
eqlIgnoreCase(component, "secret") or
eqlIgnoreCase(component, "password") or
eqlIgnoreCase(component, "passwd") or
eqlIgnoreCase(component, "apikey") or
eqlIgnoreCase(component, "clientsecret") or
eqlIgnoreCase(component, "privatekey") or
eqlIgnoreCase(component, "bearertoken") or
eqlIgnoreCase(component, "secretaccesskey"))
{
return .{ .score = 3, .strong = true };
}
if (eqlIgnoreCase(component, "access") or
eqlIgnoreCase(component, "key") or
eqlIgnoreCase(component, "auth") or
eqlIgnoreCase(component, "bearer") or
eqlIgnoreCase(component, "credential") or
eqlIgnoreCase(component, "credentials") or
eqlIgnoreCase(component, "session") or
eqlIgnoreCase(component, "client") or
eqlIgnoreCase(component, "private") or
eqlIgnoreCase(component, "api") or
eqlIgnoreCase(component, "webhook") or
eqlIgnoreCase(component, "slack") or
eqlIgnoreCase(component, "aws"))
{
return .{ .score = 1, .strong = false };
}
return .{ .score = 0, .strong = false };
}
fn isIdentifierChar(ch: u8) bool {
return std.ascii.isAlphanumeric(ch) or ch == '_' or ch == '-';
}
fn isDocumentationPath(path: []const u8) bool {
if (std.mem.startsWith(u8, path, "docs/") or std.mem.startsWith(u8, path, "reference/")) return true;
const basename = std.fs.path.basename(path);
if (eqlIgnoreCase(basename, "README") or eqlIgnoreCase(basename, "README.md")) return true;
const ext = std.fs.path.extension(path);
return eqlIgnoreCase(ext, ".md") or eqlIgnoreCase(ext, ".rst") or eqlIgnoreCase(ext, ".adoc");
}
fn isConfigLikePath(path: []const u8) bool {
const basename = std.fs.path.basename(path);
const ext = std.fs.path.extension(path);
if (std.mem.startsWith(u8, basename, ".env")) return true;
if (eqlIgnoreCase(ext, ".env") or eqlIgnoreCase(ext, ".pem") or eqlIgnoreCase(ext, ".key") or eqlIgnoreCase(ext, ".crt") or eqlIgnoreCase(ext, ".cer") or eqlIgnoreCase(ext, ".p12") or eqlIgnoreCase(ext, ".pfx")) {
return true;
}
if (eqlIgnoreCase(ext, ".json") or eqlIgnoreCase(ext, ".yaml") or eqlIgnoreCase(ext, ".yml") or eqlIgnoreCase(ext, ".toml") or eqlIgnoreCase(ext, ".ini") or eqlIgnoreCase(ext, ".conf") or eqlIgnoreCase(ext, ".properties")) {
return true;
}
return indexOfIgnoreCase(basename, "secret") != null or
indexOfIgnoreCase(basename, "credential") != null or
indexOfIgnoreCase(basename, "config") != null;
}
fn isCodePath(path: []const u8) bool {
const ext = std.fs.path.extension(path);
const code_exts = [_][]const u8{
".zig", ".c", ".h", ".cc", ".cpp", ".hpp", ".rs", ".go", ".py", ".js",
".ts", ".tsx", ".jsx", ".java", ".kt", ".swift", ".rb", ".php", ".cs", ".scala",
".sh", ".bash", ".zsh",
};
for (code_exts) |code_ext| {
if (eqlIgnoreCase(ext, code_ext)) return true;
}
return false;
}
fn looksOpaqueSecretValue(value: []const u8) bool {
if (value.len < 16) return false;
if (std.mem.indexOfAny(u8, value, " \t(){}[]") != null) return false;
var alpha: usize = 0;
var digit: usize = 0;
var allowed: usize = 0;
for (value) |ch| {
if (std.ascii.isAlphabetic(ch)) alpha += 1;
if (std.ascii.isDigit(ch)) digit += 1;
if (std.ascii.isAlphanumeric(ch) or ch == '-' or ch == '_' or ch == '.' or ch == ':' or ch == '/' or ch == '+' or ch == '=') {
allowed += 1;
}
}
if (alpha == 0 or digit == 0) return false;
return allowed * 100 >= value.len * 85;
}
fn looksLikeExpression(value: []const u8) bool {
if (std.mem.indexOfScalar(u8, value, '(') != null or std.mem.indexOfScalar(u8, value, ')') != null) return true;
if (std.mem.indexOf(u8, value, "std.") != null) return true;
if (std.mem.indexOf(u8, value, ".get") != null) return true;
if (std.mem.indexOf(u8, value, "process.env.") != null) return true;
if (std.mem.indexOf(u8, value, "System.getenv") != null) return true;
if (std.mem.indexOf(u8, value, "getenv") != null) return true;
if (std.mem.indexOf(u8, value, "trim") != null and std.mem.indexOfScalar(u8, value, '(') != null) return true;
if (std.mem.indexOfScalar(u8, value, '{') != null or std.mem.indexOfScalar(u8, value, '}') != null) return true;
return false;
}
fn looksLikeAccessorLine(line: []const u8) bool {
return std.mem.indexOf(u8, line, ".get(\"authorization\")") != null or
std.mem.indexOf(u8, line, ".get(\"token\")") != null or
std.mem.indexOf(u8, line, ".headers.get(") != null;
}
fn detectHighEntropyCandidate(path: []const u8, line: []const u8, source: FindingSource) ?DetectedRule {
_ = source;
const path_category = classifyPath(path);
const candidate = findHighEntropyCandidate(line) orelse return null;
return .{
.severity = if (path_category == .config) .high else .medium,
.confidence = switch (path_category) {
.config => .medium,
.neutral => .medium,
.code => .low,
.docs => .low,
.vendor_like => .low,
},
.rule = "high_entropy_secret_candidate",
.detected_value = candidate,
};
}
fn containsHighEntropyCandidate(line: []const u8) bool {
return findHighEntropyCandidate(line) != null;
}
fn findHighEntropyCandidate(line: []const u8) ?[]const u8 {
var i: usize = 0;
while (i < line.len) {
while (i < line.len and !isEntropyCharset(line[i])) : (i += 1) {}
if (i >= line.len) break;
const start = i;
while (i < line.len and isEntropyCharset(line[i])) : (i += 1) {}
const candidate_run = line[start..i];
if (candidateFromEntropyRun(candidate_run)) |candidate| {