forked from cloudfoundry/gorouter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouteservice.go
More file actions
249 lines (219 loc) · 7.26 KB
/
routeservice.go
File metadata and controls
249 lines (219 loc) · 7.26 KB
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package handlers
import (
"errors"
"fmt"
"net/http"
"net/url"
"code.cloudfoundry.org/gorouter/errorwriter"
"code.cloudfoundry.org/gorouter/logger"
"code.cloudfoundry.org/gorouter/proxy/utils"
"code.cloudfoundry.org/gorouter/registry"
"code.cloudfoundry.org/gorouter/routeservice"
"github.com/uber-go/zap"
"github.com/urfave/negroni"
"code.cloudfoundry.org/gorouter/route"
)
type RouteService struct {
config *routeservice.RouteServiceConfig
registry registry.Registry
logger logger.Logger
errorWriter errorwriter.ErrorWriter
}
// NewRouteService creates a handler responsible for handling route services
func NewRouteService(
config *routeservice.RouteServiceConfig,
routeRegistry registry.Registry,
logger logger.Logger,
errorWriter errorwriter.ErrorWriter,
) negroni.Handler {
return &RouteService{
config: config,
registry: routeRegistry,
logger: logger,
errorWriter: errorWriter,
}
}
func (r *RouteService) ServeHTTP(rw http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
prw, ok := rw.(utils.ProxyResponseWriter)
if !ok {
r.logger.Fatal("request-info-err", zap.String("error", "ProxyResponseWriter not found"))
return
}
reqInfo, err := ContextRequestInfo(req)
if err != nil {
r.logger.Fatal("request-info-err", zap.Error(err))
return
}
if reqInfo.RoutePool == nil {
r.logger.Fatal("request-info-err", zap.Error(errors.New("failed-to-access-RoutePool")))
return
}
routeServiceURL := reqInfo.RoutePool.RouteServiceUrl()
if routeServiceURL == "" {
// No route service is associated with this request
next(rw, req)
return
}
if !r.config.RouteServiceEnabled() {
r.logger.Info("route-service-unsupported")
AddRouterErrorHeader(rw, "route_service_unsupported")
r.errorWriter.WriteError(
rw,
http.StatusBadGateway,
"Support for route services is disabled.",
r.logger,
)
return
}
if IsWebSocketUpgrade(req) {
r.logger.Info("route-service-unsupported")
AddRouterErrorHeader(rw, "route_service_unsupported")
r.errorWriter.WriteError(
rw,
http.StatusServiceUnavailable,
"Websocket requests are not supported for routes bound to Route Services.",
r.logger,
)
return
}
hasBeenToRouteService, err := r.ArrivedViaRouteService(req)
if err != nil {
r.logger.Error("signature-validation-failed", zap.Error(err))
r.errorWriter.WriteError(
rw,
http.StatusBadRequest,
"Failed to validate Route Service Signature",
r.logger,
)
return
}
if hasBeenToRouteService {
// Remove the headers since the backend should not see it
req.Header.Del(routeservice.HeaderKeySignature)
req.Header.Del(routeservice.HeaderKeyMetadata)
req.Header.Del(routeservice.HeaderKeyForwardedURL)
next(rw, req)
return
}
// Update request with metadata for route service destination
var recommendedScheme string
if r.config.RouteServiceRecommendHttps() {
recommendedScheme = "https"
} else {
recommendedScheme = "http"
}
forwardedURLRaw := recommendedScheme + "://" + hostWithoutPort(req.Host) + req.RequestURI
routeServiceArgs, err := r.config.CreateRequest(routeServiceURL, forwardedURLRaw)
if err != nil {
r.logger.Error("route-service-failed", zap.Error(err))
r.errorWriter.WriteError(
rw,
http.StatusInternalServerError,
"Route service request failed.",
r.logger,
)
return
}
hostWithoutPort := hostWithoutPort(routeServiceArgs.ParsedUrl.Host)
escapedPath := routeServiceArgs.ParsedUrl.EscapedPath()
if r.config.RouteServiceHairpinning() && r.registry.Lookup(route.Uri(hostWithoutPort+escapedPath)) != nil {
reqInfo.ShouldRouteToInternalRouteService = true
}
req.Header.Set(routeservice.HeaderKeySignature, routeServiceArgs.Signature)
req.Header.Set(routeservice.HeaderKeyMetadata, routeServiceArgs.Metadata)
req.Header.Set(routeservice.HeaderKeyForwardedURL, routeServiceArgs.ForwardedURL)
reqInfo.RouteServiceURL = routeServiceArgs.ParsedUrl
next(rw, req)
// drop the first endpoint from the pool in the event of route service failure,
// because a stale route at index 0 with a bad route-service-url will result in
// all other requests failing at the route-service level. (the non-stale routes'
// route-services would never be hit)
// Using >= 400 here, rather than >= 500, since the route_service_url could
// contain auth information that is out of date
if prw.Status() >= http.StatusBadRequest {
if reqInfo.RoutePool.NumEndpoints() > 1 && !reqInfo.RoutePool.RemoveByIndex(0) {
r.logger.Error("route-service-prune-failed", zap.String("error", "failed to prune endpoint with failing route-service-url"))
}
}
}
func (r *RouteService) IsRouteServiceTraffic(req *http.Request) bool {
forwardedURLRaw := req.Header.Get(routeservice.HeaderKeyForwardedURL)
signature := req.Header.Get(routeservice.HeaderKeySignature)
if forwardedURLRaw == "" || signature == "" {
return false
}
request := newRequestReceivedFromRouteService(forwardedURLRaw, req.Header)
_, err := r.config.ValidateRequest(request)
return err == nil
}
func (r *RouteService) ArrivedViaRouteService(req *http.Request) (bool, error) {
reqInfo, err := ContextRequestInfo(req)
if err != nil {
r.logger.Fatal("request-info-err", zap.Error(err))
return false, err
}
if reqInfo.RoutePool == nil {
err = errors.New("failed-to-access-RoutePool")
r.logger.Fatal("request-info-err", zap.Error(err))
return false, err
}
var recommendedScheme string
if r.config.RouteServiceRecommendHttps() {
recommendedScheme = "https"
} else {
recommendedScheme = "http"
}
forwardedURLRaw := recommendedScheme + "://" + hostWithoutPort(req.Host) + req.RequestURI
routeServiceURL := reqInfo.RoutePool.RouteServiceUrl()
rsSignature := req.Header.Get(routeservice.HeaderKeySignature)
if hasBeenToRouteService(routeServiceURL, rsSignature) {
// A request from a route service destined for a backend instances
request := newRequestReceivedFromRouteService(forwardedURLRaw, req.Header)
validatedSig, err := r.config.ValidateRequest(request)
if err != nil {
return false, err
}
err = r.validateRouteServicePool(validatedSig, reqInfo.RoutePool)
if err != nil {
return false, err
}
return true, nil
}
return false, nil
}
func newRequestReceivedFromRouteService(appUrl string, requestHeaders http.Header) routeservice.RequestReceivedFromRouteService {
return routeservice.RequestReceivedFromRouteService{
AppUrl: appUrl,
Signature: requestHeaders.Get(routeservice.HeaderKeySignature),
Metadata: requestHeaders.Get(routeservice.HeaderKeyMetadata),
}
}
func (r *RouteService) validateRouteServicePool(
validatedSig *routeservice.SignatureContents,
requestPool *route.EndpointPool,
) error {
forwardedURL, err := url.ParseRequestURI(validatedSig.ForwardedUrl)
if err != nil {
return err
}
uri := route.Uri(hostWithoutPort(forwardedURL.Host) + forwardedURL.EscapedPath())
forwardedPool := r.registry.Lookup(uri)
if forwardedPool == nil {
return fmt.Errorf(
"original request URL %s does not exist in the routing table",
uri.String(),
)
}
if !route.PoolsMatch(requestPool, forwardedPool) {
return fmt.Errorf(
"route service forwarded URL %s%s does not match the original request URL %s",
requestPool.Host(),
requestPool.ContextPath(),
uri.String(),
)
}
return nil
}
func hasBeenToRouteService(rsUrl, sigHeader string) bool {
return sigHeader != "" && rsUrl != ""
}