-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresource_package_test.go
More file actions
8932 lines (8217 loc) · 330 KB
/
Copy pathresource_package_test.go
File metadata and controls
8932 lines (8217 loc) · 330 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
// Copyright 2024-2026 Defense Unicorns
// SPDX-License-Identifier: AGPL-3.0-or-later OR LicenseRef-Defense-Unicorns-Commercial
package provider
import (
"bytes"
"context"
"crypto/sha1"
"encoding/json"
"errors"
"fmt"
"math/big"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/defenseunicorns/pkg/helpers/v2"
"github.com/hashicorp/terraform-plugin-framework-timeouts/resource/timeouts"
"github.com/hashicorp/terraform-plugin-framework/attr"
"github.com/hashicorp/terraform-plugin-framework/diag"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/defaults"
"github.com/hashicorp/terraform-plugin-framework/tfsdk"
"github.com/hashicorp/terraform-plugin-framework/types"
"github.com/hashicorp/terraform-plugin-framework/types/basetypes"
"github.com/hashicorp/terraform-plugin-go/tftypes"
"github.com/hashicorp/terraform-plugin-log/tflogtest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
zarfAPI "github.com/zarf-dev/zarf/src/api"
"github.com/zarf-dev/zarf/src/api/v1alpha1"
zarfCluster "github.com/zarf-dev/zarf/src/pkg/cluster"
"github.com/zarf-dev/zarf/src/pkg/packager"
zarfPackager "github.com/zarf-dev/zarf/src/pkg/packager"
"github.com/zarf-dev/zarf/src/pkg/packager/filters"
"github.com/zarf-dev/zarf/src/pkg/packager/layout"
zarfSigning "github.com/zarf-dev/zarf/src/pkg/signing"
zarfState "github.com/zarf-dev/zarf/src/pkg/state"
zarfValue "github.com/zarf-dev/zarf/src/pkg/value"
"github.com/zarf-dev/zarf/src/pkg/variables"
zarfZoci "github.com/zarf-dev/zarf/src/pkg/zoci"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes/fake"
"github.com/defenseunicorns/terraform-provider-uds/internal/logging"
udsPackager "github.com/defenseunicorns/terraform-provider-uds/internal/packager"
)
// testCtx returns a context with a 5-minute deadline, matching the minimum
// lifecycle budget expected by zarfOperationTimeout.
func testCtx(t *testing.T) context.Context {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
t.Cleanup(cancel)
return ctx
}
func testOCISource(rawURL string) string {
host := strings.TrimPrefix(rawURL, "https://")
host = strings.TrimPrefix(host, "http://")
return "oci://" + host + "/packages/test:v1.0.0"
}
func TestPackageResource_GetPackageSourceRemoteOptions(t *testing.T) {
t.Run("disabled leaves HTTPS default without probing", func(t *testing.T) {
var requests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
requests.Add(1)
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
resource := NewPackageResource(&udsProviderConfig{}, nil, nil, nil).(*PackageResource)
opts, err := resource.getPackageSourceRemoteOptions(testCtx(t), testOCISource(server.URL))
require.NoError(t, err)
assert.False(t, opts.PlainHTTP)
assert.Zero(t, requests.Load())
})
t.Run("HTTP-only source resolves to plain HTTP", func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
}))
defer server.Close()
resource := NewPackageResource(&udsProviderConfig{InsecureForceHTTP: true}, nil, nil, nil).(*PackageResource)
opts, err := resource.getPackageSourceRemoteOptions(testCtx(t), testOCISource(server.URL))
require.NoError(t, err)
assert.True(t, opts.PlainHTTP)
})
t.Run("self-signed HTTPS source remains HTTPS when verification is skipped", func(t *testing.T) {
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
}))
defer server.Close()
resource := NewPackageResource(&udsProviderConfig{
InsecureForceHTTP: true,
InsecureSkipTLSVerification: true,
}, nil, nil, nil).(*PackageResource)
opts, err := resource.getPackageSourceRemoteOptions(testCtx(t), testOCISource(server.URL))
require.NoError(t, err)
assert.False(t, opts.PlainHTTP)
assert.True(t, opts.InsecureSkipTLSVerify)
})
t.Run("certificate failure does not downgrade to HTTP", func(t *testing.T) {
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
resource := NewPackageResource(&udsProviderConfig{InsecureForceHTTP: true}, nil, nil, nil).(*PackageResource)
opts, err := resource.getPackageSourceRemoteOptions(testCtx(t), testOCISource(server.URL))
require.Error(t, err)
assert.False(t, opts.PlainHTTP)
assert.Contains(t, err.Error(), "unable to determine transport for package source")
})
t.Run("local source does not negotiate", func(t *testing.T) {
resource := NewPackageResource(&udsProviderConfig{InsecureForceHTTP: true}, nil, nil, nil).(*PackageResource)
opts, err := resource.getPackageSourceRemoteOptions(testCtx(t), "./zarf-package-test.tar.zst")
require.NoError(t, err)
assert.False(t, opts.PlainHTTP)
})
t.Run("provider aliases do not share cached failures", func(t *testing.T) {
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
source := testOCISource(server.URL)
strictResource := NewPackageResource(&udsProviderConfig{InsecureForceHTTP: true}, nil, nil, nil).(*PackageResource)
_, err := strictResource.getPackageSourceRemoteOptions(testCtx(t), source)
require.Error(t, err)
skipVerifyResource := NewPackageResource(&udsProviderConfig{
InsecureForceHTTP: true,
InsecureSkipTLSVerification: true,
}, nil, nil, nil).(*PackageResource)
opts, err := skipVerifyResource.getPackageSourceRemoteOptions(testCtx(t), source)
require.NoError(t, err)
assert.False(t, opts.PlainHTTP)
})
}
type MockCluster struct {
mock.Mock
}
func newFakeCluster() *zarfCluster.Cluster {
return &zarfCluster.Cluster{Clientset: fake.NewSimpleClientset()}
}
// newLifecycleDeployedPackage builds cluster state from pkgLayout with an amd64
// architecture and the supplied deployed components.
func newLifecycleDeployedPackage(pkgLayout *layout.PackageLayout, components ...zarfState.DeployedComponent) zarfState.DeployedPackage {
data := pkgLayout.AsV1alpha1()
data.Metadata.Architecture = "amd64"
return zarfState.DeployedPackage{
Name: data.Metadata.Name,
Data: data,
DeployedComponents: components,
}
}
// newPackageStateSecret serializes pkg into the Secret shape Zarf uses for
// deployed package state.
func newPackageStateSecret(t *testing.T, pkg zarfState.DeployedPackage) *corev1.Secret {
t.Helper()
data, err := json.Marshal(pkg)
require.NoError(t, err)
return &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{Name: pkg.GetSecretName(), Namespace: zarfState.ZarfNamespaceName},
Data: map[string][]byte{"data": data},
}
}
// newCreateLifecycleModel builds a Create plan model from options, with known
// empty runtime outputs and unknown metadata as Terraform supplies before Create.
func newCreateLifecycleModel(options ...PackageResourceModelDataOption) PackageResourceModel {
model := NewTestPackageResourceModel(options...)
model.SetVariables = types.MapValueMust(types.StringType, map[string]attr.Value{})
model.ConnectStrings = emptyConnectStringSet()
model.Metadata = types.ObjectUnknown(packageMetadataAttrTypes)
return model
}
// runCreateLifecycleTest builds a Terraform plan from model, calls Create, and
// returns the response for lifecycle assertions.
func runCreateLifecycleTest(t *testing.T, packageResource *PackageResource, model PackageResourceModel) resource.CreateResponse {
t.Helper()
plan := buildTestPlan(t, packageResource, model)
resp := resource.CreateResponse{State: tfsdk.State{Schema: plan.Schema}}
packageResource.Create(context.Background(), resource.CreateRequest{Plan: plan}, &resp)
return resp
}
// runUpdateLifecycleTest builds Terraform plan and prior state from planModel
// and stateModel, calls Update, and returns the response.
func runUpdateLifecycleTest(t *testing.T, packageResource *PackageResource, planModel, stateModel PackageResourceModel) resource.UpdateResponse {
t.Helper()
plan := buildTestPlan(t, packageResource, planModel)
state := buildTestState(t, packageResource, stateModel)
resp := resource.UpdateResponse{State: tfsdk.State{Schema: plan.Schema}}
packageResource.Update(context.Background(), resource.UpdateRequest{Plan: plan, State: state}, &resp)
return resp
}
// requirePackageState decodes state into a package model and fails the test if
// the framework reports state conversion diagnostics.
func requirePackageState(t *testing.T, state tfsdk.State) PackageResourceModel {
t.Helper()
var model PackageResourceModel
require.False(t, state.Get(context.Background(), &model).HasError())
return model
}
// assertNoPackageState verifies that state has no readable package resource ID.
func assertNoPackageState(t *testing.T, state tfsdk.State) {
t.Helper()
var model PackageResourceModel
diags := state.Get(context.Background(), &model)
assert.True(t, diags.HasError() || model.ID.IsNull())
}
// assertPackageMetadata verifies the cluster-derived status, generation, and
// digest values stored in the package metadata object.
func assertPackageMetadata(t *testing.T, metadata types.Object, status string, generation int64, digest string) {
t.Helper()
attributes := metadata.Attributes()
assert.Equal(t, status, attributes["status"].(types.String).ValueString())
assert.Equal(t, generation, attributes["generation"].(types.Int64).ValueInt64())
assert.Equal(t, digest, attributes["digest"].(types.String).ValueString())
}
func (m *MockCluster) NewWithWait(ctx context.Context) (*zarfCluster.Cluster, error) {
args := m.Called(ctx)
return args.Get(0).(*zarfCluster.Cluster), args.Error(1)
}
type MockPackager struct {
mock.Mock
}
func (m *MockPackager) Deploy(ctx context.Context, pkgLayout *layout.PackageLayout, opts packager.DeployOptions) (packager.DeployResult, error) {
args := m.Called(ctx, pkgLayout, opts)
return args.Get(0).(packager.DeployResult), args.Error(1)
}
func (m *MockPackager) Remove(ctx context.Context, pkg zarfAPI.PackageDefinition, opts packager.RemoveOptions) error {
args := m.Called(ctx, legacyPackageDefinition(pkg), opts)
return args.Error(0)
}
func (m *MockPackager) LoadPackage(ctx context.Context, source string, opts packager.LoadOptions) (*layout.PackageLayout, error) {
args := m.Called(ctx, source, opts)
return args.Get(0).(*layout.PackageLayout), args.Error(1)
}
func (m *MockPackager) GetPackageFromSourceOrCluster(ctx context.Context, cluster *zarfCluster.Cluster, src string, namespaceOverride string, opts zarfPackager.LoadOptions) (_ zarfAPI.PackageDefinition, err error) {
args := m.Called(ctx, cluster, src, namespaceOverride, opts)
if pkg, ok := args.Get(0).(zarfAPI.PackageDefinition); ok {
return pkg, args.Error(1)
}
return zarfAPI.NewPackageDefinitionFromV1alpha1(args.Get(0).(v1alpha1.ZarfPackage)), args.Error(1)
}
// legacyPackageDefinition preserves the v1alpha1 representation used by the
// existing mock fixtures. PackageDefinition conversion fills API defaults that
// were previously absent from those fixtures.
func legacyPackageDefinition(definition zarfAPI.PackageDefinition) v1alpha1.ZarfPackage {
pkg := definition.AsV1alpha1()
if pkg.APIVersion == v1alpha1.APIVersion {
pkg.APIVersion = ""
}
if pkg.Kind == v1alpha1.ZarfPackageConfig {
pkg.Kind = ""
}
pkg.Build.SetOriginalAPIVersion("")
return pkg
}
type MockPackageComponentFilter struct {
mock.Mock
packageComponentFilter udsPackager.PackageComponentFilter
}
func (m *MockPackageComponentFilter) ForRemove(optionalComponents []string) filters.ComponentFilterStrategy {
m.Called(optionalComponents)
return m.getPackageComponentFilter().ForRemove(optionalComponents)
}
func (m *MockPackageComponentFilter) ForDeploy(optionalComponents []string) filters.ComponentFilterStrategy {
m.Called(optionalComponents)
return m.getPackageComponentFilter().ForDeploy(optionalComponents)
}
func (m *MockPackageComponentFilter) getPackageComponentFilter() udsPackager.PackageComponentFilter {
if m.packageComponentFilter == nil {
m.packageComponentFilter = udsPackager.NewPackageComponentFilter()
}
return m.packageComponentFilter
}
type MockLoadPackageResult struct {
Layout *layout.PackageLayout
Error error
}
type PackageResourceModelDataOption func(*PackageResourceModel)
func WithSource(source string) PackageResourceModelDataOption {
return func(model *PackageResourceModel) {
model.Source = types.StringValue(source)
}
}
func WithArchitecture(arch string) PackageResourceModelDataOption {
return func(model *PackageResourceModel) {
model.Architecture = types.StringValue(arch)
}
}
// newTestSigVerification builds a SignatureVerificationModel for use in tests.
func newTestSigVerification(enabled bool, publicKey string, keyless *KeylessVerificationModel) SignatureVerificationModel {
pubKeyVal := types.StringNull()
if publicKey != "" {
pubKeyVal = types.StringValue(publicKey)
}
sig := SignatureVerificationModel{
Verify: types.BoolValue(enabled),
PublicKey: pubKeyVal,
Keyless: types.ObjectNull(keylessVerificationAttrTypes),
}
if keyless != nil {
obj, diags := types.ObjectValueFrom(context.Background(), keylessVerificationAttrTypes, *keyless)
if diags.HasError() {
panic("newTestSigVerification: failed to build keyless object")
}
sig.Keyless = obj
}
return sig
}
// withSigVerification sets the signature_verification block from a SignatureVerificationModel.
func withSigVerification(sig SignatureVerificationModel) PackageResourceModelDataOption {
return func(model *PackageResourceModel) {
obj, diags := types.ObjectValueFrom(context.Background(), signatureVerificationAttrTypes, sig)
if diags.HasError() {
panic("withSigVerification: failed to build object")
}
model.SignatureVerification = obj
}
}
func WithPublicKey(publicKey string) PackageResourceModelDataOption {
return withSigVerification(newTestSigVerification(true, publicKey, nil))
}
func WithSignatureVerificationEnabled(enabled bool) PackageResourceModelDataOption {
return withSigVerification(newTestSigVerification(enabled, "", nil))
}
// nullTimeoutsValue returns a timeouts.Value with no durations configured
// so all operations fall back to their code defaults.
func nullTimeoutsValue() timeouts.Value {
return timeouts.Value{
Object: types.ObjectNull(map[string]attr.Type{
"create": types.StringType,
"read": types.StringType,
"update": types.StringType,
"delete": types.StringType,
}),
}
}
// WithTimeout sets all four timeout operations to the same duration string.
func WithTimeout(duration string) PackageResourceModelDataOption {
return func(model *PackageResourceModel) {
model.Timeouts = timeouts.Value{
Object: types.ObjectValueMust(
map[string]attr.Type{
"create": types.StringType,
"read": types.StringType,
"update": types.StringType,
"delete": types.StringType,
},
map[string]attr.Value{
"create": types.StringValue(duration),
"read": types.StringValue(duration),
"update": types.StringValue(duration),
"delete": types.StringValue(duration),
},
),
}
}
}
// WithCreateTimeout sets only the create timeout, leaving others null (defaults apply).
func WithCreateTimeout(duration string) PackageResourceModelDataOption {
return func(model *PackageResourceModel) {
model.Timeouts = timeouts.Value{
Object: types.ObjectValueMust(
map[string]attr.Type{
"create": types.StringType,
"read": types.StringType,
"update": types.StringType,
"delete": types.StringType,
},
map[string]attr.Value{
"create": types.StringValue(duration),
"read": types.StringNull(),
"update": types.StringNull(),
"delete": types.StringNull(),
},
),
}
}
}
// WithDeployedState populates computed read-only fields to plausible post-deploy values.
// Required when constructing a prior-state tfsdk.State for handler-level Read/Delete tests.
func WithDeployedState() PackageResourceModelDataOption {
return func(model *PackageResourceModel) {
model.ID = types.StringValue("test-pkg")
model.Name = types.StringValue("test-pkg")
model.Kind = types.StringValue("ZarfPackageConfig")
model.Version = types.StringValue("1.0.0")
meta, _ := types.ObjectValue(
packageMetadataAttrTypes,
map[string]attr.Value{
"name": types.StringValue("test-pkg"),
"description": types.StringValue("test package"),
"version": types.StringValue("1.0.0"),
"status": types.StringNull(),
"generation": types.Int64Null(),
"digest": types.StringNull(),
},
)
model.Metadata = meta
model.ConnectStrings = emptyConnectStringSet()
model.SetVariables = types.MapValueMust(types.StringType, map[string]attr.Value{})
}
}
// buildTestState serializes model into a tfsdk.State using the resource schema.
// Use for handler-level tests that call r.Create/Read/Update/Delete directly.
func buildTestState(t *testing.T, r *PackageResource, model PackageResourceModel) tfsdk.State {
t.Helper()
ctx := context.Background()
var schemaResp resource.SchemaResponse
r.Schema(ctx, resource.SchemaRequest{}, &schemaResp)
state := tfsdk.State{Schema: schemaResp.Schema}
diags := state.Set(ctx, &model)
require.False(t, diags.HasError(), "buildTestState: %v", diags)
return state
}
func buildTestPlan(t *testing.T, r *PackageResource, model PackageResourceModel) tfsdk.Plan {
t.Helper()
ctx := context.Background()
var schemaResp resource.SchemaResponse
r.Schema(ctx, resource.SchemaRequest{}, &schemaResp)
plan := tfsdk.Plan{Schema: schemaResp.Schema}
diags := plan.Set(ctx, &model)
require.False(t, diags.HasError(), "buildTestPlan: %v", diags)
return plan
}
func buildTestConfig(t *testing.T, r *PackageResource, model PackageResourceModel) tfsdk.Config {
t.Helper()
plan := buildTestPlan(t, r, model)
return tfsdk.Config{Raw: plan.Raw, Schema: plan.Schema}
}
func WithNamespace(namespace string) PackageResourceModelDataOption {
return func(model *PackageResourceModel) {
model.Namespace = types.StringValue(namespace)
}
}
func WithComponents(components []ComponentModel) PackageResourceModelDataOption {
return func(model *PackageResourceModel) {
model.Components = componentSliceToSet(components)
}
}
func WithVars(vars []VariableModel) PackageResourceModelDataOption {
return func(model *PackageResourceModel) {
model.Vars = variableSliceToSet(vars)
}
}
func WithSensitiveVars(sensitiveVars []VariableModel) PackageResourceModelDataOption {
return func(model *PackageResourceModel) {
model.SensitiveVars = variableSliceToSet(sensitiveVars)
}
}
// WithOptionalComponents sets optional_components to an explicit set of names.
// Pass an empty slice to set an empty (non-null) set.
func WithOptionalComponents(names []string) PackageResourceModelDataOption {
return func(model *PackageResourceModel) {
vals := make([]attr.Value, len(names))
for i, name := range names {
vals[i] = types.StringValue(name)
}
model.OptionalComponents = types.SetValueMust(types.StringType, vals)
}
}
func WithValues(values types.Dynamic) PackageResourceModelDataOption {
return func(model *PackageResourceModel) {
model.Values = values
}
}
func WithSensitiveValues(values types.Dynamic) PackageResourceModelDataOption {
return func(model *PackageResourceModel) {
model.SensitiveValues = values
}
}
// NewTestPackageResourceModel creates a PackageResourceModel with default values and applies data options
func NewTestPackageResourceModel(options ...PackageResourceModelDataOption) PackageResourceModel {
model := PackageResourceModel{
Source: types.StringValue("oci://ghcr.io/defenseunicorns/packages/test:latest"),
Architecture: types.StringValue(runtime.GOARCH),
SignatureVerification: types.ObjectNull(signatureVerificationAttrTypes),
Timeouts: nullTimeoutsValue(),
Namespace: types.StringValue(""),
Components: componentSliceToSet([]ComponentModel{}),
OptionalComponents: types.SetNull(types.StringType),
Vars: variableSliceToSet([]VariableModel{}),
SensitiveVars: variableSliceToSet([]VariableModel{}),
Values: types.DynamicNull(),
SensitiveValues: types.DynamicNull(),
}
for _, option := range options {
option(&model)
}
return model
}
type ComponentModelDataOption func(*ComponentModel)
func WithComponentOverrides(overrides []ComponentChartValuesModel) ComponentModelDataOption {
return func(model *ComponentModel) {
model.Overrides = componentChartValuesSliceToSet(overrides)
}
}
type ComponentChartValuesModelDataOption func(*ComponentChartValuesModel)
func WithComponentChartName(chartName string) ComponentChartValuesModelDataOption {
return func(model *ComponentChartValuesModel) {
model.ChartName = types.StringValue(chartName)
}
}
func WithComponentChartValues(values []HelmChartPathValueModel) ComponentChartValuesModelDataOption {
return func(model *ComponentChartValuesModel) {
model.Values = helmChartPathValueSliceToSet(values)
}
}
func WithComponentChartSensitiveValues(values []HelmChartPathValueModel) ComponentChartValuesModelDataOption {
return func(model *ComponentChartValuesModel) {
model.SensitiveValues = helmChartPathValueSliceToSet(values)
}
}
// NewTestComponentModel creates a ComponentModel with default values and applies data options
func NewTestComponentModel(name string, options ...ComponentModelDataOption) ComponentModel {
model := ComponentModel{
Name: types.StringValue(name),
}
for _, option := range options {
option(&model)
}
return model
}
// SetVarEntry is a small helper for defining expected runtime set variables
// in a compact, tabular form for tests.
type SetVarEntry struct {
Name string
Value string
Sensitive bool
}
// buildVCFromEntries constructs a *variables.VariableConfig from a slice of SetVarEntry.
func buildVCFromEntries(entries []SetVarEntry) *variables.VariableConfig {
vc := variables.New("", nil, nil)
for _, e := range entries {
vc.SetVariable(e.Name, e.Value, e.Sensitive, false, v1alpha1.RawVariableType)
}
return vc
}
// buildVCFromMaps constructs a *variables.VariableConfig from two input maps:
// one marked non-sensitive and one marked sensitive. Keys are provided as they
// come from deploy results (may be mixed case); production code will
// normalize names to lowercase when exporting.
func buildVCFromMaps(nonSensitive map[string]string, sensitive map[string]string) *variables.VariableConfig {
vc := variables.New("", nil, nil)
for k, v := range nonSensitive {
vc.SetVariable(k, v, false, false, v1alpha1.RawVariableType)
}
for k, v := range sensitive {
vc.SetVariable(k, v, true, false, v1alpha1.RawVariableType)
}
return vc
}
// DeployedVar is a compact representation of a deployed set variable with its
// value and whether it is sensitive.
type DeployedVar struct {
Value string
Sensitive bool
}
// buildVCFromCondensedMap constructs a *variables.VariableConfig from a
// condensed map of deployed variables where the value includes whether it is
// sensitive. This mirrors the reviewer-suggested table format.
func buildVCFromCondensedMap(in map[string]DeployedVar) *variables.VariableConfig {
vc := variables.New("", nil, nil)
for k, v := range in {
vc.SetVariable(k, v.Value, v.Sensitive, false, v1alpha1.RawVariableType)
}
return vc
}
// readStringMap extracts a map[string]string from a Terraform types.Map value.
// It returns an empty map (not nil) when the input is null/unknown/empty to make
// assertions simpler in tests.
func readStringMap(ctx context.Context, m types.Map) (map[string]string, error) {
out := map[string]string{}
if m.IsNull() || m.IsUnknown() {
return out, nil
}
diags := m.ElementsAs(ctx, &out, false)
if diags.HasError() {
return nil, fmt.Errorf("failed to read types.Map: %v", diags)
}
return out, nil
}
// NewTestComponentChartValuesModel creates a ComponentChartValuesModel with default values and applies data options
func NewTestComponentChartValuesModel(chartName string, options ...ComponentChartValuesModelDataOption) ComponentChartValuesModel {
model := ComponentChartValuesModel{
ChartName: types.StringValue(chartName),
}
for _, option := range options {
option(&model)
}
return model
}
// NewComponentModelsFromNames creates ComponentModel slice from component names
func NewComponentModelsFromNames(componentNames []string) []ComponentModel {
componentModels := make([]ComponentModel, len(componentNames))
for i, componentName := range componentNames {
componentModels[i] = ComponentModel{
Name: types.StringValue(componentName),
}
}
return componentModels
}
func newErrorLoadPackageResult(err error) MockLoadPackageResult {
return MockLoadPackageResult{
Layout: &layout.PackageLayout{
PackageDefinition: zarfAPI.NewPackageDefinitionFromV1alpha1(v1alpha1.ZarfPackage{}),
},
Error: err,
}
}
// Helper function to create fresh MockLoadPackageResult for each test
func newValidLoadPackageResult() MockLoadPackageResult {
return MockLoadPackageResult{
Layout: &layout.PackageLayout{
PackageDefinition: zarfAPI.NewPackageDefinitionFromV1alpha1(v1alpha1.ZarfPackage{
Metadata: v1alpha1.ZarfMetadata{
Name: "test-package",
Description: "Test package",
Version: "0.0.1",
},
Components: []v1alpha1.ZarfComponent{
{
Name: "test-required-component-0",
Required: helpers.BoolPtr(true),
Default: false,
},
{
Name: "test-required-component-1",
Required: helpers.BoolPtr(true),
Default: false,
},
{
Name: "test-optional-default-component-0",
Required: nil, // Why zarf, why?
Default: true,
},
{
Name: "test-optional-default-component-1",
Required: helpers.BoolPtr(false),
Default: true,
},
{
Name: "test-optional-non-default-component-0",
Required: nil,
Default: false,
},
{
Name: "test-optional-non-default-component-1",
Required: helpers.BoolPtr(false),
Default: false,
},
},
}),
},
Error: nil,
}
}
func testPackageIdentity(namespace string) deployedPackageIdentity {
id := "test-package"
if namespace != "" {
id = namespace + ":" + id
}
return deployedPackageIdentity{
ID: id,
Name: "test-package",
Namespace: namespace,
Package: zarfState.DeployedPackage{
Name: "test-package",
NamespaceOverride: namespace,
Data: v1alpha1.ZarfPackage{Metadata: v1alpha1.ZarfMetadata{Name: "test-package"}},
},
}
}
func TestPackageResource_Upsert_VariableModels(t *testing.T) {
packageLayout := layout.PackageLayout{
PackageDefinition: zarfAPI.NewPackageDefinitionFromV1alpha1(v1alpha1.ZarfPackage{
Metadata: v1alpha1.ZarfMetadata{
Name: "test-package",
Description: "Test package",
Version: "0.0.1",
},
Components: []v1alpha1.ZarfComponent{
{
Name: "test-required-component-0",
Required: helpers.BoolPtr(true),
Default: false,
},
},
}),
}
tests := []struct {
name string
vars []VariableModel
sensitiveVars []VariableModel
VariableModelMap types.Map
expectedVariableModels map[string]string
}{
{
name: "vars and sensitiveVars",
vars: []VariableModel{{Name: types.StringValue("listKey"), Value: types.StringValue("listsValue")}},
sensitiveVars: []VariableModel{{Name: types.StringValue("sensitive_listKey"), Value: types.StringValue("sensitive listValue")}},
expectedVariableModels: map[string]string{
"listKey": "listsValue",
"sensitive_listKey": "sensitive listValue",
},
},
{
name: "vars only",
vars: []VariableModel{{Name: types.StringValue("listKey"), Value: types.StringValue("listsValue")}},
sensitiveVars: []VariableModel{},
expectedVariableModels: map[string]string{
"listKey": "listsValue",
},
},
{
name: "sensitiveVars only",
vars: []VariableModel{},
sensitiveVars: []VariableModel{{Name: types.StringValue("sensitive_listKey"), Value: types.StringValue("sensitive listValue")}},
expectedVariableModels: map[string]string{
"sensitive_listKey": "sensitive listValue",
},
},
{
name: "no vars at all",
vars: []VariableModel{},
sensitiveVars: []VariableModel{},
expectedVariableModels: map[string]string{},
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
mockPackager := &MockPackager{}
mockPackageComponentFilter := &MockPackageComponentFilter{}
mockPackager.On("LoadPackage", mock.Anything, mock.Anything, mock.Anything).Return(
&packageLayout,
nil,
)
mockPackager.On("Deploy", mock.Anything, mock.Anything, mock.Anything).Return(packager.DeployResult{}, nil)
mockPackageComponentFilter.On("ForDeploy", mock.Anything).Return(mock.Anything)
packageResource := NewPackageResource(nil, mockPackager, mockPackageComponentFilter, nil).(*PackageResource)
testModel := NewTestPackageResourceModel(
WithVars(tc.vars),
WithSensitiveVars(tc.sensitiveVars),
)
_, err := packageResource.upsert(testCtx(t), testModel)
assert.NoError(t, err)
// Check that Deploy was called and the variables map was provided with the correct values
mockPackageComponentFilter.AssertExpectations(t)
for _, call := range mockPackager.Calls {
if call.Method == "Deploy" {
deployOptions := call.Arguments[2].(zarfPackager.DeployOptions)
assert.NotNil(t, deployOptions.SetVariables)
assert.Len(t, deployOptions.SetVariables, len(tc.expectedVariableModels))
assert.Equal(t, deployOptions.SetVariables, tc.expectedVariableModels)
}
}
})
}
}
func TestPackageResource_Upsert_ForceHelmSSAConflicts(t *testing.T) {
packageLayout := newValidLoadPackageResult().Layout
tests := []struct {
name string
forceHelmSSAConflicts bool
}{
{
name: "ForceConflicts is false when provider setting is false",
forceHelmSSAConflicts: false,
},
{
name: "ForceConflicts is true when provider setting is true",
forceHelmSSAConflicts: true,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
mockPackager := &MockPackager{}
mockPackageComponentFilter := &MockPackageComponentFilter{}
mockPackager.On("LoadPackage", mock.Anything, mock.Anything, mock.Anything).Return(packageLayout, nil)
mockPackager.On("Deploy", mock.Anything, mock.Anything, mock.Anything).Return(packager.DeployResult{}, nil)
mockPackageComponentFilter.On("ForDeploy", mock.Anything).Return(mock.Anything)
providerCfg := &udsProviderConfig{
ForceHelmSSAConflicts: tc.forceHelmSSAConflicts,
}
packageResource := NewPackageResource(providerCfg, mockPackager, mockPackageComponentFilter, nil).(*PackageResource)
_, err := packageResource.upsert(testCtx(t), NewTestPackageResourceModel())
assert.NoError(t, err)
for _, call := range mockPackager.Calls {
if call.Method == "Deploy" {
deployOptions := call.Arguments[2].(zarfPackager.DeployOptions)
assert.Equal(t, tc.forceHelmSSAConflicts, deployOptions.ForceConflicts)
}
}
})
}
}
func TestPackageResource_UpsertNegotiatesPackageSourceAndPreservesRegistryOptions(t *testing.T) {
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
}))
defer server.Close()
mockPackager := &MockPackager{}
mockPackageComponentFilter := &MockPackageComponentFilter{}
mockPackager.On("LoadPackage", mock.Anything, mock.Anything, mock.Anything).
Return(newValidLoadPackageResult().Layout, nil)
mockPackager.On("Deploy", mock.Anything, mock.Anything, mock.Anything).
Return(packager.DeployResult{}, nil)
mockPackageComponentFilter.On("ForDeploy", mock.Anything).Return(mock.Anything)
providerConfig := &udsProviderConfig{
InsecureForceHTTP: true,
InsecureSkipTLSVerification: true,
}
packageResource := NewPackageResource(providerConfig, mockPackager, mockPackageComponentFilter, nil).(*PackageResource)
model := NewTestPackageResourceModel(WithSource(testOCISource(server.URL)))
_, err := packageResource.upsert(testCtx(t), model)
require.NoError(t, err)
var loadOptions zarfPackager.LoadOptions
var deployOptions zarfPackager.DeployOptions
for _, call := range mockPackager.Calls {
switch call.Method {
case "LoadPackage":
loadOptions = call.Arguments[2].(zarfPackager.LoadOptions)
case "Deploy":
deployOptions = call.Arguments[2].(zarfPackager.DeployOptions)
}
}
assert.False(t, loadOptions.PlainHTTP, "working HTTPS package source must not be downgraded")
assert.True(t, loadOptions.InsecureSkipTLSVerify)
assert.True(t, deployOptions.PlainHTTP, "external HTTP Zarf registry compatibility must be preserved")
assert.True(t, deployOptions.InsecureSkipTLSVerify)
}
func TestPackageResource_LoadPackageLayoutForInspectionUsesNegotiatedSourceOptions(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
}))
defer server.Close()
mockPackager := &MockPackager{}
mockPackager.On("LoadPackage", mock.Anything, mock.Anything, mock.Anything).
Return(newValidLoadPackageResult().Layout, nil)
packageResource := NewPackageResource(
&udsProviderConfig{InsecureForceHTTP: true},
mockPackager,
nil,
nil,
).(*PackageResource)
_, err := packageResource.loadPackageLayoutForInspection(
testCtx(t),
NewTestPackageResourceModel(WithSource(testOCISource(server.URL))),
)
require.NoError(t, err)
loadOptions := mockPackager.Calls[0].Arguments[2].(zarfPackager.LoadOptions)
assert.True(t, loadOptions.PlainHTTP)
}
func TestPackageResource_Upsert_SetVariables(t *testing.T) {
cases := []struct {
name string
deployedPackageSetVariables map[string]DeployedVar
expectedSetVariables map[string]string
}{
{
name: "no deployed package set variables returns empty set_variables map",
deployedPackageSetVariables: map[string]DeployedVar{},
expectedSetVariables: map[string]string{},
},
{
name: "single non-sensitive set variable is exported into set_variables",
deployedPackageSetVariables: map[string]DeployedVar{
"OUTPUT": {Value: "output-val", Sensitive: false},
},
expectedSetVariables: map[string]string{"output": "output-val"},
},
{
name: "single sensitive set variable is exported into set_variables",
deployedPackageSetVariables: map[string]DeployedVar{
"API_KEY": {Value: "s3cr3t", Sensitive: true},
},
expectedSetVariables: map[string]string{"api_key": "s3cr3t"},
},
{
name: "variable names normalized to lowercase",
deployedPackageSetVariables: map[string]DeployedVar{