/
middleware.go
187 lines (152 loc) · 5.2 KB
/
middleware.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
// Copyright © 2020 Banzai Cloud
//
// 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 auditlog
import (
"bytes"
"io"
"io/ioutil"
"net/http"
"regexp"
"time"
"emperror.dev/errors"
"github.com/gin-gonic/gin"
"github.com/banzaicloud/pipeline/internal/platform/gin/correlationid"
)
// Clock provides time.
type Clock interface {
Now() time.Time
Since(time.Time) time.Duration
}
type realClock struct{}
func (realClock) Now() time.Time { return time.Now() }
func (realClock) Since(t time.Time) time.Duration { return time.Since(t) }
// Driver saves audit log entries.
type Driver interface {
// Store saves an audit log entry.
Store(entry Entry) error
}
// Option configures an audit log middleware.
type Option interface {
// apply is unexported,
// so only the current package can implement this interface.
apply(o *middlewareOptions)
}
// In the future, sensitivePaths and userIDExtractor might be replaced by request matchers and propagators/decorators
// respectively to generalize them for multiple use cases, but for now this solution (borrowed from the previous one)
// should be fine.
type middlewareOptions struct {
clock Clock
sensitivePaths []*regexp.Regexp
userIDExtractor func(req *http.Request) uint
errorHandler ErrorHandler
}
type optionFunc func(o *middlewareOptions)
func (fn optionFunc) apply(o *middlewareOptions) {
fn(o)
}
// WithClock sets the clock in an audit log middleware.
func WithClock(clock Clock) Option {
return optionFunc(func(o *middlewareOptions) {
o.clock = clock
})
}
// WithSensitivePaths marks API call paths as sensitive, causing the log entry to omit the request body.
func WithSensitivePaths(sensitivePaths []*regexp.Regexp) Option {
return optionFunc(func(o *middlewareOptions) {
o.sensitivePaths = sensitivePaths
})
}
// WithErrorHandler sets the clock in an audit log middleware.
func WithErrorHandler(errorHandler ErrorHandler) Option {
return optionFunc(func(o *middlewareOptions) {
o.errorHandler = errorHandler
})
}
// WithUserIDExtractor sets the function that extracts the user ID from the request.
func WithUserIDExtractor(userIDExtractor func(req *http.Request) uint) Option {
return optionFunc(func(o *middlewareOptions) {
o.userIDExtractor = userIDExtractor
})
}
// Middleware returns a new HTTP middleware that records audit log entries.
func Middleware(driver Driver, opts ...Option) gin.HandlerFunc {
options := middlewareOptions{
clock: realClock{},
userIDExtractor: func(req *http.Request) uint { return 0 },
errorHandler: NoopErrorHandler{},
}
for _, opt := range opts {
opt.apply(&options)
}
return func(c *gin.Context) {
path := c.Request.URL.Path
if c.Request.URL.RawQuery != "" {
path = path + "?" + c.Request.URL.RawQuery
}
entry := Entry{
Time: options.clock.Now(),
CorrelationID: c.GetString(correlationid.ContextKey),
HTTP: HTTPEntry{
ClientIP: c.ClientIP(),
UserAgent: c.Request.UserAgent(),
Method: c.Request.Method,
Path: path,
},
}
var sensitiveCall bool
// Determine if this call contains sensitive information in its request body.
for _, r := range options.sensitivePaths {
if r.MatchString(c.Request.URL.Path) {
sensitiveCall = true
break
}
}
// Only override the request body if there is actually one and it doesn't contain sensitive information.
saveBody := c.Request.Body != nil && !sensitiveCall
var buf bytes.Buffer
if saveBody {
// This should be ok, because the server keeps a reference to the original body,
// so it can close the original request itself.
c.Request.Body = ioutil.NopCloser(io.TeeReader(c.Request.Body, &buf))
}
c.Next() // process request
entry.UserID = options.userIDExtractor(c.Request)
// Consider making this configurable if you need to log unauthorized requests,
// but keep in mind that in case of a public installation it's a potential DoS attack vector.
if c.Writer.Status() == http.StatusUnauthorized {
return
}
entry.HTTP.StatusCode = c.Writer.Status()
entry.HTTP.ResponseSize = c.Writer.Size()
entry.HTTP.ResponseTime = int(options.clock.Since(entry.Time).Milliseconds())
if saveBody {
// Make sure everything is read from the body.
_, err := ioutil.ReadAll(c.Request.Body)
if err != nil && err != io.EOF {
options.errorHandler.HandleContext(c.Request.Context(), errors.WithStack(err))
}
entry.HTTP.RequestBody = string(buf.Bytes())
}
if c.IsAborted() {
for _, e := range c.Errors {
_e, _ := e.MarshalJSON()
entry.HTTP.Errors = append(entry.HTTP.Errors, string(_e))
}
}
err := driver.Store(entry)
if err != nil {
options.errorHandler.HandleContext(c.Request.Context(), errors.WithStackIf(err))
}
}
}