/
reverseproxy.go
198 lines (165 loc) · 5.69 KB
/
reverseproxy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package proxy
import (
"context"
"errors"
"net/http"
"net/http/httputil"
"net/url"
"strconv"
"strings"
"go.uber.org/zap"
"github.com/kyma-project/kyma/components/central-application-gateway/internal/csrf"
"github.com/kyma-project/kyma/components/central-application-gateway/pkg/apperrors"
"github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization"
"github.com/kyma-project/kyma/components/central-application-gateway/pkg/authorization/clientcert"
"github.com/kyma-project/kyma/components/central-application-gateway/pkg/httpconsts"
"github.com/kyma-project/kyma/components/central-application-gateway/pkg/httptools"
)
func makeProxy(
targetURL string,
requestParameters *authorization.RequestParameters,
serviceName string,
skipTLSVerify bool,
authorizationStrategy authorization.Strategy,
csrfTokenStrategy csrf.TokenStrategy,
clientCertificate clientcert.ClientCertificate,
timeout int,
) (*httputil.ReverseProxy, apperrors.AppError) {
roundTripper := httptools.NewRoundTripper(httptools.WithTLSSkipVerify(skipTLSVerify), httptools.WithGetClientCertificate(clientCertificate.GetClientCertificate))
retryableRoundTripper := NewRetryableRoundTripper(roundTripper, authorizationStrategy, csrfTokenStrategy, clientCertificate, timeout, skipTLSVerify)
return newProxy(targetURL, requestParameters, serviceName, retryableRoundTripper)
}
func newProxy(targetURL string, requestParameters *authorization.RequestParameters, serviceName string, transport http.RoundTripper) (*httputil.ReverseProxy, apperrors.AppError) {
target, err := url.Parse(targetURL)
if err != nil {
zap.L().Error("failed to parse target URL",
zap.String("targetURL", targetURL),
zap.Error(err))
return nil, apperrors.Internal("failed to parse target url '%s': '%s'", targetURL, err.Error())
}
targetQuery := target.RawQuery
director := func(req *http.Request) {
zap.L().Info("Proxy call for service",
zap.String("serviceName", serviceName),
zap.String("targetURL", targetURL))
req.URL.Scheme = target.Scheme
req.URL.Host = target.Host
req.Host = target.Host
combinedPath := joinPaths(target.Path, req.URL.Path)
combinedPathEscaped := joinPaths(target.Path, req.URL.RawPath)
req.URL.Path = combinedPath
req.URL.RawPath = combinedPathEscaped
if targetQuery == "" || req.URL.RawQuery == "" {
req.URL.RawQuery = targetQuery + req.URL.RawQuery
} else {
req.URL.RawQuery = targetQuery + "&" + req.URL.RawQuery
}
if requestParameters != nil {
setCustomQueryParameters(req.URL, requestParameters.QueryParameters)
setCustomHeaders(req.Header, requestParameters.Headers)
}
zap.L().Info("modified request URL",
zap.String("url", req.URL.String()),
zap.String("schema", req.URL.Scheme),
zap.String("path", req.URL.Path))
}
errorHandler := func(rw http.ResponseWriter, req *http.Request, err error) {
zap.L().Warn("Request failed",
zap.Error(err),
zap.Any("requestID", req.Context().Value(httptools.ContextUUID)),
zap.String("method", req.Method),
zap.String("host", req.Host),
zap.String("url", req.URL.RequestURI()),
zap.String("proto", req.Proto),
)
codeRewriter(rw, err)
}
return &httputil.ReverseProxy{
Director: director,
Transport: transport,
ErrorHandler: errorHandler,
}, nil
}
func joinPaths(a, b string) string {
if b == "" {
return a
}
aslash := strings.HasSuffix(a, "/")
bslash := strings.HasPrefix(b, "/")
switch {
case aslash && bslash:
return a + b[1:]
case !aslash && !bslash:
return a + "/" + b
}
return a + b
}
func setCustomQueryParameters(reqURL *url.URL, customQueryParams *map[string][]string) {
httptools.SetQueryParameters(reqURL, customQueryParams)
}
func setCustomHeaders(reqHeaders http.Header, customHeaders *map[string][]string) {
if _, ok := reqHeaders[httpconsts.HeaderUserAgent]; !ok {
// explicitly disable User-Agent so it's not set to default value
reqHeaders.Set(httpconsts.HeaderUserAgent, "")
}
httptools.SetHeaders(reqHeaders, customHeaders)
}
func responseModifier(
gatewayURL *url.URL,
targetURL string,
urlRewriter func(gatewayURL, target, loc *url.URL) *url.URL,
) func(*http.Response) error {
return func(resp *http.Response) error {
_ = httptools.LogResponse(zap.L().Sugar(), resp)
if resp.StatusCode >= 500 && resp.StatusCode < 600 {
resp.Header.Set("Target-System-Status", strconv.Itoa(resp.StatusCode))
resp.StatusCode = http.StatusBadGateway
}
if (resp.StatusCode < 300 || resp.StatusCode >= 400) &&
resp.StatusCode != http.StatusCreated {
return nil
}
const locationHeader = "Location"
locRaw := resp.Header.Get(locationHeader)
if locRaw == "" {
return nil
}
loc, err := resp.Request.URL.Parse(locRaw)
if err != nil {
return nil
}
target, err := url.Parse(targetURL)
if err != nil {
return nil
}
newURL := urlRewriter(gatewayURL, target, loc)
if newURL != nil {
resp.Header.Set(locationHeader, newURL.String())
}
return nil
}
}
// urlRewriter modifies redirect URLs for reverse proxy.
// If the URL should be left unmodified - it returns nil.
func urlRewriter(gatewayURL, target, loc *url.URL) *url.URL {
if loc.Scheme != "http" && loc.Scheme != "https" {
return nil
}
if loc.Hostname() != target.Hostname() || !strings.HasPrefix(loc.Path, target.Path) {
return nil
}
stripped := strings.TrimPrefix(loc.Path, target.Path)
gatewayURL = gatewayURL.JoinPath(stripped)
gatewayURL.RawQuery = loc.RawQuery
gatewayURL.Fragment = loc.Fragment
return gatewayURL
}
func codeRewriter(rw http.ResponseWriter, err error) {
if errors.Is(err, context.DeadlineExceeded) {
zap.L().Warn("HTTP status code rewritten to 504",
zap.Error(err))
rw.WriteHeader(http.StatusGatewayTimeout)
return
}
rw.WriteHeader(http.StatusBadGateway)
}