GitLabgitlab-org
cli
main
1package login
3import (
4 "context"
5 "errors"
6 "fmt"
7 "io"
8 "net"
9 "net/url"
10 "os"
11 "slices"
12 "strings"
13 "time"
15 "charm.land/huh/v2"
16 "github.com/MakeNowJust/heredoc/v2"
17 "github.com/spf13/cobra"
19 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
21 "gitlab.com/gitlab-org/cli/internal/api"
22 "gitlab.com/gitlab-org/cli/internal/cmdutils"
23 "gitlab.com/gitlab-org/cli/internal/commands/auth/authutils"
24 "gitlab.com/gitlab-org/cli/internal/config"
25 "gitlab.com/gitlab-org/cli/internal/dbg"
26 "gitlab.com/gitlab-org/cli/internal/git"
27 "gitlab.com/gitlab-org/cli/internal/glinstance"
28 "gitlab.com/gitlab-org/cli/internal/iostreams"
29 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
30 "gitlab.com/gitlab-org/cli/internal/oauth2"
31)
33type LoginOptions struct {
34 IO *iostreams.IOStreams
35 Config func() config.Config
36 apiClient func(repoHost string) (*api.Client, error)
37 defaultHostname string
39 unauthenticatedAPIClient func(repoHost string) (*api.Client, error)
41 Interactive bool
43 Hostname string
44 Token string
45 JobToken string
47 ApiHost string
48 ApiProtocol string
49 GitProtocol string
50 SSHHostname string
51 ContainerRegistryDomains string
53 WebLogin bool
54 DeviceLogin bool
55 UseKeyring bool // Deprecated: keyring storage is now the default.
56 InsecureStorage bool
58 SetupGitCredentialHelper bool
59}
61var opts *LoginOptions
63func NewCmdLogin(f cmdutils.Factory) *cobra.Command {
64 opts = &LoginOptions{
65 IO: f.IO(),
66 Config: f.Config,
67 apiClient: f.ApiClient,
68 defaultHostname: f.DefaultHostname(),
69 // loginRun sets use_keyring before the OAuth2 flow stores a token, so
70 // f.ApiClient would fail here on the missing keyring token.
71 unauthenticatedAPIClient: func(repoHost string) (*api.Client, error) {
72 return api.NewClientFromConfig(repoHost, f.Config(), false, f.BuildInfo().UserAgent(), api.WithoutAuthentication())
73 },
74 }
76 var tokenStdin bool
78 cmd := &cobra.Command{
79 Use: "login",
80 Args: cobra.NoArgs,
81 ValidArgsFunction: cobra.NoFileCompletions,
82 Short: "Authenticate with a GitLab instance.",
83 Long: heredoc.Docf(`
84 Authenticates with a GitLab instance.
86 By default, glab stores your credentials in your operating system's
87 keyring (macOS Keychain, Windows Credential Manager, or the Secret
88 Service on Linux) when one is available. If no keyring is available,
89 or if you pass %[1]s--insecure-storage%[1]s, glab stores them in the global
90 configuration file (default %[1]s~/.config/glab-cli/config.yml%[1]s) as
91 plaintext instead. After authentication, all glab commands use the
92 stored credentials.
94 If you previously signed in and your credentials are stored as
95 plaintext in the configuration file, run %[1]sglab auth login%[1]s again to
96 move them into the keyring.
98 In CI (when %[1]sGITLAB_CI%[1]s or %[1]sCI%[1]s is set), glab stores credentials in the
99 configuration file rather than the keyring. Credentials in CI are
100 usually supplied through environment variables, and an OS keyring is
101 often unavailable there.
103 If %[1]sGITLAB_TOKEN%[1]s, %[1]sGITLAB_ACCESS_TOKEN%[1]s, or %[1]sOAUTH_TOKEN%[1]s are set,
104 they take precedence over the stored credentials. When CI auto-login is
105 enabled, these variables also override %[1]sCI_JOB_TOKEN%[1]s. They apply only
106 to the host named by %[1]sGITLAB_HOST%[1]s or %[1]sGITLAB_REPO%[1]s, and to hosts in the
107 configuration file.
109 To pass a token on standard input, use %[1]s--stdin%[1]s.
111 On instances where personal access tokens are disabled, sign in with OAuth and use glab as the Git credential helper instead of Git Credential Manager. glab automatically refreshes the OAuth token for Git and doesn't need an OAuth client secret.
113 To configure glab as the Git credential helper non-interactively (for example, in a CI/CD job), use %[1]s--setup-git-credential-helper%[1]s.
115 In interactive mode, glab detects GitLab instances from your Git remotes
116 and lists them as options, so you do not have to type the hostname manually.
118 After you sign in, glab can make the instance your default %[1]shost%[1]s, which
119 glab uses outside a Git repository. glab does this automatically when the
120 default is still %[1]sgitlab.com%[1]s and you have no %[1]sgitlab.com%[1]s credentials.
121 Otherwise, it asks first, or in a non-interactive run prints the
122 %[1]sglab config set%[1]s command to run. glab leaves %[1]shost%[1]s unchanged in CI,
123 or when %[1]sGITLAB_HOST%[1]s, %[1]sGITLAB_URI%[1]s, or %[1]sGL_HOST%[1]s is set.
125 When you omit %[1]s--hostname%[1]s in a non-interactive run, glab authenticates
126 with the first of these that applies:
128 - The host of the base repository, if you're in a Git repository with a GitLab remote.
129 - The %[1]sGITLAB_HOST%[1]s environment variable, if it's set.
130 - The %[1]shost%[1]s key in your configuration file, if it's set.
131 - %[1]sgitlab.com%[1]s, if none of the above apply.
132 `, "`"),
133 Example: heredoc.Docf(`
134 # Start interactive setup
135 # If in a Git repository, glab detects and suggests GitLab instances from remotes
136 glab auth login
138 # Authenticate against %[1]sgitlab.com%[1]s by reading the token from a file
139 glab auth login --stdin < myaccesstoken.txt
141 # Authenticate with GitLab Self-Managed or GitLab Dedicated
142 glab auth login --hostname salsa.debian.org
144 # Non-interactive setup
145 glab auth login --hostname gitlab.example.org --token glpat-xxx --api-host gitlab.example.org:3443 --api-protocol https --git-protocol ssh
147 # Non-interactive setup reading the token from a file
148 glab auth login --hostname gitlab.example.org --api-host gitlab.example.org:3443 --api-protocol https --git-protocol ssh --stdin < myaccesstoken.txt
150 # Semi-interactive OAuth login, skipping all prompts except browser auth
151 glab auth login --hostname gitlab.com --web --git-protocol ssh --container-registry-domains "gitlab.com,gitlab.com:443,registry.gitlab.com"
153 # Semi-interactive OAuth login for GitLab Self-Managed, with every
154 # prompted value supplied by a flag.
155 glab auth login --hostname gitlab.example.com --web --api-host gitlab.example.com --ssh-hostname gitlab.example.com --api-protocol https --git-protocol ssh --container-registry-domains registry.gitlab.example.com
157 # OAuth device authorization flow for headless environments without a local browser.
158 # glab displays a one-time code and verification URL; you authorize on any
159 # other device with a browser. Requires GitLab 17.9 or later.
160 glab auth login --hostname gitlab.com --device
162 # CI/CD setup: for most cases, prefer auto-login over manual login
163 GLAB_ENABLE_CI_AUTOLOGIN=true glab release list -R $CI_PROJECT_PATH
165 # CI/CD setup with manual login: use when the command does not support CI job tokens, or you need a personal access token
166 glab auth login --hostname $CI_SERVER_FQDN --job-token $CI_JOB_TOKEN --api-protocol $CI_SERVER_PROTOCOL
168 # Non-interactive setup that also lets Git push and pull with the same token
169 glab auth login --hostname $CI_SERVER_FQDN --token $GITLAB_TOKEN --setup-git-credential-helper
171 # Sign in with OAuth and configure glab as the Git credential helper (recommended when personal access tokens are disabled)
172 glab config set client_id <CLIENT_ID> --host gitlab.example.com
173 glab auth login --hostname gitlab.example.com --web --setup-git-credential-helper
174 `, "`"),
175 Annotations: map[string]string{
176 mcpannotations.Exclude: "true",
177 },
178 RunE: func(cmd *cobra.Command, args []string) error {
179 if !opts.IO.PromptEnabled() && !tokenStdin && opts.Token == "" && opts.JobToken == "" && !opts.WebLogin && !opts.DeviceLogin {
180 return &cmdutils.FlagError{Err: errors.New("'--stdin', '--token', '--job-token', '--web', or '--device' required when not running interactively")}
181 }
183 // --token, --stdin, --job-token, --web, --device are pairwise mutually
184 // exclusive via cmd.MarkFlagsMutuallyExclusive below.
186 if tokenStdin {
187 defer opts.IO.In.Close()
188 token, err := io.ReadAll(opts.IO.In)
189 if err != nil {
190 return fmt.Errorf("failed to read token from STDIN: %w", err)
191 }
192 opts.Token = strings.TrimSpace(string(token))
193 }
195 if opts.IO.PromptEnabled() && opts.Token == "" && opts.JobToken == "" && opts.IO.IsaTTY {
196 opts.Interactive = true
197 }
199 if cmd.Flags().Changed("hostname") {
200 if err := hostnameValidator(opts.Hostname); err != nil {
201 return &cmdutils.FlagError{Err: fmt.Errorf("error parsing '--hostname': %w", err)}
202 }
203 }
205 if cmd.Flags().Changed("api-host") && strings.Contains(opts.ApiHost, "://") {
206 stripped, _ := glinstance.StripHostProtocol(opts.ApiHost)
207 if stripped == "" {
208 return &cmdutils.FlagError{Err: fmt.Errorf("error parsing '--api-host': value must be a hostname, not a URL (for example, %q or %q)", "example.com", "example.com:3443")}
209 }
210 return &cmdutils.FlagError{Err: fmt.Errorf("error parsing '--api-host': value must be a hostname, not a URL. Use %q instead", stripped)}
211 }
213 // defaultHostname is the factory's resolution of GITLAB_HOST and
214 // the config, not the gitlab.com constant.
215 if !opts.Interactive && opts.Hostname == "" {
216 opts.Hostname = opts.defaultHostname
217 }
219 if err := loginRun(cmd.Context(), opts); err != nil {
220 return cmdutils.WrapError(err, "Could not sign in!")
221 }
223 return nil
224 },
225 }
227 cmd.Flags().StringVarP(&opts.Hostname, "hostname", "", "", "The hostname of the GitLab instance to authenticate with. When omitted, glab prompts in interactive mode, or uses the host resolved from your Git remotes, GITLAB_HOST, and your configuration.")
228 cmd.Flags().StringVarP(&opts.Token, "token", "t", "", "Your GitLab access token.")
229 cmd.Flags().StringVarP(&opts.JobToken, "job-token", "j", "", "CI job token.")
230 cmd.Flags().BoolVar(&tokenStdin, "stdin", false, "Read the token from standard input.")
231 cmd.Flags().BoolVar(&opts.UseKeyring, "use-keyring", false, "Store the token in your operating system's keyring.")
232 cmd.Flags().BoolVar(&opts.InsecureStorage, "insecure-storage", false, "Store the token as plaintext in the configuration file instead of the operating system's keyring.")
233 cobra.CheckErr(cmd.Flags().MarkDeprecated("use-keyring", "keyring storage is now the default. Use --insecure-storage to store the token in the configuration file."))
234 cmd.Flags().BoolVar(&opts.WebLogin, "web", false, "Skip the login type prompt and use web/OAuth login.")
235 cmd.Flags().BoolVar(&opts.DeviceLogin, "device", false, "Use the OAuth 2.0 device authorization flow. Useful for headless environments where a local browser is not available. Requires GitLab 17.9 or later.")
236 cmd.Flags().StringVarP(&opts.ApiHost, "api-host", "a", "", "Hostname for the API endpoint, if different from --hostname. Accepts a hostname or hostname:port. Also skips the API hostname prompt in interactive mode.")
237 cmd.Flags().StringVarP(&opts.ApiProtocol, "api-protocol", "p", "", "API protocol. Options: https, http.")
238 cmd.Flags().StringVarP(&opts.GitProtocol, "git-protocol", "g", "", "Git protocol. Options: ssh, https, http.")
239 cmd.Flags().StringVar(&opts.SSHHostname, "ssh-hostname", "", "SSH hostname for instances with a different SSH endpoint. A port is not required; Git uses the port from the remote URL. Also skips the SSH hostname prompt in interactive mode.")
240 cmd.Flags().StringVar(&opts.ContainerRegistryDomains, "container-registry-domains", "", "Container registry and image dependency proxy domains, comma-separated.")
241 cmd.Flags().BoolVar(&opts.SetupGitCredentialHelper, "setup-git-credential-helper", false, "Configure glab as the Git credential helper for this host without prompting. Use this in non-interactive runs, such as CI/CD jobs.")
243 cmd.MarkFlagsMutuallyExclusive("token", "stdin", "job-token", "web", "device")
244 cmd.MarkFlagsMutuallyExclusive("use-keyring", "insecure-storage")
246 return cmd
247}
249// lookupUsername resolves the account behind the token that was just stored on
250// hostname, so `glab auth status` and the Git credential helper can use the
251// real username.
252func lookupUsername(ctx context.Context, opts *LoginOptions, hostname string) (string, error) {
253 apiClient, err := opts.apiClient(hostname)
254 if err != nil {
255 return "", err
256 }
258 ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
259 defer cancel()
261 user, _, err := apiClient.Lab().Users.CurrentUser(gitlab.WithContext(ctx))
262 if err != nil {
263 return "", err
264 }
265 return user.Username, nil
266}
268// glabExecutable returns the path Git should call back into for the credential
269// helper, and falls back to the command name when the path is unavailable.
270func glabExecutable() string {
271 if exe, err := os.Executable(); err == nil {
272 return exe
273 }
274 return "glab"
275}
277func loginRun(ctx context.Context, opts *LoginOptions) error {
278 c := opts.IO.Color()
279 cfg := opts.Config()
281 // Decide once whether credentials should be stored in the OS keyring.
282 // Keyring is the default when a backend is available. --insecure-storage
283 // forces plaintext file storage. The deprecated --use-keyring only still
284 // matters in CI, where it opts back in to the keyring. The resolved value
285 // is persisted per-host in each authentication path below.
286 keyringPref := "false"
287 switch {
288 case opts.InsecureStorage:
289 // Explicit opt-out: store in the configuration file without warning.
290 case !opts.UseKeyring && config.InCI():
291 // In CI, credentials are ephemeral and usually supplied via environment
292 // variables, and an OS keyring is typically unavailable or not persisted
293 // across job steps (a locked keyring would also make later reads fail).
294 // Default to file storage there unless the keyring is explicitly
295 // requested with the (deprecated) --use-keyring.
296 case config.KeyringAvailable():
297 keyringPref = "true"
298 default:
299 // No keyring backend available: fall back to file storage, but warn that
300 // credentials are stored as plaintext.
301 opts.IO.LogErrorf("%s The operating system keyring is unavailable. Storing credentials as plaintext in the configuration file.\n", c.Yellow("WARNING:"))
302 if config.SnapConfined() {
303 opts.IO.LogErrorf("glab is running under snap confinement. To enable OS keyring storage, run:\n %s\nThen re-run %s to migrate this token into the keyring.\n", c.Bold(config.SnapConnectCommand), c.Bold("glab auth login"))
304 }
305 }
307 if opts.Token != "" {
308 if opts.Hostname == "" {
309 return errors.New("empty hostname would leak `oauth_token`")
310 }
312 hostname, subfolder := splitHostnameAndSubfolder(opts.Hostname)
314 if err := authutils.ClearAuthFields(cfg, hostname); err != nil {
315 return err
316 }
318 if err := cfg.Set(hostname, "use_keyring", keyringPref); err != nil {
319 return err
320 }
322 err := cfg.Set(hostname, "token", opts.Token)
323 if err != nil {
324 return err
325 }
327 if opts.ApiHost != "" {
328 err := cfg.Set(hostname, "api_host", opts.ApiHost)
329 if err != nil {
330 return err
331 }
332 }
334 if subfolder != "" {
335 err := cfg.Set(hostname, "subfolder", subfolder)
336 if err != nil {
337 return err
338 }
339 }
341 if opts.ApiProtocol != "" {
342 err := cfg.Set(hostname, "api_protocol", opts.ApiProtocol)
343 if err != nil {
344 return err
345 }
346 }
348 if opts.GitProtocol != "" {
349 err := cfg.Set(hostname, "git_protocol", opts.GitProtocol)
350 if err != nil {
351 return err
352 }
353 }
355 // Best-effort: a failed lookup must not make this flow require network
356 // access, because it is the flow scripts and CI jobs use.
357 if username, err := lookupUsername(ctx, opts, hostname); err != nil {
358 opts.IO.LogErrorf("%s Could not look up the username for this token: %v\n", c.Yellow("WARNING:"), err)
359 } else {
360 if err := cfg.Set(hostname, "user", username); err != nil {
361 return err
362 }
363 opts.IO.LogErrorf("%s Logged in as %s\n", c.GreenCheck(), c.Bold(username))
364 }
366 domains := initialContainerRegistryDomains(cfg, hostname, opts.ContainerRegistryDomains)
367 if err := setContainerRegistryDomains(cfg, hostname, domains); err != nil {
368 return err
369 }
371 if err := cfg.Write(); err != nil {
372 return err
373 }
374 if err := setupGitCredentialHelper(opts, hostname, opts.GitProtocol); err != nil {
375 return err
376 }
377 logCredentialStorage(opts.IO, keyringPref)
378 warnEnvTokenPrecedence(opts.IO)
379 return updateDefaultHost(ctx, opts, cfg, hostname)
380 }
382 if opts.JobToken != "" {
383 if opts.Hostname == "" {
384 return errors.New("empty hostname would leak `oauth_token`")
385 }
387 hostname, subfolder := splitHostnameAndSubfolder(opts.Hostname)
389 if err := authutils.ClearAuthFields(cfg, hostname); err != nil {
390 return err
391 }
393 if err := cfg.Set(hostname, "use_keyring", keyringPref); err != nil {
394 return err
395 }
397 err := cfg.Set(hostname, "job_token", opts.JobToken)
398 if err != nil {
399 return err
400 }
402 if opts.ApiHost != "" {
403 err := cfg.Set(hostname, "api_host", opts.ApiHost)
404 if err != nil {
405 return err
406 }
407 }
409 if subfolder != "" {
410 err := cfg.Set(hostname, "subfolder", subfolder)
411 if err != nil {
412 return err
413 }
414 }
416 if opts.ApiProtocol != "" {
417 err := cfg.Set(hostname, "api_protocol", opts.ApiProtocol)
418 if err != nil {
419 return err
420 }
421 }
423 if opts.GitProtocol != "" {
424 err := cfg.Set(hostname, "git_protocol", opts.GitProtocol)
425 if err != nil {
426 return err
427 }
428 }
430 if err := cfg.Write(); err != nil {
431 return err
432 }
433 if err := setupGitCredentialHelper(opts, hostname, opts.GitProtocol); err != nil {
434 return err
435 }
436 logCredentialStorage(opts.IO, keyringPref)
437 return nil
438 }
440 // Split hostname into base hostname and subfolder if present
441 var subfolder string
442 hostname, _ := splitHostnameAndSubfolder(opts.Hostname)
443 apiHostname := initialAPIHostname(cfg, hostname, opts.ApiHost)
445 isSelfHosted := false
447 // GITLAB_HOST already answers "which instance", so skip the menu.
448 if hostname == "" {
449 if envHost := config.GetFromEnv("host"); envHost != "" {
450 hostname, _ = splitHostnameAndSubfolder(envHost)
451 apiHostname = initialAPIHostname(cfg, hostname, opts.ApiHost)
452 }
453 }
455 if hostname == "" {
456 // Try to detect GitLab hosts from git remotes
457 detectedHosts, detectErr := detectGitLabHosts(cfg)
459 if detectErr == nil && len(detectedHosts) > 0 {
460 // We have detected hosts, present them to the user
461 options := make([]string, 0, len(detectedHosts)+1)
462 for _, host := range detectedHosts {
463 options = append(options, host.String())
464 }
465 options = append(options, promptLoginDifferentHostname)
467 var selectedOption string
468 err := opts.IO.Select(ctx, &selectedOption, "Found GitLab instances in git remotes. Select one:", options)
469 if err != nil {
470 return fmt.Errorf("could not prompt: %w", err)
471 }
473 // Check if user selected "Enter a different hostname"
474 if selectedOption == promptLoginDifferentHostname {
475 // Fall back to manual entry
476 var sshHostname string
477 var err error
478 hostname, apiHostname, sshHostname, err = promptForSelfHostedInstance(ctx, opts)
479 if err != nil {
480 return err
481 }
482 opts.SSHHostname = sshHostname
483 } else {
484 // User selected a detected host - find it in the list
485 for _, host := range detectedHosts {
486 if host.String() == selectedOption {
487 hostname = host.hostname
488 apiHostname = initialAPIHostname(cfg, hostname, opts.ApiHost)
489 break
490 }
491 }
492 }
493 } else {
494 // No detected hosts or detection failed, fall back to original behavior
495 options := []string{}
496 if hosts, err := cfg.Hosts(); err == nil {
497 options = append(options, hosts...)
498 }
499 if !slices.Contains(options, opts.defaultHostname) {
500 options = append(options, opts.defaultHostname)
501 }
502 options = append(options, promptSelfManagedOrDedicatedInstance)
504 var selectedOption string
505 err := opts.IO.Select(ctx, &selectedOption, "What GitLab instance do you want to sign in to?", options)
506 if err != nil {
507 return fmt.Errorf("could not prompt: %w", err)
508 }
510 isSelfHosted = selectedOption == promptSelfManagedOrDedicatedInstance
512 if isSelfHosted {
513 var sshHostname string
514 var err error
515 hostname, apiHostname, sshHostname, err = promptForSelfHostedInstance(ctx, opts)
516 if err != nil {
517 return err
518 }
519 opts.SSHHostname = sshHostname
520 } else {
521 hostname = selectedOption
522 apiHostname = initialAPIHostname(cfg, hostname, opts.ApiHost)
523 }
524 }
525 } else {
526 isSelfHosted = glinstance.IsSelfHosted(hostname)
528 if opts.Interactive && isSelfHosted {
529 if envSSHHost := config.GetFromEnv("ssh_host"); opts.SSHHostname == "" && envSSHHost != "" {
530 opts.SSHHostname = envSSHHost
531 }
533 if opts.ApiHost == "" && config.GetFromEnv("api_host") == "" {
534 // Pre-filled by initialAPIHostname above.
535 apiHostnameInput := huh.NewInput().
536 Title("API hostname:").
537 Description("For instances with a different hostname for the API endpoint.").
538 Value(&apiHostname).
539 Placeholder(hostname).
540 Validate(func(s string) error {
541 return hostnameValidator(s)
542 })
543 if err := opts.IO.Run(ctx, apiHostnameInput); err != nil {
544 return fmt.Errorf("could not prompt: %w", err)
545 }
546 }
548 if opts.SSHHostname == "" {
549 sshHostname := initialSSHHostname(cfg, hostname)
551 sshHostnameInput := huh.NewInput().
552 Title("SSH hostname:").
553 Description("For instances with a different hostname for SSH git operations.").
554 Value(&sshHostname).
555 Placeholder(hostname).
556 Validate(func(s string) error {
557 return hostnameValidator(s)
558 })
559 if err := opts.IO.Run(ctx, sshHostnameInput); err != nil {
560 return fmt.Errorf("could not prompt: %w", err)
561 }
563 opts.SSHHostname = sshHostname
564 }
565 }
566 }
568 opts.IO.LogErrorf("- Signing into %s\n", hostname)
570 // Surface the env-token precedence before the prompts below (the
571 // "already logged in" confirmation and the sign-in method selection),
572 // since it should inform the user's choice.
573 warnEnvTokenPrecedence(opts.IO)
575 existingToken, _, _ := cfg.GetWithSource(hostname, "token", false)
577 if existingToken != "" && opts.Interactive {
578 apiClient, err := opts.apiClient(hostname)
579 if err != nil {
580 return err
581 }
583 authCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
584 defer cancel()
585 user, _, err := apiClient.Lab().Users.CurrentUser(gitlab.WithContext(authCtx))
586 if err == nil {
587 username := user.Username
588 keepGoing := false // default value
589 confirm := huh.NewConfirm().
590 Title(fmt.Sprintf(
591 "You're already logged into %s as %s. Do you want to re-authenticate?",
592 hostname,
593 username)).
594 Value(&keepGoing)
595 err = opts.IO.Run(ctx, confirm)
596 if err != nil {
597 return fmt.Errorf("could not prompt: %w", err)
598 }
600 if !keepGoing {
601 return nil
602 }
603 }
604 }
606 var loginType string
608 // Resolved before the interactive block so a login that never reaches the
609 // prompt keeps the host's existing domains instead of clearing them.
610 containerRegistryDomains := initialContainerRegistryDomains(cfg, hostname, opts.ContainerRegistryDomains)
612 switch {
613 case opts.Interactive:
614 switch {
615 case opts.WebLogin:
616 loginType = promptLoginTypeWeb
617 case opts.DeviceLogin:
618 loginType = promptLoginTypeDevice
619 default:
620 loginTypeOptions := []string{promptLoginTypeToken, promptLoginTypeWeb, promptLoginTypeDevice}
621 err := opts.IO.Select(ctx, &loginType, "How would you like to sign in?", loginTypeOptions)
622 if err != nil {
623 return fmt.Errorf("could not get sign-in type: %w", err)
624 }
625 }
627 if opts.ContainerRegistryDomains == "" && config.GetFromEnv("container_registry_domains") == "" {
628 containerRegistryInput := huh.NewInput().
629 Title("What domains does this host use for the container registry and image dependency proxy?").
630 Value(&containerRegistryDomains).
631 Placeholder(defaultContainerRegistryDomainsString(hostname))
632 err := opts.IO.Run(ctx, containerRegistryInput)
633 if err != nil {
634 return fmt.Errorf("could not get container registry domains: %w", err)
635 }
636 }
637 case opts.WebLogin:
638 // Non-interactive web login: go straight to OAuth
639 loginType = promptLoginTypeWeb
640 case opts.DeviceLogin:
641 // Non-interactive device flow login
642 loginType = promptLoginTypeDevice
643 }
645 // Re-split hostname in case it was changed by prompts
646 hostname, subfolder = splitHostnameAndSubfolder(hostname)
648 // Persist the keyring preference before acquiring the token so that the
649 // token (including tokens written by the OAuth flow's marshal step) is
650 // routed to the correct storage backend.
651 if hostname != "" {
652 if err := cfg.Set(hostname, "use_keyring", keyringPref); err != nil {
653 return err
654 }
655 }
657 var token string
658 var err error
659 if strings.EqualFold(loginType, promptLoginTypeToken) {
660 token, err = showTokenPrompt(ctx, opts.IO, hostname)
661 if err != nil {
662 return err
663 }
665 // Clear stale OAuth fields only after the prompt succeeds, so that a
666 // cancelled or failed login leaves existing credentials intact.
667 // This handles the OAuth → PAT switch: is_oauth2 / refresh / expiry fields
668 // that were set by a previous OAuth login are removed before the PAT is saved.
669 if err := authutils.ClearAuthFields(cfg, hostname); err != nil {
670 return err
671 }
672 } else {
673 client, err := opts.unauthenticatedAPIClient(hostname)
674 if err != nil {
675 return err
676 }
678 // StartFlow / StartDeviceFlow both call marshal() internally, which writes
679 // is_oauth2, token, oauth2_refresh_token, and oauth2_expiry_date. No
680 // explicit ClearAuthFields is needed: marshal() overwrites every field it
681 // owns, and is_oauth2=true ensures the OAuth auth source wins over any
682 // residual job_token.
683 if strings.EqualFold(loginType, promptLoginTypeDevice) {
684 token, err = oauth2.StartDeviceFlow(ctx, cfg, opts.IO, client.HTTPClient(), hostname)
685 } else {
686 token, err = oauth2.StartFlow(ctx, cfg, opts.IO, client.HTTPClient(), hostname)
687 }
688 if err != nil {
689 return err
690 }
691 }
693 if hostname == "" {
694 return errors.New("empty hostname would leak the token")
695 }
697 if err := cfg.Set(hostname, "token", token); err != nil {
698 return err
699 }
701 if err := setContainerRegistryDomains(cfg, hostname, containerRegistryDomains); err != nil {
702 return err
703 }
705 if err := cfg.Set(hostname, "api_host", apiHostname); err != nil {
706 return err
707 }
709 // Set subfolder if present
710 if subfolder != "" {
711 if err := cfg.Set(hostname, "subfolder", subfolder); err != nil {
712 return err
713 }
714 }
716 // Set SSH hostname if it's different from the main hostname
717 if opts.SSHHostname != "" && opts.SSHHostname != hostname {
718 if err := cfg.Set(hostname, "ssh_host", opts.SSHHostname); err != nil {
719 return err
720 }
721 }
723 // Smart default: use SSH if user configured a custom SSH host
724 gitProtocol := "https"
725 if opts.SSHHostname != "" && opts.SSHHostname != hostname {
726 gitProtocol = "ssh"
727 }
728 apiProtocol := "https"
730 credentialFlow := &authutils.GitCredentialFlow{Executable: glabExecutable()}
732 // Persist --git-protocol / --api-protocol before the interactive block so
733 // the flags aren't silently dropped when stdin isn't a TTY (--web /
734 // --device in CI or a devcontainer setup script). The interactive block
735 // below also writes, but idempotently with the same value.
736 if err := persistProtocolFlags(cfg, hostname, opts.GitProtocol, opts.ApiProtocol); err != nil {
737 return err
738 }
740 if opts.Interactive {
741 if opts.GitProtocol != "" {
742 gitProtocol = strings.ToLower(opts.GitProtocol)
743 } else if envGitProtocol := config.GetFromEnv("git_protocol"); envGitProtocol != "" {
744 gitProtocol = strings.ToLower(envGitProtocol)
745 } else {
746 gitProtocolOptions := []string{promptProtocolSSH, promptProtocolHTTPS, promptProtocolHTTP}
747 // Use smart default based on SSH hostname configuration
748 defaultProtocol := promptProtocolHTTPS
749 if gitProtocol == "ssh" {
750 defaultProtocol = promptProtocolSSH
751 }
752 gitProtocol = defaultProtocol
753 err = opts.IO.Select(ctx, &gitProtocol, "Choose default Git protocol:", gitProtocolOptions)
754 if err != nil {
755 return fmt.Errorf("could not prompt: %w", err)
756 }
758 gitProtocol = strings.ToLower(gitProtocol)
759 }
761 // --setup-git-credential-helper already answers this prompt.
762 if gitProtocol != "ssh" && !opts.SetupGitCredentialHelper {
763 if err := credentialFlow.Prompt(ctx, opts.IO, hostname, gitProtocol); err != nil {
764 return err
765 }
766 }
768 if isSelfHosted {
769 if opts.ApiProtocol != "" {
770 apiProtocol = strings.ToLower(opts.ApiProtocol)
771 } else if envApiProtocol := config.GetFromEnv("api_protocol"); envApiProtocol != "" {
772 apiProtocol = strings.ToLower(envApiProtocol)
773 } else {
774 apiProtocolOptions := []string{promptProtocolHTTPS, promptProtocolHTTP}
775 apiProtocol = promptProtocolHTTPS // Set default
776 err = opts.IO.Select(ctx, &apiProtocol, "Choose host API protocol:", apiProtocolOptions)
777 if err != nil {
778 return fmt.Errorf("could not prompt: %w", err)
779 }
781 apiProtocol = strings.ToLower(apiProtocol)
782 }
783 }
785 opts.IO.LogErrorf("- glab config set -h %s git_protocol %s\n", hostname, gitProtocol)
786 if err := cfg.Set(hostname, "git_protocol", gitProtocol); err != nil {
787 return err
788 }
790 opts.IO.LogErrorf("%s Configured Git protocol.\n", c.GreenCheck())
792 opts.IO.LogErrorf("- glab config set -h %s api_protocol %s\n", hostname, apiProtocol)
793 if err := cfg.Set(hostname, "api_protocol", apiProtocol); err != nil {
794 return err
795 }
797 opts.IO.LogErrorf("%s Configured API protocol.\n", c.GreenCheck())
798 } else if opts.GitProtocol != "" {
799 gitProtocol = strings.ToLower(opts.GitProtocol)
800 }
801 username, err := lookupUsername(ctx, opts, hostname)
802 if err != nil {
803 return fmt.Errorf("error using API: %w", err)
804 }
806 if err := cfg.Set(hostname, "user", username); err != nil {
807 return err
808 }
810 err = cfg.Write()
811 if err != nil {
812 return err
813 }
815 if credentialFlow.ShouldSetup() {
816 err := credentialFlow.Setup(hostname, gitProtocol, username, token)
817 if err != nil {
818 return err
819 }
820 }
821 if err := setupGitCredentialHelper(opts, hostname, gitProtocol); err != nil {
822 return err
823 }
825 opts.IO.LogErrorf("%s Logged in as %s\n", c.GreenCheck(), c.Bold(username))
826 logCredentialStorage(opts.IO, keyringPref)
827 opts.IO.LogErrorf("%s Configuration saved to %s\n", c.GreenCheck(), config.ConfigFile())
828 opts.IO.LogErrorf(" - Host: %s\n", hostname)
829 if subfolder != "" {
830 opts.IO.LogErrorf(" - Subfolder: %s\n", subfolder)
831 }
832 if sshHostValue, _ := cfg.Get(hostname, "ssh_host"); sshHostValue != "" {
833 opts.IO.LogErrorf(" - SSH host: %s\n", sshHostValue)
834 }
836 return updateDefaultHost(ctx, opts, cfg, hostname)
837}
839// updateDefaultHost points the global host key at hostname, which commands run
840// outside a Git repository (such as `glab repo clone`) fall back to. It does so
841// unprompted only while the default is still gitlab.com and gitlab.com holds no
842// credentials, so an existing setup is never repointed silently. Otherwise it
843// asks in interactive mode, and prints the command to run in scripted mode.
844// The host environment variables and CI already decide the host per run, so it
845// leaves those alone. The login has already succeeded, so cancelling the prompt
846// counts as a no, and any other failure is a warning rather than an error.
847func updateDefaultHost(ctx context.Context, opts *LoginOptions, cfg config.Config, hostname string) error {
848 if config.InCI() {
849 return nil
850 }
851 if envHost := config.GetFromEnv("host"); envHost != "" {
852 return nil
853 }
855 c := opts.IO.Color()
856 warn := func(err error) error {
857 opts.IO.LogErrorf("%s Could not set the default host: %v. To set it, run: %s\n",
858 c.WarnIcon(), err, c.Bold("glab config set --global host "+hostname))
859 return nil
860 }
862 current, _, err := cfg.GetWithSource("", "host", false)
863 if err != nil {
864 return warn(err)
865 }
866 // glab accepts host as a URL, so compare without the scheme.
867 current, _ = glinstance.StripHostProtocol(current)
868 if current == "" {
869 current = glinstance.DefaultHostname
870 }
871 if strings.EqualFold(current, hostname) {
872 return nil
873 }
875 setDefault := strings.EqualFold(current, glinstance.DefaultHostname) && !hasCredentials(cfg, glinstance.DefaultHostname)
876 if !setDefault {
877 if !opts.Interactive {
878 opts.IO.LogErrorf("%s Outside a Git repository, glab uses the default host %s. To use %s instead, run: %s\n",
879 c.WarnIcon(), current, hostname, c.Bold("glab config set --global host "+hostname))
880 return nil
881 }
882 confirm := huh.NewConfirm().
883 Title(fmt.Sprintf("Outside a Git repository, glab uses the default host %s. Make %s the default instead?", current, hostname)).
884 Value(&setDefault)
885 if err := opts.IO.Run(ctx, confirm); err != nil {
886 if errors.Is(err, iostreams.ErrUserCancelled) {
887 return nil
888 }
889 return warn(fmt.Errorf("could not prompt: %w", err))
890 }
891 if !setDefault {
892 return nil
893 }
894 }
896 if err := cfg.Set("", "host", hostname); err != nil {
897 return warn(err)
898 }
899 if err := cfg.Write(); err != nil {
900 return warn(err)
901 }
902 opts.IO.LogErrorf("%s Default host set to %s\n", c.GreenCheck(), hostname)
903 return nil
904}
906// hasCredentials counts an environment token, because glab sends it to every
907// host and repointing the default would send it to the new one. It also counts
908// an unreadable keyring or config entry, so a read failure cannot cause the
909// default host to be repointed.
910func hasCredentials(cfg config.Config, hostname string) bool {
911 if config.GetFromEnv("token") != "" {
912 return true
913 }
914 for _, key := range []string{"token", "job_token"} {
915 value, _, err := cfg.GetWithSource(hostname, key, false)
916 if err != nil {
917 dbg.Debugf("Could not read %s for %s, keeping the default host: %v", key, hostname, err)
918 return true
919 }
920 if value != "" {
921 return true
922 }
923 }
924 return false
925}
927// logCredentialStorage tells the user where their credentials were stored, so
928// the default keyring behavior (and any fallback to the file) is visible.
929func logCredentialStorage(io *iostreams.IOStreams, keyringPref string) {
930 c := io.Color()
931 if keyringPref == "true" {
932 io.LogErrorf("%s Stored your credentials in the operating system keyring.\n", c.GreenCheck())
933 } else {
934 io.LogErrorf("%s Stored your credentials in the configuration file.\n", c.GreenCheck())
935 }
936}
938// warnEnvTokenPrecedence alerts the user when a token is provided through an
939// environment variable. Such a variable takes precedence over the token stored
940// in the keyring or configuration file, so glab keeps using it. It is emitted
941// before the interactive prompts so it can inform the user's choice, hence the
942// timing-neutral wording. The cause is diagnosed rather than assumed: the
943// variable might be injected temporarily by a wrapper such as the 1Password
944// shell integration (which is expected and needs no action) or persisted in
945// the shell environment (which the user should remove). `type glab`
946// distinguishes the two.
947func warnEnvTokenPrecedence(io *iostreams.IOStreams) {
948 envToken, envTokenSource := config.GetFromEnvWithSource("token")
949 if envToken == "" {
950 return
951 }
952 c := io.Color()
953 io.LogErrorf("\n%s The environment variable %s is set and takes precedence over credentials stored in the keyring or configuration file.\n", c.WarnIcon(), c.Bold(envTokenSource))
954 io.LogErrorf(" Run %s 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.\n", c.Bold("type glab"))
955 io.LogErrorf(" A plain path means it is set in your environment (for example, a shell profile such as ~/.bashrc or ~/.zshrc, or a CI/CD variable); remove it there so glab uses your stored credentials.\n")
956}
958func hostnameValidator(v any) error {
959 s, ok := v.(string)
960 if !ok {
961 return errors.New("hostname must be a string")
962 }
964 if strings.TrimSpace(s) == "" {
965 return errors.New("hostname cannot be empty")
966 }
968 // NOTE: adding a scheme here so that `url.Parse`
969 // doesn't interpret the first segment before a colon
970 // as a scheme. We never expect `v` to contain
971 // a scheme anyways.
972 val := fmt.Sprintf("https://%s", s)
973 _, err := url.Parse(val)
974 if err != nil {
975 return fmt.Errorf("invalid hostname: %w", err)
976 }
978 return nil
979}
981func getAccessTokenTip(hostname string) string {
982 // legacy/new does not exist before GitLab 18.9, hence the fallback URL.
983 return fmt.Sprintf(`
984 The minimum required scopes are 'api' and 'write_repository'.
985 Generate a personal access token at https://%[1]s/-/user_settings/personal_access_tokens/legacy/new?scopes=api,write_repository
986 On GitLab 18.8 and earlier, use https://%[1]s/-/user_settings/personal_access_tokens?scopes=api,write_repository instead.`, hostname)
987}
989func showTokenPrompt(ctx context.Context, io *iostreams.IOStreams, hostname string) (string, error) {
990 io.LogError()
991 io.LogError(heredoc.Doc(getAccessTokenTip(hostname)))
993 var token string
994 tokenInput := huh.NewInput().
995 Title("Paste your authentication token:").
996 Value(&token).
997 EchoMode(huh.EchoModePassword).
998 Validate(func(s string) error {
999 if s == "" {
1000 return fmt.Errorf("required")
1001 }
1002 return nil
1003 })
1004 err := io.Run(ctx, tokenInput)
1005 if err != nil {
1006 return "", fmt.Errorf("could not prompt: %w", err)
1007 }
1009 return token, nil
1010}
1012// initialAPIHostname returns the value used to pre-fill the API-hostname
1013// prompt (and the value written to config when the prompt is skipped).
1014// Precedence: --api-host flag, then a value previously saved for the host,
1015// then the base hostname. Reading the saved value first prevents a
1016// re-authentication from silently overwriting a value the user set with
1017// `glab config set`.
1018func initialAPIHostname(cfg config.Config, hostname, apiHostFlag string) string {
1019 if apiHostFlag != "" {
1020 return apiHostFlag
1021 }
1022 if saved, _ := cfg.Get(hostname, "api_host"); saved != "" {
1023 return saved
1024 }
1025 return hostname
1026}
1028// initialSSHHostname returns the value used to pre-fill the SSH-hostname
1029// prompt. Precedence: a value previously saved for the host, then a value
1030// detected from local git remotes, then the base hostname.
1031func initialSSHHostname(cfg config.Config, hostname string) string {
1032 if saved, _ := cfg.Get(hostname, "ssh_host"); saved != "" {
1033 return saved
1034 }
1035 if detected := detectSSHHost(hostname); detected != "" {
1036 return detected
1037 }
1038 return hostname
1039}
1041// initialContainerRegistryDomains returns the value used to pre-fill the
1042// container-registry-domains prompt, and the value written when the prompt is
1043// skipped. Precedence: the flag, then a value already saved for the host, then
1044// a hostname-derived default. Preferring the saved value over the default keeps
1045// a re-authentication from overwriting domains set with `glab config set`.
1046func initialContainerRegistryDomains(cfg config.Config, hostname, domainsFlag string) string {
1047 if domainsFlag != "" {
1048 return domainsFlag
1049 }
1050 if saved, _ := cfg.Get(hostname, "container_registry_domains"); saved != "" {
1051 return saved
1052 }
1053 return defaultContainerRegistryDomainsString(hostname)
1054}
1056// persistProtocolFlags writes --git-protocol / --api-protocol to config when
1057// their flags are non-empty, regardless of interactivity. Mirrors the
1058// --token / --job-token branches earlier in loginRun so the --web / --device
1059// flows persist the same flags even when stdin isn't a TTY (CI, devcontainer
1060// setup scripts). Values are lowercased to match how the interactive prompt
1061// path normalizes them.
1062func persistProtocolFlags(cfg config.Config, hostname, gitProtocol, apiProtocol string) error {
1063 if gitProtocol != "" {
1064 if err := cfg.Set(hostname, "git_protocol", strings.ToLower(gitProtocol)); err != nil {
1065 return err
1066 }
1067 }
1068 if apiProtocol != "" {
1069 if err := cfg.Set(hostname, "api_protocol", strings.ToLower(apiProtocol)); err != nil {
1070 return err
1071 }
1072 }
1073 return nil
1074}
1076func defaultContainerRegistryDomainsString(hostname string) string {
1077 if !strings.Contains(hostname, ":") {
1078 return strings.Join(
1079 []string{
1080 hostname,
1081 net.JoinHostPort(hostname, "443"),
1082 "registry." + hostname,
1083 }, ",")
1084 }
1086 return hostname + "," + "registry." + hostname
1087}
1089func setContainerRegistryDomains(cfg config.Config, hostname string, domains string) error {
1090 return cfg.Set(hostname, "container_registry_domains", domains)
1091}
1093// promptForSelfHostedInstance prompts the user for hostname, API hostname, and SSH hostname
1094// for a self-hosted GitLab instance. Returns (hostname, apiHostname, sshHostname, error).
1095func promptForSelfHostedInstance(ctx context.Context, opts *LoginOptions) (string, string, string, error) {
1096 hostname := opts.defaultHostname
1098 // Prompt for GitLab hostname
1099 hostnameInput := huh.NewInput().
1100 Title("GitLab hostname:").
1101 Value(&hostname).
1102 Placeholder(opts.defaultHostname).
1103 Validate(func(s string) error {
1104 return hostnameValidator(s)
1105 })
1106 err := opts.IO.Run(ctx, hostnameInput)
1107 if err != nil {
1108 return "", "", "", fmt.Errorf("could not prompt: %w", err)
1109 }
1111 apiHostname := opts.ApiHost
1112 if apiHostname == "" {
1113 apiHostname = hostname
1115 apiHostnameInput := huh.NewInput().
1116 Title("API hostname:").
1117 Description("For instances with a different hostname for the API endpoint.").
1118 Value(&apiHostname).
1119 Placeholder(hostname).
1120 Validate(func(s string) error {
1121 return hostnameValidator(s)
1122 })
1123 if err := opts.IO.Run(ctx, apiHostnameInput); err != nil {
1124 return "", "", "", fmt.Errorf("could not prompt: %w", err)
1125 }
1126 }
1128 sshHostname := opts.SSHHostname
1129 if sshHostname == "" {
1130 sshHostname = hostname
1131 // Try to detect from git remotes as a suggestion
1132 if detectedSSH := detectSSHHost(hostname); detectedSSH != "" {
1133 sshHostname = detectedSSH
1134 }
1136 sshHostnameInput := huh.NewInput().
1137 Title("SSH hostname:").
1138 Description("For instances with a different hostname for SSH git operations.").
1139 Value(&sshHostname).
1140 Placeholder(hostname).
1141 Validate(func(s string) error {
1142 return hostnameValidator(s)
1143 })
1144 if err := opts.IO.Run(ctx, sshHostnameInput); err != nil {
1145 return "", "", "", fmt.Errorf("could not prompt: %w", err)
1146 }
1147 }
1149 return hostname, apiHostname, sshHostname, nil
1150}
1152// splitHostnameAndSubfolder splits a hostname that may contain a subfolder path.
1153// Examples:
1154// - "example.com" → ("example.com", "")
1155// - "example.com/gitlab" → ("example.com", "gitlab")
1156// - "example.com:3000/gitlab" → ("example.com:3000", "gitlab")
1157// - "https://example.com/gitlab" → ("example.com", "gitlab")
1158func splitHostnameAndSubfolder(input string) (string, string) {
1159 // Ensure the input has a scheme for proper URL parsing
1160 if !strings.HasPrefix(input, "http://") && !strings.HasPrefix(input, "https://") {
1161 input = "https://" + input
1162 }
1164 u, err := url.Parse(input)
1165 if err != nil {
1166 // Fallback to string manipulation if parsing fails
1167 input = strings.TrimPrefix(input, "https://")
1168 input = strings.TrimPrefix(input, "http://")
1169 input = strings.TrimSuffix(input, "/")
1170 return glinstance.ExtractSubfolder(input)
1171 }
1173 // Use u.Host to preserve port information (e.g., "example.com:3000")
1174 hostname := u.Host
1175 subfolder := strings.Trim(u.Path, "/")
1177 return hostname, subfolder
1178}
1180// detectSSHHost attempts to detect the SSH hostname from git remotes.
1181// Returns empty string if not found or same as HTTP hostname.
1182func detectSSHHost(httpHostname string) string {
1183 // Check if we're in a git repository
1184 remotes, err := git.Remotes()
1185 if err != nil {
1186 return ""
1187 }
1189 // Look for SSH remotes and extract hostname
1190 // Note: git.ParseURL() already normalizes SCP-style URLs (git@host:path)
1191 // to SSH URLs (ssh://host/path) when remotes are loaded, so the Scheme=="ssh"
1192 // check below catches all SSH remotes regardless of original URL format.
1193 for _, remote := range remotes {
1194 if remote.FetchURL != nil && remote.FetchURL.Scheme == "ssh" {
1195 sshHost := remote.FetchURL.Hostname()
1196 if sshHost != "" && sshHost != httpHostname {
1197 return sshHost
1198 }
1199 }
1200 }
1202 return ""
1203}
Diagnostics8 git calls · 242 ms
CallStatusSizeTime0242 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 KiB2 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=2 git.response.bytes=59849 git.response.cache=UPDATING git.response.duration_ms=2 git.protocol.version=2 git.pkt.frames=731 git.pkt.data=730 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=59849 git.pkt.payload.max=143 git.ls_refs.count=730 git.ls_refs.head=refs/heads/main
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · 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=44Open 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=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=3 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
fetch20011 KiB230 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=230 git.response.bytes=11630 git.response.cache=MISS git.response.duration_ms=230 git.fetch.wants=39eb45d9632ad0f93c085a3dd798d25f5c8c48f1 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=11630 git.pkt.payload.max=11603 git.sideband.band1.bytes=11603 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
- a5e2d8c5cc7714c2
- Request
- 3fbcd53d…
- 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