forked from algorand/indexer
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdisabled_parameters.go
More file actions
530 lines (423 loc) · 15.9 KB
/
disabled_parameters.go
File metadata and controls
530 lines (423 loc) · 15.9 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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
package api
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
"github.com/getkin/kin-openapi/openapi3"
"github.com/labstack/echo/v4"
"gopkg.in/yaml.v3"
)
const (
disabledStatusStr = "disabled"
enabledStatusStr = "enabled"
requiredParameterStr = "required"
optionalParameterStr = "optional"
)
// DisplayDisabledMap is a struct that contains the necessary information
// to output the current config to the screen
type DisplayDisabledMap struct {
// A complicated map but necessary to output the correct YAML.
// This is supposed to represent a data structure with a similar YAML
// representation:
// /v2/accounts/{account-id}:
// required:
// - account-id : enabled
// /v2/accounts:
// optional:
// - auth-addr : enabled
// - next: disabled
Data map[string]map[string][]map[string]string
}
func (ddm *DisplayDisabledMap) String() (string, error) {
if len(ddm.Data) == 0 {
return "", nil
}
bytes, err := yaml.Marshal(ddm.Data)
if err != nil {
return "", err
}
return string(bytes), nil
}
func makeDisplayDisabledMap() *DisplayDisabledMap {
return &DisplayDisabledMap{
Data: make(map[string]map[string][]map[string]string),
}
}
func (ddm *DisplayDisabledMap) addEntry(restPath string, requiredOrOptional string, entryName string, status string) {
if ddm.Data == nil {
ddm.Data = make(map[string]map[string][]map[string]string)
}
if ddm.Data[restPath] == nil {
ddm.Data[restPath] = make(map[string][]map[string]string)
}
mapEntry := map[string]string{entryName: status}
ddm.Data[restPath][requiredOrOptional] = append(ddm.Data[restPath][requiredOrOptional], mapEntry)
}
// validateSchema takes in a newly loaded DisplayDisabledMap and validates that all the
// "strings" are the correct values. For instance, it says that the sub-config is either
// "required" or "optional" as well as making sure the string values for the parameters
// are either "enabled" or "disabled".
//
// However, it does not validate whether the values actually exist. That comes with the "Validate"
// function on a DisabledMapConfig
func (ddm *DisplayDisabledMap) validateSchema() error {
type innerStruct struct {
// IllegalParamTypes: list of the mis-spelled parameter types (i.e. not required or optional)
IllegalParamTypes []string
// IllegalParamStatus: list of parameter names with mis-spelled parameter status combined as a string
IllegalParamStatus []string
}
illegalSchema := make(map[string]innerStruct)
for restPath, entries := range ddm.Data {
tmp := innerStruct{}
for requiredOrOptional, paramList := range entries {
if requiredOrOptional != requiredParameterStr && requiredOrOptional != optionalParameterStr {
tmp.IllegalParamTypes = append(tmp.IllegalParamTypes, requiredOrOptional)
}
for _, paramDict := range paramList {
for paramName, paramStatus := range paramDict {
if paramStatus != disabledStatusStr && paramStatus != enabledStatusStr {
errorStr := fmt.Sprintf("%s : %s", paramName, paramStatus)
tmp.IllegalParamStatus = append(tmp.IllegalParamStatus, errorStr)
}
}
}
if len(tmp.IllegalParamTypes) != 0 || len(tmp.IllegalParamStatus) != 0 {
illegalSchema[restPath] = tmp
}
}
}
// No error if there are no entries
if len(illegalSchema) == 0 {
return nil
}
var sb strings.Builder
for restPath, iStruct := range illegalSchema {
_, _ = sb.WriteString(fmt.Sprintf("REST Path %s contained the following errors:\n", restPath))
if len(iStruct.IllegalParamTypes) != 0 {
_, _ = sb.WriteString(fmt.Sprintf(" -> Illegal Parameter Types: %v\n", iStruct.IllegalParamTypes))
}
if len(iStruct.IllegalParamStatus) != 0 {
_, _ = sb.WriteString(fmt.Sprintf(" -> Illegal Parameter Status: %v\n", iStruct.IllegalParamStatus))
}
}
return fmt.Errorf(sb.String())
}
// toDisabledMapConfig creates a disabled map config from a display disabled map. If the swag pointer
// is nil then no validation is performed on the disabled map config. This is useful for unit tests
func (ddm *DisplayDisabledMap) toDisabledMapConfig(swag *openapi3.T) (*DisabledMapConfig, error) {
// Check that all the "strings" are valid
err := ddm.validateSchema()
if err != nil {
return nil, err
}
// We now should have a correctly formed DisplayDisabledMap.
// Let's turn that into a config
dmc := MakeDisabledMapConfig()
for restPath, entries := range ddm.Data {
var disabledParams []string
for _, paramList := range entries {
// We don't care if they are required or optional, only if the are disabled
for _, paramDict := range paramList {
for paramName, paramStatus := range paramDict {
if paramStatus != disabledStatusStr {
continue
}
disabledParams = append(disabledParams, paramName)
}
}
}
// Default to just get for now
dmc.addEntry(restPath, http.MethodGet, disabledParams)
}
if swag != nil {
err = dmc.validate(swag)
if err != nil {
return nil, err
}
}
return dmc, nil
}
// MakeDisabledMapConfigFromFile loads a file containing a disabled map configuration.
func MakeDisabledMapConfigFromFile(swag *openapi3.T, filePath string) (*DisabledMapConfig, error) {
// First load the file...
f, err := ioutil.ReadFile(filePath)
if err != nil {
return nil, err
}
ddm := makeDisplayDisabledMap()
err = yaml.Unmarshal(f, &ddm.Data)
if err != nil {
return nil, err
}
return ddm.toDisabledMapConfig(swag)
}
// MakeDisplayDisabledMapFromConfig will make a DisplayDisabledMap that takes into account the DisabledMapConfig.
// If limited is set to true, then only disabled parameters will be added to the DisplayDisabledMap
func MakeDisplayDisabledMapFromConfig(swag *openapi3.T, mapConfig *DisabledMapConfig, limited bool) *DisplayDisabledMap {
rval := makeDisplayDisabledMap()
for restPath, item := range swag.Paths {
for opName, opItem := range item.Operations() {
for _, pref := range opItem.Parameters {
paramName := pref.Value.Name
parameterIsDisabled := mapConfig.isDisabled(restPath, opName, paramName)
// If we are limited, then don't bother with enabled parameters
if !parameterIsDisabled && limited {
// If the parameter is not disabled, then we don't need
// to do anything
continue
}
var statusStr string
if parameterIsDisabled {
statusStr = disabledStatusStr
} else {
statusStr = enabledStatusStr
}
if pref.Value.Required {
rval.addEntry(restPath, requiredParameterStr, paramName, statusStr)
} else {
// If the optional parameter is disabled, add it to the map
rval.addEntry(restPath, optionalParameterStr, paramName, statusStr)
}
}
}
}
return rval
}
// EndpointConfig is a data structure that contains whether the
// endpoint is disabled (with a boolean) as well as a set that
// contains disabled optional parameters. The disabled optional parameter
// set is keyed by the name of the variable
type EndpointConfig struct {
EndpointDisabled bool
DisabledOptionalParameters map[string]bool
}
// makeEndpointConfig creates a new empty endpoint config
func makeEndpointConfig() *EndpointConfig {
rval := &EndpointConfig{
EndpointDisabled: false,
DisabledOptionalParameters: make(map[string]bool),
}
return rval
}
// DisabledMap a type that holds a map of disabled types
// The key for a disabled map is the handler function name
type DisabledMap struct {
// Key -> Function Name/Operation ID
Data map[string]*EndpointConfig
}
// MakeDisabledMap creates a new empty disabled map
func MakeDisabledMap() *DisabledMap {
return &DisabledMap{
Data: make(map[string]*EndpointConfig),
}
}
// DisabledMapConfig is a type that holds the configuration for setting up
// a DisabledMap
type DisabledMapConfig struct {
// Key -> Path of REST endpoint (i.e. /v2/accounts/{account-id}/transactions)
// Value -> Operation "get, post, etc" -> Sub-value: List of parameters disabled for that endpoint
Data map[string]map[string][]string
}
// isDisabled Returns true if the parameter is disabled for the given path
func (dmc *DisabledMapConfig) isDisabled(restPath string, operationName string, parameterName string) bool {
parameterList, exists := dmc.Data[restPath][operationName]
if !exists {
return false
}
for _, parameter := range parameterList {
if parameterName == parameter {
return true
}
}
return false
}
func (dmc *DisabledMapConfig) addEntry(restPath string, operationName string, parameterNames []string) {
if dmc.Data == nil {
dmc.Data = make(map[string]map[string][]string)
}
if dmc.Data[restPath] == nil {
dmc.Data[restPath] = make(map[string][]string)
}
dmc.Data[restPath][operationName] = parameterNames
}
// MakeDisabledMapConfig creates a new disabled map configuration with everything enabled
func MakeDisabledMapConfig() *DisabledMapConfig {
return &DisabledMapConfig{
Data: make(map[string]map[string][]string),
}
}
// GetDefaultDisabledMapConfigForPostgres will generate a configuration that will block certain
// parameters. Should be used only for the postgres implementation
func GetDefaultDisabledMapConfigForPostgres() *DisabledMapConfig {
rval := MakeDisabledMapConfig()
// Some syntactic sugar
get := func(restPath string, parameterNames []string) {
rval.addEntry(restPath, http.MethodGet, parameterNames)
}
get("/v2/accounts", []string{"currency-greater-than", "currency-less-than"})
get("/v2/accounts/{account-id}/transactions", []string{"note-prefix", "tx-type", "sig-type", "asset-id", "before-time", "after-time", "rekey-to"})
get("/v2/assets", []string{"name", "unit"})
get("/v2/assets/{asset-id}/balances", []string{"currency-greater-than", "currency-less-than"})
get("/v2/transactions", []string{"note-prefix", "tx-type", "sig-type", "asset-id", "before-time", "after-time", "currency-greater-than", "currency-less-than", "address-role", "exclude-close-to", "rekey-to", "application-id"})
get("/v2/assets/{asset-id}/transactions", []string{"note-prefix", "tx-type", "sig-type", "asset-id", "before-time", "after-time", "currency-greater-than", "currency-less-than", "address-role", "exclude-close-to", "rekey-to"})
return rval
}
// ErrDisabledMapConfig contains any mis-spellings that could be present in a configuration
type ErrDisabledMapConfig struct {
// Key -> REST Path that was mis-spelled
// Value -> Operation "get, post, etc" -> Sub-value: Any parameters that were found to be mis-spelled in a valid REST PATH
BadEntries map[string]map[string][]string
}
func (edmc *ErrDisabledMapConfig) Error() string {
var sb strings.Builder
for k, v := range edmc.BadEntries {
// If the length of the list is zero then it is an unknown REST path
if len(v) == 0 {
_, _ = sb.WriteString(fmt.Sprintf("Unknown REST Path: %s\n", k))
continue
}
for op, param := range v {
_, _ = sb.WriteString(fmt.Sprintf("REST Path %s (Operation: %s) contains unknown parameters: %s\n", k, op, strings.Join(param, ",")))
}
}
return sb.String()
}
// makeErrDisabledMapConfig returns a new disabled map config error
func makeErrDisabledMapConfig() *ErrDisabledMapConfig {
return &ErrDisabledMapConfig{
BadEntries: make(map[string]map[string][]string),
}
}
// validate makes sure that all keys and values in the Disabled Map Configuration
// are actually spelled right. What might happen is that a user might
// accidentally mis-spell an entry, so we want to make sure to mitigate against
// that by checking the openapi definition
func (dmc *DisabledMapConfig) validate(swag *openapi3.T) error {
potentialRval := makeErrDisabledMapConfig()
for recordedPath, recordedOp := range dmc.Data {
swagPath, exists := swag.Paths[recordedPath]
if !exists {
// This means that the rest endpoint itself is mis-spelled
potentialRval.BadEntries[recordedPath] = map[string][]string{}
continue
}
for opName, recordedParams := range recordedOp {
// This will panic if it is an illegal name so no need to check for nil
swagOperation := swagPath.GetOperation(opName)
for _, recordedParam := range recordedParams {
found := false
for _, swagParam := range swagOperation.Parameters {
if recordedParam == swagParam.Value.Name {
found = true
break
}
}
if found {
continue
}
// If we didn't find it then it's time to add it to the entry
if potentialRval.BadEntries[recordedPath] == nil {
potentialRval.BadEntries[recordedPath] = make(map[string][]string)
}
potentialRval.BadEntries[recordedPath][opName] = append(potentialRval.BadEntries[recordedPath][opName], recordedParam)
}
}
}
// If we have no entries then don't return an error
if len(potentialRval.BadEntries) != 0 {
return potentialRval
}
return nil
}
// MakeDisabledMapFromOA3 Creates a new disabled map from an openapi3 definition
func MakeDisabledMapFromOA3(swag *openapi3.T, config *DisabledMapConfig) (*DisabledMap, error) {
if config == nil {
return nil, nil
}
err := config.validate(swag)
if err != nil {
return nil, err
}
rval := MakeDisabledMap()
for restPath, item := range swag.Paths {
for opName, opItem := range item.Operations() {
endpointConfig := makeEndpointConfig()
for _, pref := range opItem.Parameters {
paramName := pref.Value.Name
parameterIsDisabled := config.isDisabled(restPath, opName, paramName)
if !parameterIsDisabled {
// If the parameter is not disabled, then we don't need
// to do anything
continue
}
if pref.Value.Required {
// If an endpoint config required parameter is disabled, then the whole endpoint is disabled
endpointConfig.EndpointDisabled = true
} else {
// If the optional parameter is disabled, add it to the map
endpointConfig.DisabledOptionalParameters[paramName] = true
}
}
rval.Data[opItem.OperationID] = endpointConfig
}
}
return rval, err
}
// ErrVerifyFailedEndpoint an error that signifies that the entire endpoint is disabled
var ErrVerifyFailedEndpoint error = fmt.Errorf("endpoint is disabled")
// ErrVerifyFailedParameter an error that signifies that a parameter was provided when it was disabled
type ErrVerifyFailedParameter struct {
ParameterName string
}
func (evfp ErrVerifyFailedParameter) Error() string {
return fmt.Sprintf("provided disabled parameter: %s", evfp.ParameterName)
}
// DisabledParameterErrorReporter defines an error reporting interface
// for the Verify functions
type DisabledParameterErrorReporter interface {
Errorf(format string, args ...interface{})
}
// Verify returns nil if the function can continue (i.e. the parameters are valid and disabled
// parameters are not supplied), otherwise VerifyFailedEndpoint if the endpoint failed and
// VerifyFailedParameter if a disabled parameter was provided.
func Verify(dm *DisabledMap, nameOfHandlerFunc string, ctx echo.Context, log DisabledParameterErrorReporter) error {
if dm == nil || dm.Data == nil {
return nil
}
if val, ok := dm.Data[nameOfHandlerFunc]; ok {
return val.verify(ctx, log)
}
// If the function name wasn't in the map something got messed up....
log.Errorf("verify function could not find name of handler function in map: %s", nameOfHandlerFunc)
// We want to fail-safe to not stop the indexer
return nil
}
func (ec *EndpointConfig) verify(ctx echo.Context, log DisabledParameterErrorReporter) error {
if ec.EndpointDisabled {
return ErrVerifyFailedEndpoint
}
queryParams := ctx.QueryParams()
formParams, formErr := ctx.FormParams()
if formErr != nil {
log.Errorf("retrieving form parameters for verification resulted in an error: %v", formErr)
}
for paramName := range ec.DisabledOptionalParameters {
// The optional param is disabled, check that it wasn't supplied...
queryValue := queryParams.Get(paramName)
if queryValue != "" {
// If the query value is non-zero, and it was disabled, we should return false
return ErrVerifyFailedParameter{paramName}
}
if formErr != nil {
continue
}
formValue := formParams.Get(paramName)
if formValue != "" {
// If the query value is non-zero, and it was disabled, we should return false
return ErrVerifyFailedParameter{paramName}
}
}
return nil
}