forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
coprocess_bundle.go
403 lines (317 loc) · 8.95 KB
/
coprocess_bundle.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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
package main
import (
"github.com/TykTechnologies/logrus"
"github.com/TykTechnologies/goverify"
"github.com/TykTechnologies/tykcommon"
"archive/zip"
"bytes"
"crypto/md5"
b64 "encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
)
var tykBundlePath string
func init() {
tykBundlePath = filepath.Join(config.MiddlewarePath, "middleware/bundles")
}
// Bundle is the basic bundle data structure, it holds the bundle name and the data.
type Bundle struct {
Name string
Data []byte
Path string
Spec *APISpec
Manifest tykcommon.BundleManifest
}
func (b *Bundle) Verify() (err error) {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("----> Verifying bundle: ", b.Spec.CustomMiddlewareBundle)
var useSignature bool
var bundleVerifier goverify.Verifier
// Perform signature verification if a public key path is set:
if config.PublicKeyPath != "" {
if b.Manifest.Signature == "" {
// Error: A public key is set, but the bundle isn't signed.
err = errors.New("Bundle isn't signed")
}
if notificationVerifier == nil {
bundleVerifier, err = goverify.LoadPublicKeyFromFile(config.PublicKeyPath)
}
if err != nil {
return err
}
useSignature = true
}
h := md5.New()
h.Write(b.Data)
checksum := hex.EncodeToString(h.Sum(nil))
var bundleData bytes.Buffer
for _, f := range b.Manifest.FileList {
extractedFilePath := filepath.Join(b.Path, f)
var data []byte
data, err = ioutil.ReadFile(extractedFilePath)
if err != nil {
break
}
bundleData.Write(data)
}
checksum = fmt.Sprintf("%x", md5.Sum(bundleData.Bytes()))
if checksum != b.Manifest.Checksum {
err = errors.New("Invalid checksum")
}
if useSignature {
var signed []byte
signed, err = b64.StdEncoding.DecodeString(b.Manifest.Signature)
if err != nil {
return err
}
err = bundleVerifier.Verify([]byte(bundleData.Bytes()), signed)
if err != nil {
return err
}
}
return err
}
func (b *Bundle) AddToSpec() {
b.Spec.APIDefinition.CustomMiddleware = b.Manifest.CustomMiddleware
if GlobalDispatcher != nil {
GlobalDispatcher.HandleMiddlewareCache(&b.Manifest, b.Path)
}
}
// BundleGetter is used for downloading bundle data, see HttpBundleGetter for reference.
type BundleGetter interface {
Get() ([]byte, error)
}
// HttpBundleGetter is a simple HTTP BundleGetter.
type HttpBundleGetter struct {
Url string
}
// Get performs an HTTP GET request.
func (g *HttpBundleGetter) Get() (bundleData []byte, err error) {
var resp *http.Response
resp, err = http.Get(g.Url)
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
return nil, errors.New("HTTP Error")
}
defer resp.Body.Close()
bundleData, err = ioutil.ReadAll(resp.Body)
return bundleData, err
}
// BundleSaver is an interface used by bundle saver structures.
type BundleSaver interface {
Save(*Bundle, string, *APISpec) error
}
// ZipBundleSaver is a BundleSaver for ZIP files.
type ZipBundleSaver struct {
}
// Save implements the main method of the BundleSaver interface. It makes use of archive/zip.
func (s *ZipBundleSaver) Save(bundle *Bundle, bundlePath string, spec *APISpec) (err error) {
buf := bytes.NewReader(bundle.Data)
reader, _ := zip.NewReader(buf, int64(len(bundle.Data)))
for _, f := range reader.File {
var rc io.ReadCloser
rc, err = f.Open()
if err != nil {
return err
}
var destPath string
destPath = filepath.Join(bundlePath, f.Name)
isDir := f.FileHeader.Mode().IsDir()
if isDir {
err = os.Mkdir(destPath, 0755)
if err != nil {
return err
}
} else {
var newFile *os.File
newFile, err = os.Create(destPath)
if err != nil {
return err
}
_, err = io.Copy(newFile, rc)
if err != nil {
return err
}
}
}
return err
}
// fetchBundle will fetch a given bundle, using the right BundleGetter. The first argument is the bundle name, the base bundle URL will be used as prefix.
func fetchBundle(spec *APISpec) (thisBundle Bundle, err error) {
if !config.EnableBundleDownloader {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Warning("Bundle downloader is disabled.")
err = errors.New("Bundle downloader is disabled.")
return thisBundle, err
}
var bundleUrl string
bundleUrl = strings.Join([]string{config.BundleBaseURL, spec.CustomMiddlewareBundle}, "")
var thisGetter BundleGetter
var u *url.URL
u, err = url.Parse(bundleUrl)
switch u.Scheme {
case "http":
thisGetter = &HttpBundleGetter{
Url: bundleUrl,
}
default:
err = errors.New("Unknown URL scheme!")
}
bundleData, err := thisGetter.Get()
thisBundle = Bundle{
Name: spec.CustomMiddlewareBundle,
Data: bundleData,
Spec: spec,
}
return thisBundle, err
}
// saveBundle will save a bundle to the disk, see ZipBundleSaver methods for reference.
func saveBundle(bundle *Bundle, destPath string, spec *APISpec) (err error) {
var bundleFormat = "zip"
var bundleSaver BundleSaver
// TODO: use enums?
switch bundleFormat {
case "zip":
bundleSaver = &ZipBundleSaver{}
}
bundleSaver.Save(bundle, destPath, spec)
return err
}
// loadBundleManifest will parse the manifest file and return the bundle parameters.
func loadBundleManifest(bundle *Bundle, spec *APISpec, skipVerification bool) (err error) {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("----> Loading bundle: ", spec.CustomMiddlewareBundle)
manifestPath := filepath.Join(bundle.Path, "manifest.json")
var manifestData []byte
manifestData, err = ioutil.ReadFile(manifestPath)
err = json.Unmarshal(manifestData, &bundle.Manifest)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("----> Couldn't unmarshal the manifest file for bundle: ", spec.CustomMiddlewareBundle)
return err
}
if skipVerification {
return err
}
err = bundle.Verify()
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("----> Bundle verification failed: ", spec.CustomMiddlewareBundle)
}
return err
}
// loadBundle wraps the load and save steps, it will return if an error occurs at any point.
func loadBundle(spec *APISpec) {
var err error
// Skip if no custom middleware bundle name is set.
if spec.CustomMiddlewareBundle == "" {
return
}
// Skip if no bundle base URL is set.
if config.BundleBaseURL == "" {
bundleError(spec, err, "No bundle base URL set, skipping bundle")
return
}
// Skip if the bundle destination path already exists.
bundlePath := strings.Join([]string{spec.APIID, spec.CustomMiddlewareBundle}, "-")
destPath := filepath.Join(tykBundlePath, bundlePath)
// The bundle exists, load and return:
if _, err := os.Stat(destPath); err == nil {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("Loading existing bundle: ", spec.CustomMiddlewareBundle)
bundle := Bundle{
Name: spec.CustomMiddlewareBundle,
Path: destPath,
Spec: spec,
}
err = loadBundleManifest(&bundle, spec, true)
if err != nil {
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("----> Couldn't load bundle: ", spec.CustomMiddlewareBundle, " ", err)
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("----> Using bundle: ", spec.CustomMiddlewareBundle)
bundle.AddToSpec()
return
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("----> Fetching Bundle: ", spec.CustomMiddlewareBundle)
var bundle Bundle
bundle, err = fetchBundle(spec)
if err != nil {
bundleError(spec, err, "Couldn't fetch bundle")
return
}
err = os.Mkdir(destPath, 0755)
if err != nil {
bundleError(spec, err, "Couldn't create bundle directory")
return
}
err = saveBundle(&bundle, destPath, spec)
if err != nil {
bundleError(spec, err, "Couldn't save bundle")
return
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Debug("----> Saving Bundle: ", spec.CustomMiddlewareBundle)
// Set the destination path:
bundle.Path = destPath
err = loadBundleManifest(&bundle, spec, false)
if err != nil {
bundleError(spec, err, "Couldn't load bundle")
removeErr := os.RemoveAll(bundle.Path)
if removeErr != nil {
bundleError(spec, err, "Couldn't remove bundle")
}
return
}
log.WithFields(logrus.Fields{
"prefix": "main",
}).Info("----> Bundle is valid, adding to spec: ", spec.CustomMiddlewareBundle)
bundle.AddToSpec()
}
// bundleError is a log helper.
func bundleError(spec *APISpec, err error, message string) {
log.WithFields(logrus.Fields{
"prefix": "main",
"user_ip": "-",
"server_name": spec.APIDefinition.Proxy.TargetURL,
"user_id": "-",
"org_id": spec.APIDefinition.OrgID,
"api_id": spec.APIDefinition.APIID,
"path": "-",
}).Error(message, ": ", err)
}
// getBundlePaths will return an array of the available bundle directories:
func getBundlePaths() []string {
directories := make([]string, 0)
bundles, _ := ioutil.ReadDir(tykBundlePath)
for _, f := range bundles {
if f.IsDir() {
fullPath := filepath.Join(tykBundlePath, f.Name())
directories = append(directories, fullPath)
}
}
return directories
}