Repository navigation
Expand file tree
/
Copy pathbody_dump.go
More file actions
201 lines (171 loc) · 5.56 KB
/
Copy pathbody_dump.go
File metadata and controls
201 lines (171 loc) · 5.56 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
// SPDX-License-Identifier: MIT
// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors
package middleware
import (
"bufio"
"bytes"
"errors"
"io"
"net"
"net/http"
"sync"
"github.com/labstack/echo/v5"
)
// BodyDumpConfig defines the config for BodyDump middleware.
type BodyDumpConfig struct {
// Skipper defines a function to skip middleware.
Skipper Skipper
// Handler receives request, response payloads and handler error if there are any.
// Required.
Handler BodyDumpHandler
// MaxRequestBytes limits how much of the request body to dump.
// If the request body exceeds this limit, only the first MaxRequestBytes
// are dumped. The handler callback receives truncated data.
// The next handler still receives the full request body.
// Default: 5 * MB (5,242,880 bytes)
// Set to -1 to disable limits (not recommended in production).
MaxRequestBytes int64
// MaxResponseBytes limits how much of the response body to dump.
// If the response body exceeds this limit, only the first MaxResponseBytes
// are dumped. The handler callback receives truncated data.
// Default: 5 * MB (5,242,880 bytes)
// Set to -1 to disable limits (not recommended in production).
MaxResponseBytes int64
}
// BodyDumpHandler receives the request and response payload.
type BodyDumpHandler func(c *echo.Context, reqBody []byte, resBody []byte, err error)
type bodyDumpResponseWriter struct {
io.Writer
http.ResponseWriter
}
// BodyDump returns a BodyDump middleware.
//
// BodyDump middleware captures the request and response payload and calls the
// registered handler.
//
// SECURITY: By default, this limits dumped bodies to 5MB to prevent memory exhaustion
// attacks. To customize limits, use BodyDumpWithConfig. To disable limits (not recommended
// in production), explicitly set MaxRequestBytes and MaxResponseBytes to -1.
func BodyDump(handler BodyDumpHandler) echo.MiddlewareFunc {
return BodyDumpWithConfig(BodyDumpConfig{Handler: handler})
}
// BodyDumpWithConfig returns a BodyDump middleware with config.
// See: `BodyDump()`.
//
// SECURITY: If MaxRequestBytes and MaxResponseBytes are not set (zero values), they default
// to 5MB each to prevent DoS attacks via large payloads. Set them explicitly to -1 to disable
// limits if needed for your use case.
func BodyDumpWithConfig(config BodyDumpConfig) echo.MiddlewareFunc {
return toMiddlewareOrPanic(config)
}
// ToMiddleware converts BodyDumpConfig to middleware or returns an error for invalid configuration
func (config BodyDumpConfig) ToMiddleware() (echo.MiddlewareFunc, error) {
if config.Handler == nil {
return nil, errors.New("echo body-dump middleware requires a handler function")
}
if config.Skipper == nil {
config.Skipper = DefaultSkipper
}
if config.MaxRequestBytes == 0 {
config.MaxRequestBytes = 5 * MB
}
if config.MaxResponseBytes == 0 {
config.MaxResponseBytes = 5 * MB
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
if config.Skipper(c) {
return next(c)
}
reqBuf := bodyDumpBufferPool.Get().(*bytes.Buffer)
reqBuf.Reset()
defer bodyDumpBufferPool.Put(reqBuf)
var bodyReader io.Reader = c.Request().Body
if config.MaxRequestBytes > 0 {
bodyReader = io.LimitReader(c.Request().Body, config.MaxRequestBytes)
}
_, readErr := io.Copy(reqBuf, bodyReader)
if readErr != nil && readErr != io.EOF {
return readErr
}
reqBody := make([]byte, reqBuf.Len())
copy(reqBody, reqBuf.Bytes())
c.Request().Body = struct {
io.Reader
io.Closer
}{
Reader: io.MultiReader(bytes.NewReader(reqBody), c.Request().Body),
Closer: c.Request().Body,
}
// response part
resBuf := bodyDumpBufferPool.Get().(*bytes.Buffer)
resBuf.Reset()
defer bodyDumpBufferPool.Put(resBuf)
var respWriter io.Writer
if config.MaxResponseBytes > 0 {
respWriter = &limitedWriter{
response: c.Response(),
dumpBuf: resBuf,
limit: config.MaxResponseBytes,
}
} else {
respWriter = io.MultiWriter(c.Response(), resBuf)
}
origResponse := c.Response()
writer := &bodyDumpResponseWriter{
Writer: respWriter,
ResponseWriter: origResponse,
}
c.SetResponse(writer)
defer c.SetResponse(origResponse)
err := next(c)
// Callback
config.Handler(c, reqBody, resBuf.Bytes(), err)
return err
}
}, nil
}
func (w *bodyDumpResponseWriter) WriteHeader(code int) {
w.ResponseWriter.WriteHeader(code)
}
func (w *bodyDumpResponseWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}
func (w *bodyDumpResponseWriter) Flush() {
err := http.NewResponseController(w.ResponseWriter).Flush()
if err != nil && errors.Is(err, http.ErrNotSupported) {
panic(errors.New("response writer flushing is not supported"))
}
}
func (w *bodyDumpResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
return http.NewResponseController(w.ResponseWriter).Hijack()
}
func (w *bodyDumpResponseWriter) Unwrap() http.ResponseWriter {
return w.ResponseWriter
}
var bodyDumpBufferPool = sync.Pool{
New: func() any {
return new(bytes.Buffer)
},
}
type limitedWriter struct {
response http.ResponseWriter
dumpBuf *bytes.Buffer
dumped int64
limit int64
}
func (w *limitedWriter) Write(b []byte) (n int, err error) {
// Always write full data to actual response (don't truncate client response)
n, err = w.response.Write(b)
if err != nil {
return n, err
}
// Write to dump buffer only up to limit
if w.dumped < w.limit {
remaining := w.limit - w.dumped
toDump := min(int64(n), remaining)
w.dumpBuf.Write(b[:toDump])
w.dumped += toDump
}
return n, nil
}