-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathlogging.go
170 lines (136 loc) · 4.33 KB
/
logging.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
/*
Copyright 2024-2025 the Unikorn Authors.
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 audit
import (
"encoding/json"
"net/http"
"regexp"
"strings"
"github.com/getkin/kin-openapi/routers"
"github.com/unikorn-cloud/core/pkg/openapi"
"github.com/unikorn-cloud/core/pkg/server/errors"
"github.com/unikorn-cloud/core/pkg/server/middleware"
"github.com/unikorn-cloud/identity/pkg/middleware/authorization"
"sigs.k8s.io/controller-runtime/pkg/log"
)
type Logger struct {
// next defines the next HTTP handler in the chain.
next http.Handler
// openapi caches the Schema schema.
openapi *openapi.Schema
// application is the application name.
application string
// version is the application version.
version string
}
// Ensure this implements the required interfaces.
var _ http.Handler = &Logger{}
// New returns an initialized middleware.
func New(next http.Handler, openapi *openapi.Schema, application, version string) *Logger {
return &Logger{
next: next,
openapi: openapi,
application: application,
version: version,
}
}
// getResource will resolve to a resource type.
func getResource(w *middleware.LoggingResponseWriter, r *http.Request, route *routers.Route, params map[string]string) *Resource {
// Creates rely on the response containing the resource ID in the response metadata.
if r.Method == http.MethodPost {
// Nothing written, possibly a bug somewhere?
if w.Body() == nil {
return nil
}
var metadata struct {
Metadata openapi.ResourceReadMetadata `json:"metadata"`
}
// Not a canonical API resource, possibly a bug somewhere?
if err := json.Unmarshal(w.Body().Bytes(), &metadata); err != nil {
return nil
}
segments := strings.Split(route.Path, "/")
return &Resource{
Type: segments[len(segments)-1],
ID: metadata.Metadata.Id,
}
}
// Read, updates and deletes you can get the information from the route.
matches := regexp.MustCompile(`/([^/]+)/{([^/}]+)}$`).FindStringSubmatch(route.Path)
if matches == nil {
return nil
}
return &Resource{
Type: matches[1],
ID: params[matches[2]],
}
}
// ServeHTTP implements the http.Handler interface.
func (l *Logger) ServeHTTP(w http.ResponseWriter, r *http.Request) {
route, params, err := l.openapi.FindRoute(r)
if err != nil {
errors.HandleError(w, r, errors.OAuth2ServerError("route lookup failure").WithError(err))
return
}
writer := middleware.NewLoggingResponseWriter(w)
l.next.ServeHTTP(writer, r)
// Users and auditors care about things coming, going and changing, who did
// those things and when? Certainly not periodic polling that is par for the
// course. Failures of reads may be indicative of someone trying to do
// something they shouldn't via the API (or indeed a bug in a UI leeting them
// attempt something they are forbidden to do).
if r.Method == http.MethodGet {
return
}
// If there is not accountibility e.g. a global call, it's not worth logging.
info, err := authorization.FromContext(r.Context())
if err != nil {
return
}
// If there's no scope, then discard also.
if len(params) == 0 {
return
}
// If you cannot derive the resource, then discard.
resource := getResource(writer, r, route, params)
if resource == nil {
return
}
subject := info.Userinfo.Sub
if info.Userinfo.Email != nil {
subject = *info.Userinfo.Email
}
logParams := []any{
"component", &Component{
Name: l.application,
Version: l.version,
},
"actor", &Actor{
Subject: subject,
},
"operation", &Operation{
Verb: r.Method,
},
"scope", params,
"resource", resource,
"result", &Result{
Status: writer.StatusCode(),
},
}
log.FromContext(r.Context()).Info("audit", logParams...)
}
func Middleware(openapi *openapi.Schema, application, version string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return New(next, openapi, application, version)
}
}