GitLabgitlab-org
cli
main
1//go:build !integration
3package oauth2
5import (
6 "errors"
7 "net/http"
8 "net/http/httptest"
9 "strings"
10 "testing"
12 "github.com/stretchr/testify/assert"
13 "github.com/stretchr/testify/require"
15 "gitlab.com/gitlab-org/cli/internal/config"
16 "gitlab.com/gitlab-org/cli/internal/glinstance"
17)
19func TestClientID(t *testing.T) {
20 testCasesTable := []struct {
21 name string
22 hostname string
23 configClientID string
24 expectedClientID string
25 }{
26 {
27 name: "managed",
28 hostname: glinstance.DefaultHostname,
29 configClientID: "",
30 expectedClientID: glinstance.DefaultClientID,
31 },
32 {
33 name: "self-managed-complete",
34 hostname: "salsa.debian.org",
35 configClientID: "321",
36 expectedClientID: "321",
37 },
38 }
40 for _, testCase := range testCasesTable {
41 t.Run(testCase.name, func(t *testing.T) {
42 cfg := stubConfig{
43 hosts: map[string]map[string]string{
44 testCase.hostname: {
45 "client_id": testCase.configClientID,
46 },
47 },
48 }
49 clientID, err := oauthClientID(cfg, testCase.hostname)
50 require.NoError(t, err)
51 assert.Equal(t, testCase.expectedClientID, clientID)
52 })
53 }
55 t.Run("self-managed with no client_id configured resolves to empty, not an error", func(t *testing.T) {
56 // oauthClientID only looks up what's already configured; deciding what
57 // to do about an empty result (prompt vs. fail) is resolveClientID's
58 // job, tested separately in prompt_test.go.
59 cfg := stubConfig{
60 hosts: map[string]map[string]string{
61 "salsa.debian.org": {},
62 },
63 }
64 clientID, err := oauthClientID(cfg, "salsa.debian.org")
65 require.NoError(t, err)
66 assert.Empty(t, clientID)
67 })
68}
70// A client_id supplied via GITLAB_CLIENT_ID must resolve like a configured
71// value and never reach the interactive prompt. Uses the real config package
72// rather than stubConfig because the env short-circuit lives in
73// fileConfig.Get, not in this package.
74func TestClientID_GITLAB_CLIENT_ID_ShortCircuitsInteractivePrompt(t *testing.T) {
75 validClientID := "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
76 t.Setenv("GITLAB_CLIENT_ID", validClientID)
77 cfg := config.NewBlankConfig()
79 clientID, err := oauthClientID(cfg, "salsa.debian.org")
80 require.NoError(t, err)
81 assert.Equal(t, validClientID, clientID)
83 // A non-interactive io would surface the non-interactive error instead
84 // of the env value if resolveClientID ever reached the prompt.
85 clientID, persist, err := resolveClientID(t.Context(), cfg, newNonInteractiveIOStreams(), "salsa.debian.org")
86 require.NoError(t, err)
87 assert.Equal(t, validClientID, clientID)
88 assert.NoError(t, persist(), "an already-resolved value's persist func must be a no-op")
89}
91func TestOAuthBaseURL(t *testing.T) {
92 t.Parallel()
94 tests := []struct {
95 name string
96 subfolder string
97 expectedURL string
98 }{
99 {
100 name: "nested subfolder",
101 subfolder: "apps/gitlab",
102 expectedURL: "https://gitlab.example.com/apps/gitlab",
103 },
104 {
105 name: "nested subfolder with surrounding slashes",
106 subfolder: "/apps/gitlab/",
107 expectedURL: "https://gitlab.example.com/apps/gitlab",
108 },
109 {
110 name: "no subfolder",
111 expectedURL: "https://gitlab.example.com",
112 },
113 }
115 for _, tt := range tests {
116 t.Run(tt.name, func(t *testing.T) {
117 t.Parallel()
119 cfg := stubConfig{
120 hosts: map[string]map[string]string{
121 "gitlab.example.com": {
122 "subfolder": tt.subfolder,
123 },
124 },
125 }
127 baseURL, err := oauthBaseURL(cfg, "gitlab.example.com", glinstance.DefaultProtocol)
129 require.NoError(t, err)
130 assert.Equal(t, tt.expectedURL, baseURL)
131 })
132 }
133}
135func TestOAuthBaseURLReturnsConfigError(t *testing.T) {
136 t.Parallel()
138 expectedErr := errors.New("read config")
139 cfg := stubConfig{getErr: expectedErr}
141 baseURL, err := oauthBaseURL(cfg, "gitlab.example.com", glinstance.DefaultProtocol)
143 require.ErrorIs(t, err, expectedErr)
144 assert.Empty(t, baseURL)
145}
147func TestResolveClientID_RejectsInvalidConfigClientID(t *testing.T) {
148 tests := []struct {
149 name string
150 clientID string
151 wantErr string
152 }{
153 {
154 name: "personal access token",
155 clientID: "glpat-abcdef1234567890abcdef1234567890abcdef1234567890abcdef123456",
156 wantErr: "value is a personal access token (glpat-), not an OAuth application ID",
157 },
158 {
159 name: "application secret",
160 clientID: "gloas-abcdef1234567890abcdef1234567890abcdef1234567890abcdef123456",
161 wantErr: "value is an OAuth application secret (gloas-), not the Application ID",
162 },
163 }
165 for _, tt := range tests {
166 t.Run(tt.name, func(t *testing.T) {
167 cfg := stubConfig{
168 hosts: map[string]map[string]string{
169 "salsa.debian.org": {
170 "client_id": tt.clientID,
171 },
172 },
173 }
175 clientID, persist, err := resolveClientID(t.Context(), cfg, newNonInteractiveIOStreams(), "salsa.debian.org")
176 require.Error(t, err)
177 assert.Empty(t, clientID)
178 assert.Nil(t, persist)
179 assert.Contains(t, err.Error(), tt.wantErr)
180 })
181 }
182}
184func TestResolveClientID_RejectsNonHexConfigClientID(t *testing.T) {
185 t.Run("configured value", func(t *testing.T) {
186 cfg := stubConfig{
187 hosts: map[string]map[string]string{
188 "salsa.debian.org": {
189 "client_id": " custom-legacy-id \n",
190 },
191 },
192 }
194 clientID, persist, err := resolveClientID(t.Context(), cfg, newNonInteractiveIOStreams(), "salsa.debian.org")
195 require.Error(t, err)
196 assert.Empty(t, clientID)
197 assert.Nil(t, persist)
198 assert.Contains(t, err.Error(), "OAuth application ID must be 64 hexadecimal characters")
199 })
201 t.Run("GITLAB_CLIENT_ID env var", func(t *testing.T) {
202 t.Setenv("GITLAB_CLIENT_ID", "custom-legacy-id")
203 cfg := config.NewBlankConfig()
205 clientID, persist, err := resolveClientID(t.Context(), cfg, newNonInteractiveIOStreams(), "salsa.debian.org")
206 require.Error(t, err)
207 assert.Empty(t, clientID)
208 assert.Nil(t, persist)
209 assert.Contains(t, err.Error(), "OAuth application ID must be 64 hexadecimal characters")
210 })
211}
213func TestPreflightCheckClientID(t *testing.T) {
214 validClientID := "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
216 newTokenServer := func(t *testing.T, status int, contentType, body string) *httptest.Server {
217 t.Helper()
218 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
219 assert.Equal(t, http.MethodPost, r.Method)
220 assert.Equal(t, "/oauth/token", r.URL.Path)
221 assert.NoError(t, r.ParseForm())
222 assert.Equal(t, "authorization_code", r.PostForm.Get("grant_type"))
223 assert.Equal(t, validClientID, r.PostForm.Get("client_id"))
224 assert.Equal(t, redirectURL, r.PostForm.Get("redirect_uri"))
225 assert.False(t, hasIAMPrefix(r.PostForm.Get("code")), "the code must not route the request to IAM")
227 w.Header().Set("Content-Type", contentType)
228 w.WriteHeader(status)
229 _, _ = w.Write([]byte(body))
230 }))
231 t.Cleanup(server.Close)
232 return server
233 }
235 assertRejected := func(t *testing.T, err error, host string) {
236 t.Helper()
237 require.ErrorIs(t, err, ErrClientIDRejected)
238 assert.Contains(t, err.Error(), host)
239 assert.Contains(t, err.Error(), "the application is confidential")
240 assert.Contains(t, err.Error(), "glab config set client_id")
241 assert.Contains(t, err.Error(), "GITLAB_CLIENT_ID")
242 }
244 t.Run("fails fast on 401 invalid_client", func(t *testing.T) {
245 server := newTokenServer(t, http.StatusUnauthorized, "application/json", `{"error":"invalid_client","error_description":"Client authentication failed"}`)
246 host := strings.TrimPrefix(server.URL, "http://")
248 err := preflightCheckClientID(t.Context(), server.Client(), server.URL, validClientID, host)
249 assertRejected(t, err, host)
250 })
252 t.Run("fails fast on 400 invalid_client", func(t *testing.T) {
253 server := newTokenServer(t, http.StatusBadRequest, "application/json", `{"error":"invalid_client"}`)
254 host := strings.TrimPrefix(server.URL, "http://")
256 err := preflightCheckClientID(t.Context(), server.Client(), server.URL, validClientID, host)
257 assertRejected(t, err, host)
258 })
260 t.Run("continues on 400 invalid_grant from a known client", func(t *testing.T) {
261 server := newTokenServer(t, http.StatusBadRequest, "application/json", `{"error":"invalid_grant","error_description":"The provided authorization grant is invalid"}`)
262 host := strings.TrimPrefix(server.URL, "http://")
264 err := preflightCheckClientID(t.Context(), server.Client(), server.URL, validClientID, host)
265 require.NoError(t, err)
266 })
268 t.Run("continues when invalid_client appears only in the description", func(t *testing.T) {
269 server := newTokenServer(t, http.StatusBadRequest, "application/json", `{"error":"invalid_request","error_description":"not an invalid_client"}`)
270 host := strings.TrimPrefix(server.URL, "http://")
272 err := preflightCheckClientID(t.Context(), server.Client(), server.URL, validClientID, host)
273 require.NoError(t, err)
274 })
276 t.Run("continues on a 401 proxy page", func(t *testing.T) {
277 server := newTokenServer(t, http.StatusUnauthorized, "text/html", `<html><body>invalid_client</body></html>`)
278 host := strings.TrimPrefix(server.URL, "http://")
280 err := preflightCheckClientID(t.Context(), server.Client(), server.URL, validClientID, host)
281 require.NoError(t, err)
282 })
284 t.Run("continues on a redirect", func(t *testing.T) {
285 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
286 http.Redirect(w, r, "/users/sign_in", http.StatusFound)
287 }))
288 t.Cleanup(server.Close)
289 host := strings.TrimPrefix(server.URL, "http://")
291 err := preflightCheckClientID(t.Context(), server.Client(), server.URL, validClientID, host)
292 require.NoError(t, err)
293 })
295 t.Run("continues on a server error", func(t *testing.T) {
296 server := newTokenServer(t, http.StatusInternalServerError, "text/plain", "boom")
297 host := strings.TrimPrefix(server.URL, "http://")
299 err := preflightCheckClientID(t.Context(), server.Client(), server.URL, validClientID, host)
300 require.NoError(t, err)
301 })
302}
304func hasIAMPrefix(code string) bool {
305 for _, prefix := range []string{"gliamac-", "gliamat-", "gliamrt-"} {
306 if strings.HasPrefix(code, prefix) {
307 return true
308 }
309 }
310 return false
311}
Diagnostics6 git calls · 452 ms
CallStatusSizeTime0452 ms
discover200185 B4 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.bytes=185 git.server.agent=git/2.56.g1891de4-Linux git.server.object_format=sha1 git.server.caps=agent ls-refs fetch server-option object-format git.server.fetch=shallow wait-for-done filter git.protocol.version=2 git.pkt.frames=9 git.pkt.data=7 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=185 git.pkt.payload.max=35
ls-refs20058 KiB3 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=59849 git.response.cache=UPDATING git.response.duration_ms=3 git.protocol.version=2 git.pkt.frames=731 git.pkt.data=730 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=59849 git.pkt.payload.max=143 git.ls_refs.count=730 git.ls_refs.head=refs/heads/main
fetchtree:0 · deepen 1020032 KiB · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=4 git.response.bytes=32926 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=tree:0 git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9 git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=22 git.pkt.data=20 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=32926 git.pkt.payload.max=32046 git.sideband.band1.bytes=32046 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=80 git.pack.bytes=32046 git.pack.ofs_delta=36 git.pack.ref_delta=0 git.pack.chain.max=2 git.pack.trailer=cb0bad5d7ffc514895d8b21c4dd470327f90bc91 git.pack.full=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=3 git.response.bytes=4273 git.response.cache=HIT git.response.duration_ms=4 git.fetch.filter=combine:blob:none+tree:2 git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9 git.fetch.haves.count=0 git.fetch.deepen=1 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=7 git.pkt.data=5 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=4273 git.pkt.payload.max=4173 git.sideband.band1.bytes=4173 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=11 git.pack.bytes=4173 git.fetch.wide.objects=11 git.fetch.wide.extra_bytes=3930 git.fetch.wide.blobs=0
fetchtree:0200468 B · hit3 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=441 git.response.bytes=468 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=c498f09dbd0cebbc59f9eff3b3ef8be66186fac6 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=468 git.pkt.payload.max=441 git.sideband.band1.bytes=441 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=441 git.pack.trailer=6420a98b3b2e923a6b61c550c00de326d620e479Open pack map
fetch2002.5 KiB441 ms
git.upload-pack fetch http.response.status_code=200 git.response.bytes=2526 git.response.cache=MISS git.response.duration_ms=441 git.fetch.wants=4d5aa339f3ecb02a7b1c79dca34884bee452a2fe 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=2526 git.pkt.payload.max=2499 git.sideband.band1.bytes=2499 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
- a5e22467da3ba87d
- Request
- 8e295ad9…
- 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