GitLabgitlab-org
cli
main
1//go:build !integration
3package serviceaccountutils
5import (
6 "errors"
7 "testing"
8 "time"
10 "github.com/stretchr/testify/assert"
11 "github.com/stretchr/testify/require"
12 "go.uber.org/mock/gomock"
14 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
15 gitlabtesting "gitlab.com/gitlab-org/api/client-go/v3/testing"
17 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
18)
20func TestListTokens(t *testing.T) {
21 t.Parallel()
23 t.Run("collects every page of a group account", func(t *testing.T) {
24 t.Parallel()
26 tc := gitlabtesting.NewTestClient(t)
27 gomock.InOrder(
28 tc.MockGroups.EXPECT().
29 ListServiceAccountPersonalAccessTokens("my-group", int64(41), gomock.Cond(func(o *gitlab.ListServiceAccountPersonalAccessTokensOptions) bool {
30 return o.PerPage == 100 && o.State == nil
31 }), gomock.Any(), gomock.Any()).
32 Return([]*gitlab.PersonalAccessToken{{ID: 7}}, &gitlab.Response{NextPage: 2}, nil),
33 tc.MockGroups.EXPECT().
34 ListServiceAccountPersonalAccessTokens("my-group", int64(41), gomock.Any(), gomock.Any(), gomock.Any()).
35 Return([]*gitlab.PersonalAccessToken{{ID: 8}}, noMorePages(), nil),
36 )
38 tokens, err := ListTokens(t.Context(), tc.Client, Scope{Group: "my-group"}, 41, false)
39 require.NoError(t, err)
40 require.Len(t, tokens, 2)
41 assert.Equal(t, int64(7), tokens[0].ID)
42 assert.Equal(t, int64(8), tokens[1].ID)
43 })
45 t.Run("asks a project for active tokens only", func(t *testing.T) {
46 t.Parallel()
48 tc := gitlabtesting.NewTestClient(t)
49 tc.MockProjects.EXPECT().
50 ListProjectServiceAccountPersonalAccessTokens("OWNER/REPO", int64(51), gomock.Cond(func(o *gitlab.ListProjectServiceAccountPersonalAccessTokensOptions) bool {
51 return o.PerPage == 100 && o.State != nil && *o.State == "active"
52 }), gomock.Any(), gomock.Any()).
53 Return([]*gitlab.PersonalAccessToken{{ID: 7}}, noMorePages(), nil)
55 tokens, err := ListTokens(t.Context(), tc.Client, Scope{Project: "OWNER/REPO"}, 51, true)
56 require.NoError(t, err)
57 require.Len(t, tokens, 1)
58 assert.Equal(t, int64(7), tokens[0].ID)
59 })
60}
62func TestResolveTokenID(t *testing.T) {
63 t.Parallel()
65 // No expectation is set, so any API call fails the test.
66 t.Run("numeric ID makes no request", func(t *testing.T) {
67 t.Parallel()
69 tc := gitlabtesting.NewTestClient(t)
71 id, err := ResolveTokenID(t.Context(), tc.Client, Scope{Project: "OWNER/REPO"}, 51, "7")
72 require.NoError(t, err)
73 assert.Equal(t, int64(7), id)
74 })
76 t.Run("name found among active project tokens", func(t *testing.T) {
77 t.Parallel()
79 tc := gitlabtesting.NewTestClient(t)
80 tc.MockProjects.EXPECT().
81 ListProjectServiceAccountPersonalAccessTokens("OWNER/REPO", int64(51), gomock.Cond(func(o *gitlab.ListProjectServiceAccountPersonalAccessTokensOptions) bool {
82 return o.PerPage == 100 && o.State != nil && *o.State == "active" && o.Search != nil && *o.Search == "ci"
83 }), gomock.Any(), gomock.Any()).
84 Return([]*gitlab.PersonalAccessToken{{ID: 6, Name: "ci-old"}, {ID: 7, Name: "ci"}}, noMorePages(), nil)
86 id, err := ResolveTokenID(t.Context(), tc.Client, Scope{Project: "OWNER/REPO"}, 51, "ci")
87 require.NoError(t, err)
88 assert.Equal(t, int64(7), id)
89 })
91 t.Run("name found among active group tokens", func(t *testing.T) {
92 t.Parallel()
94 tc := gitlabtesting.NewTestClient(t)
95 tc.MockGroups.EXPECT().
96 ListServiceAccountPersonalAccessTokens("my-group", int64(41), gomock.Cond(func(o *gitlab.ListServiceAccountPersonalAccessTokensOptions) bool {
97 return o.State != nil && *o.State == "active" && o.Search != nil && *o.Search == "deploy"
98 }), gomock.Any(), gomock.Any()).
99 Return([]*gitlab.PersonalAccessToken{{ID: 9, Name: "deploy"}}, noMorePages(), nil)
101 id, err := ResolveTokenID(t.Context(), tc.Client, Scope{Group: "my-group"}, 41, "deploy")
102 require.NoError(t, err)
103 assert.Equal(t, int64(9), id)
104 })
106 // The search is partial and case-insensitive, so only an exact name counts.
107 t.Run("a partial or differently cased name is not a match", func(t *testing.T) {
108 t.Parallel()
110 tc := gitlabtesting.NewTestClient(t)
111 tc.MockProjects.EXPECT().
112 ListProjectServiceAccountPersonalAccessTokens("OWNER/REPO", int64(51), gomock.Any(), gomock.Any(), gomock.Any()).
113 Return([]*gitlab.PersonalAccessToken{{ID: 6, Name: "ci-old"}, {ID: 8, Name: "CI"}}, noMorePages(), nil)
115 _, err := ResolveTokenID(t.Context(), tc.Client, Scope{Project: "OWNER/REPO"}, 51, "ci")
116 require.EqualError(t, err, `no active token named "ci" for service account 51 in project OWNER/REPO`)
117 })
119 t.Run("duplicate active names", func(t *testing.T) {
120 t.Parallel()
122 tc := gitlabtesting.NewTestClient(t)
123 tc.MockProjects.EXPECT().
124 ListProjectServiceAccountPersonalAccessTokens("OWNER/REPO", int64(51), gomock.Any(), gomock.Any(), gomock.Any()).
125 Return([]*gitlab.PersonalAccessToken{{ID: 7, Name: "ci"}, {ID: 8, Name: "ci"}}, noMorePages(), nil)
127 _, err := ResolveTokenID(t.Context(), tc.Client, Scope{Project: "OWNER/REPO"}, 51, "ci")
128 require.EqualError(t, err, `multiple active tokens named "ci" for service account 51; use the token ID instead`)
129 })
131 t.Run("invalid ID", func(t *testing.T) {
132 t.Parallel()
134 tc := gitlabtesting.NewTestClient(t)
136 _, err := ResolveTokenID(t.Context(), tc.Client, Scope{Project: "OWNER/REPO"}, 51, "0")
137 require.EqualError(t, err, `invalid token ID "0"`)
138 })
140 t.Run("a list error is returned", func(t *testing.T) {
141 t.Parallel()
143 tc := gitlabtesting.NewTestClient(t)
144 tc.MockProjects.EXPECT().
145 ListProjectServiceAccountPersonalAccessTokens("OWNER/REPO", int64(51), gomock.Any(), gomock.Any(), gomock.Any()).
146 Return(nil, nil, errors.New("403 Forbidden"))
148 _, err := ResolveTokenID(t.Context(), tc.Client, Scope{Project: "OWNER/REPO"}, 51, "ci")
149 require.EqualError(t, err, "403 Forbidden")
150 })
151}
153func TestPrintToken(t *testing.T) {
154 t.Parallel()
156 expiresAt := gitlab.ISOTime(time.Date(2027, 1, 31, 0, 0, 0, 0, time.UTC))
157 io, _, stdout, stderr := cmdtest.TestIOStreams()
158 err := PrintToken(io, &gitlab.PersonalAccessToken{
159 ID: 7,
160 Name: "ci",
161 Scopes: []string{"api"},
162 ExpiresAt: &expiresAt,
163 Token: "glpat-secret",
164 })
166 require.NoError(t, err)
167 assert.Equal(t, "glpat-secret\n", stdout.String())
168 assert.Equal(t, "ID\t7\nName\tci\nDescription\t-\nScopes\tapi\nExpires At\t2027-01-31\n", stderr.String())
169}
171type failingWriter struct{}
173func (failingWriter) Write([]byte) (int, error) { return 0, errors.New("broken pipe") }
175func TestPrintToken_StdoutWriteErrorIsReturned(t *testing.T) {
176 t.Parallel()
178 io, _, _, _ := cmdtest.TestIOStreams()
179 io.StdOut = failingWriter{}
181 err := PrintToken(io, &gitlab.PersonalAccessToken{ID: 7, Name: "ci", Token: "glpat-secret"})
182 require.EqualError(t, err, "broken pipe")
183}
185func TestFormatScopes(t *testing.T) {
186 t.Parallel()
188 assert.Equal(t, "-", FormatScopes(nil))
189 assert.Equal(t, "api, read_repository", FormatScopes([]string{"api", "read_repository"}))
190}
192func TestFormatDate(t *testing.T) {
193 t.Parallel()
195 d := gitlab.ISOTime(time.Date(2027, 1, 31, 0, 0, 0, 0, time.UTC))
196 assert.Equal(t, "-", FormatDate(nil))
197 assert.Equal(t, "2027-01-31", FormatDate(&d))
198}
200func TestFormatTime(t *testing.T) {
201 t.Parallel()
203 ts := time.Date(2026, 11, 5, 10, 30, 0, 0, time.FixedZone("CET", 3600))
204 assert.Equal(t, "-", FormatTime(nil))
205 assert.Equal(t, "2026-11-05T09:30:00Z", FormatTime(&ts))
206}
Diagnostics8 git calls · 243 ms
CallStatusSizeTime0243 ms
discover200185 B2 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
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=4 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
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit4 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=4273 git.response.cache=HIT git.response.duration_ms=4 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:02001.8 KiB · hit3 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=3 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:0200322 B · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=4 git.response.bytes=322 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=ba2caccf6c55211c6b29b98f40c2358479d91b1f 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=322 git.pkt.payload.max=295 git.sideband.band1.bytes=295 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=295 git.pack.trailer=3488e558d4708096e879feba968e084c249dbe22Open pack map
fetchtree:0200207 B · hit4 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=227 git.response.bytes=207 git.response.cache=HIT git.response.duration_ms=4 git.fetch.filter=tree:0 git.fetch.wants=46257722a5d9837ad7305a4a6942623f79e26348 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=207 git.pkt.payload.max=180 git.sideband.band1.bytes=180 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=180 git.pack.trailer=49c3336eecdc11d5831924e911d2e17735206333Open pack map
fetch2001.7 KiB227 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=1730 git.response.cache=MISS git.response.duration_ms=227 git.fetch.wants=6cc9184ee062e07437d5487a0520e11d5738d7e7 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=1730 git.pkt.payload.max=1703 git.sideband.band1.bytes=1703 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
- a5e370c85e9622ce
- Request
- c9289ac5…
- 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