GitLabgitlab-org

cli

main
ply6 git calls429 ms98 KiB3 cachedprotocol v2
160 lines5.8 KiBRaw
1package oauth2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "io"
9 "net/http"
10 "net/url"
11 "strings"
12 "time"
14 "golang.org/x/oauth2"
16 "gitlab.com/gitlab-org/api/client-go/v3/gitlaboauth2"
18 "gitlab.com/gitlab-org/cli/internal/config"
19 "gitlab.com/gitlab-org/cli/internal/dbg"
20 "gitlab.com/gitlab-org/cli/internal/glinstance"
21 "gitlab.com/gitlab-org/cli/internal/iostreams"
22 "gitlab.com/gitlab-org/cli/internal/utils"
25// ErrClientIDRejected indicates the OAuth client ID was rejected by the GitLab instance.
26var ErrClientIDRejected = errors.New("OAuth client ID was rejected by the GitLab instance")
28func preflightRejectedClientIDErr(hostname string) error {
29 return fmt.Errorf("%w on %s: the Application ID is unknown, or the application is confidential (glab needs a non-confidential application); update it with `glab config set client_id <client_id> -g --host %s`, clear it with `glab config set client_id \"\" -g --host %s`, or update or unset GITLAB_CLIENT_ID", ErrClientIDRejected, hostname, hostname, hostname)
32// StartFlow performs the OAuth 2.0 Authorization Code flow: it opens a
33// browser (or prints the URL if that fails) and waits for the local
34// callback.
35func StartFlow(ctx context.Context, cfg config.Config, io *iostreams.IOStreams, httpClient *http.Client, hostname string) (string, error) {
36 clientID, persistClientID, err := resolveClientID(ctx, cfg, io, hostname)
37 if err != nil {
38 return "", err
39 }
41 ctx = context.WithValue(ctx, oauth2.HTTPClient, httpClient)
42 baseURL, err := oauthBaseURL(cfg, hostname, glinstance.DefaultProtocol)
43 if err != nil {
44 return "", err
45 }
47 // GitLab.com always uses the built-in ID, so there is nothing to check.
48 if glinstance.IsSelfHosted(hostname) {
49 if err := preflightCheckClientID(ctx, httpClient, baseURL, clientID, hostname); err != nil {
50 return "", err
51 }
52 }
54 token, err := gitlaboauth2.AuthorizationFlow(ctx, baseURL, clientID, redirectURL, scopes, callbackServerListenAddr, func(url string) error {
55 browser, _ := cfg.Get(hostname, "browser")
56 if err := utils.OpenInBrowser(url, browser); err != nil {
57 io.LogErrorf("Failed opening a browser at %s\n", url)
58 io.LogErrorf("Encountered error: %s\n", err)
59 io.LogError("Try entering the URL in your browser manually.")
60 }
61 // A wrong redirect URI or missing scope only shows up in the browser.
62 if glinstance.IsSelfHosted(hostname) {
63 io.LogErrorf("If the browser shows an error instead of returning here, press Ctrl+C and check that the OAuth application on %s has redirect URI %s and the scopes %s.\n", hostname, redirectURL, strings.Join(scopes, " "))
64 }
66 return nil
67 })
68 if err != nil {
69 return "", err
70 }
72 // clientID just completed a real OAuth round trip, so it's proven now:
73 // only commit it to config at this point, not on the paste itself.
74 if err := persistClientID(); err != nil {
75 return "", err
76 }
78 err = marshal(hostname, cfg, token)
79 if err != nil {
80 return "", err
81 }
83 return token.AccessToken, nil
86// preflightCode is a deliberately invalid authorization code. Workhorse sends
87// /oauth/token to the IAM Auth service only for codes with a gliam prefix, so
88// this one always reaches Rails, which knows every application glab can use.
89const preflightCode = "glab-preflight"
91// preflightCheckClientID fails fast on a client ID the instance doesn't know,
92// before the browser opens and the callback wait can hang. It uses the token
93// endpoint because, without the IAM Auth service, /oauth/authorize redirects
94// to sign-in before it checks the client.
95func preflightCheckClientID(ctx context.Context, httpClient *http.Client, baseURL, clientID, hostname string) error {
96 tokenURL := gitlaboauth2.NewOAuth2Config(baseURL, clientID, redirectURL, scopes).Endpoint.TokenURL
97 form := url.Values{
98 "grant_type": {"authorization_code"},
99 "client_id": {clientID},
100 "code": {preflightCode},
101 "redirect_uri": {redirectURL},
102 }
104 req, err := http.NewRequestWithContext(ctx, http.MethodPost, tokenURL, strings.NewReader(form.Encode()))
105 if err != nil {
106 dbg.Debugf("oauth2: preflight request build failed for %s: %v", hostname, err)
107 return nil
108 }
109 req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
111 checkClient := &http.Client{
112 CheckRedirect: func(req *http.Request, via []*http.Request) error {
113 return http.ErrUseLastResponse
114 },
115 Timeout: 5 * time.Second,
116 }
117 if httpClient != nil && httpClient.Transport != nil {
118 checkClient.Transport = httpClient.Transport
119 }
121 resp, err := checkClient.Do(req)
122 if err != nil {
123 dbg.Debugf("oauth2: preflight check request failed for %s: %v", hostname, err)
124 return nil
125 }
126 defer resp.Body.Close()
128 // RFC 6749 section 5.2 allows invalid_client as 400 or 401.
129 if resp.StatusCode != http.StatusBadRequest && resp.StatusCode != http.StatusUnauthorized {
130 dbg.Debugf("oauth2: preflight check received %d on %s, continuing to browser flow", resp.StatusCode, hostname)
131 return nil
132 }
134 var body struct {
135 Error string `json:"error"`
136 }
137 if err := json.NewDecoder(io.LimitReader(resp.Body, 4096)).Decode(&body); err != nil {
138 dbg.Debugf("oauth2: preflight check could not decode %d response on %s: %v", resp.StatusCode, hostname, err)
139 return nil
140 }
141 if body.Error == "invalid_client" {
142 return preflightRejectedClientIDErr(hostname)
143 }
145 dbg.Debugf("oauth2: preflight check received %q on %s, continuing to browser flow", body.Error, hostname)
146 return nil
149// oauthBaseURL is the single place an OAuth base URL is built, so every flow that
150// talks to the instance -- authorization, device, and token refresh -- picks up a
151// configured subfolder. AuthEndpoint falls back to the default protocol when
152// protocol is empty.
153func oauthBaseURL(cfg config.Config, hostname, protocol string) (string, error) {
154 subfolder, err := cfg.Get(hostname, "subfolder")
155 if err != nil {
156 return "", err
157 }
159 return glinstance.AuthEndpoint(hostname, protocol, subfolder), nil
Diagnostics6 git calls · 429 ms
CallStatusSizeTime0429 ms
discover200185 B3 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
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 KiB172 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=172
git.response.bytes=59849
git.response.cache=EXPIRED
git.response.duration_ms=172
git.protocol.version=2
git.pkt.frames=731
git.pkt.data=730
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=59849
git.pkt.payload.max=143
git.ls_refs.count=730
git.ls_refs.head=refs/heads/main
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit4 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=4
git.response.bytes=4273
git.response.cache=HIT
git.response.duration_ms=4
git.fetch.filter=combine:blob:none+tree:2
git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9
git.fetch.haves.count=0
git.fetch.deepen=1
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=7
git.pkt.data=5
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=4273
git.pkt.payload.max=4173
git.sideband.band1.bytes=4173
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=11
git.pack.bytes=4173
git.fetch.wide.objects=11
git.fetch.wide.extra_bytes=3930
git.fetch.wide.blobs=0
fetchtree:0 · deepen 1020032 KiB · 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=32926
git.response.cache=HIT
git.response.duration_ms=4
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
fetchtree:0200468 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=468
git.response.cache=HIT
git.response.duration_ms=2
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=6420a98b3b2e923a6b61c550c00de326d620e479
Open pack map
fetch2002.2 KiB251 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=251
git.response.bytes=2300
git.response.cache=MISS
git.response.duration_ms=251
git.fetch.wants=fc6d7c771d52d47350028eec93acc72a28650156
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=2300
git.pkt.payload.max=2273
git.sideband.band1.bytes=2273
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
a5e9e6b4cd3deefa
Request
98e4b6aa…
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