/
client.go
333 lines (281 loc) · 11.9 KB
/
client.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
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
package ord
import (
"context"
"encoding/json"
"io"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/avast/retry-go/v4"
"github.com/kyma-incubator/compass/components/director/internal/domain/application"
"github.com/kyma-incubator/compass/components/director/pkg/str"
directorwh "github.com/kyma-incubator/compass/components/director/pkg/webhook"
directorresource "github.com/kyma-incubator/compass/components/director/pkg/resource"
"github.com/kyma-incubator/compass/components/director/internal/domain/tenant"
"github.com/kyma-incubator/compass/components/director/pkg/accessstrategy"
"github.com/kyma-incubator/compass/components/director/internal/model"
httputil "github.com/kyma-incubator/compass/components/director/pkg/http"
"github.com/kyma-incubator/compass/components/director/pkg/log"
"github.com/pkg/errors"
)
// ClientConfig contains configuration for the ORD aggregator client
type ClientConfig struct {
maxParallelDocumentsPerApplication int
retryDelay time.Duration
retryAttempts uint
}
// Resource represents a resource that is being aggregated. This would be an Application or Application Template
type Resource struct {
Type directorresource.Type
ID string
ParentID *string
Name string
LocalTenantID *string
}
// NewClientConfig creates new ClientConfig from the supplied parameters
func NewClientConfig(maxParallelDocumentsPerApplication int, retryDelay time.Duration, retryAttempts uint) ClientConfig {
return ClientConfig{
maxParallelDocumentsPerApplication: maxParallelDocumentsPerApplication,
retryDelay: retryDelay,
retryAttempts: retryAttempts,
}
}
// Client represents ORD documents client
//
//go:generate mockery --name=Client --output=automock --outpkg=automock --case=underscore --disable-version-string
type Client interface {
FetchOpenResourceDiscoveryDocuments(ctx context.Context, resource Resource, webhook *model.Webhook, ordWebhookMapping application.ORDWebhookMapping, appBaseURL directorwh.OpenResourceDiscoveryWebhookRequestObject) (Documents, []string, string, error)
}
// ORDDocumentsClient defines ORD documents client
type ORDDocumentsClient struct {
config ClientConfig
*http.Client
accessStrategyExecutorProvider accessstrategy.ExecutorProvider
}
// NewClient creates new ORD Client via a provided http.Client
func NewClient(config ClientConfig, httpClient *http.Client, accessStrategyExecutorProvider accessstrategy.ExecutorProvider) *ORDDocumentsClient {
return &ORDDocumentsClient{
config: config,
Client: httpClient,
accessStrategyExecutorProvider: accessStrategyExecutorProvider,
}
}
// FetchOpenResourceDiscoveryDocuments fetches all the documents for a single ORD .well-known endpoint
func (c *ORDDocumentsClient) FetchOpenResourceDiscoveryDocuments(ctx context.Context, resource Resource, webhook *model.Webhook, ordWebhookMapping application.ORDWebhookMapping, requestObject directorwh.OpenResourceDiscoveryWebhookRequestObject) (Documents, []string, string, error) {
var tenantValue string
if needsTenantHeader := webhook.ObjectType == model.ApplicationTemplateWebhookReference && resource.Type != directorresource.ApplicationTemplate; needsTenantHeader {
tntFromCtx, err := tenant.LoadTenantPairFromContext(ctx)
if err != nil {
return nil, nil, "", errors.Wrapf(err, "while loading tenant from context for application template webhook flow")
}
tenantValue = tntFromCtx.ExternalID
}
log.C(ctx).Infof("Fetching ORD well-known config with retry")
var config *WellKnownConfig
err := retry.Do(
func() error {
var err error
config, err = c.fetchConfig(ctx, resource, webhook, tenantValue, requestObject)
return err
},
retry.Attempts(c.config.retryAttempts),
retry.Delay(c.config.retryDelay),
retry.OnRetry(func(n uint, err error) {
log.C(ctx).Infof("Retrying request attempt (%d) after error %v", n, err)
}),
)
if err != nil {
log.C(ctx).Error(errors.Wrap(err, "error fetching ORD well-known config").Error())
return nil, nil, "", err
}
webhookBaseURL, err := calculateBaseURL(webhook, *config)
if err != nil {
return nil, nil, "", errors.Wrap(err, "while calculating baseURL")
}
err = config.Validate(webhookBaseURL)
if err != nil {
return nil, nil, "", errors.Wrap(err, "while validating ORD config")
}
docs := make([]*Document, 0)
docsString := make([]string, 0)
docMutex := sync.Mutex{}
wg := sync.WaitGroup{}
workers := make(chan struct{}, c.config.maxParallelDocumentsPerApplication)
fetchDocErrors := make([]error, 0)
errMutex := sync.Mutex{}
for _, docDetails := range config.OpenResourceDiscoveryV1.Documents {
wg.Add(1)
workers <- struct{}{}
go func(docDetails DocumentDetails) {
defer func() {
wg.Done()
<-workers
}()
documentURL, err := buildDocumentURL(docDetails.URL, webhookBaseURL, str.PtrStrToStr(webhook.ProxyURL), ordWebhookMapping)
if err != nil {
log.C(ctx).Error(errors.Wrap(err, "error building document URL").Error())
addError(&fetchDocErrors, err, &errMutex)
return
}
strategy, ok := docDetails.AccessStrategies.GetSupported()
if !ok {
log.C(ctx).Warnf("Unsupported access strategies for ORD Document %q", documentURL)
}
var doc *Document
var docString string
err = retry.Do(
func() error {
var innerErr error
doc, docString, innerErr = c.fetchOpenDiscoveryDocumentWithAccessStrategy(ctx, documentURL, strategy, requestObject)
return innerErr
},
retry.Attempts(c.config.retryAttempts),
retry.Delay(c.config.retryDelay),
retry.OnRetry(func(n uint, err error) {
log.C(ctx).Infof("Retrying request attempt (%d) after error %v", n, err)
}),
)
if err != nil {
log.C(ctx).Error(errors.Wrapf(err, "error fetching ORD document from: %s", documentURL).Error())
addError(&fetchDocErrors, err, &errMutex)
return
}
if docDetails.Perspective == SystemVersionPerspective {
doc.Perspective = SystemVersionPerspective
} else {
doc.Perspective = SystemInstancePerspective
}
addDocument(&docs, doc, &docMutex, &docsString, docString)
}(docDetails)
}
wg.Wait()
var fetchDocErr error = nil
if len(fetchDocErrors) > 0 {
stringErrors := convertErrorsToStrings(fetchDocErrors)
fetchDocErr = errors.Errorf(strings.Join(stringErrors, "\n"))
}
return docs, docsString, webhookBaseURL, fetchDocErr
}
func convertErrorsToStrings(errors []error) (result []string) {
for _, err := range errors {
result = append(result, err.Error())
}
return result
}
func (c *ORDDocumentsClient) fetchOpenDiscoveryDocumentWithAccessStrategy(ctx context.Context, documentURL string, accessStrategy accessstrategy.Type, requestObject directorwh.OpenResourceDiscoveryWebhookRequestObject) (*Document, string, error) {
log.C(ctx).Infof("Fetching ORD Document %q with Access Strategy %q", documentURL, accessStrategy)
executor, err := c.accessStrategyExecutorProvider.Provide(accessStrategy)
if err != nil {
return nil, "", err
}
resp, err := executor.Execute(ctx, c.Client, documentURL, requestObject.TenantID, requestObject.Headers)
if err != nil {
return nil, "", err
}
defer closeBody(ctx, resp.Body)
if resp.StatusCode != http.StatusOK {
return nil, "", errors.Errorf("error while fetching open resource discovery document %q: status code %d", documentURL, resp.StatusCode)
}
resp.Body = http.MaxBytesReader(nil, resp.Body, 2097152)
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, "", errors.Wrap(err, "error reading document body")
}
result := &Document{}
if err := json.Unmarshal(bodyBytes, &result); err != nil {
return nil, "", errors.Wrap(err, "error unmarshaling document")
}
return result, string(bodyBytes), nil
}
func closeBody(ctx context.Context, body io.ReadCloser) {
if err := body.Close(); err != nil {
log.C(ctx).WithError(err).Warnf("Got error on closing response body")
}
}
func addDocument(docs *[]*Document, doc *Document, mutex *sync.Mutex, docsString *[]string, docString string) {
mutex.Lock()
defer mutex.Unlock()
*docs = append(*docs, doc)
*docsString = append(*docsString, docString)
}
func addError(fetchDocErrors *[]error, err error, mutex *sync.Mutex) {
mutex.Lock()
defer mutex.Unlock()
*fetchDocErrors = append(*fetchDocErrors, err)
}
func (c *ORDDocumentsClient) fetchConfig(ctx context.Context, resource Resource, webhook *model.Webhook, tenantValue string, requestObject directorwh.OpenResourceDiscoveryWebhookRequestObject) (*WellKnownConfig, error) {
var resp *http.Response
var err error
webhookURL := *webhook.URL
if webhook.ProxyURL != nil {
webhookURL = *webhook.ProxyURL
}
if webhook.Auth != nil && webhook.Auth.AccessStrategy != nil && len(*webhook.Auth.AccessStrategy) > 0 {
log.C(ctx).Infof("%s %q (id = %q) ORD webhook is configured with %q access strategy.", resource.Type, resource.Name, resource.ID, *webhook.Auth.AccessStrategy)
executor, err := c.accessStrategyExecutorProvider.Provide(accessstrategy.Type(*webhook.Auth.AccessStrategy))
if err != nil {
return nil, errors.Wrapf(err, "cannot find executor for access strategy %q as part of webhook processing", *webhook.Auth.AccessStrategy)
}
resp, err = executor.Execute(ctx, c.Client, webhookURL, tenantValue, requestObject.Headers)
if err != nil {
return nil, errors.Wrapf(err, "error while fetching open resource discovery well-known configuration with access strategy %q", *webhook.Auth.AccessStrategy)
}
} else if webhook.Auth != nil {
log.C(ctx).Infof("%s %q (id = %q) configuration endpoint is secured and webhook credentials will be used", resource.Type, resource.Name, resource.ID)
resp, err = httputil.GetRequestWithCredentials(ctx, c.Client, webhookURL, requestObject.TenantID, webhook.Auth)
if err != nil {
return nil, errors.Wrap(err, "error while fetching open resource discovery well-known configuration with webhook credentials")
}
} else {
log.C(ctx).Infof("%s %q (id = %q) configuration endpoint is not secured", resource.Type, resource.Name, resource.ID)
resp, err = httputil.GetRequestWithoutCredentials(c.Client, webhookURL, requestObject.TenantID)
if err != nil {
return nil, errors.Wrap(err, "error while fetching open resource discovery well-known configuration")
}
}
defer closeBody(ctx, resp.Body)
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrap(err, "error reading response body")
}
if resp.StatusCode != http.StatusOK {
return nil, errors.Errorf("error while fetching open resource discovery well-known configuration: status code %d Body: %s", resp.StatusCode, string(bodyBytes))
}
config := WellKnownConfig{}
if err := json.Unmarshal(bodyBytes, &config); err != nil {
return nil, errors.Wrap(err, "error unmarshaling wellknown json body")
}
return &config, nil
}
func buildDocumentURL(docURL, appBaseURL, webhookProxyURL string, ordWebhookMapping application.ORDWebhookMapping) (string, error) {
docURLParsed, err := url.Parse(docURL)
if err != nil {
return "", err
}
if docURLParsed.IsAbs() {
return docURL, nil
}
if webhookProxyURL != "" {
return ordWebhookMapping.ProxyURL + docURL, nil
}
return appBaseURL + docURL, nil
}
// if webhookURL is not /well-known, but there is a valid baseURL provided in the config - use it
// if webhookURL is /well-known, strip the suffix and use it as baseURL. In case both are provided - the config baseURL is used.
func calculateBaseURL(webhook *model.Webhook, config WellKnownConfig) (string, error) {
if config.BaseURL != "" {
return config.BaseURL, nil
}
parsedWebhookURL, err := url.ParseRequestURI(str.PtrStrToStr(webhook.URL))
if err != nil {
return "", errors.New("error while parsing input webhook url")
}
if strings.HasSuffix(parsedWebhookURL.Path, WellKnownEndpoint) {
strippedPath := strings.ReplaceAll(parsedWebhookURL.Path, WellKnownEndpoint, "")
parsedWebhookURL.Path = strippedPath
return parsedWebhookURL.String(), nil
}
return "", nil
}