-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
505 lines (426 loc) · 14.4 KB
/
main.go
File metadata and controls
505 lines (426 loc) · 14.4 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
package main
import (
"flag"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"strings"
sops "github.com/getsops/sops/v3"
sopsformats "github.com/getsops/sops/v3/cmd/sops/formats"
sopsconfig "github.com/getsops/sops/v3/config"
sopsstores "github.com/getsops/sops/v3/stores"
sopsdotenv "github.com/getsops/sops/v3/stores/dotenv"
sopsini "github.com/getsops/sops/v3/stores/ini"
sopsjson "github.com/getsops/sops/v3/stores/json"
sopsyaml "github.com/getsops/sops/v3/stores/yaml"
"gopkg.in/yaml.v3"
)
// version is set at build time via -ldflags "-X main.version=...".
var version = "dev"
const (
encryptedPrefix = "ENC["
dryRunMarker = "__SOPS_COP_SELECTED__"
exitSuccess = 0
exitInvalidArguments = 2
exitFileReadError = 3
exitInvalidInput = 4
exitUnencryptedValue = 5
exitConfigError = 6
)
func exitPriority(code int) int {
switch code {
case exitConfigError:
return 3
case exitFileReadError, exitInvalidInput:
return 2
case exitUnencryptedValue:
return 1
default:
return 0
}
}
func mergeExitCode(current, candidate int) int {
if exitPriority(candidate) > exitPriority(current) {
return candidate
}
return current
}
// main configures CLI behavior and exits with process-level status codes.
func main() {
target := flag.String("target", ".", "Path inside a SOPS project (optional). Used to locate .sops.yaml")
showVersion := flag.Bool("version", false, "Print version and exit")
flag.Usage = usage
flag.Parse()
if *showVersion {
fmt.Fprintf(os.Stdout, "sops-cop %s\n", version)
os.Exit(exitSuccess)
}
os.Exit(run(*target, os.Stderr))
}
// usage prints CLI help text and available flags.
func usage() {
out := flag.CommandLine.Output()
fmt.Fprintf(out, "sops-cop %s\n\n", version)
fmt.Fprintln(out, "Validates YAML/JSON/ENV/INI values are encrypted according to .sops.yaml rules.")
fmt.Fprintln(out, "Usage:")
fmt.Fprintln(out, " sops-cop [-target <path-inside-project>]")
fmt.Fprintln(out)
fmt.Fprintln(out, "The enforcer locates .sops.yaml from the provided path (or current directory),")
fmt.Fprintln(out, "then scans the SOPS project and validates files matched by path_regex rules.")
fmt.Fprintln(out)
flag.PrintDefaults()
}
// run executes validation and returns an exit code.
func run(target string, stderr io.Writer) int {
if strings.TrimSpace(target) == "" {
target = "."
}
// Resolve absolute path
absTarget, err := filepath.Abs(target)
if err != nil {
fmt.Fprintf(stderr, "error: failed to resolve path: %v\n", err)
return exitInvalidArguments
}
// Check if target exists
info, err := os.Stat(absTarget)
if err != nil {
fmt.Fprintf(stderr, "error: target not found: %v\n", err)
return exitFileReadError
}
// Load .sops.yaml
startDir := absTarget
if !info.IsDir() {
startDir = filepath.Dir(absTarget)
}
config, configDir, err := loadSopsConfig(startDir)
if err != nil {
fmt.Fprintf(stderr, "error: failed to load .sops.yaml config: %v\n", err)
return exitConfigError
}
// Validate all files matched by creation_rules from the SOPS project root.
return validateProject(config, configDir, stderr)
}
// validateProject validates all files in configDir that match creation_rules.path_regex.
func validateProject(config *SopsConfig, configDir string, stderr io.Writer) int {
exitCode := exitSuccess
totalViolations := 0
err := filepath.Walk(configDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
if filepath.Base(path) == ".sops.yaml" {
return nil
}
rule, matched, err := loadCreationRuleForFile(config, path)
if err != nil {
fmt.Fprintf(stderr, "error: failed to match creation rule for %s: %v\n", path, err)
exitCode = exitConfigError
return nil
}
if !matched {
return nil
}
if !isSupportedStructuredFile(path) {
fmt.Fprintf(stderr, "warning: skipping unsupported file matched by path_regex: %s\n", path)
return nil
}
code, violations := validateFileWithRule(path, rule, stderr)
totalViolations += violations
exitCode = mergeExitCode(exitCode, code)
return nil
})
if err != nil {
fmt.Fprintf(stderr, "error: failed to walk project directory: %v\n", err)
return mergeExitCode(exitCode, exitFileReadError)
}
// Summary report to stderr so it doesn't interfere with piping.
if totalViolations > 0 {
fmt.Fprintf(stderr, "\n🚨 SOPS-COP found %d violations! Fix these before committing.\n", totalViolations)
} else if exitCode == exitSuccess {
fmt.Fprintf(stderr, "\n✅ All files compliant with .sops.yaml rules.\n")
}
return exitCode
}
// validateFileWithRule validates a single file using a specific creation rule.
// Returns (exitCode, violationCount).
func validateFileWithRule(filePath string, rule *sopsconfig.Config, stderr io.Writer) (int, int) {
data, err := os.ReadFile(filePath)
if err != nil {
fmt.Fprintf(stderr, "error: failed to read file: %v\n", err)
return exitFileReadError, 0
}
failures, formatName, err := validateContentForFile(filePath, data, rule)
if err != nil {
fmt.Fprintf(stderr, "error: invalid %s: %v\n", formatName, err)
return exitInvalidInput, 0
}
if len(failures) > 0 {
for _, msg := range failures {
fmt.Fprintf(stderr, "%s:%s\n", filePath, msg)
}
return exitUnencryptedValue, len(failures)
}
return exitSuccess, 0
}
// plainFileLoader is implemented by SOPS format stores that load plaintext into tree branches.
type plainFileLoader interface {
LoadPlainFile([]byte) (sops.TreeBranches, error)
}
func isSupportedStructuredFile(path string) bool {
return sopsformats.IsYAMLFile(path) ||
sopsformats.IsJSONFile(path) ||
sopsformats.IsEnvFile(path) ||
sopsformats.IsIniFile(path)
}
func formatNameForPath(path string) string {
switch {
case sopsformats.IsYAMLFile(path):
return "YAML"
case sopsformats.IsJSONFile(path):
return "JSON"
case sopsformats.IsEnvFile(path):
return "ENV"
case sopsformats.IsIniFile(path):
return "INI"
default:
return "file"
}
}
func validateContentForFile(filePath string, data []byte, rule *sopsconfig.Config) ([]string, string, error) {
if sopsformats.IsYAMLFile(filePath) {
failures, err := validateYAMLContent(data, rule)
return failures, "YAML", err
}
if strings.TrimSpace(string(data)) == "" {
return []string{}, formatNameForPath(filePath), nil
}
switch {
case sopsformats.IsJSONFile(filePath):
failures, err := validateStructuredContent(data, rule, sopsjson.NewStore(&sopsconfig.JSONStoreConfig{}))
return failures, "JSON", err
case sopsformats.IsEnvFile(filePath):
failures, err := validateStructuredContent(data, rule, sopsdotenv.NewStore(&sopsconfig.DotenvStoreConfig{}))
return failures, "ENV", err
case sopsformats.IsIniFile(filePath):
failures, err := validateStructuredContent(data, rule, sopsini.NewStore(&sopsconfig.INIStoreConfig{}))
return failures, "INI", err
default:
return []string{}, formatNameForPath(filePath), nil
}
}
func validateStructuredContent(data []byte, rule *sopsconfig.Config, store plainFileLoader) ([]string, error) {
branchesForValidation, err := store.LoadPlainFile(data)
if err != nil {
return []string{}, err
}
if len(branchesForValidation) == 0 {
return []string{}, nil
}
branchesForSelection, err := store.LoadPlainFile(data)
if err != nil {
return []string{}, err
}
encryptedPaths, err := computeSOPSSelectedPathsFromBranches(branchesForSelection, rule)
if err != nil {
return []string{}, err
}
var failures []string
for _, branch := range branchesForValidation {
walkTreeValue(branch, nil, &failures, encryptedPaths)
}
if failures == nil {
failures = []string{}
}
return failures, nil
}
// validateYAMLContent parses YAML bytes and returns locations of unencrypted values that should be encrypted.
func validateYAMLContent(data []byte, rule *sopsconfig.Config) ([]string, error) {
// Parse YAML first to detect empty or comment-only files before
// handing data to the SOPS store, which rejects empty input.
var root yaml.Node
if err := yaml.Unmarshal(data, &root); err != nil {
return []string{}, err
}
// Empty file or comment-only: nothing to validate.
if len(root.Content) == 0 {
return []string{}, nil
}
doc := root.Content[0]
// Document node with no data (e.g., bare "---").
if len(doc.Content) == 0 {
return []string{}, nil
}
// Determine which paths SOPS would encrypt. tree.Encrypt with our
// dryRunCipher respects EncryptedRegex, UnencryptedRegex, EncryptedSuffix,
// UnencryptedSuffix, and comment-based regex selectors — mirroring SOPS's
// own selection logic exactly.
encryptedPaths, err := computeSOPSSelectedPaths(data, rule)
if err != nil {
return []string{}, err
}
var failures []string
walkNode(doc, nil, &failures, encryptedPaths)
// Ensure we return a proper empty slice, not nil.
if failures == nil {
failures = []string{}
}
return failures, nil
}
// walkNode recursively traverses YAML nodes and checks encryption based on SOPS-selected paths.
func walkNode(node *yaml.Node, path []string, failures *[]string, encryptedPaths map[string]struct{}) {
if node == nil {
return
}
switch node.Kind {
case yaml.DocumentNode:
for _, child := range node.Content {
walkNode(child, path, failures, encryptedPaths)
}
case yaml.MappingNode:
for i := 0; i+1 < len(node.Content); i += 2 {
keyNode := node.Content[i]
valueNode := node.Content[i+1]
// Always skip the sops metadata
if keyNode.Value == sopsstores.SopsMetadataKey {
continue
}
nextPath := appendPath(path, keyNode.Value)
walkNode(valueNode, nextPath, failures, encryptedPaths)
}
case yaml.SequenceNode:
for i, child := range node.Content {
nextPath := appendPath(path, strconv.Itoa(i))
walkNode(child, nextPath, failures, encryptedPaths)
}
case yaml.ScalarNode:
// Flag this value only when both conditions are met:
// 1. The path is in encryptedPaths (SOPS selected it for encryption).
// 2. The value is not already encrypted (missing "ENC[" prefix or not a string).
if _, shouldEncrypt := encryptedPaths[joinPath(path)]; shouldEncrypt && (node.Tag != "!!str" || !strings.HasPrefix(node.Value, encryptedPrefix)) {
msg := fmt.Sprintf("%d:%d: unencrypted value found at '%s'",
node.Line, node.Column, joinPath(path))
*failures = append(*failures, msg)
}
case yaml.AliasNode:
if node.Alias != nil {
walkNode(node.Alias, path, failures, encryptedPaths)
}
}
}
// dryRunCipher is a no-op cipher that marks values as selected for encryption.
// When passed to tree.Encrypt, SOPS applies its full regex/suffix selection logic
// and calls Encrypt only for values it considers encryptable — letting us discover
// the exact set of paths SOPS would encrypt without performing real cryptography.
type dryRunCipher struct{}
func (c dryRunCipher) Encrypt(plaintext interface{}, key []byte, additionalData string) (string, error) {
return dryRunMarker, nil
}
func (c dryRunCipher) Decrypt(ciphertext string, key []byte, additionalData string) (interface{}, error) {
return ciphertext, nil
}
func computeSOPSSelectedPaths(data []byte, rule *sopsconfig.Config) (map[string]struct{}, error) {
store := sopsyaml.NewStore(&sopsconfig.YAMLStoreConfig{})
branches, err := store.LoadPlainFile(data)
if err != nil {
return nil, err
}
return computeSOPSSelectedPathsFromBranches(branches, rule)
}
func computeSOPSSelectedPathsFromBranches(branches sops.TreeBranches, rule *sopsconfig.Config) (map[string]struct{}, error) {
// Apply the SOPS default: when no selector is specified, keys ending in
// "_unencrypted" are left as plaintext.
unencryptedSuffix := rule.UnencryptedSuffix
if rule.UnencryptedSuffix == "" && rule.EncryptedSuffix == "" &&
rule.UnencryptedRegex == "" && rule.EncryptedRegex == "" &&
rule.UnencryptedCommentRegex == "" && rule.EncryptedCommentRegex == "" {
unencryptedSuffix = sops.DefaultUnencryptedSuffix
}
tree := sops.Tree{
Branches: branches,
Metadata: sops.Metadata{
UnencryptedSuffix: unencryptedSuffix,
EncryptedSuffix: rule.EncryptedSuffix,
UnencryptedRegex: rule.UnencryptedRegex,
EncryptedRegex: rule.EncryptedRegex,
UnencryptedCommentRegex: rule.UnencryptedCommentRegex,
EncryptedCommentRegex: rule.EncryptedCommentRegex,
MACOnlyEncrypted: rule.MACOnlyEncrypted,
},
}
if _, err := tree.Encrypt([]byte("sops-cop-dry-run-key"), dryRunCipher{}); err != nil {
return nil, err
}
selected := make(map[string]struct{})
for _, branch := range tree.Branches {
collectSelectedPaths(branch, nil, selected)
}
return selected, nil
}
func walkTreeValue(value interface{}, path []string, failures *[]string, encryptedPaths map[string]struct{}) {
switch typed := value.(type) {
case sops.TreeBranch:
for _, item := range typed {
key := fmt.Sprint(item.Key)
if key == sopsstores.SopsMetadataKey {
continue
}
nextPath := appendPath(path, key)
walkTreeValue(item.Value, nextPath, failures, encryptedPaths)
}
case []interface{}:
for i, item := range typed {
nextPath := appendPath(path, strconv.Itoa(i))
walkTreeValue(item, nextPath, failures, encryptedPaths)
}
case string:
if _, shouldEncrypt := encryptedPaths[joinPath(path)]; shouldEncrypt && !strings.HasPrefix(typed, encryptedPrefix) {
msg := fmt.Sprintf("unencrypted value found at '%s'", joinPath(path))
*failures = append(*failures, msg)
}
default:
if _, shouldEncrypt := encryptedPaths[joinPath(path)]; shouldEncrypt {
msg := fmt.Sprintf("unencrypted value found at '%s'", joinPath(path))
*failures = append(*failures, msg)
}
}
}
func collectSelectedPaths(value interface{}, path []string, selected map[string]struct{}) {
switch typed := value.(type) {
case sops.TreeBranch:
for _, item := range typed {
key := fmt.Sprint(item.Key)
if key == sopsstores.SopsMetadataKey {
continue
}
nextPath := appendPath(path, key)
collectSelectedPaths(item.Value, nextPath, selected)
}
case []interface{}:
for i, item := range typed {
nextPath := appendPath(path, strconv.Itoa(i))
collectSelectedPaths(item, nextPath, selected)
}
case string:
if typed == dryRunMarker {
selected[joinPath(path)] = struct{}{}
}
}
}
// appendPath creates a new path with one additional segment.
func appendPath(path []string, part string) []string {
next := make([]string, len(path), len(path)+1)
copy(next, path)
return append(next, part)
}
// joinPath formats a breadcrumb path for error reporting.
func joinPath(path []string) string {
if len(path) == 0 {
return "<root>"
}
return strings.Join(path, ".")
}