GitLabgitlab-org
cli
main
1//go:build !integration
3package login
5import (
6 "bytes"
7 "context"
8 "errors"
9 "io"
10 "net/http"
11 "net/http/httptest"
12 "os"
13 "os/exec"
14 "path/filepath"
15 "strings"
16 "testing"
17 "time"
19 tea "charm.land/bubbletea/v2"
20 "git.sr.ht/~timofurrer/ugh"
21 "github.com/google/shlex"
22 "github.com/stretchr/testify/assert"
23 "github.com/stretchr/testify/require"
24 "github.com/zalando/go-keyring"
25 "go.uber.org/mock/gomock"
27 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
28 gitlabtesting "gitlab.com/gitlab-org/api/client-go/v3/testing"
30 "gitlab.com/gitlab-org/cli/internal/api"
31 "gitlab.com/gitlab-org/cli/internal/config"
32 "gitlab.com/gitlab-org/cli/internal/iostreams"
33 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
34)
36// currentUserFactoryOption stubs the username lookup that a token login makes
37// after storing the token.
38func currentUserFactoryOption(t *testing.T) cmdtest.FactoryOption {
39 t.Helper()
41 tc := gitlabtesting.NewTestClient(t)
42 tc.MockUsers.EXPECT().
43 CurrentUser(gomock.Any()).
44 Return(&gitlab.User{Username: "john_smith"}, nil, nil).
45 AnyTimes()
47 return cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, nil, "", "gitlab.com", api.WithGitLabClient(tc.Client)))
48}
50func TestMain(m *testing.M) {
51 cmdtest.InitTest(m, "auth_login_test")
52}
54func Test_NewCmdLogin(t *testing.T) {
55 tests := []struct {
56 name string
57 cli string
58 stdin string
59 wants LoginOptions
60 stdinTTY bool
61 wantsErr bool
62 err string
63 }{
64 {
65 name: "nontty, stdin",
66 stdin: "abc123\n",
67 cli: "--stdin",
68 wants: LoginOptions{
69 Hostname: "gitlab.com",
70 Token: "abc123",
71 },
72 },
73 {
74 name: "tty, stdin",
75 stdin: "def456",
76 cli: "--stdin",
77 wants: LoginOptions{
78 Hostname: "gitlab.com",
79 Token: "def456",
80 },
81 stdinTTY: true,
82 },
83 {
84 name: "nontty, hostname",
85 cli: "--hostname salsa.debian.org --token dummy-token",
86 wants: LoginOptions{
87 Hostname: "salsa.debian.org",
88 Token: "dummy-token",
89 },
90 stdinTTY: false,
91 },
92 {
93 name: "nontty",
94 cli: "--token dummy-token",
95 wants: LoginOptions{
96 Hostname: "gitlab.com",
97 Token: "dummy-token",
98 },
99 stdinTTY: false,
100 },
101 {
102 name: "nontty, stdin, hostname",
103 cli: "--hostname db.org --stdin",
104 stdin: "abc123\n",
105 wants: LoginOptions{
106 Hostname: "db.org",
107 Token: "abc123",
108 },
109 },
110 {
111 name: "tty, stdin, hostname",
112 stdin: "gli789",
113 cli: "--stdin --hostname gl.io",
114 wants: LoginOptions{
115 Hostname: "gl.io",
116 Token: "gli789",
117 },
118 stdinTTY: true,
119 },
120 {
121 name: "non-interactive hostname, token, api-host",
122 cli: "--hostname gl.io --token foo --api-host api.gitlab.com",
123 wants: LoginOptions{
124 Hostname: "gl.io",
125 Token: "foo",
126 ApiHost: "api.gitlab.com",
127 },
128 },
129 {
130 name: "non-interactive hostname, token, api-host, api-protocol, git-protocol",
131 cli: "--hostname gl.io --token foo --api-host gl.io:3443 --api-protocol https --git-protocol ssh",
132 wants: LoginOptions{
133 Hostname: "gl.io",
134 Token: "foo",
135 ApiHost: "gl.io:3443",
136 ApiProtocol: "https",
137 GitProtocol: "ssh",
138 },
139 },
140 {
141 name: "non-interactive hostname, api-host, api-protocol, git-protocol with stdin token",
142 cli: "--hostname gl.io --api-host gl.io:3443 --api-protocol https --git-protocol ssh --stdin",
143 stdin: "gli789",
144 wants: LoginOptions{
145 Hostname: "gl.io",
146 Token: "gli789",
147 ApiHost: "gl.io:3443",
148 ApiProtocol: "https",
149 GitProtocol: "ssh",
150 },
151 stdinTTY: true,
152 },
153 {
154 name: "api-host with token",
155 cli: "--hostname gl.io --api-host api.gitlab.com --token foo",
156 wants: LoginOptions{
157 Hostname: "gl.io",
158 Token: "foo",
159 ApiHost: "api.gitlab.com",
160 },
161 stdinTTY: true,
162 },
163 {
164 name: "api-protocol with token",
165 cli: "--hostname gl.io --api-protocol http --token foo",
166 wants: LoginOptions{
167 Hostname: "gl.io",
168 Token: "foo",
169 ApiProtocol: "http",
170 },
171 stdinTTY: true,
172 },
173 {
174 name: "git-protocol with token",
175 cli: "--hostname gl.io --git-protocol ssh --token foo",
176 wants: LoginOptions{
177 Hostname: "gl.io",
178 Token: "foo",
179 GitProtocol: "ssh",
180 },
181 stdinTTY: true,
182 },
183 {
184 name: "web with token",
185 cli: "--hostname gl.io --web --token foo",
186 wantsErr: true,
187 err: "none of the others can be",
188 },
189 {
190 name: "web with stdin",
191 cli: "--hostname gl.io --web --stdin",
192 stdin: "abc123\n",
193 wantsErr: true,
194 err: "none of the others can be",
195 },
196 {
197 name: "web with job-token",
198 cli: "--hostname gl.io --web --job-token foo",
199 wantsErr: true,
200 err: "none of the others can be",
201 },
202 {
203 name: "web with device",
204 cli: "--hostname gl.io --web --device",
205 wantsErr: true,
206 err: "none of the others can be",
207 },
208 {
209 name: "device with token",
210 cli: "--hostname gl.io --device --token foo",
211 wantsErr: true,
212 err: "none of the others can be",
213 },
214 {
215 name: "device with stdin",
216 cli: "--hostname gl.io --device --stdin",
217 stdin: "abc123\n",
218 wantsErr: true,
219 err: "none of the others can be",
220 },
221 {
222 name: "device with job-token",
223 cli: "--hostname gl.io --device --job-token foo",
224 wantsErr: true,
225 err: "none of the others can be",
226 },
227 // TODO: how to test survey
228 //{
229 // name: "tty, hostname",
230 // cli: "--hostname local.dev",
231 // wants: LoginOptions{
232 // Hostname: "local.dev",
233 // Token: "",
234 // Interactive: true,
235 // },
236 // stdinTTY: true,
237 // },
238 //{
239 // name: "tty",
240 // cli: "",
241 // wants: LoginOptions{
242 // Hostname: "",
243 // Token: "",
244 // Interactive: true,
245 // },
246 // stdinTTY: true,
247 // },
248 {
249 name: "token and stdin",
250 cli: "--token xxxx --stdin",
251 wantsErr: true,
252 err: "none of the others can be",
253 },
254 {
255 name: "no keyring, token",
256 cli: "--token glpat-123",
257 wants: LoginOptions{
258 Hostname: "gitlab.com",
259 Token: "glpat-123",
260 UseKeyring: false,
261 },
262 },
263 {
264 name: "keyring, token",
265 cli: "--token glpat-123 --use-keyring",
266 wants: LoginOptions{
267 Hostname: "gitlab.com",
268 Token: "glpat-123",
269 UseKeyring: true,
270 },
271 },
272 {
273 name: "non-interactive hostname, jobToken, api-host",
274 cli: "--hostname gl.io --job-token foo --api-host api.gitlab.com",
275 wants: LoginOptions{
276 Hostname: "gl.io",
277 JobToken: "foo",
278 ApiHost: "api.gitlab.com",
279 },
280 },
281 {
282 name: "non-interactive hostname, jobToken, api-host, api-protocol, git-protocol",
283 cli: "--hostname gl.io --job-token foo --api-host gl.io:3443 --api-protocol https --git-protocol ssh",
284 wants: LoginOptions{
285 Hostname: "gl.io",
286 JobToken: "foo",
287 ApiHost: "gl.io:3443",
288 ApiProtocol: "https",
289 GitProtocol: "ssh",
290 },
291 },
292 {
293 name: "container-registry-domains flag",
294 cli: "--hostname gl.io --token foo --container-registry-domains a.com,b.com",
295 wants: LoginOptions{
296 Hostname: "gl.io",
297 Token: "foo",
298 ContainerRegistryDomains: "a.com,b.com",
299 },
300 },
301 {
302 name: "ssh-hostname flag",
303 cli: "--hostname gl.io --token foo --ssh-hostname ssh.gl.io",
304 wants: LoginOptions{
305 Hostname: "gl.io",
306 Token: "foo",
307 SSHHostname: "ssh.gl.io",
308 },
309 },
310 {
311 name: "all new flags combined with token",
312 cli: "--hostname gl.io --token foo --ssh-hostname ssh.gl.io --container-registry-domains a.com,b.com --git-protocol ssh",
313 wants: LoginOptions{
314 Hostname: "gl.io",
315 Token: "foo",
316 SSHHostname: "ssh.gl.io",
317 ContainerRegistryDomains: "a.com,b.com",
318 GitProtocol: "ssh",
319 },
320 },
321 }
323 // Enable keyring mocking, so no changes are made to it accidentally and to prevent failing in some environments
324 keyring.MockInit()
326 for _, tt := range tests {
327 t.Run(tt.name, func(t *testing.T) {
328 d := t.TempDir()
329 t.Setenv("GLAB_CONFIG_DIR", d)
331 io, stdin, _, _ := cmdtest.TestIOStreams(cmdtest.WithTestIOStreamsAsTTY(true), iostreams.WithStdin(nil, tt.stdinTTY))
332 f := cmdtest.NewTestFactory(io, currentUserFactoryOption(t))
334 if tt.stdin != "" {
335 stdin.WriteString(tt.stdin)
336 }
338 argv, err := shlex.Split(tt.cli)
339 require.NoError(t, err)
341 cmd := NewCmdLogin(f)
342 // TODO cobra hack-around
343 cmd.Flags().BoolP("help", "x", false, "")
345 cmd.SetArgs(argv)
346 cmd.SetIn(&bytes.Buffer{})
347 cmd.SetOut(&bytes.Buffer{})
348 cmd.SetErr(&bytes.Buffer{})
350 _, err = cmd.ExecuteC()
352 if tt.wantsErr {
353 require.Error(t, err)
354 assert.Contains(t, err.Error(), tt.err)
355 return
356 }
357 require.NoError(t, err)
359 assert.Equal(t, tt.wants.Token, opts.Token)
360 assert.Equal(t, tt.wants.JobToken, opts.JobToken)
361 assert.Equal(t, tt.wants.Hostname, opts.Hostname)
362 assert.Equal(t, tt.wants.Interactive, opts.Interactive)
363 assert.Equal(t, tt.wants.ApiHost, opts.ApiHost)
364 assert.Equal(t, tt.wants.ApiProtocol, opts.ApiProtocol)
365 assert.Equal(t, tt.wants.GitProtocol, opts.GitProtocol)
366 assert.Equal(t, tt.wants.WebLogin, opts.WebLogin)
367 assert.Equal(t, tt.wants.DeviceLogin, opts.DeviceLogin)
368 assert.Equal(t, tt.wants.SSHHostname, opts.SSHHostname)
369 assert.Equal(t, tt.wants.ContainerRegistryDomains, opts.ContainerRegistryDomains)
370 })
371 }
372}
374func Test_hostnameValidator(t *testing.T) {
375 t.Parallel()
377 testMap := make(map[string]string)
378 testMap["profclems"] = "glab"
380 testCases := []struct {
381 name string
382 hostname any
383 expected string
384 }{
385 {
386 name: "valid",
387 hostname: "localhost",
388 },
389 {
390 name: "valid-default-value",
391 hostname: "gitlab.com",
392 },
393 {
394 name: "valid-external-instance-alpine",
395 hostname: "gitlab.alpinelinux.org",
396 },
397 {
398 name: "valid-external-instance-freedesktop",
399 hostname: "gitlab.freedesktop.org",
400 },
401 {
402 name: "valid-external-instance-gnome",
403 hostname: "gitlab.gnome.org",
404 },
405 {
406 name: "valid-external-instance-debian",
407 hostname: "salsa.debian.org",
408 },
409 {
410 name: "valid-external-instance-ip",
411 hostname: "1.1.1.1",
412 },
413 {
414 name: "valid-external-instance-ip-with-port",
415 hostname: "1.1.1.1:8080",
416 },
417 {
418 name: "empty",
419 hostname: "",
420 expected: "hostname cannot be empty",
421 },
422 {
423 name: "only whitespaces",
424 hostname: " ",
425 expected: "hostname cannot be empty",
426 },
427 {
428 name: "valid-hostname-slash",
429 hostname: "localhost:9999/host",
430 },
431 {
432 name: "hostname-with-valid-port",
433 hostname: "gitlab.mycompany.com:4000",
434 },
435 {
436 name: "hostname-with-invalid-port",
437 hostname: "local:host",
438 expected: `invalid hostname: parse "https://local:host": invalid port ":host" after host`,
439 },
440 {
441 name: "valid-hostname-with-path-and-dash",
442 hostname: "internal.hostname.com/gitlab-licensed",
443 },
444 }
445 for _, tC := range testCases {
446 t.Run(tC.name, func(t *testing.T) {
447 t.Parallel()
449 err := hostnameValidator(tC.hostname)
450 if tC.expected == "" {
451 assert.NoError(t, err)
452 } else {
453 assert.EqualError(t, err, tC.expected)
454 }
455 })
456 }
457}
459func Test_keyringLogin(t *testing.T) {
460 keyring.MockInit()
462 d := t.TempDir()
463 t.Setenv("GLAB_CONFIG_DIR", d)
465 token, err := keyring.Get("glab:gitlab.com:token", "")
466 require.Error(t, err)
467 assert.Empty(t, token)
469 io, _, _, _ := cmdtest.TestIOStreams()
470 f := cmdtest.NewTestFactory(io, currentUserFactoryOption(t))
471 cmd := NewCmdLogin(f)
472 cmd.Flags().BoolP("help", "x", false, "")
474 cmd.SetArgs([]string{"--use-keyring", "--token", "glpat-1234"})
476 _, err = cmd.ExecuteC()
477 require.NoError(t, err)
479 token, err = keyring.Get("glab:gitlab.com:token", "")
480 require.NoError(t, err)
481 assert.Equal(t, "glpat-1234", token)
482}
484func Test_defaultKeyringLogin(t *testing.T) {
485 keyring.MockInit()
486 // Exercise the non-CI default-keyring path even when the test suite runs
487 // inside CI (where GITLAB_CI/CI would otherwise route storage to the file).
488 t.Setenv("GITLAB_CI", "")
489 t.Setenv("CI", "")
491 d := t.TempDir()
492 t.Setenv("GLAB_CONFIG_DIR", d)
494 io, _, _, _ := cmdtest.TestIOStreams()
495 f := cmdtest.NewTestFactory(io, currentUserFactoryOption(t))
496 cfg := config.NewBlankConfigInDir(d)
497 f.ConfigStub = func() config.Config { return cfg }
498 cmd := NewCmdLogin(f)
499 cmd.Flags().BoolP("help", "x", false, "")
501 cmd.SetArgs([]string{"--token", "glpat-default"})
503 _, err := cmd.ExecuteC()
504 require.NoError(t, err)
506 // With a keyring available, the token is stored there by default even
507 // without passing --use-keyring.
508 got, err := keyring.Get("glab:gitlab.com:token", "")
509 require.NoError(t, err)
510 assert.Equal(t, "glpat-default", got)
512 // The config file records the preference and holds no plaintext token.
513 useKeyring, _ := cfg.Get("gitlab.com", "use_keyring")
514 assert.Equal(t, "true", useKeyring)
515 data, err := os.ReadFile(filepath.Join(d, "config.yml"))
516 require.NoError(t, err)
517 assert.NotContains(t, string(data), "glpat-default")
518}
520func Test_insecureStorageLogin(t *testing.T) {
521 keyring.MockInit()
523 d := t.TempDir()
524 t.Setenv("GLAB_CONFIG_DIR", d)
526 io, _, _, _ := cmdtest.TestIOStreams()
527 f := cmdtest.NewTestFactory(io, currentUserFactoryOption(t))
528 cfg := config.NewBlankConfigInDir(d)
529 f.ConfigStub = func() config.Config { return cfg }
530 cmd := NewCmdLogin(f)
531 cmd.Flags().BoolP("help", "x", false, "")
533 cmd.SetArgs([]string{"--insecure-storage", "--token", "glpat-plain"})
535 _, err := cmd.ExecuteC()
536 require.NoError(t, err)
538 // --insecure-storage keeps the token out of the keyring entirely.
539 _, err = keyring.Get("glab:gitlab.com:token", "")
540 require.Error(t, err)
542 // The token is stored as plaintext in the config file.
543 data, err := os.ReadFile(filepath.Join(d, "config.yml"))
544 require.NoError(t, err)
545 assert.Contains(t, string(data), "glpat-plain")
546}
548func Test_keyringUnavailableFallsBackToFile(t *testing.T) {
549 keyring.MockInitWithError(errors.New("keyring unavailable"))
550 t.Cleanup(keyring.MockInit)
551 // Exercise the non-CI warning path. In CI the fallback is silent, so clear
552 // GITLAB_CI/CI in case the suite itself runs inside CI.
553 t.Setenv("GITLAB_CI", "")
554 t.Setenv("CI", "")
555 t.Setenv("SNAP_NAME", "")
557 d := t.TempDir()
558 t.Setenv("GLAB_CONFIG_DIR", d)
560 io, _, _, stderr := cmdtest.TestIOStreams()
561 f := cmdtest.NewTestFactory(io, currentUserFactoryOption(t))
562 cfg := config.NewBlankConfigInDir(d)
563 f.ConfigStub = func() config.Config { return cfg }
564 cmd := NewCmdLogin(f)
565 cmd.Flags().BoolP("help", "x", false, "")
567 cmd.SetArgs([]string{"--token", "glpat-fallback"})
569 _, err := cmd.ExecuteC()
570 require.NoError(t, err)
572 assert.Contains(t, stderr.String(), "The operating system keyring is unavailable. Storing credentials as plaintext in the configuration file.")
573 assert.NotContains(t, stderr.String(), "sudo snap connect")
574 data, err := os.ReadFile(filepath.Join(d, "config.yml"))
575 require.NoError(t, err)
576 assert.Contains(t, string(data), "glpat-fallback")
577}
579func Test_keyringUnavailableUnderSnapShowsConnectHint(t *testing.T) {
580 keyring.MockInitWithError(errors.New("keyring unavailable"))
581 t.Cleanup(keyring.MockInit)
582 t.Setenv("GITLAB_CI", "")
583 t.Setenv("CI", "")
584 t.Setenv("SNAP_NAME", "glab")
586 d := t.TempDir()
587 t.Setenv("GLAB_CONFIG_DIR", d)
589 io, _, _, stderr := cmdtest.TestIOStreams()
590 f := cmdtest.NewTestFactory(io, currentUserFactoryOption(t))
591 cfg := config.NewBlankConfigInDir(d)
592 f.ConfigStub = func() config.Config { return cfg }
593 cmd := NewCmdLogin(f)
594 cmd.Flags().BoolP("help", "x", false, "")
596 cmd.SetArgs([]string{"--token", "glpat-snap"})
598 _, err := cmd.ExecuteC()
599 require.NoError(t, err)
601 assert.Contains(t, stderr.String(), "The operating system keyring is unavailable")
602 assert.Contains(t, stderr.String(), "sudo snap connect glab:password-manager-service")
603}
605func Test_ciLoginDefaultsToFile(t *testing.T) {
606 // A working keyring is available, but in CI we default to file storage
607 // unless --use-keyring is passed explicitly.
608 keyring.MockInit()
609 t.Setenv("GITLAB_CI", "true")
611 d := t.TempDir()
612 t.Setenv("GLAB_CONFIG_DIR", d)
614 io, _, _, _ := cmdtest.TestIOStreams()
615 f := cmdtest.NewTestFactory(io, currentUserFactoryOption(t))
616 cfg := config.NewBlankConfigInDir(d)
617 f.ConfigStub = func() config.Config { return cfg }
618 cmd := NewCmdLogin(f)
619 cmd.Flags().BoolP("help", "x", false, "")
621 cmd.SetArgs([]string{"--token", "glpat-ci"})
623 _, err := cmd.ExecuteC()
624 require.NoError(t, err)
626 // Token is stored in the config file, not the keyring.
627 _, err = keyring.Get("glab:gitlab.com:token", "")
628 require.Error(t, err)
629 data, err := os.ReadFile(filepath.Join(d, "config.yml"))
630 require.NoError(t, err)
631 assert.Contains(t, string(data), "glpat-ci")
632}
634func Test_ciLoginHonorsExplicitUseKeyring(t *testing.T) {
635 keyring.MockInit()
636 t.Setenv("GITLAB_CI", "true")
638 d := t.TempDir()
639 t.Setenv("GLAB_CONFIG_DIR", d)
641 io, _, _, _ := cmdtest.TestIOStreams()
642 f := cmdtest.NewTestFactory(io, currentUserFactoryOption(t))
643 cfg := config.NewBlankConfigInDir(d)
644 f.ConfigStub = func() config.Config { return cfg }
645 cmd := NewCmdLogin(f)
646 cmd.Flags().BoolP("help", "x", false, "")
648 cmd.SetArgs([]string{"--use-keyring", "--token", "glpat-ci-explicit"})
650 _, err := cmd.ExecuteC()
651 require.NoError(t, err)
653 // Explicit --use-keyring overrides the CI default and stores in the keyring.
654 got, err := keyring.Get("glab:gitlab.com:token", "")
655 require.NoError(t, err)
656 assert.Equal(t, "glpat-ci-explicit", got)
657}
659func Test_useKeyringDeprecatedFallsBackToFileWhenUnavailable(t *testing.T) {
660 keyring.MockInitWithError(errors.New("keyring unavailable"))
661 t.Cleanup(keyring.MockInit)
662 t.Setenv("GITLAB_CI", "")
663 t.Setenv("CI", "")
664 t.Setenv("SNAP_NAME", "")
666 d := t.TempDir()
667 t.Setenv("GLAB_CONFIG_DIR", d)
669 io, _, _, stderr := cmdtest.TestIOStreams()
670 f := cmdtest.NewTestFactory(io, currentUserFactoryOption(t))
671 cfg := config.NewBlankConfigInDir(d)
672 f.ConfigStub = func() config.Config { return cfg }
673 cmd := NewCmdLogin(f)
674 cmd.Flags().BoolP("help", "x", false, "")
676 cmd.SetArgs([]string{"--use-keyring", "--token", "glpat-deprecated"})
678 _, err := cmd.ExecuteC()
680 // The deprecated --use-keyring no longer errors when the keyring is
681 // unavailable; it warns and falls back to plaintext file storage like the
682 // default does.
683 require.NoError(t, err)
684 assert.Contains(t, stderr.String(), "The operating system keyring is unavailable")
685 data, err := os.ReadFile(filepath.Join(d, "config.yml"))
686 require.NoError(t, err)
687 assert.Contains(t, string(data), "glpat-deprecated")
688}
690func Test_tokenLogin_persistsUsername(t *testing.T) {
691 keyring.MockInit()
693 login := func(t *testing.T, cfg config.Config, opts ...cmdtest.FactoryOption) (*bytes.Buffer, error) {
694 t.Helper()
695 t.Setenv("GLAB_CONFIG_DIR", t.TempDir())
697 io, _, _, stderr := cmdtest.TestIOStreams()
698 cmd := NewCmdLogin(cmdtest.NewTestFactory(io, append([]cmdtest.FactoryOption{cmdtest.WithConfig(cfg)}, opts...)...))
699 cmd.Flags().BoolP("help", "x", false, "")
700 cmd.SetArgs([]string{"--hostname", "gitlab.com", "--token", "glpat-1234"})
702 _, err := cmd.ExecuteC()
703 return stderr, err
704 }
706 t.Run("records the account the token belongs to", func(t *testing.T) {
707 cfg := config.NewBlankConfigInDir(t.TempDir())
709 stderr, err := login(t, cfg, currentUserFactoryOption(t))
710 require.NoError(t, err)
712 user, err := cfg.Get("gitlab.com", "user")
713 require.NoError(t, err)
714 assert.Equal(t, "john_smith", user)
715 assert.Contains(t, stderr.String(), "Logged in as john_smith")
716 })
718 // The lookup is best-effort so that `--token` keeps working for scripted
719 // and CI logins that cannot reach the API.
720 t.Run("still stores the token when the lookup fails", func(t *testing.T) {
721 cfg := config.NewBlankConfigInDir(t.TempDir())
723 tc := gitlabtesting.NewTestClient(t)
724 tc.MockUsers.EXPECT().
725 CurrentUser(gomock.Any()).
726 Return(nil, nil, errors.New("no such host")).
727 AnyTimes()
728 apiClient := cmdtest.NewTestApiClient(t, nil, "", "gitlab.com", api.WithGitLabClient(tc.Client))
730 stderr, err := login(t, cfg, cmdtest.WithApiClient(apiClient))
731 require.NoError(t, err)
733 token, err := cfg.Get("gitlab.com", "token")
734 require.NoError(t, err)
735 assert.Equal(t, "glpat-1234", token)
737 user, err := cfg.Get("gitlab.com", "user")
738 require.NoError(t, err)
739 assert.Empty(t, user, "the credential helper falls back to a placeholder for this case")
740 assert.Contains(t, stderr.String(), "Could not look up the username for this token")
741 })
742}
744func Test_tokenLogin_persistsContainerRegistryDomains(t *testing.T) {
745 for _, storageFlag := range []string{"--use-keyring", "--insecure-storage"} {
746 for _, tt := range []struct {
747 name string
748 saved string
749 flag string
750 want string
751 }{
752 {
753 name: "explicit domains",
754 flag: "registry.example.com,registry.example.com:5000",
755 want: "registry.example.com,registry.example.com:5000",
756 },
757 {
758 name: "flag overrides saved domains",
759 saved: "old.example.com",
760 flag: "registry.example.com",
761 want: "registry.example.com",
762 },
763 {
764 name: "preserves saved domains without flag",
765 saved: "saved.example.com",
766 want: "saved.example.com",
767 },
768 {
769 name: "defaults without flag",
770 want: "gitlab.example.com,gitlab.example.com:443,registry.gitlab.example.com",
771 },
772 } {
773 t.Run(storageFlag+"/"+tt.name, func(t *testing.T) {
774 keyring.MockInit()
775 dir := t.TempDir()
776 t.Setenv("GLAB_CONFIG_DIR", dir)
777 cfg := config.NewBlankConfigInDir(dir)
778 if tt.saved != "" {
779 require.NoError(t, cfg.Set("gitlab.example.com", "container_registry_domains", tt.saved))
780 }
782 exec := cmdtest.SetupCmdForTest(t, NewCmdLogin, false,
783 cmdtest.WithConfig(cfg), currentUserFactoryOption(t))
784 args := "--hostname gitlab.example.com --token test-token " + storageFlag
785 if tt.flag != "" {
786 args += " --container-registry-domains " + tt.flag
787 }
788 _, err := exec(args)
789 require.NoError(t, err)
791 data, err := os.ReadFile(filepath.Join(dir, "config.yml"))
792 require.NoError(t, err)
793 saved := config.NewFromString(string(data))
794 domains, err := saved.Get("gitlab.example.com", "container_registry_domains")
795 require.NoError(t, err)
796 assert.Equal(t, tt.want, domains)
797 })
798 }
799 }
800}
802func Test_tokenLogin_warnsWhenEnvTokenTakesPrecedence(t *testing.T) {
803 keyring.MockInit()
805 login := func(t *testing.T) *bytes.Buffer {
806 t.Helper()
807 t.Setenv("GLAB_CONFIG_DIR", t.TempDir())
808 cfg := config.NewBlankConfigInDir(t.TempDir())
810 io, _, _, stderr := cmdtest.TestIOStreams()
811 cmd := NewCmdLogin(cmdtest.NewTestFactory(io, cmdtest.WithConfig(cfg), currentUserFactoryOption(t)))
812 cmd.Flags().BoolP("help", "x", false, "")
813 cmd.SetArgs([]string{"--hostname", "gitlab.com", "--token", "glpat-1234"})
815 _, err := cmd.ExecuteC()
816 require.NoError(t, err)
817 return stderr
818 }
820 t.Run("warns and points at removing the variable", func(t *testing.T) {
821 t.Setenv("GITLAB_TOKEN", "glpat-from-env")
823 stderr := login(t)
825 assert.Contains(t, stderr.String(), "The environment variable GITLAB_TOKEN is set and takes precedence")
826 assert.Contains(t, stderr.String(), "Run type glab to find the source: an alias such as 'op plugin run -- glab' means a wrapper (for example, a 1Password shell plugin) is injecting it, which is expected and needs no action.")
827 assert.Contains(t, stderr.String(), "remove it there so glab uses your stored credentials")
828 })
830 t.Run("stays quiet when no token environment variable is set", func(t *testing.T) {
831 // Clear every env var that maps to the "token" key. Setting them to the
832 // empty string is equivalent to unsetting them here: GetFromEnvWithSource
833 // only treats a non-empty value as a source.
834 for _, e := range config.EnvKeyEquivalence("token") {
835 t.Setenv(e, "")
836 }
838 stderr := login(t)
840 assert.NotContains(t, stderr.String(), "takes precedence")
841 })
842}
844func Test_initialAPIHostname(t *testing.T) {
845 t.Run("flag wins over saved value", func(t *testing.T) {
846 cfg := config.NewBlankConfigInDir(t.TempDir())
847 require.NoError(t, cfg.Set("gl.io", "api_host", "saved.gl.io"))
849 got := initialAPIHostname(cfg, "gl.io", "flag.gl.io")
851 assert.Equal(t, "flag.gl.io", got)
852 })
854 t.Run("saved value wins over hostname when flag empty", func(t *testing.T) {
855 cfg := config.NewBlankConfigInDir(t.TempDir())
856 require.NoError(t, cfg.Set("gl.io", "api_host", "saved.gl.io"))
858 got := initialAPIHostname(cfg, "gl.io", "")
860 assert.Equal(t, "saved.gl.io", got)
861 })
863 t.Run("falls back to hostname when nothing saved and flag empty", func(t *testing.T) {
864 cfg := config.NewBlankConfigInDir(t.TempDir())
866 got := initialAPIHostname(cfg, "gl.io", "")
868 assert.Equal(t, "gl.io", got)
869 })
870}
872func Test_initialSSHHostname(t *testing.T) {
873 t.Run("saved value is used", func(t *testing.T) {
874 cfg := config.NewBlankConfigInDir(t.TempDir())
875 require.NoError(t, cfg.Set("gl.io", "ssh_host", "ssh.gl.io"))
877 got := initialSSHHostname(cfg, "gl.io")
879 assert.Equal(t, "ssh.gl.io", got)
880 })
882 t.Run("uses SSH host detected from git remotes when nothing saved", func(t *testing.T) {
883 t.Chdir(t.TempDir())
884 require.NoError(t, exec.Command("git", "init").Run())
885 require.NoError(t, exec.Command("git", "remote", "add", "origin", "ssh://ssh.gl.io/owner/repo.git").Run())
886 cfg := config.NewBlankConfigInDir(t.TempDir())
888 got := initialSSHHostname(cfg, "gl.io")
890 assert.Equal(t, "ssh.gl.io", got)
891 })
893 t.Run("falls back to hostname when nothing saved and no git detection", func(t *testing.T) {
894 t.Chdir(t.TempDir())
895 cfg := config.NewBlankConfigInDir(t.TempDir())
897 got := initialSSHHostname(cfg, "gl.io")
899 assert.Equal(t, "gl.io", got)
900 })
901}
903func Test_initialContainerRegistryDomains(t *testing.T) {
904 t.Run("saved value is used", func(t *testing.T) {
905 cfg := config.NewBlankConfigInDir(t.TempDir())
906 require.NoError(t, cfg.Set("gitlab.com", "container_registry_domains", "my.custom.registry"))
908 got := initialContainerRegistryDomains(cfg, "gitlab.com", "")
910 assert.Equal(t, "my.custom.registry", got)
911 })
913 t.Run("falls back to hostname-derived default when nothing saved", func(t *testing.T) {
914 cfg := config.NewBlankConfigInDir(t.TempDir())
916 got := initialContainerRegistryDomains(cfg, "gitlab.com", "")
918 assert.Equal(t, "gitlab.com,gitlab.com:443,registry.gitlab.com", got)
919 })
921 t.Run("flag wins over the saved value", func(t *testing.T) {
922 cfg := config.NewBlankConfigInDir(t.TempDir())
923 require.NoError(t, cfg.Set("gitlab.com", "container_registry_domains", "my.custom.registry"))
925 got := initialContainerRegistryDomains(cfg, "gitlab.com", "none")
927 assert.Equal(t, "none", got)
928 })
930 // A login that does not reach the prompt, which is every non-interactive
931 // login, must not clear domains the host already has.
932 t.Run("never resolves to empty", func(t *testing.T) {
933 cfg := config.NewBlankConfigInDir(t.TempDir())
934 require.NoError(t, cfg.Set("example.com", "container_registry_domains", "registry.example.com"))
936 assert.Equal(t, "registry.example.com", initialContainerRegistryDomains(cfg, "example.com", ""))
937 assert.Equal(t, defaultContainerRegistryDomainsString("other.example.com"),
938 initialContainerRegistryDomains(cfg, "other.example.com", ""))
939 })
940}
942func Test_persistProtocolFlags(t *testing.T) {
943 t.Run("both flags set writes both keys lowercased", func(t *testing.T) {
944 cfg := config.NewBlankConfigInDir(t.TempDir())
946 err := persistProtocolFlags(cfg, "gl.io", "SSH", "HTTPS")
947 require.NoError(t, err)
949 gitProto, _ := cfg.Get("gl.io", "git_protocol")
950 assert.Equal(t, "ssh", gitProto)
951 apiProto, _ := cfg.Get("gl.io", "api_protocol")
952 assert.Equal(t, "https", apiProto)
953 })
955 t.Run("only git flag set leaves api untouched", func(t *testing.T) {
956 cfg := config.NewBlankConfigInDir(t.TempDir())
957 require.NoError(t, cfg.Set("gl.io", "api_protocol", "http"))
959 err := persistProtocolFlags(cfg, "gl.io", "ssh", "")
960 require.NoError(t, err)
962 gitProto, _ := cfg.Get("gl.io", "git_protocol")
963 assert.Equal(t, "ssh", gitProto)
964 apiProto, _ := cfg.Get("gl.io", "api_protocol")
965 assert.Equal(t, "http", apiProto)
966 })
968 t.Run("only api flag set leaves git untouched", func(t *testing.T) {
969 cfg := config.NewBlankConfigInDir(t.TempDir())
970 require.NoError(t, cfg.Set("gl.io", "git_protocol", "ssh"))
972 err := persistProtocolFlags(cfg, "gl.io", "", "http")
973 require.NoError(t, err)
975 gitProto, _ := cfg.Get("gl.io", "git_protocol")
976 assert.Equal(t, "ssh", gitProto)
977 apiProto, _ := cfg.Get("gl.io", "api_protocol")
978 assert.Equal(t, "http", apiProto)
979 })
981 t.Run("neither flag set leaves config untouched", func(t *testing.T) {
982 cfg := config.NewBlankConfigInDir(t.TempDir())
983 require.NoError(t, cfg.Set("gl.io", "git_protocol", "ssh"))
984 require.NoError(t, cfg.Set("gl.io", "api_protocol", "https"))
986 err := persistProtocolFlags(cfg, "gl.io", "", "")
987 require.NoError(t, err)
989 gitProto, _ := cfg.Get("gl.io", "git_protocol")
990 assert.Equal(t, "ssh", gitProto)
991 apiProto, _ := cfg.Get("gl.io", "api_protocol")
992 assert.Equal(t, "https", apiProto)
993 })
994}
996func Test_getAccessTokenTip(t *testing.T) {
997 const (
998 current = "https://gitlab.example.com/-/user_settings/personal_access_tokens/legacy/new?scopes=api,write_repository"
999 older = "https://gitlab.example.com/-/user_settings/personal_access_tokens?scopes=api,write_repository"
1000 )
1002 tip := getAccessTokenTip("gitlab.example.com")
1004 assert.Contains(t, tip, "The minimum required scopes are 'api' and 'write_repository'.")
1005 assert.Contains(t, tip, current)
1006 assert.Contains(t, tip, older)
1007 assert.Less(t, strings.Index(tip, current), strings.Index(tip, older),
1008 "the URL for supported versions should come first")
1009}
1011// A non-interactive login with no --hostname used to fall back to the
1012// gitlab.com constant, storing credentials under the wrong host for anyone who
1013// had pointed glab at another instance with GITLAB_HOST.
1014func Test_nonInteractiveLoginDefaultsToTheResolvedHost(t *testing.T) {
1015 keyring.MockInit()
1017 d := t.TempDir()
1018 t.Setenv("GLAB_CONFIG_DIR", d)
1020 io, _, _, _ := cmdtest.TestIOStreams()
1021 f := cmdtest.NewTestFactory(io, currentUserFactoryOption(t))
1022 f.DefaultHostnameStub = "gitlab.example.com"
1023 cfg := config.NewBlankConfigInDir(d)
1024 f.ConfigStub = func() config.Config { return cfg }
1026 cmd := NewCmdLogin(f)
1027 cmd.Flags().BoolP("help", "x", false, "")
1028 cmd.SetArgs([]string{"--job-token", "job-abc"})
1030 _, err := cmd.ExecuteC()
1031 require.NoError(t, err)
1033 got, err := cfg.Get("gitlab.example.com", "job_token")
1034 require.NoError(t, err)
1035 assert.Equal(t, "job-abc", got)
1037 onDefault, _ := cfg.Get("gitlab.com", "job_token")
1038 assert.Empty(t, onDefault, "credentials should not land on gitlab.com")
1039}
1041// loginRun stores use_keyring before the OAuth2 flow has a token, so the
1042// client for that flow must not depend on a stored token.
1043func Test_deviceLoginWithKeyringAndNoStoredToken(t *testing.T) {
1044 keyring.MockInit()
1045 t.Setenv("GITLAB_CI", "")
1046 t.Setenv("CI", "")
1047 t.Setenv("GITLAB_TOKEN", "")
1048 t.Setenv("GITLAB_ACCESS_TOKEN", "")
1049 t.Setenv("OAUTH_TOKEN", "")
1051 requests := make(chan string, 10)
1052 server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1053 requests <- r.URL.Path
1054 w.WriteHeader(http.StatusBadRequest)
1055 }))
1056 t.Cleanup(server.Close)
1057 hostname := strings.TrimPrefix(server.URL, "https://")
1059 d := t.TempDir()
1060 t.Setenv("GLAB_CONFIG_DIR", d)
1061 cfg := config.NewBlankConfigInDir(d)
1062 require.NoError(t, cfg.Set(hostname, "client_id", "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"))
1063 require.NoError(t, cfg.Set(hostname, "skip_tls_verify", "true"))
1065 exec := cmdtest.SetupCmdForTest(t, NewCmdLogin, false,
1066 cmdtest.WithConfig(cfg),
1067 cmdtest.WithApiClientFunc(func(repoHost string) (*api.Client, error) {
1068 return api.NewClientFromConfig(repoHost, cfg, false, "test-agent")
1069 }),
1070 )
1072 _, err := exec("--hostname " + hostname + " --device")
1073 require.ErrorContains(t, err, "failed to start device authorization")
1074 require.Len(t, requests, 1)
1075 assert.Equal(t, "/oauth/authorize_device", <-requests)
1077 useKeyring, _ := cfg.Get(hostname, "use_keyring")
1078 assert.Equal(t, "true", useKeyring)
1079}
1081// clearDefaultHostEnv unsets what updateDefaultHost skips on, so a test does not
1082// inherit them from the developer's shell or the CI job running it.
1083func clearDefaultHostEnv(t *testing.T) {
1084 t.Helper()
1086 for _, e := range []string{"GITLAB_CI", "CI", "GITLAB_HOST", "GITLAB_URI", "GL_HOST", "GITLAB_TOKEN", "GITLAB_ACCESS_TOKEN", "OAUTH_TOKEN"} {
1087 t.Setenv(e, "")
1088 }
1089}
1091func defaultHost(t *testing.T, cfg config.Config) string {
1092 t.Helper()
1094 host, _, err := cfg.GetWithSource("", "host", false)
1095 require.NoError(t, err)
1096 return host
1097}
1099// defaultHostFailingConfig fails reading the default host, or writing the
1100// config once the default host has been set, so the token saved before it
1101// still persists.
1102type defaultHostFailingConfig struct {
1103 config.Config
1104 failRead bool
1105 hostSet bool
1106}
1108func (c *defaultHostFailingConfig) GetWithSource(hostname, key string, searchENVVars bool) (string, string, error) {
1109 if c.failRead && hostname == "" && key == "host" {
1110 return "", "", errors.New("read failed")
1111 }
1112 return c.Config.GetWithSource(hostname, key, searchENVVars)
1113}
1115func (c *defaultHostFailingConfig) Set(hostname, key, value string) error {
1116 if hostname == "" && key == "host" {
1117 c.hostSet = true
1118 }
1119 return c.Config.Set(hostname, key, value)
1120}
1122func (c *defaultHostFailingConfig) Write() error {
1123 if c.hostSet {
1124 return errors.New("write failed")
1125 }
1126 return c.Config.Write()
1127}
1129func Test_tokenLogin_updatesDefaultHost(t *testing.T) {
1130 clearDefaultHostEnv(t)
1132 login := func(t *testing.T, cfg config.Config, args ...string) string {
1133 t.Helper()
1134 keyring.MockInit()
1135 t.Setenv("GLAB_CONFIG_DIR", t.TempDir())
1137 io, _, _, stderr := cmdtest.TestIOStreams()
1138 cmd := NewCmdLogin(cmdtest.NewTestFactory(io, cmdtest.WithConfig(cfg), currentUserFactoryOption(t)))
1139 cmd.Flags().BoolP("help", "x", false, "")
1140 cmd.SetArgs(args)
1142 _, err := cmd.ExecuteC()
1143 require.NoError(t, err)
1144 return stderr.String()
1145 }
1147 t.Run("sets the default when gitlab.com has no credentials", func(t *testing.T) {
1148 cfg := config.NewBlankConfigInDir(t.TempDir())
1150 stderr := login(t, cfg, "--hostname", "gitlab.example.com", "--token", "glpat-1234")
1152 assert.Equal(t, "gitlab.example.com", defaultHost(t, cfg))
1153 assert.Contains(t, stderr, "Default host set to gitlab.example.com")
1154 })
1156 t.Run("keeps gitlab.com when it has credentials", func(t *testing.T) {
1157 cfg := config.NewBlankConfigInDir(t.TempDir())
1158 require.NoError(t, cfg.Set("gitlab.com", "token", "glpat-existing"))
1160 stderr := login(t, cfg, "--hostname", "gitlab.example.com", "--token", "glpat-1234")
1162 assert.Equal(t, "gitlab.com", defaultHost(t, cfg))
1163 assert.Contains(t, stderr, "glab config set --global host gitlab.example.com")
1164 })
1166 // Repointing the default would send the environment token, which glab uses
1167 // for every host, to the new instance.
1168 t.Run("keeps gitlab.com when an environment token is set", func(t *testing.T) {
1169 t.Setenv("GITLAB_TOKEN", "glpat-from-env")
1170 cfg := config.NewBlankConfigInDir(t.TempDir())
1172 stderr := login(t, cfg, "--hostname", "gitlab.example.com", "--token", "glpat-1234")
1174 assert.Equal(t, "gitlab.com", defaultHost(t, cfg))
1175 assert.Contains(t, stderr, "glab config set --global host gitlab.example.com")
1176 })
1178 t.Run("keeps a default the user set", func(t *testing.T) {
1179 cfg := config.NewBlankConfigInDir(t.TempDir())
1180 require.NoError(t, cfg.Set("", "host", "gitlab.other.com"))
1182 stderr := login(t, cfg, "--hostname", "gitlab.example.com", "--token", "glpat-1234")
1184 assert.Equal(t, "gitlab.other.com", defaultHost(t, cfg))
1185 assert.Contains(t, stderr, "glab config set --global host gitlab.example.com")
1186 })
1188 t.Run("suggests gitlab.com when the default is another instance", func(t *testing.T) {
1189 cfg := config.NewBlankConfigInDir(t.TempDir())
1190 require.NoError(t, cfg.Set("", "host", "gitlab.example.com"))
1192 stderr := login(t, cfg, "--hostname", "gitlab.com", "--token", "glpat-1234")
1194 assert.Equal(t, "gitlab.example.com", defaultHost(t, cfg))
1195 assert.Contains(t, stderr, "glab uses the default host gitlab.example.com")
1196 assert.Contains(t, stderr, "glab config set --global host gitlab.com")
1197 assert.NotContains(t, stderr, "Default host set")
1198 })
1200 for _, host := range []string{"https://gitlab.example.com", "http://gitlab.example.com/"} {
1201 t.Run("keeps a URL-form default for the same instance: "+host, func(t *testing.T) {
1202 cfg := config.NewBlankConfigInDir(t.TempDir())
1203 require.NoError(t, cfg.Set("", "host", host))
1205 stderr := login(t, cfg, "--hostname", "gitlab.example.com", "--token", "glpat-1234")
1207 assert.Equal(t, host, defaultHost(t, cfg))
1208 assert.NotContains(t, stderr, "Default host")
1209 assert.NotContains(t, stderr, "glab config set")
1210 })
1211 }
1213 t.Run("treats a URL-form gitlab.com as the default", func(t *testing.T) {
1214 cfg := config.NewBlankConfigInDir(t.TempDir())
1215 require.NoError(t, cfg.Set("", "host", "https://gitlab.com"))
1217 stderr := login(t, cfg, "--hostname", "gitlab.example.com", "--token", "glpat-1234")
1219 assert.Equal(t, "gitlab.example.com", defaultHost(t, cfg))
1220 assert.Contains(t, stderr, "Default host set to gitlab.example.com")
1221 })
1223 t.Run("warns and succeeds when the default host cannot be read", func(t *testing.T) {
1224 cfg := &defaultHostFailingConfig{Config: config.NewBlankConfigInDir(t.TempDir()), failRead: true}
1226 stderr := login(t, cfg, "--hostname", "gitlab.example.com", "--token", "glpat-1234")
1228 assert.Contains(t, stderr, "Could not set the default host: read failed")
1229 assert.Contains(t, stderr, "glab config set --global host gitlab.example.com")
1230 })
1232 t.Run("warns and succeeds when the default host cannot be written", func(t *testing.T) {
1233 cfg := &defaultHostFailingConfig{Config: config.NewBlankConfigInDir(t.TempDir())}
1235 stderr := login(t, cfg, "--hostname", "gitlab.example.com", "--token", "glpat-1234")
1237 assert.Contains(t, stderr, "Could not set the default host: write failed")
1238 assert.Contains(t, stderr, "glab config set --global host gitlab.example.com")
1239 assert.NotContains(t, stderr, "Default host set")
1240 })
1242 t.Run("does nothing for gitlab.com", func(t *testing.T) {
1243 cfg := config.NewBlankConfigInDir(t.TempDir())
1245 stderr := login(t, cfg, "--hostname", "gitlab.com", "--token", "glpat-1234")
1247 assert.Equal(t, "gitlab.com", defaultHost(t, cfg))
1248 assert.NotContains(t, stderr, "Default host")
1249 assert.NotContains(t, stderr, "glab config set")
1250 })
1252 for _, env := range []string{"GITLAB_HOST", "GITLAB_URI", "GL_HOST"} {
1253 t.Run("does nothing when "+env+" is set", func(t *testing.T) {
1254 t.Setenv(env, "gitlab.env.com")
1255 cfg := config.NewBlankConfigInDir(t.TempDir())
1257 stderr := login(t, cfg, "--hostname", "gitlab.example.com", "--token", "glpat-1234")
1259 assert.Equal(t, "gitlab.com", defaultHost(t, cfg))
1260 assert.NotContains(t, stderr, "Default host")
1261 })
1262 }
1264 t.Run("does nothing in CI", func(t *testing.T) {
1265 t.Setenv("GITLAB_CI", "true")
1266 cfg := config.NewBlankConfigInDir(t.TempDir())
1268 login(t, cfg, "--hostname", "gitlab.example.com", "--token", "glpat-1234")
1270 assert.Equal(t, "gitlab.com", defaultHost(t, cfg))
1271 })
1273 t.Run("does nothing for a job token", func(t *testing.T) {
1274 cfg := config.NewBlankConfigInDir(t.TempDir())
1276 stderr := login(t, cfg, "--hostname", "gitlab.example.com", "--job-token", "job-abc")
1278 assert.Equal(t, "gitlab.com", defaultHost(t, cfg))
1279 assert.NotContains(t, stderr, "Default host")
1280 })
1281}
1283func Test_updateDefaultHost_prompt(t *testing.T) {
1284 clearDefaultHostEnv(t)
1285 t.Setenv("GLAB_CONFIG_DIR", t.TempDir())
1287 run := func(t *testing.T, answer ugh.Action) (config.Config, string) {
1288 t.Helper()
1290 cfg := config.NewBlankConfigInDir(t.TempDir())
1291 require.NoError(t, cfg.Set("gitlab.com", "token", "glpat-existing"))
1293 c := ugh.New(t)
1294 // The full title wraps differently depending on the terminal layout, so
1295 // match only a prefix that always fits on the first line.
1296 c.Expect(ugh.Confirm("Outside a Git repository, glab uses the default host gitlab.com.")).Do(answer)
1298 inR, inW := io.Pipe()
1299 outR, outW := io.Pipe()
1300 wait := c.Start(t.Context(), outR, inW)
1301 var stderr bytes.Buffer
1302 ios := iostreams.New(
1303 iostreams.WithStdin(inR, true),
1304 iostreams.WithStdout(outW, true),
1305 iostreams.WithStderr(&stderr, true),
1306 iostreams.WithProgramOptions(tea.WithWindowSize(cmdtest.ConsoleWidth, cmdtest.ConsoleHeight)),
1307 )
1309 // Fail with ugh's screen dump before the package timeout if the prompt
1310 // is never matched.
1311 ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second)
1312 defer cancel()
1313 err := updateDefaultHost(ctx, &LoginOptions{IO: ios, Interactive: true}, cfg, "gitlab.example.com")
1314 inW.Close()
1315 outW.Close()
1316 outR.Close()
1317 wait()
1318 require.NoError(t, err)
1319 return cfg, stderr.String()
1320 }
1322 t.Run("sets the default when the user accepts", func(t *testing.T) {
1323 cfg, stderr := run(t, ugh.Affirm)
1324 assert.Equal(t, "gitlab.example.com", defaultHost(t, cfg))
1325 assert.Contains(t, stderr, "Default host set to gitlab.example.com")
1326 })
1328 t.Run("keeps the default when the user declines", func(t *testing.T) {
1329 cfg, stderr := run(t, ugh.Reject)
1330 assert.Equal(t, "gitlab.com", defaultHost(t, cfg))
1331 assert.NotContains(t, stderr, "Default host set")
1332 })
1334 t.Run("keeps the default when the user cancels", func(t *testing.T) {
1335 cfg, _ := run(t, func(r *ugh.Response) { r.Send(ugh.CtrlC) })
1336 assert.Equal(t, "gitlab.com", defaultHost(t, cfg))
1337 })
1338}
1340// The interactive token flow ends at the same call site as the web and device
1341// flows, so it covers that call site without a browser.
1342func Test_interactiveLogin_updatesDefaultHost(t *testing.T) {
1343 keyring.MockInit()
1344 clearDefaultHostEnv(t)
1345 t.Setenv("GLAB_CONFIG_DIR", t.TempDir())
1347 c := ugh.New(t)
1348 c.Expect(ugh.Select("How would you like to sign in?")).
1349 Do(ugh.SelectOption(promptLoginTypeToken))
1350 c.Expect(ugh.Input("Paste your authentication token:")).
1351 Do(ugh.Type("glpat-1234"))
1353 cfg := config.NewBlankConfigInDir(t.TempDir())
1354 exec := cmdtest.SetupCmdForTest(t, NewCmdLogin, true,
1355 cmdtest.WithConfig(cfg), currentUserFactoryOption(t), cmdtest.WithConsole(t, c))
1356 out, err := exec("--hostname gitlab.example.com --api-host gitlab.example.com --ssh-hostname gitlab.example.com " +
1357 "--git-protocol ssh --api-protocol https --container-registry-domains registry.example.com")
1358 require.NoError(t, err)
1360 assert.Equal(t, "gitlab.example.com", defaultHost(t, cfg))
1361 assert.Contains(t, out.Stderr(), "Default host set to gitlab.example.com")
1362}
Diagnostics8 git calls · 231 ms
CallStatusSizeTime0231 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=5 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 · hit4 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=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:0 · deepen 1020032 KiB · hit5 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=5 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 · 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: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=5d783fac547a70b19ca138c47d067b44febb52da 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=22a484e5ecad6d6e62b224e8a7f90cf5ff085938Open pack map
fetchtree:0200281 B · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=215 git.response.bytes=281 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=c0c82a025b3ed38528b387b0c264c6de5ea513c8 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=281 git.pkt.payload.max=254 git.sideband.band1.bytes=254 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=254 git.pack.trailer=f67b2cbb934192bc54c7c67883cb789a9f00fa4aOpen pack map
fetch2008.1 KiB215 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=8256 git.response.cache=MISS git.response.duration_ms=215 git.fetch.wants=811c5b42e3990742ea20231e72d9ee4746b1a991 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=8256 git.pkt.payload.max=8229 git.sideband.band1.bytes=8229 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
- a5e2df4a9d242308
- Request
- 95f410e6…
- 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