-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsanitize.go
More file actions
184 lines (177 loc) · 4.11 KB
/
sanitize.go
File metadata and controls
184 lines (177 loc) · 4.11 KB
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
// Package sanitize provides functions to sanitize (anonymize) certain string
// fields of arbitrary json messages.
//
// Note that the main use case for this package is handling of opaque json
// messages, not anything with the known structure, which is better handled
// explicitly by sanitizing data and then marshaling sanitized representation.
package sanitize
import (
"bufio"
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"strconv"
)
var errInvalidArguents = errors.New("sanitize: fn cannot not be nil")
// Stream sanitizes json payload read from r writing result to w. fn must be
// a non-nil FieldFunc called on each string key/value pair of json payload.
//
// For already allocated messages it is more effective to use Message function.
func Stream(w io.Writer, r io.Reader, fn FieldFunc) error {
if fn == nil {
return errInvalidArguents
}
bw := bufio.NewWriter(w)
defer bw.Flush()
dec := json.NewDecoder(r)
dec.UseNumber()
var ds []rune // stack of separators
var cnt int
var sanitize bool
var prevDelim byte
var key string
for {
var delim byte = comma
t, err := dec.Token()
if err == io.EOF {
return bw.Flush()
}
if err != nil {
return err
}
switch v := t.(type) {
case string:
if sanitize && prevDelim == ':' {
if val, ok := fn(key, v); ok {
v = val
}
sanitize = false
}
if cnt%2 != 0 && len(ds) > 0 && ds[len(ds)-1] == '{' {
delim = colon
key = v
sanitize = true
}
bw.WriteByte('"')
writeEscapedString(bw, v)
bw.WriteByte('"')
case bool:
if v {
bw.WriteString("true")
} else {
bw.WriteString("false")
}
case json.Delim:
switch v {
case '{', '[':
ds = append(ds, rune(v))
case '}', ']':
if len(ds) > 0 {
ds = ds[:len(ds)-1]
}
}
cnt = 0
prevDelim = 0
bw.WriteRune(rune(v))
case json.Number:
bw.WriteString(string(v))
case nil:
bw.WriteString("null")
default:
return fmt.Errorf("unknown json token: %v", v)
}
cnt++
if dec.More() {
if v, ok := t.(json.Delim); !ok || v == '}' || v == ']' {
prevDelim = delim
bw.WriteByte(delim)
}
}
}
}
// FieldFunc is called on each string attribute of JSON object processed by
// MessageFunc. Arguments provided are key/value pair of JSON payload, if
// function returns true for mask, attribute value is substituted by
// newValue.
type FieldFunc func(key, value string) (newValue string, mask bool)
// Message sanitizes json payload from src and returns its sanitized
// representation. If dst is non-nil, it is used as a scratch buffer to reduce
// allocations. fn must be a non-nil FieldFunc called on each string key/value
// pair of json payload.
func Message(dst, src []byte, fn FieldFunc) ([]byte, error) {
if fn == nil {
return nil, errInvalidArguents
}
if len(dst) > 0 {
dst = dst[:0]
}
dec := json.NewDecoder(bytes.NewReader(src))
dec.UseNumber()
var ds []rune // stack of separators
var cnt int
var sanitize bool
var prevDelim byte
var key string
for {
var delim byte = comma
t, err := dec.Token()
if err == io.EOF {
return dst, nil
}
if err != nil {
return nil, err
}
switch v := t.(type) {
case string:
if sanitize && prevDelim == ':' {
if val, ok := fn(key, v); ok {
v = val
}
sanitize = false
}
if cnt%2 != 0 && len(ds) > 0 && ds[len(ds)-1] == '{' {
delim = colon
key = v
sanitize = true
}
dst = append(dst, '"')
dst = appendEscapedString(dst, v)
dst = append(dst, '"')
case bool:
dst = strconv.AppendBool(dst, v)
case json.Delim:
switch v {
case '{', '[':
ds = append(ds, rune(v))
case '}', ']':
if len(ds) > 0 {
ds = ds[:len(ds)-1]
}
}
cnt = 0
prevDelim = 0
dst = append(dst, byte(v))
case json.Number:
dst = append(dst, string(v)...)
case nil:
dst = append(dst, "null"...)
default:
return nil, fmt.Errorf("unknown json token: %v", v)
}
cnt++
if dec.More() {
if v, ok := t.(json.Delim); !ok || v == '}' || v == ']' {
prevDelim = delim
dst = append(dst, delim)
}
}
}
}
// Mask is a placeholder to replace sensitive fields
const Mask = "********"
const (
comma = ','
colon = ':'
)