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

feat: add ubi mapping for base image recommendation #313

Merged
merged 2 commits into from
Mar 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ protected DependencyTree buildTree(InputStream input) {
if (bom.getComponents() != null) {
componentPurls.putAll(
bom.getComponents().stream()
.filter(c -> c.getBomRef() != null)
.filter(c -> c.getBomRef() != null && c.getPurl() != null)
.collect(Collectors.toMap(Component::getBomRef, c -> new PackageRef(c.getPurl()))));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,12 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.redhat.exhort.integration.Constants;
import com.redhat.exhort.integration.trustedcontent.ubi.UBIRecommendation;

import io.quarkus.runtime.annotations.RegisterForReflection;

import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;

@RegisterForReflection
@ApplicationScoped
Expand All @@ -56,6 +58,8 @@ public class ReportTemplate {
@ConfigProperty(name = "report.cve.issue.regex")
String cveIssuePathRegex;

@Inject UBIRecommendation ubiRecommendation;

public Map<String, Object> setVariables(
@Body Object report,
@ExchangeProperty(Constants.PROVIDER_PRIVATE_DATA_PROPERTY) List<String> providerPrivateData)
Expand All @@ -69,6 +73,7 @@ public Map<String, Object> setVariables(
params.put("providerPrivateData", providerPrivateData);
params.put("snykSignup", snykSignup);
params.put("cveIssueTemplate", cveIssuePathRegex);
params.put("imageMapping", getImageMapping());

ObjectWriter objectWriter = new ObjectMapper().writer();
String appData = objectWriter.writeValueAsString(params);
Expand All @@ -77,6 +82,22 @@ public Map<String, Object> setVariables(
return params;
}

private String getImageMapping() throws JsonProcessingException {
List<Map<String, String>> urlMapping =
ubiRecommendation.purl().keySet().stream()
.map(
ubi -> {
Map<String, String> urls = new HashMap<>(2);
urls.put("purl", ubiRecommendation.purl().get(ubi));
urls.put("catalogUrl", ubiRecommendation.catalogurl().get(ubi));
return urls;
})
.toList();

ObjectWriter objectWriter = new ObjectMapper().writer();
return objectWriter.writeValueAsString(urlMapping);
}

@RegisterForReflection
public static record IssueLinkFormatter(String issuePathRegex) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,13 @@
import org.apache.camel.Body;
import org.apache.camel.Exchange;
import org.apache.camel.ExchangeProperty;
import org.eclipse.microprofile.config.inject.ConfigProperty;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.redhat.exhort.api.PackageRef;
import com.redhat.exhort.api.v4.ProviderStatus;
import com.redhat.exhort.integration.Constants;
import com.redhat.exhort.integration.providers.ProviderResponseHandler;
import com.redhat.exhort.integration.trustedcontent.ubi.UBIRecommendation;
import com.redhat.exhort.model.DependencyTree;
import com.redhat.exhort.model.ProviderResponse;
import com.redhat.exhort.model.trustedcontent.IndexedRecommendation;
Expand All @@ -60,8 +60,7 @@ public class TcResponseHandler extends ProviderResponseHandler {

@Inject ObjectMapper mapper;

@ConfigProperty(name = "trustedcontent.recommended.ubi")
String recommendedUBIPurl;
@Inject UBIRecommendation ubiRecommendation;

public TrustedContentResponse parseResponse(
@Body byte[] tcResponse, @ExchangeProperty(Constants.SBOM_ID_PROPERTY) String sbomId)
Expand Down Expand Up @@ -116,14 +115,17 @@ private Map<PackageRef, IndexedRecommendation> getUBIRecommendation(String sbomI
return Collections.emptyMap();
}

PackageRef pkgRef = new PackageRef(sbomId);
var pkgRef = new PackageRef(sbomId);
if (!Constants.OCI_PURL_TYPE.equals(pkgRef.purl().getType())) {
return Collections.emptyMap();
}

IndexedRecommendation recommendation =
new IndexedRecommendation(new PackageRef(recommendedUBIPurl), null);
return Collections.singletonMap(pkgRef, recommendation);
var recommendedUBIPurl = ubiRecommendation.mapping().get(pkgRef.name());
if (recommendedUBIPurl != null) {
var recommendation = new IndexedRecommendation(new PackageRef(recommendedUBIPurl), null);
return Collections.singletonMap(pkgRef, recommendation);
}
return Collections.emptyMap();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Copyright 2024 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.
*/

package com.redhat.exhort.integration.trustedcontent.ubi;

import java.util.Map;

import io.smallrye.config.ConfigMapping;

@ConfigMapping(prefix = "trustedcontent.recommendation.ubi")
public interface UBIRecommendation {
Map<String, String> mapping();

Map<String, String> purl();

Map<String, String> catalogurl();
}
11 changes: 10 additions & 1 deletion src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,13 @@ quarkus.rest-client.segment-api.url=https://api.segment.io/
quarkus.management.enabled=true
quarkus.http.limits.max-body-size=4G

trustedcontent.recommended.ubi=pkg:oci/registry.access.redhat.com/ubi9/ubi@latest
trustedcontent.recommendation.ubi.purl.ubi9=pkg:oci/ubi@sha256:f5983f7c7878cc9b26a3962be7756e3c810e9831b0b9f9613e6f6b445f884e74?repository_url=registry.access.redhat.com/ubi9/ubi&tag=9.3-1552&arch=amd64
trustedcontent.recommendation.ubi.catalogurl.ubi9=https://catalog.redhat.com/software/containers/ubi9/ubi/615bcf606feffc5384e8452e?architecture=amd64&image=65a82982a10f3e68777870b5f
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@olavtar I moved the configurations for the links to application.properties

trustedcontent.recommendation.ubi.purl.ubi9-minimal=pkg:oci/ubi-minimal@sha256:06d06f15f7b641a78f2512c8817cbecaa1bf549488e273f5ac27ff1654ed33f0?repository_url=registry.access.redhat.com/ubi9/ubi-minimal&tag=9.3-1552&arch=amd64
trustedcontent.recommendation.ubi.catalogurl.ubi9-minimal=https://catalog.redhat.com/software/containers/ubi9/ubi-minimal/615bd9b4075b022acc111bf5?architecture=amd64&image=65a828e3cda4984705d45d26
trustedcontent.recommendation.ubi.mapping.alpine=${trustedcontent.recommendation.ubi.purl.ubi9-minimal}
trustedcontent.recommendation.ubi.mapping.ubuntu=${trustedcontent.recommendation.ubi.purl.ubi9}
trustedcontent.recommendation.ubi.mapping.centos=${trustedcontent.recommendation.ubi.purl.ubi9}
trustedcontent.recommendation.ubi.mapping.debian=${trustedcontent.recommendation.ubi.purl.ubi9}
trustedcontent.recommendation.ubi.mapping.fedora=${trustedcontent.recommendation.ubi.purl.ubi9}
trustedcontent.recommendation.ubi.mapping.amazonlinux=${trustedcontent.recommendation.ubi.purl.ubi9}
2 changes: 1 addition & 1 deletion src/main/resources/freemarker/templates/generated/main.js

Large diffs are not rendered by default.

6 changes: 3 additions & 3 deletions src/test/java/com/redhat/exhort/integration/AnalysisTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -668,9 +668,9 @@ public void testBatchSBOMAllWithToken(String sbom) {
.asPrettyString();

assertJson("reports/batch_report_all_token.json", body);
verifySnykRequest(OK_TOKEN, 2);
verifyOssRequest(OK_USER, OK_TOKEN, 2);
verifyOsvNvdRequest(2);
verifySnykRequest(OK_TOKEN, 3);
verifyOssRequest(OK_USER, OK_TOKEN, 3);
verifyOsvNvdRequest(3);
}

private void assertScanned(Scanned scanned) {
Expand Down
43 changes: 43 additions & 0 deletions src/test/java/com/redhat/exhort/integration/HtmlReportTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.DomNodeList;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlHeading2;
import com.gargoylesoftware.htmlunit.html.HtmlHeading4;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
Expand Down Expand Up @@ -317,6 +319,47 @@ public void testHtmlError() throws IOException {
verifyNoInteractionsWithOSS();
}

@Test
public void testBatchHtmlWithToken() throws IOException {
stubAllProviders();

String body =
given()
.header(CONTENT_TYPE, CycloneDxMediaType.APPLICATION_CYCLONEDX_JSON)
.body(loadBatchSBOMFile(CYCLONEDX))
.header("Accept", MediaType.TEXT_HTML)
.header(Constants.SNYK_TOKEN_HEADER, OK_TOKEN)
.header(Constants.OSS_INDEX_USER_HEADER, OK_USER)
.header(Constants.OSS_INDEX_TOKEN_HEADER, OK_TOKEN)
.when()
.post("/api/v4/batch-analysis")
.then()
.assertThat()
.statusCode(200)
.contentType(MediaType.TEXT_HTML)
.header(
Constants.EXHORT_REQUEST_ID_HEADER,
MatchesPattern.matchesPattern(REGEX_MATCHER_REQUEST_ID))
.extract()
.body()
.asString();

HtmlPage page = extractPage(body);
// Find the root div element with id "root"
HtmlElement rootElement = page.getFirstByXPath("//div[@id='root']");

// Verify multi tab layout
List<HtmlElement> sectionElements = rootElement.getByXPath("./section");
assertEquals(1, sectionElements.size());
List<HtmlAnchor> anchorElements =
page.getByXPath(
"//a[contains(@href, 'https://catalog.redhat.com/software/containers/ubi9/')]");
assertTrue(!anchorElements.isEmpty(), "At least one href contains the desired substring");

verifySnykRequest(OK_TOKEN, 3);
verifyOssRequest(OK_USER, OK_TOKEN, 3);
}

private HtmlTableBody getTableBodyForDependency(String depRef, DomElement table) {
List<HtmlTableBody> tbodies = table.getByXPath(".//tbody");
return tbodies.stream()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@
import java.util.Map;
import java.util.Set;

import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.junit.jupiter.api.Test;

import com.redhat.exhort.api.PackageRef;
import com.redhat.exhort.integration.Constants;
import com.redhat.exhort.integration.trustedcontent.ubi.UBIRecommendation;
import com.redhat.exhort.model.trustedcontent.IndexedRecommendation;

import io.quarkus.test.junit.QuarkusTest;
Expand All @@ -47,8 +47,7 @@ class TcResponseHandlerTest {

@Inject TcResponseHandler handler;

@ConfigProperty(name = "trustedcontent.recommended.ubi")
String recommendedUBIPurl;
@Inject UBIRecommendation mapping;

@Test
void testAggregation() throws IOException {
Expand Down Expand Up @@ -114,14 +113,15 @@ void testEmpty() throws IOException {

@Test
void testSbomId() throws IOException {
String sbomId = "pkg:oci/quay.io/test-app@0.0.1";
String sbomId = "pkg:oci/alpine@0.0.1";
handler.ubiRecommendation = mapping;
var response =
handler.parseResponse(
getClass()
.getClassLoader()
.getResourceAsStream("__files/trustedcontent/empty_report.json")
.readAllBytes(),
"pkg:oci/quay.io/test-app@0.0.1");
sbomId);
assertNotNull(response);
assertTrue(response.status().getOk());
assertEquals("OK", response.status().getMessage());
Expand All @@ -130,17 +130,19 @@ void testSbomId() throws IOException {

PackageRef sbomRef = new PackageRef(sbomId);
IndexedRecommendation recommendation =
new IndexedRecommendation(new PackageRef(recommendedUBIPurl), null);
new IndexedRecommendation(new PackageRef(expectedUBIRecommendation), null);
assertEquals(1, response.recommendations().size());
assertEquals(recommendation, response.recommendations().get(sbomRef));
}

private static final record ExpectedRecommendation(String version, Set<String> cves) {}

private static final String expectedUBIRecommendation = "pkg:oci/ubi@0.0.2";

public static class SbomIdTestProfile implements QuarkusTestProfile {
@Override
public Map<String, String> getConfigOverrides() {
return Map.of("trustedcontent.recommended.ubi", "pkg:oci/quay.io/test-app@0.0.2");
return Map.of("trustedcontent.recommendation.ubi.mapping.alpine", expectedUBIRecommendation);
}
}
}
76 changes: 70 additions & 6 deletions src/test/resources/__files/reports/batch_report_all_token.json
Original file line number Diff line number Diff line change
Expand Up @@ -839,7 +839,71 @@
}
}
},
"pkg:oci/quay.io/default-app@0.0.1": {
"pkg:oci/default-app@sha256:7c288032ecf3319045d9fa538c3b0cc868a320d01d03bce15b99c2c336319994?repository_url=quay.io/default-app&tag=0.0.1": {
"scanned": {
"total": 2,
"direct": 2,
"transitive": 0
},
"providers": {
"oss-index": {
"status": {
"ok": false,
"name": "oss-index",
"code": 401,
"message": "Unauthorized: Verify the provided credentials are valid."
}
},
"trusted-content": {
"status": {
"ok": true,
"name": "trusted-content",
"code": 200,
"message": "OK"
}
},
"osv-nvd": {
"status": {
"ok": true,
"name": "osv-nvd",
"code": 200,
"message": "OK"
}
},
"snyk": {
"status": {
"ok": true,
"name": "snyk",
"code": 200,
"message": "OK"
},
"sources": {
"snyk": {
"summary": {
"direct": 0,
"transitive": 0,
"total": 0,
"dependencies": 0,
"critical": 0,
"high": 0,
"medium": 0,
"low": 0,
"remediations": 0,
"recommendations": 0,
"unscanned": 1
},
"unscanned": [
{
"ref": "pkg:oci/default-app@sha256%3A7c288032ecf3319045d9fa538c3b0cc868a320d01d03bce15b99c2c336319994?repository_url=quay.io%2Fdefault-app&tag=0.0.1",
"reason": "unsupported-pkg-type"
}
]
}
}
}
}
},
"pkg:oci/debian@sha256:7c288032ecf3319045d9fa538c3b0cc868a320d01d03bce15b99c2c336319994?tag=0.0.1": {
"scanned": {
"total": 2,
"direct": 2,
Expand Down Expand Up @@ -886,8 +950,8 @@
},
"dependencies": [
{
"ref": "pkg:oci/quay.io/default-app@0.0.1",
"recommendation": "pkg:oci/registry.access.redhat.com/ubi9/ubi@latest"
"ref": "pkg:oci/debian@sha256%3A7c288032ecf3319045d9fa538c3b0cc868a320d01d03bce15b99c2c336319994?tag=0.0.1",
"recommendation": "pkg:oci/ubi@sha256%3Af5983f7c7878cc9b26a3962be7756e3c810e9831b0b9f9613e6f6b445f884e74?arch=amd64&repository_url=registry.access.redhat.com%2Fubi9%2Fubi&tag=9.3-1552"
}
]
}
Expand Down Expand Up @@ -917,13 +981,13 @@
},
"dependencies": [
{
"ref": "pkg:oci/quay.io/default-app@0.0.1",
"recommendation": "pkg:oci/registry.access.redhat.com/ubi9/ubi@latest"
"ref": "pkg:oci/debian@sha256%3A7c288032ecf3319045d9fa538c3b0cc868a320d01d03bce15b99c2c336319994?tag=0.0.1",
"recommendation": "pkg:oci/ubi@sha256%3Af5983f7c7878cc9b26a3962be7756e3c810e9831b0b9f9613e6f6b445f884e74?arch=amd64&repository_url=registry.access.redhat.com%2Fubi9%2Fubi&tag=9.3-1552"
}
],
"unscanned": [
{
"ref": "pkg:oci/quay.io/default-app@0.0.1",
"ref": "pkg:oci/debian@sha256%3A7c288032ecf3319045d9fa538c3b0cc868a320d01d03bce15b99c2c336319994?tag=0.0.1",
"reason": "unsupported-pkg-type"
}
]
Expand Down
Loading
Loading