GitLabgitlab-org

cli

main
ply9 git calls307 ms100 KiB7 cachedprotocol v2
347 lines11 KiBRaw
1//go:build !integration
3package rotate
5import (
6 "encoding/json"
7 "errors"
8 "testing"
9 "time"
11 "github.com/MakeNowJust/heredoc/v2"
12 "github.com/stretchr/testify/assert"
13 "github.com/stretchr/testify/require"
14 "go.uber.org/mock/gomock"
16 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
17 gitlabtesting "gitlab.com/gitlab-org/api/client-go/v3/testing"
19 "gitlab.com/gitlab-org/cli/internal/api"
20 "gitlab.com/gitlab-org/cli/internal/cmdutils"
21 "gitlab.com/gitlab-org/cli/internal/cmdutils/tokenduration"
22 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
25func setupExec(t *testing.T, tc *gitlabtesting.TestClient, opts ...cmdtest.FactoryOption) cmdtest.CmdExecFunc {
26 t.Helper()
28 opts = append(
29 []cmdtest.FactoryOption{
30 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "", "", api.WithGitLabClient(tc.Client))),
31 },
32 opts...,
33 )
35 return cmdtest.SetupCmdForTest(t, NewCmd, false, opts...)
38func noMorePages() *gitlab.Response {
39 return &gitlab.Response{NextPage: 0}
42func rotatedToken() *gitlab.PersonalAccessToken {
43 expiresAt := gitlab.ISOTime(time.Date(2027, 1, 31, 0, 0, 0, 0, time.UTC))
44 return &gitlab.PersonalAccessToken{
45 ID: 12,
46 Name: "ci",
47 Description: "CI token",
48 Scopes: []string{"api"},
49 Active: true,
50 ExpiresAt: &expiresAt,
51 Token: "glpat-new",
52 }
55// expectProjectRotate returns an accessor for the options the command sent, so
56// the tests can assert on the request and not only on what is printed.
57func expectProjectRotate(tc *gitlabtesting.TestClient) func() *gitlab.RotateProjectServiceAccountPersonalAccessTokenOptions {
58 var sent *gitlab.RotateProjectServiceAccountPersonalAccessTokenOptions
59 tc.MockProjects.EXPECT().
60 RotateProjectServiceAccountPersonalAccessToken("OWNER/REPO", int64(51), int64(7), gomock.Any(), gomock.Any()).
61 DoAndReturn(func(_ any, _, _ int64, opt *gitlab.RotateProjectServiceAccountPersonalAccessTokenOptions, _ ...gitlab.RequestOptionFunc) (*gitlab.PersonalAccessToken, *gitlab.Response, error) {
62 sent = opt
63 return rotatedToken(), nil, nil
64 })
66 return func() *gitlab.RotateProjectServiceAccountPersonalAccessTokenOptions { return sent }
69// No list expectation is set: both IDs go straight to the rotate.
70func TestTokenRotate_ProjectByIDs(t *testing.T) {
71 t.Parallel()
73 tc := gitlabtesting.NewTestClient(t)
74 expectProjectRotate(tc)
76 out, err := setupExec(t, tc)("51 7")
77 require.NoError(t, err)
79 assert.Equal(t, "glpat-new\n", out.OutBuf.String())
80 expected := heredoc.Doc(`
81 ID 12
82 Name ci
83 Description CI token
84 Scopes api
85 Expires At 2027-01-31
86 ! Rotated token 7 of service account 51 in project OWNER/REPO into token 12. Store the token value now. It is not shown again.
87 `)
88 assert.Equal(t, expected, out.ErrBuf.String())
91func TestTokenRotate_DefaultExpiryIs30Days(t *testing.T) {
92 t.Parallel()
94 tc := gitlabtesting.NewTestClient(t)
95 sent := expectProjectRotate(tc)
97 _, err := setupExec(t, tc)("51 7")
98 require.NoError(t, err)
100 want := tokenduration.TokenDuration(30 * 24 * time.Hour).CalculateExpirationDate().Format(time.DateOnly)
101 require.NotNil(t, sent().ExpiresAt)
102 assert.Equal(t, want, sent().ExpiresAt.String())
105func TestTokenRotate_Duration(t *testing.T) {
106 t.Parallel()
108 tc := gitlabtesting.NewTestClient(t)
109 sent := expectProjectRotate(tc)
111 _, err := setupExec(t, tc)("51 7 --duration 2w")
112 require.NoError(t, err)
114 want := tokenduration.TokenDuration(14 * 24 * time.Hour).CalculateExpirationDate().Format(time.DateOnly)
115 assert.Equal(t, want, sent().ExpiresAt.String())
118func TestTokenRotate_ExpiresAt(t *testing.T) {
119 t.Parallel()
121 tc := gitlabtesting.NewTestClient(t)
122 sent := expectProjectRotate(tc)
124 _, err := setupExec(t, tc)("51 7 --expires-at 2027-12-31")
125 require.NoError(t, err)
127 assert.Equal(t, "2027-12-31", sent().ExpiresAt.String())
130func TestTokenRotate_Group(t *testing.T) {
131 t.Parallel()
133 var sent *gitlab.RotateServiceAccountPersonalAccessTokenOptions
134 tc := gitlabtesting.NewTestClient(t)
135 tc.MockGroups.EXPECT().
136 RotateServiceAccountPersonalAccessToken("group/sub-group", int64(41), int64(9), gomock.Any(), gomock.Any()).
137 DoAndReturn(func(_ any, _, _ int64, opt *gitlab.RotateServiceAccountPersonalAccessTokenOptions, _ ...gitlab.RequestOptionFunc) (*gitlab.PersonalAccessToken, *gitlab.Response, error) {
138 sent = opt
139 return rotatedToken(), nil, nil
140 })
142 out, err := setupExec(t, tc)("41 9 --expires-at 2027-12-31 --group group/sub-group")
143 require.NoError(t, err)
145 assert.Equal(t, "2027-12-31", sent.ExpiresAt.String())
146 assert.Contains(t, out.ErrBuf.String(), "! Rotated token 9 of service account 41 in group group/sub-group into token 12. Store the token value now. It is not shown again.\n")
149func TestTokenRotate_ByNames(t *testing.T) {
150 t.Parallel()
152 tc := gitlabtesting.NewTestClient(t)
153 gomock.InOrder(
154 tc.MockProjects.EXPECT().
155 ListProjectServiceAccounts("OWNER/REPO", gomock.Any(), gomock.Any(), gomock.Any()).
156 Return([]*gitlab.ProjectServiceAccount{{ID: 52, Username: "release-bot"}}, noMorePages(), nil),
157 tc.MockProjects.EXPECT().
158 ListProjectServiceAccountPersonalAccessTokens("OWNER/REPO", int64(52), gomock.Cond(func(o *gitlab.ListProjectServiceAccountPersonalAccessTokensOptions) bool {
159 return o.State != nil && *o.State == "active" && o.Search != nil && *o.Search == "ci"
160 }), gomock.Any(), gomock.Any()).
161 Return([]*gitlab.PersonalAccessToken{{ID: 7, Name: "ci"}}, noMorePages(), nil),
162 tc.MockProjects.EXPECT().
163 RotateProjectServiceAccountPersonalAccessToken("OWNER/REPO", int64(52), int64(7), gomock.Any(), gomock.Any()).
164 Return(rotatedToken(), nil, nil),
165 )
167 out, err := setupExec(t, tc)("release-bot ci")
168 require.NoError(t, err)
170 assert.Contains(t, out.ErrBuf.String(), "Rotated token 7 of service account 52 in project OWNER/REPO into token 12.")
173// Like create, rotate prints the new token value, because this is the only
174// time GitLab returns it.
175func TestTokenRotate_JSONKeepsTokenValue(t *testing.T) {
176 t.Parallel()
178 tc := gitlabtesting.NewTestClient(t)
179 expectProjectRotate(tc)
181 out, err := setupExec(t, tc)("51 7 --output json")
182 require.NoError(t, err)
184 var result gitlab.PersonalAccessToken
185 require.NoError(t, json.Unmarshal(out.OutBuf.Bytes(), &result))
186 assert.Equal(t, int64(12), result.ID)
187 assert.Equal(t, "ci", result.Name)
188 assert.Equal(t, "glpat-new", result.Token)
189 assert.Empty(t, out.ErrBuf.String())
192func TestTokenRotate_DurationAndExpiresAtAreMutuallyExclusive(t *testing.T) {
193 t.Parallel()
195 tc := gitlabtesting.NewTestClient(t)
197 _, err := setupExec(t, tc)("51 7 --duration 7d --expires-at 2027-12-31")
198 require.Error(t, err)
199 assert.Contains(t, err.Error(), "none of the others can be")
202func TestTokenRotate_InvalidDuration(t *testing.T) {
203 t.Parallel()
205 tc := gitlabtesting.NewTestClient(t)
207 _, err := setupExec(t, tc)("51 7 --duration 400d")
208 require.Error(t, err)
209 assert.Contains(t, err.Error(), "duration must be between 1 and 365 days")
212func TestTokenRotate_InvalidExpiresAt(t *testing.T) {
213 t.Parallel()
215 tc := gitlabtesting.NewTestClient(t)
217 _, err := setupExec(t, tc)("51 7 --expires-at 31.12.2027")
218 require.Error(t, err)
219 assert.Contains(t, err.Error(), `invalid argument "31.12.2027" for "-E, --expires-at"`)
222func TestTokenRotate_TokenNameNotFound(t *testing.T) {
223 t.Parallel()
225 tc := gitlabtesting.NewTestClient(t)
226 tc.MockProjects.EXPECT().
227 ListProjectServiceAccountPersonalAccessTokens("OWNER/REPO", int64(51), gomock.Any(), gomock.Any(), gomock.Any()).
228 Return([]*gitlab.PersonalAccessToken{}, noMorePages(), nil)
230 _, err := setupExec(t, tc)("51 ci")
231 require.Error(t, err)
233 var exitErr *cmdutils.ExitError
234 require.ErrorAs(t, err, &exitErr)
235 assert.Equal(t, "failed to rotate service account token", exitErr.Details)
236 assert.Contains(t, err.Error(), `no active token named "ci" for service account 51 in project OWNER/REPO`)
239func TestTokenRotate_DuplicateTokenName(t *testing.T) {
240 t.Parallel()
242 tc := gitlabtesting.NewTestClient(t)
243 tc.MockProjects.EXPECT().
244 ListProjectServiceAccountPersonalAccessTokens("OWNER/REPO", int64(51), gomock.Any(), gomock.Any(), gomock.Any()).
245 Return([]*gitlab.PersonalAccessToken{{ID: 7, Name: "ci"}, {ID: 8, Name: "ci"}}, noMorePages(), nil)
247 _, err := setupExec(t, tc)("51 ci")
248 require.Error(t, err)
249 assert.Contains(t, err.Error(), `multiple active tokens named "ci" for service account 51; use the token ID instead`)
252func TestTokenRotate_InvalidTokenID(t *testing.T) {
253 t.Parallel()
255 tc := gitlabtesting.NewTestClient(t)
257 _, err := setupExec(t, tc)("51 0")
258 require.Error(t, err)
259 assert.Contains(t, err.Error(), `invalid token ID "0"`)
262func TestTokenRotate_InvalidAccountID(t *testing.T) {
263 t.Parallel()
265 tc := gitlabtesting.NewTestClient(t)
267 _, err := setupExec(t, tc)("0 7")
268 require.Error(t, err)
269 assert.Contains(t, err.Error(), `invalid service account ID "0"`)
272func TestTokenRotate_APIError(t *testing.T) {
273 t.Parallel()
275 tc := gitlabtesting.NewTestClient(t)
276 tc.MockProjects.EXPECT().
277 RotateProjectServiceAccountPersonalAccessToken("OWNER/REPO", int64(51), int64(7), gomock.Any(), gomock.Any()).
278 Return(nil, nil, errors.New("400 Bad Request"))
280 _, err := setupExec(t, tc)("51 7")
281 require.Error(t, err)
283 var exitErr *cmdutils.ExitError
284 require.ErrorAs(t, err, &exitErr)
285 assert.Equal(t, "failed to rotate service account token", exitErr.Details)
286 assert.Contains(t, err.Error(), "400 Bad Request")
289func TestTokenRotate_RequiresArguments(t *testing.T) {
290 t.Parallel()
292 tc := gitlabtesting.NewTestClient(t)
294 _, err := setupExec(t, tc)("51")
295 require.Error(t, err)
296 assert.Contains(t, err.Error(), "accepts 2 arg(s), received 1")
299func TestTokenRotate_RepoAndGroupAreMutuallyExclusive(t *testing.T) {
300 t.Parallel()
302 tc := gitlabtesting.NewTestClient(t)
304 _, err := setupExec(t, tc)("51 7 --repo OWNER/REPO --group my-group")
305 require.Error(t, err)
306 assert.Contains(t, err.Error(), "none of the others can be")
309func TestTokenRotate_OutsideRepositoryWithoutGroup(t *testing.T) {
310 t.Parallel()
312 tc := gitlabtesting.NewTestClient(t)
314 _, err := setupExec(t, tc, cmdtest.WithBaseRepoError(errors.New("not a git repository")))("51 7")
315 require.Error(t, err)
316 assert.Contains(t, err.Error(), "not a git repository")
319func TestTokenRotate_OutsideRepositoryWithGroup(t *testing.T) {
320 t.Parallel()
322 tc := gitlabtesting.NewTestClient(t)
323 tc.MockGroups.EXPECT().
324 RotateServiceAccountPersonalAccessToken("my-group", int64(41), int64(9), gomock.Any(), gomock.Any()).
325 Return(rotatedToken(), nil, nil)
327 out, err := setupExec(t, tc, cmdtest.WithBaseRepoError(errors.New("not a git repository")))("41 9 --group my-group")
328 require.NoError(t, err)
330 assert.Contains(t, out.OutBuf.String(), "glpat-new")
333// GITLAB_GROUP redirects the command with no flag passed. t.Setenv rules out
334// t.Parallel.
335func TestTokenRotate_GroupFromEnvironment(t *testing.T) {
336 t.Setenv("GITLAB_GROUP", "env-group")
338 tc := gitlabtesting.NewTestClient(t)
339 tc.MockGroups.EXPECT().
340 RotateServiceAccountPersonalAccessToken("env-group", int64(41), int64(9), gomock.Any(), gomock.Any()).
341 Return(rotatedToken(), nil, nil)
343 out, err := setupExec(t, tc)("41 9")
344 require.NoError(t, err)
346 assert.Contains(t, out.ErrBuf.String(), "in group env-group into token 12.")
Diagnostics9 git calls · 307 ms
CallStatusSizeTime0307 ms
discover200185 B2 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=2
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 KiB · hit2 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=HIT
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 · 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=4273
git.response.cache=HIT
git.response.duration_ms=3
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=3
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=44
Open pack map
fetchtree:02001.8 KiB · hit1 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=1
git.response.bytes=1857
git.response.cache=HIT
git.response.duration_ms=1
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=fb03183b7909876778f740d196d7516811003517
Open 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=3
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=3488e558d4708096e879feba968e084c249dbe22
Open pack map
fetchtree:0200223 B · 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=223
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=tree:0
git.fetch.wants=41d72d07155f99e3acc572f8fe5ad26c802e4ddc
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=223
git.pkt.payload.max=196
git.sideband.band1.bytes=196
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=196
git.pack.trailer=d9c58aac50f427eb21501a81fe28c81c7c49ae44
Open pack map
fetchtree:0200138 B · 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=138
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=d264b3875ee1acf022000760e2b7fc444284f0af
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=138
git.pkt.payload.max=111
git.sideband.band1.bytes=111
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=111
git.pack.trailer=ddb4ccc30fa55adee2cda1366700c19af506815f
Open pack map
fetch2002.5 KiB293 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=293
git.response.bytes=2511
git.response.cache=MISS
git.response.duration_ms=293
git.fetch.wants=a547aebea80bb2162450526ed3f10fc5b3582f0f
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=2511
git.pkt.payload.max=2484
git.sideband.band1.bytes=2484
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
a5e35c088ea0dfff
Request
48360a79…
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