-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_test.go
More file actions
2365 lines (2198 loc) · 73.6 KB
/
main_test.go
File metadata and controls
2365 lines (2198 loc) · 73.6 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
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"time"
"github.com/compliance-framework/agent/runner/proto"
"github.com/hashicorp/go-hclog"
)
func stubLookPath(t *testing.T, fn func(string) (string, error)) {
t.Helper()
original := lookPath
lookPath = fn
t.Cleanup(func() {
lookPath = original
})
}
func stubNetworkDiagnostics(
t *testing.T,
lookup func(context.Context, string) ([]string, error),
tlsProbe func(context.Context, networkDiagnosticEndpoint) (tlsProbeResult, error),
) {
t.Helper()
originalLookup := lookupHost
originalTLSProbe := tlsProbeEndpoint
lookupHost = lookup
tlsProbeEndpoint = tlsProbe
t.Cleanup(func() {
lookupHost = originalLookup
tlsProbeEndpoint = originalTLSProbe
})
}
func TestPluginConfigParse(t *testing.T) {
stubLookPath(t, func(binary string) (string, error) {
return "/usr/local/bin/" + binary, nil
})
t.Run("inline only", func(t *testing.T) {
cfg := &PluginConfig{
PoliciesYAML: `policies:
- name: s3-check
resource: aws.s3`,
}
parsed, err := cfg.Parse()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if parsed.PoliciesYAML == "" {
t.Fatalf("expected inline yaml to be preserved")
}
if parsed.CheckTimeout != 300*time.Second {
t.Fatalf("expected default timeout 300s, got %s", parsed.CheckTimeout)
}
if parsed.CustodianBinary != "/usr/local/bin/custodian" {
t.Fatalf("unexpected resolved binary: %s", parsed.CustodianBinary)
}
})
t.Run("path only", func(t *testing.T) {
cfg := &PluginConfig{
PoliciesPath: "/tmp/policies.yaml",
CustodianBinary: "custom-custodian",
CustodianDebug: " true ",
CustodianVerbose: " true ",
CustodianAWSAPITrace: " true ",
CustodianNetworkDiag: " true ",
CustodianNetworkDiagnosticEndpoints: "https://vpce-123.backup.eu-west-1.vpce.amazonaws.com, vpce-456.ec2.eu-west-1.vpce.amazonaws.com",
CustodianLogTail: " true ",
CheckTimeoutSeconds: "45",
AWSRegions: "us-east-1, eu-west-1 us-east-1",
PreserveArtifacts: " true ",
}
parsed, err := cfg.Parse()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if parsed.PoliciesPath != "/tmp/policies.yaml" {
t.Fatalf("unexpected policies path: %s", parsed.PoliciesPath)
}
if parsed.CheckTimeout != 45*time.Second {
t.Fatalf("expected timeout 45s, got %s", parsed.CheckTimeout)
}
if parsed.CustodianBinary != "/usr/local/bin/custom-custodian" {
t.Fatalf("unexpected resolved binary: %s", parsed.CustodianBinary)
}
if !parsed.CustodianDebug {
t.Fatalf("expected custodian debug to be enabled")
}
if !parsed.CustodianVerbose {
t.Fatalf("expected custodian verbose to be enabled")
}
if !parsed.CustodianAWSAPITrace {
t.Fatalf("expected custodian AWS API trace to be enabled")
}
if !parsed.CustodianNetworkDiag {
t.Fatalf("expected custodian network diagnostics to be enabled")
}
if !parsed.CustodianLogTail {
t.Fatalf("expected custodian log tailing to be enabled")
}
if !parsed.PreserveArtifacts {
t.Fatalf("expected artifact preservation to be enabled")
}
if len(parsed.AWSRegions) != 2 || parsed.AWSRegions[0] != "us-east-1" || parsed.AWSRegions[1] != "eu-west-1" {
t.Fatalf("unexpected aws regions: %#v", parsed.AWSRegions)
}
if len(parsed.CustodianNetworkDiagnosticEndpoints) != 2 || parsed.CustodianNetworkDiagnosticEndpoints[0] != "https://vpce-123.backup.eu-west-1.vpce.amazonaws.com" {
t.Fatalf("unexpected network diagnostic endpoints: %#v", parsed.CustodianNetworkDiagnosticEndpoints)
}
})
t.Run("reject empty sources", func(t *testing.T) {
_, err := (&PluginConfig{}).Parse()
if err == nil {
t.Fatalf("expected error for missing policies source")
}
})
t.Run("reject invalid labels json", func(t *testing.T) {
_, err := (&PluginConfig{PoliciesYAML: "x", PolicyLabels: "{"}).Parse()
if err == nil {
t.Fatalf("expected error for invalid policy_labels json")
}
})
t.Run("parse resource identity fields", func(t *testing.T) {
parsed, err := (&PluginConfig{
PoliciesYAML: "x",
ResourceIdentityFields: `{"aws.ec2":[" InstanceId ","Arn",""]}`,
}).Parse()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
got := parsed.ResourceIdentityFields["aws.ec2"]
if len(got) != 2 || got[0] != "InstanceId" || got[1] != "Arn" {
t.Fatalf("unexpected normalized resource identity fields: %#v", got)
}
})
t.Run("reject invalid resource identity fields json", func(t *testing.T) {
_, err := (&PluginConfig{PoliciesYAML: "x", ResourceIdentityFields: "{"}).Parse()
if err == nil {
t.Fatalf("expected error for invalid resource_identity_fields json")
}
})
t.Run("reject empty resource type in resource identity fields", func(t *testing.T) {
_, err := (&PluginConfig{
PoliciesYAML: "x",
ResourceIdentityFields: `{"":["Id"]}`,
}).Parse()
if err == nil {
t.Fatalf("expected error for empty resource type key")
}
})
t.Run("reject empty resource identity field list", func(t *testing.T) {
_, err := (&PluginConfig{
PoliciesYAML: "x",
ResourceIdentityFields: `{"aws.ec2":[" ",""]}`,
}).Parse()
if err == nil {
t.Fatalf("expected error for empty resource identity field list")
}
})
t.Run("reject invalid timeout", func(t *testing.T) {
_, err := (&PluginConfig{PoliciesYAML: "x", CheckTimeoutSeconds: "abc"}).Parse()
if err == nil {
t.Fatalf("expected error for invalid timeout")
}
})
t.Run("reject invalid debug boolean", func(t *testing.T) {
_, err := (&PluginConfig{PoliciesYAML: "x", DebugDumpPayloads: "not-bool"}).Parse()
if err == nil {
t.Fatalf("expected error for invalid debug_dump_payloads")
}
})
t.Run("reject invalid custodian debug boolean", func(t *testing.T) {
_, err := (&PluginConfig{PoliciesYAML: "x", CustodianDebug: "not-bool"}).Parse()
if err == nil {
t.Fatalf("expected error for invalid custodian_debug")
}
})
t.Run("reject invalid custodian verbose boolean", func(t *testing.T) {
_, err := (&PluginConfig{PoliciesYAML: "x", CustodianVerbose: "not-bool"}).Parse()
if err == nil {
t.Fatalf("expected error for invalid custodian_verbose")
}
})
t.Run("reject invalid diagnostic booleans", func(t *testing.T) {
fields := []PluginConfig{
{PoliciesYAML: "x", CustodianAWSAPITrace: "not-bool"},
{PoliciesYAML: "x", CustodianNetworkDiag: "not-bool"},
{PoliciesYAML: "x", CustodianLogTail: "not-bool"},
{PoliciesYAML: "x", PreserveArtifacts: "not-bool"},
}
for _, cfg := range fields {
_, err := cfg.Parse()
if err == nil {
t.Fatalf("expected error for invalid diagnostic boolean in %#v", cfg)
}
}
})
t.Run("enable debug dump when output dir is set", func(t *testing.T) {
cfg := &PluginConfig{
PoliciesYAML: "policies: []",
DebugPayloadOutputDir: "/tmp/custom-debug-dir",
}
parsed, err := cfg.Parse()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !parsed.DebugDumpPayloads {
t.Fatalf("expected debug dump to auto-enable when output dir is provided")
}
if parsed.DebugPayloadOutputDir != "/tmp/custom-debug-dir" {
t.Fatalf("unexpected debug output dir: %s", parsed.DebugPayloadOutputDir)
}
})
}
func TestResolvePoliciesYAML(t *testing.T) {
t.Run("inline preferred over path", func(t *testing.T) {
content, err := resolvePoliciesYAML(context.Background(), "policies: []", "https://example.invalid/policies.yaml")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if string(content) != "policies: []" {
t.Fatalf("unexpected content: %s", string(content))
}
})
t.Run("local file", func(t *testing.T) {
f := filepath.Join(t.TempDir(), "policies.yaml")
if err := os.WriteFile(f, []byte("policies: []"), 0o600); err != nil {
t.Fatalf("failed to write temp file: %v", err)
}
content, err := resolvePoliciesYAML(context.Background(), "", f)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if string(content) != "policies: []" {
t.Fatalf("unexpected content: %s", string(content))
}
})
t.Run("http success", func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("policies:\n - name: test\n resource: aws.s3"))
}))
defer srv.Close()
content, err := resolvePoliciesYAML(context.Background(), "", srv.URL)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !strings.Contains(string(content), "name: test") {
t.Fatalf("expected fetched yaml content")
}
})
t.Run("http non-2xx", func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadGateway)
}))
defer srv.Close()
_, err := resolvePoliciesYAML(context.Background(), "", srv.URL)
if err == nil {
t.Fatalf("expected error for non-2xx response")
}
})
t.Run("http response too large", func(t *testing.T) {
oversized := strings.Repeat("a", defaultMaxRemotePolicyBytes+1)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(oversized))
}))
defer srv.Close()
_, err := resolvePoliciesYAML(context.Background(), "", srv.URL)
if err == nil {
t.Fatalf("expected error for oversized response body")
}
if !strings.Contains(err.Error(), "too large") {
t.Fatalf("expected oversized body error, got: %v", err)
}
})
t.Run("unsupported scheme", func(t *testing.T) {
_, err := resolvePoliciesYAML(context.Background(), "", "s3://bucket/policies.yaml")
if err == nil {
t.Fatalf("expected error for unsupported scheme")
}
})
t.Run("windows style path treated as local path", func(t *testing.T) {
_, err := resolvePoliciesYAML(context.Background(), "", `C:\policies.yaml`)
if err == nil {
t.Fatalf("expected local file read error for missing windows-style path")
}
if !strings.Contains(err.Error(), "failed to read local policies file") {
t.Fatalf("expected local file read path handling, got: %v", err)
}
})
}
func TestParseCustodianChecks(t *testing.T) {
t.Run("valid policies", func(t *testing.T) {
checks, err := parseCustodianChecks([]byte(`policies:
- name: s3-public
resource: aws.s3
non_compliance_message: S3 bucket allows public access.
mode:
type: periodic
- name: vm-policy
resource: azure.vm`))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(checks) != 2 {
t.Fatalf("expected 2 checks, got %d", len(checks))
}
if checks[0].Provider != "aws" {
t.Fatalf("expected provider aws, got %s", checks[0].Provider)
}
if len(checks[0].ParseErrors) != 0 {
t.Fatalf("expected no parse errors, got %v", checks[0].ParseErrors)
}
if checks[0].RawPolicy[nonComplianceMessageField] != "S3 bucket allows public access." {
t.Fatalf("expected non-compliance message to be preserved in raw policy, got %#v", checks[0].RawPolicy[nonComplianceMessageField])
}
})
t.Run("invalid entries become check errors", func(t *testing.T) {
checks, err := parseCustodianChecks([]byte(`policies:
- "not-an-object"
- name: missing-resource`))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(checks) != 2 {
t.Fatalf("expected 2 checks, got %d", len(checks))
}
if len(checks[0].ParseErrors) == 0 {
t.Fatalf("expected parse error for first check")
}
if len(checks[1].ParseErrors) == 0 {
t.Fatalf("expected parse error for second check")
}
})
t.Run("missing top-level policies fails", func(t *testing.T) {
_, err := parseCustodianChecks([]byte(`foo: bar`))
if err == nil {
t.Fatalf("expected error when top-level policies missing")
}
})
}
func writeExecutableScript(t *testing.T, script string) string {
t.Helper()
if runtime.GOOS == "windows" {
t.Skip("shell script helper is not supported on windows")
}
binary := filepath.Join(t.TempDir(), "custodian")
if err := os.WriteFile(binary, []byte(script), 0o755); err != nil {
t.Fatalf("failed to write script: %v", err)
}
return binary
}
func TestCommandCustodianExecutor(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("executor tests use POSIX shell scripts")
}
t.Run("passes required args and loads resources", func(t *testing.T) {
argsFile := filepath.Join(t.TempDir(), "args.txt")
t.Setenv("ARGS_FILE", argsFile)
script := `#!/bin/sh
set -eu
echo "$@" > "$ARGS_FILE"
out=""
while [ "$#" -gt 0 ]; do
if [ "$1" = "-s" ]; then
out="$2"
shift 2
continue
fi
shift
done
mkdir -p "$out/test-policy"
printf '[{"id":"abc"}]' > "$out/test-policy/resources.json"
`
binary := writeExecutableScript(t, script)
executor := &CommandCustodianExecutor{Logger: hclog.NewNullLogger()}
outDir := filepath.Join(t.TempDir(), "out")
result := executor.Execute(context.Background(), CustodianExecutionRequest{
BinaryPath: binary,
Check: CustodianCheck{
Name: "test-policy",
Resource: "aws.s3",
Provider: "aws",
RawPolicy: map[string]interface{}{"name": "test-policy", "resource": "aws.s3"},
},
Timeout: 5 * time.Second,
OutputDir: outDir,
})
if result.Err != nil {
t.Fatalf("expected successful execution, got error: %v", result.Err)
}
if result.ExitCode != 0 {
t.Fatalf("expected exit code 0, got %d", result.ExitCode)
}
if len(result.Resources) != 1 {
t.Fatalf("expected one resource, got %d", len(result.Resources))
}
if result.ResourcesPath == "" {
t.Fatalf("expected resources path to be set")
}
argsContent, err := os.ReadFile(argsFile)
if err != nil {
t.Fatalf("failed to read args capture file: %v", err)
}
argsStr := string(argsContent)
if !strings.Contains(argsStr, "run --dryrun -s") {
t.Fatalf("expected dry-run args, got: %s", argsStr)
}
if !strings.Contains(argsStr, "policy.yaml") {
t.Fatalf("expected policy.yaml argument, got: %s", argsStr)
}
if !strings.Contains(argsStr, "--region all") {
t.Fatalf("expected aws region fanout args, got: %s", argsStr)
}
})
t.Run("passes configured aws regions without all fallback", func(t *testing.T) {
argsFile := filepath.Join(t.TempDir(), "args.txt")
t.Setenv("ARGS_FILE", argsFile)
script := `#!/bin/sh
set -eu
echo "$@" > "$ARGS_FILE"
out=""
while [ "$#" -gt 0 ]; do
if [ "$1" = "-s" ]; then
out="$2"
shift 2
continue
fi
shift
done
mkdir -p "$out/test-policy"
printf '[]' > "$out/test-policy/resources.json"
`
binary := writeExecutableScript(t, script)
executor := &CommandCustodianExecutor{Logger: hclog.NewNullLogger()}
result := executor.Execute(context.Background(), CustodianExecutionRequest{
BinaryPath: binary,
Check: CustodianCheck{
Name: "test-policy",
Resource: "aws.s3",
Provider: "aws",
RawPolicy: map[string]interface{}{"name": "test-policy", "resource": "aws.s3"},
},
Timeout: 5 * time.Second,
OutputDir: filepath.Join(t.TempDir(), "out"),
AWSRegions: []string{"us-east-1", "eu-west-1"},
})
if result.Err != nil {
t.Fatalf("expected successful execution, got error: %v", result.Err)
}
argsContent, err := os.ReadFile(argsFile)
if err != nil {
t.Fatalf("failed to read args capture file: %v", err)
}
argsStr := string(argsContent)
if !strings.Contains(argsStr, "--region us-east-1 --region eu-west-1") {
t.Fatalf("expected configured aws region args, got: %s", argsStr)
}
if strings.Contains(argsStr, "--region all") {
t.Fatalf("did not expect all-region fallback when aws regions are configured, got: %s", argsStr)
}
})
t.Run("network diagnostics failure prevents custodian execution", func(t *testing.T) {
executedFile := filepath.Join(t.TempDir(), "executed.txt")
t.Setenv("EXECUTED_FILE", executedFile)
stubNetworkDiagnostics(
t,
func(ctx context.Context, host string) ([]string, error) {
return []string{"10.0.0.10"}, nil
},
func(ctx context.Context, endpoint networkDiagnosticEndpoint) (tlsProbeResult, error) {
if endpoint.Source != "aws-vpc-endpoint" {
t.Fatalf("expected vpc endpoint source, got %s", endpoint.Source)
}
if endpoint.Host != "vpce-123.backup.eu-west-1.vpce.amazonaws.com" {
t.Fatalf("unexpected endpoint host: %s", endpoint.Host)
}
return tlsProbeResult{}, errors.New("handshake failed")
},
)
script := `#!/bin/sh
set -eu
touch "$EXECUTED_FILE"
`
binary := writeExecutableScript(t, script)
executor := &CommandCustodianExecutor{Logger: hclog.NewNullLogger()}
result := executor.Execute(context.Background(), CustodianExecutionRequest{
BinaryPath: binary,
Check: CustodianCheck{
Name: "test-policy",
Resource: "aws.backup-vault",
Provider: "aws",
RawPolicy: map[string]interface{}{"name": "test-policy", "resource": "aws.backup-vault"},
},
Timeout: 5 * time.Second,
OutputDir: filepath.Join(t.TempDir(), "out"),
NetworkDiagnostics: true,
NetworkDiagnosticEndpoints: []string{"https://vpce-123.backup.eu-west-1.vpce.amazonaws.com"},
})
if result.Err == nil {
t.Fatalf("expected network diagnostics failure")
}
if !strings.Contains(result.Error, "aws endpoint network diagnostics failed") || !strings.Contains(result.Error, "handshake failed") {
t.Fatalf("expected diagnostic failure detail, got: %s", result.Error)
}
if _, err := os.Stat(executedFile); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("expected custodian command not to execute, stat err: %v", err)
}
})
t.Run("network diagnostics allow configured endpoints for unmapped resources", func(t *testing.T) {
stubNetworkDiagnostics(
t,
func(ctx context.Context, host string) ([]string, error) {
return []string{"10.0.0.10"}, nil
},
func(ctx context.Context, endpoint networkDiagnosticEndpoint) (tlsProbeResult, error) {
if endpoint.Host != "vpce-123.example.eu-west-1.vpce.amazonaws.com" {
t.Fatalf("unexpected endpoint host: %s", endpoint.Host)
}
return tlsProbeResult{RemoteAddr: "10.0.0.10:443", TLSVersion: "TLS1.3"}, nil
},
)
script := `#!/bin/sh
set -eu
out=""
while [ "$#" -gt 0 ]; do
if [ "$1" = "-s" ]; then
out="$2"
shift 2
continue
fi
shift
done
mkdir -p "$out/test-policy"
printf '[]' > "$out/test-policy/resources.json"
`
binary := writeExecutableScript(t, script)
executor := &CommandCustodianExecutor{Logger: hclog.NewNullLogger()}
result := executor.Execute(context.Background(), CustodianExecutionRequest{
BinaryPath: binary,
Check: CustodianCheck{
Name: "test-policy",
Resource: "aws.future-resource",
Provider: "aws",
RawPolicy: map[string]interface{}{"name": "test-policy", "resource": "aws.future-resource"},
},
Timeout: 5 * time.Second,
OutputDir: filepath.Join(t.TempDir(), "out"),
NetworkDiagnostics: true,
NetworkDiagnosticEndpoints: []string{"vpce-123.example.eu-west-1.vpce.amazonaws.com"},
})
if result.Err != nil {
t.Fatalf("expected successful execution, got error: %v", result.Err)
}
})
t.Run("network diagnostics stop when context is canceled", func(t *testing.T) {
stubNetworkDiagnostics(
t,
func(ctx context.Context, host string) ([]string, error) {
t.Fatalf("did not expect DNS probe after context cancellation, got host %s", host)
return nil, nil
},
func(ctx context.Context, endpoint networkDiagnosticEndpoint) (tlsProbeResult, error) {
t.Fatalf("did not expect TLS probe after context cancellation, got endpoint %#v", endpoint)
return tlsProbeResult{}, nil
},
)
executor := &CommandCustodianExecutor{Logger: hclog.NewNullLogger()}
ctx, cancel := context.WithCancel(context.Background())
cancel()
err := executor.runAWSEndpointDiagnostics(ctx, CustodianExecutionRequest{
Check: CustodianCheck{
Name: "test-policy",
Resource: "aws.backup-vault",
Provider: "aws",
},
NetworkDiagnosticEndpoints: []string{"vpce-123.backup.eu-west-1.vpce.amazonaws.com"},
})
if !errors.Is(err, context.Canceled) {
t.Fatalf("expected context canceled error, got %v", err)
}
})
t.Run("network diagnostics skip service probes when regions are not concrete", func(t *testing.T) {
stubNetworkDiagnostics(
t,
func(ctx context.Context, host string) ([]string, error) {
t.Fatalf("did not expect DNS probe for non-concrete regions, got host %s", host)
return nil, nil
},
func(ctx context.Context, endpoint networkDiagnosticEndpoint) (tlsProbeResult, error) {
t.Fatalf("did not expect TLS probe for non-concrete regions, got endpoint %#v", endpoint)
return tlsProbeResult{}, nil
},
)
script := `#!/bin/sh
set -eu
out=""
while [ "$#" -gt 0 ]; do
if [ "$1" = "-s" ]; then
out="$2"
shift 2
continue
fi
shift
done
mkdir -p "$out/test-policy"
printf '[]' > "$out/test-policy/resources.json"
`
binary := writeExecutableScript(t, script)
executor := &CommandCustodianExecutor{Logger: hclog.NewNullLogger()}
result := executor.Execute(context.Background(), CustodianExecutionRequest{
BinaryPath: binary,
Check: CustodianCheck{
Name: "test-policy",
Resource: "aws.backup-vault",
Provider: "aws",
RawPolicy: map[string]interface{}{"name": "test-policy", "resource": "aws.backup-vault"},
},
Timeout: 5 * time.Second,
OutputDir: filepath.Join(t.TempDir(), "out"),
AWSRegions: []string{"all"},
NetworkDiagnostics: true,
})
if result.Err != nil {
t.Fatalf("expected successful execution, got error: %v", result.Err)
}
})
t.Run("passes debug and verbose args", func(t *testing.T) {
argsFile := filepath.Join(t.TempDir(), "args.txt")
t.Setenv("ARGS_FILE", argsFile)
script := `#!/bin/sh
set -eu
echo "$@" > "$ARGS_FILE"
out=""
while [ "$#" -gt 0 ]; do
if [ "$1" = "-s" ]; then
out="$2"
shift 2
continue
fi
shift
done
mkdir -p "$out/test-policy"
printf '[]' > "$out/test-policy/resources.json"
`
binary := writeExecutableScript(t, script)
executor := &CommandCustodianExecutor{Logger: hclog.NewNullLogger()}
result := executor.Execute(context.Background(), CustodianExecutionRequest{
BinaryPath: binary,
Check: CustodianCheck{
Name: "test-policy",
Resource: "aws.s3",
Provider: "aws",
RawPolicy: map[string]interface{}{"name": "test-policy", "resource": "aws.s3"},
},
Timeout: 5 * time.Second,
OutputDir: filepath.Join(t.TempDir(), "out"),
Debug: true,
Verbose: true,
})
if result.Err != nil {
t.Fatalf("expected successful execution, got error: %v", result.Err)
}
argsContent, err := os.ReadFile(argsFile)
if err != nil {
t.Fatalf("failed to read args capture file: %v", err)
}
argsStr := string(argsContent)
if !strings.Contains(argsStr, "run --debug -v --dryrun -s") {
t.Fatalf("expected debug and verbose args before dry-run args, got: %s", argsStr)
}
})
t.Run("injects AWS API trace environment", func(t *testing.T) {
envFile := filepath.Join(t.TempDir(), "env.txt")
t.Setenv("ENV_FILE", envFile)
script := `#!/bin/sh
set -eu
printf '%s\n%s\n%s\n' "$PYTHONPATH" "$CCF_CUSTODIAN_AWS_API_TRACE_LOG" "$PYTHONUNBUFFERED" > "$ENV_FILE"
out=""
while [ "$#" -gt 0 ]; do
if [ "$1" = "-s" ]; then
out="$2"
shift 2
continue
fi
shift
done
mkdir -p "$out/test-policy"
printf '[]' > "$out/test-policy/resources.json"
`
binary := writeExecutableScript(t, script)
outDir := filepath.Join(t.TempDir(), "out")
executor := &CommandCustodianExecutor{Logger: hclog.NewNullLogger()}
result := executor.Execute(context.Background(), CustodianExecutionRequest{
BinaryPath: binary,
Check: CustodianCheck{
Name: "test-policy",
Resource: "aws.backup-vault",
Provider: "aws",
RawPolicy: map[string]interface{}{"name": "test-policy", "resource": "aws.backup-vault"},
},
Timeout: 5 * time.Second,
OutputDir: outDir,
AWSAPITrace: true,
})
if result.Err != nil {
t.Fatalf("expected successful execution, got error: %v", result.Err)
}
content, err := os.ReadFile(envFile)
if err != nil {
t.Fatalf("failed to read env capture file: %v", err)
}
lines := strings.Split(strings.TrimSpace(string(content)), "\n")
if len(lines) != 3 {
t.Fatalf("expected three env lines, got %q", string(content))
}
traceDir := strings.Split(lines[0], string(os.PathListSeparator))[0]
if _, err := os.Stat(filepath.Join(traceDir, "sitecustomize.py")); err != nil {
t.Fatalf("expected sitecustomize.py in trace dir: %v", err)
}
if lines[1] != filepath.Join(outDir, "custodian-aws-api-trace.jsonl") {
t.Fatalf("unexpected trace log path: %s", lines[1])
}
traceLogInfo, err := os.Stat(lines[1])
if err != nil {
t.Fatalf("expected trace log file to be created: %v", err)
}
if traceLogInfo.Mode().Perm() != 0o600 {
t.Fatalf("expected trace log permissions 0600, got %v", traceLogInfo.Mode().Perm())
}
if lines[2] != "1" {
t.Fatalf("expected PYTHONUNBUFFERED=1, got %s", lines[2])
}
})
t.Run("timeout cancellation", func(t *testing.T) {
script := `#!/bin/sh
sleep 2
`
binary := writeExecutableScript(t, script)
executor := &CommandCustodianExecutor{Logger: hclog.NewNullLogger()}
result := executor.Execute(context.Background(), CustodianExecutionRequest{
BinaryPath: binary,
Check: CustodianCheck{
Name: "slow-check",
Resource: "aws.ec2",
Provider: "aws",
RawPolicy: map[string]interface{}{"name": "slow-check", "resource": "aws.ec2"},
},
Timeout: 100 * time.Millisecond,
OutputDir: filepath.Join(t.TempDir(), "out"),
})
if result.Err == nil {
t.Fatalf("expected timeout error")
}
if !strings.Contains(result.Error, "deadline exceeded") {
t.Fatalf("expected deadline exceeded in error, got: %s", result.Error)
}
deadlineMentions := 0
for _, msg := range result.Errors {
if strings.Contains(msg, "deadline exceeded") {
deadlineMentions++
}
}
if deadlineMentions > 1 {
t.Fatalf("expected at most one deadline exceeded entry, got: %v", result.Errors)
}
})
t.Run("includes custodian log artifacts on failure", func(t *testing.T) {
script := `#!/bin/sh
set -eu
out=""
while [ "$#" -gt 0 ]; do
if [ "$1" = "-s" ]; then
out="$2"
shift 2
continue
fi
shift
done
mkdir -p "$out/test-policy/us-east-1/test-policy"
printf 'custodian artifact detail\nlast api call before hang\n' > "$out/test-policy/us-east-1/test-policy/custodian-run.log"
exit 3
`
binary := writeExecutableScript(t, script)
executor := &CommandCustodianExecutor{Logger: hclog.NewNullLogger()}
result := executor.Execute(context.Background(), CustodianExecutionRequest{
BinaryPath: binary,
Check: CustodianCheck{
Name: "test-policy",
Resource: "aws.backup-vault",
Provider: "aws",
RawPolicy: map[string]interface{}{"name": "test-policy", "resource": "aws.backup-vault"},
},
Timeout: 5 * time.Second,
OutputDir: filepath.Join(t.TempDir(), "out"),
})
if result.Err == nil {
t.Fatalf("expected execution failure")
}
if len(result.LogPaths) != 1 || !strings.HasSuffix(result.LogPaths[0], "custodian-run.log") {
t.Fatalf("expected custodian log path to be captured, got %#v", result.LogPaths)
}
if !strings.Contains(result.Error, "custodian log tail from") {
t.Fatalf("expected custodian log tail header in error, got: %s", result.Error)
}
if !strings.Contains(result.Error, "last api call before hang") {
t.Fatalf("expected custodian log content in error, got: %s", result.Error)
}
})
t.Run("limits custodian log artifact tails", func(t *testing.T) {
root := t.TempDir()
logPaths := make([]string, 0, custodianLogTailMaxSections+2)
for i := 0; i < custodianLogTailMaxSections+2; i++ {
logPath := filepath.Join(root, fmt.Sprintf("log-%02d", i), "custodian-run.log")
if err := os.MkdirAll(filepath.Dir(logPath), 0o755); err != nil {
t.Fatalf("failed to create log dir: %v", err)
}
if err := os.WriteFile(logPath, []byte(fmt.Sprintf("log detail %02d", i)), 0o600); err != nil {
t.Fatalf("failed to write log: %v", err)
}
logPaths = append(logPaths, logPath)
}
_, logTail, err := readCustodianLogArtifactsForPaths(logPaths, custodianOutputTailBytes)
if err != nil {
t.Fatalf("unexpected log tail error: %v", err)
}
if got := strings.Count(logTail, "custodian log tail from"); got != custodianLogTailMaxSections {
t.Fatalf("expected %d log sections, got %d in:\n%s", custodianLogTailMaxSections, got, logTail)
}
if !strings.Contains(logTail, "2 additional custodian-run.log file(s) omitted") {
t.Fatalf("expected truncation marker, got:\n%s", logTail)
}
})
t.Run("limits custodian log artifact tails by non empty section count", func(t *testing.T) {
root := t.TempDir()
logPaths := make([]string, 0, custodianLogTailMaxSections+3)
for i := 0; i < custodianLogTailMaxSections+3; i++ {
logPath := filepath.Join(root, fmt.Sprintf("log-%02d", i), "custodian-run.log")
if err := os.MkdirAll(filepath.Dir(logPath), 0o755); err != nil {
t.Fatalf("failed to create log dir: %v", err)
}
content := []byte(fmt.Sprintf("log detail %02d", i))
if i < 2 {
content = []byte(" \n\t")
}
if err := os.WriteFile(logPath, content, 0o600); err != nil {
t.Fatalf("failed to write log: %v", err)
}
logPaths = append(logPaths, logPath)
}
_, logTail, err := readCustodianLogArtifactsForPaths(logPaths, custodianOutputTailBytes)
if err != nil {
t.Fatalf("unexpected log tail error: %v", err)
}
if got := strings.Count(logTail, "custodian log tail from"); got != custodianLogTailMaxSections {
t.Fatalf("expected %d non-empty log sections, got %d in:\n%s", custodianLogTailMaxSections, got, logTail)
}
if strings.Contains(logTail, "log detail 00") || strings.Contains(logTail, "log detail 01") {
t.Fatalf("expected empty logs not to be included, got:\n%s", logTail)
}
if !strings.Contains(logTail, "log detail 06") {
t.Fatalf("expected empty logs not to consume section budget, got:\n%s", logTail)
}
if !strings.Contains(logTail, "1 additional custodian-run.log file(s) omitted") {
t.Fatalf("expected truncation marker based on remaining paths, got:\n%s", logTail)
}
})
t.Run("does not read custodian log artifacts on success by default", func(t *testing.T) {
script := `#!/bin/sh
set -eu
out=""
while [ "$#" -gt 0 ]; do
if [ "$1" = "-s" ]; then
out="$2"
shift 2
continue
fi
shift
done
mkdir -p "$out/test-policy/us-east-1/test-policy"
printf 'success log detail\n' > "$out/test-policy/us-east-1/test-policy/custodian-run.log"
printf '[]' > "$out/test-policy/resources.json"
`
binary := writeExecutableScript(t, script)
executor := &CommandCustodianExecutor{Logger: hclog.NewNullLogger()}
result := executor.Execute(context.Background(), CustodianExecutionRequest{
BinaryPath: binary,
Check: CustodianCheck{
Name: "test-policy",
Resource: "aws.backup-vault",
Provider: "aws",
RawPolicy: map[string]interface{}{"name": "test-policy", "resource": "aws.backup-vault"},
},
Timeout: 5 * time.Second,
OutputDir: filepath.Join(t.TempDir(), "out"),
})
if result.Err != nil {
t.Fatalf("expected successful execution, got error: %v", result.Err)
}
if len(result.LogPaths) != 0 {
t.Fatalf("expected successful execution not to walk log artifacts by default, got %#v", result.LogPaths)
}
})
t.Run("finds custodian log artifacts in stable order", func(t *testing.T) {
root := t.TempDir()
first := filepath.Join(root, "a", "custodian-run.log")
second := filepath.Join(root, "z", "custodian-run.log")
if err := os.MkdirAll(filepath.Dir(second), 0o755); err != nil {
t.Fatalf("failed to create second log dir: %v", err)
}