-
Notifications
You must be signed in to change notification settings - Fork 9
/
filter.go
296 lines (260 loc) · 7.91 KB
/
filter.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
package filter
import (
"bytes"
"fmt"
"io"
"log"
"net/http"
"net/http/httptest"
"regexp"
"strconv"
"go.uber.org/zap"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
)
func init() {
caddy.RegisterModule(Middleware{})
httpcaddyfile.RegisterHandlerDirective("filter", parseCaddyfile)
}
var paramReplacementPattern = regexp.MustCompile("\\{[a-zA-Z0-9_\\-.]+?}")
// Middleware implements an HTTP handler that replaces response contents based on regex
//
// Additional configuration is required in addition to adding a filter{} block. See
// Github page for instructions.
type Middleware struct {
// Regex to specify which kind of response should we filter
ContentType string `json:"content_type"`
// Regex to specify which pattern to look up
SearchPattern string `json:"search_pattern"`
// A byte-array specifying the string used to replace matches
Replacement []byte `json:"replacement"`
MaxSize int `json:"max_size"`
Path string `json:"path"`
compiledContentTypeRegex *regexp.Regexp
compiledSearchRegex *regexp.Regexp
compiledPathRegex *regexp.Regexp
logger *zap.Logger
}
// CaddyModule returns the Caddy module information.
func (Middleware) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "http.handlers.filter",
New: func() caddy.Module { return new(Middleware) },
}
}
const DefaultMaxSize = 2 * 1024 * 1024
// Provision implements caddy.Provisioner.
func (m *Middleware) Provision(ctx caddy.Context) error {
var err error
m.logger = ctx.Logger(m)
m.logger.Debug(fmt.Sprintf("ContentType: %s. SearchPattern: %s",
m.ContentType,
m.SearchPattern))
if m.MaxSize == 0 {
m.MaxSize = DefaultMaxSize
}
if m.Path == "" {
m.Path = ".*"
}
if m.compiledContentTypeRegex, err = regexp.Compile(m.ContentType); err != nil {
return fmt.Errorf("invalid content_type: %w", err)
}
if m.compiledSearchRegex, err = regexp.Compile(m.SearchPattern); err != nil {
return fmt.Errorf("invalid search_pattern: %w", err)
}
if m.compiledPathRegex, err = regexp.Compile(m.Path); err != nil {
return fmt.Errorf("invalid path: %w", err)
}
return nil
}
// Validate implements caddy.Validator.
func (m *Middleware) Validate() error {
return nil
}
// CappedSizeRecorder is like httptest.ResponseRecorder,
// but with a cap.
//
// When the size of body exceeds cap,
// CappedSizeRecorder flushes all contents in ResponseRecorder
// together with all subsequent writes into the ResponseWriter
type CappedSizeRecorder struct {
overflowed bool
recorder *httptest.ResponseRecorder
w http.ResponseWriter
cap int
}
func NewCappedSizeRecorder(cap int, w http.ResponseWriter) *CappedSizeRecorder {
return &CappedSizeRecorder{
overflowed: false,
recorder: httptest.NewRecorder(),
w: w,
cap: cap,
}
}
func (csr *CappedSizeRecorder) Overflowed() bool {
return csr.overflowed
}
func (csr *CappedSizeRecorder) Header() http.Header {
return csr.recorder.Header()
}
func (csr *CappedSizeRecorder) FlushHeaders() {
for k, vs := range csr.recorder.Header() {
for _, v := range vs {
csr.w.Header().Add(k, v)
}
}
csr.w.WriteHeader(csr.recorder.Code)
}
// Flush contents to writer
func (csr *CappedSizeRecorder) Flush() (int64, error) {
if !csr.overflowed {
log.Fatal("Flush called when overflowed is false")
}
csr.FlushHeaders()
return io.Copy(csr.w, csr.recorder.Body)
}
func (csr *CappedSizeRecorder) Recorder() *httptest.ResponseRecorder {
if csr.overflowed {
log.Fatal("trying to get Recorder when overflowed")
}
return csr.recorder
}
func (csr *CappedSizeRecorder) Write(b []byte) (int, error) {
if !csr.overflowed && len(b)+csr.recorder.Body.Len() > csr.cap {
csr.overflowed = true
if written, err := csr.Flush(); err != nil {
return int(written), err
}
}
if csr.overflowed {
return csr.w.Write(b)
} else {
return csr.recorder.Write(b)
}
}
func (csr *CappedSizeRecorder) WriteHeader(statusCode int) {
if csr.overflowed {
log.Fatal("CappedSizeRecorder overflowed on WriteHeader")
}
csr.recorder.WriteHeader(statusCode)
}
// Performs the replacement of each placeholder in the previously matched response fragment
// (matched using SearchRegex).
func (m Middleware) replacer(input []byte, repl *caddy.Replacer) []byte {
pattern := m.compiledSearchRegex
if pattern == nil {
return input
}
if len(m.Replacement) <= 0 {
return []byte{}
}
groups := pattern.FindSubmatch(input)
replacement := paramReplacementPattern.ReplaceAllFunc(m.Replacement, func(input2 []byte) []byte {
return m.paramReplacer(input2, groups, repl) // forward the placeholder replacement
})
return replacement
}
// This method supports two types of placeholders:
// - {N} where N matches any capturing group of SearchRegex
// - {X} where X is any key available in caddy.Replacer
func (m Middleware) paramReplacer(input []byte, groups [][]byte, repl *caddy.Replacer) []byte {
if len(input) < 3 {
return input
}
// replace based on a capturing group
name := string(input[1 : len(input)-1])
if index, err := strconv.Atoi(name); err == nil {
if index >= 0 && index < len(groups) {
return groups[index]
}
return input
}
// replace based on caddy's replacer
if value, found := repl.GetString(name); found {
return []byte(value)
}
return input
}
// ServeHTTP implements caddyhttp.MiddlewareHandler.
func (m Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
if !m.compiledPathRegex.MatchString(r.URL.Path) {
return next.ServeHTTP(w, r)
}
csr := NewCappedSizeRecorder(m.MaxSize, w)
nextErr := next.ServeHTTP(csr, r)
if csr.Overflowed() {
return nextErr
}
if m.compiledContentTypeRegex.MatchString(csr.Recorder().Result().Header.Get("Content-Type")) {
buf := new(bytes.Buffer)
repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
if _, err := buf.ReadFrom(csr.Recorder().Result().Body); err != nil {
return fmt.Errorf("failed to read from response body: %w", err)
}
replaced := m.compiledSearchRegex.ReplaceAllFunc(buf.Bytes(), func(input []byte) []byte {
return m.replacer(input, repl) // forward the replacement processing
})
oldContentLength := csr.Header().Get("Content-Length")
if len(oldContentLength) > 0 {
csr.Header().Set("Content-Length", strconv.Itoa(len(replaced)))
}
csr.FlushHeaders()
if _, err := io.Copy(w, bytes.NewReader(replaced)); err != nil {
return fmt.Errorf("error when copying replaced response body: %w", err)
}
} else {
csr.FlushHeaders()
if _, err := io.Copy(w, csr.recorder.Body); err != nil {
return fmt.Errorf("error when copying response body: %w", err)
}
}
return nextErr
}
// UnmarshalCaddyfile implements caddyfile.Unmarshaler.
func (m *Middleware) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
if !d.Next() {
return d.Err("expected token following filter")
}
for d.NextBlock(0) {
key := d.Val()
var value string
d.Args(&value)
if d.NextArg() {
return d.ArgErr()
}
switch key {
case "content_type":
m.ContentType = value
case "search_pattern":
m.SearchPattern = value
case "replacement":
m.Replacement = []byte(value)
case "max_size":
val, err := strconv.Atoi(value)
if err != nil {
_ = d.Err(fmt.Sprintf("max_size error: %s", err.Error()))
}
m.MaxSize = val
case "path":
m.Path = value
default:
return d.Err(fmt.Sprintf("invalid key for filter directive: %s", key))
}
}
return nil
}
// parseCaddyfile unmarshals tokens from h into a new Middleware.
func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
var m Middleware
err := m.UnmarshalCaddyfile(h.Dispenser)
return m, err
}
// Interface guards
var (
_ caddy.Provisioner = (*Middleware)(nil)
_ caddy.Validator = (*Middleware)(nil)
_ caddyhttp.MiddlewareHandler = (*Middleware)(nil)
_ caddyfile.Unmarshaler = (*Middleware)(nil)
)