-
Notifications
You must be signed in to change notification settings - Fork 303
Expand file tree
/
Copy pathagent_plugins_test.go
More file actions
3757 lines (3283 loc) · 133 KB
/
Copy pathagent_plugins_test.go
File metadata and controls
3757 lines (3283 loc) · 133 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 (
"archive/zip"
"bytes"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"sync"
"testing"
"time"
biutils "github.com/jfrog/build-info-go/utils"
agentTestutil "github.com/jfrog/jfrog-cli-artifactory/agent/common/testutil"
plugincommon "github.com/jfrog/jfrog-cli-artifactory/agent/plugins/common"
"github.com/jfrog/jfrog-cli-artifactory/artifactory/commands/generic"
artUtils "github.com/jfrog/jfrog-cli-core/v2/artifactory/utils"
coreBuild "github.com/jfrog/jfrog-cli-core/v2/common/build"
"github.com/jfrog/jfrog-cli-core/v2/common/spec"
coretests "github.com/jfrog/jfrog-cli-core/v2/utils/tests"
"github.com/jfrog/jfrog-cli-evidence/evidence/cryptox"
"github.com/jfrog/jfrog-cli-evidence/evidence/generate"
"github.com/jfrog/jfrog-client-go/utils/log"
clientTestUtils "github.com/jfrog/jfrog-client-go/utils/tests"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/jfrog/jfrog-cli/inttestutils"
"github.com/jfrog/jfrog-cli/utils/tests"
)
// ---------------------------------------------------------------------------
// Init / cleanup
// ---------------------------------------------------------------------------
func InitAgentPluginsTests() {
initArtifactoryCli()
cleanUpOldRepositories()
tests.AddTimestampToGlobalVars()
createRequiredRepos()
}
func CleanAgentPluginsTests() {
deleteCreatedRepos()
}
func initAgentPluginsTest(t *testing.T) {
if !*tests.TestAgentPlugins {
t.Skip("Skipping Agent Plugins test. To run Agent Plugins test add the '-test.agentPlugins=true' option.")
}
createJfrogHomeConfig(t, false)
require.True(t, isRepoExist(tests.AgentPluginsLocalRepo), "agent plugins local repo does not exist: "+tests.AgentPluginsLocalRepo)
// The test Artifactory instance has no evidence/One-Model service configured.
// Disable the quiet-failure evidence gate so install commands don't block on 403.
t.Setenv("JFROG_AGENT_PLUGINS_DISABLE_QUIET_FAILURE", "true")
stubNativeAgentCLIs(t)
}
func cleanAgentPluginsTest() {
inttestutils.DeleteBuild(serverDetails.ArtifactoryUrl, tests.AgentPluginsBuildName, artHttpDetails)
tests.CleanFileSystem()
}
// runAgentPluginsCmd executes `jf agent plugins <args...>`.
func runAgentPluginsCmd(t *testing.T, args ...string) error {
t.Helper()
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
return jfrogCli.Exec(append([]string{"agent", "plugins"}, args...)...)
}
// runAgentPluginsCmdWithOutput executes `jf agent plugins <args...>` and returns captured stdout.
func runAgentPluginsCmdWithOutput(t *testing.T, args ...string) (string, error) {
t.Helper()
jfrogCli := coretests.NewJfrogCli(execMain, "jfrog", "")
return jfrogCli.RunCliCmdWithOutputs(t, append([]string{"agent", "plugins"}, args...)...)
}
// assertErrorContainsAll requires a non-nil error whose message contains every substring.
// Prefer this over loose OR-chains (e.g. "repo" || "405") that pass on unrelated failures.
func assertErrorContainsAll(t *testing.T, err error, substrings ...string) {
t.Helper()
require.Error(t, err)
msg := err.Error()
for _, sub := range substrings {
assert.Contains(t, msg, sub, "error %q should contain %q", msg, sub)
}
}
// recreateAgentPluginsLocalRepo recreates the e2e agentplugins repository after a temporary delete.
func recreateAgentPluginsLocalRepo(t *testing.T) {
t.Helper()
repoConfig := tests.GetTestResourcesPath() + tests.AgentPluginsLocalRepositoryConfig
repoConfig, err := tests.ReplaceTemplateVariables(repoConfig, "")
require.NoError(t, err)
execCreateRepoRest(repoConfig, tests.AgentPluginsLocalRepo)
require.True(t, isRepoExist(tests.AgentPluginsLocalRepo),
"agent plugins local repo must exist after recreate: "+tests.AgentPluginsLocalRepo)
}
// createTestPlugin copies the test-plugin fixture to a fresh temp dir and patches
// plugin.json with the given slug and version so tests don't conflict.
func createTestPlugin(t *testing.T, slug, version string) string {
t.Helper()
pluginSrc := filepath.Join(filepath.FromSlash(tests.GetTestResourcesPath()), "agent_plugins", "test-plugin")
pluginPath, cleanup := coretests.CreateTempDirWithCallbackAndAssert(t)
t.Cleanup(cleanup)
require.NoError(t, biutils.CopyDir(pluginSrc, pluginPath, true, nil))
manifest := map[string]any{
"name": slug,
"version": version,
"description": "Integration test plugin",
"skills": []string{},
}
data, err := json.Marshal(manifest)
require.NoError(t, err)
require.NoError(t, os.WriteFile(filepath.Join(pluginPath, "plugin.json"), data, 0644)) // #nosec G306 -- test fixture
return pluginPath
}
// assertPluginExists verifies the zip for slug/version is present in the local repo.
func assertPluginExists(t *testing.T, slug, version string) {
t.Helper()
sm, err := artUtils.CreateServiceManager(serverDetails, -1, 0, false)
require.NoError(t, err)
_, err = sm.GetItemProps(pluginArtifactPath(tests.AgentPluginsLocalRepo, slug, version))
require.NoError(t, err, "artifact should exist: %s v%s", slug, version)
}
// assertPluginAbsent verifies the zip for slug/version is gone from the local repo.
// A search-based check gives a cleaner absence assertion without relying on error message text.
func assertPluginAbsent(t *testing.T, slug, version string) {
t.Helper()
path := pluginArtifactPath(tests.AgentPluginsLocalRepo, slug, version)
searchSpec := spec.NewBuilder().Pattern(path).BuildSpec()
searchCmd := generic.NewSearchCommand()
searchCmd.SetServerDetails(serverDetails).SetSpec(searchSpec)
reader, err := searchCmd.Search()
require.NoError(t, err, "search for absent artifact failed")
// Read-side Close: search reader has no write flush; nothing actionable on failure.
defer func() { _ = reader.Close() }()
var found bool
for item := new(artUtils.SearchResult); reader.NextRecord(item) == nil; item = new(artUtils.SearchResult) {
found = true
break
}
assert.False(t, found, "artifact should not exist: %s v%s", slug, version)
}
// pluginArtifactPath returns the Artifactory path for a published plugin zip:
// <repo>/<slug>/<version>/<slug>-<version>.zip
func pluginArtifactPath(repo, slug, version string) string {
return repo + "/" + slug + "/" + version + "/" + slug + "-" + version + ".zip"
}
// ---------------------------------------------------------------------------
// Harness helpers
// ---------------------------------------------------------------------------
// agentPluginHarnessCase is one of the four required harness conditions:
// claude, codex, cursor, and combined claude,codex,cursor.
type agentPluginHarnessCase struct {
name string
harnesses []string
}
func agentPluginHarnessCases() []agentPluginHarnessCase {
return []agentPluginHarnessCase{
{name: "claude", harnesses: []string{"claude"}},
{name: "codex", harnesses: []string{"codex"}},
{name: "cursor", harnesses: []string{"cursor"}},
{name: "claude,codex,cursor", harnesses: []string{"claude", "codex", "cursor"}},
}
}
func harnessFlag(harnesses []string) string {
return strings.Join(harnesses, ",")
}
// globalPluginInstallDir returns the current global install destination for a built-in harness.
// claude/codex use repo-keyed layout under .../local/jfrog/<repo>/<slug>;
// cursor installs under ~/.cursor/plugins/local/<slug>.
func globalPluginInstallDir(homeDir, harness, repoKey, slug string) string {
switch strings.ToLower(harness) {
case "claude":
return filepath.Join(homeDir, ".claude", "plugins", "local", "jfrog", repoKey, slug)
case "codex":
return filepath.Join(homeDir, ".agents", "plugins", "local", "jfrog", repoKey, slug)
case "cursor":
return filepath.Join(homeDir, ".cursor", "plugins", "local", slug)
default:
return filepath.Join(homeDir, "."+harness, "plugins", slug)
}
}
// assertPluginsInstalledGlobally checks each harness install directory and plugin-info.json.
// When wantVersion is set, also asserts installedVersion, slug, agent, and repo fields.
func assertPluginsInstalledGlobally(t *testing.T, homeDir string, harnesses []string, slug string, wantVersion ...string) {
t.Helper()
version := ""
if len(wantVersion) > 0 {
version = wantVersion[0]
}
for _, harness := range harnesses {
path := globalPluginInstallDir(homeDir, harness, tests.AgentPluginsLocalRepo, slug)
assert.DirExists(t, path, "plugin %q should be installed for harness %q at %s", slug, harness, path)
manifestPath := filepath.Join(path, ".jfrog", "plugin-info.json")
assert.FileExists(t, manifestPath, "plugin-info.json should exist for harness %q", harness)
if version == "" {
continue
}
data, err := os.ReadFile(manifestPath) // #nosec G304 -- path under t.TempDir
require.NoError(t, err)
var manifest map[string]any
require.NoError(t, json.Unmarshal(data, &manifest))
assert.Equal(t, version, manifest["installedVersion"], "installedVersion for harness %q", harness)
assert.Equal(t, slug, manifest["slug"], "slug for harness %q", harness)
assert.Equal(t, harness, manifest["agent"], "agent for harness %q", harness)
assert.Equal(t, tests.AgentPluginsLocalRepo, manifest["repo"], "repo for harness %q", harness)
}
}
func setIsolatedHome(t *testing.T) string {
t.Helper()
homeDir := t.TempDir()
t.Setenv("HOME", homeDir)
t.Setenv("USERPROFILE", homeDir)
return homeDir
}
// createTestHarnessPlugin creates a plugin fixture with .<harness>-plugin/plugin.json for each harness.
func createTestHarnessPlugin(t *testing.T, slug, version string, harnesses []string) string {
t.Helper()
pluginPath, cleanup := coretests.CreateTempDirWithCallbackAndAssert(t)
t.Cleanup(cleanup)
for _, harness := range harnesses {
harnessDir := filepath.Join(pluginPath, "."+harness+"-plugin")
require.NoError(t, os.MkdirAll(harnessDir, 0755)) // #nosec G301 -- test directory
manifest := map[string]any{
"name": slug,
"version": version,
"description": fmt.Sprintf("Integration test plugin for %s", harness),
"skills": []string{},
}
data, err := json.Marshal(manifest)
require.NoError(t, err)
require.NoError(t, os.WriteFile(filepath.Join(harnessDir, "plugin.json"), data, 0644)) // #nosec G306 -- test fixture
}
return pluginPath
}
// nativeAgentStubOnce builds the shared claude/codex stub binary once per process.
// stubNativeAgentCLIs copies that binary into each test's PATH dir so we avoid
// recompiling on every initAgentPluginsTest (~99 times across the suite).
var (
nativeAgentStubOnce sync.Once
nativeAgentStubData []byte
nativeAgentStubErr error
)
func nativeAgentStubBinary() ([]byte, error) {
nativeAgentStubOnce.Do(func() {
srcDir, err := os.MkdirTemp("", "jf-agent-plugins-native-stub-src-*")
if err != nil {
nativeAgentStubErr = err
return
}
defer func() { _ = os.RemoveAll(srcDir) }() // best-effort teardown of compile workspace
if err := os.WriteFile(filepath.Join(srcDir, "go.mod"), []byte("module nativeagentstub\n\ngo 1.22\n"), 0644); err != nil { // #nosec G306 -- test fixture
nativeAgentStubErr = err
return
}
if err := os.WriteFile(filepath.Join(srcDir, "main.go"), []byte(nativeAgentCLIStubSource), 0644); err != nil { // #nosec G306 -- test fixture
nativeAgentStubErr = err
return
}
outBin := filepath.Join(srcDir, "claude")
if runtime.GOOS == "windows" {
outBin += ".exe"
}
build := exec.Command("go", "build", "-o", outBin, ".") // #nosec G204 -- fixed go build of local stub sources
build.Dir = srcDir
out, err := build.CombinedOutput()
if err != nil {
nativeAgentStubErr = fmt.Errorf("building claude stub failed: %w: %s", err, string(out))
return
}
nativeAgentStubData, nativeAgentStubErr = os.ReadFile(outBin) // #nosec G304 -- path under MkdirTemp
})
return nativeAgentStubData, nativeAgentStubErr
}
// stubNativeAgentCLIs installs cross-platform stub claude/codex binaries on PATH and wires
// LookPath/Exec hooks so install/list/update do not depend on real native CLIs.
func stubNativeAgentCLIs(t *testing.T) {
t.Helper()
data, err := nativeAgentStubBinary()
require.NoError(t, err)
binDir := t.TempDir()
claudeBin := filepath.Join(binDir, "claude")
codexBin := filepath.Join(binDir, "codex")
if runtime.GOOS == "windows" {
claudeBin += ".exe"
codexBin += ".exe"
}
require.NoError(t, os.WriteFile(claudeBin, data, 0755)) // #nosec G306 -- test stub binary path is under t.TempDir
require.NoError(t, os.WriteFile(codexBin, data, 0755)) // #nosec G306 -- test stub binary path is under t.TempDir
prevPath := os.Getenv("PATH")
t.Setenv("PATH", binDir+string(os.PathListSeparator)+prevPath)
prevLookClaude := plugincommon.LookPathClaude
prevLookCodex := plugincommon.LookPathCodex
prevClaudeExec := plugincommon.ClaudeExec
prevCodexExec := plugincommon.CodexExec
t.Cleanup(func() {
plugincommon.LookPathClaude = prevLookClaude
plugincommon.LookPathCodex = prevLookCodex
plugincommon.ClaudeExec = prevClaudeExec
plugincommon.CodexExec = prevCodexExec
})
plugincommon.LookPathClaude = func() (string, error) { return claudeBin, nil }
plugincommon.LookPathCodex = func() (string, error) { return codexBin, nil }
plugincommon.ClaudeExec = func(args ...string) error {
return exec.Command(claudeBin, args...).Run() // #nosec G204 -- test stub binary
}
plugincommon.CodexExec = func(args ...string) error {
return exec.Command(codexBin, args...).Run() // #nosec G204 -- test stub binary
}
}
// nativeAgentCLIStubSource is a tiny stdlib-only program that pretends to be claude/codex.
// `plugin list --json` scans jf's global install layout under $HOME/$USERPROFILE.
const nativeAgentCLIStubSource = `package main
import (
"encoding/json"
"os"
"path/filepath"
"strings"
)
func main() {
name := filepath.Base(os.Args[0])
name = strings.TrimSuffix(name, ".exe")
if len(os.Args) >= 3 && os.Args[1] == "plugin" && os.Args[2] == "list" {
home := os.Getenv("HOME")
if home == "" {
home = os.Getenv("USERPROFILE")
}
switch name {
case "claude":
_ = json.NewEncoder(os.Stdout).Encode(scanClaude(home))
case "codex":
_ = json.NewEncoder(os.Stdout).Encode(map[string]any{"installed": scanCodex(home)})
default:
_, _ = os.Stdout.Write([]byte("[]\n"))
}
return
}
}
type pluginInfo struct {
InstalledVersion string ` + "`json:\"installedVersion\"`" + `
}
func scanClaude(home string) []map[string]string {
root := filepath.Join(home, ".claude", "plugins", "local", "jfrog")
var out []map[string]string
repos, _ := os.ReadDir(root)
for _, repo := range repos {
if !repo.IsDir() || strings.HasPrefix(repo.Name(), ".") {
continue
}
slugs, _ := os.ReadDir(filepath.Join(root, repo.Name()))
for _, slug := range slugs {
if !slug.IsDir() || strings.HasPrefix(slug.Name(), ".") {
continue
}
dir := filepath.Join(root, repo.Name(), slug.Name())
out = append(out, map[string]string{
"id": slug.Name() + "@" + repo.Name(),
"version": installedVersion(dir),
"installPath": dir,
})
}
}
if out == nil {
out = []map[string]string{}
}
return out
}
func scanCodex(home string) []map[string]any {
root := filepath.Join(home, ".agents", "plugins", "local", "jfrog")
var out []map[string]any
repos, _ := os.ReadDir(root)
for _, repo := range repos {
if !repo.IsDir() || strings.HasPrefix(repo.Name(), ".") {
continue
}
slugs, _ := os.ReadDir(filepath.Join(root, repo.Name()))
for _, slug := range slugs {
if !slug.IsDir() || strings.HasPrefix(slug.Name(), ".") {
continue
}
dir := filepath.Join(root, repo.Name(), slug.Name())
out = append(out, map[string]any{
"pluginId": slug.Name() + "@" + repo.Name(),
"name": slug.Name(),
"marketplaceName": repo.Name(),
"version": installedVersion(dir),
"source": map[string]string{"path": dir},
})
}
}
if out == nil {
out = []map[string]any{}
}
return out
}
func installedVersion(dir string) string {
data, err := os.ReadFile(filepath.Join(dir, ".jfrog", "plugin-info.json"))
if err != nil {
return ""
}
var info pluginInfo
if err := json.Unmarshal(data, &info); err != nil {
return ""
}
return info.InstalledVersion
}
`
// ---------------------------------------------------------------------------
// Publish
// ---------------------------------------------------------------------------
// TestAgentPluginsPublish verifies that publishing a plugin directory uploads
// the zip to the correct path in the agentplugins local repository.
func TestAgentPluginsPublish(t *testing.T) {
initAgentPluginsTest(t)
defer cleanAgentPluginsTest()
slug := "publish-plugin"
version := "1.0.0"
pluginPath := createTestPlugin(t, slug, version)
require.NoError(t, runAgentPluginsCmd(t,
"publish", pluginPath,
"--repo="+tests.AgentPluginsLocalRepo,
))
assertPluginExists(t, slug, version)
}
// TestAgentPluginsVersionCollisionCI verifies that publishing the same version
// twice in CI/non-interactive mode fails with a clear "already exists" error.
func TestAgentPluginsVersionCollisionCI(t *testing.T) {
initAgentPluginsTest(t)
defer cleanAgentPluginsTest()
slug := "collision-plugin"
version := "1.0.0"
pluginPath := createTestPlugin(t, slug, version)
require.NoError(t, runAgentPluginsCmd(t,
"publish", pluginPath,
"--repo="+tests.AgentPluginsLocalRepo,
))
// Force non-interactive mode so the collision check fails immediately.
t.Setenv("CI", "true")
err := runAgentPluginsCmd(t,
"publish", pluginPath,
"--repo="+tests.AgentPluginsLocalRepo,
)
require.Error(t, err, "second publish of the same version in CI mode should fail")
assertErrorContainsAll(t, err,
fmt.Sprintf("version %s of plugin '%s' already exists", version, slug),
"Use a different version or remove the existing one")
}
// TestAgentPluginsPublishWithVersion verifies that --version overrides the
// manifest version on publish.
func TestAgentPluginsPublishWithVersion(t *testing.T) {
initAgentPluginsTest(t)
defer cleanAgentPluginsTest()
slug := "version-override-plugin"
overrideVersion := "2.0.0"
pluginPath := createTestPlugin(t, slug, "1.0.0")
require.NoError(t, runAgentPluginsCmd(t,
"publish", pluginPath,
"--repo="+tests.AgentPluginsLocalRepo,
"--version="+overrideVersion,
))
assertPluginExists(t, slug, overrideVersion)
}
// TestAgentPluginsPublishMissingPluginJson verifies that publishing a directory
// without plugin.json returns a clear error.
func TestAgentPluginsPublishMissingPluginJson(t *testing.T) {
initAgentPluginsTest(t)
defer cleanAgentPluginsTest()
emptyDir := t.TempDir()
err := runAgentPluginsCmd(t,
"publish", emptyDir,
"--repo="+tests.AgentPluginsLocalRepo,
)
assertErrorContainsAll(t, err, "no plugin.json")
}
// TestAgentPluginsPublishToNonExistentRepo verifies that publishing to a
// nonexistent repository returns a clear error.
func TestAgentPluginsPublishToNonExistentRepo(t *testing.T) {
initAgentPluginsTest(t)
defer cleanAgentPluginsTest()
pluginPath := createTestPlugin(t, "invalid-repo-plugin", "1.0.0")
err := runAgentPluginsCmd(t,
"publish", pluginPath,
"--repo=nonexistent-agent-plugins-repo-xyz",
)
// Publish wraps the Artifactory upload failure (see publish.go: "upload failed: %w").
assertErrorContainsAll(t, err, "upload failed")
}
// TestAgentPluginsChecksumIntegrity verifies that after publish the artifact
// in build info has non-empty, non-"untrusted" MD5, SHA1, and SHA256 checksums,
// confirming Artifactory computed all three correctly on upload.
func TestAgentPluginsChecksumIntegrity(t *testing.T) {
initAgentPluginsTest(t)
defer cleanAgentPluginsTest()
slug := "checksum-plugin"
version := "1.0.0"
buildNumber := t.Name()
// Best-effort teardown of local build-info dir; leftover dirs do not affect assertions.
t.Cleanup(func() { _ = coreBuild.RemoveBuildDir(tests.AgentPluginsBuildName, buildNumber, "") })
pluginPath := createTestPlugin(t, slug, version)
require.NoError(t, runAgentPluginsCmd(t,
"publish", pluginPath,
"--repo="+tests.AgentPluginsLocalRepo,
"--build-name="+tests.AgentPluginsBuildName,
"--build-number="+buildNumber,
))
require.NoError(t, artifactoryCli.Exec("bp", tests.AgentPluginsBuildName, buildNumber))
publishedBuildInfo, found, err := tests.GetBuildInfo(serverDetails, tests.AgentPluginsBuildName, buildNumber)
require.NoError(t, err, "GetBuildInfo failed")
require.True(t, found, "build info not found — was jf rt bp successful?")
require.Len(t, publishedBuildInfo.BuildInfo.Modules, 1)
require.NotEmpty(t, publishedBuildInfo.BuildInfo.Modules[0].Artifacts,
"expected at least one artifact in build info")
for _, artifact := range publishedBuildInfo.BuildInfo.Modules[0].Artifacts {
assert.NotEmpty(t, artifact.Md5, "artifact %s: md5 must not be empty", artifact.Name)
assert.NotEmpty(t, artifact.Sha1, "artifact %s: sha1 must not be empty", artifact.Name)
assert.NotEmpty(t, artifact.Sha256, "artifact %s: sha256 must not be empty", artifact.Name)
assert.NotEqual(t, "untrusted", strings.ToLower(artifact.Md5),
"artifact %s: md5 must not be 'untrusted'", artifact.Name)
assert.NotEqual(t, "untrusted", strings.ToLower(artifact.Sha1),
"artifact %s: sha1 must not be 'untrusted'", artifact.Name)
assert.NotEqual(t, "untrusted", strings.ToLower(artifact.Sha256),
"artifact %s: sha256 must not be 'untrusted'", artifact.Name)
}
}
// TestAgentPluginsPublishWithBuildInfo verifies that --build-name and
// --build-number cause the published zip to appear as an artifact in build info
// with a valid SHA256 checksum.
func TestAgentPluginsPublishWithBuildInfo(t *testing.T) {
initAgentPluginsTest(t)
defer cleanAgentPluginsTest()
slug := "buildinfo-plugin"
version := "1.0.0"
buildNumber := t.Name()
// Best-effort teardown of local build-info dir; leftover dirs do not affect assertions.
t.Cleanup(func() { _ = coreBuild.RemoveBuildDir(tests.AgentPluginsBuildName, buildNumber, "") })
pluginPath := createTestPlugin(t, slug, version)
assert.NoError(t, runAgentPluginsCmd(t,
"publish", pluginPath,
"--repo="+tests.AgentPluginsLocalRepo,
"--build-name="+tests.AgentPluginsBuildName,
"--build-number="+buildNumber,
))
require.NoError(t, artifactoryCli.Exec("bp", tests.AgentPluginsBuildName, buildNumber))
publishedBuildInfo, found, err := tests.GetBuildInfo(serverDetails, tests.AgentPluginsBuildName, buildNumber)
require.NoError(t, err, "GetBuildInfo failed")
require.True(t, found, "build info not found — was 'jf rt bp' successful?")
require.Len(t, publishedBuildInfo.BuildInfo.Modules, 1, "expected 1 build info module")
module := publishedBuildInfo.BuildInfo.Modules[0]
require.NotEmpty(t, module.Artifacts, "published zip should appear as an artifact in build info")
assert.NotEmpty(t, module.Artifacts[0].Sha256, "artifact sha256 should be non-empty in build info")
}
// TestAgentPluginsNoBuildInfoWithoutFlags verifies that publishing without
// --build-name and --build-number does not create a build info entry.
func TestAgentPluginsNoBuildInfoWithoutFlags(t *testing.T) {
initAgentPluginsTest(t)
defer cleanAgentPluginsTest()
slug := "no-buildinfo-plugin"
pluginPath := createTestPlugin(t, slug, "1.0.0")
assert.NoError(t, runAgentPluginsCmd(t,
"publish", pluginPath,
"--repo="+tests.AgentPluginsLocalRepo,
))
localBuilds, err := coreBuild.GetGeneratedBuildsInfo(tests.AgentPluginsBuildName, "1", "")
assert.NoError(t, err)
assert.Empty(t, localBuilds, "no local build info should be stored when --build-name/--build-number are absent")
}
// TestAgentPluginsPublishBuildNameWithoutNumber verifies that providing only
// one of --build-name / --build-number (scenarios #61 and #62) returns an
// error requiring both flags together.
func TestAgentPluginsPublishBuildNameWithoutNumber(t *testing.T) {
initAgentPluginsTest(t)
defer cleanAgentPluginsTest()
cases := []struct {
name string
extraArgs []string
description string
}{
{
name: "name-only",
extraArgs: []string{"--build-name=" + tests.AgentPluginsBuildName},
description: "--build-name without --build-number must return an error",
},
{
name: "number-only",
extraArgs: []string{"--build-number=42"},
description: "--build-number without --build-name must return an error",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
slug := "build-flag-validation-plugin-" + tc.name
pluginPath := createTestPlugin(t, slug, "1.0.0")
args := append([]string{"publish", pluginPath, "--repo=" + tests.AgentPluginsLocalRepo}, tc.extraArgs...)
err := runAgentPluginsCmd(t, args...)
assertErrorContainsAll(t, err, "the build-name and build-number options cannot be provided separately")
})
}
}
// TestAgentPluginsModuleOverride verifies that --module overrides the default
// module ID (slug) in build info.
func TestAgentPluginsModuleOverride(t *testing.T) {
initAgentPluginsTest(t)
defer cleanAgentPluginsTest()
slug := "module-override-plugin"
buildNumber := t.Name()
// Best-effort teardown of local build-info dir; leftover dirs do not affect assertions.
t.Cleanup(func() { _ = coreBuild.RemoveBuildDir(tests.AgentPluginsBuildName, buildNumber, "") })
customModule := "my-custom-agent-module"
pluginPath := createTestPlugin(t, slug, "1.0.0")
assert.NoError(t, runAgentPluginsCmd(t,
"publish", pluginPath,
"--repo="+tests.AgentPluginsLocalRepo,
"--build-name="+tests.AgentPluginsBuildName,
"--build-number="+buildNumber,
"--module="+customModule,
))
require.NoError(t, artifactoryCli.Exec("bp", tests.AgentPluginsBuildName, buildNumber))
publishedBuildInfo, found, err := tests.GetBuildInfo(serverDetails, tests.AgentPluginsBuildName, buildNumber)
require.NoError(t, err, "GetBuildInfo failed")
require.True(t, found, "build info not found")
require.NotEmpty(t, publishedBuildInfo.BuildInfo.Modules)
assert.Equal(t, customModule, publishedBuildInfo.BuildInfo.Modules[0].Id,
"--module flag should override the default module ID in build info")
}
// TestAgentPluginsPublishInvalidSemver verifies that a manifest with a
// non-semver version string is rejected before any upload attempt.
func TestAgentPluginsPublishInvalidSemver(t *testing.T) {
initAgentPluginsTest(t)
defer cleanAgentPluginsTest()
cases := []struct {
name string
version string
errContains []string
}{
{
name: "non-numeric-patch",
version: "1.9.e",
errContains: []string{`invalid version "1.9.e"`, `patch must be a number (got "e")`},
},
{
name: "missing-patch-segment",
version: "1.9",
errContains: []string{`invalid version "1.9"`, "expected format major.minor.patch"},
},
{
name: "non-numeric-major",
version: "x.1.0",
errContains: []string{`invalid version "x.1.0"`, `major must be a number (got "x")`},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
pluginPath := createMinimalPlugin(t, "semver-plugin", tc.version)
err := runAgentPluginsCmd(t,
"publish", pluginPath,
"--repo="+tests.AgentPluginsLocalRepo,
)
assertErrorContainsAll(t, err, tc.errContains...)
})
}
}
// TestAgentPluginsPublishInvalidSlug verifies that a manifest whose name field
// contains invalid characters is rejected with a ValidateSlug error.
func TestAgentPluginsPublishInvalidSlug(t *testing.T) {
initAgentPluginsTest(t)
defer cleanAgentPluginsTest()
pluginPath := createMinimalPlugin(t, "Invalid Slug With Spaces!", "1.0.0")
err := runAgentPluginsCmd(t,
"publish", pluginPath,
"--repo="+tests.AgentPluginsLocalRepo,
)
assertErrorContainsAll(t, err, "invalid slug")
}
// TestAgentPluginsPublishMissingPathArg verifies that omitting the required
// <path> argument returns a usage error.
func TestAgentPluginsPublishMissingPathArg(t *testing.T) {
initAgentPluginsTest(t)
defer cleanAgentPluginsTest()
err := runAgentPluginsCmd(t, "publish", "--repo="+tests.AgentPluginsLocalRepo)
assertErrorContainsAll(t, err, "usage: jf agent plugins publish")
}
// TestAgentPluginsPublishToWrongRepoType verifies that publishing to a
// repository of the wrong package type (e.g. a generic local repo) returns an
// error from Artifactory.
func TestAgentPluginsPublishToWrongRepoType(t *testing.T) {
initAgentPluginsTest(t)
defer cleanAgentPluginsTest()
// Use a known non-agentplugins repo (generic local) to trigger a type mismatch.
wrongTypeRepo := tests.RtRepo1
pluginPath := createTestPlugin(t, "wrong-repo-type-plugin", "1.0.0")
err := runAgentPluginsCmd(t,
"publish", pluginPath,
"--repo="+wrongTypeRepo,
)
assertErrorContainsAll(t, err, "upload failed")
}
// TestAgentPluginsPublishPrebuiltZip verifies that a prebuilt <slug>-<version>.zip
// inside a zip/ sub-directory is uploaded as-is without being re-zipped.
func TestAgentPluginsPublishPrebuiltZip(t *testing.T) {
initAgentPluginsTest(t)
defer cleanAgentPluginsTest()
slug := "prebuilt-zip-plugin"
version := "1.0.0"
// Create the plugin directory with a plugin.json and a prebuilt zip.
pluginDir := t.TempDir()
manifest := map[string]string{"name": slug, "version": version, "description": "prebuilt test"}
data, err := json.Marshal(manifest)
require.NoError(t, err)
require.NoError(t, os.WriteFile(filepath.Join(pluginDir, "plugin.json"), data, 0644)) // #nosec G306 -- test fixture
// The prebuilt zip lives at <pluginDir>/zip/<slug>-<version>.zip.
zipSubDir := filepath.Join(pluginDir, "zip")
require.NoError(t, os.MkdirAll(zipSubDir, 0755)) // #nosec G301 -- test directory
var zipBuf bytes.Buffer
zw := zip.NewWriter(&zipBuf)
f, err := zw.Create("placeholder.txt")
require.NoError(t, err)
_, err = f.Write([]byte("placeholder"))
require.NoError(t, err)
require.NoError(t, zw.Close())
zipContent := zipBuf.Bytes()
require.NoError(t, os.WriteFile(
filepath.Join(zipSubDir, slug+"-"+version+".zip"), zipContent, 0644, // #nosec G306 -- test fixture
))
require.NoError(t, runAgentPluginsCmd(t,
"publish", pluginDir,
"--repo="+tests.AgentPluginsLocalRepo,
), "publish with prebuilt zip should succeed without re-zipping")
assertPluginExists(t, slug, version)
}
// TestAgentPluginsBuildPropertiesOnArtifact verifies that after publish with
// build info collection, build.name / build.number / build.timestamp are
// stamped on the artifact in Artifactory.
func TestAgentPluginsBuildPropertiesOnArtifact(t *testing.T) {
initAgentPluginsTest(t)
defer cleanAgentPluginsTest()
slug := "build-props-plugin"
version := "1.0.0"
buildNumber := t.Name()
// Best-effort teardown of local build-info dir; leftover dirs do not affect assertions.
t.Cleanup(func() { _ = coreBuild.RemoveBuildDir(tests.AgentPluginsBuildName, buildNumber, "") })
pluginPath := createTestPlugin(t, slug, version)
require.NoError(t, runAgentPluginsCmd(t,
"publish", pluginPath,
"--repo="+tests.AgentPluginsLocalRepo,
"--build-name="+tests.AgentPluginsBuildName,
"--build-number="+buildNumber,
))
require.NoError(t, artifactoryCli.Exec("bp", tests.AgentPluginsBuildName, buildNumber))
sm, err := artUtils.CreateServiceManager(serverDetails, -1, 0, false)
require.NoError(t, err)
artifactPath := pluginArtifactPath(tests.AgentPluginsLocalRepo, slug, version)
props, err := sm.GetItemProps(artifactPath)
require.NoError(t, err, "GetItemProps should succeed for %s", artifactPath)
require.NotNil(t, props)
assert.Contains(t, props.Properties, "build.name",
"build.name property must be stamped on the published zip")
assert.Contains(t, props.Properties, "build.number",
"build.number property must be stamped on the published zip")
assert.Contains(t, props.Properties, "build.timestamp",
"build.timestamp property must be stamped on the published zip")
}
// TestAgentPluginsBuildInfoFromEnvVars verifies that JFROG_CLI_BUILD_NAME and
// JFROG_CLI_BUILD_NUMBER environment variables trigger build info collection
// even when the --build-name/--build-number flags are not passed explicitly.
func TestAgentPluginsBuildInfoFromEnvVars(t *testing.T) {
initAgentPluginsTest(t)
defer cleanAgentPluginsTest()
envBuildName := tests.AgentPluginsBuildName + "-envvar"
envBuildNumber := "42"
t.Setenv("JFROG_CLI_BUILD_NAME", envBuildName)
t.Setenv("JFROG_CLI_BUILD_NUMBER", envBuildNumber)
inttestutils.DeleteBuild(serverDetails.ArtifactoryUrl, envBuildName, artHttpDetails)
defer inttestutils.DeleteBuild(serverDetails.ArtifactoryUrl, envBuildName, artHttpDetails)
slug := "envvar-build-plugin"
pluginPath := createTestPlugin(t, slug, "1.0.0")
// No --build-name / --build-number flags; env vars should be picked up.
assert.NoError(t, runAgentPluginsCmd(t,
"publish", pluginPath,
"--repo="+tests.AgentPluginsLocalRepo,
))
require.NoError(t, artifactoryCli.Exec("bp", envBuildName, envBuildNumber))
_, found, err := tests.GetBuildInfo(serverDetails, envBuildName, envBuildNumber)
require.NoError(t, err, "GetBuildInfo failed")
assert.True(t, found,
"build info should be captured from JFROG_CLI_BUILD_NAME/NUMBER env vars")
}
// TestAgentPluginsBuildPublishRetrievable verifies the full build info flow:
// publish plugin → publish build info → retrieve build info from Artifactory.
func TestAgentPluginsBuildPublishRetrievable(t *testing.T) {
initAgentPluginsTest(t)
defer cleanAgentPluginsTest()
slug := "bp-retrievable-plugin"
version := "1.0.0"
buildNumber := t.Name()
// Best-effort teardown of local build-info dir; leftover dirs do not affect assertions.
t.Cleanup(func() { _ = coreBuild.RemoveBuildDir(tests.AgentPluginsBuildName, buildNumber, "") })
pluginPath := createTestPlugin(t, slug, version)
require.NoError(t, runAgentPluginsCmd(t,
"publish", pluginPath,
"--repo="+tests.AgentPluginsLocalRepo,
"--build-name="+tests.AgentPluginsBuildName,
"--build-number="+buildNumber,
))
require.NoError(t, artifactoryCli.Exec("bp", tests.AgentPluginsBuildName, buildNumber),
"jf rt bp should succeed")
publishedBuildInfo, found, err := tests.GetBuildInfo(serverDetails, tests.AgentPluginsBuildName, buildNumber)
require.NoError(t, err, "GetBuildInfo failed")
require.True(t, found, "build info must be retrievable from Artifactory after jf rt bp")
assert.Equal(t, tests.AgentPluginsBuildName, publishedBuildInfo.BuildInfo.Name,
"retrieved build info name must match")
}
// TestAgentPluginsChecksumStoredByArtifactory publishes a plugin and verifies
// that Artifactory stores non-empty MD5, SHA1, and SHA256 for the artifact.
func TestAgentPluginsChecksumStoredByArtifactory(t *testing.T) {
initAgentPluginsTest(t)
defer cleanAgentPluginsTest()
slug := "checksum-rt-plugin"
version := "1.0.0"
pluginPath := createTestPlugin(t, slug, version)
require.NoError(t, runAgentPluginsCmd(t,
"publish", pluginPath,
"--repo="+tests.AgentPluginsLocalRepo,
))
// Retrieve checksums Artifactory stored for the zip via AQL search.
artifactPath := pluginArtifactPath(tests.AgentPluginsLocalRepo, slug, version)
searchSpec := spec.NewBuilder().Pattern(artifactPath).BuildSpec()
searchCmd := generic.NewSearchCommand()
searchCmd.SetServerDetails(serverDetails).SetSpec(searchSpec)
reader, err := searchCmd.Search()
require.NoError(t, err, "search for artifact checksum failed")
// Read-side Close: search reader has no write flush; nothing actionable on failure.
defer func() { _ = reader.Close() }()
item := new(artUtils.SearchResult)
require.NoError(t, reader.NextRecord(item), "artifact must be found in Artifactory")
assert.NotEmpty(t, item.Md5, "Artifactory must store an md5 for the artifact")
assert.NotEmpty(t, item.Sha1, "Artifactory must store a sha1 for the artifact")
assert.NotEmpty(t, item.Sha256, "Artifactory must store a sha256 for the artifact")
}
// TestAgentPluginsPublishWithSigningKey generates a real ECDSA key pair,
// uploads the public key to Artifactory trusted keys, and publishes a plugin
// with --signing-key. Asserts the artifact exists; evidence attachment depends
// on the Artifactory evidence service and is not queried here.
func TestAgentPluginsPublishWithSigningKey(t *testing.T) {
initAgentPluginsTest(t)
defer cleanAgentPluginsTest()
// The trusted keys API rejects duplicate aliases, and the suite may run more than
// once against the same Artifactory instance, so keep the alias unique per run.
keyAlias := fmt.Sprintf("agent-plugins-test-key-%d", time.Now().UnixNano())
// Generate an ECDSA P-256 key pair without network access.
privateKeyPEM, publicKeyPEM, err := cryptox.GenerateECDSAKeyPair()
require.NoError(t, err, "key generation must succeed")
privateKeyPath := filepath.Join(t.TempDir(), "evidence.key")
require.NoError(t, os.WriteFile(privateKeyPath, []byte(privateKeyPEM), 0600)) // #nosec G306 -- test private key under t.TempDir
// Upload the public key to Artifactory trusted keys so the evidence service can verify
// signatures made with the corresponding private key. KeyPairCommand.Run is not used here:
// it refuses to overwrite an existing key file and only warns (never returns) on upload
// failure, so uploading directly is what surfaces a real error to skip on.
serviceManager, err := artUtils.CreateUploadServiceManager(serverDetails, 1, 0, 0, false, nil)
require.NoError(t, err)
keyPairCmd := generate.NewGenerateKeyPairCommand(serverDetails, true, keyAlias, "", "")
if _, err := keyPairCmd.UploadTrustedKey(&serviceManager, keyAlias, publicKeyPEM); err != nil {
t.Skipf("skipping: could not upload public key to trusted keys (evidence service may not be configured): %v", err)
}
slug := "signed-plugin"
version := "1.0.0"
pluginPath := createTestPlugin(t, slug, version)
require.NoError(t, runAgentPluginsCmd(t,
"publish", pluginPath,
"--repo="+tests.AgentPluginsLocalRepo,
"--signing-key="+privateKeyPath,
"--key-alias="+keyAlias,
), "publish with --signing-key must succeed")
assertPluginExists(t, slug, version)
}
// TestAgentPluginsPublishWithoutSigningKey confirms that omitting --signing-key
// and clearing key env vars still results in a successful publish (evidence is
// skipped with an info log, not a failure).
func TestAgentPluginsPublishWithoutSigningKey(t *testing.T) {