forked from rancher/rancher
-
Notifications
You must be signed in to change notification settings - Fork 1
/
audit.go
170 lines (147 loc) · 4.39 KB
/
audit.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
package audit
import (
"bytes"
"context"
"encoding/json"
"io/ioutil"
"net/http"
"time"
"github.com/pborman/uuid"
"github.com/pkg/errors"
k8stypes "k8s.io/apimachinery/pkg/types"
)
const (
contentTypeJSON = "application/json"
)
const (
levelNull = iota
levelMetadata
levelRequest
levelRequestResponse
)
var (
bodyMethods = map[string]bool{
http.MethodPut: true,
http.MethodPost: true,
}
sensitiveRequestHeader = []string{"Cookie", "Authorization"}
sensitiveResponseHeader = []string{"Cookie", "Set-Cookie"}
)
type auditLog struct {
log *log
writer *LogWriter
reqBody []byte
}
type log struct {
AuditID k8stypes.UID `json:"auditID,omitempty"`
RequestURI string `json:"requestURI,omitempty"`
User *UserInfo `json:"user,omitempty"`
Method string `json:"method,omitempty"`
RemoteAddr string `json:"remoteAddr,omitempty"`
RequestTimestamp string `json:"requestTimestamp,omitempty"`
ResponseTimestamp string `json:"responseTimestamp,omitempty"`
ResponseCode int `json:"responseCode,omitempty"`
RequestHeader http.Header `json:"requestHeader,omitempty"`
ResponseHeader http.Header `json:"responseHeader,omitempty"`
RequestBody []byte `json:"requestBody,omitempty"`
ResponseBody []byte `json:"responseBody,omitempty"`
}
var userKey struct{}
type UserInfo struct {
Name string `json:"name,omitempty"`
Group []string `json:"group,omitempty"`
// RequestUser is the --as user
RequestUser string `json:"requestUser,omitempty"`
// RequestGroups is the --as-group list
RequestGroups []string `json:"requestGroups,omitempty"`
}
func GetUserInfo(req *http.Request) *UserInfo {
return &UserInfo{
Name: req.Header.Get("Impersonate-User"),
Group: req.Header["Impersonate-Group"],
}
}
func FromContext(ctx context.Context) (*UserInfo, bool) {
u, ok := ctx.Value(userKey).(*UserInfo)
return u, ok
}
func new(writer *LogWriter, req *http.Request) (*auditLog, error) {
auditLog := &auditLog{
writer: writer,
log: &log{
AuditID: k8stypes.UID(uuid.NewRandom().String()),
RequestURI: req.RequestURI,
Method: req.Method,
RemoteAddr: req.RemoteAddr,
RequestTimestamp: time.Now().Format(time.RFC3339),
},
}
contentType := req.Header.Get("Content-Type")
if writer.Level >= levelRequest && bodyMethods[req.Method] && contentType == contentTypeJSON {
reqBody, err := readBodyWithoutLosingContent(req)
if err != nil {
return nil, err
}
auditLog.reqBody = reqBody
}
return auditLog, nil
}
func (a *auditLog) write(userInfo *UserInfo, reqHeaders, resHeaders http.Header, resCode int, resBody []byte) error {
a.log.User = userInfo
a.log.ResponseTimestamp = time.Now().Format(time.RFC3339)
a.log.RequestHeader = filterOutHeaders(reqHeaders, sensitiveRequestHeader)
a.log.ResponseHeader = filterOutHeaders(resHeaders, sensitiveResponseHeader)
a.log.ResponseCode = resCode
var buffer bytes.Buffer
alByte, err := json.Marshal(a.log)
if err != nil {
return err
}
buffer.Write(bytes.TrimSuffix(alByte, []byte("}")))
if a.writer.Level >= levelRequest && len(a.reqBody) > 0 {
buffer.WriteString(`,"requestBody":`)
buffer.Write(bytes.TrimSuffix(a.reqBody, []byte("\n")))
}
if a.writer.Level >= levelRequestResponse && resHeaders.Get("Content-Type") == contentTypeJSON && len(resBody) > 0 {
buffer.WriteString(`,"responseBody":`)
buffer.Write(bytes.TrimSuffix(resBody, []byte("\n")))
}
buffer.WriteString("}")
var compactBuffer bytes.Buffer
err = json.Compact(&compactBuffer, buffer.Bytes())
if err != nil {
return errors.Wrap(err, "compact audit log json failed")
}
compactBuffer.WriteString("\n")
_, err = a.writer.Output.Write(compactBuffer.Bytes())
return err
}
func readBodyWithoutLosingContent(req *http.Request) ([]byte, error) {
if !bodyMethods[req.Method] {
return nil, nil
}
bodyBytes, err := ioutil.ReadAll(req.Body)
if err != nil {
return nil, err
}
req.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
return bodyBytes, nil
}
func filterOutHeaders(headers http.Header, filterKeys []string) map[string][]string {
newHeader := make(map[string][]string)
for k, v := range headers {
if isExist(filterKeys, k) {
continue
}
newHeader[k] = v
}
return newHeader
}
func isExist(array []string, key string) bool {
for _, v := range array {
if v == key {
return true
}
}
return false
}