-
Notifications
You must be signed in to change notification settings - Fork 306
Expand file tree
/
Copy pathapk_test.go
More file actions
1943 lines (1637 loc) · 76.3 KB
/
Copy pathapk_test.go
File metadata and controls
1943 lines (1637 loc) · 76.3 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 (
"crypto/sha256"
"fmt"
"io"
"net/url"
"os"
"os/exec"
"strings"
"testing"
buildinfo "github.com/jfrog/build-info-go/entities"
"github.com/jfrog/jfrog-cli-artifactory/artifactory/commands/generic"
rtLifecycle "github.com/jfrog/jfrog-cli-artifactory/lifecycle"
artUtils "github.com/jfrog/jfrog-cli-core/v2/artifactory/utils"
"github.com/jfrog/jfrog-cli-core/v2/common/spec"
coreutils "github.com/jfrog/jfrog-cli-core/v2/utils/coreutils"
coretests "github.com/jfrog/jfrog-cli-core/v2/utils/tests"
accessServices "github.com/jfrog/jfrog-client-go/access/services"
artServices "github.com/jfrog/jfrog-client-go/artifactory/services"
lifecycleServices "github.com/jfrog/jfrog-client-go/lifecycle/services"
clientTestUtils "github.com/jfrog/jfrog-client-go/utils/tests"
"github.com/jfrog/jfrog-cli/inttestutils"
"github.com/jfrog/jfrog-cli/utils/tests"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// ==================== Initialization ====================
func initApkTest(t *testing.T) {
if !*tests.TestAlpine {
t.Skip("Skipping Alpine APK test. To run Alpine APK tests add the '-test.alpine=true' option.")
}
require.True(t, isRepoExist(tests.AlpineLocalRepo), "APK test local repository doesn't exist.")
require.True(t, isRepoExist(tests.AlpineVirtualRepo), "APK test virtual repository doesn't exist.")
}
// apkAvailable returns true when the `apk` binary is present on this machine.
// Tests that actually invoke `apk` must call t.Skip when this returns false.
func apkAvailable() bool {
_, err := exec.LookPath("apk")
return err == nil
}
// computeFileSHA256 returns the hex-encoded SHA256 digest of the file at path.
func computeFileSHA256(t *testing.T, path string) string {
t.Helper()
f, err := os.Open(path)
require.NoError(t, err, "open file for SHA256: %s", path)
defer func() { require.NoError(t, f.Close()) }()
h := sha256.New()
_, err = io.Copy(h, f)
require.NoError(t, err, "compute SHA256 for: %s", path)
return fmt.Sprintf("%x", h.Sum(nil))
}
// ==================== jf apk add (build info collection) ====================
// TestApkAdd_BasicBuildInfo verifies that `jf apk add` records build-info
// dependencies for a single explicitly requested package.
func TestApkAdd_BasicBuildInfo(t *testing.T) {
initApkTest(t)
if !apkAvailable() {
t.Skip("apk binary not found — test requires Alpine Linux.")
}
oldHomeDir, newHomeDir := prepareHomeDir(t)
defer func() {
clientTestUtils.SetEnvAndAssert(t, coreutils.HomeDir, oldHomeDir)
clientTestUtils.RemoveAllAndAssert(t, newHomeDir)
}()
buildName := tests.AlpineBuildName + "-add-basic"
buildNumber := "1"
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
err := jfrogCli.Exec("apk", "add", "curl",
"--build-name="+buildName, "--build-number="+buildNumber,
"--repo="+tests.AlpineVirtualRepo)
if err != nil {
t.Skipf("jf apk add failed (apk system command unavailable or repo not configured): %v", err)
}
assert.NoError(t, artifactoryCli.Exec("bp", buildName, buildNumber))
publishedBuildInfo, found, err := tests.GetBuildInfo(serverDetails, buildName, buildNumber)
assert.NoError(t, err)
assert.True(t, found, "build-info should be published after jf apk add")
if found {
bi := publishedBuildInfo.BuildInfo
require.Len(t, bi.Modules, 1)
assert.Equal(t, buildinfo.Apk, bi.Modules[0].Type)
assert.GreaterOrEqual(t, len(bi.Modules[0].Dependencies), 1,
"curl should produce at least 1 dependency (curl itself + transitive)")
}
inttestutils.DeleteBuild(serverDetails.ArtifactoryUrl, buildName, artHttpDetails)
}
// TestApkReleaseBundleCreation verifies that a Release Bundle can be created from the
// build-info produced by `jf apk upload`. Upload is used (not `apk add`) because a release
// bundle requires source *artifacts*, and only the upload flow records an artifact in the
// build-info — `apk add` records dependencies only, which yields "Source artifacts not found".
// It uploads an .apk with build-info, publishes the build, runs `rbc --build-name/--build-number`,
// and asserts the release bundle reaches COMPLETED status. Release bundle operations require a
// lifecycle service, so the test skips gracefully when it is unavailable.
func TestApkReleaseBundleCreation(t *testing.T) {
initApkTest(t)
oldHomeDir, newHomeDir := prepareHomeDir(t)
defer func() {
clientTestUtils.SetEnvAndAssert(t, coreutils.HomeDir, oldHomeDir)
clientTestUtils.RemoveAllAndAssert(t, newHomeDir)
}()
tmpDir, err := os.MkdirTemp("", "apk-rb-*")
if err != nil {
t.Fatalf("failed to create temp dir: %v", err)
}
defer clientTestUtils.RemoveAllAndAssert(t, tmpDir)
fakePkgInfo := "pkgname = testpkg-rb\npkgver = 1.0.0-r0\narch = x86_64\n"
if writeErr := os.WriteFile(tmpDir+"/.PKGINFO", []byte(fakePkgInfo), 0644); writeErr != nil {
t.Fatalf("failed to write .PKGINFO: %v", writeErr)
}
apkPath := tmpDir + "/testpkg-rb-1.0.0-r0.apk"
if tarErr := exec.Command("tar", "-czf", apkPath, "-C", tmpDir, ".PKGINFO").Run(); tarErr != nil {
t.Skipf("tar not available to build test .apk: %v", tarErr)
}
buildName := tests.AlpineBuildName + "-rb"
buildNumber := "1"
inttestutils.DeleteBuild(serverDetails.ArtifactoryUrl, buildName, artHttpDetails)
defer inttestutils.DeleteBuild(serverDetails.ArtifactoryUrl, buildName, artHttpDetails)
// Upload an .apk with build-info so the build records a promotable/bundlable artifact.
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
if uploadErr := jfrogCli.Exec("apk", "upload", apkPath,
"--repo="+tests.AlpineLocalRepo,
"--alpine-version=3.18",
"--build-name="+buildName, "--build-number="+buildNumber,
"--server-id=default"); uploadErr != nil {
t.Skipf("jf apk upload failed: %v", uploadErr)
}
assert.NoError(t, artifactoryCli.Exec("bp", buildName, buildNumber))
// The build must exist with an Alpine module recording an artifact before we can bundle it.
publishedBuildInfo, found, err := tests.GetBuildInfo(serverDetails, buildName, buildNumber)
assert.NoError(t, err)
if !assert.True(t, found, "build-info should be published before creating a release bundle") {
return
}
require.NotEmpty(t, publishedBuildInfo.BuildInfo.Modules, "Alpine build-info should have at least one module")
assert.Equal(t, buildinfo.Apk, publishedBuildInfo.BuildInfo.Modules[0].Type)
require.NotEmpty(t, publishedBuildInfo.BuildInfo.Modules[0].Artifacts,
"upload build-info must record an artifact so the release bundle has source artifacts")
// Create a release bundle from the Alpine build-info.
rbName := buildName + "-release-bundle"
rbVersion := "1.0.0"
if err = runJfrogCliWithoutAssertion("rbc", rbName, rbVersion,
"--build-name="+buildName, "--build-number="+buildNumber); err != nil {
// Release bundle creation requires a lifecycle/Distribution service — skip if unavailable.
t.Skipf("Skipping release bundle creation test: %v", err)
}
// Verify the release bundle reached COMPLETED status, then clean it up.
// The lifecycle service manager authenticates against serverDetails.LifecycleUrl, which is
// not derived from the platform URL automatically — populate it as the lifecycle CLI does.
rtLifecycle.PlatformToLifecycleUrls(serverDetails)
lcManager, err := artUtils.CreateLifecycleServiceManager(serverDetails, false)
if assert.NoError(t, err) {
rbDetails := lifecycleServices.ReleaseBundleDetails{
ReleaseBundleName: rbName,
ReleaseBundleVersion: rbVersion,
}
resp, statusErr := lcManager.GetReleaseBundleCreationStatus(rbDetails, "", true)
if assert.NoError(t, statusErr) {
assert.Equal(t, lifecycleServices.Completed, resp.Status,
"release bundle created from Alpine build-info should reach COMPLETED status")
}
_ = lcManager.DeleteReleaseBundleVersion(rbDetails, lifecycleServices.CommonOptionalQueryParams{Async: false})
}
}
// TestApkAdd_MultiplePackages verifies build-info when installing more than one
// package in a single invocation.
func TestApkAdd_MultiplePackages(t *testing.T) {
initApkTest(t)
if !apkAvailable() {
t.Skip("apk binary not found — test requires Alpine Linux.")
}
oldHomeDir, newHomeDir := prepareHomeDir(t)
defer func() {
clientTestUtils.SetEnvAndAssert(t, coreutils.HomeDir, oldHomeDir)
clientTestUtils.RemoveAllAndAssert(t, newHomeDir)
}()
buildName := tests.AlpineBuildName + "-add-multi"
buildNumber := "1"
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
err := jfrogCli.Exec("apk", "add", "wget", "jq",
"--build-name="+buildName, "--build-number="+buildNumber,
"--repo="+tests.AlpineVirtualRepo)
if err != nil {
t.Skipf("jf apk add failed: %v", err)
}
assert.NoError(t, artifactoryCli.Exec("bp", buildName, buildNumber))
publishedBuildInfo, found, err := tests.GetBuildInfo(serverDetails, buildName, buildNumber)
assert.NoError(t, err)
assert.True(t, found)
if found && len(publishedBuildInfo.BuildInfo.Modules) > 0 {
deps := publishedBuildInfo.BuildInfo.Modules[0].Dependencies
// wget + jq each pull in multiple transitive deps; at minimum 2 direct ones
assert.GreaterOrEqual(t, len(deps), 2,
"wget + jq should produce at least 2 direct dependencies")
}
inttestutils.DeleteBuild(serverDetails.ArtifactoryUrl, buildName, artHttpDetails)
}
// TestApkAdd_NoBuildFlags verifies that `jf apk add` without --build-name / --build-number
// still runs natively without a panic or crash.
func TestApkAdd_NoBuildFlags(t *testing.T) {
initApkTest(t)
if !apkAvailable() {
t.Skip("apk binary not found — test requires Alpine Linux.")
}
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
err := jfrogCli.Exec("apk", "add", "busybox")
if err != nil {
// busybox may already be installed; that's fine.
t.Logf("jf apk add busybox (no build flags): %v", err)
}
}
// ==================== jf apk upgrade (build info collection) ====================
// TestApkUpgrade_BuildInfo verifies that `jf apk upgrade` records build-info.
func TestApkUpgrade_BuildInfo(t *testing.T) {
initApkTest(t)
if !apkAvailable() {
t.Skip("apk binary not found — test requires Alpine Linux.")
}
oldHomeDir, newHomeDir := prepareHomeDir(t)
defer func() {
clientTestUtils.SetEnvAndAssert(t, coreutils.HomeDir, oldHomeDir)
clientTestUtils.RemoveAllAndAssert(t, newHomeDir)
}()
buildName := tests.AlpineBuildName + "-upgrade"
buildNumber := "1"
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
err := jfrogCli.Exec("apk", "upgrade",
"--build-name="+buildName, "--build-number="+buildNumber,
"--repo="+tests.AlpineVirtualRepo)
if err != nil {
t.Skipf("jf apk upgrade failed (no packages to upgrade or system unavailable): %v", err)
}
assert.NoError(t, artifactoryCli.Exec("bp", buildName, buildNumber))
publishedBuildInfo, found, err := tests.GetBuildInfo(serverDetails, buildName, buildNumber)
assert.NoError(t, err)
assert.True(t, found, "build-info should exist after jf apk upgrade")
if found {
require.Len(t, publishedBuildInfo.BuildInfo.Modules, 1)
assert.Equal(t, buildinfo.Apk, publishedBuildInfo.BuildInfo.Modules[0].Type)
}
inttestutils.DeleteBuild(serverDetails.ArtifactoryUrl, buildName, artHttpDetails)
}
// ==================== Module override ====================
// TestApkAdd_ModuleOverride verifies that --module overrides the module ID in build-info.
func TestApkAdd_ModuleOverride(t *testing.T) {
initApkTest(t)
if !apkAvailable() {
t.Skip("apk binary not found — test requires Alpine Linux.")
}
oldHomeDir, newHomeDir := prepareHomeDir(t)
defer func() {
clientTestUtils.SetEnvAndAssert(t, coreutils.HomeDir, oldHomeDir)
clientTestUtils.RemoveAllAndAssert(t, newHomeDir)
}()
buildName := tests.AlpineBuildName + "-module-override"
buildNumber := "1"
customModule := "my-custom-alpine-module"
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
err := jfrogCli.Exec("apk", "add", "curl",
"--build-name="+buildName, "--build-number="+buildNumber,
"--module="+customModule,
"--repo="+tests.AlpineVirtualRepo)
if err != nil {
t.Skipf("jf apk add failed: %v", err)
}
assert.NoError(t, artifactoryCli.Exec("bp", buildName, buildNumber))
publishedBuildInfo, found, err := tests.GetBuildInfo(serverDetails, buildName, buildNumber)
assert.NoError(t, err)
assert.True(t, found)
if found && len(publishedBuildInfo.BuildInfo.Modules) > 0 {
assert.Equal(t, customModule, publishedBuildInfo.BuildInfo.Modules[0].Id,
"module ID should be overridden to the custom value")
}
inttestutils.DeleteBuild(serverDetails.ArtifactoryUrl, buildName, artHttpDetails)
}
// ==================== Build-info JSON structure ====================
// TestApkAdd_BuildInfoJSON verifies the basic structure of the published build-info:
// correct name, number, started timestamp, module type, and non-empty dep IDs.
func TestApkAdd_BuildInfoJSON(t *testing.T) {
initApkTest(t)
if !apkAvailable() {
t.Skip("apk binary not found — test requires Alpine Linux.")
}
oldHomeDir, newHomeDir := prepareHomeDir(t)
defer func() {
clientTestUtils.SetEnvAndAssert(t, coreutils.HomeDir, oldHomeDir)
clientTestUtils.RemoveAllAndAssert(t, newHomeDir)
}()
buildName := tests.AlpineBuildName + "-bi-json"
buildNumber := "1"
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
err := jfrogCli.Exec("apk", "add", "jq",
"--build-name="+buildName, "--build-number="+buildNumber,
"--repo="+tests.AlpineVirtualRepo)
if err != nil {
t.Skipf("jf apk add failed: %v", err)
}
assert.NoError(t, artifactoryCli.Exec("bp", buildName, buildNumber))
publishedBuildInfo, found, err := tests.GetBuildInfo(serverDetails, buildName, buildNumber)
assert.NoError(t, err)
assert.True(t, found)
if found {
bi := publishedBuildInfo.BuildInfo
assert.Equal(t, buildName, bi.Name)
assert.Equal(t, buildNumber, bi.Number)
assert.NotEmpty(t, bi.Started, "build-info should have a Started timestamp")
require.Len(t, bi.Modules, 1)
assert.Equal(t, buildinfo.Apk, bi.Modules[0].Type)
for _, dep := range bi.Modules[0].Dependencies {
assert.NotEmpty(t, dep.Id, "dependency ID must not be empty")
}
}
inttestutils.DeleteBuild(serverDetails.ArtifactoryUrl, buildName, artHttpDetails)
}
// ==================== Dependency ID format ====================
// TestApkAdd_DepIDFormat verifies that every dependency ID is in the "name:version" format.
func TestApkAdd_DepIDFormat(t *testing.T) {
initApkTest(t)
if !apkAvailable() {
t.Skip("apk binary not found — test requires Alpine Linux.")
}
oldHomeDir, newHomeDir := prepareHomeDir(t)
defer func() {
clientTestUtils.SetEnvAndAssert(t, coreutils.HomeDir, oldHomeDir)
clientTestUtils.RemoveAllAndAssert(t, newHomeDir)
}()
buildName := tests.AlpineBuildName + "-dep-id-format"
buildNumber := "1"
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
err := jfrogCli.Exec("apk", "add", "curl",
"--build-name="+buildName, "--build-number="+buildNumber,
"--repo="+tests.AlpineVirtualRepo)
if err != nil {
t.Skipf("jf apk add failed: %v", err)
}
assert.NoError(t, artifactoryCli.Exec("bp", buildName, buildNumber))
publishedBuildInfo, found, err := tests.GetBuildInfo(serverDetails, buildName, buildNumber)
assert.NoError(t, err)
assert.True(t, found)
if found && len(publishedBuildInfo.BuildInfo.Modules) > 0 {
for _, dep := range publishedBuildInfo.BuildInfo.Modules[0].Dependencies {
assert.Contains(t, dep.Id, ":",
"dep ID should be 'name:version' format, got: %s", dep.Id)
}
}
inttestutils.DeleteBuild(serverDetails.ArtifactoryUrl, buildName, artHttpDetails)
}
// ==================== Dependency scopes ====================
// TestApkAdd_DepScopes verifies that directly-requested packages get scope "prod"
// and transitive packages get scope "transitive".
func TestApkAdd_DepScopes(t *testing.T) {
initApkTest(t)
if !apkAvailable() {
t.Skip("apk binary not found — test requires Alpine Linux.")
}
oldHomeDir, newHomeDir := prepareHomeDir(t)
defer func() {
clientTestUtils.SetEnvAndAssert(t, coreutils.HomeDir, oldHomeDir)
clientTestUtils.RemoveAllAndAssert(t, newHomeDir)
}()
buildName := tests.AlpineBuildName + "-dep-scopes"
buildNumber := "1"
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
// curl brings in transitive deps (libcurl, musl, etc.)
err := jfrogCli.Exec("apk", "add", "curl",
"--build-name="+buildName, "--build-number="+buildNumber,
"--repo="+tests.AlpineVirtualRepo)
if err != nil {
t.Skipf("jf apk add failed: %v", err)
}
assert.NoError(t, artifactoryCli.Exec("bp", buildName, buildNumber))
publishedBuildInfo, found, err := tests.GetBuildInfo(serverDetails, buildName, buildNumber)
assert.NoError(t, err)
assert.True(t, found)
if found && len(publishedBuildInfo.BuildInfo.Modules) > 0 {
deps := publishedBuildInfo.BuildInfo.Modules[0].Dependencies
hasProd := false
hasTransitive := false
for _, dep := range deps {
for _, scope := range dep.Scopes {
if scope == "prod" {
hasProd = true
}
if scope == "transitive" {
hasTransitive = true
}
}
}
assert.True(t, hasProd, "at least one dependency should have scope 'prod'")
if len(deps) > 1 {
assert.True(t, hasTransitive,
"%d dependencies were recorded for a single requested package, so at least one should have scope 'transitive'",
len(deps))
} else {
t.Logf("only %d dependency recorded — curl's own dependencies were already installed, "+
"so the transitive scope cannot be validated", len(deps))
}
}
inttestutils.DeleteBuild(serverDetails.ArtifactoryUrl, buildName, artHttpDetails)
}
// ==================== Dependency checksums ====================
func TestApkAdd_DepChecksums(t *testing.T) {
initApkTest(t)
if !apkAvailable() {
t.Skip("apk binary not found — test requires Alpine Linux.")
}
oldHomeDir, newHomeDir := prepareHomeDir(t)
defer func() {
clientTestUtils.SetEnvAndAssert(t, coreutils.HomeDir, oldHomeDir)
clientTestUtils.RemoveAllAndAssert(t, newHomeDir)
}()
buildName := tests.AlpineBuildName + "-dep-checksums"
buildNumber := "1"
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
err := jfrogCli.Exec("apk", "add", "curl",
"--build-name="+buildName, "--build-number="+buildNumber,
"--repo="+tests.AlpineVirtualRepo)
if err != nil {
t.Skipf("jf apk add failed: %v", err)
}
assert.NoError(t, artifactoryCli.Exec("bp", buildName, buildNumber))
publishedBuildInfo, found, err := tests.GetBuildInfo(serverDetails, buildName, buildNumber)
assert.NoError(t, err)
assert.True(t, found)
if found && len(publishedBuildInfo.BuildInfo.Modules) > 0 {
deps := publishedBuildInfo.BuildInfo.Modules[0].Dependencies
depsWithChecksums, depsWithSha1, depsWithSha256, depsWithMd5 := 0, 0, 0, 0
for _, dep := range deps {
if dep.Sha1 != "" {
depsWithSha1++
}
if dep.Sha256 != "" {
depsWithSha256++
}
if dep.Md5 != "" {
depsWithMd5++
}
if dep.Sha1 != "" || dep.Sha256 != "" || dep.Md5 != "" {
depsWithChecksums++
}
}
t.Logf("Dependencies with checksums out of %d: any=%d sha1=%d sha256=%d md5=%d",
len(deps), depsWithChecksums, depsWithSha1, depsWithSha256, depsWithMd5)
assert.Greater(t, depsWithChecksums, 0, "at least one dep should have a checksum")
assert.Greater(t, depsWithSha1, 0, "at least one dep should have a SHA1 checksum")
assert.Greater(t, depsWithSha256, 0, "at least one dep should have a SHA256 checksum")
assert.Greater(t, depsWithMd5, 0, "at least one dep should have an MD5 checksum")
}
inttestutils.DeleteBuild(serverDetails.ArtifactoryUrl, buildName, artHttpDetails)
}
// ==================== requestedBy chains ====================
// TestApkAdd_DepRequestedBy verifies that transitive dependencies carry non-empty RequestedBy.
func TestApkAdd_DepRequestedBy(t *testing.T) {
initApkTest(t)
if !apkAvailable() {
t.Skip("apk binary not found — test requires Alpine Linux.")
}
oldHomeDir, newHomeDir := prepareHomeDir(t)
defer func() {
clientTestUtils.SetEnvAndAssert(t, coreutils.HomeDir, oldHomeDir)
clientTestUtils.RemoveAllAndAssert(t, newHomeDir)
}()
buildName := tests.AlpineBuildName + "-requestedby"
buildNumber := "1"
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
// curl has libcurl as a transitive dep, which should carry RequestedBy=[["curl:..."]]
err := jfrogCli.Exec("apk", "add", "curl",
"--build-name="+buildName, "--build-number="+buildNumber,
"--repo="+tests.AlpineVirtualRepo)
if err != nil {
t.Skipf("jf apk add failed: %v", err)
}
assert.NoError(t, artifactoryCli.Exec("bp", buildName, buildNumber))
publishedBuildInfo, found, err := tests.GetBuildInfo(serverDetails, buildName, buildNumber)
assert.NoError(t, err)
assert.True(t, found)
if found && len(publishedBuildInfo.BuildInfo.Modules) > 0 {
deps := publishedBuildInfo.BuildInfo.Modules[0].Dependencies
if len(deps) <= 1 {
t.Skip("only one dep installed; transitive RequestedBy cannot be validated")
}
curlID := ""
for _, dep := range deps {
if strings.HasPrefix(dep.Id, "curl:") {
curlID = dep.Id
break
}
}
require.NotEmpty(t, curlID, "the requested package curl should be recorded as a dependency")
transitiveWithParent := 0
for _, dep := range deps {
if dep.Id == curlID {
continue
}
if len(dep.RequestedBy) == 0 {
continue
}
for _, chain := range dep.RequestedBy {
require.NotEmpty(t, chain, "RequestedBy chain should not be empty for %s", dep.Id)
assert.Equal(t, curlID, chain[len(chain)-1],
"RequestedBy chain of %s should end at the requested package %s, got %v",
dep.Id, curlID, chain)
assert.NotContains(t, chain, dep.Id,
"RequestedBy chain of %s should not contain the dependency itself: %v", dep.Id, chain)
}
transitiveWithParent++
}
assert.Greater(t, transitiveWithParent, 0,
"at least one transitive dep should have a RequestedBy chain rooted at %s", curlID)
}
inttestutils.DeleteBuild(serverDetails.ArtifactoryUrl, buildName, artHttpDetails)
}
// ==================== Multiple builds isolation ====================
// TestApkAdd_MultipleBuildsIsolated verifies that two sequential `jf apk add` calls with
// different build numbers produce independent build-info records.
func TestApkAdd_MultipleBuildsIsolated(t *testing.T) {
initApkTest(t)
if !apkAvailable() {
t.Skip("apk binary not found — test requires Alpine Linux.")
}
oldHomeDir, newHomeDir := prepareHomeDir(t)
defer func() {
clientTestUtils.SetEnvAndAssert(t, coreutils.HomeDir, oldHomeDir)
clientTestUtils.RemoveAllAndAssert(t, newHomeDir)
}()
buildName := tests.AlpineBuildName + "-multi-isolated"
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
err := jfrogCli.Exec("apk", "add", "curl",
"--build-name="+buildName, "--build-number=1",
"--repo="+tests.AlpineVirtualRepo)
if err != nil {
t.Skipf("jf apk add (build 1) failed: %v", err)
}
assert.NoError(t, artifactoryCli.Exec("bp", buildName, "1"))
err = jfrogCli.Exec("apk", "add", "jq",
"--build-name="+buildName, "--build-number=2",
"--repo="+tests.AlpineVirtualRepo)
if err != nil {
t.Skipf("jf apk add (build 2) failed: %v", err)
}
assert.NoError(t, artifactoryCli.Exec("bp", buildName, "2"))
bi1, found1, err := tests.GetBuildInfo(serverDetails, buildName, "1")
assert.NoError(t, err)
assert.True(t, found1, "build 1 should be found")
bi2, found2, err := tests.GetBuildInfo(serverDetails, buildName, "2")
assert.NoError(t, err)
assert.True(t, found2, "build 2 should be found")
if found1 && found2 {
assert.NotEqual(t,
bi1.BuildInfo.Modules[0].Dependencies,
bi2.BuildInfo.Modules[0].Dependencies,
"build 1 (curl) and build 2 (jq) should have different dependency sets")
}
inttestutils.DeleteBuild(serverDetails.ArtifactoryUrl, buildName, artHttpDetails)
}
// ==================== Passthrough commands (no build info) ====================
// TestApkPassthroughCommands verifies that every apk sub-command that does not
// produce build-info (update, del, info, search, fetch, fix, audit, version, stats)
// is forwarded to the native apk binary without panicking.
// Each case also confirms that passing --build-name/--build-number does NOT result
// in build-info being published — these commands are read-only or destructive, not
// installation events.
func TestApkPassthroughCommands(t *testing.T) {
initApkTest(t)
if !apkAvailable() {
t.Skip("apk binary not found — test requires Alpine Linux.")
}
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
cases := []struct {
name string
args []string
}{
{"update", []string{"apk", "update"}},
{"update-with-build-flags", []string{"apk", "update", "--build-name=" + tests.AlpineBuildName + "-pt", "--build-number=1"}},
{"del", []string{"apk", "del", "curl", "--build-name=" + tests.AlpineBuildName + "-pt", "--build-number=1"}},
{"info", []string{"apk", "info", "musl"}},
{"search", []string{"apk", "search", "curl"}},
{"fix", []string{"apk", "fix"}},
{"audit", []string{"apk", "audit"}},
{"version", []string{"apk", "version"}},
{"stats", []string{"apk", "stats"}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
// A non-zero exit is acceptable (e.g. nothing to fix, package absent);
// what must not happen is a panic or an unknown-flag error caused by
// JFrog CLI flags leaking into the native apk invocation.
err := jfrogCli.Exec(tc.args...)
if err != nil {
t.Logf("jf %v: %v (non-zero exit is acceptable for passthrough)", tc.args, err)
}
})
}
}
// ==================== jf apk config ====================
// TestApkConfig_SetsUpRepo verifies that `jf apk config` runs without error when the
// Artifactory repo key and server details are valid.
// Note: this test requires write access to /etc/apk/repositories (root on Alpine).
func TestApkConfig_SetsUpRepo(t *testing.T) {
initApkTest(t)
if !apkAvailable() {
t.Skip("apk binary not found — test requires Alpine Linux.")
}
if os.Getuid() != 0 {
t.Skip("jf apk config modifies /etc/apk/repositories and requires root.")
}
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
err := jfrogCli.Exec("apk", "config",
"--server-id=default",
"--repo="+tests.AlpineVirtualRepo)
if err != nil {
t.Logf("jf apk config: %v (Artifactory may not be reachable or missing RSA key)", err)
}
}
// TestApkConfig_UnknownServerID verifies that jf apk config with an unknown
// --server-id returns a clear error rather than silently continuing.
func TestApkConfig_UnknownServerID(t *testing.T) {
initApkTest(t)
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
err := jfrogCli.Exec("apk", "config",
"--server-id=nonexistent-server-id-xyz",
"--repo="+tests.AlpineVirtualRepo)
assert.Error(t, err, "jf apk config with an unknown --server-id should return a clear error")
}
// ==================== jf setup apk ====================
// TestSetupApk_WithRepoSkipsPromptAndConfigures verifies that `jf setup apk --repo <repo>`
// validates the repo, skips the interactive repo-type/repo selection, and appends the
// given Artifactory Alpine repository to /etc/apk/repositories with the credentials
// embedded in the URL so native apk can authenticate without HTTP_AUTH. Existing lines
// (public mirrors included) are left untouched — setup apk only ever appends.
// The file must also be locked to 0600 because it now stores a secret.
// Note: setup apk writes to /etc/apk/* and therefore requires root on Alpine.
func TestSetupApk_WithRepoSkipsPromptAndConfigures(t *testing.T) {
initApkTest(t)
if !apkAvailable() {
t.Skip("apk binary not found — test requires Alpine Linux.")
}
if os.Getuid() != 0 {
t.Skip("jf setup apk modifies /etc/apk/repositories and requires root.")
}
// Configure the 'default' server so --server-id=default resolves an Artifactory URL.
oldHomeDir, newHomeDir := prepareHomeDir(t)
defer func() {
clientTestUtils.SetEnvAndAssert(t, coreutils.HomeDir, oldHomeDir)
clientTestUtils.RemoveAllAndAssert(t, newHomeDir)
}()
const apkRepositoriesFile = "/etc/apk/repositories"
// Back up the current repositories file and restore it after the test.
original, readErr := os.ReadFile(apkRepositoriesFile)
if readErr != nil && !os.IsNotExist(readErr) {
t.Fatalf("failed to read %s: %v", apkRepositoriesFile, readErr)
}
defer func() {
if original != nil {
// #nosec G703 -- apkRepositoriesFile is a hardcoded constant, not user input
require.NoError(t, os.WriteFile(apkRepositoriesFile, original, 0644))
}
}()
// With --repo supplied, setup must not prompt for a repo type or repo selection;
// a non-interactive run reaching completion confirms the prompt was skipped.
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
err := jfrogCli.Exec("setup", "apk",
"--server-id=default",
"--repo="+tests.AlpineVirtualRepo)
require.NoError(t, err, "jf setup apk --repo should succeed for an existing repo without prompting")
// The repositories file should now reference the configured Artifactory repo.
content, err := os.ReadFile(apkRepositoriesFile)
require.NoError(t, err)
assert.Contains(t, string(content), tests.AlpineVirtualRepo,
"/etc/apk/repositories should contain the configured Artifactory Alpine repo")
// setup apk only appends the Artifactory repo — it never rewrites or removes
// existing lines (public mirrors like dl-cdn included), so apk keeps working
// against whatever the user already had configured.
// The configured Artifactory line must carry embedded credentials (userinfo "@")
// so native apk authenticates directly from the file without HTTP_AUTH.
var artifactoryLine string
for _, line := range strings.Split(string(content), "\n") {
if strings.Contains(line, "/artifactory/") && strings.Contains(line, tests.AlpineVirtualRepo) {
artifactoryLine = strings.TrimSpace(line)
break
}
}
require.NotEmpty(t, artifactoryLine, "expected an Artifactory repo line in %s", apkRepositoriesFile)
parsed, parseErr := url.Parse(artifactoryLine)
require.NoError(t, parseErr, "the configured repo URL should be parseable")
assert.NotNil(t, parsed.User,
"the configured repo URL should embed credentials in its userinfo component")
if user := parsed.User; user != nil {
assert.NotEmpty(t, user.Username(),
"the embedded userinfo should contain a username")
}
// Because the file now stores a secret, it must be locked down to 0600.
info, statErr := os.Stat(apkRepositoriesFile)
require.NoError(t, statErr)
assert.Equal(t, os.FileMode(0600), info.Mode().Perm(),
"/etc/apk/repositories must be 0600 since it embeds credentials")
}
// TestSetupApk_InvalidRepoFails verifies that `jf setup apk` with a repository that does not
// exist in Artifactory fails fast during repo validation, before touching /etc/apk.
func TestSetupApk_InvalidRepoFails(t *testing.T) {
initApkTest(t)
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
err := jfrogCli.Exec("setup", "apk",
"--server-id=default",
"--repo=nonexistent-alpine-repo-xyz-12345")
assert.Error(t, err, "jf setup apk with a nonexistent --repo should fail during validation")
}
// ==================== P0: package not found ====================
// TestApkAdd_PackageNotFound verifies that jf apk add with a package that does
// not exist in Artifactory returns a clear error and does not silently fall back
// to the public Alpine CDN.
func TestApkAdd_PackageNotFound(t *testing.T) {
initApkTest(t)
if !apkAvailable() {
t.Skip("apk binary not found — test requires Alpine Linux.")
}
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
err := jfrogCli.Exec("apk", "add", "nonexistent-pkg-xyz-jfrog-test-12345",
"--repo="+tests.AlpineVirtualRepo,
"--build-name="+tests.AlpineBuildName+"-pkg-not-found",
"--build-number=1")
assert.Error(t, err,
"jf apk add with a nonexistent package should fail, not silently succeed or fall back to CDN")
}
// ==================== P0: checksum stored in Artifactory ====================
// TestApkUpload_ChecksumNotUntrusted verifies that after jf apk upload the
// artifact stored in Artifactory has a non-empty, non-"untrusted" SHA256
// checksum. Artifactory marks artifacts as "untrusted" when upload does not
// supply X-Checksum headers — this test catches that integration gap.
func TestApkUpload_ChecksumNotUntrusted(t *testing.T) {
initApkTest(t)
tmpDir, err := os.MkdirTemp("", "apk-chksum-stored-*")
if err != nil {
t.Fatalf("failed to create temp dir: %v", err)
}
defer clientTestUtils.RemoveAllAndAssert(t, tmpDir)
fakePkgInfo := "pkgname = testpkg-chksum\npkgver = 1.0.0-r0\narch = x86_64\n"
if writeErr := os.WriteFile(tmpDir+"/.PKGINFO", []byte(fakePkgInfo), 0644); writeErr != nil {
t.Fatalf("failed to write .PKGINFO: %v", writeErr)
}
apkPath := tmpDir + "/testpkg-chksum-1.0.0-r0.apk"
if tarErr := exec.Command("tar", "-czf", apkPath, "-C", tmpDir, ".PKGINFO").Run(); tarErr != nil {
t.Skipf("tar not available to build test .apk: %v", tarErr)
}
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
if uploadErr := jfrogCli.Exec("apk", "upload", apkPath, "--repo="+tests.AlpineLocalRepo); uploadErr != nil {
t.Skipf("jf apk upload failed: %v", uploadErr)
}
// Search Artifactory for the uploaded artifact and verify the stored sha256.
searchSpec := spec.NewBuilder().Pattern(tests.AlpineLocalRepo + "/testpkg-chksum-1.0.0-r0.apk").BuildSpec()
searchCmd := generic.NewSearchCommand()
searchCmd.SetServerDetails(serverDetails).SetSpec(searchSpec)
reader, searchErr := searchCmd.Search()
require.NoError(t, searchErr, "AQL search for uploaded artifact should succeed")
defer func() { _ = reader.Close() }()
item := new(artUtils.SearchResult)
require.NoError(t, reader.NextRecord(item),
"uploaded artifact must be found in Artifactory — jf apk upload may have failed silently")
assert.NotEmpty(t, item.Sha256,
"Artifactory must store a sha256 checksum for the uploaded .apk artifact")
assert.NotEqual(t, "untrusted", strings.ToLower(item.Sha256),
"Artifactory must not mark the .apk artifact as 'untrusted' — X-Checksum headers may be missing on upload")
}
// ==================== jf apk upload ====================
// TestApkUpload_LocalApkFile verifies that `jf apk upload` can upload a real .apk file
// to Artifactory. The test creates a minimal (but valid enough) .apk archive.
func TestApkUpload_LocalApkFile(t *testing.T) {
initApkTest(t)
if !apkAvailable() {
t.Skip("apk binary not found — test requires Alpine Linux.")
}
tmpDir, err := os.MkdirTemp("", "apk-upload-*")
if err != nil {
t.Fatalf("failed to create temp dir: %v", err)
}
defer clientTestUtils.RemoveAllAndAssert(t, tmpDir)
// Build a minimal .apk (tgz containing just a PKGINFO) via abuild-tar or tar.
// If abuild-tar is not available, skip gracefully.
fakePkgInfo := "pkgname = testpkg\npkgver = 1.0.0-r0\narch = x86_64\n"
pkgInfoPath := tmpDir + "/.PKGINFO"
if writeErr := os.WriteFile(pkgInfoPath, []byte(fakePkgInfo), 0644); writeErr != nil {
t.Fatalf("failed to write .PKGINFO: %v", writeErr)
}
apkFilePath := fmt.Sprintf("%s/testpkg-1.0.0-r0.apk", tmpDir)
// Create a minimal tar.gz containing the PKGINFO
tarCmd := exec.Command("tar", "-czf", apkFilePath, "-C", tmpDir, ".PKGINFO")
if tarOut, tarErr := tarCmd.CombinedOutput(); tarErr != nil {
t.Skipf("failed to create fake .apk archive with tar: %v\n%s", tarErr, tarOut)
}
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
err = jfrogCli.Exec("apk", "upload", apkFilePath,
"--repo="+tests.AlpineLocalRepo,
"--alpine-version=3.18",
"--server-id=default")
if err != nil {
t.Logf("jf apk upload: %v (Artifactory may not accept the synthetic .apk)", err)
}
}
// TestApkUpload_ArchAutoDetectedFromPkgInfo verifies that when --arch is omitted,
// `jf apk upload` reads the architecture from the package's embedded .PKGINFO and
// uploads the artifact under that arch path segment. The .PKGINFO declares aarch64
// (deliberately different from the typical x86_64 CI host) so a match proves the arch
// came from the package metadata, not the uploading machine.
func TestApkUpload_ArchAutoDetectedFromPkgInfo(t *testing.T) {
initApkTest(t)
// Configure the 'default' server so --server-id=default resolves for upload.
oldHomeDir, newHomeDir := prepareHomeDir(t)
defer func() {
clientTestUtils.SetEnvAndAssert(t, coreutils.HomeDir, oldHomeDir)
clientTestUtils.RemoveAllAndAssert(t, newHomeDir)
}()
tmpDir, err := os.MkdirTemp("", "apk-arch-detect-*")
if err != nil {
t.Fatalf("failed to create temp dir: %v", err)
}
defer clientTestUtils.RemoveAllAndAssert(t, tmpDir)
const pkgArch = "aarch64"
fakePkgInfo := "pkgname = testpkg-archdetect\npkgver = 1.0.0-r0\narch = " + pkgArch + "\n"
if writeErr := os.WriteFile(tmpDir+"/.PKGINFO", []byte(fakePkgInfo), 0644); writeErr != nil {
t.Fatalf("failed to write .PKGINFO: %v", writeErr)
}
apkPath := tmpDir + "/testpkg-archdetect-1.0.0-r0.apk"
if tarErr := exec.Command("tar", "-czf", apkPath, "-C", tmpDir, ".PKGINFO").Run(); tarErr != nil {
t.Skipf("tar not available to build test .apk: %v", tarErr)
}
// Upload WITHOUT --arch: the command must auto-detect aarch64 from .PKGINFO.
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
if uploadErr := jfrogCli.Exec("apk", "upload", apkPath,
"--repo="+tests.AlpineLocalRepo,
"--alpine-version=3.18",
"--server-id=default"); uploadErr != nil {
t.Skipf("jf apk upload failed: %v", uploadErr)
}
// The artifact must be stored under the aarch64 path segment derived from .PKGINFO.
searchSpec := spec.NewBuilder().
Pattern(tests.AlpineLocalRepo + "/*/" + pkgArch + "/testpkg-archdetect-1.0.0-r0.apk").
BuildSpec()
searchCmd := generic.NewSearchCommand()
searchCmd.SetServerDetails(serverDetails).SetSpec(searchSpec)
reader, searchErr := searchCmd.Search()
require.NoError(t, searchErr, "AQL search for uploaded artifact should succeed")
defer func() { _ = reader.Close() }()
item := new(artUtils.SearchResult)
require.NoError(t, reader.NextRecord(item),
"artifact must be found under the aarch64 path — arch was not auto-detected from .PKGINFO")
assert.Contains(t, item.Path, "/"+pkgArch+"/",
"uploaded artifact path must contain the arch auto-detected from .PKGINFO")