GitLabgitlab-org

cli

main
ply8 git calls41 ms100 KiB7 cachedprotocol v2
211 lines6.7 KiBRaw
1package credentialhelper
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "strings"
9 "time"
11 "github.com/MakeNowJust/heredoc/v2"
12 "github.com/spf13/cobra"
13 "golang.org/x/oauth2"
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/glrepo"
19 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
22const (
23 errorCodeNotAuthenticated = "not_authenticated"
24 errorCodeUnsupportedAuthSource = "unsupported_auth_source"
25 errorCodeRefreshFailed = "refresh_failed"
26 errorCodeKeyringUnavailable = "keyring_unavailable"
27 errorCodeInvalidRepoOverride = "invalid_repo_override"
28 errorCodeUnknown = "unknown"
31type responseType any
33type errorResponseType struct{}
35func (errorResponseType) MarshalJSON() ([]byte, error) {
36 return []byte(`"error"`), nil
39type successResponseType struct{}
41func (successResponseType) MarshalJSON() ([]byte, error) {
42 return []byte(`"success"`), nil
45type response struct {
46 Type successResponseType `json:"type"` // always evaluates to "success"
47 InstanceURL string `json:"instance_url"`
48 Token token `json:"token"`
51type token struct {
52 Type string `json:"type"`
53 Token string `json:"token"`
54 ExpiryTimestamp time.Time `json:"expiry_timestamp,omitzero"`
57type errorResponse struct {
58 Type errorResponseType `json:"type"` // always evaluates to "error"
59 Code string `json:"code"`
60 Host string `json:"host,omitempty"`
61 OAuthError string `json:"oauth_error,omitempty"`
62 Message string `json:"message"`
65type options struct {
66 baseRepo func() (glrepo.Interface, error)
67 apiClient func(repoHost string) (*api.Client, error)
68 defaultHostname func() string
71func NewCmd(f cmdutils.Factory) *cobra.Command {
72 opts := &options{
73 baseRepo: f.BaseRepo,
74 apiClient: f.ApiClient,
75 defaultHostname: f.DefaultHostname,
76 }
78 writeResponse := func(resp responseType) error {
79 io := f.IO()
80 enc := json.NewEncoder(io.StdOut) //nolint:forbidigo // git credential helper protocol writes JSON to both stdout and stderr; PrintJSON only handles stdout
81 if err := enc.Encode(resp); err != nil {
82 errEnc := json.NewEncoder(io.StdErr) //nolint:forbidigo // git credential helper protocol error response on stderr
83 if err := errEnc.Encode(errorResponse{Code: errorCodeUnknown, Message: err.Error()}); err != nil {
84 return err
85 }
86 return cmdutils.SilentError
87 }
88 return nil
89 }
91 cmd := &cobra.Command{
92 Use: "credential-helper [flags]",
93 Args: cobra.NoArgs,
94 ValidArgsFunction: cobra.NoFileCompletions,
95 Short: "Implements a generic credential helper.",
96 Long: heredoc.Docf(`
97 Outputs a JSON object on stdout with %[1]stype%[1]s set to %[1]ssuccess%[1]s or %[1]serror%[1]s.
99 An %[1]serror%[1]s response always has a %[1]scode%[1]s field. Use it instead of matching on the %[1]smessage%[1]s text, which can change. The codes are:
101 - %[1]snot_authenticated%[1]s: glab has no credentials for the host.
102 - %[1]sunsupported_auth_source%[1]s: the authentication method in use does not provide a token.
103 - %[1]srefresh_failed%[1]s: the OAuth2 token could not be refreshed.
104 - %[1]skeyring_unavailable%[1]s: the operating system keyring could not be read or written.
105 - %[1]sinvalid_repo_override%[1]s: the %[1]s--repo%[1]s flag or the %[1]sGITLAB_REPO%[1]s environment variable is not valid.
106 - %[1]sunknown%[1]s: any other error.
108 An %[1]serror%[1]s response also has %[1]shost%[1]s whenever glab resolved a host, and %[1]soauth_error%[1]s when the OAuth2 server returned an error code such as %[1]sinvalid_grant%[1]s.
110 Callers must parse the JSON response on stdout to detect %[1]stype: "error"%[1]s responses rather than relying on the process exit code, because credential resolution errors exit with status 0 while flag validation errors exit with a non-zero status.
111 `, "`"),
112 Hidden: true,
113 Annotations: map[string]string{
114 mcpannotations.Exclude: "true",
115 },
116 RunE: func(cmd *cobra.Command, args []string) error {
117 resp := opts.run(cmd.Context())
119 return writeResponse(resp)
120 },
121 }
123 cmdutils.EnableRepoOverride(cmd, f)
124 // NOTE: this is a hack to ensure the JSON protocol for the hook that EnableRepoOverride added.
125 repoOverridePersistentPreRunE := cmd.PersistentPreRunE
126 cmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
127 err := repoOverridePersistentPreRunE(cmd, args)
128 if err != nil {
129 _ = writeResponse(errorResponse{
130 Code: errorCodeInvalidRepoOverride,
131 Message: err.Error(),
132 })
133 // We need to signal cobra that we want to error, but that cobra shouldn't log anything else.
134 // This silent error is the way to go here.
135 return cmdutils.SilentError
136 }
137 return nil
138 }
140 return cmd
143func (o *options) run(ctx context.Context) responseType {
144 host := o.defaultHostname()
145 if baseRepo, err := o.baseRepo(); err == nil {
146 host = baseRepo.RepoHost()
147 }
149 apiClient, err := o.apiClient(host)
150 if err != nil {
151 return errorResponse{
152 Code: errorCode(err),
153 Host: host,
154 Message: err.Error(),
155 }
156 }
158 // NOTE: the API client ensures this suffix via glinstance.APIEndpoint().
159 instanceURL := strings.TrimSuffix(apiClient.BaseURL(), "/api/v4/")
161 cred, err := apiClient.Credential(ctx)
162 switch {
163 case errors.Is(err, api.ErrUnauthenticated):
164 return errorResponse{
165 Code: errorCodeNotAuthenticated,
166 Host: host,
167 Message: "glab is not authenticated. Use glab auth login to authenticate",
168 }
169 case errors.Is(err, api.ErrUnsupportedAuthSource):
170 return errorResponse{
171 Code: errorCodeUnsupportedAuthSource,
172 Host: host,
173 Message: "unable to determine token",
174 }
175 case err != nil:
176 var oauthError string
177 if retrieveErr, ok := errors.AsType[*oauth2.RetrieveError](err); ok {
178 oauthError = retrieveErr.ErrorCode
179 }
180 return errorResponse{
181 Code: errorCode(err),
182 Host: host,
183 OAuthError: oauthError,
184 Message: fmt.Sprintf("failed to read the credentials for %q: %v", host, err),
185 }
186 }
188 return response{
189 InstanceURL: instanceURL,
190 Token: token{
191 Type: string(cred.Kind),
192 Token: cred.Token,
193 ExpiryTimestamp: cred.Expiry.UTC(),
194 },
195 }
198func errorCode(err error) string {
199 switch {
200 case errors.Is(err, config.ErrKeyringUnavailable):
201 return errorCodeKeyringUnavailable
202 case errors.Is(err, api.ErrUnauthenticated):
203 return errorCodeNotAuthenticated
204 case errors.Is(err, api.ErrUnsupportedAuthSource):
205 return errorCodeUnsupportedAuthSource
206 case errors.Is(err, api.ErrRefreshFailed):
207 return errorCodeRefreshFailed
208 default:
209 return errorCodeUnknown
210 }
Diagnostics8 git calls · 41 ms
CallStatusSizeTime041 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 · hit3 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=HIT
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
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=44
Open pack map
fetchtree:02001.8 KiB · hit0 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=0
git.response.bytes=1857
git.response.cache=HIT
git.response.duration_ms=0
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 · 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=358
git.response.cache=HIT
git.response.duration_ms=4
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:0200210 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=210
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=fdc25df6aed20e918abcba0c5926ee346b0b6156
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=210
git.pkt.payload.max=183
git.sideband.band1.bytes=183
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=183
git.pack.trailer=de1eb375f226089570c36c780ef053302b0a08a9
Open pack map
fetch2002.4 KiB · hit28 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=28
git.response.bytes=2447
git.response.cache=HIT
git.response.duration_ms=28
git.fetch.wants=94243c2a1c60bc38e4cab25b914d73d6cb25fb86
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=2447
git.pkt.payload.max=2420
git.sideband.band1.bytes=2420
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
a5e2f986297d90c0
Request
167c1c26…
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