Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance badge API to require authorization #4059

43 changes: 25 additions & 18 deletions docs/_docs/integrations/badges.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,21 @@ chapter: 6
order: 10
---

Dependency-Track supports badges in Scalable Vector Graphics (SVG) format. Support for badges is a globally configurable
option and is disabled by default.
Dependency-Track supports badges in Scalable Vector Graphics (SVG) format. Support for badges is configurable on a team
basis via permission.

> Enabling badge support will provide vulnerability and policy violation metric information to unauthenticated users.
> Any anonymous user with network access to Dependency-Track and knowledge of a projects information will be able
> to view the SVG badge.
To enable badges for a team, activate the permission `VIEW_BADGES`. To deactivate badges, remove the permission. To
retrieve a badge, use a team's API key either in the badge API header `X-API-Key` or in the URI parameter `apiKey`.

In all following examples, replace `{name}`, `{version}`, and `{uuid}` with their respective values.
> As badges are typically embedded in places that more people have access to than to Dependency-Track, the API key used
> for the badge request should have minimal scope to prevent unintended access beyond that badge. Ideally, the API
> key belongs to a single-purpose team, having just the `VIEW_BADGES` permission, with only one API key and access to
> only the projects/project versions whose badges are displayed at one site--the latter requiring _Portfolio Access
> Control_.

In all following examples, replace `{name}`, `{version}`, `{uuid}`, and `{apiKey}` with their respective values. For
brevity, the examples use the URI query parameter as the method of authentication, however, they also work with
authentication by header.

### Vulnerable components
Create a badge for vulnerable components of the project. It either shows:
Expand All @@ -33,8 +40,8 @@ name and version.

#### Examples
```
https://dtrack.example.com/api/v1/badge/vulns/project/{name}/{version}
https://dtrack.example.com/api/v1/badge/vulns/project/{uuid}
https://dtrack.example.com/api/v1/badge/vulns/project/{name}/{version}?apiKey={apiKey}
https://dtrack.example.com/api/v1/badge/vulns/project/{uuid}?apiKey={apiKey}
```

### Policy violations
Expand All @@ -57,8 +64,8 @@ projects name and version.
#### Examples

```
https://dtrack.example.com/api/v1/badge/violations/project/{name}/{version}
https://dtrack.example.com/api/v1/badge/violations/project/{uuid}
https://dtrack.example.com/api/v1/badge/violations/project/{name}/{version}?apiKey={apiKey}
https://dtrack.example.com/api/v1/badge/violations/project/{uuid}?apiKey={apiKey}
```


Expand All @@ -67,17 +74,17 @@ You can embed the badges in other documents. It allows you to display a badge in

#### HTML Examples
```html
<img src="https://dtrack.example.com/api/v1/badge/vulns/project/{name}/{version}">
<img src="https://dtrack.example.com/api/v1/badge/vulns/project/{uuid}">
<img src="https://dtrack.example.com/api/v1/badge/violations/project/{name}/{version}">
<img src="https://dtrack.example.com/api/v1/badge/violations/project/{uuid}">
<img src="https://dtrack.example.com/api/v1/badge/vulns/project/{name}/{version}?apiKey={apiKey}">
<img src="https://dtrack.example.com/api/v1/badge/vulns/project/{uuid}?apiKey={apiKey}">
<img src="https://dtrack.example.com/api/v1/badge/violations/project/{name}/{version}?apiKey={apiKey}">
<img src="https://dtrack.example.com/api/v1/badge/violations/project/{uuid}?apiKey={apiKey}">
```

#### Markdown Examples
```markdown
![alt text](https://dtrack.example.com/api/v1/badge/vulns/project/{name}/{version})
![alt text](https://dtrack.example.com/api/v1/badge/vulns/project/{uuid})
![alt text](https://dtrack.example.com/api/v1/badge/violations/project/{name}/{version})
![alt text](https://dtrack.example.com/api/v1/badge/violations/project/{uuid})
![alt text](https://dtrack.example.com/api/v1/badge/vulns/project/{name}/{version}?apiKey={apiKey})
![alt text](https://dtrack.example.com/api/v1/badge/vulns/project/{uuid}?apiKey={apiKey})
![alt text](https://dtrack.example.com/api/v1/badge/violations/project/{name}/{version}?apiKey={apiKey})
![alt text](https://dtrack.example.com/api/v1/badge/violations/project/{uuid}?apiKey={apiKey})
```

