//go:build e2ev2 package lifecycle import ( "context" "errors" "os" "path/filepath" "reflect" "slices" "strings" "testing" . "github.com/onsi/gomega" hyperv1 "github.com/openshift/hypershift/api/hypershift/v1beta1" "github.com/openshift/hypershift/test/e2e/v2/util/mirrorregistry" imagev1 "github.com/openshift/api/image/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" crclient "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/fake" ) func TestAWSPlatformConfigClusterSpecs(t *testing.T) { t.Setenv("HYPERSHIFT_ETCD_KMS_KEY_ARN", "") t.Run("When AWS cluster specs are built, it should use public-only networking except for Karpenter and deterministic-lb variants", func(t *testing.T) { t.Setenv("EXTRA_ARGS", "") t.Setenv("HYPERSHIFT_STORAGE_KMS_KEY_ALIAS", "") t.Setenv("HYPERSHIFT_DETERMINISTIC_LB_EIP", "eipalloc-test") t.Setenv("HYPERSHIFT_DETERMINISTIC_LB_SUBNET", "subnet-test") g := NewWithT(t) specs := (&AWSPlatformConfig{}).ClusterSpecs(t.Context(), "release-image", "n1-image") g.Expect(specs).To(HaveLen(12)) for _, spec := range specs { switch spec.Variant { case "public", "public-rollouts", "managed-dns", "upgrade", "autoscaling", "external-oidc", "image-mirroring", "etcd-sharded", "kms-reencryption": g.Expect(spec.CreateArgs).To(ContainElement("--public-only"), "variant %s", spec.Variant) case "karpenter", "karpenter-upgrade": g.Expect(spec.CreateArgs).NotTo(ContainElement("--public-only"), "variant %s", spec.Variant) g.Expect(spec.CreateArgs).To(ContainElement("--endpoint-access=PublicAndPrivate"), "variant %s", spec.Variant) case "deterministic-lb": g.Expect(spec.CreateArgs).NotTo(ContainElement("--public-only"), "variant %s", spec.Variant) g.Expect(spec.CreateArgs).To(ContainElement("--endpoint-access=PublicAndPrivate"), "variant %s", spec.Variant) g.Expect(spec.CreateArgs).To(ContainElement("--kas-service-annotations=service.beta.kubernetes.io/aws-load-balancer-eip-allocations=eipalloc-test"), "variant %s", spec.Variant) g.Expect(spec.CreateArgs).To(ContainElement("--kas-service-annotations=service.beta.kubernetes.io/aws-load-balancer-subnets=subnet-test"), "variant %s", spec.Variant) default: t.Fatalf("unexpected AWS variant %q", spec.Variant) } } }) t.Run("When deterministic LB env vars are absent, it should keep the variant but omit its annotations", func(t *testing.T) { t.Setenv("HYPERSHIFT_DETERMINISTIC_LB_EIP", "") t.Setenv("HYPERSHIFT_DETERMINISTIC_LB_SUBNET", "") g := NewWithT(t) specs := (&AWSPlatformConfig{}).ClusterSpecs(t.Context(), "release-image", "n1-image") var deterministicLB *ClusterSpec for i := range specs { if specs[i].Variant == "deterministic-lb" { deterministicLB = &specs[i] break } } g.Expect(deterministicLB).NotTo(BeNil()) g.Expect(deterministicLB.CreateArgs).To(ContainElement("--endpoint-access=PublicAndPrivate")) for _, arg := range deterministicLB.CreateArgs { g.Expect(arg).NotTo(HavePrefix("--kas-service-annotations=")) } }) t.Run("When AWS cluster specs are built, it should omit Azure dump credentials for every variant", func(t *testing.T) { g := NewWithT(t) specs := (&AWSPlatformConfig{}).ClusterSpecs(t.Context(), "release-image", "n1-image") g.Expect(specs).NotTo(BeEmpty()) for _, spec := range specs { g.Expect(spec.DumpArgs).To(BeEmpty(), "variant %s", spec.Variant) } }) t.Run("When AWS cluster specs are built, kms-reencryption variant is always present", func(t *testing.T) { specs := (&AWSPlatformConfig{}).ClusterSpecs(t.Context(), "release-image", "n1-image") var found bool for _, s := range specs { if s.Variant == "kms-reencryption" { found = true } } if !found { t.Fatal("kms-reencryption variant missing from ClusterSpecs") } }) t.Run("When HYPERSHIFT_ETCD_KMS_KEY_ARN is set, kms-reencryption CreateArgs should include --kms-key-arn", func(t *testing.T) { t.Setenv("HYPERSHIFT_ETCD_KMS_KEY_ARN", "arn:aws:kms:us-east-1:123456789012:key/test-key") specs := (&AWSPlatformConfig{}).ClusterSpecs(t.Context(), "release-image", "n1-image") for _, s := range specs { if s.Variant == "kms-reencryption" { if !slices.Contains(s.CreateArgs, "--kms-key-arn=arn:aws:kms:us-east-1:123456789012:key/test-key") { t.Fatalf("kms-reencryption CreateArgs missing --kms-key-arn: %v", s.CreateArgs) } return } } t.Fatal("kms-reencryption variant not found") }) t.Run("When HYPERSHIFT_ETCD_KMS_KEY_ARN is an alias, kms-reencryption CreateArgs should use the resolved ARN not the alias", func(t *testing.T) { t.Setenv("HYPERSHIFT_ETCD_KMS_KEY_ARN", "alias/hypershift-ci") const resolvedARN = "arn:aws:kms:us-east-1:123456789012:key/resolved-test-key" cfg := &AWSPlatformConfig{ resolveKMSKeyARNFn: func(_ context.Context, _ string) (string, error) { return resolvedARN, nil }, } specs := cfg.ClusterSpecs(t.Context(), "release-image", "n1-image") for _, s := range specs { if s.Variant == "kms-reencryption" { if !slices.Contains(s.CreateArgs, "--kms-key-arn="+resolvedARN) { t.Fatalf("kms-reencryption CreateArgs should use resolved ARN %q, got: %v", resolvedARN, s.CreateArgs) } if slices.Contains(s.CreateArgs, "--kms-key-arn=alias/hypershift-ci") { t.Fatalf("kms-reencryption CreateArgs must not use the alias: %v", s.CreateArgs) } return } } t.Fatal("kms-reencryption variant not found") }) t.Run("When HYPERSHIFT_ETCD_KMS_KEY_ARN is not set, kms-reencryption CreateArgs should not include --kms-key-arn", func(t *testing.T) { t.Setenv("HYPERSHIFT_ETCD_KMS_KEY_ARN", "") specs := (&AWSPlatformConfig{}).ClusterSpecs(t.Context(), "release-image", "n1-image") for _, s := range specs { if s.Variant == "kms-reencryption" { for _, arg := range s.CreateArgs { if strings.HasPrefix(arg, "--kms-key-arn=") { t.Fatalf("kms-reencryption CreateArgs should not contain --kms-key-arn when env var is unset, got: %v", s.CreateArgs) } } return } } t.Fatal("kms-reencryption variant not found") }) t.Run("When AWS cluster specs are built, the variant catalog is identical with and without HYPERSHIFT_ETCD_KMS_KEY_ARN", func(t *testing.T) { // The variant catalog must be static — create-guests and run-tests run in // separate shells, so any env-var-conditional variant would produce different // plans in the two steps and cause a mismatch. wantVariants := []string{ "autoscaling", "deterministic-lb", "etcd-sharded", "external-oidc", "image-mirroring", "karpenter", "karpenter-upgrade", "kms-reencryption", "managed-dns", "public", "public-rollouts", "upgrade", } for _, arn := range []string{"", "arn:aws:kms:us-east-1:123456789012:key/test-key"} { t.Setenv("HYPERSHIFT_ETCD_KMS_KEY_ARN", arn) specs := (&AWSPlatformConfig{}).ClusterSpecs(t.Context(), "release-image", "n1-image") got := make([]string, len(specs)) for i, s := range specs { got[i] = s.Variant } slices.Sort(got) if !reflect.DeepEqual(got, wantVariants) { t.Errorf("HYPERSHIFT_ETCD_KMS_KEY_ARN=%q: variant catalog mismatch:\n got %v\n want %v", arn, got, wantVariants) } } }) } func TestAWSPlatformConfigTestMatrix(t *testing.T) { // clearEnv ensures both gating env vars are unset so inherited values from // the shell don't change results. Each subtest overrides as needed. clearEnv := func(t *testing.T) { t.Helper() t.Setenv("HYPERSHIFT_ETCD_KMS_KEY_ARN", "") t.Setenv("E2E_MERGE_PUBLIC_ROLLOUTS", "") } t.Run("When HYPERSHIFT_ETCD_KMS_KEY_ARN is unset, kms-reencryption is absent from the parallel group", func(t *testing.T) { clearEnv(t) cfg := NewAWSPlatformConfig(AWSPlatformOptions{}, t.TempDir()) matrix := cfg.TestMatrix() for _, g := range matrix.Parallel { if g.Variant == "kms-reencryption" { t.Fatalf("kms-reencryption should be absent from parallel when HYPERSHIFT_ETCD_KMS_KEY_ARN is unset: %+v", matrix.Parallel) } } }) t.Run("When HYPERSHIFT_ETCD_KMS_KEY_ARN is set, kms-reencryption is present in the parallel group", func(t *testing.T) { clearEnv(t) t.Setenv("HYPERSHIFT_ETCD_KMS_KEY_ARN", "arn:aws:kms:us-east-1:123456789012:key/test-key") cfg := NewAWSPlatformConfig(AWSPlatformOptions{}, t.TempDir()) matrix := cfg.TestMatrix() want := TestGroup{Name: "kms-reencryption", Variant: "kms-reencryption", LabelFilter: "etcd-encryption-reencryption"} if !slices.Contains(matrix.Parallel, want) { t.Fatalf("TestMatrix parallel group missing kms-reencryption: %+v", matrix.Parallel) } }) t.Run("When E2E_MERGE_PUBLIC_ROLLOUTS is set, rollout labels appear as step 2 on the public variant", func(t *testing.T) { clearEnv(t) t.Setenv("E2E_MERGE_PUBLIC_ROLLOUTS", "true") cfg := NewAWSPlatformConfig(AWSPlatformOptions{}, t.TempDir()) matrix := cfg.TestMatrix() // public-rollouts sequential group must be absent. for _, sg := range matrix.Sequential { if sg.Name == "public-rollouts" { t.Fatal("public-rollouts sequential group should be absent when E2E_MERGE_PUBLIC_ROLLOUTS is set") } } // The "public" sequential group must have exactly 2 steps, the second // using variant "public" with the rollout label filter. var publicGroup *SequentialGroup for i := range matrix.Sequential { if matrix.Sequential[i].Name == "public" { publicGroup = &matrix.Sequential[i] break } } if publicGroup == nil { t.Fatal("missing public sequential group") } if len(publicGroup.Steps) != 2 { t.Fatalf("expected 2 steps on public group, got %d: %+v", len(publicGroup.Steps), publicGroup.Steps) } rolloutStep := publicGroup.Steps[1] if rolloutStep.Variant != "public" { t.Fatalf("rollout step should use variant %q, got %q", "public", rolloutStep.Variant) } if rolloutStep.Name != "public-nodepool-rollouts" { t.Fatalf("rollout step name = %q, want %q", rolloutStep.Name, "public-nodepool-rollouts") } }) t.Run("When E2E_MERGE_PUBLIC_ROLLOUTS is unset, rollout tests run on a separate public-rollouts variant", func(t *testing.T) { clearEnv(t) cfg := NewAWSPlatformConfig(AWSPlatformOptions{}, t.TempDir()) matrix := cfg.TestMatrix() var found bool for _, sg := range matrix.Sequential { if sg.Name == "public-rollouts" { found = true if len(sg.Steps) != 1 || sg.Steps[0].Variant != "public-rollouts" { t.Fatalf("unexpected public-rollouts group: %+v", sg) } } } if !found { t.Fatal("public-rollouts sequential group missing when E2E_MERGE_PUBLIC_ROLLOUTS is unset") } // The "public" sequential group should have exactly 1 step. for _, sg := range matrix.Sequential { if sg.Name == "public" { if len(sg.Steps) != 1 { t.Fatalf("public group should have 1 step when split, got %d: %+v", len(sg.Steps), sg.Steps) } } } }) // Consistency: the default plan validates against ClusterSpecs for all 4 // env-var combinations. for _, tc := range []struct { name string kmsARN string mergeEnv string }{ {name: "neither set"}, {name: "only HYPERSHIFT_ETCD_KMS_KEY_ARN set", kmsARN: "arn:aws:kms:us-east-1:123456789012:key/test-key"}, {name: "only E2E_MERGE_PUBLIC_ROLLOUTS set", mergeEnv: "true"}, {name: "both set", kmsARN: "arn:aws:kms:us-east-1:123456789012:key/test-key", mergeEnv: "true"}, } { t.Run("When "+tc.name+", the default plan validates against ClusterSpecs", func(t *testing.T) { clearEnv(t) t.Setenv("HYPERSHIFT_ETCD_KMS_KEY_ARN", tc.kmsARN) t.Setenv("E2E_MERGE_PUBLIC_ROLLOUTS", tc.mergeEnv) cfg := NewAWSPlatformConfig(AWSPlatformOptions{}, t.TempDir()) specs := cfg.ClusterSpecs(t.Context(), "current", "previous") plan := cfg.DefaultTestPlan() if err := plan.Validate(specs); err != nil { t.Fatalf("default AWS plan is invalid (%s): %v", tc.name, err) } }) } t.Run("When the default AWS plan is built, it should validate and run the image-mirroring tests as a sequential lane ending with the removal", func(t *testing.T) { clearEnv(t) cfg := NewAWSPlatformConfig(AWSPlatformOptions{}, t.TempDir()) plan := cfg.DefaultTestPlan() if err := plan.Validate(cfg.ClusterSpecs(t.Context(), "current", "previous")); err != nil { t.Fatalf("default AWS plan is invalid: %v", err) } for _, group := range plan.TestMatrix.Parallel { if group.Variant == "image-mirroring" { t.Fatalf("image-mirroring variant must not run in a parallel group: %+v", group) } } var lanes []SequentialGroup for _, group := range plan.TestMatrix.Sequential { if slices.ContainsFunc(group.Steps, func(step TestGroup) bool { return step.Variant == "image-mirroring" }) { lanes = append(lanes, group) } } if len(lanes) != 1 { t.Fatalf("expected exactly one sequential group using the image-mirroring variant, got %+v", lanes) } want := SequentialGroup{ Name: "image-mirroring", Steps: []TestGroup{ {Name: "image-mirroring", Variant: "image-mirroring", LabelFilter: "image-mirroring"}, // The removal mutates the HC without restoring it, so it must be last. {Name: "image-mirroring-removal", Variant: "image-mirroring", LabelFilter: "image-mirroring-removal"}, }, } if !reflect.DeepEqual(lanes[0], want) { t.Fatalf("got %+v, want %+v", lanes[0], want) } }) } // testCLIImage is a digest-pinned openshift/cli image reference used in lookup and setup tests. const testCLIImage = "quay.io/openshift-release-dev/ocp-v4.0-art-dev@sha256:0a9d58f9d8dd969c7bd107319a2498a674fe4e6477185a44558f168d994b39a5" func TestNewAWSPlatformConfig(t *testing.T) { t.Run("When the AWS config is built, it should retain the shared directory and the mirror registry factory", func(t *testing.T) { dir := t.TempDir() cfg := NewAWSPlatformConfig(AWSPlatformOptions{Region: "us-east-1", Zones: "us-east-1a,us-east-1b"}, dir) if cfg.sharedDir != dir || cfg.newMirrorRegistry == nil { t.Fatalf("unexpected config: %+v", cfg) } }) } func TestAWSPlatformConfigImageMirroringClusterSpecs(t *testing.T) { t.Run("When AWS cluster specs are built, it should declare a single-replica image-mirroring variant consuming the fixture artifacts", func(t *testing.T) { t.Setenv("EXTRA_ARGS", "--instance-type=m5.large") dir := t.TempDir() cfg := NewAWSPlatformConfig(AWSPlatformOptions{}, dir) specs := cfg.ClusterSpecs(t.Context(), "current", "previous") var mirroring, autoscaling *ClusterSpec for i := range specs { switch specs[i].Variant { case "image-mirroring": if mirroring != nil { t.Fatal("duplicate image-mirroring variant") } mirroring = &specs[i] case "autoscaling": autoscaling = &specs[i] } } if mirroring == nil || autoscaling == nil { t.Fatalf("missing image-mirroring or autoscaling variant in %+v", specs) } // The autoscaling variant uses only the common args plus EXTRA_ARGS. commonAndExtra := autoscaling.CreateArgs if !slices.Contains(commonAndExtra, "--root-volume-type=gp3") || !slices.Contains(commonAndExtra, "--instance-type=m5.large") { t.Fatalf("unexpected common args: %v", commonAndExtra) } one := 1 want := ClusterSpec{ Variant: "image-mirroring", DestroyArgs: autoscaling.DestroyArgs, InitialNodePoolReplicas: &one, CreateArgs: slices.Concat(commonAndExtra, []string{ "--additional-trust-bundle=" + filepath.Join(dir, "mirror-registry-ca.pem"), "--image-content-sources=" + filepath.Join(dir, "mirror-registry-ics.yaml"), }), } if !reflect.DeepEqual(*mirroring, want) { t.Fatalf("got %+v, want %+v", *mirroring, want) } }) } func TestDeterministicLBTestPlan(t *testing.T) { t.Run("When the dedicated deterministic-lb plan is loaded, it should validate against the AWS variant and select the lifecycle lane", func(t *testing.T) { t.Setenv("HYPERSHIFT_DETERMINISTIC_LB_EIP", "eipalloc-test") t.Setenv("HYPERSHIFT_DETERMINISTIC_LB_SUBNET", "subnet-test") g := NewWithT(t) cfg := NewAWSPlatformConfig(AWSPlatformOptions{}, t.TempDir()) plan, err := ReadTestPlan(filepath.Join("plans", "deterministic-lb.yaml")) g.Expect(err).NotTo(HaveOccurred()) g.Expect(plan.Validate(cfg.ClusterSpecs(t.Context(), "current", "previous"))).To(Succeed()) specs := plan.FilterClusterSpecs(cfg.ClusterSpecs(t.Context(), "current", "previous")) g.Expect(specs).To(HaveLen(1)) g.Expect(specs[0].Variant).To(Equal("deterministic-lb")) g.Expect(specs[0].CreateArgs).To(ContainElement("--kas-service-annotations=service.beta.kubernetes.io/aws-load-balancer-eip-allocations=eipalloc-test")) g.Expect(specs[0].CreateArgs).To(ContainElement("--kas-service-annotations=service.beta.kubernetes.io/aws-load-balancer-subnets=subnet-test")) g.Expect(plan.TestMatrix.Sequential).To(HaveLen(1)) g.Expect(plan.TestMatrix.Sequential[0].Steps).To(HaveLen(1)) g.Expect(plan.TestMatrix.Sequential[0].Steps[0].Variant).To(Equal("deterministic-lb")) g.Expect(plan.TestMatrix.Sequential[0].Steps[0].LabelFilter).To(Equal("deterministic-lb-ip")) }) } type stubMirrorRegistry struct { setup func(context.Context, mirrorregistry.MirrorRequest) (*mirrorregistry.Result, error) } func (s stubMirrorRegistry) Setup(ctx context.Context, req mirrorregistry.MirrorRequest) (*mirrorregistry.Result, error) { return s.setup(ctx, req) } func TestAWSPlatformConfigPreCreate(t *testing.T) { for _, tt := range []struct { name string emptyDir bool missingStream bool newError bool setupError bool emptySources bool writeError bool wantError string }{ {name: "When the shared directory is set, it should set up the fixture and write artifacts"}, {name: "When the shared directory is empty, it should fail before setup", emptyDir: true, wantError: "requires a shared directory"}, {name: "When the CLI ImageStream is missing, it should return the lookup error", missingStream: true, wantError: "read ImageStream"}, {name: "When registry initialization fails, it should return the error", newError: true, wantError: "initialize mirror registry"}, {name: "When registry setup fails, it should return the error", setupError: true, wantError: "set up mirror registry"}, {name: "When setup returns no image content sources, it should return the validation error", emptySources: true, wantError: "no image content sources"}, {name: "When artifact writing fails, it should return the error", writeError: true, wantError: "write mirror registry file"}, } { t.Run(tt.name, func(t *testing.T) { dir := t.TempDir() if tt.emptyDir { dir = "" } if tt.writeError { dir = filepath.Join(dir, "missing") } cfg := NewAWSPlatformConfig(AWSPlatformOptions{}, dir) factoryCalled, setupCalled := false, false cfg.newMirrorRegistry = func(_ crclient.Client, opts mirrorregistry.Options) (mirrorRegistry, error) { factoryCalled = true if opts.CopierImage != testCLIImage { t.Fatalf("copier image = %s", opts.CopierImage) } if tt.newError { return nil, errors.New("initialization failed") } return stubMirrorRegistry{setup: func(ctx context.Context, req mirrorregistry.MirrorRequest) (*mirrorregistry.Result, error) { setupCalled = true if _, ok := ctx.Deadline(); !ok { t.Fatal("setup has no deadline") } want := mirrorregistry.MirrorRequest{Images: []mirrorregistry.ImageMapping{ {From: mirrorregistry.DefaultRegistryImage}, {From: mirrorregistry.DefaultRegistryImage, SourceRepository: "mirror-source.hypershift-e2e.invalid/libpod/registry"}, }} if !reflect.DeepEqual(req, want) { t.Fatalf("request = %+v, want %+v", req, want) } if tt.setupError { return nil, errors.New("copy failed") } host := "mirror-registry-test-mirror-registry.apps.alesross-mc.alesross.hypershift.devcluster.openshift.com" result := &mirrorregistry.Result{ Host: host, CABundlePEM: []byte("test-ca"), ImageContentSources: []hyperv1.ImageContentSource{{Source: "quay.io/libpod/registry", Mirrors: []string{host + "/quay.io/libpod/registry"}}}, } if tt.emptySources { result.ImageContentSources = nil } return result, nil }}, nil } scheme := runtime.NewScheme() if err := imagev1.AddToScheme(scheme); err != nil { t.Fatal(err) } builder := fake.NewClientBuilder().WithScheme(scheme) if !tt.missingStream { builder.WithObjects(cliStream(testCLIImage)) } err := cfg.setupImageMirroring(t.Context(), builder.Build()) if tt.wantError != "" { if err == nil || !strings.Contains(err.Error(), tt.wantError) { t.Fatalf("got %v, want error containing %q", err, tt.wantError) } } else if err != nil { t.Fatal(err) } wantFactory := !tt.emptyDir && !tt.missingStream if factoryCalled != wantFactory || setupCalled != (wantFactory && !tt.newError) { t.Fatalf("factory called=%v, setup called=%v", factoryCalled, setupCalled) } if tt.wantError == "" { for _, name := range []string{"mirror-registry-ca.pem", "mirror-registry-ics.yaml", "mirror-registry.json"} { if _, err := os.Stat(filepath.Join(dir, name)); err != nil { t.Fatal(err) } } } }) } } func cliStream(ref string) *imagev1.ImageStream { return &imagev1.ImageStream{ ObjectMeta: metav1.ObjectMeta{Namespace: "openshift", Name: "cli"}, Status: imagev1.ImageStreamStatus{Tags: []imagev1.NamedTagEventList{{Tag: "latest", Items: []imagev1.TagEvent{{DockerImageReference: ref}}}}}, } }