Debian Codegraph @

plumbing/transport/http/common.go

raw
1 // Package http implements the HTTP transport protocol.
2 package http
3
4 import (
5 "bytes"
6 "context"
7 "crypto/tls"
8 "crypto/x509"
9 "fmt"
10 "net/http"
11 "net/url"
12 "reflect"
13 "strconv"
14 "strings"
15 "sync"
16
17 "github.com/golang/groupcache/lru"
18
19 "github.com/go-git/go-git/v5/plumbing"
20 "github.com/go-git/go-git/v5/plumbing/protocol/packp"
21 "github.com/go-git/go-git/v5/plumbing/protocol/packp/capability"
22 "github.com/go-git/go-git/v5/plumbing/transport"
23 "github.com/go-git/go-git/v5/utils/ioutil"
24 )
25
26 type contextKey int
27
28 const initialRequestKey contextKey = iota
29
30 // RedirectPolicy controls how the HTTP transport follows redirects.
31 //
32 // The values mirror Git's http.followRedirects config:
33 // "true" follows redirects for all requests, "false" treats redirects as
34 // errors, and "initial" follows redirects only for the initial
35 // /info/refs discovery request. The zero value defaults to "initial".
36 type RedirectPolicy string
37
38 const (
39 FollowInitialRedirects RedirectPolicy = "initial"
40 FollowRedirects RedirectPolicy = "true"
41 NoFollowRedirects RedirectPolicy = "false"
42 )
43
44 func withInitialRequest(ctx context.Context) context.Context {
45 return context.WithValue(ctx, initialRequestKey, true)
46 }
47
48 func isInitialRequest(req *http.Request) bool {
49 v, _ := req.Context().Value(initialRequestKey).(bool)
50 return v
51 }
52
53 // it requires a bytes.Buffer, because we need to know the length
54 func applyHeadersToRequest(req *http.Request, content *bytes.Buffer, host string, requestType string) {
55 req.Header.Add("User-Agent", capability.DefaultAgent())
56 req.Header.Add("Host", host) // host:port
57
58 if content == nil {
59 req.Header.Add("Accept", "*/*")
60 return
61 }
62
63 req.Header.Add("Accept", fmt.Sprintf("application/x-%s-result", requestType))
64 req.Header.Add("Content-Type", fmt.Sprintf("application/x-%s-request", requestType))
65 req.Header.Add("Content-Length", strconv.Itoa(content.Len()))
66 }
67
68 const infoRefsPath = "/info/refs"
69
70 func advertisedReferences(ctx context.Context, s *session, serviceName string) (ref *packp.AdvRefs, err error) {
71 url := fmt.Sprintf(
72 "%s%s?service=%s",
73 s.endpoint.String(), infoRefsPath, serviceName,
74 )
75
76 req, err := http.NewRequest(http.MethodGet, url, nil)
77 if err != nil {
78 return nil, err
79 }
80
81 s.ApplyAuthToRequest(req)
82 applyHeadersToRequest(req, nil, s.endpoint.Host, serviceName)
83 res, err := s.client.Do(req.WithContext(withInitialRequest(ctx)))
84 if err != nil {
85 return nil, err
86 }
87
88 if err := s.ModifyEndpointIfRedirect(res); err != nil {
89 _ = res.Body.Close()
90 return nil, err
91 }
92 defer ioutil.CheckClose(res.Body, &err)
93
94 if err = NewErr(res); err != nil {
95 return nil, err
96 }
97
98 ar := packp.NewAdvRefs()
99 if err = ar.Decode(res.Body); err != nil {
100 if err == packp.ErrEmptyAdvRefs {
101 err = transport.ErrEmptyRemoteRepository
102 }
103
104 return nil, err
105 }
106
107 // Git 2.41+ returns a zero-id plus capabilities when an empty
108 // repository is being cloned. This skips the existing logic within
109 // advrefs_decode.decodeFirstHash, which expects a flush-pkt instead.
110 //
111 // This logic aligns with plumbing/transport/internal/common/common.go.
112 if ar.IsEmpty() &&
113 // Empty repositories are valid for git-receive-pack.
114 transport.ReceivePackServiceName != serviceName {
115 return nil, transport.ErrEmptyRemoteRepository
116 }
117
118 transport.FilterUnsupportedCapabilities(ar.Capabilities)
119 s.advRefs = ar
120
121 return ar, nil
122 }
123
124 type client struct {
125 client *http.Client
126 transports *lru.Cache
127 mutex sync.RWMutex
128 follow RedirectPolicy
129 }
130
131 // ClientOptions holds user configurable options for the client.
132 type ClientOptions struct {
133 // CacheMaxEntries is the max no. of entries that the transport objects
134 // cache will hold at any given point of time. It must be a positive integer.
135 // Calling `client.addTransport()` after the cache has reached the specified
136 // size, will result in the least recently used transport getting deleted
137 // before the provided transport is added to the cache.
138 CacheMaxEntries int
139
140 // RedirectPolicy controls redirect handling. Supported values are
141 // "true", "false", and "initial". The zero value defaults to
142 // "initial", matching Git's http.followRedirects default.
143 RedirectPolicy RedirectPolicy
144 }
145
146 var (
147 // defaultTransportCacheSize is the default capacity of the transport objects cache.
148 // Its value is 0 because transport caching is turned off by default and is an
149 // opt-in feature.
150 defaultTransportCacheSize = 0
151
152 // DefaultClient is the default HTTP client, which uses a net/http client configured
153 // with http.DefaultTransport.
154 DefaultClient = NewClient(nil)
155 )
156
157 // NewClient creates a new client with a custom net/http client.
158 // See `InstallProtocol` to install and override default http client.
159 // If the net/http client is nil or empty, it will use a net/http client configured
160 // with http.DefaultTransport.
161 //
162 // Note that for HTTP client cannot distinguish between private repositories and
163 // unexistent repositories on GitHub. So it returns `ErrAuthorizationRequired`
164 // for both.
165 func NewClient(c *http.Client) transport.Transport {
166 if c == nil {
167 c = &http.Client{
168 Transport: http.DefaultTransport,
169 }
170 }
171 return NewClientWithOptions(c, &ClientOptions{
172 CacheMaxEntries: defaultTransportCacheSize,
173 })
174 }
175
176 // NewClientWithOptions returns a new client configured with the provided net/http client
177 // and other custom options specific to the client.
178 // If the net/http client is nil or empty, it will use a net/http client configured
179 // with http.DefaultTransport.
180 func NewClientWithOptions(c *http.Client, opts *ClientOptions) transport.Transport {
181 if c == nil {
182 c = &http.Client{
183 Transport: http.DefaultTransport,
184 }
185 }
186 cl := &client{
187 client: c,
188 follow: FollowInitialRedirects,
189 }
190
191 if opts != nil {
192 if opts.CacheMaxEntries > 0 {
193 cl.transports = lru.New(opts.CacheMaxEntries)
194 }
195 if opts.RedirectPolicy != "" {
196 cl.follow = opts.RedirectPolicy
197 }
198 }
199 return cl
200 }
201
202 func (c *client) NewUploadPackSession(ep *transport.Endpoint, auth transport.AuthMethod) (
203 transport.UploadPackSession, error) {
204
205 return newUploadPackSession(c, ep, auth)
206 }
207
208 func (c *client) NewReceivePackSession(ep *transport.Endpoint, auth transport.AuthMethod) (
209 transport.ReceivePackSession, error) {
210
211 return newReceivePackSession(c, ep, auth)
212 }
213
214 type session struct {
215 auth AuthMethod
216 client *http.Client
217 endpoint *transport.Endpoint
218 advRefs *packp.AdvRefs
219 }
220
221 func transportWithInsecureTLS(transport *http.Transport) {
222 if transport.TLSClientConfig == nil {
223 transport.TLSClientConfig = &tls.Config{}
224 }
225 transport.TLSClientConfig.InsecureSkipVerify = true
226 }
227
228 func transportWithClientCert(transport *http.Transport, cert, key []byte) error {
229 keyPair, err := tls.X509KeyPair(cert, key)
230 if err != nil {
231 return err
232 }
233 if transport.TLSClientConfig == nil {
234 transport.TLSClientConfig = &tls.Config{}
235 }
236 transport.TLSClientConfig.Certificates = []tls.Certificate{keyPair}
237 return nil
238 }
239
240 func transportWithCABundle(transport *http.Transport, caBundle []byte) error {
241 rootCAs, err := x509.SystemCertPool()
242 if err != nil {
243 return err
244 }
245 if rootCAs == nil {
246 rootCAs = x509.NewCertPool()
247 }
248 rootCAs.AppendCertsFromPEM(caBundle)
249 if transport.TLSClientConfig == nil {
250 transport.TLSClientConfig = &tls.Config{}
251 }
252 transport.TLSClientConfig.RootCAs = rootCAs
253 return nil
254 }
255
256 func transportWithProxy(transport *http.Transport, proxyURL *url.URL) {
257 transport.Proxy = http.ProxyURL(proxyURL)
258 }
259
260 func configureTransport(transport *http.Transport, ep *transport.Endpoint) error {
261 if len(ep.ClientCert) > 0 && len(ep.ClientKey) > 0 {
262 if err := transportWithClientCert(transport, ep.ClientCert, ep.ClientKey); err != nil {
263 return err
264 }
265 }
266 if len(ep.CaBundle) > 0 {
267 if err := transportWithCABundle(transport, ep.CaBundle); err != nil {
268 return err
269 }
270 }
271 if ep.InsecureSkipTLS {
272 transportWithInsecureTLS(transport)
273 }
274
275 if ep.Proxy.URL != "" {
276 proxyURL, err := ep.Proxy.FullURL()
277 if err != nil {
278 return err
279 }
280 transportWithProxy(transport, proxyURL)
281 }
282 return nil
283 }
284
285 func newSession(c *client, ep *transport.Endpoint, auth transport.AuthMethod) (*session, error) {
286 var httpClient *http.Client
287
288 // We need to configure the http transport if there are transport specific
289 // options present in the endpoint.
290 if len(ep.ClientKey) > 0 || len(ep.ClientCert) > 0 || len(ep.CaBundle) > 0 || ep.InsecureSkipTLS || ep.Proxy.URL != "" {
291 var transport *http.Transport
292 // if the client wasn't configured to have a cache for transports then just configure
293 // the transport and use it directly, otherwise try to use the cache.
294 if c.transports == nil {
295 tr, ok := c.client.Transport.(*http.Transport)
296 if !ok {
297 return nil, fmt.Errorf("expected underlying client transport to be of type: %s; got: %s",
298 reflect.TypeOf(transport), reflect.TypeOf(c.client.Transport))
299 }
300
301 transport = tr.Clone()
302 if err := configureTransport(transport, ep); err != nil {
303 return nil, err
304 }
305 } else {
306 transportOpts := transportOptions{
307 clientCert: string(ep.ClientCert),
308 clientKey: string(ep.ClientKey),
309 caBundle: string(ep.CaBundle),
310 insecureSkipTLS: ep.InsecureSkipTLS,
311 }
312 if ep.Proxy.URL != "" {
313 proxyURL, err := ep.Proxy.FullURL()
314 if err != nil {
315 return nil, err
316 }
317 transportOpts.proxyURL = *proxyURL
318 }
319 var found bool
320 transport, found = c.fetchTransport(transportOpts)
321
322 if !found {
323 transport = c.client.Transport.(*http.Transport).Clone()
324 if err := configureTransport(transport, ep); err != nil {
325 return nil, err
326 }
327 c.addTransport(transportOpts, transport)
328 }
329 }
330
331 httpClient = c.cloneHTTPClient(transport)
332 } else {
333 httpClient = c.cloneHTTPClient(c.client.Transport)
334 }
335
336 s := &session{
337 auth: basicAuthFromEndpoint(ep),
338 client: httpClient,
339 endpoint: ep,
340 }
341 if auth != nil {
342 a, ok := auth.(AuthMethod)
343 if !ok {
344 return nil, transport.ErrInvalidAuthMethod
345 }
346
347 s.auth = a
348 }
349
350 return s, nil
351 }
352
353 func (s *session) ApplyAuthToRequest(req *http.Request) {
354 if s.auth == nil {
355 return
356 }
357
358 s.auth.SetAuth(req)
359 }
360
361 func (s *session) ModifyEndpointIfRedirect(res *http.Response) error {
362 if res.Request == nil {
363 return nil
364 }
365 if s.endpoint == nil {
366 return fmt.Errorf("http redirect: nil endpoint")
367 }
368
369 r := res.Request
370 if !strings.HasSuffix(r.URL.Path, infoRefsPath) {
371 return fmt.Errorf("http redirect: target %q does not end with %s", r.URL.Path, infoRefsPath)
372 }
373 if r.URL.Scheme != "http" && r.URL.Scheme != "https" {
374 return fmt.Errorf("http redirect: unsupported scheme %q", r.URL.Scheme)
375 }
376 if r.URL.Scheme != s.endpoint.Protocol &&
377 !(s.endpoint.Protocol == "http" && r.URL.Scheme == "https") {
378 return fmt.Errorf("http redirect: changes scheme from %q to %q", s.endpoint.Protocol, r.URL.Scheme)
379 }
380
381 host := endpointHost(r.URL.Hostname())
382 port, err := endpointPort(r.URL.Port())
383 if err != nil {
384 return err
385 }
386
387 if host != s.endpoint.Host || effectivePort(r.URL.Scheme, port) != effectivePort(s.endpoint.Protocol, s.endpoint.Port) {
388 s.endpoint.User = ""
389 s.endpoint.Password = ""
390 s.auth = nil
391 }
392
393 s.endpoint.Host = host
394 s.endpoint.Port = port
395
396 s.endpoint.Protocol = r.URL.Scheme
397 s.endpoint.Path = r.URL.Path[:len(r.URL.Path)-len(infoRefsPath)]
398 return nil
399 }
400
401 func endpointHost(host string) string {
402 if strings.Contains(host, ":") {
403 return "[" + host + "]"
404 }
405
406 return host
407 }
408
409 func endpointPort(port string) (int, error) {
410 if port == "" {
411 return 0, nil
412 }
413
414 parsed, err := strconv.Atoi(port)
415 if err != nil {
416 return 0, fmt.Errorf("http redirect: invalid port %q", port)
417 }
418
419 return parsed, nil
420 }
421
422 func effectivePort(scheme string, port int) int {
423 if port != 0 {
424 return port
425 }
426
427 switch strings.ToLower(scheme) {
428 case "http":
429 return 80
430 case "https":
431 return 443
432 default:
433 return 0
434 }
435 }
436
437 func (c *client) cloneHTTPClient(transport http.RoundTripper) *http.Client {
438 return &http.Client{
439 Transport: transport,
440 CheckRedirect: wrapCheckRedirect(c.follow, c.client.CheckRedirect),
441 Jar: c.client.Jar,
442 Timeout: c.client.Timeout,
443 }
444 }
445
446 func wrapCheckRedirect(policy RedirectPolicy, next func(*http.Request, []*http.Request) error) func(*http.Request, []*http.Request) error {
447 return func(req *http.Request, via []*http.Request) error {
448 if err := checkRedirect(req, via, policy); err != nil {
449 return err
450 }
451 if next != nil {
452 return next(req, via)
453 }
454 return nil
455 }
456 }
457
458 func checkRedirect(req *http.Request, via []*http.Request, policy RedirectPolicy) error {
459 switch policy {
460 case FollowRedirects:
461 case NoFollowRedirects:
462 return fmt.Errorf("http redirect: redirects disabled to %s", req.URL)
463 case "", FollowInitialRedirects:
464 if !isInitialRequest(req) {
465 return fmt.Errorf("http redirect: redirect on non-initial request to %s", req.URL)
466 }
467 default:
468 return fmt.Errorf("http redirect: invalid redirect policy %q", policy)
469 }
470 if req.URL.Scheme != "http" && req.URL.Scheme != "https" {
471 return fmt.Errorf("http redirect: unsupported scheme %q", req.URL.Scheme)
472 }
473 if len(via) >= 10 {
474 return fmt.Errorf("http redirect: too many redirects")
475 }
476 return nil
477 }
478
479 func (*session) Close() error {
480 return nil
481 }
482
483 // AuthMethod is concrete implementation of common.AuthMethod for HTTP services
484 type AuthMethod interface {
485 transport.AuthMethod
486 SetAuth(r *http.Request)
487 }
488
489 func basicAuthFromEndpoint(ep *transport.Endpoint) *BasicAuth {
490 u := ep.User
491 if u == "" {
492 return nil
493 }
494
495 return &BasicAuth{u, ep.Password}
496 }
497
498 // BasicAuth represent a HTTP basic auth
499 type BasicAuth struct {
500 Username, Password string
501 }
502
503 func (a *BasicAuth) SetAuth(r *http.Request) {
504 if a == nil {
505 return
506 }
507
508 r.SetBasicAuth(a.Username, a.Password)
509 }
510
511 // Name is name of the auth
512 func (a *BasicAuth) Name() string {
513 return "http-basic-auth"
514 }
515
516 func (a *BasicAuth) String() string {
517 masked := "*******"
518 if a.Password == "" {
519 masked = "<empty>"
520 }
521
522 return fmt.Sprintf("%s - %s:%s", a.Name(), a.Username, masked)
523 }
524
525 // TokenAuth implements an http.AuthMethod that can be used with http transport
526 // to authenticate with HTTP token authentication (also known as bearer
527 // authentication).
528 //
529 // IMPORTANT: If you are looking to use OAuth tokens with popular servers (e.g.
530 // GitHub, Bitbucket, GitLab) you should use BasicAuth instead. These servers
531 // use basic HTTP authentication, with the OAuth token as user or password.
532 // Check the documentation of your git server for details.
533 type TokenAuth struct {
534 Token string
535 }
536
537 func (a *TokenAuth) SetAuth(r *http.Request) {
538 if a == nil {
539 return
540 }
541 r.Header.Add("Authorization", fmt.Sprintf("Bearer %s", a.Token))
542 }
543
544 // Name is name of the auth
545 func (a *TokenAuth) Name() string {
546 return "http-token-auth"
547 }
548
549 func (a *TokenAuth) String() string {
550 masked := "*******"
551 if a.Token == "" {
552 masked = "<empty>"
553 }
554 return fmt.Sprintf("%s - %s", a.Name(), masked)
555 }
556
557 // Err is a dedicated error to return errors based on status code
558 type Err struct {
559 Response *http.Response
560 Reason string
561 }
562
563 // NewErr returns a new Err based on a http response and closes response body
564 // if needed
565 func NewErr(r *http.Response) error {
566 if r.StatusCode >= http.StatusOK && r.StatusCode < http.StatusMultipleChoices {
567 return nil
568 }
569
570 var reason string
571
572 // If a response message is present, add it to error
573 var messageBuffer bytes.Buffer
574 if r.Body != nil {
575 messageLength, _ := messageBuffer.ReadFrom(r.Body)
576 if messageLength > 0 {
577 reason = messageBuffer.String()
578 }
579 _ = r.Body.Close()
580 }
581
582 switch r.StatusCode {
583 case http.StatusUnauthorized:
584 return fmt.Errorf("%w: %s", transport.ErrAuthenticationRequired, reason)
585 case http.StatusForbidden:
586 return fmt.Errorf("%w: %s", transport.ErrAuthorizationFailed, reason)
587 case http.StatusNotFound:
588 return fmt.Errorf("%w: %s", transport.ErrRepositoryNotFound, reason)
589 }
590
591 return plumbing.NewUnexpectedError(&Err{r, reason})
592 }
593
594 // StatusCode returns the status code of the response
595 func (e *Err) StatusCode() int {
596 return e.Response.StatusCode
597 }
598
599 func (e *Err) Error() string {
600 return fmt.Sprintf("unexpected requesting %q status code: %d",
601 e.Response.Request.URL, e.Response.StatusCode,
602 )
603 }