GitLabgitlab-org

cli

main
ply8 git calls368 ms101 KiB6 cachedprotocol v2
694 lines22 KiBRaw
1//go:build !integration
3package rotate
5import (
6 "encoding/json"
7 "errors"
8 "testing"
9 "time"
11 "github.com/spf13/cobra"
12 "github.com/stretchr/testify/assert"
13 "github.com/stretchr/testify/require"
14 "github.com/zalando/go-keyring"
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/config"
22 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
25// noMorePages creates a response that indicates no more pages are available
26func noMorePages() *gitlab.Response {
27 return &gitlab.Response{NextPage: 0}
30func parseTime(s string) *time.Time {
31 t, _ := time.Parse(time.RFC3339, s)
32 return &t
35func TestRotatePersonalAccessToken(t *testing.T) {
36 // NOTE: Subtests cannot run in parallel because they use cmdutils.GroupOverride()
37 // which modifies global viper state (SetEnvPrefix, BindEnv).
39 type testCase struct {
40 name string
41 cli string
42 expectedOut string
43 wantJSON bool
44 wantErr bool
45 wantStderr string
46 setupMock func(tc *gitlabtesting.TestClient)
47 }
49 testUser := &gitlab.User{
50 ID: 1,
51 Username: "johndoe",
52 Name: "John Doe",
53 Email: "john.doe@acme.com",
54 }
56 testPAT := &gitlab.PersonalAccessToken{
57 ID: 10183862,
58 Name: "my-pat",
59 Revoked: false,
60 CreatedAt: parseTime("2024-07-08T01:23:04.311Z"),
61 Scopes: []string{"k8s_proxy"},
62 UserID: 926857,
63 Active: true,
64 ExpiresAt: new(gitlab.ISOTime(*parseTime("2024-08-07T00:00:00Z"))),
65 Token: "sometoken",
66 }
68 testCases := []testCase{
69 {
70 name: "rotate PAT as text",
71 cli: "--user @me my-pat",
72 expectedOut: "sometoken\n",
73 setupMock: func(tc *gitlabtesting.TestClient) {
74 tc.MockUsers.EXPECT().
75 CurrentUser(gomock.Any()).
76 Return(testUser, nil, nil)
77 tc.MockPersonalAccessTokens.EXPECT().
78 ListPersonalAccessTokens(gomock.Any(), gomock.Any(), gomock.Any()).
79 Return([]*gitlab.PersonalAccessToken{testPAT}, noMorePages(), nil)
80 tc.MockPersonalAccessTokens.EXPECT().
81 RotatePersonalAccessToken(int64(10183862), gomock.Any(), gomock.Any()).
82 Return(testPAT, nil, nil)
83 },
84 },
85 {
86 name: "rotate PAT as json",
87 cli: "--user @me --output json my-pat",
88 wantJSON: true,
89 setupMock: func(tc *gitlabtesting.TestClient) {
90 tc.MockUsers.EXPECT().
91 CurrentUser(gomock.Any()).
92 Return(testUser, nil, nil)
93 tc.MockPersonalAccessTokens.EXPECT().
94 ListPersonalAccessTokens(gomock.Any(), gomock.Any(), gomock.Any()).
95 Return([]*gitlab.PersonalAccessToken{testPAT}, noMorePages(), nil)
96 tc.MockPersonalAccessTokens.EXPECT().
97 RotatePersonalAccessToken(int64(10183862), gomock.Any(), gomock.Any()).
98 Return(testPAT, nil, nil)
99 },
100 },
101 {
102 name: "rotate PAT by ID",
103 cli: "--user @me 10183862",
104 expectedOut: "sometoken\n",
105 setupMock: func(tc *gitlabtesting.TestClient) {
106 tc.MockUsers.EXPECT().
107 CurrentUser(gomock.Any()).
108 Return(testUser, nil, nil)
109 tc.MockPersonalAccessTokens.EXPECT().
110 ListPersonalAccessTokens(gomock.Any(), gomock.Any(), gomock.Any()).
111 Return([]*gitlab.PersonalAccessToken{testPAT}, noMorePages(), nil)
112 tc.MockPersonalAccessTokens.EXPECT().
113 RotatePersonalAccessToken(int64(10183862), gomock.Any(), gomock.Any()).
114 Return(testPAT, nil, nil)
115 },
116 },
117 {
118 name: "error when PAT not found by ID",
119 cli: "--user @me 99999",
120 wantErr: true,
121 wantStderr: "no active token found with the ID '99999'",
122 setupMock: func(tc *gitlabtesting.TestClient) {
123 tc.MockUsers.EXPECT().
124 CurrentUser(gomock.Any()).
125 Return(testUser, nil, nil)
126 tc.MockPersonalAccessTokens.EXPECT().
127 ListPersonalAccessTokens(gomock.Any(), gomock.Any(), gomock.Any()).
128 Return([]*gitlab.PersonalAccessToken{testPAT}, noMorePages(), nil)
129 },
130 },
131 {
132 name: "error when missing argument without self",
133 cli: "",
134 wantErr: true,
135 wantStderr: "requires either '--self' or a token name/ID argument",
136 setupMock: func(tc *gitlabtesting.TestClient) {},
137 },
138 }
140 for _, tc := range testCases {
141 t.Run(tc.name, func(t *testing.T) {
142 // GIVEN
143 testClient := gitlabtesting.NewTestClient(t)
144 tc.setupMock(testClient)
145 exec := cmdtest.SetupCmdForTest(
146 t,
147 NewCmdRotate,
148 true,
149 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "", "", api.WithGitLabClient(testClient.Client))),
150 )
152 // WHEN
153 out, err := exec(tc.cli)
155 // THEN
156 if tc.wantErr {
157 require.Error(t, err)
158 assert.Contains(t, err.Error(), tc.wantStderr)
159 return
160 }
161 require.NoError(t, err)
162 if tc.wantJSON {
163 var result map[string]any
164 err := json.Unmarshal(out.OutBuf.Bytes(), &result)
165 require.NoError(t, err)
166 assert.Equal(t, "my-pat", result["name"])
167 } else if tc.expectedOut != "" {
168 assert.Equal(t, tc.expectedOut, out.OutBuf.String())
169 }
170 assert.Empty(t, out.ErrBuf.String())
171 })
172 }
175func TestRotateGroupAccessToken(t *testing.T) {
176 // NOTE: Subtests cannot run in parallel because they use cmdutils.GroupOverride()
177 // which modifies global viper state (SetEnvPrefix, BindEnv).
179 type testCase struct {
180 name string
181 cli string
182 expectedOut string
183 wantJSON bool
184 wantErr bool
185 wantStderr string
186 setupMock func(tc *gitlabtesting.TestClient)
187 }
189 testGroupToken := &gitlab.GroupAccessToken{
190 PersonalAccessToken: gitlab.PersonalAccessToken{
191 ID: 10190772,
192 UserID: 21989300,
193 Name: "my-group-token",
194 Scopes: []string{"read_registry", "read_repository"},
195 CreatedAt: parseTime("2024-07-08T17:33:34.829Z"),
196 ExpiresAt: new(gitlab.ISOTime(*parseTime("2024-08-07T00:00:00Z"))),
197 Active: true,
198 Revoked: false,
199 Token: "glpat-yz2791KMU-xxxxxxxxx",
200 },
201 AccessLevel: gitlab.DeveloperPermissions,
202 }
204 testCases := []testCase{
205 {
206 name: "rotate group token as text",
207 cli: "--group GROUP my-group-token",
208 expectedOut: "glpat-yz2791KMU-xxxxxxxxx\n",
209 setupMock: func(tc *gitlabtesting.TestClient) {
210 tc.MockGroupAccessTokens.EXPECT().
211 ListGroupAccessTokens("GROUP", gomock.Any(), gomock.Any(), gomock.Any()).
212 Return([]*gitlab.GroupAccessToken{testGroupToken}, noMorePages(), nil)
213 tc.MockGroupAccessTokens.EXPECT().
214 RotateGroupAccessToken("GROUP", int64(10190772), gomock.Any(), gomock.Any()).
215 Return(testGroupToken, nil, nil)
216 },
217 },
218 {
219 name: "rotate group token as json",
220 cli: "--group GROUP my-group-token --output json",
221 wantJSON: true,
222 setupMock: func(tc *gitlabtesting.TestClient) {
223 tc.MockGroupAccessTokens.EXPECT().
224 ListGroupAccessTokens("GROUP", gomock.Any(), gomock.Any(), gomock.Any()).
225 Return([]*gitlab.GroupAccessToken{testGroupToken}, noMorePages(), nil)
226 tc.MockGroupAccessTokens.EXPECT().
227 RotateGroupAccessToken("GROUP", int64(10190772), gomock.Any(), gomock.Any()).
228 Return(testGroupToken, nil, nil)
229 },
230 },
231 {
232 name: "rotate group token by ID",
233 cli: "--group GROUP 10190772",
234 expectedOut: "glpat-yz2791KMU-xxxxxxxxx\n",
235 setupMock: func(tc *gitlabtesting.TestClient) {
236 tc.MockGroupAccessTokens.EXPECT().
237 ListGroupAccessTokens("GROUP", gomock.Any(), gomock.Any(), gomock.Any()).
238 Return([]*gitlab.GroupAccessToken{testGroupToken}, noMorePages(), nil)
239 tc.MockGroupAccessTokens.EXPECT().
240 RotateGroupAccessToken("GROUP", int64(10190772), gomock.Any(), gomock.Any()).
241 Return(testGroupToken, nil, nil)
242 },
243 },
244 }
246 for _, tc := range testCases {
247 t.Run(tc.name, func(t *testing.T) {
248 // GIVEN
249 testClient := gitlabtesting.NewTestClient(t)
250 tc.setupMock(testClient)
251 exec := cmdtest.SetupCmdForTest(
252 t,
253 NewCmdRotate,
254 true,
255 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "", "", api.WithGitLabClient(testClient.Client))),
256 )
258 // WHEN
259 out, err := exec(tc.cli)
261 // THEN
262 if tc.wantErr {
263 require.Error(t, err)
264 assert.Contains(t, err.Error(), tc.wantStderr)
265 return
266 }
267 require.NoError(t, err)
268 if tc.wantJSON {
269 var result map[string]any
270 err := json.Unmarshal(out.OutBuf.Bytes(), &result)
271 require.NoError(t, err)
272 assert.Equal(t, "my-group-token", result["name"])
273 } else if tc.expectedOut != "" {
274 assert.Equal(t, tc.expectedOut, out.OutBuf.String())
275 }
276 assert.Empty(t, out.ErrBuf.String())
277 })
278 }
281func TestRotateProjectAccessToken(t *testing.T) {
282 // NOTE: Subtests cannot run in parallel because they use cmdutils.GroupOverride()
283 // which modifies global viper state (SetEnvPrefix, BindEnv).
285 type testCase struct {
286 name string
287 cli string
288 expectedOut string
289 wantJSON bool
290 wantErr bool
291 wantStderr string
292 setupMock func(tc *gitlabtesting.TestClient)
293 }
295 testProjectToken := &gitlab.ProjectAccessToken{
296 PersonalAccessToken: gitlab.PersonalAccessToken{
297 ID: 10191548,
298 UserID: 21990679,
299 Name: "my-project-token",
300 Scopes: []string{"api", "read_repository"},
301 CreatedAt: parseTime("2024-07-08T19:47:14.727Z"),
302 ExpiresAt: new(gitlab.ISOTime(*parseTime("2024-08-07T00:00:00Z"))),
303 Active: true,
304 Revoked: false,
305 Token: "glpat-dfsdfjksjdfslkdfjsd",
306 },
307 AccessLevel: gitlab.DeveloperPermissions,
308 }
310 testCases := []testCase{
311 {
312 name: "rotate project token as text",
313 cli: "my-project-token",
314 expectedOut: "glpat-dfsdfjksjdfslkdfjsd\n",
315 setupMock: func(tc *gitlabtesting.TestClient) {
316 tc.MockProjectAccessTokens.EXPECT().
317 ListProjectAccessTokens("OWNER/REPO", gomock.Any(), gomock.Any(), gomock.Any()).
318 Return([]*gitlab.ProjectAccessToken{testProjectToken}, noMorePages(), nil)
319 tc.MockProjectAccessTokens.EXPECT().
320 RotateProjectAccessToken("OWNER/REPO", int64(10191548), gomock.Any(), gomock.Any()).
321 Return(testProjectToken, nil, nil)
322 },
323 },
324 {
325 name: "rotate project token as json",
326 cli: "--output json my-project-token",
327 wantJSON: true,
328 setupMock: func(tc *gitlabtesting.TestClient) {
329 tc.MockProjectAccessTokens.EXPECT().
330 ListProjectAccessTokens("OWNER/REPO", gomock.Any(), gomock.Any(), gomock.Any()).
331 Return([]*gitlab.ProjectAccessToken{testProjectToken}, noMorePages(), nil)
332 tc.MockProjectAccessTokens.EXPECT().
333 RotateProjectAccessToken("OWNER/REPO", int64(10191548), gomock.Any(), gomock.Any()).
334 Return(testProjectToken, nil, nil)
335 },
336 },
337 {
338 name: "rotate project token by ID",
339 cli: "10191548",
340 expectedOut: "glpat-dfsdfjksjdfslkdfjsd\n",
341 setupMock: func(tc *gitlabtesting.TestClient) {
342 tc.MockProjectAccessTokens.EXPECT().
343 ListProjectAccessTokens("OWNER/REPO", gomock.Any(), gomock.Any(), gomock.Any()).
344 Return([]*gitlab.ProjectAccessToken{testProjectToken}, noMorePages(), nil)
345 tc.MockProjectAccessTokens.EXPECT().
346 RotateProjectAccessToken("OWNER/REPO", int64(10191548), gomock.Any(), gomock.Any()).
347 Return(testProjectToken, nil, nil)
348 },
349 },
350 }
352 for _, tc := range testCases {
353 t.Run(tc.name, func(t *testing.T) {
354 // GIVEN
355 testClient := gitlabtesting.NewTestClient(t)
356 tc.setupMock(testClient)
357 exec := cmdtest.SetupCmdForTest(
358 t,
359 NewCmdRotate,
360 true,
361 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "", "", api.WithGitLabClient(testClient.Client))),
362 )
364 // WHEN
365 out, err := exec(tc.cli)
367 // THEN
368 if tc.wantErr {
369 require.Error(t, err)
370 assert.Contains(t, err.Error(), tc.wantStderr)
371 return
372 }
373 require.NoError(t, err)
374 if tc.wantJSON {
375 var result map[string]any
376 err := json.Unmarshal(out.OutBuf.Bytes(), &result)
377 require.NoError(t, err)
378 assert.Equal(t, "my-project-token", result["name"])
379 } else if tc.expectedOut != "" {
380 assert.Equal(t, tc.expectedOut, out.OutBuf.String())
381 }
382 assert.Empty(t, out.ErrBuf.String())
383 })
384 }
387func TestRotatePersonalAccessTokenSelf(t *testing.T) {
388 // NOTE: Subtests cannot run in parallel because they use cmdutils.GroupOverride()
389 // which modifies global viper state (SetEnvPrefix, BindEnv).
391 type testCase struct {
392 name string
393 cli string
394 expectedOut string
395 wantJSON bool
396 wantErr bool
397 wantStderr string
398 setupMock func(tc *gitlabtesting.TestClient)
399 }
401 testPAT := &gitlab.PersonalAccessToken{
402 ID: 10183862,
403 Name: "my-pat",
404 Revoked: false,
405 CreatedAt: parseTime("2024-07-08T01:23:04.311Z"),
406 Scopes: []string{"k8s_proxy"},
407 UserID: 926857,
408 Active: true,
409 ExpiresAt: new(gitlab.ISOTime(*parseTime("2024-08-07T00:00:00Z"))),
410 Token: "newtoken",
411 }
413 testCases := []testCase{
414 {
415 name: "rotate self as text",
416 cli: "--self",
417 expectedOut: "newtoken\n",
418 setupMock: func(tc *gitlabtesting.TestClient) {
419 tc.MockPersonalAccessTokens.EXPECT().
420 RotatePersonalAccessTokenSelf(gomock.Any(), gomock.Any()).
421 Return(testPAT, nil, nil)
422 },
423 },
424 {
425 name: "rotate self as json",
426 cli: "--self --output json",
427 wantJSON: true,
428 setupMock: func(tc *gitlabtesting.TestClient) {
429 tc.MockPersonalAccessTokens.EXPECT().
430 RotatePersonalAccessTokenSelf(gomock.Any(), gomock.Any()).
431 Return(testPAT, nil, nil)
432 },
433 },
434 {
435 name: "error when self with positional argument",
436 cli: "--self my-token",
437 wantErr: true,
438 wantStderr: "'--self' does not accept a positional argument",
439 setupMock: func(tc *gitlabtesting.TestClient) {},
440 },
441 }
443 for _, tc := range testCases {
444 t.Run(tc.name, func(t *testing.T) {
445 // GIVEN
446 testClient := gitlabtesting.NewTestClient(t)
447 tc.setupMock(testClient)
448 exec := cmdtest.SetupCmdForTest(
449 t,
450 NewCmdRotate,
451 true,
452 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "", "gitlab.example.com", api.WithGitLabClient(testClient.Client))),
453 )
455 // WHEN
456 out, err := exec(tc.cli)
458 // THEN
459 if tc.wantErr {
460 require.Error(t, err)
461 assert.Contains(t, err.Error(), tc.wantStderr)
462 return
463 }
464 require.NoError(t, err)
465 if tc.wantJSON {
466 var result map[string]any
467 err := json.Unmarshal(out.OutBuf.Bytes(), &result)
468 require.NoError(t, err)
469 assert.Equal(t, "my-pat", result["name"])
470 } else if tc.expectedOut != "" {
471 assert.Equal(t, tc.expectedOut, out.OutBuf.String())
472 }
473 assert.Empty(t, out.ErrBuf.String())
474 })
475 }
478// failingSetConfig makes the credential write fail, to prove the new token is
479// printed before glab tries to store it.
480type failingSetConfig struct{ config.Config }
482func (failingSetConfig) Set(string, string, string) error { return errors.New("disk full") }
484func TestRotateSelf_StoredToken(t *testing.T) {
485 const host = "gitlab.example.com"
487 rotated := &gitlab.PersonalAccessToken{ID: 1, Name: "my-pat", Active: true, Token: "newtoken"}
489 tests := []struct {
490 name string
491 hostsYAML string
492 seedToken bool
493 seedLegacy bool
494 envToken string
495 apiHost string
496 noBaseRepo bool
497 wrap func(config.Config) config.Config
498 cli string
499 wantErr string
500 wantStored string
501 wantStderr []string
502 notStderr []string
503 noStderr bool
504 }{
505 {
506 name: "config file token is replaced",
507 hostsYAML: "hosts:\n gitlab.example.com:\n token: oldtoken\n use_keyring: \"false\"\n",
508 cli: "--self",
509 wantStored: "newtoken",
510 wantStderr: []string{"Updated the stored token for gitlab.example.com", "config file"},
511 },
512 {
513 name: "keyring token is replaced",
514 hostsYAML: "hosts:\n gitlab.example.com:\n use_keyring: \"true\"\n",
515 seedToken: true,
516 cli: "--self",
517 wantStored: "newtoken",
518 wantStderr: []string{"Updated the stored token for gitlab.example.com", "keyring"},
519 },
520 {
521 name: "stdout stays clean JSON while stderr reports the update",
522 hostsYAML: "hosts:\n gitlab.example.com:\n token: oldtoken\n use_keyring: \"false\"\n",
523 cli: "--self --output json",
524 wantStored: "newtoken",
525 wantStderr: []string{"Updated the stored token for gitlab.example.com"},
526 },
527 {
528 name: "environment token cannot be updated, so glab warns",
529 hostsYAML: "hosts:\n gitlab.example.com:\n use_keyring: \"false\"\n",
530 envToken: "envtoken",
531 cli: "--self",
532 wantStored: "",
533 wantStderr: []string{"GITLAB_TOKEN", "gitlab.example.com", "can't update"},
534 },
535 {
536 name: "no stored token means nothing to update and nothing printed",
537 hostsYAML: "hosts:\n gitlab.example.com:\n use_keyring: \"false\"\n",
538 cli: "--self",
539 noStderr: true,
540 },
541 {
542 name: "an api_host is not the key the token is stored under",
543 hostsYAML: "hosts:\n gitlab.example.com:\n token: oldtoken\n api_host: api.example.com\n use_keyring: \"false\"\n",
544 apiHost: "api.example.com",
545 cli: "--self",
546 wantStored: "newtoken",
547 wantStderr: []string{"Updated the stored token for gitlab.example.com", "config file"},
548 },
549 {
550 name: "outside a repository the default host is the key",
551 hostsYAML: "hosts:\n gitlab.example.com:\n token: oldtoken\n use_keyring: \"false\"\n",
552 noBaseRepo: true,
553 cli: "--self",
554 wantStored: "newtoken",
555 wantStderr: []string{"Updated the stored token for gitlab.example.com", "config file"},
556 },
557 {
558 name: "a legacy keyring token moves to the config file and the message says so",
559 hostsYAML: "hosts:\n gitlab.example.com:\n api_protocol: https\n",
560 seedLegacy: true,
561 cli: "--self",
562 wantStored: "newtoken",
563 wantStderr: []string{"Updated the stored token for gitlab.example.com", "config file"},
564 notStderr: []string{"keyring"},
565 },
566 {
567 name: "a failed write still prints the token and reports the failure",
568 hostsYAML: "hosts:\n gitlab.example.com:\n token: oldtoken\n use_keyring: \"false\"\n",
569 wrap: func(c config.Config) config.Config { return failingSetConfig{c} },
570 cli: "--self",
571 wantErr: "could not store the new token for gitlab.example.com",
572 wantStderr: nil,
573 },
574 }
576 for _, tt := range tests {
577 t.Run(tt.name, func(t *testing.T) {
578 keyring.MockInit()
579 for _, k := range []string{"GITLAB_TOKEN", "GITLAB_ACCESS_TOKEN", "OAUTH_TOKEN", "CI_JOB_TOKEN", "GITLAB_CI"} {
580 t.Setenv(k, "")
581 }
582 if tt.envToken != "" {
583 t.Setenv("GITLAB_TOKEN", tt.envToken)
584 }
586 cfg := config.NewFromStringInDir(tt.hostsYAML, t.TempDir())
587 if tt.seedToken {
588 require.NoError(t, cfg.Set(host, "token", "oldtoken"))
589 }
590 if tt.seedLegacy {
591 require.NoError(t, keyring.Set("glab:"+host+":token", "", "oldtoken"))
592 }
593 factoryCfg := cfg
594 if tt.wrap != nil {
595 factoryCfg = tt.wrap(cfg)
596 }
598 testClient := gitlabtesting.NewTestClient(t)
599 testClient.MockPersonalAccessTokens.EXPECT().
600 RotatePersonalAccessTokenSelf(gomock.Any(), gomock.Any()).
601 Return(rotated, nil, nil)
602 apiHost := host
603 if tt.apiHost != "" {
604 apiHost = tt.apiHost
605 }
606 repoOption := cmdtest.WithBaseRepo("OWNER", "REPO", host)
607 if tt.noBaseRepo {
608 repoOption = cmdtest.WithBaseRepoError(errors.New("no repository"))
609 }
610 exec := cmdtest.SetupCmdForTest(
611 t,
612 NewCmdRotate,
613 true,
614 cmdtest.WithConfig(factoryCfg),
615 cmdtest.WithDefaultHostname(host),
616 repoOption,
617 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "", apiHost, api.WithGitLabClient(testClient.Client))),
618 )
620 out, err := exec(tt.cli)
622 if tt.wantErr != "" {
623 require.Error(t, err)
624 assert.Contains(t, err.Error(), tt.wantErr)
625 assert.Equal(t, "newtoken\n", out.OutBuf.String(), "the token must be printed before the store is attempted")
626 return
627 }
628 require.NoError(t, err)
629 if tt.cli == "--self" {
630 assert.Equal(t, "newtoken\n", out.OutBuf.String(), "stdout carries only the token")
631 } else {
632 var parsed map[string]any
633 require.NoError(t, json.Unmarshal(out.OutBuf.Bytes(), &parsed), "stdout must stay valid JSON")
634 }
635 if tt.noStderr {
636 assert.Empty(t, out.ErrBuf.String())
637 }
638 for _, want := range tt.wantStderr {
639 assert.Contains(t, out.ErrBuf.String(), want)
640 }
641 for _, unwanted := range tt.notStderr {
642 assert.NotContains(t, out.ErrBuf.String(), unwanted)
643 }
644 got, _, getErr := cfg.GetWithSource(host, "token", false)
645 require.NoError(t, getErr)
646 assert.Equal(t, tt.wantStored, got)
647 })
648 }
651func TestRotate_Completions(t *testing.T) {
652 testClient := gitlabtesting.NewTestClient(t)
653 // No mock expectations: with an argument already present the completion
654 // must not call the API.
655 f := cmdtest.NewTestFactory(nil,
656 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "", "", api.WithGitLabClient(testClient.Client))),
657 )
659 // With --self set, no token names are offered.
660 cmd := NewCmdRotate(f)
661 cmd.SetContext(t.Context())
662 require.NoError(t, cmd.Flags().Set("self", "true"))
663 comps, directive := cmd.ValidArgsFunction(cmd, []string{}, "")
664 assert.Empty(t, comps)
665 assert.Equal(t, cobra.ShellCompDirectiveNoFileComp, directive)
667 cmd = NewCmdRotate(f)
668 cmd.SetContext(t.Context())
670 comps, directive = cmd.ValidArgsFunction(cmd, []string{"123"}, "")
671 assert.Empty(t, comps)
672 assert.Equal(t, cobra.ShellCompDirectiveNoFileComp, directive)
674 testCases := map[string]struct {
675 wantComps []cobra.Completion
676 wantDirective cobra.ShellCompDirective
677 }{
678 "group": {wantDirective: cobra.ShellCompDirectiveNoFileComp},
679 "user": {wantComps: []cobra.Completion{cobra.CompletionWithDesc("@me", "Current user")}, wantDirective: cobra.ShellCompDirectiveNoFileComp},
680 "duration": {wantDirective: cobra.ShellCompDirectiveNoFileComp},
681 "expires-at": {wantDirective: cobra.ShellCompDirectiveNoFileComp},
682 }
684 for flag, tc := range testCases {
685 t.Run(flag, func(t *testing.T) {
686 compFn, ok := cmd.GetFlagCompletionFunc(flag)
687 require.True(t, ok, "--%s should have a completion function registered", flag)
689 comps, directive := compFn(cmd, nil, "")
690 assert.Equal(t, tc.wantComps, comps)
691 assert.Equal(t, tc.wantDirective, directive)
692 })
693 }
Diagnostics8 git calls · 368 ms
CallStatusSizeTime0368 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=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
fetchtree:0 · deepen 1020032 KiB · hit2 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=2
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
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=fb03183b7909876778f740d196d7516811003517
Open pack map
fetchtree:0200358 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=358
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=218b543e075f31e84c52193d193103408c52cb34
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=358
git.pkt.payload.max=331
git.sideband.band1.bytes=331
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=331
git.pack.trailer=fbb77d44047cd3e1ee682eb9483227c59489e50f
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=353
git.response.bytes=138
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=af225ea2432d7fff1c2afd415d9aa91b45507f7a
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=dfb59e832d53de2ef63e61029c585106e9af59eb
Open pack map
fetch2003.9 KiB353 ms
git.upload-pack fetch
http.response.status_code=200
git.response.bytes=3945
git.response.cache=MISS
git.response.duration_ms=353
git.fetch.wants=a3e5c6e5e668d13f3be6e403cf027577d13fdf1d
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=3945
git.pkt.payload.max=3918
git.sideband.band1.bytes=3918
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
a5e2ebc27f2a4bc2
Request
0b290501…
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