GitLabgitlab-org
cli
main
1//go:build !integration
3package list
5import (
6 "encoding/json"
7 "errors"
8 "net/http"
9 "testing"
10 "time"
12 "github.com/MakeNowJust/heredoc/v2"
13 "github.com/stretchr/testify/assert"
14 "github.com/stretchr/testify/require"
15 "go.uber.org/mock/gomock"
17 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
18 gitlabtesting "gitlab.com/gitlab-org/api/client-go/v3/testing"
20 "gitlab.com/gitlab-org/cli/internal/api"
21 "gitlab.com/gitlab-org/cli/internal/cmdutils"
22 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
23)
25func noMorePages() *gitlab.Response {
26 return &gitlab.Response{NextPage: 0}
27}
29func setupExec(t *testing.T, tc *gitlabtesting.TestClient) cmdtest.CmdExecFunc {
30 t.Helper()
32 return cmdtest.SetupCmdForTest(
33 t,
34 NewCmd,
35 false,
36 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "", "", api.WithGitLabClient(tc.Client))),
37 )
38}
40func TestList_Project(t *testing.T) {
41 t.Parallel()
43 expiresAt := time.Date(2027, 1, 1, 0, 0, 0, 0, time.UTC)
44 tc := gitlabtesting.NewTestClient(t)
45 tc.MockDeployTokens.EXPECT().
46 ListProjectDeployTokens("OWNER/REPO", gomock.Any(), gomock.Any(), gomock.Any()).
47 Return([]*gitlab.DeployToken{
48 {
49 ID: 1,
50 Name: "ci-reader",
51 Username: "gitlab+deploy-token-1",
52 ExpiresAt: &expiresAt,
53 Scopes: []string{"read_repository", "read_registry"},
54 },
55 {
56 ID: 2,
57 Name: "retired",
58 Username: "gitlab+deploy-token-2",
59 Revoked: true,
60 Scopes: []string{"read_repository"},
61 },
62 }, noMorePages(), nil)
64 out, err := setupExec(t, tc)("")
65 require.NoError(t, err)
67 expected := heredoc.Doc(`
68 ID Name Username Scopes Expires At Revoked Expired
69 1 ci-reader gitlab+deploy-token-1 read_repository, read_registry 2027-01-01T00:00:00Z false false
70 2 retired gitlab+deploy-token-2 read_repository - true false
71 `)
72 assert.Equal(t, expected, out.OutBuf.String())
73 assert.Empty(t, out.ErrBuf.String())
74}
76func TestList_Group(t *testing.T) {
77 t.Parallel()
79 tc := gitlabtesting.NewTestClient(t)
80 tc.MockDeployTokens.EXPECT().
81 ListGroupDeployTokens("group/sub-group", gomock.Any(), gomock.Any(), gomock.Any()).
82 Return([]*gitlab.DeployToken{
83 {
84 ID: 7,
85 Name: "group-reader",
86 Username: "gitlab+deploy-token-7",
87 Scopes: []string{"read_repository"},
88 },
89 }, noMorePages(), nil)
91 out, err := setupExec(t, tc)("--group group/sub-group")
92 require.NoError(t, err)
94 expected := heredoc.Doc(`
95 ID Name Username Scopes Expires At Revoked Expired
96 7 group-reader gitlab+deploy-token-7 read_repository - false false
97 `)
98 assert.Equal(t, expected, out.OutBuf.String())
99}
101// The deploy token list endpoints accept no active filter, so --active is
102// applied to the tokens that were retrieved.
103func TestList_ActiveOnly(t *testing.T) {
104 t.Parallel()
106 tc := gitlabtesting.NewTestClient(t)
107 tc.MockDeployTokens.EXPECT().
108 ListProjectDeployTokens("OWNER/REPO", gomock.Any(), gomock.Any(), gomock.Any()).
109 Return([]*gitlab.DeployToken{
110 {ID: 1, Name: "active", Username: "gitlab+deploy-token-1", Scopes: []string{"read_repository"}},
111 {ID: 2, Name: "revoked", Username: "gitlab+deploy-token-2", Revoked: true, Scopes: []string{"read_repository"}},
112 {ID: 3, Name: "expired", Username: "gitlab+deploy-token-3", Expired: true, Scopes: []string{"read_repository"}},
113 }, noMorePages(), nil)
115 out, err := setupExec(t, tc)("--active")
116 require.NoError(t, err)
118 expected := heredoc.Doc(`
119 ID Name Username Scopes Expires At Revoked Expired
120 1 active gitlab+deploy-token-1 read_repository - false false
121 `)
122 assert.Equal(t, expected, out.OutBuf.String())
123}
125func TestList_JSON(t *testing.T) {
126 t.Parallel()
128 expiresAt := time.Date(2027, 1, 1, 0, 0, 0, 0, time.UTC)
129 tc := gitlabtesting.NewTestClient(t)
130 tc.MockDeployTokens.EXPECT().
131 ListProjectDeployTokens("OWNER/REPO", gomock.Any(), gomock.Any(), gomock.Any()).
132 Return([]*gitlab.DeployToken{
133 {
134 ID: 1,
135 Name: "ci-reader",
136 Username: "gitlab+deploy-token-1",
137 ExpiresAt: &expiresAt,
138 Scopes: []string{"read_repository", "read_registry"},
139 },
140 }, noMorePages(), nil)
142 out, err := setupExec(t, tc)("--output json")
143 require.NoError(t, err)
145 var result []*gitlab.DeployToken
146 require.NoError(t, json.Unmarshal(out.OutBuf.Bytes(), &result))
147 require.Len(t, result, 1)
148 assert.Equal(t, int64(1), result[0].ID)
149 assert.Equal(t, "ci-reader", result[0].Name)
150 assert.Equal(t, "gitlab+deploy-token-1", result[0].Username)
151 assert.Equal(t, expiresAt, *result[0].ExpiresAt)
152 assert.Equal(t, []string{"read_repository", "read_registry"}, result[0].Scopes)
153 assert.False(t, result[0].Revoked)
154 assert.False(t, result[0].Expired)
155}
157// A token value must never reach the output, in either format.
158func TestList_OmitsTokenValue(t *testing.T) {
159 t.Parallel()
161 tests := []struct {
162 name string
163 args string
164 }{
165 {name: "text", args: ""},
166 {name: "json", args: "--output json"},
167 }
169 for _, tt := range tests {
170 t.Run(tt.name, func(t *testing.T) {
171 t.Parallel()
173 tc := gitlabtesting.NewTestClient(t)
174 tc.MockDeployTokens.EXPECT().
175 ListProjectDeployTokens("OWNER/REPO", gomock.Any(), gomock.Any(), gomock.Any()).
176 Return([]*gitlab.DeployToken{
177 {ID: 1, Name: "ci-reader", Username: "gitlab+deploy-token-1", Token: "gldt-secret", Scopes: []string{"read_repository"}},
178 }, noMorePages(), nil)
180 out, err := setupExec(t, tc)(tt.args)
181 require.NoError(t, err)
183 assert.Contains(t, out.OutBuf.String(), "ci-reader")
184 assert.NotContains(t, out.OutBuf.String(), "gldt-secret")
185 })
186 }
187}
189func TestList_Empty(t *testing.T) {
190 t.Parallel()
192 tc := gitlabtesting.NewTestClient(t)
193 tc.MockDeployTokens.EXPECT().
194 ListProjectDeployTokens("OWNER/REPO", gomock.Any(), gomock.Any(), gomock.Any()).
195 Return([]*gitlab.DeployToken{}, noMorePages(), nil)
197 out, err := setupExec(t, tc)("")
198 require.NoError(t, err)
200 assert.Equal(t, "No deploy tokens found.\n", out.OutBuf.String())
201}
203func TestList_EmptyJSON(t *testing.T) {
204 t.Parallel()
206 tc := gitlabtesting.NewTestClient(t)
207 tc.MockDeployTokens.EXPECT().
208 ListProjectDeployTokens("OWNER/REPO", gomock.Any(), gomock.Any(), gomock.Any()).
209 Return([]*gitlab.DeployToken{}, noMorePages(), nil)
211 out, err := setupExec(t, tc)("--output json")
212 require.NoError(t, err)
214 var result []*gitlab.DeployToken
215 require.NoError(t, json.Unmarshal(out.OutBuf.Bytes(), &result))
216 assert.Empty(t, result)
217}
219func TestList_APIError(t *testing.T) {
220 t.Parallel()
222 tc := gitlabtesting.NewTestClient(t)
223 tc.MockDeployTokens.EXPECT().
224 ListProjectDeployTokens("OWNER/REPO", gomock.Any(), gomock.Any(), gomock.Any()).
225 Return(nil, nil, errors.New("403 Forbidden"))
227 _, err := setupExec(t, tc)("")
228 require.Error(t, err)
230 var exitErr *cmdutils.ExitError
231 require.ErrorAs(t, err, &exitErr)
232 assert.Equal(t, "failed to list deploy tokens", exitErr.Details)
233 assert.Contains(t, err.Error(), "403 Forbidden")
234}
236func TestList_RepoAndGroupAreMutuallyExclusive(t *testing.T) {
237 t.Parallel()
239 tc := gitlabtesting.NewTestClient(t)
241 _, err := setupExec(t, tc)("--repo OWNER/REPO --group group/sub-group")
242 require.Error(t, err)
243 assert.Contains(t, err.Error(), "none of the others can be")
244}
246// The project scope needs a base repository, and says so before any client is
247// built, so the caller is told why the repository was needed.
248func TestList_OutsideRepositoryWithoutGroup(t *testing.T) {
249 t.Parallel()
251 tc := gitlabtesting.NewTestClient(t)
252 exec := cmdtest.SetupCmdForTest(
253 t,
254 NewCmd,
255 false,
256 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "", "", api.WithGitLabClient(tc.Client))),
257 cmdtest.WithBaseRepoError(errors.New("not a git repository")),
258 )
260 _, err := exec("")
261 require.Error(t, err)
262 assert.Contains(t, err.Error(), "not a git repository")
263}
265// The group scope does not need a base repository.
266func TestList_OutsideRepositoryWithGroup(t *testing.T) {
267 t.Parallel()
269 tc := gitlabtesting.NewTestClient(t)
270 tc.MockDeployTokens.EXPECT().
271 ListGroupDeployTokens("group/sub-group", gomock.Any(), gomock.Any(), gomock.Any()).
272 Return([]*gitlab.DeployToken{
273 {ID: 7, Name: "group-reader", Username: "gitlab+deploy-token-7", Scopes: []string{"read_repository"}},
274 }, noMorePages(), nil)
276 exec := cmdtest.SetupCmdForTest(
277 t,
278 NewCmd,
279 false,
280 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "", "", api.WithGitLabClient(tc.Client))),
281 cmdtest.WithBaseRepoError(errors.New("not a git repository")),
282 )
284 out, err := exec("--group group/sub-group")
285 require.NoError(t, err)
287 expected := heredoc.Doc(`
288 ID Name Username Scopes Expires At Revoked Expired
289 7 group-reader gitlab+deploy-token-7 read_repository - false false
290 `)
291 assert.Equal(t, expected, out.OutBuf.String())
292}
294func TestList_Instance(t *testing.T) {
295 t.Parallel()
297 tc := gitlabtesting.NewTestClient(t)
298 tc.MockDeployTokens.EXPECT().
299 ListAllDeployTokens(gomock.Any(), gomock.Any()).
300 Return([]*gitlab.DeployToken{
301 {ID: 3, Name: "registry-pull", Username: "gitlab+deploy-token-3", Scopes: []string{"read_registry"}},
302 }, noMorePages(), nil)
304 out, err := setupExec(t, tc)("--instance")
305 require.NoError(t, err)
307 expected := heredoc.Doc(`
308 ID Name Username Scopes Expires At Revoked Expired
309 3 registry-pull gitlab+deploy-token-3 read_registry - false false
310 `)
311 assert.Equal(t, expected, out.OutBuf.String())
312}
314func TestList_InstanceOutsideRepository(t *testing.T) {
315 t.Parallel()
317 tc := gitlabtesting.NewTestClient(t)
318 tc.MockDeployTokens.EXPECT().
319 ListAllDeployTokens(gomock.Any(), gomock.Any()).
320 Return([]*gitlab.DeployToken{
321 {ID: 3, Name: "registry-pull", Username: "gitlab+deploy-token-3", Scopes: []string{"read_registry"}},
322 }, noMorePages(), nil)
324 exec := cmdtest.SetupCmdForTest(
325 t,
326 NewCmd,
327 false,
328 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "", "", api.WithGitLabClient(tc.Client))),
329 cmdtest.WithBaseRepoError(errors.New("not a git repository")),
330 )
332 out, err := exec("--instance")
333 require.NoError(t, err)
334 assert.Contains(t, out.OutBuf.String(), "registry-pull")
335}
337// Any call to the group endpoint fails the mock, so this proves GITLAB_GROUP
338// does not redirect --instance.
339func TestList_InstanceIgnoresGroupEnv(t *testing.T) {
340 t.Setenv("GITLAB_GROUP", "env-group")
342 tc := gitlabtesting.NewTestClient(t)
343 tc.MockDeployTokens.EXPECT().
344 ListAllDeployTokens(gomock.Any(), gomock.Any()).
345 Return([]*gitlab.DeployToken{}, noMorePages(), nil)
347 out, err := setupExec(t, tc)("--instance")
348 require.NoError(t, err)
349 assert.Equal(t, "No deploy tokens found.\n", out.OutBuf.String())
350}
352func TestList_InstanceAPIError(t *testing.T) {
353 t.Parallel()
355 tests := []struct {
356 name string
357 status int
358 wantHint bool
359 }{
360 {name: "forbidden names the administrator requirement", status: http.StatusForbidden, wantHint: true},
361 {name: "other failures are passed through", status: http.StatusInternalServerError, wantHint: false},
362 }
364 for _, tt := range tests {
365 t.Run(tt.name, func(t *testing.T) {
366 t.Parallel()
368 tc := gitlabtesting.NewTestClient(t)
369 tc.MockDeployTokens.EXPECT().
370 ListAllDeployTokens(gomock.Any(), gomock.Any()).
371 Return(nil, nil, &gitlab.ErrorResponse{StatusCode: tt.status, Message: http.StatusText(tt.status)})
373 _, err := setupExec(t, tc)("--instance")
374 require.Error(t, err)
376 var exitErr *cmdutils.ExitError
377 require.ErrorAs(t, err, &exitErr)
378 assert.Equal(t, "failed to list deploy tokens", exitErr.Details)
379 assert.True(t, gitlab.HasStatusCode(err, tt.status))
380 if tt.wantHint {
381 assert.Contains(t, err.Error(), "requires administrator access")
382 } else {
383 assert.NotContains(t, err.Error(), "administrator")
384 }
385 })
386 }
387}
389func TestList_InstanceIsMutuallyExclusive(t *testing.T) {
390 t.Parallel()
392 tests := []struct {
393 name string
394 args string
395 }{
396 {name: "with repo", args: "--instance --repo OWNER/REPO"},
397 {name: "with group", args: "--instance --group group/sub-group"},
398 }
400 for _, tt := range tests {
401 t.Run(tt.name, func(t *testing.T) {
402 t.Parallel()
404 tc := gitlabtesting.NewTestClient(t)
406 _, err := setupExec(t, tc)(tt.args)
407 require.Error(t, err)
408 assert.Contains(t, err.Error(), "none of the others can be")
409 })
410 }
411}
Diagnostics8 git calls · 284 ms
CallStatusSizeTime0284 ms
discover200185 B3 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=185 git.server.agent=git/2.56.g1891de4-Linux git.server.object_format=sha1 git.server.caps=agent ls-refs fetch server-option object-format git.server.fetch=shallow wait-for-done filter git.protocol.version=2 git.pkt.frames=9 git.pkt.data=7 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=185 git.pkt.payload.max=35
ls-refs20058 KiB2 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=2 git.response.bytes=59849 git.response.cache=UPDATING git.response.duration_ms=2 git.protocol.version=2 git.pkt.frames=731 git.pkt.data=730 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=59849 git.pkt.payload.max=143 git.ls_refs.count=730 git.ls_refs.head=refs/heads/main
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.bytes=4273 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=combine:blob:none+tree:2 git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9 git.fetch.haves.count=0 git.fetch.deepen=1 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=7 git.pkt.data=5 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=4273 git.pkt.payload.max=4173 git.sideband.band1.bytes=4173 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=11 git.pack.bytes=4173 git.fetch.wide.objects=11 git.fetch.wide.extra_bytes=3930 git.fetch.wide.blobs=0
fetchtree:0 · deepen 1020032 KiB · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.bytes=32926 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9 git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=22 git.pkt.data=20 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=32926 git.pkt.payload.max=32046 git.sideband.band1.bytes=32046 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=80 git.pack.bytes=32046 git.pack.ofs_delta=36 git.pack.ref_delta=0 git.pack.chain.max=2 git.pack.trailer=cb0bad5d7ffc514895d8b21c4dd470327f90bc91 git.pack.full=44Open pack map
fetchtree:02001.8 KiB · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=3 git.response.bytes=1857 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=dce174ff8c632a19d17eea99c8a9b7c37fb2b592 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=1857 git.pkt.payload.max=1830 git.sideband.band1.bytes=1830 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=1830 git.pack.trailer=fb03183b7909876778f740d196d7516811003517Open pack map
fetchtree:0200263 B · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.bytes=263 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=aff3dd5052d75f0afe2383713d669f993c82b2f9 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=263 git.pkt.payload.max=236 git.sideband.band1.bytes=236 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=236 git.pack.trailer=4076aed8a003d312c41b730611843784ab33181fOpen pack map
fetchtree:0200134 B · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=272 git.response.bytes=134 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=40969612a65fa6a96744b73de65446048116a040 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=134 git.pkt.payload.max=107 git.sideband.band1.bytes=107 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=107 git.pack.trailer=1e7eaae72922b05c59dc8831312483164e8f30aaOpen pack map
fetch2002.3 KiB272 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=2392 git.response.cache=MISS git.response.duration_ms=272 git.fetch.wants=39c8f300aa3416ae621bc1c14a271d8668ddce31 git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=4 git.pkt.data=3 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=2392 git.pkt.payload.max=2365 git.sideband.band1.bytes=2365 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0
Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.
- Remote
- https://gitlab.com/gitlab-org/cli
- Ref
- refs/heads/main
- Commit
- 0dd7574dce9e385c5c30540e6c15657adc6bdce9
- cf-ray
- a5e2b5b7aa64cf33
- Request
- 4a022fe8…
- Protocol
- v2 · sha1
- Agent
- git/2.56.g1891de4-Linux
- Filter
- advertised
- Fetch
- shallow wait-for-done filter
- Capabilities
- agent ls-refs fetch server-option object-format