-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjsonrpcfilter.go
116 lines (93 loc) · 2.34 KB
/
jsonrpcfilter.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
package traefik_jsonrpc_filter
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type Config struct {
Allowlist []string `json:"allowlist,omitempty"`
BatchedRequestLimit int `json:"batchedRequestLimit,omitempty"`
}
func CreateConfig() *Config {
return &Config{
Allowlist: make([]string, 0),
BatchedRequestLimit: 1,
}
}
type JSONRPCFilter struct {
next http.Handler
allowlist []string
batchedRequestLimit int
name string
}
type JSONRPCRequest struct {
Method string `json:"method"`
}
func stringInSlice(target string, list []string) bool {
for _, b := range list {
if b == target {
return true
}
}
return false
}
func (jf *JSONRPCFilter) isSingleRequestBlocked(req JSONRPCRequest) bool {
return !stringInSlice(req.Method, jf.allowlist)
}
func (jf *JSONRPCFilter) isBatchRequestBlocked(reqs []JSONRPCRequest) bool {
if len(reqs) > jf.batchedRequestLimit {
return true
}
for _, req := range reqs {
if jf.isSingleRequestBlocked(req) {
return true
}
}
return false
}
func New(ctx context.Context, next http.Handler, config *Config, name string) (http.Handler, error) {
if len(config.Allowlist) == 0 {
return nil, fmt.Errorf("allowlist cannot be empty")
}
return &JSONRPCFilter{
allowlist: config.Allowlist,
batchedRequestLimit: config.BatchedRequestLimit,
next: next,
name: name,
}, nil
}
func (jf *JSONRPCFilter) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
body, err := ioutil.ReadAll(req.Body)
req.Body.Close()
req.Body = ioutil.NopCloser(bytes.NewBuffer(body))
if err != nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
parsed_request := JSONRPCRequest{}
err = json.Unmarshal(body, &parsed_request)
if err == nil {
blocked := jf.isSingleRequestBlocked(parsed_request)
if blocked {
http.Error(rw, "JSON-RPC method blocked", http.StatusForbidden)
return
}
jf.next.ServeHTTP(rw, req)
return
}
batched_requests := make([]JSONRPCRequest, 0)
err = json.Unmarshal(body, &batched_requests)
if err == nil {
blocked := jf.isBatchRequestBlocked(batched_requests)
if blocked {
http.Error(rw, "JSON-RPC methods blocked", http.StatusForbidden)
return
}
jf.next.ServeHTTP(rw, req)
return
}
jf.next.ServeHTTP(rw, req)
}