/
sanitizer.go
313 lines (265 loc) · 6.64 KB
/
sanitizer.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
package values
import (
"fmt"
"regexp"
"strconv"
"strings"
"time"
"github.com/cortezaproject/corteza-server/pkg/expr"
"github.com/cortezaproject/corteza-server/pkg/logger"
"github.com/microcosm-cc/bluemonday"
"go.uber.org/zap"
"github.com/cortezaproject/corteza-server/compose/types"
)
type (
sanitizer struct{}
)
// Sanitizer initializes sanitizer
//
// Not really needed, following pattern in the package
func Sanitizer() *sanitizer {
return &sanitizer{}
}
// Run cleans up input data
// - fix multi-value order/place index
// - trim all the strings!
// - parse & format input values to match field specific -- nullify/falsify invalid
// - field kind specific, no errors raised, data is modified
//
// Existing data (when updating record) is not yet loaded at this point
func (s sanitizer) Run(m *types.Module, vv types.RecordValueSet) (out types.RecordValueSet) {
var (
exprParser = expr.Parser()
)
out = make([]*types.RecordValue, 0, len(vv))
for _, f := range m.Fields {
// Reorder and sanitize place value (no gaps)
//
// Values are ordered when received so we treat them like it
// and assign the appropriate place no.
var i = 0
for _, v := range vv.FilterByName(f.Name) {
if v.IsDeleted() {
continue
}
c := v.Clone()
c.Place = uint(i)
out = append(out, c)
i++
}
}
var (
f *types.ModuleField
kind string
log = logger.Default().
WithOptions(zap.AddStacktrace(zap.PanicLevel)).
With(zap.Uint64("module", m.ID))
)
for _, v := range out {
f = m.Fields.FindByName(v.Name)
if f == nil {
// Unknown field,
// if it is not handled before,
// sanitizer does not care about it
continue
}
if f.Expressions.ValueExpr != "" {
// do not do any sanitization if field has value expression!
continue
}
if v.IsDeleted() || !v.Updated {
// Ignore unchanged and deleted
continue
}
kind = strings.ToLower(f.Kind)
if len(f.Expressions.Sanitizers) > 0 {
for _, expr := range f.Expressions.Sanitizers {
rval, err := exprParser.Evaluate(expr, map[string]interface{}{"value": v.Value})
if err != nil {
log.Error(
"failed to evaluate sanitizer expression",
zap.String("field", f.Name),
zap.String("expr", expr),
zap.Error(err),
)
continue
}
v.Value = sanitize(f, rval)
}
}
if kind != "string" {
// Trim all but string
v.Value = strings.TrimSpace(v.Value)
}
if f.IsRef() {
if refy.MatchString(v.Value) {
v.Ref, _ = strconv.ParseUint(v.Value, 10, 64)
}
if v.Ref == 0 {
v.Value = ""
}
}
// Per field type validators
switch kind {
case "bool":
v.Value = sBool(v.Value)
case "datetime":
v.Value = sDatetime(v.Value, f.Options.Bool("onlyDate"), f.Options.Bool("onlyTime"))
case "number":
v.Value = sNumber(v.Value, f.Options.Precision())
case "string":
v.Value = sString(v.Value)
// Uncomment when they become relevant for sanitization
//case "email":
// v = s.sEmail(v, f, m)
//case "file":
// v = s.sFile(v, f, m)
//case "record":
// v = s.sRecord(v, f, m)
//case "select":
// v = s.sSelect(v, f, m)
//case "url":
// v = s.sUrl(v, f, m)
//case "user":
// v = s.sUser(v, f, m)
}
}
return
}
func (s sanitizer) RunXSS(m *types.Module, vv types.RecordValueSet) types.RecordValueSet {
var (
f *types.ModuleField
)
for _, v := range vv {
f = m.Fields.FindByName(v.Name)
if f == nil {
// Unknown field,
// if it is not handled before,
// sanitizer does not care about it
continue
}
switch strings.ToLower(f.Kind) {
case "string":
v.Value = sString(v.Value)
}
}
return vv
}
func sBool(v interface{}) string {
switch c := v.(type) {
case bool:
if c {
return strBoolTrue
}
case string:
if truthy.MatchString(strings.ToLower(c)) {
return strBoolTrue
}
}
return strBoolFalse
}
func sDatetime(v interface{}, onlyDate, onlyTime bool) string {
var (
// input format set
inputFormats []string
// output format
internalFormat string
datetime = fmt.Sprintf("%v", v)
)
if onlyTime {
internalFormat = datetimeIntenralFormatTime
inputFormats = []string{
datetimeIntenralFormatTime,
"15:04",
"15:04:05Z07:00",
"15:04:05 MST",
"15:04:05 -0700",
"15:04 MST",
"15:04Z07:00",
"15:04 -0700",
time.Kitchen,
}
} else {
if onlyDate {
// In case only date is used, make sure we format it properly
internalFormat = datetimeInternalFormatDate
} else {
internalFormat = datetimeInternalFormatFull
}
// date & time
inputFormats = []string{
datetimeInternalFormatFull,
"2006-01-02T15:04:05", // iso8601 without timezone
time.RFC1123Z,
time.RFC1123,
time.RFC822Z,
time.RFC822,
time.RFC850,
time.ANSIC,
time.UnixDate,
time.RubyDate,
"2006-01-02 15:04:05.999999999 -0700 MST", // Time.String()
"2006-01-02",
"02 Jan 2006",
"2006-01-02T15:04:05-0700", // RFC3339 without timezone hh:mm colon
"2006-01-02 15:04:05 -07:00",
"2006-01-02 15:04:05 -0700",
"2006-01-02 15:04:05Z07:00", // RFC3339 without T
"2006-01-02 15:04:05Z0700", // RFC3339 without T or timezone hh:mm colon
"2006-01-02 15:04:05",
time.Kitchen,
time.Stamp,
time.StampMilli,
time.StampMicro,
time.StampNano,
datetimeInternalFormatDate,
"02 Jan 06",
"Monday, 02-Jan-06",
"Mon, 02 Jan 2006",
"2006/_1/_2",
}
}
for _, format := range inputFormats {
parsed, err := time.Parse(format, datetime)
if err == nil {
return parsed.UTC().Format(internalFormat)
}
}
return ""
}
func sNumber(num interface{}, p uint) string {
base, err := strconv.ParseFloat(fmt.Sprintf("%v", num), 64)
if err != nil {
return "0"
}
// Format the value to the desired precision
str := strconv.FormatFloat(base, 'f', int(p), 64)
// In case of fractures, remove trailing 0's
if strings.Contains(str, ".") {
str = strings.TrimRight(str, "0")
str = strings.TrimRight(str, ".")
}
return str
}
// sString is used mostly to strip insecure html data
// from strings
func sString(str string) string {
// use standard html escaping policy
p := bluemonday.UGCPolicy()
// match only colors for html editor elements on style attr
p.AllowAttrs("style").OnElements("span", "p")
p.AllowStyles("color").Matching(regexp.MustCompile("(?i)^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$")).Globally()
return p.Sanitize(str)
}
// sanitize casts value to field kind format
func sanitize(f *types.ModuleField, v interface{}) string {
switch strings.ToLower(f.Kind) {
case "bool":
return sBool(v)
case "datetime":
v = sDatetime(v, f.Options.Bool("onlyDate"), f.Options.Bool("onlyTime"))
case "number":
v = sNumber(v, f.Options.Precision())
}
return fmt.Sprintf("%v", v)
}