forked from couchbase/sync_gateway
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
1810 lines (1537 loc) · 50.4 KB
/
util.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 2012-Present Couchbase, Inc.
//
// Use of this software is governed by the Business Source License included
// in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
// in that file, in accordance with the Business Source License, use of this
// software will be governed by the Apache License, Version 2.0, included in
// the file licenses/APL2.txt.
package base
import (
"bytes"
"context"
"crypto/rand"
"crypto/sha1"
"crypto/tls"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"expvar"
"fmt"
"hash/crc32"
"io"
"math"
"net"
"net/http"
"net/url"
"regexp"
"runtime"
"runtime/debug"
"sort"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/couchbase/go-couchbase"
"github.com/couchbase/gomemcached"
"github.com/gorilla/mux"
pkgerrors "github.com/pkg/errors"
"golang.org/x/exp/constraints"
"gopkg.in/couchbaselabs/gocbconnstr.v1"
)
const (
kMaxDeltaTtl = 60 * 60 * 24 * 30
kMaxDeltaTtlDuration = 60 * 60 * 24 * 30 * time.Second
)
// NonCancellableContext is here to stroe a context that is not cancellable. Used to explicitly state when a change from
// a cancellable context to a context withoutr contex is required
type NonCancellableContext struct {
Ctx context.Context
}
// NewNonCancelCtx creates a new background context struct for operations that require a fresh context
func NewNonCancelCtx() NonCancellableContext {
ctxStruct := NonCancellableContext{
Ctx: context.Background(),
}
return ctxStruct
}
// RedactBasicAuthURLUserAndPassword returns the given string, with a redacted HTTP basic auth component.
func RedactBasicAuthURLUserAndPassword(urlIn string) string {
redactedUrl, err := RedactBasicAuthURL(urlIn, false)
if err != nil {
WarnfCtx(context.Background(), "%v", err)
return ""
}
return redactedUrl
}
// RedactBasicAuthURLPassword returns the given string, with a redacted HTTP basic auth password component.
func RedactBasicAuthURLPassword(urlIn string) string {
redactedUrl, err := RedactBasicAuthURL(urlIn, true)
if err != nil {
WarnfCtx(context.Background(), "%v", err)
return ""
}
return redactedUrl
}
func RedactBasicAuthURL(urlIn string, passwordOnly bool) (string, error) {
urlParsed, err := url.Parse(urlIn)
if err != nil {
// err can't be wrapped or logged as it contains unredacted data from the provided url
return "", fmt.Errorf("unable to redact URL, returning empty string")
}
if urlParsed.User != nil {
user := urlParsed.User.Username()
if !passwordOnly {
user = RedactedStr
}
urlParsed.User = url.UserPassword(user, RedactedStr)
}
return urlParsed.String(), nil
}
// GenerateRandomSecret returns a cryptographically-secure 160-bit random number encoded as a hex string.
func GenerateRandomSecret() (string, error) {
val, err := randCryptoHex(160)
if err != nil {
return "", fmt.Errorf("RNG failed, can't create password: %w", err)
}
return val, nil
}
// GenerateRandomID returns a cryptographically-secure 128-bit random number encoded as a hex string.
func GenerateRandomID() (string, error) {
val, err := randCryptoHex(128)
if err != nil {
return "", fmt.Errorf("failed to generate random ID: %w", err)
}
return val, nil
}
// randCryptoHex returns a cryptographically-secure random number of length sizeBits encoded as a hex string.
func randCryptoHex(sizeBits int) (string, error) {
if sizeBits%8 != 0 {
return "", fmt.Errorf("randCryptoHex sizeBits must be a multiple of 8: %d", sizeBits)
}
b := make([]byte, sizeBits/8)
_, err := rand.Read(b)
if err != nil {
return "", err
}
return fmt.Sprintf("%x", b), nil
}
// This is a workaround for an incompatibility between Go's JSON marshaler and CouchDB.
// Go parses JSON numbers into float64 type, and then when it marshals float64 to JSON it uses
// scientific notation if the number is more than six digits long, even if it's an integer.
// However, CouchDB doesn't seem to like scientific notation and throws an exception.
// (See <https://issues.apache.org/jira/browse/COUCHDB-1670>)
// Thus, this function, which walks through a JSON-compatible object and converts float64 values
// to int64 when possible.
// NOTE: This function works on generic map[string]interface{}, but *not* on types based on it,
// like db.Body. Thus, db.Body has a special FixJSONNumbers method -- call that instead.
// TODO: In Go 1.1 we will be able to use a new option in the JSON parser that converts numbers
// to a special number type that preserves the exact formatting.
func FixJSONNumbers(value interface{}) interface{} {
switch value := value.(type) {
case float64:
var asInt int64 = int64(value)
if float64(asInt) == value {
return asInt // Representable as int, so return it as such
}
case map[string]interface{}:
for k, v := range value {
value[k] = FixJSONNumbers(v)
}
case []interface{}:
for i, v := range value {
value[i] = FixJSONNumbers(v)
}
default:
}
return value
}
// Convert a JSON string, which has extra double quotes (eg, `"thing"`) into a normal string
// with the extra double quotes removed (eg "thing"). Normal strings will be returned as-is.
//
// `"thing"` -> "thing"
// "thing" -> "thing"
func ConvertJSONString(s string) string {
var jsonString string
err := JSONUnmarshal([]byte(s), &jsonString)
if err != nil {
return s
} else {
return jsonString
}
}
// ConvertToJSONString takes a string, and returns a JSON string, with any illegal characters escaped.
func ConvertToJSONString(s string) string {
b, _ := JSONMarshal(s)
return string(b)
}
// Concatenates and merges multiple string arrays into one, discarding all duplicates (including
// duplicates within a single array.) Ordering is preserved.
func MergeStringArrays(arrays ...[]string) (merged []string) {
seen := make(map[string]bool)
for _, array := range arrays {
for _, str := range array {
if !seen[str] {
seen[str] = true
merged = append(merged, str)
}
}
}
return
}
func ToArrayOfInterface(arrayOfString []string) []interface{} {
arrayOfInterface := make([]interface{}, len(arrayOfString))
for i, v := range arrayOfString {
arrayOfInterface[i] = v
}
return arrayOfInterface
}
func ToInt64(value interface{}) (int64, bool) {
switch value := value.(type) {
case int64:
return value, true
case float64:
return int64(value), true
case int:
return int64(value), true
case json.Number:
if n, err := value.Int64(); err == nil {
return n, true
}
}
return 0, false
}
func CouchbaseUrlWithAuth(serverUrl, username, password, bucketname string) (string, error) {
// parse url and reconstruct it piece by piece
u, err := url.Parse(serverUrl)
if err != nil {
return "", pkgerrors.WithStack(RedactErrorf("Error parsing serverUrl: %v. Error: %v", MD(serverUrl), err))
}
userPass := bytes.Buffer{}
addedUsername := false
// do we have a username? if so add it
if username != "" {
userPass.WriteString(username)
addedUsername = true
} else {
// do we have a non-default bucket name? if so, use that as the username
if bucketname != "" && bucketname != "default" {
userPass.WriteString(bucketname)
addedUsername = true
}
}
if addedUsername {
if password != "" {
userPass.WriteString(":")
userPass.WriteString(password)
}
}
if addedUsername {
return fmt.Sprintf(
"%v://%v@%v%v",
u.Scheme,
userPass.String(),
u.Host,
u.Path,
), nil
} else {
// just return the original
return serverUrl, nil
}
}
// This transforms raw input bucket credentials (for example, from config), to input
// credentials expected by Couchbase server, based on a few rules
func TransformBucketCredentials(inputUsername, inputPassword, inputBucketname string) (username, password, bucketname string) {
username = inputUsername
password = inputPassword
// If the username is empty then set the username to the bucketname.
if inputUsername == "" {
username = inputBucketname
}
// if the username is empty, then the password should be empty too
if username == "" {
password = ""
}
return username, password, inputBucketname
}
func IsPowerOfTwo(n uint16) bool {
return (n & (n - 1)) == 0
}
// This is how Couchbase Server handles document expiration times
//
// The actual value sent may either be
// Unix time (number of seconds since January 1, 1970, as a 32-bit
// value), or a number of seconds starting from current time. In the
// latter case, this number of seconds may not exceed 60*60*24*30 (number
// of seconds in 30 days); if the number sent by a client is larger than
// that, the server will consider it to be real Unix time value rather
// than an offset from current time.
// DurationToCbsExpiry takes a ttl as a Duration and returns an int
// formatted as required by CBS expiry processing
func DurationToCbsExpiry(ttl time.Duration) uint32 {
if ttl <= kMaxDeltaTtlDuration {
return uint32(ttl.Seconds())
} else {
return uint32(time.Now().Add(ttl).Unix())
}
}
// SecondsToCbsExpiry takes a ttl in seconds and returns an int
// formatted as required by CBS expiry processing
func SecondsToCbsExpiry(ttl int) uint32 {
return DurationToCbsExpiry(time.Duration(ttl) * time.Second)
}
// CbsExpiryToTime takes a CBS expiry and returns as a time
func CbsExpiryToTime(expiry uint32) time.Time {
if expiry <= kMaxDeltaTtl {
return time.Now().Add(time.Duration(expiry) * time.Second)
} else {
return time.Unix(int64(expiry), 0)
}
}
// CbsExpiryToDuration takes a CBS expiry and returns as a duration
func CbsExpiryToDuration(expiry uint32) time.Duration {
if expiry <= kMaxDeltaTtl {
return time.Duration(expiry) * time.Second
} else {
expiryTime := time.Unix(int64(expiry), 0)
return time.Until(expiryTime)
}
}
// ReflectExpiry attempts to convert expiry from one of the following formats to a Couchbase Server expiry value:
// 1. Numeric JSON values are converted to uint32 and returned as-is
// 2. JSON numbers are converted to uint32 and returned as-is
// 3. String JSON values that are numbers are converted to int32 and returned as-is
// 4. String JSON values that are ISO-8601 dates are converted to UNIX time and returned
// 5. Null JSON values return 0
func ReflectExpiry(rawExpiry interface{}) (*uint32, error) {
switch expiry := rawExpiry.(type) {
case int64:
return ValidateUint32Expiry(expiry)
case float64:
return ValidateUint32Expiry(int64(expiry))
case json.Number:
// Attempt to convert to int
expInt, err := expiry.Int64()
if err != nil {
return nil, err
}
return ValidateUint32Expiry(expInt)
case string:
// First check if it's a numeric string
expInt, err := strconv.ParseInt(expiry, 10, 32)
if err == nil {
return ValidateUint32Expiry(expInt)
}
// Check if it's an ISO-8601 date
expRFC3339, err := time.Parse(time.RFC3339, expiry)
if err == nil {
return ValidateUint32Expiry(expRFC3339.Unix())
} else {
return nil, pkgerrors.Wrapf(err, "Unable to parse expiry %s as either numeric or date expiry", rawExpiry)
}
case nil:
// Leave as zero/empty expiry
return nil, nil
default:
return nil, fmt.Errorf("Unrecognized expiry format")
}
}
func ValidateUint32Expiry(expiry int64) (*uint32, error) {
if expiry < 0 || expiry > math.MaxUint32 {
return nil, fmt.Errorf("Expiry value is not within valid range: %d", expiry)
}
uint32Expiry := uint32(expiry)
return &uint32Expiry, nil
}
// Needed due to https://github.com/couchbase/sync_gateway/issues/1345
func AddDbPathToCookie(rq *http.Request, cookie *http.Cookie) {
// "/db/foo" -> "db/foo"
urlPathWithoutLeadingSlash := strings.TrimPrefix(rq.URL.Path, "/")
dbPath := "/"
pathComponents := strings.Split(urlPathWithoutLeadingSlash, "/")
if len(pathComponents) > 0 && pathComponents[0] != "" {
dbPath = fmt.Sprintf("/%v", pathComponents[0])
}
cookie.Path = dbPath
}
// A retry sleeper is called back by the retry loop and passed
// the current retryCount, and should return the amount of milliseconds
// that the retry should sleep.
type RetrySleeper func(retryCount int) (shouldContinue bool, timeTosleepMs int)
// A RetryWorker encapsulates the work being done in a Retry Loop. The shouldRetry
// return value determines whether the worker will retry, regardless of the err value.
// If the worker has exceeded it's retry attempts, then it will not be called again
// even if it returns shouldRetry = true.
type RetryWorker func() (shouldRetry bool, err error, value interface{})
type RetryCasWorker func() (shouldRetry bool, err error, value uint64)
type RetryTimeoutError struct {
description string
attempts int
}
func NewRetryTimeoutError(description string, attempts int) *RetryTimeoutError {
return &RetryTimeoutError{
description: description,
attempts: attempts,
}
}
func (r *RetryTimeoutError) Error() string {
return fmt.Sprintf("RetryLoop for %v giving up after %v attempts", r.description, r.attempts)
}
func RetryLoop(description string, worker RetryWorker, sleeper RetrySleeper) (error, interface{}) {
return RetryLoopCtx(description, worker, sleeper, context.Background())
}
func RetryLoopCtx(description string, worker RetryWorker, sleeper RetrySleeper, ctx context.Context) (error, interface{}) {
numAttempts := 1
for {
shouldRetry, err, value := worker()
if !shouldRetry {
if err != nil {
return err, nil
}
return nil, value
}
shouldContinue, sleepMs := sleeper(numAttempts)
if !shouldContinue {
if err == nil {
err = NewRetryTimeoutError(description, numAttempts)
}
WarnfCtx(ctx, "RetryLoop for %v giving up after %v attempts", description, numAttempts)
return err, value
}
DebugfCtx(ctx, KeyAll, "RetryLoop retrying %v after %v ms.", description, sleepMs)
select {
case <-ctx.Done():
return fmt.Errorf("Retry loop for %v closed based on context", description), nil
case <-time.After(time.Millisecond * time.Duration(sleepMs)):
}
numAttempts += 1
}
}
// A version of RetryLoop that returns a strongly typed cas as uint64, to avoid interface conversion overhead for
// high throughput operations.
func RetryLoopCas(description string, worker RetryCasWorker, sleeper RetrySleeper) (error, uint64) {
numAttempts := 1
for {
shouldRetry, err, value := worker()
if !shouldRetry {
if err != nil {
return err, value
}
return nil, value
}
shouldContinue, sleepMs := sleeper(numAttempts)
if !shouldContinue {
if err == nil {
err = NewRetryTimeoutError(description, numAttempts)
}
WarnfCtx(context.Background(), "RetryLoopCas for %v giving up after %v attempts", description, numAttempts)
return err, value
}
DebugfCtx(context.Background(), KeyAll, "RetryLoopCas retrying %v after %v ms.", description, sleepMs)
<-time.After(time.Millisecond * time.Duration(sleepMs))
numAttempts += 1
}
}
// SleeperFuncCtx wraps the given RetrySleeper with a context, so it can be cancelled, or have a deadline.
func SleeperFuncCtx(sleeperFunc RetrySleeper, ctx context.Context) RetrySleeper {
return func(retryCount int) (bool, int) {
if err := ctx.Err(); err != nil {
return false, -1
}
return sleeperFunc(retryCount)
}
}
// Create a RetrySleeper that will double the retry time on every iteration and
// use the given parameters.
// The longest wait time can be calculated with: initialTimeToSleepMs * 2^maxNumAttempts
// The total wait time can be calculated with: initialTimeToSleepMs * 2^maxNumAttempts+1
func CreateDoublingSleeperFunc(maxNumAttempts, initialTimeToSleepMs int) RetrySleeper {
timeToSleepMs := initialTimeToSleepMs
sleeper := func(numAttempts int) (bool, int) {
if numAttempts > maxNumAttempts {
return false, -1
}
if numAttempts > 1 {
timeToSleepMs *= 2
}
return true, timeToSleepMs
}
return sleeper
}
// Create a RetrySleeper that will double the retry time on every iteration with
// initial sleep time and a total max wait no longer than maxWait
func CreateDoublingSleeperDurationFunc(initialTimeToSleepMs int, maxWait time.Duration) RetrySleeper {
timeToSleepMs := initialTimeToSleepMs
startTime := time.Now()
sleeper := func(numAttempts int) (bool, int) {
totalWait := time.Since(startTime)
if totalWait > maxWait {
return false, -1
}
if numAttempts > 1 {
timeToSleepMs *= 2
}
// If next sleep time would take us past maxWait, only sleep for required amount
timeRemainingMs := int((maxWait - totalWait).Milliseconds())
if timeRemainingMs < timeToSleepMs {
return true, timeRemainingMs
}
return true, timeToSleepMs
}
return sleeper
}
// Create a sleeper function that sleeps up to maxNumAttempts, sleeping timeToSleepMs each attempt
func CreateSleeperFunc(maxNumAttempts, timeToSleepMs int) RetrySleeper {
sleeper := func(numAttempts int) (bool, int) {
if numAttempts > maxNumAttempts {
return false, -1
}
return true, timeToSleepMs
}
return sleeper
}
// Create a RetrySleeper that will double the retry time on every iteration, with each sleep not exceeding maxSleepPerRetryMs.
func CreateMaxDoublingSleeperFunc(maxNumAttempts, initialTimeToSleepMs int, maxSleepPerRetryMs int) RetrySleeper {
timeToSleepMs := initialTimeToSleepMs
sleeper := func(numAttempts int) (bool, int) {
if numAttempts > maxNumAttempts {
return false, -1
}
if numAttempts > 1 {
timeToSleepMs *= 2
if timeToSleepMs > maxSleepPerRetryMs {
timeToSleepMs = maxSleepPerRetryMs
}
}
return true, timeToSleepMs
}
return sleeper
}
// CreateIndefiniteMaxDoublingSleeperFunc is similar to CreateMaxDoublingSleeperFunc, with the exception that there is no number of maximum retries.
func CreateIndefiniteMaxDoublingSleeperFunc(initialTimeToSleepMs int, maxSleepPerRetryMs int) RetrySleeper {
timeToSleepMs := initialTimeToSleepMs
sleeper := func(numAttempts int) (bool, int) {
timeToSleepMs *= 2
if timeToSleepMs > maxSleepPerRetryMs {
timeToSleepMs = maxSleepPerRetryMs
}
return true, timeToSleepMs
}
return sleeper
}
// SortedUint64Slice attaches the methods of sort.Interface to []uint64, sorting in increasing order.
type SortedUint64Slice []uint64
func (s SortedUint64Slice) Len() int { return len(s) }
func (s SortedUint64Slice) Less(i, j int) bool { return s[i] < s[j] }
func (s SortedUint64Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// Sort is a convenience method.
func (s SortedUint64Slice) Sort() {
sort.Sort(s)
}
func WriteHistogram(expvarMap *expvar.Map, since time.Time, prefix string) {
WriteHistogramForDuration(expvarMap, time.Since(since), prefix)
}
func WriteHistogramForDuration(expvarMap *expvar.Map, duration time.Duration, prefix string) {
if LogDebugEnabled(KeyAll) {
var durationMs int
if duration < 1*time.Second {
durationMs = int(duration/(100*time.Millisecond)) * 100
} else {
durationMs = int(duration/(1000*time.Millisecond)) * 1000
}
expvarMap.Add(fmt.Sprintf("%s-%06dms", prefix, durationMs), 1)
}
}
/*
* Returns a URL formatted string which excludes the path, query and fragment
* This is used by _replicate to split the single URL passed in a CouchDB style
* request into a source URL and a database name as used in sg_replicate
*/
func SyncSourceFromURL(u *url.URL) string {
var buf bytes.Buffer
if u.Scheme != "" {
buf.WriteString(u.Scheme)
buf.WriteByte(':')
}
if u.Scheme != "" || u.Host != "" || u.User != nil {
buf.WriteString("//")
if ui := u.User; ui != nil {
buf.WriteString(ui.String())
buf.WriteByte('@')
}
if h := u.Host; h != "" {
buf.WriteString(h)
}
}
return buf.String()
}
// Convert string or array into a string array, otherwise return nil. If
// the input slice contains entries of mixed type, all string entries would
// be collected and returned as a slice and non-string entries as another.
func ValueToStringArray(value interface{}) ([]string, []interface{}) {
var nonStrings []interface{}
switch valueType := value.(type) {
case string:
return []string{valueType}, nil
case []string:
return valueType, nil
case []interface{}:
result := make([]string, 0, len(valueType))
for _, item := range valueType {
if str, ok := item.(string); ok {
result = append(result, str)
} else {
nonStrings = append(nonStrings, item)
}
}
return result, nonStrings
default:
nonStrings = append(nonStrings, valueType)
return nil, nonStrings
}
}
// SanitizeRequestURL will return a sanitised string of the URL by:
// - Tagging mux path variables.
// - Tagging query parameters.
// - Replacing sensitive data from the URL query string with ******.
// Have to use string replacement instead of writing directly to the Values URL object, as only the URL's raw query is mutable.
func SanitizeRequestURL(req *http.Request, cachedQueryValues *url.Values) string {
// Populate a cached copy of query values if nothing is passed in.
if cachedQueryValues == nil {
v := req.URL.Query()
cachedQueryValues = &v
}
urlString := sanitizeRequestURLQueryParams(req.URL.String(), *cachedQueryValues)
if RedactSystemData || RedactMetadata || RedactUserData {
tagQueryParams(*cachedQueryValues, &urlString)
tagPathVars(req, &urlString)
}
return urlString
}
// redactedPathVars is a lookup map of path variables to redaction types.
var redactedPathVars = map[string]string{
"docid": "UD",
"attach": "UD",
"name": "UD",
"channel": "UD",
// MD redaction is not yet supported.
// "db": "MD",
// "newdb": "MD",
// "ddoc": "MD",
// "view": "MD",
// "sessionid": "MD",
}
// tagPathVars will tag all redactble path variables in the urlString for the given request.
func tagPathVars(req *http.Request, urlString *string) {
if urlString == nil || req == nil {
return
}
str := *urlString
pathVars := mux.Vars(req)
for k, v := range pathVars {
switch redactedPathVars[k] {
case "UD":
str = replaceLast(str, "/"+v, "/"+UD(v).Redact())
case "MD":
str = replaceLast(str, "/"+v, "/"+MD(v).Redact())
case "SD":
str = replaceLast(str, "/"+v, "/"+SD(v).Redact())
}
}
*urlString = str
}
// replaceLast replaces the last instance of search in s with replacement.
func replaceLast(s, search, replacement string) string {
idx := strings.LastIndex(s, search)
if idx == -1 {
return s
}
return s[:idx] + replacement + s[idx+len(search):]
}
// redactedQueryParams is a lookup map of query params to redaction types.
var redactedQueryParams = map[string]string{
"channels": "UD", // updateChangesOptionsFromQuery, handleChanges
"doc_ids": "UD", // updateChangesOptionsFromQuery, handleChanges
"startkey": "UD", // handleAllDocs
"endkey": "UD", // handleAllDocs
// MD redaction is not yet supported.
// "since": "MD", // handleDumpChannel, updateChangesOptionsFromQuery, handleChanges
// "rev": "MD", // handleGetDoc, handlePutDoc, handleDeleteDoc, handleDelLocalDoc, handleGetAttachment, handlePutAttachment
// "open_revs": "MD", // handleGetDoc
}
func tagQueryParams(values url.Values, urlString *string) {
if urlString == nil || len(values) == 0 {
return
}
str := *urlString
str, _ = url.QueryUnescape(str)
for k, vals := range values {
// Query params can have more than one value (i.e: foo=bar&foo=buz)
for _, v := range vals {
switch redactedQueryParams[k] {
case "UD":
str = strings.Replace(str, fmt.Sprintf("%s=%s", k, v), fmt.Sprintf("%s=%s", k, UD(v).Redact()), 1)
case "MD":
str = strings.Replace(str, fmt.Sprintf("%s=%s", k, v), fmt.Sprintf("%s=%s", k, MD(v).Redact()), 1)
case "SD":
str = strings.Replace(str, fmt.Sprintf("%s=%s", k, v), fmt.Sprintf("%s=%s", k, SD(v).Redact()), 1)
}
}
}
*urlString = str
}
// sanitizeRequestURLQueryParams replaces sensitive data from the URL query string with ******.
func sanitizeRequestURLQueryParams(urlStr string, values url.Values) string {
if urlStr == "" || len(values) == 0 {
return urlStr
}
// Do a basic contains for the values we care about, to minimize performance impact on other requests.
if strings.Contains(urlStr, "code=") || strings.Contains(urlStr, "token=") {
// Iterate over the URL values looking for matches, and then do a string replacement of the found value
// into urlString. Need to unescapte the urlString, as the values returned by URL.Query() get unescaped.
urlStr, _ = url.QueryUnescape(urlStr)
for key, vals := range values {
if key == "code" || strings.Contains(key, "token") {
// In case there are multiple entries
for _, val := range vals {
urlStr = strings.Replace(urlStr, fmt.Sprintf("%s=%s", key, val), fmt.Sprintf("%s=******", key), -1)
}
}
}
}
return urlStr
}
// StdlibDurationPtr returns a pointer to the given time.Duration literal.
func StdlibDurationPtr(value time.Duration) *time.Duration {
return &value
}
// DurationPtr returns a pointer to the given ConfigDuration literal.
func DurationPtr(value ConfigDuration) *ConfigDuration {
return &value
}
// LogLevelPtr returns a pointer to the given LogLevel literal.
func LogLevelPtr(value LogLevel) *LogLevel {
return &value
}
// StringPtr returns a pointer to the given string literal.
func StringPtr(value string) *string {
return &value
}
// StringDefault returns ifNil if s is nil, or else returns dereferenced value of s
func StringDefault(s *string, ifNil string) string {
if s != nil {
return *s
}
return ifNil
}
// Uint16Ptr returns a pointer to the given uint16 literal.
func Uint16Ptr(u uint16) *uint16 {
return &u
}
// Uint32Ptr returns a pointer to the given uint32 literal.
func Uint32Ptr(u uint32) *uint32 {
return &u
}
// Uint64Ptr returns a pointer to the given uint64 literal.
func Uint64Ptr(u uint64) *uint64 {
return &u
}
// UintPtr returns a pointer to the given uint literal.
func UintPtr(u uint) *uint {
return &u
}
// IntPtr returns a pointer to the given int literal.
func IntPtr(i int) *int {
return &i
}
// BoolPtr returns a pointer to the given bool literal.
func BoolPtr(b bool) *bool {
return &b
}
// BoolDefault returns ifNil if b is nil, or else returns dereferenced value of b
func BoolDefault(b *bool, ifNil bool) bool {
if b != nil {
return *b
}
return ifNil
}
func Float32Ptr(f float32) *float32 {
return &f
}
// Convert a Bucket, or a Couchbase URI (eg, couchbase://host1,host2) to a list of HTTP URLs with ports (eg, ["http://host1:8091", "http://host2:8091"])
// connSpec can be optionally passed in if available, to prevent unnecessary double-parsing of connstr
// Primary use case is for backwards compatibility with go-couchbase, cbdatasource, and CBGT. Supports secure URI's as well (couchbases://).
// Related CBGT ticket: https://issues.couchbase.com/browse/MB-25522
func CouchbaseURIToHttpURL(bucket Bucket, couchbaseUri string, connSpec *gocbconnstr.ConnSpec) (httpUrls []string, err error) {
// If we're using a couchbase bucket, use the bucket to retrieve the mgmt endpoints.
cbBucket, ok := AsCouchbaseBucketStore(bucket)
if ok {
return cbBucket.MgmtEps()
}
// No bucket-based handling, fall back to URI parsing
// First try to do a simple URL parse, which will only work for http:// and https:// urls where there
// is a single host. If that works, return the result
singleHttpUrl := SingleHostCouchbaseURIToHttpURL(couchbaseUri)
if len(singleHttpUrl) > 0 {
return []string{singleHttpUrl}, nil
}
// Parse the given URI if we've not already got a connSpec
if connSpec == nil {
// Unable to do simple URL parse, try to parse into components w/ gocbconnstr
newConnSpec, errParse := gocbconnstr.Parse(couchbaseUri)
if errParse != nil {
return httpUrls, pkgerrors.WithStack(RedactErrorf("Error parsing gocb connection string: %v. Error: %v", MD(couchbaseUri), errParse))
}
connSpec = &newConnSpec
}
return connSpecToHTTPURLs(*connSpec)
}
func connSpecToHTTPURLs(connSpec gocbconnstr.ConnSpec) (httpUrls []string, err error) {
for _, address := range connSpec.Addresses {
// Determine port to use for management API
port := gocbconnstr.DefaultHttpPort
translatedScheme := "http"
switch connSpec.Scheme {
case "couchbase":
fallthrough
case "couchbases":
return nil, RedactErrorf("couchbase:// and couchbases:// URI schemes can only be used with GoCB buckets.")
case "https":
translatedScheme = "https"
}
if address.Port > 0 {
port = address.Port
} else {
// If gocbconnstr didn't return a port, and it was detected to be an HTTPS connection,
// change the port to the secure port 18091
if translatedScheme == "https" {
port = 18091
}
}
httpUrl := fmt.Sprintf("%s://%s:%d", translatedScheme, address.Host, port)
httpUrls = append(httpUrls, httpUrl)
}
return httpUrls, nil
}
// Add auth credentials to the given urls, since CBGT cannot take auth handlers in certain API calls yet
func ServerUrlsWithAuth(urls []string, spec BucketSpec) (urlsWithAuth []string, err error) {
urlsWithAuth = make([]string, len(urls))
username, password, bucketName := spec.Auth.GetCredentials()
for i, url := range urls {
urlWithAuth, err := CouchbaseUrlWithAuth(
url,
username,
password,
bucketName,
)
if err != nil {
return urlsWithAuth, err
}
urlsWithAuth[i] = urlWithAuth
}
return urlsWithAuth, nil
}
// Special case for couchbaseUri strings that contain a single host with http:// or https:// schemes,
// possibly containing embedded basic auth. Needed since gocbconnstr.Parse() will remove embedded
// basic auth from URLS.
func SingleHostCouchbaseURIToHttpURL(couchbaseUri string) (httpUrl string) {
result, parseUrlErr := couchbase.ParseURL(couchbaseUri)
// If there was an error parsing, return an empty string
if parseUrlErr != nil {
return ""
}
// If the host contains a "," then it parsed http://host1,host2 into a url with "host1,host2" as the host, which
// is not going to work. Return an empty string
if strings.Contains(result.Host, ",") {
return ""
}
// The scheme was couchbase://, but this method only deals with non-couchbase schemes, so return empty slice
if strings.Contains(result.Scheme, "couchbase") {
return ""
}