13493: Move proxy and federation code to their own source files.
[arvados.git] / lib / controller / proxy.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package controller
6
7 import (
8         "context"
9         "io"
10         "net/http"
11         "net/url"
12         "time"
13
14         "git.curoverse.com/arvados.git/sdk/go/arvados"
15         "git.curoverse.com/arvados.git/sdk/go/httpserver"
16 )
17
18 // headers that shouldn't be forwarded when proxying. See
19 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers
20 var dropHeaders = map[string]bool{
21         "Connection":          true,
22         "Keep-Alive":          true,
23         "Proxy-Authenticate":  true,
24         "Proxy-Authorization": true,
25         "TE":                true,
26         "Trailer":           true,
27         "Transfer-Encoding": true,
28         "Upgrade":           true,
29 }
30
31 func (h *Handler) proxy(w http.ResponseWriter, reqIn *http.Request, urlOut *url.URL) {
32         // Copy headers from incoming request, then add/replace proxy
33         // headers like Via and X-Forwarded-For.
34         hdrOut := http.Header{}
35         for k, v := range reqIn.Header {
36                 if !dropHeaders[k] {
37                         hdrOut[k] = v
38                 }
39         }
40         xff := reqIn.RemoteAddr
41         if xffIn := reqIn.Header.Get("X-Forwarded-For"); xffIn != "" {
42                 xff = xffIn + "," + xff
43         }
44         hdrOut.Set("X-Forwarded-For", xff)
45         hdrOut.Add("Via", reqIn.Proto+" arvados-controller")
46
47         ctx := reqIn.Context()
48         if timeout := h.Cluster.HTTPRequestTimeout; timeout > 0 {
49                 var cancel context.CancelFunc
50                 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(time.Duration(timeout)))
51                 defer cancel()
52         }
53
54         reqOut := (&http.Request{
55                 Method: reqIn.Method,
56                 URL:    urlOut,
57                 Header: hdrOut,
58                 Body:   reqIn.Body,
59         }).WithContext(ctx)
60         resp, err := arvados.InsecureHTTPClient.Do(reqOut)
61         if err != nil {
62                 httpserver.Error(w, err.Error(), http.StatusInternalServerError)
63                 return
64         }
65         for k, v := range resp.Header {
66                 for _, v := range v {
67                         w.Header().Add(k, v)
68                 }
69         }
70         w.WriteHeader(resp.StatusCode)
71         n, err := io.Copy(w, resp.Body)
72         if err != nil {
73                 httpserver.Logger(reqIn).WithError(err).WithField("bytesCopied", n).Error("error copying response body")
74         }
75 }