4 changes: 3 additions & 1 deletion src/main/java/org/dependencytrack/auth/Permissions.java
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ public enum Permissions {
SYSTEM_CONFIGURATION("Allows the configuration of the system including notifications, repositories, and email settings"),
PROJECT_CREATION_UPLOAD("Provides the ability to optionally create project (if non-existent) on BOM or scan upload"),
POLICY_MANAGEMENT("Allows the creation, modification, and deletion of policy"),
TAG_MANAGEMENT("Allows the modification and deletion of tags");
TAG_MANAGEMENT("Allows the modification and deletion of tags"),
VIEW_BADGES("Provides the ability to view badges");

private final String description;

Expand All @@ -64,6 +65,7 @@ public static class Constants {
public static final String PROJECT_CREATION_UPLOAD = "PROJECT_CREATION_UPLOAD";
public static final String POLICY_MANAGEMENT = "POLICY_MANAGEMENT";
public static final String TAG_MANAGEMENT = "TAG_MANAGEMENT";
public static final String VIEW_BADGES = "VIEW_BADGES";
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
public enum ConfigPropertyConstants {

GENERAL_BASE_URL("general", "base.url", null, PropertyType.URL, "URL used to construct links back to Dependency-Track from external systems"),
GENERAL_BADGE_ENABLED("general", "badge.enabled", "false", PropertyType.BOOLEAN, "Flag to enable/disable SVG badge support from metrics"),
EMAIL_SMTP_ENABLED("email", "smtp.enabled", "false", PropertyType.BOOLEAN, "Flag to enable/disable SMTP"),
EMAIL_SMTP_FROM_ADDR("email", "smtp.from.address", null, PropertyType.STRING, "The from email address to use to send output SMTP mail"),
EMAIL_PREFIX("email", "subject.prefix", "[Dependency-Track]", PropertyType.STRING, "The Prefix Subject email to use"),
Expand Down
121 changes: 62 additions & 59 deletions src/main/java/org/dependencytrack/resources/v1/BadgeResource.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,19 @@
*/
package org.dependencytrack.resources.v1;

import alpine.common.util.BooleanUtil;
import alpine.model.ConfigProperty;
import alpine.server.auth.AuthenticationNotRequired;
import alpine.server.auth.AllowApiKeyInQueryParameter;
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.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 org.dependencytrack.auth.Permissions;
import org.dependencytrack.model.Project;
import org.dependencytrack.model.ProjectMetrics;
import org.dependencytrack.model.validation.ValidUuid;
Expand All @@ -41,8 +43,6 @@
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.Response;

import static org.dependencytrack.model.ConfigPropertyConstants.GENERAL_BADGE_ENABLED;

/**
* JAX-RS resources for processing metrics.
*
Expand All @@ -51,47 +51,47 @@
*/
@Path("/v1/badge")
@Tag(name = "badge")
@SecurityRequirements({
@SecurityRequirement(name = "ApiKeyAuth"),
@SecurityRequirement(name = "BearerAuth"),
@SecurityRequirement(name = "ApiKeyQueryAuth")
})
public class BadgeResource extends AlpineResource {

private static final String SVG_MEDIA_TYPE = "image/svg+xml";

private boolean isBadgeSupportEnabled(final QueryManager qm) {
ConfigProperty property = qm.getConfigProperty(
GENERAL_BADGE_ENABLED.getGroupName(), GENERAL_BADGE_ENABLED.getPropertyName());
return BooleanUtil.valueOf(property.getPropertyValue());
}

@GET
@Path("/vulns/project/{uuid}")
@Produces(SVG_MEDIA_TYPE)
@Operation(
summary = "Returns current metrics for a specific project")
summary = "Returns current metrics for a specific project",
description = "<p>Requires permission <strong>VIEW_BADGES</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(
responseCode = "200",
description = "A badge displaying current vulnerability metrics for a project in SVG format",
content = @Content(schema = @Schema(type = "string"))
),
@ApiResponse(responseCode = "204", description = "Badge support is disabled. No content will be returned."),
@ApiResponse(responseCode = "401", description = "Unauthorized"),
@ApiResponse(responseCode = "404", description = "The project could not be found")
})
@AuthenticationNotRequired
@PermissionRequired(Permissions.Constants.VIEW_BADGES)
@AllowApiKeyInQueryParameter
public Response getProjectVulnerabilitiesBadge(
@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()) {
if (isBadgeSupportEnabled(qm)) {
final Project project = qm.getObjectByUuid(Project.class, uuid);
if (project != null) {
final ProjectMetrics metrics = qm.getMostRecentProjectMetrics(project);
final Badger badger = new Badger();
return Response.ok(badger.generateVulnerabilities(metrics)).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The project could not be found.").build();
final Project project = qm.getObjectByUuid(Project.class, uuid);
if (project != null) {
if (!qm.hasAccess(super.getPrincipal(), project)) {
return Response.status(Response.Status.FORBIDDEN).entity("Access to the specified project is forbidden").build();
}
final ProjectMetrics metrics = qm.getMostRecentProjectMetrics(project);
final Badger badger = new Badger();
return Response.ok(badger.generateVulnerabilities(metrics)).build();
} else {
return Response.status(Response.Status.NO_CONTENT).build();
return Response.status(Response.Status.NOT_FOUND).entity("The project could not be found.").build();
}
}
}
Expand All @@ -100,35 +100,36 @@ public Response getProjectVulnerabilitiesBadge(
@Path("/vulns/project/{name}/{version}")
@Produces(SVG_MEDIA_TYPE)
@Operation(
summary = "Returns current metrics for a specific project")
summary = "Returns current metrics for a specific project",
description = "<p>Requires permission <strong>VIEW_BADGES</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(
responseCode = "200",
description = "A badge displaying current vulnerability metrics for a project in SVG format",
content = @Content(schema = @Schema(type = "string"))
),
@ApiResponse(responseCode = "204", description = "Badge support is disabled. No content will be returned."),
@ApiResponse(responseCode = "401", description = "Unauthorized"),
@ApiResponse(responseCode = "404", description = "The project could not be found")
})
@AuthenticationNotRequired
@PermissionRequired(Permissions.Constants.VIEW_BADGES)
@AllowApiKeyInQueryParameter
public Response getProjectVulnerabilitiesBadge(
@Parameter(description = "The name of the project to query on", required = true)
@PathParam("name") String name,
@Parameter(description = "The version of the project to query on", required = true)
@PathParam("version") String version) {
try (QueryManager qm = new QueryManager()) {
if (isBadgeSupportEnabled(qm)) {
final Project project = qm.getProject(name, version);
if (project != null) {
final ProjectMetrics metrics = qm.getMostRecentProjectMetrics(project);
final Badger badger = new Badger();
return Response.ok(badger.generateVulnerabilities(metrics)).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The project could not be found.").build();
final Project project = qm.getProject(name, version);
if (project != null) {
if (!qm.hasAccess(super.getPrincipal(), project)) {
return Response.status(Response.Status.FORBIDDEN).entity("Access to the specified project is forbidden").build();
}
final ProjectMetrics metrics = qm.getMostRecentProjectMetrics(project);
final Badger badger = new Badger();
return Response.ok(badger.generateVulnerabilities(metrics)).build();
} else {
return Response.status(Response.Status.NO_CONTENT).build();
return Response.status(Response.Status.NOT_FOUND).entity("The project could not be found.").build();
}
}
}
Expand All @@ -137,33 +138,34 @@ public Response getProjectVulnerabilitiesBadge(
@Path("/violations/project/{uuid}")
@Produces(SVG_MEDIA_TYPE)
@Operation(
summary = "Returns a policy violations badge for a specific project")
summary = "Returns a policy violations badge for a specific project",
description = "<p>Requires permission <strong>VIEW_BADGES</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(
responseCode = "200",
description = "A badge displaying current policy violation metrics of a project in SVG format",
content = @Content(schema = @Schema(type = "string"))
),
@ApiResponse(responseCode = "204", description = "Badge support is disabled. No content will be returned."),
@ApiResponse(responseCode = "401", description = "Unauthorized"),
@ApiResponse(responseCode = "404", description = "The project could not be found")
})
@AuthenticationNotRequired
@PermissionRequired(Permissions.Constants.VIEW_BADGES)
@AllowApiKeyInQueryParameter
public Response getProjectPolicyViolationsBadge(
@Parameter(description = "The UUID of the project to retrieve a badge for", schema = @Schema(type = "string", format = "uuid"), required = true)
@PathParam("uuid") @ValidUuid String uuid) {
try (QueryManager qm = new QueryManager()) {
if (isBadgeSupportEnabled(qm)) {
final Project project = qm.getObjectByUuid(Project.class, uuid);
if (project != null) {
final ProjectMetrics metrics = qm.getMostRecentProjectMetrics(project);
final Badger badger = new Badger();
return Response.ok(badger.generateViolations(metrics)).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The project could not be found.").build();
final Project project = qm.getObjectByUuid(Project.class, uuid);
if (project != null) {
if (!qm.hasAccess(super.getPrincipal(), project)) {
return Response.status(Response.Status.FORBIDDEN).entity("Access to the specified project is forbidden").build();
}
final ProjectMetrics metrics = qm.getMostRecentProjectMetrics(project);
final Badger badger = new Badger();
return Response.ok(badger.generateViolations(metrics)).build();
} else {
return Response.status(Response.Status.NO_CONTENT).build();
return Response.status(Response.Status.NOT_FOUND).entity("The project could not be found.").build();
}
}
}
Expand All @@ -172,35 +174,36 @@ public Response getProjectPolicyViolationsBadge(
@Path("/violations/project/{name}/{version}")
@Produces(SVG_MEDIA_TYPE)
@Operation(
summary = "Returns a policy violations badge for a specific project")
summary = "Returns a policy violations badge for a specific project",
description = "<p>Requires permission <strong>VIEW_BADGES</strong></p>"
)
@ApiResponses(value = {
@ApiResponse(
responseCode = "200",
description = "A badge displaying current policy violation metrics of a project in SVG format",
content = @Content(schema = @Schema(type = "string"))
),
@ApiResponse(responseCode = "204", description = "Badge support is disabled. No content will be returned."),
@ApiResponse(responseCode = "401", description = "Unauthorized"),
@ApiResponse(responseCode = "404", description = "The project could not be found")
})
@AuthenticationNotRequired
@PermissionRequired(Permissions.Constants.VIEW_BADGES)
@AllowApiKeyInQueryParameter
public Response getProjectPolicyViolationsBadge(
@Parameter(description = "The name of the project to query on", required = true)
@PathParam("name") String name,
@Parameter(description = "The version of the project to query on", required = true)
@PathParam("version") String version) {
try (QueryManager qm = new QueryManager()) {
if (isBadgeSupportEnabled(qm)) {
final Project project = qm.getProject(name, version);
if (project != null) {
final ProjectMetrics metrics = qm.getMostRecentProjectMetrics(project);
final Badger badger = new Badger();
return Response.ok(badger.generateViolations(metrics)).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The project could not be found.").build();
final Project project = qm.getProject(name, version);
if (project != null) {
if (!qm.hasAccess(super.getPrincipal(), project)) {
return Response.status(Response.Status.FORBIDDEN).entity("Access to the specified project is forbidden").build();
}
final ProjectMetrics metrics = qm.getMostRecentProjectMetrics(project);
final Badger badger = new Badger();
return Response.ok(badger.generateViolations(metrics)).build();
} else {
return Response.status(Response.Status.NO_CONTENT).build();
return Response.status(Response.Status.NOT_FOUND).entity("The project could not be found.").build();
}
}
}
Expand Down
4 changes: 4 additions & 0 deletions src/main/resources/openapi-configuration.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ openAPI:
BearerAuth:
type: http
scheme: Bearer
ApiKeyQueryAuth:
name: apiKey
type: apiKey
in: query
prettyPrint: true
resourcePackages:
- alpine.server.resources
Expand Down
1 change: 1 addition & 0 deletions src/test/java/org/dependencytrack/ResourceTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ public abstract class ResourceTest {
protected final String SIZE = "size";
protected final String TOTAL_COUNT_HEADER = "X-Total-Count";
protected final String X_API_KEY = "X-Api-Key";
protected final String API_KEY = "apiKey";
protected final String V1_TAG = "/v1/tag";

// Hashing is expensive. Do it once and re-use across tests as much as possible.
Expand Down
Loading
Loading