-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
http.go
1387 lines (1162 loc) · 37 KB
/
http.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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 The OPA Authors. All rights reserved.
// Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file.
package topdown
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"io/ioutil"
"math"
"net"
"net/http"
"net/url"
"os"
"runtime"
"strconv"
"strings"
"time"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/internal/version"
"github.com/open-policy-agent/opa/topdown/builtins"
"github.com/open-policy-agent/opa/topdown/cache"
"github.com/open-policy-agent/opa/tracing"
"github.com/open-policy-agent/opa/util"
)
type cachingMode string
const (
defaultHTTPRequestTimeoutEnv = "HTTP_SEND_TIMEOUT"
defaultCachingMode cachingMode = "serialized"
cachingModeDeserialized cachingMode = "deserialized"
)
var defaultHTTPRequestTimeout = time.Second * 5
var allowedKeyNames = [...]string{
"method",
"url",
"body",
"enable_redirect",
"force_json_decode",
"force_yaml_decode",
"headers",
"raw_body",
"tls_use_system_certs",
"tls_ca_cert",
"tls_ca_cert_file",
"tls_ca_cert_env_variable",
"tls_client_cert",
"tls_client_cert_file",
"tls_client_cert_env_variable",
"tls_client_key",
"tls_client_key_file",
"tls_client_key_env_variable",
"tls_insecure_skip_verify",
"tls_server_name",
"timeout",
"cache",
"force_cache",
"force_cache_duration_seconds",
"raise_error",
"caching_mode",
}
var (
allowedKeys = ast.NewSet()
requiredKeys = ast.NewSet(ast.StringTerm("method"), ast.StringTerm("url"))
httpSendLatencyMetricKey = "rego_builtin_" + strings.ReplaceAll(ast.HTTPSend.Name, ".", "_")
httpSendInterQueryCacheHits = httpSendLatencyMetricKey + "_interquery_cache_hits"
)
type httpSendKey string
const (
// httpSendBuiltinCacheKey is the key in the builtin context cache that
// points to the http.send() specific cache resides at.
httpSendBuiltinCacheKey httpSendKey = "HTTP_SEND_CACHE_KEY"
// HTTPSendInternalErr represents a runtime evaluation error.
HTTPSendInternalErr string = "eval_http_send_internal_error"
// HTTPSendNetworkErr represents a network error.
HTTPSendNetworkErr string = "eval_http_send_network_error"
)
func builtinHTTPSend(bctx BuiltinContext, args []*ast.Term, iter func(*ast.Term) error) error {
req, err := validateHTTPRequestOperand(args[0], 1)
if err != nil {
return handleBuiltinErr(ast.HTTPSend.Name, bctx.Location, err)
}
raiseError, err := getRaiseErrorValue(req)
if err != nil {
return handleBuiltinErr(ast.HTTPSend.Name, bctx.Location, err)
}
result, err := getHTTPResponse(bctx, req)
if err != nil {
if raiseError {
return handleHTTPSendErr(bctx, err)
}
obj := ast.NewObject()
obj.Insert(ast.StringTerm("status_code"), ast.IntNumberTerm(0))
errObj := ast.NewObject()
switch err.(type) {
case *url.Error:
errObj.Insert(ast.StringTerm("code"), ast.StringTerm(HTTPSendNetworkErr))
default:
errObj.Insert(ast.StringTerm("code"), ast.StringTerm(HTTPSendInternalErr))
}
errObj.Insert(ast.StringTerm("message"), ast.StringTerm(err.Error()))
obj.Insert(ast.StringTerm("error"), ast.NewTerm(errObj))
result = ast.NewTerm(obj)
}
return iter(result)
}
func getHTTPResponse(bctx BuiltinContext, req ast.Object) (*ast.Term, error) {
bctx.Metrics.Timer(httpSendLatencyMetricKey).Start()
reqExecutor, err := newHTTPRequestExecutor(bctx, req)
if err != nil {
return nil, err
}
// check if cache already has a response for this query
resp, err := reqExecutor.CheckCache()
if err != nil {
return nil, err
}
if resp == nil {
httpResp, err := reqExecutor.ExecuteHTTPRequest()
if err != nil {
return nil, err
}
defer util.Close(httpResp)
// add result to cache
resp, err = reqExecutor.InsertIntoCache(httpResp)
if err != nil {
return nil, err
}
}
bctx.Metrics.Timer(httpSendLatencyMetricKey).Stop()
return ast.NewTerm(resp), nil
}
func init() {
createAllowedKeys()
initDefaults()
RegisterBuiltinFunc(ast.HTTPSend.Name, builtinHTTPSend)
}
func handleHTTPSendErr(bctx BuiltinContext, err error) error {
// Return HTTP client timeout errors in a generic error message to avoid confusion about what happened.
// Do not do this if the builtin context was cancelled and is what caused the request to stop.
if urlErr, ok := err.(*url.Error); ok && urlErr.Timeout() && bctx.Context.Err() == nil {
err = fmt.Errorf("%s %s: request timed out", urlErr.Op, urlErr.URL)
}
if err := bctx.Context.Err(); err != nil {
return Halt{
Err: &Error{
Code: CancelErr,
Message: fmt.Sprintf("http.send: timed out (%s)", err.Error()),
},
}
}
return handleBuiltinErr(ast.HTTPSend.Name, bctx.Location, err)
}
func initDefaults() {
timeoutDuration := os.Getenv(defaultHTTPRequestTimeoutEnv)
if timeoutDuration != "" {
var err error
defaultHTTPRequestTimeout, err = time.ParseDuration(timeoutDuration)
if err != nil {
// If it is set to something not valid don't let the process continue in a state
// that will almost definitely give unexpected results by having it set at 0
// which means no timeout..
// This environment variable isn't considered part of the public API.
// TODO(patrick-east): Remove the environment variable
panic(fmt.Sprintf("invalid value for HTTP_SEND_TIMEOUT: %s", err))
}
}
}
func validateHTTPRequestOperand(term *ast.Term, pos int) (ast.Object, error) {
obj, err := builtins.ObjectOperand(term.Value, pos)
if err != nil {
return nil, err
}
requestKeys := ast.NewSet(obj.Keys()...)
invalidKeys := requestKeys.Diff(allowedKeys)
if invalidKeys.Len() != 0 {
return nil, builtins.NewOperandErr(pos, "invalid request parameters(s): %v", invalidKeys)
}
missingKeys := requiredKeys.Diff(requestKeys)
if missingKeys.Len() != 0 {
return nil, builtins.NewOperandErr(pos, "missing required request parameters(s): %v", missingKeys)
}
return obj, nil
}
// canonicalizeHeaders returns a copy of the headers where the keys are in
// canonical HTTP form.
func canonicalizeHeaders(headers map[string]interface{}) map[string]interface{} {
canonicalized := map[string]interface{}{}
for k, v := range headers {
canonicalized[http.CanonicalHeaderKey(k)] = v
}
return canonicalized
}
// useSocket examines the url for "unix://" and returns a *http.Transport with
// a DialContext that opens a socket (specified in the http call).
// The url is expected to contain socket=/path/to/socket (url encoded)
// Ex. "unix:localhost/end/point?socket=%2Ftmp%2Fhttp.sock"
func useSocket(rawURL string, tlsConfig *tls.Config) (bool, string, *http.Transport) {
u, err := url.Parse(rawURL)
if err != nil {
return false, "", nil
}
if u.Scheme != "unix" || u.RawQuery == "" {
return false, rawURL, nil
}
// Get the path to the socket
v, err := url.ParseQuery(u.RawQuery)
if err != nil {
return false, rawURL, nil
}
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
return http.DefaultTransport.(*http.Transport).DialContext(ctx, u.Scheme, v.Get("socket"))
}
tr.TLSClientConfig = tlsConfig
tr.DisableKeepAlives = true
rawURL = strings.Replace(rawURL, "unix:", "http:", 1)
return true, rawURL, tr
}
func verifyHost(bctx BuiltinContext, host string) error {
if bctx.Capabilities == nil || bctx.Capabilities.AllowNet == nil {
return nil
}
for _, allowed := range bctx.Capabilities.AllowNet {
if allowed == host {
return nil
}
}
return fmt.Errorf("unallowed host: %s", host)
}
func verifyURLHost(bctx BuiltinContext, unverifiedURL string) error {
// Eager return to avoid unnecessary URL parsing
if bctx.Capabilities == nil || bctx.Capabilities.AllowNet == nil {
return nil
}
parsedURL, err := url.Parse(unverifiedURL)
if err != nil {
return err
}
host := strings.Split(parsedURL.Host, ":")[0]
return verifyHost(bctx, host)
}
func createHTTPRequest(bctx BuiltinContext, obj ast.Object) (*http.Request, *http.Client, error) {
var url string
var method string
// Additional CA certificates loading options.
var tlsCaCert []byte
var tlsCaCertEnvVar string
var tlsCaCertFile string
// Client TLS certificate and key options. Each input source
// comes in a matched pair.
var tlsClientCert []byte
var tlsClientKey []byte
var tlsClientCertEnvVar string
var tlsClientKeyEnvVar string
var tlsClientCertFile string
var tlsClientKeyFile string
var tlsServerName string
var body *bytes.Buffer
var rawBody *bytes.Buffer
var enableRedirect bool
var tlsUseSystemCerts *bool
var tlsConfig tls.Config
var customHeaders map[string]interface{}
var tlsInsecureSkipVerify bool
var timeout = defaultHTTPRequestTimeout
for _, val := range obj.Keys() {
key, err := ast.JSON(val.Value)
if err != nil {
return nil, nil, err
}
key = key.(string)
var strVal string
if s, ok := obj.Get(val).Value.(ast.String); ok {
strVal = strings.Trim(string(s), "\"")
} else {
// Most parameters are strings, so consolidate the type checking.
switch key {
case "method",
"url",
"raw_body",
"tls_ca_cert",
"tls_ca_cert_file",
"tls_ca_cert_env_variable",
"tls_client_cert",
"tls_client_cert_file",
"tls_client_cert_env_variable",
"tls_client_key",
"tls_client_key_file",
"tls_client_key_env_variable",
"tls_server_name":
return nil, nil, fmt.Errorf("%q must be a string", key)
}
}
switch key {
case "method":
method = strings.ToUpper(strVal)
case "url":
err := verifyURLHost(bctx, strVal)
if err != nil {
return nil, nil, err
}
url = strVal
case "enable_redirect":
enableRedirect, err = strconv.ParseBool(obj.Get(val).String())
if err != nil {
return nil, nil, err
}
case "body":
bodyVal := obj.Get(val).Value
bodyValInterface, err := ast.JSON(bodyVal)
if err != nil {
return nil, nil, err
}
bodyValBytes, err := json.Marshal(bodyValInterface)
if err != nil {
return nil, nil, err
}
body = bytes.NewBuffer(bodyValBytes)
case "raw_body":
rawBody = bytes.NewBuffer([]byte(strVal))
case "tls_use_system_certs":
tempTLSUseSystemCerts, err := strconv.ParseBool(obj.Get(val).String())
if err != nil {
return nil, nil, err
}
tlsUseSystemCerts = &tempTLSUseSystemCerts
case "tls_ca_cert":
tlsCaCert = []byte(strVal)
case "tls_ca_cert_file":
tlsCaCertFile = strVal
case "tls_ca_cert_env_variable":
tlsCaCertEnvVar = strVal
case "tls_client_cert":
tlsClientCert = []byte(strVal)
case "tls_client_cert_file":
tlsClientCertFile = strVal
case "tls_client_cert_env_variable":
tlsClientCertEnvVar = strVal
case "tls_client_key":
tlsClientKey = []byte(strVal)
case "tls_client_key_file":
tlsClientKeyFile = strVal
case "tls_client_key_env_variable":
tlsClientKeyEnvVar = strVal
case "tls_server_name":
tlsServerName = strVal
case "headers":
headersVal := obj.Get(val).Value
headersValInterface, err := ast.JSON(headersVal)
if err != nil {
return nil, nil, err
}
var ok bool
customHeaders, ok = headersValInterface.(map[string]interface{})
if !ok {
return nil, nil, fmt.Errorf("invalid type for headers key")
}
case "tls_insecure_skip_verify":
tlsInsecureSkipVerify, err = strconv.ParseBool(obj.Get(val).String())
if err != nil {
return nil, nil, err
}
case "timeout":
timeout, err = parseTimeout(obj.Get(val).Value)
if err != nil {
return nil, nil, err
}
case "cache", "caching_mode",
"force_cache", "force_cache_duration_seconds",
"force_json_decode", "force_yaml_decode",
"raise_error": // no-op
default:
return nil, nil, fmt.Errorf("invalid parameter %q", key)
}
}
isTLS := false
client := &http.Client{
Timeout: timeout,
}
if tlsInsecureSkipVerify {
isTLS = true
tlsConfig.InsecureSkipVerify = tlsInsecureSkipVerify
}
if len(tlsClientCert) > 0 && len(tlsClientKey) > 0 {
cert, err := tls.X509KeyPair(tlsClientCert, tlsClientKey)
if err != nil {
return nil, nil, err
}
isTLS = true
tlsConfig.Certificates = append(tlsConfig.Certificates, cert)
}
if tlsClientCertFile != "" && tlsClientKeyFile != "" {
cert, err := tls.LoadX509KeyPair(tlsClientCertFile, tlsClientKeyFile)
if err != nil {
return nil, nil, err
}
isTLS = true
tlsConfig.Certificates = append(tlsConfig.Certificates, cert)
}
if tlsClientCertEnvVar != "" && tlsClientKeyEnvVar != "" {
cert, err := tls.X509KeyPair(
[]byte(os.Getenv(tlsClientCertEnvVar)),
[]byte(os.Getenv(tlsClientKeyEnvVar)))
if err != nil {
return nil, nil, fmt.Errorf("cannot extract public/private key pair from envvars %q, %q: %w",
tlsClientCertEnvVar, tlsClientKeyEnvVar, err)
}
isTLS = true
tlsConfig.Certificates = append(tlsConfig.Certificates, cert)
}
// Use system certs if no CA cert is provided
// or system certs flag is not set
if len(tlsCaCert) == 0 && tlsCaCertFile == "" && tlsCaCertEnvVar == "" && tlsUseSystemCerts == nil {
trueValue := true
tlsUseSystemCerts = &trueValue
}
// Check the system certificates config first so that we
// load additional certificated into the correct pool.
if tlsUseSystemCerts != nil && *tlsUseSystemCerts && runtime.GOOS != "windows" {
pool, err := x509.SystemCertPool()
if err != nil {
return nil, nil, err
}
isTLS = true
tlsConfig.RootCAs = pool
}
if len(tlsCaCert) != 0 {
tlsCaCert = bytes.Replace(tlsCaCert, []byte("\\n"), []byte("\n"), -1)
pool, err := addCACertsFromBytes(tlsConfig.RootCAs, []byte(tlsCaCert))
if err != nil {
return nil, nil, err
}
isTLS = true
tlsConfig.RootCAs = pool
}
if tlsCaCertFile != "" {
pool, err := addCACertsFromFile(tlsConfig.RootCAs, tlsCaCertFile)
if err != nil {
return nil, nil, err
}
isTLS = true
tlsConfig.RootCAs = pool
}
if tlsCaCertEnvVar != "" {
pool, err := addCACertsFromEnv(tlsConfig.RootCAs, tlsCaCertEnvVar)
if err != nil {
return nil, nil, err
}
isTLS = true
tlsConfig.RootCAs = pool
}
if isTLS {
if ok, parsedURL, tr := useSocket(url, &tlsConfig); ok {
client.Transport = tr
url = parsedURL
} else {
tr := http.DefaultTransport.(*http.Transport).Clone()
tr.TLSClientConfig = &tlsConfig
tr.DisableKeepAlives = true
client.Transport = tr
}
} else {
if ok, parsedURL, tr := useSocket(url, nil); ok {
client.Transport = tr
url = parsedURL
}
}
// check if redirects are enabled
if !enableRedirect {
client.CheckRedirect = func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
}
}
if rawBody != nil {
body = rawBody
} else if body == nil {
body = bytes.NewBufferString("")
}
// create the http request, use the builtin context's context to ensure
// the request is cancelled if evaluation is cancelled.
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, nil, err
}
req = req.WithContext(bctx.Context)
// Add custom headers
if len(customHeaders) != 0 {
customHeaders = canonicalizeHeaders(customHeaders)
for k, v := range customHeaders {
header, ok := v.(string)
if !ok {
return nil, nil, fmt.Errorf("invalid type for headers value %q", v)
}
req.Header.Add(k, header)
}
// Don't overwrite or append to one that was set in the custom headers
if _, hasUA := customHeaders["User-Agent"]; !hasUA {
req.Header.Add("User-Agent", version.UserAgent)
}
// If the caller specifies the Host header, use it for the HTTP
// request host and the TLS server name.
if host, hasHost := customHeaders["Host"]; hasHost {
host := host.(string) // We already checked that it's a string.
req.Host = host
// Only default the ServerName if the caller has
// specified the host. If we don't specify anything,
// Go will default to the target hostname. This name
// is not the same as the default that Go populates
// `req.Host` with, which is why we don't just set
// this unconditionally.
tlsConfig.ServerName = host
}
}
if tlsServerName != "" {
tlsConfig.ServerName = tlsServerName
}
if len(bctx.DistributedTracingOpts) > 0 {
client.Transport = tracing.NewTransport(client.Transport, bctx.DistributedTracingOpts)
}
return req, client, nil
}
func executeHTTPRequest(req *http.Request, client *http.Client) (*http.Response, error) {
return client.Do(req)
}
func isContentType(header http.Header, typ ...string) bool {
for _, t := range typ {
if strings.Contains(header.Get("Content-Type"), t) {
return true
}
}
return false
}
// In the BuiltinContext cache we only store a single entry that points to
// our ValueMap which is the "real" http.send() cache.
func getHTTPSendCache(bctx BuiltinContext) *ast.ValueMap {
raw, ok := bctx.Cache.Get(httpSendBuiltinCacheKey)
if !ok {
// Initialize if it isn't there
cache := ast.NewValueMap()
bctx.Cache.Put(httpSendBuiltinCacheKey, cache)
return cache
}
cache, ok := raw.(*ast.ValueMap)
if !ok {
return nil
}
return cache
}
// checkHTTPSendCache checks for the given key's value in the cache
func checkHTTPSendCache(bctx BuiltinContext, key ast.Object) ast.Value {
requestCache := getHTTPSendCache(bctx)
if requestCache == nil {
return nil
}
return requestCache.Get(key)
}
func insertIntoHTTPSendCache(bctx BuiltinContext, key ast.Object, value ast.Value) {
requestCache := getHTTPSendCache(bctx)
if requestCache == nil {
// Should never happen.. if it does just skip caching the value
return
}
requestCache.Put(key, value)
}
// checkHTTPSendInterQueryCache checks for the given key's value in the inter-query cache
func (c *interQueryCache) checkHTTPSendInterQueryCache() (ast.Value, error) {
requestCache := c.bctx.InterQueryBuiltinCache
value, found := requestCache.Get(c.key)
if !found {
return nil, nil
}
c.bctx.Metrics.Counter(httpSendInterQueryCacheHits).Incr()
var cachedRespData *interQueryCacheData
switch v := value.(type) {
case *interQueryCacheValue:
var err error
cachedRespData, err = v.copyCacheData()
if err != nil {
return nil, err
}
case *interQueryCacheData:
cachedRespData = v
default:
return nil, nil
}
headers, err := parseResponseHeaders(cachedRespData.Headers)
if err != nil {
return nil, err
}
// check the freshness of the cached response
if isCachedResponseFresh(c.bctx, headers, c.forceCacheParams) {
return cachedRespData.formatToAST(c.forceJSONDecode, c.forceYAMLDecode)
}
c.httpReq, c.httpClient, err = createHTTPRequest(c.bctx, c.key)
if err != nil {
return nil, handleHTTPSendErr(c.bctx, err)
}
// check with the server if the stale response is still up-to-date.
// If server returns a new response (ie. status_code=200), update the cache with the new response
// If server returns an unmodified response (ie. status_code=304), update the headers for the existing response
result, modified, err := revalidateCachedResponse(c.httpReq, c.httpClient, headers)
requestCache.Delete(c.key)
if err != nil || result == nil {
return nil, err
}
defer result.Body.Close()
if !modified {
// update the headers in the cached response with their corresponding values from the 304 (Not Modified) response
for headerName, values := range result.Header {
cachedRespData.Headers.Del(headerName)
for _, v := range values {
cachedRespData.Headers.Add(headerName, v)
}
}
cachingMode, err := getCachingMode(c.key)
if err != nil {
return nil, err
}
var pcv cache.InterQueryCacheValue
if cachingMode == defaultCachingMode {
pcv, err = cachedRespData.toCacheValue()
if err != nil {
return nil, err
}
} else {
pcv = cachedRespData
}
c.bctx.InterQueryBuiltinCache.Insert(c.key, pcv)
return cachedRespData.formatToAST(c.forceJSONDecode, c.forceYAMLDecode)
}
newValue, respBody, err := formatHTTPResponseToAST(result, c.forceJSONDecode, c.forceYAMLDecode)
if err != nil {
return nil, err
}
if err := insertIntoHTTPSendInterQueryCache(c.bctx, c.key, result, respBody, c.forceCacheParams != nil); err != nil {
return nil, err
}
return newValue, nil
}
// insertIntoHTTPSendInterQueryCache inserts given key and value in the inter-query cache
func insertIntoHTTPSendInterQueryCache(bctx BuiltinContext, key ast.Value, resp *http.Response, respBody []byte, force bool) error {
if resp == nil || (!force && !canStore(resp.Header)) {
return nil
}
requestCache := bctx.InterQueryBuiltinCache
obj, ok := key.(ast.Object)
if !ok {
return fmt.Errorf("interface conversion error")
}
cachingMode, err := getCachingMode(obj)
if err != nil {
return err
}
var pcv cache.InterQueryCacheValue
if cachingMode == defaultCachingMode {
pcv, err = newInterQueryCacheValue(resp, respBody)
} else {
pcv, err = newInterQueryCacheData(resp, respBody)
}
if err != nil {
return err
}
requestCache.Insert(key, pcv)
return nil
}
func createAllowedKeys() {
for _, element := range allowedKeyNames {
allowedKeys.Add(ast.StringTerm(element))
}
}
func parseTimeout(timeoutVal ast.Value) (time.Duration, error) {
var timeout time.Duration
switch t := timeoutVal.(type) {
case ast.Number:
timeoutInt, ok := t.Int64()
if !ok {
return timeout, fmt.Errorf("invalid timeout number value %v, must be int64", timeoutVal)
}
return time.Duration(timeoutInt), nil
case ast.String:
// Support strings without a unit, treat them the same as just a number value (ns)
var err error
timeoutInt, err := strconv.ParseInt(string(t), 10, 64)
if err == nil {
return time.Duration(timeoutInt), nil
}
// Try parsing it as a duration (requires a supported units suffix)
timeout, err = time.ParseDuration(string(t))
if err != nil {
return timeout, fmt.Errorf("invalid timeout value %v: %s", timeoutVal, err)
}
return timeout, nil
default:
return timeout, builtins.NewOperandErr(1, "'timeout' must be one of {string, number} but got %s", ast.TypeName(t))
}
}
func getBoolValFromReqObj(req ast.Object, key *ast.Term) (bool, error) {
var b ast.Boolean
var ok bool
if v := req.Get(key); v != nil {
if b, ok = v.Value.(ast.Boolean); !ok {
return false, fmt.Errorf("invalid value for %v field", key.String())
}
}
return bool(b), nil
}
func getCachingMode(req ast.Object) (cachingMode, error) {
key := ast.StringTerm("caching_mode")
var s ast.String
var ok bool
if v := req.Get(key); v != nil {
if s, ok = v.Value.(ast.String); !ok {
return "", fmt.Errorf("invalid value for %v field", key.String())
}
switch cachingMode(s) {
case defaultCachingMode, cachingModeDeserialized:
return cachingMode(s), nil
default:
return "", fmt.Errorf("invalid value specified for %v field: %v", key.String(), string(s))
}
}
return cachingMode(defaultCachingMode), nil
}
type interQueryCacheValue struct {
Data []byte
}
func newInterQueryCacheValue(resp *http.Response, respBody []byte) (*interQueryCacheValue, error) {
data, err := newInterQueryCacheData(resp, respBody)
if err != nil {
return nil, err
}
b, err := json.Marshal(data)
if err != nil {
return nil, err
}
return &interQueryCacheValue{Data: b}, nil
}
func (cb interQueryCacheValue) SizeInBytes() int64 {
return int64(len(cb.Data))
}
func (cb *interQueryCacheValue) copyCacheData() (*interQueryCacheData, error) {
var res interQueryCacheData
err := util.UnmarshalJSON(cb.Data, &res)
if err != nil {
return nil, err
}
return &res, nil
}
type interQueryCacheData struct {
RespBody []byte
Status string
StatusCode int
Headers http.Header
}
func newInterQueryCacheData(resp *http.Response, respBody []byte) (*interQueryCacheData, error) {
_, err := parseResponseHeaders(resp.Header)
if err != nil {
return nil, err
}
cv := interQueryCacheData{RespBody: respBody,
Status: resp.Status,
StatusCode: resp.StatusCode,
Headers: resp.Header}
return &cv, nil
}
func (c *interQueryCacheData) formatToAST(forceJSONDecode, forceYAMLDecode bool) (ast.Value, error) {
return prepareASTResult(c.Headers, forceJSONDecode, forceYAMLDecode, c.RespBody, c.Status, c.StatusCode)
}
func (c *interQueryCacheData) toCacheValue() (*interQueryCacheValue, error) {
b, err := json.Marshal(c)
if err != nil {
return nil, err
}
return &interQueryCacheValue{Data: b}, nil
}
func (c *interQueryCacheData) SizeInBytes() int64 {
return 0
}
type responseHeaders struct {
date time.Time // origination date and time of response
cacheControl map[string]string // response cache-control header
maxAge deltaSeconds // max-age cache control directive
expires time.Time // date/time after which the response is considered stale
etag string // identifier for a specific version of the response
lastModified string // date and time response was last modified as per origin server
}
// deltaSeconds specifies a non-negative integer, representing
// time in seconds: http://tools.ietf.org/html/rfc7234#section-1.2.1
type deltaSeconds int32
func parseResponseHeaders(headers http.Header) (*responseHeaders, error) {
var err error
result := responseHeaders{}
result.date, err = getResponseHeaderDate(headers)
if err != nil {
return nil, err
}
result.cacheControl = parseCacheControlHeader(headers)
result.maxAge, err = parseMaxAgeCacheDirective(result.cacheControl)
if err != nil {
return nil, err
}
result.expires = getResponseHeaderExpires(headers)
result.etag = headers.Get("etag")
result.lastModified = headers.Get("last-modified")
return &result, nil
}
func revalidateCachedResponse(req *http.Request, client *http.Client, headers *responseHeaders) (*http.Response, bool, error) {
etag := headers.etag
lastModified := headers.lastModified
if etag == "" && lastModified == "" {
return nil, false, nil
}
cloneReq := req.Clone(req.Context())
if etag != "" {
cloneReq.Header.Set("if-none-match", etag)
}
if lastModified != "" {
cloneReq.Header.Set("if-modified-since", lastModified)
}
response, err := client.Do(cloneReq)
if err != nil {
return nil, false, err
}
switch response.StatusCode {
case http.StatusOK:
return response, true, nil
case http.StatusNotModified:
return response, false, nil
}
util.Close(response)
return nil, false, nil
}
func canStore(headers http.Header) bool {
ccHeaders := parseCacheControlHeader(headers)