GitLabgitlab-org
cli
main
1package login
3import (
4 "bufio"
5 "context"
6 "errors"
7 "fmt"
8 "net/url"
9 "slices"
10 "sort"
11 "strings"
13 "github.com/spf13/cobra"
15 "gitlab.com/gitlab-org/cli/internal/api"
16 "gitlab.com/gitlab-org/cli/internal/cmdutils"
17 "gitlab.com/gitlab-org/cli/internal/config"
18 "gitlab.com/gitlab-org/cli/internal/git"
19 "gitlab.com/gitlab-org/cli/internal/glinstance"
20 "gitlab.com/gitlab-org/cli/internal/iostreams"
21 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
22)
24// Any non-blank username is accepted when the password is a personal access
25// token: https://docs.gitlab.com/user/profile/personal_access_tokens/#use-git-over-https
26const personalAccessTokenUsername = "glab"
28type options struct {
29 io *iostreams.IOStreams
30 config func() config.Config
31 apiClient func(repoHost string) (*api.Client, error)
33 operation string
34}
36func NewCmdCredential(f cmdutils.Factory) *cobra.Command {
37 opts := &options{
38 io: f.IO(),
39 config: f.Config,
40 apiClient: f.ApiClient,
41 }
43 cmd := &cobra.Command{
44 Use: "git-credential",
45 Args: cobra.ExactArgs(1),
46 Short: "Implements Git credential helper manager.",
47 Hidden: true,
48 Annotations: map[string]string{
49 mcpannotations.Exclude: "true",
50 },
51 RunE: func(cmd *cobra.Command, args []string) error {
52 opts.complete(args)
54 if err := opts.validate(); err != nil {
55 return err
56 }
58 return opts.run(cmd.Context())
59 },
60 }
62 return cmd
63}
65func (o *options) complete(args []string) {
66 o.operation = args[0]
67}
69func (o *options) validate() error {
70 if o.operation != "get" {
71 // Ignore unsupported operation
72 return cmdutils.SilentError
73 }
74 return nil
75}
77func (o *options) run(ctx context.Context) error {
78 expectedParams := map[string]string{}
80 s := bufio.NewScanner(o.io.In)
81 for s.Scan() {
82 line := s.Text()
83 if line == "" {
84 break
85 }
86 parts := strings.SplitN(line, "=", 2)
87 if len(parts) < 2 {
88 continue
89 }
90 key, value := parts[0], parts[1]
91 if key == "url" {
92 u, err := url.Parse(value)
93 if err != nil {
94 return err
95 }
96 expectedParams["protocol"] = u.Scheme
97 expectedParams["host"] = u.Host
98 expectedParams["path"] = u.Path
99 expectedParams["username"] = u.User.Username()
100 expectedParams["password"], _ = u.User.Password()
101 } else {
102 expectedParams[key] = value
103 }
104 }
105 if err := s.Err(); err != nil {
106 return err
107 }
109 if expectedParams["protocol"] != "https" && expectedParams["protocol"] != "http" {
110 return cmdutils.SilentError
111 }
113 host := expectedParams["host"]
114 apiClient, err := o.apiClient(host)
115 if err != nil {
116 return fmt.Errorf("failed to build the API client for %q: %w", host, err)
117 }
118 cred, err := apiClient.Credential(ctx)
119 if errors.Is(err, api.ErrUnauthenticated) {
120 return cmdutils.SilentError
121 }
122 if err != nil {
123 return fmt.Errorf("failed to resolve the credentials for %q: %w", host, err)
124 }
126 output := map[string]string{"password": cred.Token}
127 switch cred.Kind {
128 case api.CredentialOAuth2:
129 // see https://docs.gitlab.com/api/oauth2/#access-git-over-https-with-access-token
130 output["username"] = "oauth2"
131 if !cred.Expiry.IsZero() {
132 output["password_expiry_utc"] = fmt.Sprintf("%d", cred.Expiry.UTC().Unix())
133 }
134 if cred.RefreshToken != "" {
135 output["oauth_refresh_token"] = cred.RefreshToken
136 }
137 case api.CredentialJobToken:
138 // see https://docs.gitlab.com/ci/jobs/ci_job_token/#to-git-clone-a-private-projects-repository
139 output["username"] = "gitlab-ci-token"
140 case api.CredentialPAT:
141 username, _ := o.config().Get(host, "user")
142 if username == "" {
143 // Legacy configs and failed username lookups leave no user on
144 // record: https://gitlab.com/gitlab-org/cli/-/issues/8044
145 username = personalAccessTokenUsername
146 }
147 output["username"] = username
148 default:
149 return fmt.Errorf("unsupported credential kind %q for %q", cred.Kind, host)
150 }
152 if expectedParams["username"] != "" && expectedParams["username"] != output["username"] {
153 return fmt.Errorf("the requested username by Git doesn't match the one that is configured for this host with GLab, want %q but got %q. Rejecting request", output["username"], expectedParams["username"])
154 }
156 // "A capability[] directive must precede any value depending on it and these directives should be the first item announced in the protocol." https://git-scm.com/docs/git-credential
157 o.io.LogInfo("capability[]=authtype")
158 for key, v := range output {
159 o.io.LogInfof("%s=%s\n", key, v)
160 }
162 return nil
163}
165// detectedHost represents a GitLab hostname detected from git remotes
166type detectedHost struct {
167 hostname string
168 remotes []string // Names of remotes pointing to this host
169 score int // Priority score for sorting
170 authenticated bool // Whether user is already authenticated to this host
171}
173// detectGitLabHosts detects GitLab hostnames from git remotes in the current repository
174func detectGitLabHosts(cfg config.Config) ([]detectedHost, error) {
175 // Check if we're in a git repository
176 _, err := git.ToplevelDir()
177 if err != nil {
178 // Not in a git repo, return empty list
179 return nil, err
180 }
182 // Get git remotes
183 gitRemotes, err := git.Remotes()
184 if err != nil {
185 return nil, err
186 }
188 if len(gitRemotes) == 0 {
189 return nil, nil
190 }
192 // Get authenticated hosts from config
193 var authenticatedHosts map[string]bool
194 if hosts, err := cfg.Hosts(); err == nil {
195 authenticatedHosts = make(map[string]bool, len(hosts))
196 for _, host := range hosts {
197 authenticatedHosts[host] = true
198 }
199 }
201 // Group remotes by hostname
202 // Pre-allocate for maximum possible unique hosts (one per remote)
203 hostMap := make(map[string][]string, len(gitRemotes))
204 for _, remote := range gitRemotes {
205 hostname := extractHostFromRemote(remote)
206 if hostname == "" {
207 // Skip local file remotes (file://, relative paths, etc.)
208 continue
209 }
210 hostMap[hostname] = append(hostMap[hostname], remote.Name)
211 }
213 // Convert to detectedHost slice
214 detectedHosts := make([]detectedHost, 0, len(hostMap))
215 for hostname, remoteNames := range hostMap {
216 host := detectedHost{
217 hostname: hostname,
218 remotes: remoteNames,
219 authenticated: authenticatedHosts[hostname],
220 }
221 detectedHosts = append(detectedHosts, host)
222 }
224 // Prioritize and sort
225 detectedHosts = prioritizeHosts(detectedHosts)
227 return detectedHosts, nil
228}
230// extractHostFromRemote extracts the hostname from a git remote
231func extractHostFromRemote(remote *git.Remote) string {
232 // Try FetchURL first, then PushURL
233 var u *url.URL
234 if remote.FetchURL != nil {
235 u = remote.FetchURL
236 } else if remote.PushURL != nil {
237 u = remote.PushURL
238 }
240 if u == nil {
241 // Both FetchURL and PushURL are nil (shouldn't happen with valid git remotes,
242 // but possible if URL parsing failed in git.parseRemotes)
243 return ""
244 }
246 return u.Host
247}
249// prioritizeHosts sorts detected hosts by priority score
250func prioritizeHosts(hosts []detectedHost) []detectedHost {
251 // Calculate scores
252 for i := range hosts {
253 hosts[i].score = calculateHostScore(&hosts[i])
254 }
256 // Sort by score (descending)
257 sort.Slice(hosts, func(i, j int) bool {
258 return hosts[i].score > hosts[j].score
259 })
261 return hosts
262}
264// calculateHostScore calculates a priority score for a detected host
265func calculateHostScore(host *detectedHost) int {
266 score := 0
268 // Sum scores from all remotes pointing to this host
269 for _, remoteName := range host.remotes {
270 score += remoteNameScore(remoteName)
271 }
273 // Already authenticated hosts get high priority
274 if host.authenticated {
275 score += 10
276 }
278 // gitlab.com gets a boost as the default instance
279 if host.hostname == glinstance.DefaultHostname {
280 score += 5
281 }
283 return score
284}
286// remoteNameScore assigns a priority score based on remote name
287func remoteNameScore(name string) int {
288 switch strings.ToLower(name) {
289 case "origin":
290 return 3
291 case "upstream":
292 return 2
293 case "gitlab":
294 return 1
295 default:
296 return 0
297 }
298}
300// String formats a detected host for display in survey prompt
301func (h detectedHost) String() string {
302 // Handle nil or empty remotes
303 if len(h.remotes) == 0 {
304 if h.authenticated {
305 return fmt.Sprintf("%s [authenticated]", h.hostname)
306 }
307 return h.hostname
308 }
310 // Sort remote names for consistent display
311 remotes := make([]string, len(h.remotes))
312 copy(remotes, h.remotes)
313 slices.Sort(remotes)
315 result := fmt.Sprintf("%s (%s)", h.hostname, strings.Join(remotes, ", "))
316 if h.authenticated {
317 result += " [authenticated]"
318 }
319 return result
320}
Diagnostics8 git calls · 302 ms
CallStatusSizeTime0302 ms
discover200185 B2 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=2 git.response.bytes=185 git.server.agent=git/2.56.g1891de4-Linux git.server.object_format=sha1 git.server.caps=agent ls-refs fetch server-option object-format git.server.fetch=shallow wait-for-done filter git.protocol.version=2 git.pkt.frames=9 git.pkt.data=7 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=185 git.pkt.payload.max=35
ls-refs20058 KiB · hit2 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=2 git.response.bytes=59849 git.response.cache=HIT git.response.duration_ms=2 git.protocol.version=2 git.pkt.frames=731 git.pkt.data=730 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=59849 git.pkt.payload.max=143 git.ls_refs.count=730 git.ls_refs.head=refs/heads/main
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
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: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 · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.bytes=358 git.response.cache=HIT git.response.duration_ms=2 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
fetch2003.0 KiB288 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=288 git.response.bytes=3101 git.response.cache=MISS git.response.duration_ms=288 git.fetch.wants=a150ea819ea8a00c99799714658593a18970c1c0 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=3101 git.pkt.payload.max=3074 git.sideband.band1.bytes=3074 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
- a5e2e45fee472947
- Request
- b53d0397…
- 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