-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
mask.go
356 lines (292 loc) · 7.37 KB
/
mask.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
// Copyright 2020 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 logs
import (
"encoding/json"
"fmt"
"net/url"
"strconv"
"strings"
"github.com/open-policy-agent/opa/internal/deepcopy"
"github.com/open-policy-agent/opa/util"
)
type maskOP string
const (
maskOPRemove maskOP = "remove"
maskOPUpsert maskOP = "upsert"
partInput = "input"
partResult = "result"
partNDBCache = "nd_builtin_cache"
)
var (
errMaskInvalidObject = fmt.Errorf("mask upsert invalid object")
)
type maskRule struct {
OP maskOP `json:"op"`
Path string `json:"path"`
Value interface{} `json:"value"`
escapedParts []string
modifyFullObj bool
failUndefinedPath bool
}
type maskRuleSet struct {
OnRuleError func(*maskRule, error)
Rules []*maskRule
resultCopied bool
}
func (r maskRule) String() string {
return "/" + strings.Join(r.escapedParts, "/")
}
type maskRuleOption func(*maskRule) error
func newMaskRule(path string, opts ...maskRuleOption) (*maskRule, error) {
const (
defaultOP = maskOPRemove
defaultFailUndefinedPath = false
)
if len(path) == 0 {
return nil, fmt.Errorf("mask must be non-empty")
} else if !strings.HasPrefix(path, "/") {
return nil, fmt.Errorf("mask must be slash-prefixed")
}
parts := strings.Split(path[1:], "/")
switch parts[0] {
case partInput, partResult, partNDBCache: // OK
default:
return nil, fmt.Errorf("mask prefix not allowed: %v", parts[0])
}
escapedParts := make([]string, len(parts))
for i := range parts {
_, err := url.PathUnescape(parts[i])
if err != nil {
return nil, err
}
escapedParts[i] = url.PathEscape(parts[i])
}
modifyFullObj := false
if len(escapedParts) == 1 {
modifyFullObj = true
}
r := &maskRule{
OP: defaultOP,
Path: path,
escapedParts: escapedParts,
failUndefinedPath: defaultFailUndefinedPath,
modifyFullObj: modifyFullObj,
}
for _, opt := range opts {
if err := opt(r); err != nil {
return nil, err
}
}
return r, nil
}
func withOP(op maskOP) maskRuleOption {
return func(r *maskRule) error {
var supportedMaskOPS = [...]maskOP{maskOPRemove, maskOPUpsert}
for _, sOP := range supportedMaskOPS {
if op == sOP {
r.OP = op
return nil
}
}
return fmt.Errorf("mask op is not supported: %s", op)
}
}
func withValue(val interface{}) maskRuleOption {
return func(r *maskRule) error {
r.Value = val
return nil
}
}
func withFailUndefinedPath() maskRuleOption {
return func(r *maskRule) error {
r.failUndefinedPath = true
return nil
}
}
func (r maskRule) Mask(event *EventV1) error {
var maskObj *interface{} // pointer to event Input|Result|NDBCache object
var maskObjPtr **interface{} // pointer to the event Input|Result|NDBCache pointer itself
switch p := r.escapedParts[0]; p {
case partInput:
if event.Input == nil {
if r.failUndefinedPath {
return errMaskInvalidObject
}
return nil
}
maskObj = event.Input
maskObjPtr = &event.Input
case partResult:
if event.Result == nil {
if r.failUndefinedPath {
return errMaskInvalidObject
}
return nil
}
maskObj = event.Result
maskObjPtr = &event.Result
case partNDBCache:
if event.NDBuiltinCache == nil {
if r.failUndefinedPath {
return errMaskInvalidObject
}
return nil
}
maskObj = event.NDBuiltinCache
maskObjPtr = &event.NDBuiltinCache
default:
return fmt.Errorf("illegal path value: %s", p)
}
switch r.OP {
case maskOPRemove:
if r.modifyFullObj {
*maskObjPtr = nil
} else {
parent, err := r.lookup(r.escapedParts[1:len(r.escapedParts)-1], *maskObj)
if err != nil {
if err == errMaskInvalidObject && r.failUndefinedPath {
return err
}
}
parentObj, ok := parent.(map[string]interface{})
if !ok {
return nil
}
fld := r.escapedParts[len(r.escapedParts)-1]
if _, ok := parentObj[fld]; !ok {
return nil
}
delete(parentObj, fld)
}
event.Erased = append(event.Erased, r.String())
case maskOPUpsert:
if r.modifyFullObj {
*maskObjPtr = &r.Value
} else {
inputObj, ok := (*maskObj).(map[string]interface{})
if !ok {
return nil
}
if err := r.mkdirp(inputObj, r.escapedParts[1:len(r.escapedParts)], r.Value); err != nil {
if r.failUndefinedPath {
return err
}
return nil
}
}
event.Masked = append(event.Masked, r.String())
default:
return fmt.Errorf("illegal mask op value: %s", r.OP)
}
return nil
}
func (r maskRule) lookup(p []string, node interface{}) (interface{}, error) {
for i := 0; i < len(p); i++ {
switch v := node.(type) {
case map[string]interface{}:
var ok bool
if node, ok = v[p[i]]; !ok {
return nil, errMaskInvalidObject
}
case []interface{}:
idx, err := strconv.Atoi(p[i])
if err != nil {
return nil, errMaskInvalidObject
} else if idx < 0 || idx >= len(v) {
return nil, errMaskInvalidObject
}
node = v[idx]
default:
return nil, errMaskInvalidObject
}
}
return node, nil
}
func (r maskRule) mkdirp(node map[string]interface{}, path []string, value interface{}) error {
if len(path) == 0 {
return nil
}
// create intermediate nodes
for i := 0; i < len(path)-1; i++ {
child, ok := node[path[i]]
if !ok {
child := map[string]interface{}{}
node[path[i]] = child
node = child
continue
}
switch obj := child.(type) {
case map[string]interface{}:
node = obj
default:
return errMaskInvalidObject
}
}
node[path[len(path)-1]] = value
return nil
}
func newMaskRuleSet(rv interface{}, onRuleError func(*maskRule, error)) (*maskRuleSet, error) {
bs, err := json.Marshal(rv)
if err != nil {
return nil, err
}
var mRuleSet = &maskRuleSet{
OnRuleError: onRuleError,
}
var rawRules []interface{}
if err := util.Unmarshal(bs, &rawRules); err != nil {
return nil, err
}
for _, iface := range rawRules {
switch v := iface.(type) {
case string:
// preserve default behavior of remove when
// structured mask format is not provided
rule, err := newMaskRule(v)
if err != nil {
return nil, err
}
mRuleSet.Rules = append(mRuleSet.Rules, rule)
case map[string]interface{}:
bs, err := json.Marshal(v)
if err != nil {
return nil, err
}
rule := &maskRule{}
if err := util.Unmarshal(bs, rule); err != nil {
return nil, err
}
// use unmarshalled values to create new Mask Rule
rule, err = newMaskRule(rule.Path, withOP(rule.OP), withValue(rule.Value))
// TODO add withFailUndefinedPath() option based on
// A) new syntax in user defined mask rule
// B) passed in/global configuration option
// rule precedence A>B
if err != nil {
return nil, err
}
mRuleSet.Rules = append(mRuleSet.Rules, rule)
default:
return nil, fmt.Errorf("invalid mask rule format encountered: %T", v)
}
}
return mRuleSet, nil
}
func (rs maskRuleSet) Mask(event *EventV1) {
for _, mRule := range rs.Rules {
// result must be deep copied if there are any mask rules
// targeting it, to avoid modifying the result sent
// to the consumer
if mRule.escapedParts[0] == partResult && event.Result != nil && !rs.resultCopied {
resultCopy := deepcopy.DeepCopy(*event.Result)
event.Result = &resultCopy
rs.resultCopied = true
}
err := mRule.Mask(event)
if err != nil {
rs.OnRuleError(mRule, err)
}
}
}