-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaudit_packets.go
More file actions
696 lines (651 loc) · 24.1 KB
/
Copy pathaudit_packets.go
File metadata and controls
696 lines (651 loc) · 24.1 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
package repomap
import (
"bufio"
"context"
"fmt"
"os"
"path/filepath"
"reflect"
"regexp"
"slices"
"strings"
"unicode"
)
const maxAuditLineBytes = 1024 * 1024
// AuditSurfaceReport captures deterministic user-facing contracts that are
// useful audit entrypoints before a model starts reading source broadly.
type AuditSurfaceReport struct {
SchemaVersion int `json:"schema_version"`
Root string `json:"root"`
Files []AuditSurfaceFile `json:"files"`
FilesOmittedReason string `json:"files_omitted_reason,omitempty"`
Truncations []AuditTruncation `json:"truncations,omitempty"`
Commands []AuditSurfaceHit `json:"commands,omitempty"`
Flags []AuditSurfaceHit `json:"flags,omitempty"`
EnvVars []AuditSurfaceHit `json:"env_vars,omitempty"`
ConfigKeys []AuditSurfaceHit `json:"config_keys,omitempty"`
SchemaFields []AuditSurfaceHit `json:"schema_fields,omitempty"`
Routes []AuditSurfaceHit `json:"routes,omitempty"`
Jobs []AuditSurfaceHit `json:"jobs,omitempty"`
ModelFields []AuditSurfaceHit `json:"model_fields,omitempty"`
Policies []AuditSurfaceHit `json:"policies,omitempty"`
Outputs []AuditSurfaceHit `json:"outputs,omitempty"`
DependencyManifests []AuditSurfaceHit `json:"dependency_manifests,omitempty"`
}
// AuditSurfaceFile groups user-facing contract hits by source file.
type AuditSurfaceFile struct {
ID string `json:"id"`
Path string `json:"path"`
Score int `json:"score"`
EvidenceClass string `json:"evidence_class,omitempty"`
Confidence string `json:"confidence,omitempty"`
Kinds []string `json:"kinds"`
Hits []AuditSurfaceHit `json:"hits"`
OmittedReason string `json:"omitted_reason,omitempty"`
}
// AuditSurfaceHit is one static surface lead.
type AuditSurfaceHit struct {
Kind string `json:"kind"`
Name string `json:"name,omitempty"`
Path string `json:"path"`
Line int `json:"line"`
Lane string `json:"lane"`
Evidence string `json:"evidence"`
Hidden bool `json:"hidden,omitempty"`
}
// AuditTruncation accounts for every deterministic packet cap.
type AuditTruncation struct {
Field string `json:"field"`
Shown int `json:"shown"`
Total int `json:"total"`
Reason string `json:"reason"`
}
// AuditEffectReport captures files with side effects and trust boundaries.
type AuditEffectReport struct {
SchemaVersion int `json:"schema_version"`
Root string `json:"root"`
Files []AuditEffectFile `json:"files"`
FilesOmittedReason string `json:"files_omitted_reason,omitempty"`
Kinds []AuditEffectKind `json:"kinds"`
Truncations []AuditTruncation `json:"truncations,omitempty"`
}
// AuditEffectFile groups side-effect leads by source file.
type AuditEffectFile struct {
ID string `json:"id"`
Path string `json:"path"`
Score int `json:"score"`
EvidenceClass string `json:"evidence_class,omitempty"`
Confidence string `json:"confidence,omitempty"`
Lanes []string `json:"lanes"`
Effects []AuditEffect `json:"effects"`
OmittedReason string `json:"omitted_reason,omitempty"`
allEffects []AuditEffect
}
// AllEffects returns the uncapped effects used to derive this file packet.
// Callers that apply an additional filter must filter this set before applying
// the public per-file cap represented by Effects.
func (f AuditEffectFile) AllEffects() []AuditEffect {
if f.allEffects != nil {
return f.allEffects
}
return f.Effects
}
// AuditEffect is one static side-effect lead.
type AuditEffect struct {
Kind string `json:"kind"`
Op string `json:"op"`
Path string `json:"path"`
Line int `json:"line"`
Lane string `json:"lane"`
Evidence string `json:"evidence"`
}
// AuditEffectKind groups files that share a side-effect kind.
type AuditEffectKind struct {
ID string `json:"id"`
Name string `json:"name"`
Reason string `json:"reason"`
Lane string `json:"lane"`
Files []string `json:"files"`
Caveat string `json:"caveat,omitempty"`
Command string `json:"command,omitempty"`
OmittedReason string `json:"omitted_reason,omitempty"`
}
type auditStaticFile struct {
path string
score int
lines []auditLine
}
type auditLine struct {
number int
text string
}
type auditPattern struct {
kind string
lane string
weight int
re *regexp.Regexp
name func([]string) string
}
var surfacePatterns = []auditPattern{
{kind: "command", lane: "cli-ux", weight: 8, re: regexp.MustCompile(`\bUse:\s*"([^"]+)"`), name: groupName(1)},
{kind: "flag", lane: "cli-ux", weight: 7, re: regexp.MustCompile(`\.(?:String|StringP|StringVar|StringVarP|Bool|BoolP|BoolVar|BoolVarP|Int|IntP|IntVar|IntVarP|StringSlice|StringSliceVar)\(\s*"([^"]+)"`), name: groupName(1)},
{kind: "flag", lane: "cli-ux", weight: 7, re: regexp.MustCompile(`\bflag\.(?:String|Bool|Int|Duration|Float64)\(\s*"([^"]+)"`), name: groupName(1)},
{kind: "env-var", lane: "config", weight: 7, re: regexp.MustCompile(`\b(?:os\.)?(?:Getenv|LookupEnv)\(\s*"([^"]+)"`), name: groupName(1)},
{kind: "config-key", lane: "config", weight: 5, re: regexp.MustCompile("`[^`]*(?:yaml|toml):\"([^\" ,]+)[^\"`]*\"[^`]*`"), name: groupName(1)},
{kind: "schema-field", lane: "api-contracts", weight: 3, re: regexp.MustCompile("`[^`]*json:\"([^\" ,]+)[^\"`]*\"[^`]*`"), name: groupName(1)},
{kind: "route", lane: "api-contracts", weight: 8, re: regexp.MustCompile(`\b(?:http\.)?(?:Handle|HandleFunc)\(\s*"([^"]+)"`), name: groupName(1)},
{kind: "job", lane: "lifecycle-concurrency", weight: 7, re: regexp.MustCompile(`\b(?:RegisterHandler|RegisterTask|HandleTask|NewTask|NewPeriodicTask|RegisterJob|AddJob)\(\s*"([^"]+)"`), name: groupName(1)},
{kind: "model-field", lane: "data-integrity", weight: 4, re: regexp.MustCompile("`[^`]*(?:gorm|db|bun):\"([^\" ,]+)[^\"`]*\"[^`]*`"), name: groupName(1)},
{kind: "policy", lane: "security", weight: 7, re: regexp.MustCompile(`\b(?:RegisterPolicy|RegisterMiddleware|AddPolicy|RequirePermission|RequireRole)\(\s*"([^"]+)"`), name: groupName(1)},
{kind: "output", lane: "cli-ux", weight: 5, re: regexp.MustCompile(`\b(?:OutOrStdout|OutOrStderr|os\.Stdout|os\.Stderr|fmt\.Fprint|fmt\.Fprintf|json\.NewEncoder|Encoder\()`)},
}
var effectPatterns = []auditPattern{
{kind: "filesystem-write", lane: "data-integrity", weight: 10, re: regexp.MustCompile(`\b(?:os\.)?(?:WriteFile|OpenFile|Create|MkdirAll|Rename|Remove|RemoveAll)\(`), name: firstToken},
{kind: "filesystem-read", lane: "data-integrity", weight: 4, re: regexp.MustCompile(`\bos\.(?:ReadFile|Open)\(`), name: firstToken},
{kind: "subprocess", lane: "error-handling", weight: 10, re: regexp.MustCompile(`\bexec\.Command(?:Context)?\(`), name: literalName("exec.Command")},
{kind: "process-exit", lane: "error-handling", weight: 8, re: regexp.MustCompile(`\b(?:os\.Exit|log\.Fatal|panic)\(`), name: firstToken},
{kind: "http", lane: "api-contracts", weight: 8, re: regexp.MustCompile(`\b(?:http\.Client|http\.NewRequest|http\.Get|http\.Post|http\.Handle|http\.HandleFunc|ListenAndServe)\b`), name: firstToken},
{kind: "database", lane: "data-integrity", weight: 10, re: regexp.MustCompile(`\b(?:sql\.Open|QueryContext|ExecContext|BeginTx|Commit|Rollback|sqlite|pgx|database/sql)\b`), name: firstToken},
{kind: "serialization", lane: "api-contracts", weight: 5, re: regexp.MustCompile(`\b(?:json|yaml|toml|xml)\.(?:Marshal|Unmarshal|NewEncoder|NewDecoder)\b`), name: firstToken},
{kind: "secret", lane: "security", weight: 9, re: regexp.MustCompile(`(?i)(?:api[_-]?key|apikey|token|secret|password|passwd|credentials?)\s*[:=]\s*["']?[A-Za-z0-9_/+.-]{8,}`), name: literalName("secret-like assignment")},
{kind: "crypto", lane: "security", weight: 8, re: regexp.MustCompile(`\b(?:crypto/|x/crypto|bcrypt|sha256|sha512|hmac|cipher)\b`), name: firstToken},
{kind: "time", lane: "data-integrity", weight: 3, re: regexp.MustCompile(`\btime\.(?:Now|Since|After|NewTicker|NewTimer)\(`), name: firstToken},
{kind: "randomness", lane: "security", weight: 5, re: regexp.MustCompile(`\b(?:rand\.|crypto/rand)\b`), name: firstToken},
{kind: "context-background", lane: "lifecycle-concurrency", weight: 7, re: regexp.MustCompile(`\bcontext\.Background\(\)`), name: literalName("context.Background")},
{kind: "goroutine", lane: "lifecycle-concurrency", weight: 8, re: regexp.MustCompile(`\bgo\s+func\s*\(`), name: literalName("go func")},
{kind: "unbounded-read", lane: "performance", weight: 9, re: regexp.MustCompile(`\bio\.ReadAll\s*\(`), name: literalName("io.ReadAll")},
}
var dependencyManifestNames = []string{
"go.mod",
"package.json",
"composer.json",
"Cargo.toml",
"pyproject.toml",
"Gemfile",
}
// AuditSurface extracts command, flag, env, config, route, and output surfaces.
func (m *Map) AuditSurface(ctx context.Context, limit int) (AuditSurfaceReport, error) {
files := m.auditStaticFiles()
report := AuditSurfaceReport{SchemaVersion: 3, Root: m.root, Files: []AuditSurfaceFile{}}
totals := map[string]int{}
for _, file := range files {
lines, err := readAuditLines(ctx, filepath.Join(m.root, filepath.FromSlash(file.path)))
if err != nil {
return AuditSurfaceReport{}, err
}
file.lines = lines
hits, score := scanSurfaceFile(file)
if len(hits) == 0 {
continue
}
sf := AuditSurfaceFile{
ID: "repomap:surface:" + auditSlug(file.path),
Path: file.path,
Score: score,
EvidenceClass: auditEvidenceHeuristic,
Confidence: auditConfidence(auditEvidenceHeuristic, false),
Kinds: hitKinds(hits),
Hits: capSurfaceHits(hits, 12),
}
if len(hits) > 12 {
sf.OmittedReason = fmt.Sprintf("showing 12 of %d hits; truncated by surface cap", len(hits))
report.Truncations = append(report.Truncations, AuditTruncation{
Field: "files[" + file.path + "].hits", Shown: 12, Total: len(hits), Reason: "surface per-file cap",
})
}
report.Files = append(report.Files, sf)
for _, hit := range hits {
totals[hit.Kind]++
switch hit.Kind {
case "command":
report.Commands = appendCapped(report.Commands, hit, 80)
case "flag":
report.Flags = appendCapped(report.Flags, hit, 120)
case "env-var":
report.EnvVars = appendCapped(report.EnvVars, hit, 120)
case "config-key":
report.ConfigKeys = appendCapped(report.ConfigKeys, hit, 120)
case "schema-field":
report.SchemaFields = appendCapped(report.SchemaFields, hit, 120)
case "route":
report.Routes = appendCapped(report.Routes, hit, 120)
case "job":
report.Jobs = appendCapped(report.Jobs, hit, 120)
case "model-field":
report.ModelFields = appendCapped(report.ModelFields, hit, 120)
case "policy":
report.Policies = appendCapped(report.Policies, hit, 120)
case "output":
report.Outputs = appendCapped(report.Outputs, hit, 120)
}
}
}
m.addDependencyManifestSurface(&report)
totals["dependency-manifest"] = len(report.DependencyManifests)
report.addSurfaceAggregateTruncations(totals)
sortSurfaceFiles(report.Files)
totalFiles := len(report.Files)
if limit > 0 && len(report.Files) > limit {
report.Files = report.Files[:limit]
}
if len(report.Files) == 0 {
report.FilesOmittedReason = "no surface data extracted from scanned files"
} else if len(report.Files) < totalFiles {
report.FilesOmittedReason = fmt.Sprintf("showing %d of %d files; truncated by --limit", len(report.Files), totalFiles)
report.Truncations = append(report.Truncations, AuditTruncation{
Field: "files", Shown: len(report.Files), Total: totalFiles, Reason: "--limit",
})
}
return report, nil
}
// AuditEffects extracts side-effect and trust-boundary packets from source.
func (m *Map) AuditEffects(ctx context.Context, limit int) (AuditEffectReport, error) {
files := m.auditStaticFiles()
report := AuditEffectReport{SchemaVersion: 3, Root: m.root, Files: []AuditEffectFile{}}
kindFiles := map[string][]string{}
for _, file := range files {
lines, err := readAuditLines(ctx, filepath.Join(m.root, filepath.FromSlash(file.path)))
if err != nil {
return AuditEffectReport{}, err
}
file.lines = lines
effects, score := scanEffectFile(file)
if len(effects) == 0 {
continue
}
lanes := effectLanes(effects)
ec := auditEvidenceForLanes(lanes)
effectFile := AuditEffectFile{
ID: "repomap:effect:" + auditSlug(file.path),
Path: file.path,
Score: score,
EvidenceClass: ec,
Confidence: auditConfidence(ec, false),
Lanes: lanes,
Effects: capEffectHits(effects, 12),
allEffects: effects,
}
if len(effects) > 12 {
effectFile.OmittedReason = fmt.Sprintf("showing 12 of %d effects; truncated by effects cap", len(effects))
report.Truncations = append(report.Truncations, AuditTruncation{
Field: "files[" + file.path + "].effects", Shown: 12, Total: len(effects), Reason: "effects per-file cap",
})
}
report.Files = append(report.Files, effectFile)
for _, effect := range effects {
kindFiles[effect.Kind] = append(kindFiles[effect.Kind], effect.Path)
}
}
sortEffectFiles(report.Files)
totalFiles := len(report.Files)
if limit > 0 && len(report.Files) > limit {
report.Files = report.Files[:limit]
}
report.Kinds = buildEffectKinds(kindFiles)
if len(report.Files) == 0 {
report.FilesOmittedReason = "no side-effect data extracted from scanned files"
} else if len(report.Files) < totalFiles {
report.FilesOmittedReason = fmt.Sprintf("showing %d of %d files; truncated by --limit", len(report.Files), totalFiles)
report.Truncations = append(report.Truncations, AuditTruncation{
Field: "files", Shown: len(report.Files), Total: totalFiles, Reason: "--limit",
})
}
return report, nil
}
func (m *Map) auditStaticFiles() []auditStaticFile {
m.mu.RLock()
ranked := cloneRanked(m.ranked)
m.mu.RUnlock()
files := make([]auditStaticFile, 0, len(ranked))
for _, f := range ranked {
path := filepath.ToSlash(f.Path)
if path == "" || isTestPath(path) {
continue
}
files = append(files, auditStaticFile{path: path, score: f.Score})
}
return files
}
func readAuditLines(ctx context.Context, path string) ([]auditLine, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
file, err := os.Open(path)
if err != nil {
return nil, fmt.Errorf("open audit source %s: %w", path, err)
}
defer func() { _ = file.Close() }()
scanner := bufio.NewScanner(file)
scanner.Buffer(make([]byte, 0, 64*1024), maxAuditLineBytes)
var lines []auditLine
for scanner.Scan() {
if err := ctx.Err(); err != nil {
return nil, err
}
lines = append(lines, auditLine{number: len(lines) + 1, text: strings.TrimSpace(scanner.Text())})
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("scan audit source %s: %w", path, err)
}
return lines, nil
}
func scanSurfaceFile(file auditStaticFile) ([]AuditSurfaceHit, int) {
var hits []AuditSurfaceHit
score := 0
for _, line := range file.lines {
if kongHit, ok := scanKongSurfaceLine(file.path, line); ok {
hits = append(hits, kongHit)
score += 7
}
for _, pattern := range surfacePatterns {
match := pattern.re.FindStringSubmatch(line.text)
if match == nil {
continue
}
name := patternName(pattern, match)
if name == "-" {
continue
}
hits = append(hits, AuditSurfaceHit{
Kind: pattern.kind,
Name: name,
Path: file.path,
Line: line.number,
Lane: pattern.lane,
Evidence: auditEvidence(line.text),
})
score += pattern.weight
}
}
return hits, score + min(file.score/20, 10)
}
func scanKongSurfaceLine(path string, line auditLine) (AuditSurfaceHit, bool) {
tagStart := strings.IndexByte(line.text, '`')
tagEnd := strings.LastIndexByte(line.text, '`')
if tagStart < 0 || tagEnd <= tagStart {
return AuditSurfaceHit{}, false
}
fields := strings.Fields(strings.TrimSpace(line.text[:tagStart]))
if len(fields) < 2 || !unicode.IsUpper(rune(fields[0][0])) {
return AuditSurfaceHit{}, false
}
tag := reflect.StructTag(line.text[tagStart+1 : tagEnd])
_, command := tag.Lookup("cmd")
_, argument := tag.Lookup("arg")
_, documented := tag.Lookup("help")
_, hidden := tag.Lookup("hidden")
_, named := tag.Lookup("name")
_, shortened := tag.Lookup("short")
if !command && (argument || (!documented && !hidden && !named && !shortened)) {
return AuditSurfaceHit{}, false
}
name := tag.Get("name")
if name == "" {
name = kebabIdentifier(fields[0])
}
kind := "flag"
if command {
kind = "command"
}
return AuditSurfaceHit{
Kind: kind, Name: name, Path: path, Line: line.number, Lane: "cli-ux",
Evidence: auditEvidence(line.text), Hidden: hidden,
}, true
}
func kebabIdentifier(value string) string {
runes := []rune(value)
var b strings.Builder
for i, r := range runes {
if i > 0 && unicode.IsUpper(r) &&
(unicode.IsLower(runes[i-1]) || unicode.IsDigit(runes[i-1]) ||
(i+1 < len(runes) && unicode.IsLower(runes[i+1]))) {
b.WriteByte('-')
}
b.WriteRune(unicode.ToLower(r))
}
return b.String()
}
func (r *AuditSurfaceReport) addSurfaceAggregateTruncations(totals map[string]int) {
fields := []struct {
kind string
field string
shown int
}{
{"command", "commands", len(r.Commands)},
{"flag", "flags", len(r.Flags)},
{"env-var", "env_vars", len(r.EnvVars)},
{"config-key", "config_keys", len(r.ConfigKeys)},
{"schema-field", "schema_fields", len(r.SchemaFields)},
{"route", "routes", len(r.Routes)},
{"job", "jobs", len(r.Jobs)},
{"model-field", "model_fields", len(r.ModelFields)},
{"policy", "policies", len(r.Policies)},
{"output", "outputs", len(r.Outputs)},
{"dependency-manifest", "dependency_manifests", len(r.DependencyManifests)},
}
for _, entry := range fields {
if total := totals[entry.kind]; total > entry.shown {
r.Truncations = append(r.Truncations, AuditTruncation{
Field: entry.field, Shown: entry.shown, Total: total, Reason: "surface aggregate cap",
})
}
}
}
func scanEffectFile(file auditStaticFile) ([]AuditEffect, int) {
var effects []AuditEffect
score := 0
for _, line := range file.lines {
for _, pattern := range effectPatterns {
match := pattern.re.FindStringSubmatch(line.text)
if match == nil {
continue
}
if pattern.kind == "unbounded-read" && strings.Contains(line.text, "LimitReader") {
continue
}
effects = append(effects, AuditEffect{
Kind: pattern.kind,
Op: patternName(pattern, match),
Path: file.path,
Line: line.number,
Lane: pattern.lane,
Evidence: auditEvidence(line.text),
})
score += pattern.weight
}
}
return effects, score + min(file.score/20, 10)
}
func (m *Map) addDependencyManifestSurface(report *AuditSurfaceReport) {
for _, name := range dependencyManifestNames {
info, err := os.Stat(filepath.Join(m.root, name))
if err != nil || info.IsDir() {
continue
}
hit := AuditSurfaceHit{
Kind: "dependency-manifest",
Name: name,
Path: name,
Lane: "dependency-policy",
Evidence: "root dependency manifest",
}
report.DependencyManifests = append(report.DependencyManifests, hit)
report.Files = append(report.Files, AuditSurfaceFile{
ID: "repomap:surface:" + auditSlug(name),
Path: name,
Score: 15,
EvidenceClass: auditEvidenceHeuristic,
Confidence: auditConfidence(auditEvidenceHeuristic, false),
Kinds: []string{"dependency-manifest"},
Hits: []AuditSurfaceHit{hit},
})
}
}
func patternName(pattern auditPattern, match []string) string {
if pattern.name == nil {
return ""
}
return pattern.name(match)
}
func groupName(index int) func([]string) string {
return func(match []string) string {
if len(match) <= index {
return ""
}
return match[index]
}
}
func literalName(name string) func([]string) string {
return func([]string) string {
return name
}
}
func firstToken(match []string) string {
if len(match) == 0 {
return ""
}
token := strings.Trim(match[0], " \t\n\r({")
if idx := strings.Index(token, "("); idx >= 0 {
token = token[:idx]
}
return token
}
func auditEvidence(text string) string {
text = strings.Join(strings.Fields(text), " ")
if len(text) <= 160 {
return text
}
return text[:157] + "..."
}
func hitKinds(hits []AuditSurfaceHit) []string {
seen := map[string]bool{}
var out []string
for _, hit := range hits {
if seen[hit.Kind] {
continue
}
seen[hit.Kind] = true
out = append(out, hit.Kind)
}
slices.Sort(out)
return out
}
func effectLanes(effects []AuditEffect) []string {
seen := map[string]bool{}
var out []string
for _, effect := range effects {
if seen[effect.Lane] {
continue
}
seen[effect.Lane] = true
out = append(out, effect.Lane)
}
slices.Sort(out)
return out
}
func appendCapped[T any](items []T, item T, cap int) []T {
if cap > 0 && len(items) >= cap {
return items
}
return append(items, item)
}
func capSurfaceHits(hits []AuditSurfaceHit, cap int) []AuditSurfaceHit {
if cap > 0 && len(hits) > cap {
return hits[:cap]
}
return hits
}
func capEffectHits(hits []AuditEffect, cap int) []AuditEffect {
if cap > 0 && len(hits) > cap {
return hits[:cap]
}
return hits
}
func sortSurfaceFiles(files []AuditSurfaceFile) {
slices.SortFunc(files, func(a, b AuditSurfaceFile) int {
if a.Score != b.Score {
return b.Score - a.Score
}
return strings.Compare(a.Path, b.Path)
})
}
func sortEffectFiles(files []AuditEffectFile) {
slices.SortFunc(files, func(a, b AuditEffectFile) int {
if a.Score != b.Score {
return b.Score - a.Score
}
return strings.Compare(a.Path, b.Path)
})
}
func buildEffectKinds(kindFiles map[string][]string) []AuditEffectKind {
names := make([]string, 0, len(kindFiles))
for name := range kindFiles {
names = append(names, name)
}
slices.Sort(names)
out := make([]AuditEffectKind, 0, len(names))
for _, name := range names {
out = append(out, AuditEffectKind{
ID: "repomap:effect-kind:" + auditSlug(name),
Name: name,
Reason: effectKindReason(name),
Lane: effectKindLane(name),
Files: dedupeAndSort(kindFiles[name]),
Caveat: auditExternalCaveat([]string{effectKindLane(name)}),
Command: "repomap audit effects --json",
})
}
return out
}
func effectKindReason(name string) string {
switch name {
case "filesystem-write":
return "writes, renames, or deletes can affect data integrity and rollback behavior"
case "filesystem-read":
return "file reads can affect config, import, and input validation behavior"
case "subprocess":
return "subprocess boundaries need timeout, stderr, and exit-code handling"
case "process-exit":
return "process termination paths affect cleanup and user-facing errors"
case "http":
return "HTTP boundaries need request, response, timeout, and contract checks"
case "database":
return "database calls need transaction, migration, and error-path checks"
case "serialization":
return "serialization boundaries define API, file, and persistence contracts"
case "secret":
return "secret-like assignments need storage, logging, and config review"
case "crypto":
return "crypto boundaries need algorithm and key-handling review"
case "time":
return "time-dependent logic can affect ordering, expiry, and reproducibility"
case "randomness":
return "randomness can affect security, determinism, and reproducibility"
case "context-background":
return "context.Background in source can break caller cancellation chains"
case "goroutine":
return "goroutine launches need exit and ownership checks"
case "unbounded-read":
return "io.ReadAll without an obvious local cap needs resource-bound review"
default:
return "static side-effect signal"
}
}
func effectKindLane(name string) string {
switch name {
case "filesystem-write", "filesystem-read", "database", "time":
return "data-integrity"
case "subprocess", "process-exit":
return "error-handling"
case "http", "serialization":
return "api-contracts"
case "secret", "crypto", "randomness":
return "security"
case "context-background", "goroutine":
return "lifecycle-concurrency"
case "unbounded-read":
return "performance"
default:
return "best-practices"
}
}