-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathmatcher_v1.go
More file actions
254 lines (223 loc) · 7.42 KB
/
Copy pathmatcher_v1.go
File metadata and controls
254 lines (223 loc) · 7.42 KB
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
package httptransport
import (
"context"
"errors"
"log/slog"
"net/http"
"net/http/httptrace"
"path"
"path/filepath"
"strconv"
"time"
"github.com/google/uuid"
"github.com/quay/claircore"
indexerController "github.com/quay/claircore/indexer/controller"
"github.com/quay/claircore/libvuln/driver"
oteltrace "go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"github.com/quay/clair/v4/indexer"
"github.com/quay/clair/v4/internal/codec"
"github.com/quay/clair/v4/internal/httputil"
"github.com/quay/clair/v4/matcher"
"github.com/quay/clair/v4/middleware/compress"
)
// NewMatcherV1 returns an http.Handler serving the Matcher V1 API rooted at
// "prefix".
func NewMatcherV1(_ context.Context, prefix string, srv matcher.Service, indexerSrv indexer.Service, cacheAge time.Duration, topt otelhttp.Option) *MatcherV1 {
prefix = path.Join("/", prefix) // Ensure the prefix is rooted and cleaned.
m := http.NewServeMux()
h := MatcherV1{
inner: otelhttp.NewHandler(
compress.Handler(m),
"matcherv1",
otelhttp.WithMessageEvents(otelhttp.ReadEvents, otelhttp.WriteEvents),
topt,
),
srv: srv,
indexerSrv: indexerSrv,
Cache: cacheAge,
}
p := path.Join(prefix, "vulnerability_report") + "/"
m.Handle(p, matcherv1wrapper.wrapFunc(p, h.vulnerabilityReport))
p = path.Join(prefix, "internal", "update_operation")
m.Handle(p, matcherv1wrapper.wrapFunc(p, h.updateOperationHandlerGet))
p = path.Join(prefix, "internal", "update_operation") + "/"
m.Handle(p, matcherv1wrapper.wrapFunc(p, h.updateOperationHandlerDelete))
p = path.Join(prefix, "internal", "update_diff")
m.Handle(p, matcherv1wrapper.wrapFunc(p, h.updateDiffHandler))
return &h
}
// MatcherV1 is a consolidated Matcher endpoint.
type MatcherV1 struct {
inner http.Handler
srv matcher.Service
indexerSrv indexer.Service
Cache time.Duration
}
var _ http.Handler = (*MatcherV1)(nil)
// ServeHTTP implements http.Handler.
func (h *MatcherV1) ServeHTTP(w http.ResponseWriter, r *http.Request) {
start := time.Now()
r = withRequestID(r)
ctx := r.Context()
var status int
var length int64
w = httputil.ResponseRecorder(&status, &length, w)
defer func() {
switch err := http.NewResponseController(w).Flush(); {
case errors.Is(err, nil):
case errors.Is(err, http.ErrNotSupported): // Skip
default:
slog.WarnContext(ctx, "unable to flush http response",
"reason", err)
}
slog.InfoContext(ctx, "handled HTTP request",
"remote_addr", r.RemoteAddr,
"method", r.Method,
"request_uri", r.RequestURI,
"status", status,
"written", length,
"duration", time.Since(start))
}()
h.inner.ServeHTTP(w, r)
}
// TODO(hank) All of these handlers need to do content negotiation.
func (h *MatcherV1) vulnerabilityReport(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if r.Method != http.MethodGet {
apiError(ctx, w, http.StatusMethodNotAllowed, "endpoint only allows GET")
}
ctx, done := context.WithCancel(ctx)
defer done()
ctx = httptrace.WithClientTrace(ctx, oteltrace.NewClientTrace(ctx))
manifestStr := path.Base(r.URL.Path)
if manifestStr == "" {
apiError(ctx, w, http.StatusBadRequest, "malformed path. provide a single manifest hash")
}
manifest, err := claircore.ParseDigest(manifestStr)
if err != nil {
apiError(ctx, w, http.StatusBadRequest, "malformed path: %v", err)
}
initd, err := h.srv.Initialized(ctx)
if err != nil {
apiError(ctx, w, http.StatusInternalServerError, "initialization error: %v", err)
}
if !initd {
w.WriteHeader(http.StatusAccepted)
return
}
indexReport, ok, err := h.indexerSrv.IndexReport(ctx, manifest)
// check err first
if err != nil {
apiError(ctx, w, http.StatusInternalServerError, "experienced a server side error: %v", err)
}
// now check present and finished only after confirming no err
if !ok || indexReport.State != indexerController.IndexFinished.String() {
apiError(ctx, w, http.StatusNotFound, "index report for manifest %q not found", manifest.String())
return
}
vulnReport, err := h.srv.Scan(ctx, indexReport)
if err != nil {
apiError(ctx, w, http.StatusInternalServerError, "failed to start scan: %v", err)
}
w.Header().Set("content-type", "application/vnd.clair.index_report.v1+json")
setCacheControl(w, h.Cache)
defer writerError(w, &err)()
enc := codec.GetEncoder(w)
err = enc.Encode(vulnReport)
}
func (h *MatcherV1) updateDiffHandler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if r.Method != http.MethodGet {
apiError(ctx, w, http.StatusMethodNotAllowed, "endpoint only allows GET")
}
// prev param is optional.
var prev uuid.UUID
var err error
if param := r.URL.Query().Get("prev"); param != "" {
prev, err = uuid.Parse(param)
if err != nil {
apiError(ctx, w, http.StatusBadRequest, "could not parse \"prev\" query param into uuid")
}
}
// cur param is required
var cur uuid.UUID
var param string
if param = r.URL.Query().Get("cur"); param == "" {
apiError(ctx, w, http.StatusBadRequest, "\"cur\" query param is required")
}
if cur, err = uuid.Parse(param); err != nil {
apiError(ctx, w, http.StatusBadRequest, "could not parse \"cur\" query param into uuid")
}
diff, err := h.srv.UpdateDiff(ctx, prev, cur)
if err != nil {
apiError(ctx, w, http.StatusInternalServerError, "could not get update operations: %v", err)
}
defer writerError(w, &err)()
enc := codec.GetEncoder(w)
err = enc.Encode(&diff)
}
func (h *MatcherV1) updateOperationHandlerGet(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
switch r.Method {
case http.MethodGet:
default:
apiError(ctx, w, http.StatusMethodNotAllowed, "method disallowed: %s", r.Method)
}
kind := driver.VulnerabilityKind
switch k := r.URL.Query().Get("kind"); k {
case "enrichment":
kind = driver.EnrichmentKind
case "", "vulnerability":
// Leave as default
default:
apiError(ctx, w, http.StatusBadRequest, "unknown kind: %q", k)
}
// handle conditional request. this is an optimization
if ref, err := h.srv.LatestUpdateOperation(ctx, kind); err == nil {
validator := `"` + ref.String() + `"`
if unmodified(r, validator) {
w.WriteHeader(http.StatusNotModified)
return
}
w.Header().Set("etag", validator)
}
latest := r.URL.Query().Get("latest")
var uos map[string][]driver.UpdateOperation
var err error
if b, _ := strconv.ParseBool(latest); b {
uos, err = h.srv.LatestUpdateOperations(ctx, kind)
} else {
uos, err = h.srv.UpdateOperations(ctx, kind)
}
if err != nil {
apiError(ctx, w, http.StatusInternalServerError, "could not get update operations: %v", err)
}
defer writerError(w, &err)()
enc := codec.GetEncoder(w)
err = enc.Encode(&uos)
}
func (h *MatcherV1) updateOperationHandlerDelete(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
switch r.Method {
case http.MethodDelete:
default:
apiError(ctx, w, http.StatusMethodNotAllowed, "method disallowed: %s", r.Method)
}
path := r.URL.Path
id := filepath.Base(path)
uuid, err := uuid.Parse(id)
if err != nil {
slog.WarnContext(ctx, "could not deserialize manifest", "reason", err)
apiError(ctx, w, http.StatusBadRequest, "could not deserialize manifest: %v", err)
}
_, err = h.srv.DeleteUpdateOperations(ctx, uuid)
if err != nil {
apiError(ctx, w, http.StatusInternalServerError, "could not get update operations: %v", err)
}
// TODO(hank) This should return HTTP 204.
}
func init() {
matcherv1wrapper.init("matcherv1")
}
var matcherv1wrapper wrapper