Repository navigation
Expand file tree
/
Copy pathgitops_test.go
More file actions
3036 lines (2909 loc) · 116 KB
/
Copy pathgitops_test.go
File metadata and controls
3036 lines (2909 loc) · 116 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"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"gopkg.in/yaml.v3"
)
var fixtureAWSManagedServices = map[string]string{
"cache": "elasticache",
"object-storage": "s3",
"store": "rds-postgresql",
"vault": "secrets-manager",
}
func TestGenerateBundleGoldenShapes(t *testing.T) {
t.Parallel()
tests := []struct {
name string
workspace string
module string
services []string
golden string
}{
{
name: "acme",
workspace: "acme-control",
module: "identity",
services: []string{"accounts", "auth-gateway", "cache", "frontend", "object-storage", "store", "vault"},
golden: "testdata/acme-bundle.golden.json",
},
{
name: "example",
workspace: "example-control",
module: "users",
services: []string{"store", "vault", "accounts", "cache", "frontend", "forge-edge", "object-storage"},
golden: "testdata/example-bundle.golden.json",
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
root, moduleDir := writeModuleFixture(t, test.workspace, test.module, test.services)
workspace, err := loadWorkspaceManifest(root)
if err != nil {
t.Fatal(err)
}
if err := generateDeploymentBundle(moduleDir, workspace); err != nil {
t.Fatal(err)
}
got, err := os.ReadFile(filepath.Join(moduleDir, filepath.FromSlash(bundleRelativeDir), "bundle.json"))
if err != nil {
t.Fatal(err)
}
if os.Getenv("UPDATE_GOLDEN") != "" {
if err := os.WriteFile(test.golden, got, 0o644); err != nil {
t.Fatal(err)
}
}
want, err := os.ReadFile(test.golden)
if err != nil {
t.Fatal(err)
}
if string(got) != string(want) {
t.Fatalf("bundle golden mismatch\nwant:\n%s\ngot:\n%s", want, got)
}
// Both declared environments must render module-owned overlays.
for _, environment := range []string{"local", "aws"} {
overlayObjects(t, moduleDir, environment)
}
})
}
}
func TestIdentityNeutralBaseDefersNamespaceAndIstioHost(t *testing.T) {
t.Parallel()
root, moduleDir := writeModuleFixture(t, "acme-control", "identity", []string{"accounts", "frontend"})
workspace, err := loadWorkspaceManifest(root)
if err != nil {
t.Fatal(err)
}
if err := generateDeploymentBundle(moduleDir, workspace); err != nil {
t.Fatal(err)
}
overlayRoot := filepath.Join(moduleDir, filepath.FromSlash(bundleRelativeDir), "overlays", "local")
baseRoot := filepath.Join(overlayRoot, "base")
// The base must carry neither identity-bearing object: no Namespace object
// (its name is the tenant identity) and no host-bearing Gateway/VirtualService
// live anywhere beneath it.
if err := filepath.WalkDir(baseRoot, func(file string, entry os.DirEntry, err error) error {
if err != nil || entry.IsDir() || entry.Name() == "kustomization.yaml" {
return err
}
objects, err := decodeYAMLDocuments(file)
if err != nil {
return err
}
for _, object := range objects {
switch object["kind"] {
case "Namespace", "Gateway", "VirtualService":
t.Errorf("base file %s bakes identity-bearing object %v", file, object["kind"])
}
}
return nil
}); err != nil {
t.Fatal(err)
}
// The overlay owns the Namespace object, named for the environment rather than
// a placeholder. This raw name matters: the CLI validates every raw Namespace
// against the AppProject destinations before rendering, so a placeholder name
// here fails promotion.
namespaceObjects, err := decodeYAMLDocuments(filepath.Join(overlayRoot, "namespace.yaml"))
if err != nil {
t.Fatal(err)
}
metadata := namespaceObjects[0]["metadata"].(map[string]any)
if metadata["name"] != "identity-local" {
t.Errorf("overlay Namespace name = %v, want identity-local", metadata["name"])
}
labels := metadata["labels"].(map[string]any)
if labels["kubernetes.io/metadata.name"] != "identity-local" {
t.Errorf("overlay Namespace kubernetes.io/metadata.name = %v, want identity-local", labels["kubernetes.io/metadata.name"])
}
// The overlay also owns the host-bearing Gateway/VirtualService and names the
// namespace for every resource the base contributes.
data, err := os.ReadFile(filepath.Join(overlayRoot, "kustomization.yaml"))
if err != nil {
t.Fatal(err)
}
var overlay kustomization
if err := yaml.Unmarshal(data, &overlay); err != nil {
t.Fatal(err)
}
if overlay.Namespace != "identity-local" {
t.Errorf("overlay namespace transformer = %q, want identity-local", overlay.Namespace)
}
for _, want := range []string{"base", "namespace.yaml", "ingress.yaml"} {
if !slices.Contains(overlay.Resources, want) {
t.Errorf("overlay resources = %v, missing %q", overlay.Resources, want)
}
}
ingressObjects, err := decodeYAMLDocuments(filepath.Join(overlayRoot, "ingress.yaml"))
if err != nil {
t.Fatal(err)
}
var sawGateway bool
var virtualServiceHosts []any
for _, object := range ingressObjects {
switch object["kind"] {
case "Gateway":
sawGateway = true
case "VirtualService":
virtualServiceHosts = object["spec"].(map[string]any)["hosts"].([]any)
}
}
if !sawGateway {
t.Error("overlay ingress is missing its Gateway")
}
if !slices.Equal(virtualServiceHosts, []any{"identity.localhost"}) {
t.Errorf("overlay VirtualService hosts = %v, want [identity.localhost]", virtualServiceHosts)
}
// The effective render still resolves to the environment identity: exactly
// one Namespace named for the environment, and the environment host on the
// VirtualService.
namespaces := 0
for _, object := range overlayObjects(t, moduleDir, "local") {
switch object["kind"] {
case "Namespace":
namespaces++
if name := object["metadata"].(map[string]any)["name"]; name != "identity-local" {
t.Errorf("rendered Namespace name = %v, want identity-local", name)
}
case "VirtualService":
if hosts := object["spec"].(map[string]any)["hosts"].([]any); !slices.Equal(hosts, []any{"identity.localhost"}) {
t.Errorf("rendered VirtualService hosts = %v, want [identity.localhost]", hosts)
}
}
}
if namespaces != 1 {
t.Errorf("rendered Namespace count = %d, want 1", namespaces)
}
}
func TestGeneratedBundleCarriesNoGitOrArgoTransport(t *testing.T) {
t.Parallel()
root, moduleDir := writeModuleFixture(t, "neutral-control", "identity", []string{"accounts", "store"})
workspace, err := loadWorkspaceManifest(root)
if err != nil {
t.Fatal(err)
}
if err := generateDeploymentBundle(moduleDir, workspace); err != nil {
t.Fatal(err)
}
generated := filepath.Join(moduleDir, filepath.FromSlash(bundleRelativeDir))
forbidden := []string{"repoURL", "targetRevision", "AppProject", "argoproj.io", "fluxcd.io", "sourceRepos"}
err = filepath.WalkDir(generated, func(file string, entry os.DirEntry, err error) error {
if err != nil || entry.IsDir() {
return err
}
data, err := os.ReadFile(file)
if err != nil {
return err
}
for _, token := range forbidden {
if strings.Contains(string(data), token) {
t.Errorf("generated file %s contains repository/Argo transport token %q", file, token)
}
}
return nil
})
if err != nil {
t.Fatal(err)
}
var bundle moduleBundle
data, err := os.ReadFile(filepath.Join(generated, "bundle.json"))
if err != nil {
t.Fatal(err)
}
if err := json.Unmarshal(data, &bundle); err != nil {
t.Fatal(err)
}
if bundle.SchemaVersion != moduleBundleSchema || bundle.Module != "identity" {
t.Fatalf("bundle identity = %q/%q", bundle.SchemaVersion, bundle.Module)
}
if len(bundle.Environments) != 2 {
t.Fatalf("bundle environments = %d, want local and aws", len(bundle.Environments))
}
aws := bundle.Environments[1]
if aws.Name != "aws" || aws.Cluster != "eks" || aws.ResourcePath != "overlays/aws" {
t.Fatalf("aws bundle environment = %#v", aws)
}
if len(aws.ManagedServiceHandoffs) != 1 || aws.ManagedServiceHandoffs[0].Service != "store" {
t.Fatalf("aws managed handoffs = %#v", aws.ManagedServiceHandoffs)
}
if slices.Contains(aws.Services, "store") {
t.Fatalf("managed store must not appear as an in-cluster workload: %v", aws.Services)
}
if bytes.Contains(data, []byte(`"awsKind"`)) {
t.Fatalf("bundle.json still emits legacy \"awsKind\" key: %s", data)
}
if !bytes.Contains(data, []byte(`"kind"`)) {
t.Fatalf("bundle.json missing \"kind\" handoff key: %s", data)
}
}
func TestManagedServiceHandoffReadsLegacyAWSKind(t *testing.T) {
t.Parallel()
var current managedServiceHandoff
if err := json.Unmarshal([]byte(`{"service":"store","kind":"rds-postgresql"}`), ¤t); err != nil {
t.Fatal(err)
}
if current.Kind != "rds-postgresql" {
t.Fatalf("kind = %q, want rds-postgresql", current.Kind)
}
var legacy managedServiceHandoff
if err := json.Unmarshal([]byte(`{"service":"store","awsKind":"azure-postgres-flexible"}`), &legacy); err != nil {
t.Fatal(err)
}
if legacy.Kind != "azure-postgres-flexible" {
t.Fatalf("legacy awsKind not read into kind: %q", legacy.Kind)
}
}
func TestGenerateBundleIgnoresLegacyGitopsPublicationBlock(t *testing.T) {
t.Parallel()
root, moduleDir := writeModuleFixture(t, "legacy-control", "identity", []string{"accounts"})
// A consumer workspace migrated from the previous release still carries the
// CLI GitOps publication block. The plugin must parse the workspace and
// ignore that block entirely rather than depend on any repository field.
appendWorkspace(t, root, `
gitops:
repo-url: git@github.com:acme/platform-config.git
branch: main
revision: 0123456789abcdef0123456789abcdef01234567
inventory: clusters/codefly/deployments/modules/identity/.codefly-render.json
environment: local
`)
workspace, err := loadWorkspaceManifest(root)
if err != nil {
t.Fatal(err)
}
if err := generateDeploymentBundle(moduleDir, workspace); err != nil {
t.Fatal(err)
}
}
func TestGenerateBundleRendersEnvironmentWithoutPublicIngress(t *testing.T) {
t.Parallel()
root, moduleDir := writeModuleFixture(t, "mixed-control", "identity", []string{"accounts", "store"})
workspace, err := loadWorkspaceManifest(root)
if err != nil {
t.Fatal(err)
}
// aws is a declared deploy target that has not configured public ingress.
// A single incompletely-exposed environment must not fail the whole bundle
// or the sibling environments that are fully configured.
workspace.Environments[1].Ingress = nil
if err := generateDeploymentBundle(moduleDir, workspace); err != nil {
t.Fatalf("generateDeploymentBundle() with an ingress-less environment: %v", err)
}
overlays := filepath.Join(moduleDir, filepath.FromSlash(bundleRelativeDir), "overlays")
if _, err := os.Stat(filepath.Join(overlays, "local", "ingress.yaml")); err != nil {
t.Fatalf("fully configured local overlay is missing its gateway: %v", err)
}
if _, err := os.Stat(filepath.Join(overlays, "aws", "ingress.yaml")); !errors.Is(err, os.ErrNotExist) {
t.Fatalf("ingress-less aws overlay emitted a public gateway: %v", err)
}
if _, err := os.Stat(filepath.Join(overlays, "aws", "namespace.yaml")); err != nil {
t.Errorf("ingress-less aws overlay is missing its Namespace object: %v", err)
}
awsBase := filepath.Join(overlays, "aws", "base")
for _, base := range []string{"network-policy.yaml", "istio-mtls.yaml"} {
if _, err := os.Stat(filepath.Join(awsBase, base)); err != nil {
t.Errorf("ingress-less aws overlay is missing module-owned %s: %v", base, err)
}
}
for _, object := range overlayObjects(t, moduleDir, "aws") {
if kind := object["kind"]; kind == "Gateway" || kind == "VirtualService" {
t.Fatalf("ingress-less aws overlay still emits %v", kind)
}
}
var bundle moduleBundle
data, err := os.ReadFile(filepath.Join(moduleDir, filepath.FromSlash(bundleRelativeDir), "bundle.json"))
if err != nil {
t.Fatal(err)
}
if err := json.Unmarshal(data, &bundle); err != nil {
t.Fatal(err)
}
if len(bundle.Environments) != 2 || bundle.Environments[1].Name != "aws" || len(bundle.Environments[1].Ingress) != 0 {
t.Fatalf("bundle did not record the ingress-less aws environment: %#v", bundle.Environments)
}
}
func TestGenerateBundleRejectsHostileContracts(t *testing.T) {
t.Parallel()
tests := []struct {
name string
mutate func(t *testing.T, moduleDir string, workspace *workspaceManifest)
want string
}{
{
name: "no declared environments",
mutate: func(_ *testing.T, _ string, workspace *workspaceManifest) {
workspace.Environments = nil
},
want: "declares no deployment environments",
},
{
name: "missing namespace",
mutate: func(_ *testing.T, _ string, workspace *workspaceManifest) {
workspace.Environments[0].Namespace = ""
},
want: "Kubernetes DNS label",
},
{
name: "duplicate environment",
mutate: func(_ *testing.T, _ string, workspace *workspaceManifest) {
workspace.Environments[1].Name = "local"
},
want: "more than once",
},
{
name: "wildcard ingress host",
mutate: func(_ *testing.T, _ string, workspace *workspaceManifest) {
workspace.Environments[0].Ingress = []environmentIngressRoute{{
Name: "product",
Service: "accounts",
Endpoint: "http",
Hosts: []string{"*"},
}}
},
want: "is not an exact DNS name",
},
{
name: "ingress targets private endpoint",
mutate: func(_ *testing.T, _ string, workspace *workspaceManifest) {
workspace.Environments[0].Ingress = []environmentIngressRoute{{
Name: "product",
Service: "frontend",
Endpoint: "http",
Hosts: []string{"identity.localhost"},
}}
},
want: "is not a public module interface",
},
{
name: "unsupported cluster kind",
mutate: func(_ *testing.T, _ string, workspace *workspaceManifest) {
workspace.Environments[0].Cluster.Kind = "openshift"
},
want: "is not supported",
},
{
name: "managed service on in-cluster environment",
mutate: func(_ *testing.T, _ string, workspace *workspaceManifest) {
workspace.Environments[0].ManagedServices = map[string]managedServiceConfig{
"store": {Kind: "rds-postgresql", ExternalName: "db.internal.example.com"},
}
},
want: "managed services for an in-cluster environment",
},
{
name: "unexpected managed service",
mutate: func(_ *testing.T, _ string, workspace *workspaceManifest) {
workspace.Environments[1].ManagedServices["phantom"] = managedServiceConfig{
Kind: "rds-postgresql",
ExternalName: "db.internal.example.com",
EgressCIDRs: []string{"10.42.0.0/24"},
}
},
want: "unexpected managed service",
},
{
name: "unsupported managed kind",
mutate: func(_ *testing.T, _ string, workspace *workspaceManifest) {
config := workspace.Environments[1].ManagedServices["store"]
config.Kind = "dynamodb"
workspace.Environments[1].ManagedServices["store"] = config
},
want: "is not supported",
},
{
name: "invalid managed egress cidr",
mutate: func(_ *testing.T, _ string, workspace *workspaceManifest) {
config := workspace.Environments[1].ManagedServices["store"]
config.EgressCIDRs = []string{"not-a-cidr"}
workspace.Environments[1].ManagedServices["store"] = config
},
want: "egress CIDR",
},
{
name: "incomplete managed secret reference",
mutate: func(_ *testing.T, _ string, workspace *workspaceManifest) {
config := workspace.Environments[1].ManagedServices["store"]
config.SecretReferences = []managedSecretReference{{
Name: "store-runtime",
RemoteKey: "",
SecretStore: secretStoreRef{Name: "aws", Kind: "ClusterSecretStore"},
}}
workspace.Environments[1].ManagedServices["store"] = config
},
want: "secret reference",
},
{
name: "cloud sql without an explicit auth mode",
mutate: func(_ *testing.T, _ string, workspace *workspaceManifest) {
config := workspace.Environments[1].ManagedServices["store"]
config.Kind = "cloud-sql-postgres"
config.InstanceConnectionName = "identity-prod:us-central1:store"
workspace.Environments[1].ManagedServices["store"] = config
},
want: "requires an explicit auth-mode",
},
{
name: "cloud sql without an instance connection name",
mutate: func(_ *testing.T, _ string, workspace *workspaceManifest) {
config := workspace.Environments[1].ManagedServices["store"]
config.Kind = "cloud-sql-postgres"
config.AuthMode = "external-identity"
workspace.Environments[1].ManagedServices["store"] = config
},
want: "is not a project:region:instance name",
},
{
name: "malformed instance connection name",
mutate: func(_ *testing.T, _ string, workspace *workspaceManifest) {
config := workspace.Environments[1].ManagedServices["store"]
config.Kind = "cloud-sql-postgres"
config.AuthMode = "external-identity"
config.InstanceConnectionName = "identity-prod:us-central1"
workspace.Environments[1].ManagedServices["store"] = config
},
want: "is not a project:region:instance name",
},
{
name: "instance connection name on a non cloud sql kind",
mutate: func(_ *testing.T, _ string, workspace *workspaceManifest) {
config := workspace.Environments[1].ManagedServices["store"]
config.InstanceConnectionName = "identity-prod:us-central1:store"
workspace.Environments[1].ManagedServices["store"] = config
},
want: "does not take an instance-connection-name",
},
{
name: "unsupported managed auth mode",
mutate: func(_ *testing.T, _ string, workspace *workspaceManifest) {
config := workspace.Environments[1].ManagedServices["store"]
config.AuthMode = "kerberos"
workspace.Environments[1].ManagedServices["store"] = config
},
want: "auth-mode",
},
{
name: "external identity with a connection secret",
mutate: func(_ *testing.T, _ string, workspace *workspaceManifest) {
config := workspace.Environments[1].ManagedServices["store"]
config.AuthMode = "external-identity"
config.SecretReferences = []managedSecretReference{{
Name: "store-runtime",
RemoteKey: "products/identity/store",
SecretStore: secretStoreRef{Name: "gcp", Kind: "ClusterSecretStore"},
}}
workspace.Environments[1].ManagedServices["store"] = config
},
want: "declares secret references",
},
{
name: "missing service path",
mutate: func(t *testing.T, moduleDir string, _ *workspaceManifest) {
t.Helper()
if err := os.RemoveAll(filepath.Join(moduleDir, "services", "frontend")); err != nil {
t.Fatal(err)
}
},
want: "declared service \"frontend\" path",
},
{
name: "extra service path",
mutate: func(t *testing.T, moduleDir string, _ *workspaceManifest) {
t.Helper()
if err := os.MkdirAll(filepath.Join(moduleDir, "services", "phantom"), 0o755); err != nil {
t.Fatal(err)
}
},
want: "has no module service declaration",
},
{
name: "duplicate Kubernetes workload identity",
mutate: func(t *testing.T, moduleDir string, _ *workspaceManifest) {
t.Helper()
replaceInServiceManifest(t, moduleDir, "accounts", " deployment:\n", " deployment:\n kubernetes:\n service-name: shared\n app-label: accounts\n")
replaceInServiceManifest(t, moduleDir, "frontend", " deployment:\n", " deployment:\n kubernetes:\n service-name: shared\n app-label: frontend\n")
},
want: "share Kubernetes service name",
},
{
name: "symlinked service path",
mutate: func(t *testing.T, moduleDir string, _ *workspaceManifest) {
t.Helper()
if err := os.RemoveAll(filepath.Join(moduleDir, "services", "accounts")); err != nil {
t.Fatal(err)
}
if err := os.Symlink(t.TempDir(), filepath.Join(moduleDir, "services", "accounts")); err != nil {
t.Fatal(err)
}
},
want: "is not a directory",
},
{
name: "deploy job with a missing catalog artifact",
mutate: func(t *testing.T, moduleDir string, _ *workspaceManifest) {
t.Helper()
appendDeployJob(t, moduleDir, "store", "http")
},
want: "catalog artifact",
},
{
name: "deploy job writing to a non-dependency",
mutate: func(t *testing.T, moduleDir string, _ *workspaceManifest) {
t.Helper()
writeCatalogArtifact(t, moduleDir)
appendDeployJob(t, moduleDir, "frontend", "http")
},
want: "does not declare that dependency",
},
{
name: "deploy job for an undeclared service",
mutate: func(t *testing.T, moduleDir string, _ *workspaceManifest) {
t.Helper()
writeCatalogArtifact(t, moduleDir)
appendDeployJob(t, moduleDir, "store", "http")
replaceInDeployJobs(t, moduleDir, " service: accounts\n", " service: phantom\n")
},
want: "references undeclared service",
},
{
name: "deploy job to a migration-bearing target without ordering",
mutate: func(t *testing.T, moduleDir string, _ *workspaceManifest) {
t.Helper()
writeCatalogArtifact(t, moduleDir)
// store declares bootstrap_job_endpoints (a migration Job), so a
// deploy Job that writes to it but omits it from after would let the
// import race the migration and write against a missing schema.
writeDeployJobs(t, moduleDir,
"deploy_jobs:\n"+
" - name: role-catalog-import\n"+
" service: accounts\n"+
" command: role-catalog-import\n"+
" catalog: deployment/generated/contributed-roles.json\n"+
" force: true\n"+
" writes:\n"+
" service: store\n"+
" endpoint: http\n")
},
want: "must run after it",
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
root, moduleDir := writeModuleFixture(t, "hostile-control", "identity", []string{"accounts", "frontend", "store"})
workspace, err := loadWorkspaceManifest(root)
if err != nil {
t.Fatal(err)
}
test.mutate(t, moduleDir, workspace)
err = generateDeploymentBundle(moduleDir, workspace)
if err == nil || !strings.Contains(err.Error(), test.want) {
t.Fatalf("generateDeploymentBundle() error = %v, want substring %q", err, test.want)
}
})
}
}
func TestGeneratedPoliciesAndGatewayMatchTopology(t *testing.T) {
t.Parallel()
root, moduleDir := writeModuleFixture(
t,
"policy-control",
"identity",
[]string{"accounts", "auth-gateway", "store"},
)
workspace, err := loadWorkspaceManifest(root)
if err != nil {
t.Fatal(err)
}
if err := generateDeploymentBundle(moduleDir, workspace); err != nil {
t.Fatal(err)
}
generated := filepath.Join(moduleDir, filepath.FromSlash(bundleRelativeDir), "overlays")
namespaceObjects, err := decodeYAMLDocuments(filepath.Join(generated, "local", "namespace.yaml"))
if err != nil {
t.Fatal(err)
}
namespaceMetadata := namespaceObjects[0]["metadata"].(map[string]any)
namespaceLabels := namespaceMetadata["labels"].(map[string]any)
if namespaceLabels["istio.io/dataplane-mode"] != "ambient" {
t.Fatalf("local namespace dataplane mode = %v, want ambient", namespaceLabels["istio.io/dataplane-mode"])
}
if _, sidecarInjection := namespaceLabels["istio-injection"]; sidecarInjection {
t.Fatal("local namespace enables sidecar injection alongside the ambient mesh")
}
// This fixture ships no authorization catalog, so there is no L7 policy and
// the namespace waypoint must not be provisioned.
if _, waypointed := namespaceLabels["istio.io/use-waypoint"]; waypointed {
t.Error("namespace opts into a waypoint without any L7 policy to enforce")
}
localNetwork, err := os.ReadFile(filepath.Join(generated, "local", "base", "network-policy.yaml"))
if err != nil {
t.Fatal(err)
}
for _, policy := range []string{
"allow-ambient-hbone-transport",
"allow-istio-ingress-to-auth-gateway",
"allow-accounts-to-store",
"allow-store-from-accounts",
"allow-store-from-bootstrap",
"allow-store-bootstrap-to-store",
"allow-auth-gateway-public-egress",
} {
if !strings.Contains(string(localNetwork), "name: "+policy) {
t.Errorf("local network policy is missing %q", policy)
}
}
if count := strings.Count(string(localNetwork), "port: 15008"); count != 2 {
t.Errorf("local network policy has %d ambient HBONE transport exceptions, want 2", count)
}
if count := strings.Count(string(localNetwork), "codefly.dev/bootstrap-service: store"); count != 2 {
t.Errorf("local network policy has %d bootstrap service selectors, want 2", count)
}
localIstio, err := os.ReadFile(filepath.Join(generated, "local", "base", "istio-mtls.yaml"))
if err != nil {
t.Fatal(err)
}
for _, expected := range []string{
"name: allow-store-from-internal-topology",
"cluster.local/ns/identity-local/sa/default",
`- "8080"`,
} {
if !strings.Contains(string(localIstio), expected) {
t.Errorf("local Istio policy is missing %q", expected)
}
}
awsIstio, err := os.ReadFile(filepath.Join(generated, "aws", "base", "istio-mtls.yaml"))
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(awsIstio), "allow-store-from-internal-topology") {
t.Error("AWS Istio policy grants internal authority to managed Postgres")
}
gatewayObjects, err := decodeYAMLDocuments(filepath.Join(generated, "local", "ingress.yaml"))
if err != nil {
t.Fatal(err)
}
var gatewayName string
var routeGateways []any
for _, object := range gatewayObjects {
metadata := object["metadata"].(map[string]any)
switch object["kind"] {
case "Gateway":
gatewayName, _ = metadata["name"].(string)
case "VirtualService":
spec := object["spec"].(map[string]any)
routeGateways, _ = spec["gateways"].([]any)
}
}
if gatewayName != "identity" || len(routeGateways) != 1 || routeGateways[0] != "identity" {
t.Errorf("generated Gateway %q and route gateways %#v do not match the module-owned route contract", gatewayName, routeGateways)
}
// No AppProject / Application is emitted anywhere in the overlay.
for _, environment := range []string{"local", "aws"} {
objects := overlayObjects(t, moduleDir, environment)
for _, object := range objects {
if kind := object["kind"]; kind == "AppProject" || kind == "Application" {
t.Fatalf("%s overlay still emits Argo %v", environment, kind)
}
}
}
awsNetwork, err := os.ReadFile(filepath.Join(generated, "aws", "base", "network-policy.yaml"))
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(awsNetwork), "cidr: 10.42.0.0/24") ||
!strings.Contains(string(awsNetwork), "name: allow-accounts-to-store") {
t.Errorf("AWS network policy does not bind the managed store CIDR:\n%s", awsNetwork)
}
if strings.Contains(string(awsNetwork), "allow-store-from-bootstrap") ||
strings.Contains(string(awsNetwork), "allow-store-bootstrap-to-store") {
t.Errorf("AWS network policy retains bootstrap authority for managed Postgres:\n%s", awsNetwork)
}
}
func TestDeployJobWiresCatalogImport(t *testing.T) {
t.Parallel()
root, moduleDir := writeModuleFixture(
t,
"catalog-deploy",
"identity",
[]string{"accounts", "auth-gateway", "store"},
)
writeCatalogArtifact(t, moduleDir)
appendDeployJob(t, moduleDir, "store", "http")
workspace, err := loadWorkspaceManifest(root)
if err != nil {
t.Fatal(err)
}
if err := generateDeploymentBundle(moduleDir, workspace); err != nil {
t.Fatal(err)
}
var bundle moduleBundle
data, err := os.ReadFile(filepath.Join(moduleDir, filepath.FromSlash(bundleRelativeDir), "bundle.json"))
if err != nil {
t.Fatal(err)
}
if err := json.Unmarshal(data, &bundle); err != nil {
t.Fatal(err)
}
// Both environments schedule the import: the store is in-cluster locally and
// a managed handoff on AWS, and either way the driver must run the step so a
// contributing module's roles land with no manual invocation.
if len(bundle.Environments) != 2 {
t.Fatalf("bundle environments = %d, want local and aws", len(bundle.Environments))
}
for _, env := range bundle.Environments {
if len(env.DeployJobs) != 1 {
t.Fatalf("%s environment deploy jobs = %d, want 1", env.Name, len(env.DeployJobs))
}
job := env.DeployJobs[0]
if job.Name != "role-catalog-import" || job.Service != "accounts" || job.Command != "role-catalog-import" || !job.Force {
t.Fatalf("%s deploy job = %#v", env.Name, job)
}
if job.Catalog != "deployment/generated/contributed-roles.json" {
t.Errorf("%s deploy job catalog = %q", env.Name, job.Catalog)
}
if job.Writes.Service != "store" || job.Writes.Endpoint != "http" || job.Writes.Port != 8080 {
t.Errorf("%s deploy job write target = %#v", env.Name, job.Writes)
}
if !slices.Equal(job.After, []string{"store"}) {
t.Errorf("%s deploy job ordering = %v", env.Name, job.After)
}
}
overlays := filepath.Join(moduleDir, filepath.FromSlash(bundleRelativeDir), "overlays")
localNetwork := mustReadFile(t, filepath.Join(overlays, "local", "base", "network-policy.yaml"))
for _, name := range []string{
"allow-store-from-role-catalog-import",
"allow-role-catalog-import-to-store",
} {
if !strings.Contains(localNetwork, "name: "+name) {
t.Errorf("local network policy is missing deploy-job reach %q", name)
}
}
if !strings.Contains(localNetwork, "codefly.dev/deploy-job: role-catalog-import") {
t.Error("local network policy does not scope the deploy-job pod identity")
}
// The managed store reaches out of cluster; the module renders no in-cluster
// reach policy for it, exactly as it omits the store's bootstrap authority.
awsNetwork := mustReadFile(t, filepath.Join(overlays, "aws", "base", "network-policy.yaml"))
if strings.Contains(awsNetwork, "role-catalog-import") {
t.Errorf("AWS network policy renders a deploy-job reach for a managed store:\n%s", awsNetwork)
}
}
func TestGeneratedMeshBaselineIsStrictMTLSDefaultDeny(t *testing.T) {
t.Parallel()
root, moduleDir := writeModuleFixture(
t,
"mesh-control",
"identity",
[]string{"accounts", "auth-gateway", "store"},
)
workspace, err := loadWorkspaceManifest(root)
if err != nil {
t.Fatal(err)
}
if err := generateDeploymentBundle(moduleDir, workspace); err != nil {
t.Fatal(err)
}
overlays := filepath.Join(moduleDir, filepath.FromSlash(bundleRelativeDir), "overlays")
// The mesh baseline is the reach gate every mesh-delivered control builds on,
// so it must hold in the in-cluster overlay and the managed-service overlay
// alike. Assert it structurally in both so no environment silently regresses.
for _, environment := range []string{"local", "aws"} {
path := filepath.Join(overlays, environment, "base", "istio-mtls.yaml")
objects, err := decodeYAMLDocuments(path)
if err != nil {
t.Fatalf("%s mesh baseline: %v", environment, err)
}
var peerAuthentications, denies, allows int
for _, object := range objects {
metadata := object["metadata"].(map[string]any)
name, _ := metadata["name"].(string)
switch object["kind"] {
case "PeerAuthentication":
peerAuthentications++
spec := object["spec"].(map[string]any)
if _, scoped := spec["selector"]; scoped {
t.Errorf("%s PeerAuthentication %q is workload-scoped, want mesh-wide", environment, name)
}
mode := spec["mtls"].(map[string]any)["mode"]
if mode != "STRICT" {
t.Errorf("%s PeerAuthentication %q mtls mode = %v, want STRICT", environment, name, mode)
}
case "AuthorizationPolicy":
spec, _ := object["spec"].(map[string]any)
if name == "default-deny" {
denies++
// A namespace-wide ALLOW policy with no rules matches nothing,
// so every workload denies by default until an explicit allow
// grants it. A selector, any rules, or a DENY action would break
// that invariant.
if _, scoped := spec["selector"]; scoped {
t.Errorf("%s default-deny is workload-scoped, want namespace-wide", environment)
}
if _, ruled := spec["rules"]; ruled {
t.Errorf("%s default-deny declares rules, want an empty deny-all policy", environment)
}
if action, ok := spec["action"]; ok && action != "ALLOW" {
t.Errorf("%s default-deny action = %v, want the empty-ALLOW deny-all form", environment, action)
}
} else {
allows++
}
}
}
if peerAuthentications != 1 {
t.Errorf("%s mesh baseline has %d PeerAuthentication objects, want exactly one mesh-wide policy", environment, peerAuthentications)
}
if denies != 1 {
t.Errorf("%s mesh baseline has %d namespace default-deny AuthorizationPolicies, want exactly one", environment, denies)
}
// Default-deny is inert without the explicit per-dependency allows layered
// on top of it; assert at least one so the deny-all never ships alone.
if allows == 0 {
t.Errorf("%s mesh baseline has a default-deny but no explicit allow policies", environment)
}
raw, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(raw), "PERMISSIVE") {
t.Errorf("%s mesh baseline contains a PERMISSIVE mTLS fallback:\n%s", environment, raw)
}
}
// Injection is enforced through the ambient dataplane label, not sidecar
// injection: every pod in the namespace is captured by the mesh, so an
// un-injected pod cannot receive traffic outside mTLS.
namespaceObjects, err := decodeYAMLDocuments(filepath.Join(overlays, "local", "namespace.yaml"))
if err != nil {
t.Fatal(err)
}
namespaceLabels := namespaceObjects[0]["metadata"].(map[string]any)["labels"].(map[string]any)
if namespaceLabels["istio.io/dataplane-mode"] != "ambient" {
t.Errorf("namespace dataplane mode = %v, want ambient so every pod is meshed", namespaceLabels["istio.io/dataplane-mode"])
}
}
func TestGeneratedMeshPolicyGatesInternalAuthorityByCallerServiceAccount(t *testing.T) {
t.Parallel()
root, moduleDir := writeModuleFixture(t, "authority", "identity", []string{"accounts", "auth-gateway"})
// Realistic identity graph: accounts exposes an internal method and runs
// under a distinct SA; auth-gateway is its only declared caller and also
// runs under a distinct SA. This is what lets the policy gate by workload
// identity instead of the shared sa/default.
writeTestFile(t, filepath.Join(moduleDir, "services", "accounts", "service.codefly.yaml"),
serviceManifestFixture("accounts", "http", "http", "private", 8080, "", " service-account:\n name: accounts\n", ""))
writeTestFile(t, filepath.Join(moduleDir, "services", "auth-gateway", "service.codefly.yaml"),
serviceManifestFixture("auth-gateway", "http", "http", "private", 8080,
"service-dependencies:\n - name: accounts\n endpoints:\n - name: http\n",
" service-account:\n name: auth-gateway\n",
" public-egress-ports:\n - 443\n"))
writeTestFile(t, filepath.Join(moduleDir, "services", "accounts", "generated", "authz-methods.json"), `{
"schema_version": "saas.authz.methods.v1",
"methods": [
{"procedure": "/saas.accounts.v1.APIKeyService/ValidateAPIKey", "policy": {"exposure": "EXPOSURE_INTERNAL"}},
{"procedure": "/saas.accounts.v1.AuthService/Authenticate", "policy": {"exposure": "EXPOSURE_PUBLIC"}}
]
}`)
workspace, err := loadWorkspaceManifest(root)
if err != nil {
t.Fatal(err)
}
if err := generateDeploymentBundle(moduleDir, workspace); err != nil {
t.Fatal(err)
}
istioPath := filepath.Join(moduleDir, filepath.FromSlash(bundleRelativeDir), "overlays", "local", "base", "istio-mtls.yaml")
objects, err := decodeYAMLDocuments(istioPath)
if err != nil {
t.Fatal(err)
}
strictMTLS := false
var authority map[string]any
var portAllow map[string]any
var waypoint map[string]any
for _, object := range objects {
metadata := object["metadata"].(map[string]any)
switch object["kind"] {
case "PeerAuthentication":
mtls := object["spec"].(map[string]any)["mtls"].(map[string]any)
if mtls["mode"] == "STRICT" {
strictMTLS = true
}
case "AuthorizationPolicy":
switch metadata["name"] {
case "allow-accounts-internal-authority":
authority = object
case "allow-accounts-from-internal-topology":
portAllow = object
}
case "Gateway":
if object["apiVersion"] == "gateway.networking.k8s.io/v1" {
waypoint = object
}
}
}
if !strictMTLS {
t.Fatal("mesh baseline is missing STRICT PeerAuthentication")
}
if authority == nil {
t.Fatalf("istio bundle is missing the internal-authority allow policy:\n%s", mustReadFile(t, istioPath))
}