-
Notifications
You must be signed in to change notification settings - Fork 573
/
audit_log.go
228 lines (201 loc) · 6.02 KB
/
audit_log.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
package handler
import (
"encoding/json"
"errors"
"net/http"
"time"
"github.com/deepfence/ThreatMapper/deepfence_server/model"
reporters_search "github.com/deepfence/ThreatMapper/deepfence_server/reporters/search"
"github.com/deepfence/ThreatMapper/deepfence_utils/directory"
"github.com/deepfence/ThreatMapper/deepfence_utils/log"
postgresql_db "github.com/deepfence/ThreatMapper/deepfence_utils/postgresql/postgresql-db"
"github.com/deepfence/ThreatMapper/deepfence_utils/telemetry"
"github.com/deepfence/ThreatMapper/deepfence_utils/utils"
"github.com/go-chi/jwtauth/v5"
httpext "github.com/go-playground/pkg/v5/net/http"
"github.com/lestrrat-go/jwx/v2/jwt"
"github.com/twmb/franz-go/pkg/kgo"
)
const (
EventComplianceScan = string(utils.NEO4JComplianceScan)
EventVulnerabilityScan = string(utils.NEO4JVulnerabilityScan)
EventSecretScan = string(utils.NEO4JSecretScan)
EventMalwareScan = string(utils.NEO4JMalwareScan)
EventIntegration = "integration"
EventGenerativeAIIntegration = "generative-ai-integration"
EventAuth = "auth"
EventReports = "reports"
EventSettings = "settings"
EventRegistry = "registry"
ActionStart = "start"
ActionStop = "stop"
ActionLogout = "logout"
ActionLogin = "login"
ActionInvite = "invite"
ActionInterrupt = "interrupt"
ActionCreate = "create"
ActionUpdate = "update"
ActionDelete = "delete"
ActionEnable = "enable"
ActionDisable = "disable"
ActionBulk = "bulk"
ActionDownload = "download"
ActionNotify = "notify"
ActionResetPassword = "reset_password"
ActionVerifyPassword = "verify_password"
ActionResetToken = "reset_token"
ActionTokenAuth = "token_auth"
ActionLogs = "logs"
)
func GetTokenFromRequest(ja *jwtauth.JWTAuth, r *http.Request) (jwt.Token, error) {
var tokenString string
findTokenFns := []func(r *http.Request) string{
jwtauth.TokenFromHeader,
jwtauth.TokenFromCookie,
}
for _, fn := range findTokenFns {
tokenString = fn(r)
if tokenString != "" {
break
}
}
if tokenString == "" {
return nil, jwtauth.ErrNoTokenFound
}
return ja.Decode(tokenString)
}
func (h *Handler) AuditUserActivity(
req *http.Request,
event string,
action string,
resources interface{},
success bool,
) {
_, span := telemetry.NewSpan(req.Context(), "audit-log", "audit-user-activity")
defer span.End()
var (
userEmail string
userRole string
namespace string
claims = map[string]interface{}{}
)
token, err := GetTokenFromRequest(h.TokenAuth, req)
if err != nil {
if !errors.Is(err, jwtauth.ErrNoTokenFound) {
log.Error().Msg(err.Error())
}
} else {
claims = token.PrivateClaims()
if claims["email"] == nil || claims["role"] == nil || claims[directory.NamespaceKey] == nil {
log.Warn().Msg("AuditUserActivity claims value is nil")
return
}
userEmail = claims["email"].(string)
userRole = claims["role"].(string)
namespace = claims[directory.NamespaceKey].(string)
}
if event == EventAuth && (action == ActionLogin || action == ActionTokenAuth || action == ActionCreate) {
user := resources.(*model.User)
userEmail = user.Email
userRole = user.Role
namespace = user.CompanyNamespace
}
var resourceStr string
if resources != nil {
rStr, err := json.Marshal(resources)
if err != nil {
log.Error().Err(err).Msg("failed to marshal resources")
rStr = []byte("")
}
resourceStr = string(rStr)
} else {
rStr, err := json.Marshal(claims)
if err != nil {
log.Error().Err(err).Msg("failed to marshal claims from jwt")
rStr = []byte("")
}
resourceStr = string(rStr)
}
params := postgresql_db.CreateAuditLogParams{
Event: event,
Action: action,
Resources: resourceStr,
Success: success,
UserEmail: userEmail,
UserRole: userRole,
CreatedAt: time.Now(),
}
if namespace == "" {
log.Error().Msgf("namespace unknown in audit log: %v", params)
return
}
go h.AddAuditLog(namespace, params)
}
func (h *Handler) AddAuditLog(namespace string, params postgresql_db.CreateAuditLogParams) {
data, err := json.Marshal(params)
if err != nil {
log.Error().Msg(err.Error())
return
}
h.IngestChan <- &kgo.Record{
Topic: utils.AuditLogs,
Value: data,
Headers: []kgo.RecordHeader{
{Key: "namespace", Value: []byte(namespace)},
},
}
}
func (h *Handler) GetAuditLogsCount(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
pgClient, err := directory.PostgresClient(ctx)
if err != nil {
log.Error().Err(err).Msg("failed to get db connection")
h.respondError(err, w)
return
}
count, err := pgClient.CountAuditLogs(ctx)
if err != nil {
log.Error().Err(err).Msg("failed to run CountAuditLogs query")
h.respondError(err, w)
return
}
err = httpext.JSON(w, http.StatusOK, reporters_search.SearchCountResp{
Count: int(count),
})
if err != nil {
log.Error().Msg(err.Error())
}
}
func (h *Handler) GetAuditLogs(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
var req model.GetAuditLogsRequest
err := httpext.DecodeJSON(r, httpext.NoQueryParams, MaxPostRequestSize, &req)
if err != nil {
h.respondError(&BadDecoding{err}, w)
return
}
ctx := r.Context()
pgClient, err := directory.PostgresClient(ctx)
if err != nil {
log.Error().Err(err).Msg("failed to get db connection")
h.respondError(err, w)
return
}
auditLogs, err := pgClient.GetAuditLogs(ctx, postgresql_db.GetAuditLogsParams{
Offset: int32(req.Window.Offset),
Limit: int32(req.Window.Size),
})
if err != nil {
log.Error().Msgf("%v", err)
h.respondError(err, w)
return
}
if len(auditLogs) == 0 {
// This is to handle when there's no data in DB
auditLogs = make([]postgresql_db.GetAuditLogsRow, 0)
}
err = httpext.JSON(w, http.StatusOK, auditLogs)
if err != nil {
log.Error().Msg(err.Error())
}
}