-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathindexer_v1.go
More file actions
281 lines (254 loc) · 8.42 KB
/
Copy pathindexer_v1.go
File metadata and controls
281 lines (254 loc) · 8.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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
package httptransport
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"path"
"time"
"github.com/quay/claircore"
"github.com/quay/claircore/pkg/tarfs"
"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/middleware/compress"
)
// NewIndexerV1 returns an http.Handler serving the Indexer V1 API rooted at
// "prefix".
func NewIndexerV1(_ context.Context, prefix string, srv indexer.Service, topt otelhttp.Option) (*IndexerV1, error) {
prefix = path.Join("/", prefix) // Ensure the prefix is rooted and cleaned.
m := http.NewServeMux()
h := IndexerV1{
inner: otelhttp.NewHandler(
compress.Handler(m),
"indexerv1",
otelhttp.WithMessageEvents(otelhttp.ReadEvents, otelhttp.WriteEvents),
topt,
),
srv: srv,
}
p := path.Join(prefix, "index_report")
m.Handle(p, indexerv1wrapper.wrapFunc(p, h.indexReport))
p += "/"
m.Handle(p, indexerv1wrapper.wrapFunc(path.Join(p, ":digest"), h.indexReportOne))
p = path.Join(prefix, "index_state")
m.Handle(p, indexerv1wrapper.wrapFunc(p, h.indexState))
p = path.Join(prefix, "internal", "affected_manifest") + "/"
m.Handle(p, indexerv1wrapper.wrapFunc(p, h.affectedManifests))
return &h, nil
}
// IndexerV1 is a consolidated Indexer endpoint.
type IndexerV1 struct {
inner http.Handler
srv indexer.Service
}
var _ http.Handler = (*IndexerV1)(nil)
// ServeHTTP implements http.Handler.
func (h *IndexerV1) 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)
}
func (h *IndexerV1) indexReport(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
switch r.Method {
case http.MethodPost:
case http.MethodDelete:
default:
apiError(ctx, w, http.StatusMethodNotAllowed, "method disallowed: %s", r.Method)
}
defer r.Body.Close()
dec := codec.GetDecoder(r.Body)
switch r.Method {
case http.MethodPost:
state, err := h.srv.State(ctx)
if err != nil {
apiError(ctx, w, http.StatusInternalServerError, "could not retrieve indexer state: %v", err)
}
var m claircore.Manifest
if err := dec.Decode(&m); err != nil {
apiError(ctx, w, http.StatusBadRequest, "failed to deserialize manifest: %v", err)
}
if m.Hash.String() == "" || len(m.Layers) == 0 {
apiError(ctx, w, http.StatusBadRequest, "bogus manifest")
}
next := path.Join(r.URL.Path, m.Hash.String())
w.Header().Add("link", fmt.Sprintf(linkIndex, next))
w.Header().Add("link", fmt.Sprintf(linkReport, path.Join(VulnerabilityReportPath, m.Hash.String())))
validator := `"` + state + `"`
if unmodified(r, validator) {
w.WriteHeader(http.StatusPreconditionFailed)
return
}
// TODO Do we need some sort of background context embedded in the HTTP
// struct?
report, err := h.srv.Index(ctx, &m)
switch {
case errors.Is(err, nil):
case errors.Is(err, tarfs.ErrFormat):
apiError(ctx, w, http.StatusBadRequest, "failed to start scan: %v", err)
default:
apiError(ctx, w, http.StatusInternalServerError, "failed to start scan: %v", err)
}
w.Header().Set("etag", validator)
w.Header().Set("location", next)
defer writerError(w, &err)()
w.WriteHeader(http.StatusCreated)
enc := codec.GetEncoder(w)
err = enc.Encode(report)
case http.MethodDelete:
var ds []claircore.Digest
if err := dec.Decode(&ds); err != nil {
apiError(ctx, w, http.StatusBadRequest, "failed to deserialize bulk delete: %v", err)
}
ds, err := h.srv.DeleteManifests(ctx, ds...)
if err != nil {
apiError(ctx, w, http.StatusInternalServerError, "could not delete manifests: %v", err)
}
slog.DebugContext(ctx, "manifests deleted",
"count", len(ds))
defer writerError(w, &err)()
w.WriteHeader(http.StatusOK)
enc := codec.GetEncoder(w)
err = enc.Encode(ds)
}
}
const (
linkIndex = `<%s>; rel="https://projectquay.io/clair/v1/index_report"`
linkReport = `<%s>; rel="https://projectquay.io/clair/v1/vulnerability_report"`
)
func (h *IndexerV1) indexReportOne(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
switch r.Method {
case http.MethodGet:
case http.MethodDelete:
default:
apiError(ctx, w, http.StatusMethodNotAllowed, "method disallowed: %s", r.Method)
}
d, err := getDigest(w, r)
if err != nil {
apiError(ctx, w, http.StatusBadRequest, "malformed path: %v", err)
}
switch r.Method {
case http.MethodGet:
allow := []string{"application/vnd.clair.index_report.v1+json", "application/json"}
switch err := pickContentType(w, r, allow); {
case errors.Is(err, nil): // OK
case errors.Is(err, ErrMediaType):
apiError(ctx, w, http.StatusUnsupportedMediaType, "unable to negotiate common media type for %v", allow)
default:
apiError(ctx, w, http.StatusBadRequest, "malformed request: %v", err)
}
state, err := h.srv.State(ctx)
if err != nil {
apiError(ctx, w, http.StatusInternalServerError, "could not retrieve indexer state: %v", err)
}
validator := `"` + state + `"`
if unmodified(r, validator) {
w.WriteHeader(http.StatusNotModified)
return
}
report, ok, err := h.srv.IndexReport(ctx, d)
if !ok {
apiError(ctx, w, http.StatusNotFound, "index report not found")
}
if err != nil {
apiError(ctx, w, http.StatusInternalServerError, "could not retrieve index report: %v", err)
}
w.Header().Add("etag", validator)
defer writerError(w, &err)()
enc := codec.GetEncoder(w)
err = enc.Encode(report)
case http.MethodDelete:
if _, err := h.srv.DeleteManifests(ctx, d); err != nil {
apiError(ctx, w, http.StatusInternalServerError, "unable to delete manifest: %v", err)
}
w.WriteHeader(http.StatusNoContent)
}
}
func (h *IndexerV1) indexState(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if r.Method != http.MethodGet {
apiError(ctx, w, http.StatusMethodNotAllowed, "method disallowed: %s", r.Method)
}
allow := []string{"application/vnd.clair.index_state.v1+json", "application/json"}
switch err := pickContentType(w, r, allow); {
case errors.Is(err, nil): // OK
case errors.Is(err, ErrMediaType):
apiError(ctx, w, http.StatusUnsupportedMediaType, "unable to negotiate common media type for %v", allow)
default:
apiError(ctx, w, http.StatusBadRequest, "malformed request: %v", err)
}
s, err := h.srv.State(ctx)
if err != nil {
apiError(ctx, w, http.StatusInternalServerError, "could not retrieve indexer state: %v", err)
}
tag := `"` + s + `"`
w.Header().Add("etag", tag)
if unmodified(r, tag) {
w.WriteHeader(http.StatusNotModified)
return
}
defer writerError(w, &err)()
// TODO(hank) Use the API type.
enc := codec.GetEncoder(w)
err = enc.Encode(struct {
State string `json:"state"`
}{
State: s,
})
}
func (h *IndexerV1) affectedManifests(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
if r.Method != http.MethodPost {
apiError(ctx, w, http.StatusMethodNotAllowed, "method disallowed: %s", r.Method)
}
allow := []string{"application/vnd.clair.affected_manifests.v1+json", "application/json"}
switch err := pickContentType(w, r, allow); {
case errors.Is(err, nil): // OK
case errors.Is(err, ErrMediaType):
apiError(ctx, w, http.StatusUnsupportedMediaType, "unable to negotiate common media type for %v", allow)
default:
apiError(ctx, w, http.StatusBadRequest, "malformed request: %v", err)
}
var vulnerabilities struct {
V []claircore.Vulnerability `json:"vulnerabilities"`
}
dec := codec.GetDecoder(r.Body)
if err := dec.Decode(&vulnerabilities); err != nil {
apiError(ctx, w, http.StatusBadRequest, "failed to deserialize vulnerabilities: %v", err)
}
affected, err := h.srv.AffectedManifests(ctx, vulnerabilities.V)
if err != nil {
apiError(ctx, w, http.StatusInternalServerError, "could not retrieve affected manifests: %v", err)
}
defer writerError(w, &err)
enc := codec.GetEncoder(w)
err = enc.Encode(affected)
}
func init() {
indexerv1wrapper.init("indexerv1")
}
var indexerv1wrapper wrapper