forked from kyma-project/kyma
/
proxy.go
215 lines (172 loc) · 6.54 KB
/
proxy.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
package proxy
import (
"bytes"
"context"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"time"
"github.com/kyma-project/kyma/components/application-gateway/internal/csrf"
"github.com/kyma-project/kyma/components/application-gateway/internal/apperrors"
"github.com/kyma-project/kyma/components/application-gateway/internal/authorization"
"github.com/kyma-project/kyma/components/application-gateway/internal/httpconsts"
"github.com/kyma-project/kyma/components/application-gateway/internal/httperrors"
"github.com/kyma-project/kyma/components/application-gateway/internal/k8sconsts"
"github.com/kyma-project/kyma/components/application-gateway/internal/metadata"
metadatamodel "github.com/kyma-project/kyma/components/application-gateway/internal/metadata/model"
)
type proxy struct {
nameResolver k8sconsts.NameResolver
serviceDefService metadata.ServiceDefinitionService
cache Cache
skipVerify bool
proxyTimeout int
authorizationStrategyFactory authorization.StrategyFactory
csrfTokenStrategyFactory csrf.TokenStrategyFactory
}
type Config struct {
SkipVerify bool
ProxyTimeout int
Application string
ProxyCacheTTL int
}
// New creates proxy for handling user's services calls
func New(serviceDefService metadata.ServiceDefinitionService, authorizationStrategyFactory authorization.StrategyFactory, csrfTokenStrategyFactory csrf.TokenStrategyFactory, config Config) http.Handler {
return &proxy{
nameResolver: k8sconsts.NewNameResolver(config.Application),
serviceDefService: serviceDefService,
cache: NewCache(config.ProxyCacheTTL),
skipVerify: config.SkipVerify,
proxyTimeout: config.ProxyTimeout,
authorizationStrategyFactory: authorizationStrategyFactory,
csrfTokenStrategyFactory: csrfTokenStrategyFactory,
}
}
// NewInvalidStateHandler creates handler always returning 500 response
func NewInvalidStateHandler(message string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
handleErrors(w, apperrors.Internal(message))
})
}
func (p *proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
id := p.extractServiceId(r.Host)
cacheEntry, err := p.getOrCreateCacheEntry(id)
if err != nil {
handleErrors(w, err)
return
}
newRequest, cancel := p.prepareRequest(r, cacheEntry)
defer cancel()
err = p.addAuthorization(newRequest, cacheEntry)
if err != nil {
handleErrors(w, err)
return
}
if err := p.addModifyResponseHandler(newRequest, id, cacheEntry); err != nil {
handleErrors(w, err)
return
}
p.executeRequest(w, newRequest, cacheEntry)
}
func (p *proxy) extractServiceId(host string) string {
return p.nameResolver.ExtractServiceId(host)
}
func (p *proxy) getOrCreateCacheEntry(id string) (*CacheEntry, apperrors.AppError) {
cacheObj, found := p.cache.Get(id)
if found {
return cacheObj, nil
}
return p.createCacheEntry(id)
}
func (p *proxy) createCacheEntry(id string) (*CacheEntry, apperrors.AppError) {
serviceApi, err := p.serviceDefService.GetAPI(id)
if err != nil {
return nil, err
}
proxy, err := makeProxy(serviceApi.TargetUrl, serviceApi.RequestParameters, id, p.skipVerify)
if err != nil {
return nil, err
}
authorizationStrategy := p.newAuthorizationStrategy(serviceApi.Credentials)
csrfTokenStrategy := p.newCSRFTokenStrategy(authorizationStrategy, serviceApi.Credentials)
return p.cache.Put(id, proxy, authorizationStrategy, csrfTokenStrategy), nil
}
func (p *proxy) newAuthorizationStrategy(credentials *metadatamodel.Credentials) authorization.Strategy {
return p.authorizationStrategyFactory.Create(credentials)
}
func (p *proxy) newCSRFTokenStrategy(authorizationStrategy authorization.Strategy, credentials *metadatamodel.Credentials) csrf.TokenStrategy {
csrfTokenEndpointURL := ""
if credentials != nil {
csrfTokenEndpointURL = credentials.CSRFTokenEndpointURL
}
return p.csrfTokenStrategyFactory.Create(authorizationStrategy, csrfTokenEndpointURL)
}
func (p *proxy) prepareRequest(r *http.Request, cacheEntry *CacheEntry) (*http.Request, context.CancelFunc) {
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(p.proxyTimeout)*time.Second)
newRequest := r.WithContext(ctx)
return newRequest, cancel
}
func (p *proxy) addAuthorization(r *http.Request, cacheEntry *CacheEntry) apperrors.AppError {
err := cacheEntry.AuthorizationStrategy.AddAuthorization(r)
if err != nil {
return err
}
return cacheEntry.CSRFTokenStrategy.AddCSRFToken(r)
}
func (p *proxy) addModifyResponseHandler(r *http.Request, id string, cacheEntry *CacheEntry) apperrors.AppError {
modifyResponseFunction, err := p.createModifyResponseFunction(id, r)
if err != nil {
return err
}
cacheEntry.Proxy.ModifyResponse = modifyResponseFunction
return nil
}
func (p *proxy) createModifyResponseFunction(id string, r *http.Request) (func(*http.Response) error, apperrors.AppError) {
// Handle the case when credentials has been changed or OAuth token has expired
secondRequestBody, err := copyRequestBody(r)
if err != nil {
return nil, err
}
modifyResponseFunction := func(response *http.Response) error {
retrier := newUnauthorizedResponseRetrier(id, r, secondRequestBody, p.proxyTimeout, p.createCacheEntry)
return retrier.RetryIfFailedToAuthorize(response)
}
return modifyResponseFunction, nil
}
func copyRequestBody(r *http.Request) (io.ReadCloser, apperrors.AppError) {
if r.Body == nil {
return nil, nil
}
bodyCopy, secondRequestBody, err := drainBody(r.Body)
if err != nil {
return nil, apperrors.Internal("failed to drain request body, %s", err)
}
r.Body = bodyCopy
return secondRequestBody, nil
}
func drainBody(b io.ReadCloser) (r1, r2 io.ReadCloser, err error) {
if b == http.NoBody {
return http.NoBody, http.NoBody, nil
}
var buf bytes.Buffer
if _, err = buf.ReadFrom(b); err != nil {
return nil, b, err
}
if err = b.Close(); err != nil {
return nil, b, err
}
return ioutil.NopCloser(&buf), ioutil.NopCloser(bytes.NewReader(buf.Bytes())), nil
}
func (p *proxy) executeRequest(w http.ResponseWriter, r *http.Request, cacheEntry *CacheEntry) {
cacheEntry.Proxy.ServeHTTP(w, r)
}
func handleErrors(w http.ResponseWriter, apperr apperrors.AppError) {
code, body := httperrors.AppErrorToResponse(apperr)
respondWithBody(w, code, body)
}
func respondWithBody(w http.ResponseWriter, code int, body httperrors.ErrorResponse) {
w.Header().Set(httpconsts.HeaderContentType, httpconsts.ContentTypeApplicationJson)
w.WriteHeader(code)
json.NewEncoder(w).Encode(body)
}