This repository was archived by the owner on May 30, 2025. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathstruct.go
More file actions
515 lines (448 loc) · 10.8 KB
/
Copy pathstruct.go
File metadata and controls
515 lines (448 loc) · 10.8 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
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
package pii
import (
"errors"
"fmt"
"reflect"
"strings"
"sync"
)
var (
tagID = "pii"
tagSubjectID = "subjectID"
tagData = "data"
tagDive = "dive"
)
var (
ErrInvalidTagConfiguration = errors.New("invalid 'pii' tag configuration")
ErrUnsupportedType = errors.New("unsupported type")
ErrUnsupportedFieldType = errors.New("unsupported field type must be convertible to string")
ErrMultipleNestedSubjectID = errors.New("potential multiple nested subject IDs")
ErrSubjectIDNotFound = errors.New("subject ID not found")
ErrRedactFuncNotFound = errors.New("redact function not found")
)
// Found returns wether or not the struct contains PII data fields.
// It returns an error if `pii` tag is misconfigured or value param isn't a struct or struct pointer.
func Found(v any) (bool, error) {
t := reflect.TypeOf(v)
for t.Kind() == reflect.Pointer {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
return false, fmt.Errorf("%w : %v", ErrUnsupportedType, t)
}
piiStructType, err := scanStructType(t)
if err != nil {
return false, err
}
return piiStructType.hasPII, nil
}
// RedactConfig presents the config required by `pii.Redact`.
type RedactConfig struct {
RedactFunc ReplaceFunc
}
// Redact does redact PII data from the struct field values
// by replacing each character with '*'.
//
// It fails if the value isn't a struct pointer, `pii` tag is misconfigured,
// or the redact function is nil.
//
// Optionally, it accepts overriding the default redact function.
func Redact(structPtr any, opts ...func(*RedactConfig)) error {
cfg := RedactConfig{
RedactFunc: defaultRedactFunc,
}
for _, opt := range opts {
if opt == nil {
continue
}
opt(&cfg)
}
if cfg.RedactFunc == nil {
return ErrRedactFuncNotFound
}
piiStruct, err := scan(structPtr, false)
if err != nil {
return err
}
if !piiStruct.typ.hasPII {
return nil
}
return piiStruct.replace(cfg.RedactFunc)
}
var defaultRedactFunc ReplaceFunc = func(_ FieldReplace, val string) (string, error) {
return strings.Repeat("*", len(val)), nil
}
var (
stringType = reflect.TypeOf("")
)
var (
cache map[reflect.Type]*piiStructType = make(map[reflect.Type]*piiStructType)
cacheMu sync.RWMutex
)
type piiStructContext struct {
seen map[reflect.Type]*piiStructType
}
type piiField struct {
sf reflect.StructField
isSub, isData, isNested bool
prefix string
replacement string
isSlice, isMap bool
nestedStructType *piiStructType
nestedStructTypeRef reflect.Type
kind string
}
func (f piiField) getType(cache map[reflect.Type]*piiStructType) *piiStructType {
if f.nestedStructTypeRef != nil {
return cache[f.nestedStructTypeRef]
}
return f.nestedStructType
}
func (f piiField) IsZero() bool {
// TBD find a better condition??
return f.sf.Name == ""
}
type piiStructType struct {
hasPII bool
subField piiField
piiFields []piiField
rt reflect.Type
}
type piiStruct struct {
typ piiStructType
val reflect.Value
subjectID string
}
func ptr[T any](t T) *T {
return &t
}
// resolveSubject resolves the PII struct subject ID value by walking through
// the struct and its nested PII structs.
//
// It returns an error if the subject ID is missing or duplicated.
func resolveSubject(pt piiStructType, pv reflect.Value) (string, error) {
subject := ""
if !pt.subField.IsZero() {
subject = pt.subField.prefix + reflect.Indirect(pv.FieldByIndex(pt.subField.sf.Index)).String()
}
for _, piiF := range pt.piiFields {
if !piiF.isNested {
continue
}
piiFV := pv.FieldByIndex(piiF.sf.Index)
if piiFV.IsZero() {
continue
}
cacheMu.Lock()
piiT := piiF.getType(cache)
cacheMu.Unlock()
if piiT == nil {
// TBD return error instead ??
panic(fmt.Errorf("unexpected: failed to resolve PII field type %v", piiF))
}
piiFV = reflect.Indirect(piiFV)
nestedSubject := ""
switch {
case piiF.isSlice:
for i := 0; i < piiFV.Len(); i++ {
nestedSubject, _ = resolveSubject(*piiT, piiFV.Index(i))
if nestedSubject != "" {
break
}
}
case piiF.isMap:
for _, k := range piiFV.MapKeys() {
nestedSubject, _ = resolveSubject(*piiT, piiFV.MapIndex(k))
if nestedSubject != "" {
break
}
}
default:
nestedSubject, _ = resolveSubject(*piiT, piiFV)
}
if nestedSubject != "" {
if subject != "" && subject != nestedSubject {
return "", ErrMultipleNestedSubjectID
}
subject = nestedSubject
}
}
if subject == "" {
return "", fmt.Errorf("%w: %v", ErrSubjectIDNotFound, pt.rt)
}
return subject, nil
}
func (ps *piiStruct) resolveSubject() (string, error) {
if ps.subjectID == "" {
var err error
ps.subjectID, err = resolveSubject(ps.typ, ps.val)
if err != nil {
return "", err
}
}
return ps.subjectID, nil
}
func (ps *piiStruct) getSubjectID() string {
s, err := ps.resolveSubject()
if err != nil {
panic(err)
}
return s
}
type FieldReplace struct {
SubjectID string
Name string
RType reflect.Type
Replacement string
Kind string
}
type ReplaceFunc func(fr FieldReplace, val string) (string, error)
func (s *piiStruct) replace(fn ReplaceFunc) error {
var (
newVal string
err error
)
for _, piiF := range s.typ.piiFields {
v := s.val.FieldByIndex(piiF.sf.Index)
if v.IsZero() {
continue
}
if !v.CanSet() {
continue
}
elem := reflect.Indirect(v)
if piiF.isData {
val := elem.String()
newVal, err = fn(FieldReplace{
SubjectID: s.subjectID,
RType: piiF.sf.Type,
Replacement: piiF.replacement,
Kind: piiF.kind,
}, val)
if err != nil {
return err
}
if newVal != val {
elem.SetString(newVal)
}
continue
}
if piiF.isNested {
var piiT piiStructType
cacheMu.Lock()
piiTPtr := piiF.getType(cache)
cacheMu.Unlock()
if piiTPtr == nil {
panic(fmt.Errorf("unexpected: failed to resolve PII field type %v", piiF))
}
piiT = *piiTPtr
if !piiT.hasPII {
continue
}
switch {
case piiF.isSlice:
for i := 0; i < elem.Len(); i++ {
if err := (&piiStruct{
subjectID: s.subjectID, // inherit parent subject ID
val: reflect.Indirect(elem.Index(i)),
typ: piiT,
}).replace(fn); err != nil {
return err
}
}
case piiF.isMap:
for _, k := range elem.MapKeys() {
mapElem := elem.MapIndex(k)
if mapElem.IsZero() {
continue
}
mapElem = reflect.Indirect(elem.MapIndex(k))
if !mapElem.CanAddr() {
newElem := reflect.New(mapElem.Type()).Elem()
newElem.Set(mapElem)
if err := (&piiStruct{
subjectID: s.subjectID, // inherit parent subject ID
val: newElem,
typ: piiT,
}).replace(fn); err != nil {
return err
}
elem.SetMapIndex(k, newElem)
continue
}
if err := (&piiStruct{
subjectID: s.subjectID,
val: reflect.Indirect(elem.MapIndex(k)),
typ: piiT,
}).replace(fn); err != nil {
return err
}
}
default:
if err := (&piiStruct{
subjectID: s.subjectID,
val: elem,
typ: piiT,
}).replace(fn); err != nil {
return err
}
}
}
}
return nil
}
func parseTag(tagStr string) (name string, opts map[string]string) {
if tagStr == "" {
return
}
tags := strings.Split(tagStr, ",")
name = strings.TrimSpace(tags[0])
opts = make(map[string]string)
for _, opt := range tags[1:] {
splits := strings.Split(opt, "=")
if len(splits) == 2 {
name, val := strings.TrimSpace(splits[0]), strings.TrimSpace(splits[1])
opts[name] = val
}
}
return
}
func scanStructType(rt reflect.Type) (piiStructType, error) {
cacheMu.Lock()
defer cacheMu.Unlock()
if _, ok := cache[rt]; !ok {
c := piiStructContext{seen: cache}
piiT, err := scanStructTypeWithContext(c, rt)
if err != nil {
return piiStructType{}, err
}
cache[rt] = &piiT
}
return *cache[rt], nil
}
func scanStructTypeWithContext(c piiStructContext, rt reflect.Type) (piiStructType, error) {
piiFields := make([]piiField, 0)
var subjectField piiField
for i := 0; i < rt.NumField(); i++ {
field := rt.Field(i)
tags := field.Tag.Get(tagID)
if tags == "" {
continue
}
if !field.IsExported() {
continue
}
name, opts := parseTag(tags)
piiF := piiField{
sf: field,
isSub: name == tagSubjectID,
isData: name == tagData,
isNested: name == tagDive,
prefix: opts["prefix"],
replacement: opts["replace"],
kind: opts["kind"],
}
switch {
case piiF.isSub:
if !field.Type.ConvertibleTo(stringType) {
return piiStructType{}, ErrUnsupportedFieldType
}
if !subjectField.IsZero() {
return piiStructType{}, ErrMultipleNestedSubjectID
}
subjectField = piiF
case piiF.isData:
tt := field.Type
if tt.Kind() == reflect.Ptr {
tt = tt.Elem()
}
if tt.Kind() != reflect.String {
continue
}
piiFields = append(piiFields, piiF)
case piiF.isNested:
tt := field.Type
if tt.Kind() == reflect.Ptr {
tt = tt.Elem()
}
if tt.Kind() == reflect.Slice {
piiF.isSlice = true
tt = tt.Elem()
}
if tt.Kind() == reflect.Map {
piiF.isMap = true
tt = tt.Elem()
}
if tt.Kind() == reflect.Ptr {
tt = tt.Elem()
}
_, seen := c.seen[tt]
if !seen {
var piiType piiStructType
var err error
c.seen[tt] = &piiType
piiType, err = scanStructTypeWithContext(c, tt)
if err != nil {
return piiStructType{}, err
}
piiF.nestedStructType = &piiType
} else {
piiF.nestedStructTypeRef = tt
}
piiFields = append(piiFields, piiF)
}
}
return piiStructType{
hasPII: len(piiFields) > 0,
subField: subjectField,
piiFields: piiFields,
rt: rt,
}, nil
}
func scan(v any, requireSubject bool) (piiStr piiStruct, err error) {
defer func() {
if err != nil {
err = errors.Join(ErrInvalidTagConfiguration, err)
}
}()
if v == nil {
err = fmt.Errorf("%w: %v", ErrUnsupportedType, nil)
return
}
tt := reflect.TypeOf(v)
if tt.Kind() != reflect.Pointer {
err = fmt.Errorf("%w: %v", ErrUnsupportedType, tt)
return
}
if tt.Kind() == reflect.Pointer {
tt = tt.Elem()
}
if tt.Kind() != reflect.Struct {
err = fmt.Errorf("%w: %v", ErrUnsupportedType, tt)
return
}
var piiType piiStructType
piiType, err = scanStructType(tt)
if err != nil {
return
}
if !piiType.hasPII {
// As struct doesn't have PII data, no need to proceed and resolve subject ID value
// that's solely used to get encryption materials to encrypt/decrypt PII fields.
// Therefore getting calling 'reflect.ValueOf', considering its cost, doesn't make sense.
piiStr = piiStruct{
typ: piiType,
}
return
}
piiStr = piiStruct{
typ: piiType,
val: reflect.ValueOf(v).Elem(),
}
if requireSubject {
if _, err = piiStr.resolveSubject(); err != nil {
return
}
}
return
}