1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
12 "git.arvados.org/arvados.git/sdk/go/httpserver"
16 Name string // to use in Via header
19 type HTTPError struct {
24 func (h HTTPError) Error() string {
28 var dropHeaders = map[string]bool{
29 // Headers that shouldn't be forwarded when proxying. See
30 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers
33 "Proxy-Authenticate": true,
34 "Proxy-Authorization": true,
35 // (comment/space here makes gofmt1.10 agree with gofmt1.11)
40 // Headers that would interfere with Go's automatic
41 // compression/decompression if we forwarded them.
42 "Accept-Encoding": true,
43 "Content-Encoding": true,
44 "Transfer-Encoding": true,
46 // Content-Length depends on encoding.
47 "Content-Length": true,
50 type ResponseFilter func(*http.Response, error) (*http.Response, error)
52 // Forward a request to upstream service, and return response or error.
56 client *http.Client) (*http.Response, error) {
58 // Copy headers from incoming request, then add/replace proxy
59 // headers like Via and X-Forwarded-For.
60 hdrOut := http.Header{}
61 for k, v := range reqIn.Header {
66 xff := reqIn.RemoteAddr
67 if xffIn := reqIn.Header.Get("X-Forwarded-For"); xffIn != "" {
68 xff = xffIn + "," + xff
70 hdrOut.Set("X-Forwarded-For", xff)
71 if hdrOut.Get("X-Forwarded-Proto") == "" {
72 hdrOut.Set("X-Forwarded-Proto", reqIn.URL.Scheme)
74 hdrOut.Add("Via", reqIn.Proto+" arvados-controller")
76 reqOut := (&http.Request{
82 }).WithContext(reqIn.Context())
83 return client.Do(reqOut)
86 // Copy a response (or error) to the downstream client
87 func (p *proxy) ForwardResponse(w http.ResponseWriter, resp *http.Response, err error) (int64, error) {
89 if he, ok := err.(HTTPError); ok {
90 httpserver.Error(w, he.Message, he.Code)
92 httpserver.Error(w, err.Error(), http.StatusBadGateway)
97 defer resp.Body.Close()
98 for k, v := range resp.Header {
103 w.WriteHeader(resp.StatusCode)
104 return io.Copy(w, resp.Body)