-
Notifications
You must be signed in to change notification settings - Fork 0
/
writer.go
173 lines (144 loc) · 3.82 KB
/
writer.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
package audit
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
lumberjack "gopkg.in/natefinch/lumberjack.v2"
k8stypes "k8s.io/apimachinery/pkg/types"
utilnet "k8s.io/apimachinery/pkg/util/net"
)
const (
contentTypeJSON = "application/json"
)
const (
levelNull = iota
levelMetadata
levelRequest
levelRequestResponse
)
var (
auditLevel = map[int]string{
levelMetadata: "MetadataLevel",
levelRequest: "RequestLevel",
levelRequestResponse: "RequestResponseLevel",
}
bodyMethods = map[string]bool{
http.MethodPut: true,
http.MethodPost: true,
}
)
const (
requestReceived = "RequestReceived"
responseComplete = "ResponseComplete"
)
type Log struct {
AuditID k8stypes.UID `json:"auditID,omitempty"`
RequestURI string `json:"requestURI,omitempty"`
RequestBody interface{} `json:"requestBody,omitempty"`
ResponseBody interface{} `json:"responseBody,omitempty"`
ResponseStatus string `json:"responseStatus,omitempty"`
SourceIPs []string `json:"sourceIPs,omitempty"`
User *userInfo `json:"user,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
Verb string `json:"verb,omitempty"`
Stage string `json:"stage,omitempty"`
StageTimestamp string `json:"stageTimestamp,omitempty"`
}
type userInfo struct {
Name string `json:"name,omitempty"`
Group []string `json:"group,omitempty"`
}
type LogWriter struct {
Level int
Output *lumberjack.Logger
}
func NewLogWriter(path string, level, maxAge, maxBackup, maxSize int) *LogWriter {
if path == "" || level == levelNull {
return nil
}
return &LogWriter{
Level: level,
Output: &lumberjack.Logger{
Filename: path,
MaxAge: maxAge,
MaxBackups: maxBackup,
MaxSize: maxSize,
},
}
}
func (a *LogWriter) LogRequest(req *http.Request, auditID k8stypes.UID, authed bool, contentType, user string, group []string) error {
al := &Log{
AuditID: auditID,
Stage: requestReceived,
StageTimestamp: time.Now().Format("2006-01-02 15:04:05 -0700"),
RequestURI: req.RequestURI,
Verb: req.Method,
}
ips := utilnet.SourceIPs(req)
var sourceIPs []string
for i := range ips {
sourceIPs = append(sourceIPs, ips[i].String())
}
al.SourceIPs = sourceIPs
if authed {
al.User = &userInfo{
Name: user,
Group: group,
}
}
var buffer bytes.Buffer
alByte, err := json.Marshal(al)
if err != nil {
return err
}
buffer.Write(bytes.TrimRight(alByte, "}\n"))
if a.Level >= levelRequest && bodyMethods[req.Method] && contentType == contentTypeJSON {
reqBody, err := readBodyWithoutLosingContent(req)
if err != nil {
return err
}
buffer.WriteString(`,"requestBody":`)
buffer.Write(bytes.TrimRight(reqBody, "\n"))
}
buffer.WriteString("}\n")
_, err = a.Output.Write(buffer.Bytes())
return err
}
func (a *LogWriter) LogResponse(resBody []byte, auditID k8stypes.UID, statusCode int, contentType string) error {
if a.Level < levelRequestResponse {
return nil
}
al := &Log{
AuditID: auditID,
Stage: responseComplete,
StageTimestamp: time.Now().Format("2006-01-02 15:04:05 -0700"),
ResponseStatus: fmt.Sprint(statusCode),
}
var buffer bytes.Buffer
alByte, err := json.Marshal(al)
if err != nil {
return err
}
buffer.Write(bytes.TrimRight(alByte, "}\n"))
if contentType == contentTypeJSON {
buffer.WriteString(`,"responseBody":`)
buffer.Write(bytes.TrimRight(resBody, "\n"))
}
buffer.WriteString("}\n")
_, err = a.Output.Write(buffer.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
}