/
transformer.go
444 lines (416 loc) · 11.2 KB
/
transformer.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
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
// Copyright 2022 Paul Greenberg greenpau@outlook.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package transformer
import (
"context"
"fmt"
"github.com/greenpau/go-authcrunch/pkg/acl"
cfgutil "github.com/greenpau/go-authcrunch/pkg/util/cfg"
"strings"
)
// Config represents a common set of configuration settings
// applicable to the cookies issued by authn.Authenticator.
type Config struct {
Matchers []string `json:"matchers,omitempty" xml:"matchers,omitempty" yaml:"matchers,omitempty"`
Actions []string `json:"actions,omitempty" xml:"actions,omitempty" yaml:"actions,omitempty"`
}
type transform struct {
matcher *acl.AccessList
actions [][]string
}
// Factory holds configuration and associated finctions
// for the cookies issued by authn.Authenticator.
type Factory struct {
configs []*Config
transforms []*transform
}
// NewFactory returns an instance of cookie factory.
func NewFactory(cfgs []*Config) (*Factory, error) {
f := &Factory{}
if len(cfgs) == 0 {
return nil, fmt.Errorf("transformer has no config")
}
f.configs = cfgs
for _, cfg := range cfgs {
if len(cfg.Matchers) < 1 {
return nil, fmt.Errorf("transformer has no matchers: %v", cfg)
}
if len(cfg.Actions) < 1 {
return nil, fmt.Errorf("transformer has no actions: %v", cfg)
}
var actions [][]string
for _, encodedArgs := range cfg.Actions {
args, err := cfgutil.DecodeArgs(encodedArgs)
if err != nil {
return nil, fmt.Errorf("transformer for %q erred during arg decoding: %v", encodedArgs, err)
}
switch args[0] {
case "require":
actions = append(actions, args)
case "block", "deny":
actions = append(actions, args)
case "ui":
if len(args) < 4 {
return nil, fmt.Errorf("transformer for %q erred: ui config too short", encodedArgs)
}
switch args[1] {
case "link":
actions = append(actions, args[1:])
default:
return nil, fmt.Errorf("transformer for %q erred: invalid ui config", encodedArgs)
}
case "add", "overwrite", "drop":
if len(args) < 3 {
return nil, fmt.Errorf("transformer for %q erred: invalid add/overwrite config", encodedArgs)
}
actions = append(actions, args)
case "delete":
if len(args) < 2 {
return nil, fmt.Errorf("transformer for %q erred: invalid delete config", encodedArgs)
}
actions = append(actions, args)
case "action":
if len(args) < 3 {
return nil, fmt.Errorf("transformer for %q erred: action config too short", encodedArgs)
}
switch args[1] {
case "add", "overwrite", "delete", "drop":
default:
return nil, fmt.Errorf("transformer for %q erred: invalid action config", encodedArgs)
}
actions = append(actions, args[1:])
default:
return nil, fmt.Errorf("transformer has unsupported action: %v", args)
}
}
matcher := acl.NewAccessList()
matchRuleConfigs := []*acl.RuleConfiguration{
{
Conditions: cfg.Matchers,
Action: "allow",
},
}
if err := matcher.AddRules(context.Background(), matchRuleConfigs); err != nil {
return nil, err
}
tr := &transform{
matcher: matcher,
actions: actions,
}
f.transforms = append(f.transforms, tr)
}
return f, nil
}
// Transform performs user data transformation.
func (f *Factory) Transform(m map[string]interface{}) error {
var challenges, frontendLinks []string
if _, exists := m["mail"]; exists {
m["email"] = m["mail"].(string)
delete(m, "mail")
}
for _, transform := range f.transforms {
if matched := transform.matcher.Allow(context.Background(), m); !matched {
continue
}
for _, args := range transform.actions {
switch args[0] {
case "block", "deny":
return fmt.Errorf("transformer action is block/deny")
case "require":
challenges = append(challenges, cfgutil.EncodeArgs(args[1:]))
case "link":
frontendLinks = append(frontendLinks, cfgutil.EncodeArgs(args[1:]))
default:
if err := transformData(args, m, transform.matcher); err != nil {
return fmt.Errorf("transformer for %v erred: %v", args, err)
}
}
}
}
if len(challenges) > 0 {
m["challenges"] = challenges
}
if len(frontendLinks) > 0 {
m["frontend_links"] = frontendLinks
}
return nil
}
func transformData(args []string, m map[string]interface{}, matcher *acl.AccessList) error {
if len(args) < 3 {
return fmt.Errorf("too short")
}
switch args[0] {
case "add", "delete", "overwrite", "drop":
default:
return fmt.Errorf("unsupported action %v", args[0])
}
k, dt := acl.GetFieldDataType(args[1])
switch args[0] {
case "add":
switch dt {
case "list_str":
var entries, newEntries []string
switch val := m[k].(type) {
case string:
entries = strings.Split(val, " ")
case []string:
entries = val
case []interface{}:
for _, entry := range val {
switch e := entry.(type) {
case string:
entries = append(entries, e)
}
}
case nil:
default:
return fmt.Errorf("unsupported %q field type %T with value: %v in %v", k, val, val, args)
}
entries = append(entries, args[2:]...)
entryMap := make(map[string]bool)
for _, e := range entries {
e = strings.TrimSpace(e)
if e == "" {
continue
}
v, err := repl(m, e)
if err != nil {
return err
}
if _, exists := entryMap[v]; exists {
continue
}
entryMap[v] = true
newEntries = append(newEntries, v)
}
m[k] = newEntries
case "str":
var e string
switch val := m[k].(type) {
case string:
e = val + " " + strings.Join(args[2:], " ")
case nil:
e = strings.Join(args[2:], " ")
}
v, err := repl(m, e)
if err != nil {
return err
}
m[k] = v
default:
// Handle custom fields.
if args[1] == "nested" {
nestedKeys, nestedValues, err := parseCustomNestedFieldValues(args[2:])
if err != nil {
return fmt.Errorf("failed transforming %q field for %q action in %v: %v", k, args[0], args, err)
}
// Use pointers to create nested map.
var mp map[string]interface{}
mp = m
for i, v := range nestedKeys {
if i == len(nestedKeys)-1 {
// Handle last element.
mp[v] = nestedValues
continue
}
mv, exists := mp[v]
if !exists {
mp[v] = make(map[string]interface{})
mp = mp[v].(map[string]interface{})
continue
}
mp = mv.(map[string]interface{})
}
break
}
v, err := parseCustomFieldValues(m, args[2:])
if err != nil {
return fmt.Errorf("failed transforming %q field for %q action in %v: %v", k, args[0], args, err)
}
m[args[1]] = v
}
case "overwrite":
switch dt {
case "list_str":
m[k] = append([]string{}, args[2:]...)
case "str":
m[k] = strings.Join(args[2:], " ")
default:
return fmt.Errorf("unsupported %q field for %q action in %v", k, args[0], args)
}
case "drop":
if len(args) != 3 {
return fmt.Errorf("malformed %q action in %v", args[0], args)
}
if args[1] != "matched" || args[2] != "role" {
return fmt.Errorf("malformed %q action in %v", args[0], args)
}
if args[1] == "matched" && args[2] == "role" {
if _, exists := m["roles"]; exists {
var entries, newEntries []string
switch val := m["roles"].(type) {
case []string:
entries = val
case []interface{}:
for _, entry := range val {
switch e := entry.(type) {
case string:
entries = append(entries, e)
}
return fmt.Errorf("failed to %q action in %v due to unsupported data type inside the input data", args[0], args)
}
default:
return fmt.Errorf("failed to %q action in %v due to unsupported data type inside the input data", args[0], args)
}
for _, e := range entries {
em := map[string]interface{}{
"roles": []string{e},
}
if matched := matcher.Allow(context.Background(), em); matched {
continue
}
newEntries = append(newEntries, e)
}
m["roles"] = newEntries
}
}
default:
return fmt.Errorf("unsupported %q action in %v", args[0], args)
}
return nil
}
func parseCustomFieldValues(m map[string]interface{}, args []string) (interface{}, error) {
var x int
for i, arg := range args {
if arg == "as" {
x = i
break
}
}
if x == 0 {
return nil, fmt.Errorf("as type directive not found")
}
if len(args[x:]) < 2 {
return nil, fmt.Errorf("as type directive is too short")
}
dt := strings.Join(args[x+1:], "_")
switch dt {
case "string_list", "list":
values, err := replArr(m, args[:x])
if err != nil {
return nil, err
}
return values, nil
case "string":
value, err := repl(m, args[x-1])
if err != nil {
return nil, err
}
return value, nil
}
return nil, fmt.Errorf("unsupported %q data type", dt)
}
func parseCustomNestedFieldValues(args []string) ([]string, interface{}, error) {
var x, y int
for i, arg := range args {
if arg == "with" {
y = i
}
if arg == "as" {
x = i
break
}
}
if x == 0 {
return nil, nil, fmt.Errorf("as type directive not found")
}
if len(args[x:]) < 2 {
return nil, nil, fmt.Errorf("as type directive is too short")
}
dt := strings.Join(args[x+1:], "_")
args = args[:x]
if (dt != "map") && (y < 1) {
return nil, nil, fmt.Errorf("the with keyword not found")
}
switch dt {
case "string_list", "list":
return args[:y], args[y+1:], nil
case "string":
return args[:y], args[y+1], nil
case "map":
m := make(map[string]interface{})
return args, m, nil
}
return nil, nil, fmt.Errorf("unsupported %q data type", dt)
}
func hasReplPattern(s string) bool {
if strings.IndexRune(s, '{') < 0 {
return false
}
if strings.IndexRune(s, '}') < 0 {
return false
}
return true
}
func getReplPattern(s string) string {
i := strings.IndexRune(s, '{')
j := strings.IndexRune(s, '}')
return string(s[i : j+1])
}
func getReplKey(s string) string {
i := strings.IndexRune(s, '.')
return string(s[i+1 : len(s)-1])
}
func getReplValue(m map[string]interface{}, s string) (string, error) {
var value string
v, exists := m[s]
if !exists {
return value, fmt.Errorf("transform replace field %q not found", s)
}
switch val := v.(type) {
case string:
value = val
default:
return "", fmt.Errorf("transform replace field %q value type %T is unsupported", s, val)
}
return value, nil
}
func repl(m map[string]interface{}, s string) (string, error) {
for {
if !hasReplPattern(s) {
break
}
ptrn := getReplPattern(s)
if !strings.HasPrefix(ptrn, "{claims.") {
return "", fmt.Errorf("transform replace pattern %q is unsupported", ptrn)
}
v, err := getReplValue(m, getReplKey(ptrn))
if err != nil {
return "", err
}
s = strings.ReplaceAll(s, ptrn, v)
}
return s, nil
}
func replArr(m map[string]interface{}, arr []string) ([]string, error) {
var values []string
for _, s := range arr {
value, err := repl(m, s)
if err != nil {
return values, err
}
values = append(values, value)
}
return values, nil
}