-
-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathMetricsResource.java
More file actions
514 lines (488 loc) · 24.5 KB
/
MetricsResource.java
File metadata and controls
514 lines (488 loc) · 24.5 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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
/*
* This file is part of Dependency-Track.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
* Copyright (c) OWASP Foundation. All Rights Reserved.
*/
package org.dependencytrack.resources.v1;
import alpine.event.framework.Event;
import alpine.server.auth.PermissionRequired;
import alpine.server.resources.AlpineResource;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.ArraySchema;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.security.SecurityRequirements;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.PathParam;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import org.apache.commons.lang3.time.DateUtils;
import org.dependencytrack.auth.Permissions;
import org.dependencytrack.event.ComponentMetricsUpdateEvent;
import org.dependencytrack.event.PortfolioMetricsUpdateEvent;
import org.dependencytrack.event.HistoricalRiskScoreUpdateEvent;
import org.dependencytrack.event.ProjectMetricsUpdateEvent;
import org.dependencytrack.model.Component;
import org.dependencytrack.model.DependencyMetrics;
import org.dependencytrack.model.PortfolioMetrics;
import org.dependencytrack.model.Project;
import org.dependencytrack.model.ProjectMetrics;
import org.dependencytrack.model.VulnerabilityMetrics;
import org.dependencytrack.model.validation.ValidUuid;
import org.dependencytrack.persistence.QueryManager;
import org.dependencytrack.util.DateUtil;
import java.util.Date;
import java.util.List;
/**
* JAX-RS resources for processing metrics.
*
* @author Steve Springett
* @since 3.0.0
*/
@Path("/v1/metrics")
@Tag(name = "metrics")
@SecurityRequirements({
@SecurityRequirement(name = "ApiKeyAuth"),
@SecurityRequirement(name = "BearerAuth")
})
public class MetricsResource extends AlpineResource {
@GET
@Path("/vulnerability")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Returns the sum of all vulnerabilities in the database by year and month",
description = "<p>Requires permission <strong>VIEW_PORTFOLIO</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(
responseCode = "200",
description = "The sum of all vulnerabilities in the database by year and month",
content = @Content(array = @ArraySchema(schema = @Schema(implementation = VulnerabilityMetrics.class)))
),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@PermissionRequired(Permissions.Constants.VIEW_PORTFOLIO)
public Response getVulnerabilityMetrics() {
try (QueryManager qm = new QueryManager()) {
final List<VulnerabilityMetrics> metrics = qm.getVulnerabilityMetrics();
return Response.ok(metrics).build();
}
}
@GET
@Path("/riskscore/refresh")
@Produces(MediaType.APPLICATION_JSON)
@ApiOperation(
value = "Requests a refresh of the historical risk score metrics",
response = PortfolioMetrics.class,
notes = "<p>Requires permission <strong>PORTFOLIO_MANAGEMENT</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(code = 401, message = "Unauthorized")
})
@PermissionRequired(Permissions.Constants.PORTFOLIO_MANAGEMENT)
public Response RefreshHistoricalRiskScoreMetrics() {
Event.dispatch(new HistoricalRiskScoreUpdateEvent());
return Response.ok().build();
}
@GET
@Path("/portfolio/current")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Returns current metrics for the entire portfolio",
description = "<p>Requires permission <strong>VIEW_PORTFOLIO</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(
responseCode = "200",
description = "Current metrics for the entire portfolio",
content = @Content(schema = @Schema(implementation = PortfolioMetrics.class))
),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@PermissionRequired(Permissions.Constants.VIEW_PORTFOLIO)
public Response getPortfolioCurrentMetrics() {
try (QueryManager qm = new QueryManager()) {
final PortfolioMetrics metrics = qm.getMostRecentPortfolioMetrics();
return Response.ok(metrics).build();
}
}
@GET
@Path("/portfolio/since/{date}")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Returns historical metrics for the entire portfolio from a specific date",
description = """
<p>Date format must be <code>YYYYMMDD</code></p>
<p>Requires permission <strong>VIEW_PORTFOLIO</strong></p>""")
@ApiResponses(value = {
@ApiResponse(
responseCode = "200",
description = "Historical metrics for the entire portfolio from a specific date",
content = @Content(array = @ArraySchema(schema = @Schema(implementation = PortfolioMetrics.class)))
),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@PermissionRequired(Permissions.Constants.VIEW_PORTFOLIO)
public Response getPortfolioMetricsSince(
@Parameter(description = "The start date to retrieve metrics for", required = true)
@PathParam("date") String date) {
final Date since = DateUtil.parseShortDate(date);
if (since == null) {
return Response.status(Response.Status.BAD_REQUEST).entity("The specified date format is incorrect.").build();
}
try (QueryManager qm = new QueryManager()) {
final List<PortfolioMetrics> metrics = qm.getPortfolioMetricsSince(since);
return Response.ok(metrics).build();
}
}
@GET
@Path("/portfolio/{days}/days")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Returns X days of historical metrics for the entire portfolio",
description = "<p>Requires permission <strong>VIEW_PORTFOLIO</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(
responseCode = "200",
description = "X days of historical metrics for the entire portfolio",
content = @Content(array = @ArraySchema(schema = @Schema(implementation = PortfolioMetrics.class)))
),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@PermissionRequired(Permissions.Constants.VIEW_PORTFOLIO)
public Response getPortfolioMetricsXDays(
@Parameter(description = "The number of days back to retrieve metrics for", required = true)
@PathParam("days") int days) {
final Date since = DateUtils.addDays(new Date(), -days);
try (QueryManager qm = new QueryManager()) {
final List<PortfolioMetrics> metrics = qm.getPortfolioMetricsSince(since);
return Response.ok(metrics).build();
}
}
@GET
@Path("/portfolio/refresh")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Requests a refresh of the portfolio metrics",
description = "<p>Requires permission <strong>PORTFOLIO_MANAGEMENT</strong> or <strong>PORTFOLIO_MANAGEMENT_READ</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Refresh requested successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized")
})
@PermissionRequired({Permissions.Constants.PORTFOLIO_MANAGEMENT, Permissions.Constants.PORTFOLIO_MANAGEMENT_READ})
public Response RefreshPortfolioMetrics() {
Event.dispatch(new PortfolioMetricsUpdateEvent());
return Response.ok().build();
}
@GET
@Path("/project/{uuid}/current")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Returns current metrics for a specific project",
description = "<p>Requires permission <strong>VIEW_PORTFOLIO</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(
responseCode = "200",
description = "Current metrics for a specific project",
content = @Content(schema = @Schema(implementation = ProjectMetrics.class))
),
@ApiResponse(responseCode = "401", description = "Unauthorized"),
@ApiResponse(responseCode = "403", description = "Access to the specified project is forbidden"),
@ApiResponse(responseCode = "404", description = "The project could not be found")
})
@PermissionRequired(Permissions.Constants.VIEW_PORTFOLIO)
public Response getProjectCurrentMetrics(
@Parameter(description = "The UUID of the project to retrieve metrics for", schema = @Schema(type = "string", format = "uuid"), required = true)
@PathParam("uuid") @ValidUuid String uuid) {
try (QueryManager qm = new QueryManager(getAlpineRequest())) {
final Project project = qm.getObjectByUuid(Project.class, uuid);
if (project != null) {
if (qm.hasAccess(super.getPrincipal(), project)) {
final ProjectMetrics metrics = qm.getMostRecentProjectMetrics(project);
return Response.ok(metrics).build();
} else {
return Response.status(Response.Status.FORBIDDEN).entity("Access to the specified project is forbidden").build();
}
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The project could not be found.").build();
}
}
}
@GET
@Path("/project/{uuid}/since/{date}")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Returns historical metrics for a specific project from a specific date",
description = """
<p>Date format must be <code>YYYYMMDD</code></p>
<p>Requires permission <strong>VIEW_PORTFOLIO</strong></p>"""
)
@ApiResponses(value = {
@ApiResponse(
responseCode = "200",
description = "Historical metrics for a specific project from a specific date",
content = @Content(array = @ArraySchema(schema = @Schema(implementation = ProjectMetrics.class)))
),
@ApiResponse(responseCode = "401", description = "Unauthorized"),
@ApiResponse(responseCode = "403", description = "Access to the specified project is forbidden"),
@ApiResponse(responseCode = "404", description = "The project could not be found")
})
@PermissionRequired(Permissions.Constants.VIEW_PORTFOLIO)
public Response getProjectMetricsSince(
@Parameter(description = "The UUID of the project to retrieve metrics for", schema = @Schema(type = "string", format = "uuid"), required = true)
@PathParam("uuid") @ValidUuid String uuid,
@Parameter(description = "The start date to retrieve metrics for", required = true)
@PathParam("date") String date) {
final Date since = DateUtil.parseShortDate(date);
return getProjectMetrics(uuid, since);
}
@GET
@Path("/project/{uuid}/days/{days}")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Returns X days of historical metrics for a specific project",
description = "<p>Requires permission <strong>VIEW_PORTFOLIO</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(
responseCode = "200",
description = "X days of historical metrics for a specific project",
content = @Content(array = @ArraySchema(schema = @Schema(implementation = ProjectMetrics.class)))
),
@ApiResponse(responseCode = "401", description = "Unauthorized"),
@ApiResponse(responseCode = "403", description = "Access to the specified project is forbidden"),
@ApiResponse(responseCode = "404", description = "The project could not be found")
})
@PermissionRequired(Permissions.Constants.VIEW_PORTFOLIO)
public Response getProjectMetricsXDays(
@Parameter(description = "The UUID of the project to retrieve metrics for", schema = @Schema(type = "string", format = "uuid"), required = true)
@PathParam("uuid") @ValidUuid String uuid,
@Parameter(description = "The number of days back to retrieve metrics for", required = true)
@PathParam("days") int days) {
final Date since = DateUtils.addDays(new Date(), -days);
return getProjectMetrics(uuid, since);
}
@GET
@Path("/project/{uuid}/refresh")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Requests a refresh of a specific projects metrics",
description = "<p>Requires permission <strong>PORTFOLIO_MANAGEMENT</strong> or <strong>PORTFOLIO_MANAGEMENT_READ</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Refresh requested successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized"),
@ApiResponse(responseCode = "403", description = "Access to the specified project is forbidden"),
@ApiResponse(responseCode = "404", description = "The project could not be found")
})
@PermissionRequired({Permissions.Constants.PORTFOLIO_MANAGEMENT, Permissions.Constants.PORTFOLIO_MANAGEMENT_READ})
public Response RefreshProjectMetrics(
@Parameter(description = "The UUID of the project to refresh metrics on", schema = @Schema(type = "string", format = "uuid"), required = true)
@PathParam("uuid") @ValidUuid String uuid) {
try (QueryManager qm = new QueryManager(getAlpineRequest())) {
final Project project = qm.getObjectByUuid(Project.class, uuid);
if (project != null) {
if (qm.hasAccess(super.getPrincipal(), project)) {
Event.dispatch(new ProjectMetricsUpdateEvent(project.getUuid()));
return Response.ok().build();
} else {
return Response.status(Response.Status.FORBIDDEN).entity("Access to the specified project is forbidden").build();
}
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The project could not be found.").build();
}
}
}
@GET
@Path("/component/{uuid}/current")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Returns current metrics for a specific component",
description = "<p>Requires permission <strong>VIEW_PORTFOLIO</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(
responseCode = "200",
description = "Current metrics for a specific component",
content = @Content(schema = @Schema(implementation = DependencyMetrics.class))
),
@ApiResponse(responseCode = "401", description = "Unauthorized"),
@ApiResponse(responseCode = "403", description = "Access to the specified component is forbidden"),
@ApiResponse(responseCode = "404", description = "The component could not be found")
})
@PermissionRequired(Permissions.Constants.VIEW_PORTFOLIO)
public Response getComponentCurrentMetrics(
@Parameter(description = "The UUID of the component to retrieve metrics for", schema = @Schema(type = "string", format = "uuid"), required = true)
@PathParam("uuid") @ValidUuid String uuid) {
try (QueryManager qm = new QueryManager(getAlpineRequest())) {
final Component component = qm.getObjectByUuid(Component.class, uuid);
if (component != null) {
if (qm.hasAccess(super.getPrincipal(), component.getProject())) {
final DependencyMetrics metrics = qm.getMostRecentDependencyMetrics(component);
return Response.ok(metrics).build();
} else {
return Response.status(Response.Status.FORBIDDEN).entity("Access to the specified component is forbidden").build();
}
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The component could not be found.").build();
}
}
}
@GET
@Path("/component/{uuid}/since/{date}")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Returns historical metrics for a specific component from a specific date",
description = """
<p>Date format must be <code>YYYYMMDD</code></p>
<p>Requires permission <strong>VIEW_PORTFOLIO</strong></p>"""
)
@ApiResponses(value = {
@ApiResponse(
responseCode = "200",
description = "Historical metrics for a specific component from a specific date",
content = @Content(array = @ArraySchema(schema = @Schema(implementation = DependencyMetrics.class)))
),
@ApiResponse(responseCode = "401", description = "Unauthorized"),
@ApiResponse(responseCode = "403", description = "Access to the specified component is forbidden"),
@ApiResponse(responseCode = "404", description = "The component could not be found")
})
@PermissionRequired(Permissions.Constants.VIEW_PORTFOLIO)
public Response getComponentMetricsSince(
@Parameter(description = "The UUID of the component to retrieve metrics for", schema = @Schema(type = "string", format = "uuid"), required = true)
@PathParam("uuid") @ValidUuid String uuid,
@Parameter(description = "The start date to retrieve metrics for", required = true)
@PathParam("date") String date) {
final Date since = DateUtil.parseShortDate(date);
if (since == null) {
return Response.status(Response.Status.BAD_REQUEST).entity("The specified date format is incorrect.").build();
}
return getComponentMetrics(uuid, since);
}
@GET
@Path("/component/{uuid}/days/{days}")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Returns X days of historical metrics for a specific component",
description = "<p>Requires permission <strong>VIEW_PORTFOLIO</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(
responseCode = "200",
description = "X days of historical metrics for a specific component",
content = @Content(array = @ArraySchema(schema = @Schema(implementation = DependencyMetrics.class)))
),
@ApiResponse(responseCode = "401", description = "Unauthorized"),
@ApiResponse(responseCode = "403", description = "Access to the specified component is forbidden"),
@ApiResponse(responseCode = "404", description = "The component could not be found")
})
@PermissionRequired(Permissions.Constants.VIEW_PORTFOLIO)
public Response getComponentMetricsXDays(
@Parameter(description = "The UUID of the component to retrieve metrics for", schema = @Schema(type = "string", format = "uuid"), required = true)
@PathParam("uuid") @ValidUuid String uuid,
@Parameter(description = "The number of days back to retrieve metrics for", required = true)
@PathParam("days") int days) {
final Date since = DateUtils.addDays(new Date(), -days);
return getComponentMetrics(uuid, since);
}
@GET
@Path("/component/{uuid}/refresh")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
summary = "Requests a refresh of a specific components metrics",
description = "<p>Requires permission <strong>PORTFOLIO_MANAGEMENT</strong> or <strong>PORTFOLIO_MANAGEMENT_READ</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Refresh requested successfully"),
@ApiResponse(responseCode = "401", description = "Unauthorized"),
@ApiResponse(responseCode = "403", description = "Access to the specified component is forbidden"),
@ApiResponse(responseCode = "404", description = "The component could not be found")
})
@PermissionRequired({Permissions.Constants.PORTFOLIO_MANAGEMENT, Permissions.Constants.PORTFOLIO_MANAGEMENT_READ})
public Response RefreshComponentMetrics(
@Parameter(description = "The UUID of the component to refresh metrics on", schema = @Schema(type = "string", format = "uuid"), required = true)
@PathParam("uuid") @ValidUuid String uuid) {
try (QueryManager qm = new QueryManager(getAlpineRequest())) {
final Component component = qm.getObjectByUuid(Component.class, uuid);
if (component != null) {
if (qm.hasAccess(super.getPrincipal(), component.getProject())) {
Event.dispatch(new ComponentMetricsUpdateEvent(component.getUuid()));
return Response.ok().build();
} else {
return Response.status(Response.Status.FORBIDDEN).entity("Access to the specified component is forbidden").build();
}
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The component could not be found.").build();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Private method common to retrieving project metrics based on a time period.
*
* @param uuid the UUID of the project
* @param since the Date to start retrieving metrics from
* @return a Response object
*/
private Response getProjectMetrics(String uuid, Date since) {
try (QueryManager qm = new QueryManager(getAlpineRequest())) {
final Project project = qm.getObjectByUuid(Project.class, uuid);
if (project != null) {
if (qm.hasAccess(super.getPrincipal(), project)) {
final List<ProjectMetrics> metrics = qm.getProjectMetricsSince(project, since);
return Response.ok(metrics).build();
} else {
return Response.status(Response.Status.FORBIDDEN).entity("Access to the specified project is forbidden").build();
}
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The project could not be found.").build();
}
}
}
/**
* Private method common to retrieving component metrics based on a time period.
*
* @param uuid the UUID of the component
* @param since the Date to start retrieving metrics from
* @return a Response object
*/
private Response getComponentMetrics(String uuid, Date since) {
try (QueryManager qm = new QueryManager(getAlpineRequest())) {
final Component component = qm.getObjectByUuid(Component.class, uuid);
if (component != null) {
if (qm.hasAccess(super.getPrincipal(), component.getProject())) {
final List<DependencyMetrics> metrics = qm.getDependencyMetricsSince(component, since);
return Response.ok(metrics).build();
} else {
return Response.status(Response.Status.FORBIDDEN).entity("Access to the specified component is forbidden").build();
}
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The component could not be found.").build();
}
}
}
}