forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sanitize_json.go
68 lines (58 loc) · 1.59 KB
/
sanitize_json.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
package ui
import (
"bytes"
"encoding/json"
"fmt"
"regexp"
)
// tokenEndpoint is explicitly excluded from sanitization
const tokenEndpoint = "token_endpoint"
var keysToSanitize = regexp.MustCompile("(?i)token|password")
var sanitizeURIParams = regexp.MustCompile(`([&?]password)=[A-Za-z0-9\-._~!$'()*+,;=:@/?]*`)
var sanitizeURLPassword = regexp.MustCompile(`([\d\w]+):\/\/([^:]+):(?:[^@]+)@`)
func SanitizeJSON(raw []byte) ([]byte, error) {
var result interface{}
decoder := json.NewDecoder(bytes.NewBuffer(raw))
decoder.UseNumber()
err := decoder.Decode(&result)
if err != nil {
return nil, err
}
sanitized := iterateAndRedact(result)
buff := new(bytes.Buffer)
encoder := json.NewEncoder(buff)
encoder.SetEscapeHTML(false)
encoder.SetIndent("", " ")
err = encoder.Encode(sanitized)
if err != nil {
return nil, err
}
return buff.Bytes(), nil
}
func iterateAndRedact(blob interface{}) interface{} {
switch v := blob.(type) {
case string:
return sanitizeURL(v)
case []interface{}:
var list []interface{}
for _, val := range v {
list = append(list, iterateAndRedact(val))
}
return list
case map[string]interface{}:
for key, value := range v {
if keysToSanitize.MatchString(key) && key != tokenEndpoint {
v[key] = RedactedValue
} else {
v[key] = iterateAndRedact(value)
}
}
return v
}
return blob
}
func sanitizeURL(rawURL string) string {
sanitized := sanitizeURLPassword.ReplaceAllString(rawURL, fmt.Sprintf("$1://$2:%s@", RedactedValue))
sanitized = sanitizeURIParams.ReplaceAllString(sanitized, fmt.Sprintf("$1=%s", RedactedValue))
return sanitized
}