-
Notifications
You must be signed in to change notification settings - Fork 68
/
handler.go
257 lines (217 loc) · 7.84 KB
/
handler.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
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
package v1
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strconv"
"time"
"github.com/aquasecurity/harbor-scanner-trivy/pkg/harbor"
"github.com/aquasecurity/harbor-scanner-trivy/pkg/etc"
"github.com/aquasecurity/harbor-scanner-trivy/pkg/http/api"
"github.com/aquasecurity/harbor-scanner-trivy/pkg/job"
"github.com/aquasecurity/harbor-scanner-trivy/pkg/persistence"
"github.com/aquasecurity/harbor-scanner-trivy/pkg/queue"
"github.com/aquasecurity/harbor-scanner-trivy/pkg/trivy"
"github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus/promhttp"
log "github.com/sirupsen/logrus"
)
const (
pathVarScanRequestID = "scan_request_id"
)
const (
propertyScannerType = "harbor.scanner-adapter/scanner-type"
propertyDBUpdatedAt = "harbor.scanner-adapter/vulnerability-database-updated-at"
propertyDBNextUpdateAt = "harbor.scanner-adapter/vulnerability-database-next-update-at"
)
type requestHandler struct {
info etc.BuildInfo
config etc.Config
enqueuer queue.Enqueuer
store persistence.Store
wrapper trivy.Wrapper
api.BaseHandler
}
func NewAPIHandler(info etc.BuildInfo, config etc.Config, enqueuer queue.Enqueuer, store persistence.Store, wrapper trivy.Wrapper) http.Handler {
handler := &requestHandler{
info: info,
config: config,
enqueuer: enqueuer,
store: store,
wrapper: wrapper,
}
router := mux.NewRouter()
router.Use(handler.logRequest)
apiV1Router := router.PathPrefix("/api/v1").Subrouter()
apiV1Router.Methods(http.MethodPost).Path("/scan").HandlerFunc(handler.AcceptScanRequest)
apiV1Router.Methods(http.MethodGet).Path("/scan/{scan_request_id}/report").HandlerFunc(handler.GetScanReport)
apiV1Router.Methods(http.MethodGet).Path("/metadata").HandlerFunc(handler.GetMetadata)
probeRouter := router.PathPrefix("/probe").Subrouter()
probeRouter.Methods(http.MethodGet).Path("/healthy").HandlerFunc(handler.GetHealthy)
probeRouter.Methods(http.MethodGet).Path("/ready").HandlerFunc(handler.GetReady)
router.Methods(http.MethodGet).Path("/metrics").Handler(promhttp.Handler())
return router
}
func (h *requestHandler) logRequest(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Tracef("%s - %s %s %s", r.RemoteAddr, r.Proto, r.Method, r.URL.RequestURI())
next.ServeHTTP(w, r)
})
}
func (h *requestHandler) AcceptScanRequest(res http.ResponseWriter, req *http.Request) {
scanRequest := harbor.ScanRequest{}
err := json.NewDecoder(req.Body).Decode(&scanRequest)
if err != nil {
log.WithError(err).Error("Error while unmarshalling scan request")
h.WriteJSONError(res, harbor.Error{
HTTPCode: http.StatusBadRequest,
Message: fmt.Sprintf("unmarshalling scan request: %s", err.Error()),
})
return
}
if validationError := h.ValidateScanRequest(scanRequest); validationError != nil {
log.Errorf("Error while validating scan request: %s", validationError.Message)
h.WriteJSONError(res, *validationError)
return
}
scanJob, err := h.enqueuer.Enqueue(scanRequest)
if err != nil {
log.WithError(err).Error("Error while enqueuing scan job")
h.WriteJSONError(res, harbor.Error{
HTTPCode: http.StatusInternalServerError,
Message: fmt.Sprintf("enqueuing scan job: %s", err.Error()),
})
return
}
scanResponse := harbor.ScanResponse{ID: scanJob.ID}
h.WriteJSON(res, scanResponse, api.MimeTypeScanResponse, http.StatusAccepted)
}
func (h *requestHandler) ValidateScanRequest(req harbor.ScanRequest) *harbor.Error {
if req.Registry.URL == "" {
return &harbor.Error{
HTTPCode: http.StatusUnprocessableEntity,
Message: "missing registry.url",
}
}
_, err := url.ParseRequestURI(req.Registry.URL)
if err != nil {
return &harbor.Error{
HTTPCode: http.StatusUnprocessableEntity,
Message: "invalid registry.url",
}
}
if req.Artifact.Repository == "" {
return &harbor.Error{
HTTPCode: http.StatusUnprocessableEntity,
Message: "missing artifact.repository",
}
}
if req.Artifact.Digest == "" {
return &harbor.Error{
HTTPCode: http.StatusUnprocessableEntity,
Message: "missing artifact.digest",
}
}
return nil
}
func (h *requestHandler) GetScanReport(res http.ResponseWriter, req *http.Request) {
vars := mux.Vars(req)
scanJobID, ok := vars[pathVarScanRequestID]
if !ok {
log.Error("Error while parsing `scan_request_id` path variable")
h.WriteJSONError(res, harbor.Error{
HTTPCode: http.StatusBadRequest,
Message: "missing scan_request_id",
})
return
}
reqLog := log.WithField("scan_job_id", scanJobID)
scanJob, err := h.store.Get(scanJobID)
if err != nil {
reqLog.Error("Error while getting scan job")
h.WriteJSONError(res, harbor.Error{
HTTPCode: http.StatusInternalServerError,
Message: fmt.Sprintf("getting scan job: %v", err),
})
return
}
if scanJob == nil {
reqLog.Error("Cannot find scan job")
h.WriteJSONError(res, harbor.Error{
HTTPCode: http.StatusNotFound,
Message: fmt.Sprintf("cannot find scan job: %v", scanJobID),
})
return
}
if scanJob.Status == job.Queued || scanJob.Status == job.Pending {
reqLog.WithField("scan_job_status", scanJob.Status).Debug("Scan job has not finished yet")
res.Header().Add("Location", req.URL.String())
res.WriteHeader(http.StatusFound)
return
}
if scanJob.Status == job.Failed {
reqLog.WithField(log.ErrorKey, scanJob.Error).Error("Scan job failed")
h.WriteJSONError(res, harbor.Error{
HTTPCode: http.StatusInternalServerError,
Message: scanJob.Error,
})
return
}
if scanJob.Status != job.Finished {
reqLog.WithField("scan_job_status", scanJob.Status).Error("Unexpected scan job status")
h.WriteJSONError(res, harbor.Error{
HTTPCode: http.StatusInternalServerError,
Message: fmt.Sprintf("unexpected status %v of scan job %v", scanJob.Status, scanJob.ID),
})
return
}
h.WriteJSON(res, scanJob.Report, api.MimeTypeHarborVulnerabilityReport, http.StatusOK)
}
func (h *requestHandler) GetMetadata(res http.ResponseWriter, _ *http.Request) {
properties := map[string]string{
propertyScannerType: "os-package-vulnerability",
"org.label-schema.version": h.info.Version,
"org.label-schema.build-date": h.info.Date,
"org.label-schema.vcs-ref": h.info.Commit,
"org.label-schema.vcs": "https://github.com/aquasecurity/harbor-scanner-trivy",
"com.github.aquasecurity.trivy.skipUpdate": strconv.FormatBool(h.config.Trivy.SkipUpdate),
"com.github.aquasecurity.trivy.ignoreUnfixed": strconv.FormatBool(h.config.Trivy.IgnoreUnfixed),
"com.github.aquasecurity.trivy.debugMode": strconv.FormatBool(h.config.Trivy.DebugMode),
"com.github.aquasecurity.trivy.insecure": strconv.FormatBool(h.config.Trivy.Insecure),
"com.github.aquasecurity.trivy.vulnType": h.config.Trivy.VulnType,
"com.github.aquasecurity.trivy.severity": h.config.Trivy.Severity,
}
vi, err := h.wrapper.GetVersion()
if err != nil {
log.WithError(err).Error("Error while retrieving vulnerability DB version")
}
if err == nil && vi.VulnerabilityDB != nil {
properties[propertyDBUpdatedAt] = vi.VulnerabilityDB.UpdatedAt.Format(time.RFC3339)
}
if err == nil && vi.VulnerabilityDB != nil && !h.config.Trivy.SkipUpdate {
properties[propertyDBNextUpdateAt] = vi.VulnerabilityDB.NextUpdate.Format(time.RFC3339)
}
metadata := &harbor.ScannerAdapterMetadata{
Scanner: etc.GetScannerMetadata(),
Capabilities: []harbor.Capability{
{
ConsumesMIMETypes: []string{
api.MimeTypeOCIImageManifest.String(),
api.MimeTypeDockerImageManifest.String(),
},
ProducesMIMETypes: []string{
api.MimeTypeHarborVulnerabilityReport.String(),
},
},
},
Properties: properties,
}
h.WriteJSON(res, metadata, api.MimeTypeMetadata, http.StatusOK)
}
func (h *requestHandler) GetHealthy(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(http.StatusOK)
}
func (h *requestHandler) GetReady(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(http.StatusOK)
}