GitLabgitlab-org

cli

main
ply8 git calls220 ms101 KiB6 cachedprotocol v2
365 lines13 KiBRaw
1//go:build !integration
3package login
5import (
6 "fmt"
7 "net/http"
8 "net/http/httptest"
9 "net/url"
10 "os/exec"
11 "strings"
12 "testing"
14 "git.sr.ht/~timofurrer/ugh"
15 "github.com/stretchr/testify/assert"
16 "github.com/stretchr/testify/require"
17 "github.com/zalando/go-keyring"
18 "go.uber.org/mock/gomock"
20 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
21 gitlabtesting "gitlab.com/gitlab-org/api/client-go/v3/testing"
23 "gitlab.com/gitlab-org/cli/internal/api"
24 "gitlab.com/gitlab-org/cli/internal/config"
25 "gitlab.com/gitlab-org/cli/internal/oauth2"
26 "gitlab.com/gitlab-org/cli/internal/run"
27 "gitlab.com/gitlab-org/cli/internal/testing/cmdtest"
28 "gitlab.com/gitlab-org/cli/test"
31// recordGitCommands captures the commands a login runs, so the tests assert on
32// the Git configuration glab writes instead of running Git.
33func recordGitCommands(t *testing.T, gitConfig map[string]string) *[][]string {
34 t.Helper()
36 var calls [][]string
37 teardown := run.SetPrepareCmd(func(cmd *exec.Cmd) run.Runnable {
38 calls = append(calls, cmd.Args)
40 // `git config <key>` reads a value: answer from the fake configuration
41 // so the credential helper check sees a realistic host state.
42 if len(cmd.Args) == 3 && cmd.Args[1] == "config" {
43 if value, ok := gitConfig[cmd.Args[2]]; ok {
44 return &test.OutputStub{Out: []byte(value + "\n")}
45 }
46 return &test.OutputStub{Error: &exec.ExitError{}}
47 }
49 // The web login opens the authorization URL in a browser. Stand in for
50 // the user who approves it, so the login receives its callback.
51 if authURL := cmd.Args[len(cmd.Args)-1]; strings.Contains(authURL, "/oauth/authorize?") {
52 approveAuthorization(t, authURL)
53 }
54 return &test.OutputStub{}
55 })
56 t.Cleanup(teardown)
58 return &calls
61func approveAuthorization(t *testing.T, authURL string) {
62 t.Helper()
64 u, err := url.Parse(authURL)
65 require.NoError(t, err)
66 query := u.Query()
68 callback := fmt.Sprintf("%s?code=test-code&state=%s", query.Get("redirect_uri"), url.QueryEscape(query.Get("state")))
69 req, err := http.NewRequestWithContext(t.Context(), http.MethodGet, callback, http.NoBody)
70 require.NoError(t, err)
72 resp, err := http.DefaultClient.Do(req)
73 require.NoError(t, err)
74 require.NoError(t, resp.Body.Close())
77// newOAuthServer stands in for the OAuth endpoints of a GitLab instance, for
78// the --web and --device logins.
79func newOAuthServer(t *testing.T) *httptest.Server {
80 t.Helper()
82 srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
83 w.Header().Set("Content-Type", "application/json")
84 switch r.URL.Path {
85 case "/oauth/authorize_device":
86 fmt.Fprint(w, `{"device_code":"device-code","user_code":"ABCD-EFGH","verification_uri":"https://gitlab.example.com/oauth/device","expires_in":300,"interval":1}`)
87 case "/oauth/token":
88 fmt.Fprint(w, `{"access_token":"oauth-token","token_type":"bearer","expires_in":7200,"refresh_token":"refresh-token"}`)
89 default:
90 http.NotFound(w, r)
91 }
92 }))
93 t.Cleanup(srv.Close)
95 return srv
98// oauthLoginExec runs `glab auth login` against srv. As a self-managed
99// instance, srv needs a client_id, and the OAuth client must accept its
100// test certificate.
101func oauthLoginExec(t *testing.T, srv *httptest.Server) (cmdtest.CmdExecFunc, string) {
102 t.Helper()
104 hostname := srv.Listener.Addr().String()
106 tc := gitlabtesting.NewTestClient(t)
107 tc.MockUsers.EXPECT().
108 CurrentUser(gomock.Any()).
109 Return(&gitlab.User{Username: "john_smith"}, nil, nil).
110 AnyTimes()
112 cfg := config.NewBlankConfigInDir(t.TempDir())
113 require.NoError(t, cfg.Set(hostname, "client_id", "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"))
114 require.NoError(t, cfg.Set(hostname, "skip_tls_verify", "true"))
116 return loginExec(t, false,
117 cmdtest.WithConfig(cfg),
118 cmdtest.WithApiClient(cmdtest.NewTestApiClient(t, srv.Client(), "", hostname, api.WithGitLabClient(tc.Client))),
119 ), hostname
122func loginExec(t *testing.T, isTTY bool, opts ...cmdtest.FactoryOption) cmdtest.CmdExecFunc {
123 t.Helper()
124 t.Setenv("GLAB_CONFIG_DIR", t.TempDir())
126 opts = append([]cmdtest.FactoryOption{cmdtest.WithConfig(config.NewBlankConfigInDir(t.TempDir()))}, opts...)
127 return cmdtest.SetupCmdForTest(t, NewCmdLogin, isTTY, opts...)
130// findCall returns the first recorded invocation that contains every fragment.
131func findCall(calls [][]string, fragments ...string) []string {
132 for _, call := range calls {
133 joined := strings.Join(call, " ")
134 matched := true
135 for _, fragment := range fragments {
136 if !strings.Contains(joined, fragment) {
137 matched = false
138 break
139 }
140 }
141 if matched {
142 return call
143 }
144 }
145 return nil
148func countCalls(calls [][]string, fragments ...string) int {
149 count := 0
150 for _, call := range calls {
151 if findCall([][]string{call}, fragments...) != nil {
152 count++
153 }
154 }
155 return count
158func Test_gitCredentialProtocol(t *testing.T) {
159 tests := []struct {
160 name string
161 gitProtocol string
162 want string
163 }{
164 {name: "empty defaults to https", gitProtocol: "", want: "https"},
165 {name: "https stays https", gitProtocol: "https", want: "https"},
166 {name: "http is preserved", gitProtocol: "http", want: "http"},
167 {name: "uppercase http is preserved", gitProtocol: "HTTP", want: "http"},
168 // A credential helper never applies to SSH remotes, so HTTPS is the
169 // only protocol worth configuring for an SSH preference.
170 {name: "ssh falls back to https", gitProtocol: "ssh", want: "https"},
171 }
173 for _, tt := range tests {
174 t.Run(tt.name, func(t *testing.T) {
175 assert.Equal(t, tt.want, gitCredentialProtocol(tt.gitProtocol))
176 })
177 }
180func Test_tokenLogin_setupGitCredentialHelper(t *testing.T) {
181 keyring.MockInit()
183 t.Run("configures glab as the helper for the host", func(t *testing.T) {
184 calls := recordGitCommands(t, nil)
186 _, err := loginExec(t, false, currentUserFactoryOption(t))(
187 "--hostname gitlab.com --token glpat-1234 --setup-git-credential-helper")
188 require.NoError(t, err)
190 key := "credential.https://gitlab.com.helper"
191 assert.Equal(t,
192 []string{"git", "config", "--global", "--replace-all", key, ""},
193 findCall(*calls, "config", "--global", "--replace-all", key))
195 add := findCall(*calls, "config", "--global", "--add", key)
196 require.NotNil(t, add, "glab should be added as the helper")
197 assert.Contains(t, strings.Join(add, " "), "auth git-credential")
198 })
200 t.Run("honors --git-protocol http", func(t *testing.T) {
201 calls := recordGitCommands(t, nil)
203 _, err := loginExec(t, false, currentUserFactoryOption(t))(
204 "--hostname gitlab.example.com --token glpat-1234 --git-protocol http --setup-git-credential-helper")
205 require.NoError(t, err)
207 assert.NotNil(t, findCall(*calls, "--add", "credential.http://gitlab.example.com.helper"))
208 })
210 t.Run("leaves a host that already uses glab alone", func(t *testing.T) {
211 calls := recordGitCommands(t, map[string]string{
212 "credential.https://gitlab.com.helper": "!/usr/bin/glab auth git-credential",
213 })
215 _, err := loginExec(t, false, currentUserFactoryOption(t))(
216 "--hostname gitlab.com --token glpat-1234 --setup-git-credential-helper")
217 require.NoError(t, err)
219 assert.Nil(t, findCall(*calls, "config", "--global"),
220 "an existing glab helper should not be configured again")
221 })
223 t.Run("writes nothing without the flag", func(t *testing.T) {
224 calls := recordGitCommands(t, nil)
226 _, err := loginExec(t, false, currentUserFactoryOption(t))(
227 "--hostname gitlab.com --token glpat-1234")
228 require.NoError(t, err)
230 assert.Nil(t, findCall(*calls, "credential.https://gitlab.com.helper"))
231 })
234func Test_stdinLogin_setupGitCredentialHelper(t *testing.T) {
235 keyring.MockInit()
236 calls := recordGitCommands(t, nil)
238 _, err := loginExec(t, false, currentUserFactoryOption(t), cmdtest.WithStdin("glpat-1234\n"))(
239 "--hostname gitlab.com --stdin --setup-git-credential-helper")
240 require.NoError(t, err)
242 assert.NotNil(t, findCall(*calls, "config", "--global", "--add", "credential.https://gitlab.com.helper"))
245// A job token cannot identify a person, but Git still needs to authenticate.
246func Test_jobTokenLogin_setupGitCredentialHelper(t *testing.T) {
247 keyring.MockInit()
248 calls := recordGitCommands(t, nil)
250 _, err := loginExec(t, false, currentUserFactoryOption(t))(
251 "--hostname gitlab.com --job-token job-token-1234 --setup-git-credential-helper")
252 require.NoError(t, err)
254 assert.NotNil(t, findCall(*calls, "config", "--global", "--add", "credential.https://gitlab.com.helper"))
257func Test_webLogin_setupGitCredentialHelper(t *testing.T) {
258 keyring.MockInit()
259 calls := recordGitCommands(t, nil)
261 execLogin, hostname := oauthLoginExec(t, newOAuthServer(t))
262 _, err := execLogin("--hostname " + hostname + " --web --setup-git-credential-helper")
263 require.NoError(t, err)
265 assert.NotNil(t, findCall(*calls, "config", "--global", "--add", "credential.https://"+hostname+".helper"))
268func Test_webLogin_selfManagedPrintsClientIDHint(t *testing.T) {
269 keyring.MockInit()
270 recordGitCommands(t, nil)
272 execLogin, hostname := oauthLoginExec(t, newOAuthServer(t))
273 out, err := execLogin("--hostname " + hostname + " --web")
274 require.NoError(t, err)
276 assert.Contains(t, out.ErrBuf.String(), "press Ctrl+C and check that the OAuth application on "+hostname+" has redirect URI http://localhost:7171/auth/redirect")
279func Test_webLogin_rejectedClientIDStopsBeforeBrowser(t *testing.T) {
280 keyring.MockInit()
281 calls := recordGitCommands(t, nil)
283 srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
284 if r.URL.Path != "/oauth/token" {
285 http.NotFound(w, r)
286 return
287 }
288 w.Header().Set("Content-Type", "application/json")
289 w.WriteHeader(http.StatusUnauthorized)
290 fmt.Fprint(w, `{"error":"invalid_client"}`)
291 }))
292 t.Cleanup(srv.Close)
294 execLogin, hostname := oauthLoginExec(t, srv)
295 _, err := execLogin("--hostname " + hostname + " --web")
297 require.ErrorIs(t, err, oauth2.ErrClientIDRejected)
298 assert.Nil(t, findCall(*calls, "/oauth/authorize?"), "the browser must not open for a rejected client ID")
301func Test_deviceLogin_setupGitCredentialHelper(t *testing.T) {
302 keyring.MockInit()
304 t.Run("configures glab as the helper for the host", func(t *testing.T) {
305 calls := recordGitCommands(t, nil)
307 execLogin, hostname := oauthLoginExec(t, newOAuthServer(t))
308 _, err := execLogin("--hostname " + hostname + " --device --setup-git-credential-helper")
309 require.NoError(t, err)
311 assert.NotNil(t, findCall(*calls, "config", "--global", "--add", "credential.https://"+hostname+".helper"))
312 })
314 t.Run("honors --git-protocol http", func(t *testing.T) {
315 calls := recordGitCommands(t, nil)
317 execLogin, hostname := oauthLoginExec(t, newOAuthServer(t))
318 _, err := execLogin("--hostname " + hostname + " --device --git-protocol http --setup-git-credential-helper")
319 require.NoError(t, err)
321 assert.NotNil(t, findCall(*calls, "config", "--global", "--add", "credential.http://"+hostname+".helper"))
322 })
325func Test_interactiveLogin_setupGitCredentialHelper(t *testing.T) {
326 // Every other prompt is answered by a flag, so the console only has to
327 // pick the token login and paste the token.
328 const args = "--hostname gitlab.com --git-protocol https --container-registry-domains gitlab.com"
330 t.Run("the flag configures glab without asking", func(t *testing.T) {
331 // A token left in the keyring by another test would add the
332 // re-authentication prompt.
333 keyring.MockInit()
335 // Another helper is configured, which is the case where answering the
336 // prompt would only store the token in that helper.
337 calls := recordGitCommands(t, map[string]string{"credential.helper": "store"})
339 console := ugh.New(t)
340 console.Expect(ugh.Select("How would you like to sign in?")).Do(ugh.SelectOption(promptLoginTypeToken))
341 console.Expect(ugh.Input("Paste your authentication token:")).Do(ugh.Type("glpat-1234"))
343 _, err := loginExec(t, true, currentUserFactoryOption(t), cmdtest.WithConsole(t, console))(
344 args + " --setup-git-credential-helper")
345 require.NoError(t, err)
347 assert.Equal(t, 1, countCalls(*calls, "config", "--global", "--add", "credential.https://gitlab.com.helper"))
348 assert.Nil(t, findCall(*calls, "credential", "approve"))
349 })
351 t.Run("answering yes configures glab", func(t *testing.T) {
352 keyring.MockInit()
353 calls := recordGitCommands(t, nil)
355 console := ugh.New(t)
356 console.Expect(ugh.Select("How would you like to sign in?")).Do(ugh.SelectOption(promptLoginTypeToken))
357 console.Expect(ugh.Input("Paste your authentication token:")).Do(ugh.Type("glpat-1234"))
358 console.Expect(ugh.Confirm("Authenticate Git with your GitLab credentials?")).Do(ugh.Affirm)
360 _, err := loginExec(t, true, currentUserFactoryOption(t), cmdtest.WithConsole(t, console))(args)
361 require.NoError(t, err)
363 assert.Equal(t, 1, countCalls(*calls, "config", "--global", "--add", "credential.https://gitlab.com.helper"))
364 })
Diagnostics8 git calls · 220 ms
CallStatusSizeTime0220 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=44
Open pack map
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit4 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=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=fb03183b7909876778f740d196d7516811003517
Open 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=22a484e5ecad6d6e62b224e8a7f90cf5ff085938
Open 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=f67b2cbb934192bc54c7c67883cb789a9f00fa4a
Open pack map
fetch2003.6 KiB206 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=206
git.response.bytes=3704
git.response.cache=MISS
git.response.duration_ms=206
git.fetch.wants=eeed387e6ac8465140949c45b4acc3108d0f8070
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=3704
git.pkt.payload.max=3677
git.sideband.band1.bytes=3677
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
a5e29b1ecc70c465
Request
bff6f8b8…
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