From 566068b9b7bd722705d03505438e16e24e7344ac Mon Sep 17 00:00:00 2001 From: Oleg Kopysov Date: Thu, 2 May 2024 14:41:02 +0300 Subject: [PATCH] feat: Check new license and alternative license names in OSORI DB Signed-off-by: Oleg Kopysov --- .../com/lpvs/service/LPVSLicenseService.java | 140 +++++++-- .../com/lpvs/service/LPVSQueueService.java | 7 +- .../scanner/LPVSScanossDetectService.java | 20 +- .../java/com/lpvs/util/LPVSPayloadUtil.java | 38 +++ src/main/resources/application.properties | 3 + .../lpvs/service/LPVSGitHubServiceTest.java | 8 - .../lpvs/service/LPVSLicenseServiceTest.java | 266 ++++++++++++++---- .../lpvs/service/LPVSQueueServiceTest.java | 36 ++- .../scanner/LPVSScanossDetectServiceTest.java | 27 +- .../com/lpvs/util/LPVSPayloadUtilTest.java | 32 +++ src/test/resources/osori_db_response1.json | 1 + src/test/resources/osori_db_response2.json | 1 + 12 files changed, 466 insertions(+), 113 deletions(-) create mode 100644 src/test/resources/osori_db_response1.json create mode 100644 src/test/resources/osori_db_response2.json diff --git a/src/main/java/com/lpvs/service/LPVSLicenseService.java b/src/main/java/com/lpvs/service/LPVSLicenseService.java index 995abf51..bd28e231 100644 --- a/src/main/java/com/lpvs/service/LPVSLicenseService.java +++ b/src/main/java/com/lpvs/service/LPVSLicenseService.java @@ -14,12 +14,19 @@ import com.lpvs.repository.LPVSLicenseRepository; import com.lpvs.util.LPVSExitHandler; +import com.lpvs.util.LPVSPayloadUtil; +import lombok.NoArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import jakarta.annotation.PostConstruct; +import java.io.BufferedReader; +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; import java.util.*; /** @@ -67,6 +74,17 @@ public class LPVSLicenseService { */ private LPVSExitHandler exitHandler; + /** + * URL of the source of the new licenses. + */ + @Value("${license_source:}") + private String osoriDbUrl; + + /** + * The object used to make HTTP requests to the OSORI DB. + */ + private OsoriConnection osoriConnection = new OsoriConnection(); + /** * Repository for accessing and managing LPVSLicense entities in the database. */ @@ -198,7 +216,9 @@ public LPVSLicense findLicenseBySPDX(String name) { * @param license The license to add. */ public void addLicenseToList(LPVSLicense license) { - licenses.add(license); + if (!licenses.contains(license)) { + licenses.add(license); + } } /** @@ -212,10 +232,87 @@ public LPVSLicense findLicenseByName(String name) { if (license.getLicenseName().equalsIgnoreCase(name)) { return license; } + if (license.getAlternativeNames() != null + && !license.getAlternativeNames().trim().isEmpty()) { + String[] names = license.getAlternativeNames().split(","); + for (String n : names) { + if (n.trim().equalsIgnoreCase(name)) { + return license; + } + } + } } return null; } + /** + * Gets a license object from the database using the specified license SPDX ID and license name. + * @param licenseSpdxId The license SPDX ID to search for + * @param licenseName The license name to use if the license is not found in the database + * @return The license object that was found or created + */ + public LPVSLicense getLicenseBySpdxIdAndName( + String licenseSpdxId, Optional licenseName) { + String licName = licenseName.orElse(licenseSpdxId); + // check by license SPDX ID + LPVSLicense lic = findLicenseBySPDX(licenseSpdxId); + if (null == lic) { + // check by license name and alternative names + lic = findLicenseByName(licName); + } + // create new license + if (lic == null) { + + if (osoriDbUrl != null && !osoriDbUrl.trim().isEmpty()) { + // check OSORI DB and try to find the license there + try { + HttpURLConnection connection = + osoriConnection.createConnection(osoriDbUrl, licenseSpdxId); + connection.setRequestMethod("GET"); + connection.connect(); + + if (connection.getResponseCode() != 200) { + throw new Exception( + "HTTP error code (" + + connection.getResponseCode() + + "): " + + connection.getResponseMessage()); + } + + BufferedReader in = + LPVSPayloadUtil.createBufferReader( + LPVSPayloadUtil.createInputStreamReader( + connection.getInputStream())); + String inputLine; + StringBuffer response = new StringBuffer(); + + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + + // if found, create new license with field values taken from OSORI DB + lic = LPVSPayloadUtil.convertOsoriDbResponseToLicense(response.toString()); + } catch (Exception e) { + log.error("Error connecting OSORI DB: " + e.getMessage()); + } + } + + if (lic == null) { + // if not found, create new license with default field values + lic = new LPVSLicense(); + lic.setSpdxId(licenseSpdxId); + lic.setLicenseName(licName); + lic.setAlternativeNames(null); + lic.setAccess("UNREVIEWED"); + } + // save new license and add it to the license list + lic = lpvsLicenseRepository.saveAndFlush(lic); + } + addLicenseToList(lic); + return lic; + } + /** * Adds a license conflict to the list of conflicts. * @@ -229,23 +326,6 @@ public void addLicenseConflict(String license1, String license2) { } } - /** - * Checks a license by SPDX identifier and returns the corresponding license object. - * - * @param spdxId SPDX identifier of the license. - * @return The corresponding LPVSLicense object. - */ - public LPVSLicense checkLicense(String spdxId) { - LPVSLicense newLicense = findLicenseBySPDX(spdxId); - if (newLicense == null && spdxId.contains("+")) { - newLicense = findLicenseBySPDX(spdxId.replace("+", "") + "-or-later"); - } - if (newLicense == null && spdxId.contains("+")) { - newLicense = findLicenseBySPDX(spdxId.replace("+", "") + "-only"); - } - return newLicense; - } - /** * Finds license conflicts based on the provided scan results and repository information. * @@ -369,4 +449,28 @@ public int hashCode() { return Objects.hash(l1, l2); } } + + /** + * The OsoriConnection class provides methods for creating a connection to the OSORI database. + */ + @NoArgsConstructor + public static class OsoriConnection { + + /** + * Creates a connection to the OSORI database using the specified OSORI server and license SPDX identifier. + * + * @param osoriDbUrl The URL of the OSORI server. + * @param licenseSpdxId The license SPDX identifier. + * @return A HttpURLConnection object representing the connection to the OSORI database. + */ + public HttpURLConnection createConnection(String osoriDbUrl, String licenseSpdxId) + throws IOException { + URL url = + new URL( + osoriDbUrl + + "/api/v1/user/licenses/spdx_identifier?searchWord=" + + URLEncoder.encode(licenseSpdxId, "UTF-8")); + return (HttpURLConnection) url.openConnection(); + } + } } diff --git a/src/main/java/com/lpvs/service/LPVSQueueService.java b/src/main/java/com/lpvs/service/LPVSQueueService.java index 1227fd81..6c1b9ada 100644 --- a/src/main/java/com/lpvs/service/LPVSQueueService.java +++ b/src/main/java/com/lpvs/service/LPVSQueueService.java @@ -228,9 +228,12 @@ public void processWebHook(LPVSQueue webhookConfig) { } // check repository license String repositoryLicense = gitHubService.getRepositoryLicense(webhookConfig); - if (licenseService.checkLicense(repositoryLicense) != null) { + if (licenseService.getLicenseBySpdxIdAndName(repositoryLicense, Optional.empty()) + != null) { webhookConfig.setRepositoryLicense( - licenseService.checkLicense(repositoryLicense).getSpdxId()); + licenseService + .getLicenseBySpdxIdAndName(repositoryLicense, Optional.empty()) + .getSpdxId()); } else if (licenseService.findLicenseByName(repositoryLicense) != null) { webhookConfig.setRepositoryLicense( licenseService.findLicenseByName(repositoryLicense).getSpdxId()); diff --git a/src/main/java/com/lpvs/service/scan/scanner/LPVSScanossDetectService.java b/src/main/java/com/lpvs/service/scan/scanner/LPVSScanossDetectService.java index a510da81..39c60c30 100644 --- a/src/main/java/com/lpvs/service/scan/scanner/LPVSScanossDetectService.java +++ b/src/main/java/com/lpvs/service/scan/scanner/LPVSScanossDetectService.java @@ -227,21 +227,11 @@ public List checkLicenses(LPVSQueue webhookConfig) { if (object.licenses != null) { for (ScanossJsonStructure.ScanossLicense license : object.licenses) { // Check detected licenses - LPVSLicense lic = licenseService.findLicenseBySPDX(license.name); - if (lic != null) { - lic.setChecklistUrl(license.checklist_url); - licenses.add(lic); - } else { - LPVSLicense newLicense = new LPVSLicense(); - newLicense.setSpdxId(license.name); - newLicense.setLicenseName(license.name); - newLicense.setAccess("UNREVIEWED"); - newLicense.setChecklistUrl(license.checklist_url); - newLicense.setAlternativeNames(null); - newLicense = lpvsLicenseRepository.save(newLicense); - licenseService.addLicenseToList(newLicense); - licenses.add(newLicense); - } + LPVSLicense lic = + licenseService.getLicenseBySpdxIdAndName( + license.name, Optional.empty()); + lic.setChecklistUrl(license.checklist_url); + licenses.add(lic); // Check for the license conflicts if the property // "license_conflict=scanner" diff --git a/src/main/java/com/lpvs/util/LPVSPayloadUtil.java b/src/main/java/com/lpvs/util/LPVSPayloadUtil.java index 678dc05e..35d81403 100644 --- a/src/main/java/com/lpvs/util/LPVSPayloadUtil.java +++ b/src/main/java/com/lpvs/util/LPVSPayloadUtil.java @@ -7,7 +7,9 @@ package com.lpvs.util; import com.google.gson.Gson; +import com.google.gson.JsonArray; import com.google.gson.JsonObject; +import com.lpvs.entity.LPVSLicense; import com.lpvs.entity.LPVSQueue; import com.lpvs.entity.enums.LPVSPullRequestAction; import lombok.extern.slf4j.Slf4j; @@ -19,6 +21,7 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; +import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -52,6 +55,41 @@ public static BufferedReader createBufferReader(InputStreamReader inputStreamRea return new BufferedReader(inputStreamReader); } + /** + * Parses the given payload from the OSORI DB and converts it into a LPVSLicense object. + * + * @param payload the JSON payload from the OSORI DB + * @return the LPVSLicense object containing the parsed information from the payload, or null if the payload is invalid + */ + public static LPVSLicense convertOsoriDbResponseToLicense(String payload) { + try { + Gson gson = new Gson(); + JsonObject json = gson.fromJson(payload, JsonObject.class); + JsonObject messageList = json.getAsJsonObject("messageList"); + JsonArray detailInfoArray = messageList.getAsJsonArray("detailInfo"); + + LPVSLicense lic = new LPVSLicense(); + lic.setLicenseName(detailInfoArray.get(0).getAsJsonObject().get("name").getAsString()); + lic.setSpdxId( + detailInfoArray.get(0).getAsJsonObject().get("spdx_identifier").getAsString()); + lic.setAccess("UNREVIEWED"); + + List nicknameList = new ArrayList<>(); + detailInfoArray + .get(0) + .getAsJsonObject() + .get("nicknameList") + .getAsJsonArray() + .forEach(element -> nicknameList.add(element.getAsString())); + lic.setAlternativeNames(String.join(",", nicknameList)); + + return lic; + } catch (Exception e) { + log.error("Error parsing OSORI DB payload: " + e.getMessage()); + } + return null; + } + /** * Parses the GitHub webhook payload and extracts relevant information to create an LPVSQueue object. * diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index ac0ba853..2268285e 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -12,6 +12,9 @@ scanner=scanoss # Corresponding env. variable LPVS_LICENSE_CONFLICT license_conflict=db +# URL of the external OSORI license database. Default is empty. +license_source=http://223.255.204.223:8082 + # Logger configuration logging.pattern.console=%d{dd-MM-yyyy HH:mm:ss.SSS} %magenta([%thread]) %highlight(%-5level) %logger.%M - %msg%n spring.profiles.active= diff --git a/src/test/java/com/lpvs/service/LPVSGitHubServiceTest.java b/src/test/java/com/lpvs/service/LPVSGitHubServiceTest.java index 31003e38..9bcadb92 100644 --- a/src/test/java/com/lpvs/service/LPVSGitHubServiceTest.java +++ b/src/test/java/com/lpvs/service/LPVSGitHubServiceTest.java @@ -4343,14 +4343,6 @@ public void testCheckEmpty() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { environmentVars.set("LPVS_GITHUB_TOKEN", ""); - - LPVSPullRequestRepository mocked_pullRequestRepository = - mock(LPVSPullRequestRepository.class); - LPVSDetectedLicenseRepository mocked_lpvsDetectedLicenseRepository = - mock(LPVSDetectedLicenseRepository.class); - LPVSLicenseRepository mocked_lpvsLicenseRepository = mock(LPVSLicenseRepository.class); - LPVSLicenseConflictRepository mocked_lpvsLicenseConflictRepository = - mock(LPVSLicenseConflictRepository.class); LPVSExitHandler exitHandler = mock(LPVSExitHandler.class); LPVSGitHubConnectionService lpvsGitHubConnectionService = new LPVSGitHubConnectionService("", "", "", exitHandler); diff --git a/src/test/java/com/lpvs/service/LPVSLicenseServiceTest.java b/src/test/java/com/lpvs/service/LPVSLicenseServiceTest.java index 8bbdee9d..fbd05fec 100644 --- a/src/test/java/com/lpvs/service/LPVSLicenseServiceTest.java +++ b/src/test/java/com/lpvs/service/LPVSLicenseServiceTest.java @@ -6,23 +6,20 @@ */ package com.lpvs.service; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertNotEquals; -import static org.junit.jupiter.api.Assertions.assertNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; +import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.*; +import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Objects; -import java.util.Set; +import java.net.HttpURLConnection; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.*; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; @@ -371,43 +368,6 @@ public void testAddLicenseConflict() throws NoSuchFieldException, IllegalAccessE } } - @Nested - class TestCheckLicense { - LPVSLicenseService licenseService; - - // `lpvs_license_1` - LPVSLicense lpvs_license_1; - final String spdx_id_1 = "MIT"; - // `lpvs_license_2` - LPVSLicense lpvs_license_2; - final String spdx_id_2 = "Apache-1.1-or-later"; - // `lpvs_license_3` - LPVSLicense lpvs_license_3; - final String spdx_id_3 = "Apache-2.0-only"; - - @BeforeEach - void setUp() throws NoSuchFieldException, IllegalAccessException { - licenseService = new LPVSLicenseService(null, exitHandler); - - lpvs_license_1 = new LPVSLicense(1L, null, spdx_id_1, null, null, null); - lpvs_license_2 = new LPVSLicense(1L, null, spdx_id_2, null, null, null); - lpvs_license_3 = new LPVSLicense(1L, null, spdx_id_3, null, null, null); - - Field conflicts_field = licenseService.getClass().getDeclaredField("licenses"); - conflicts_field.setAccessible(true); - conflicts_field.set( - licenseService, List.of(lpvs_license_1, lpvs_license_2, lpvs_license_3)); - } - - @Test - public void testCheckLicense() { - assertEquals(lpvs_license_1, licenseService.checkLicense("MIT")); - assertEquals(lpvs_license_2, licenseService.checkLicense("Apache-1.1+")); - assertEquals(lpvs_license_3, licenseService.checkLicense("Apache-2.0+")); - assertNull(licenseService.checkLicense("non-MIT")); - } - } - @Nested class TestFindConflicts_fullExecution { LPVSLicenseService licenseService; @@ -550,4 +510,212 @@ public void hashTest() { assertNotEquals(Objects.hash(license1, license2), base_conf_21.hashCode()); assertNotEquals(Objects.hash(license1, license2), base_conf_22.hashCode()); } + + @Nested + class TestGetLicenseBySpdxIdAndNameTest { + + LPVSLicenseService licenseService; + LPVSLicense lpvs_license_1, lpvs_license_2; + LPVSLicenseRepository licenseRepository; + + @BeforeEach + void init() throws NoSuchFieldException, IllegalAccessException { + licenseService = new LPVSLicenseService(null, exitHandler); + licenseRepository = Mockito.mock(LPVSLicenseRepository.class); + Field license_repository = + licenseService.getClass().getDeclaredField("lpvsLicenseRepository"); + license_repository.setAccessible(true); + license_repository.set(licenseService, licenseRepository); + + lpvs_license_1 = + new LPVSLicense( + 1L, + "OpenSSL License", + "OpenSSL", + "PERMITTED", + "OPENSSL_LICENSE,SSLeay license and OpenSSL License", + null); + lpvs_license_2 = + new LPVSLicense( + 2L, + "GNU General Public License v3.0 only", + "GPL-3.0-only", + "PROHIBITED", + null, + null); + licenseService.addLicenseToList(lpvs_license_1); + licenseService.addLicenseToList(lpvs_license_2); + } + + @Test + public void getLicenseBySpdxIdAndNameTest_findLicenseBySPDX() { + LPVSLicense result = + licenseService.getLicenseBySpdxIdAndName("GPL-3.0-only", Optional.empty()); + assertEquals("GPL-3.0-only", result.getSpdxId()); + assertEquals("GNU General Public License v3.0 only", result.getLicenseName()); + assertEquals("PROHIBITED", result.getAccess()); + } + + @Test + public void getLicenseBySpdxIdAndNameTest_findLicenseByName() { + LPVSLicense result = + licenseService.getLicenseBySpdxIdAndName("OpenSSL License", Optional.empty()); + assertEquals("OpenSSL", result.getSpdxId()); + assertEquals("OpenSSL License", result.getLicenseName()); + assertEquals("PERMITTED", result.getAccess()); + } + + @Test + public void getLicenseBySpdxIdAndNameTest_connectToOSORI() + throws NoSuchFieldException, + IllegalAccessException, + IOException, + URISyntaxException { + Field osoriDbUrl = licenseService.getClass().getDeclaredField("osoriDbUrl"); + osoriDbUrl.setAccessible(true); + osoriDbUrl.set(licenseService, "http://127.0.0.1:8080"); + + HttpURLConnection mockConnection = Mockito.mock(HttpURLConnection.class); + when(mockConnection.getResponseCode()).thenReturn(200); + + LPVSLicenseService.OsoriConnection mockOsoriConnection = + Mockito.mock(LPVSLicenseService.OsoriConnection.class); + Field osoriConnection = licenseService.getClass().getDeclaredField("osoriConnection"); + osoriConnection.setAccessible(true); + osoriConnection.set(licenseService, mockOsoriConnection); + + when(mockOsoriConnection.createConnection(anyString(), anyString())) + .thenReturn(mockConnection); + + Path path = + Paths.get( + Objects.requireNonNull( + getClass() + .getClassLoader() + .getResource("osori_db_response1.json")) + .toURI()); + + when(mockConnection.getInputStream()).thenReturn(Files.newInputStream(path)); + when(licenseRepository.saveAndFlush(Mockito.any(LPVSLicense.class))) + .thenAnswer(i -> i.getArguments()[0]); + + LPVSLicense result = + licenseService.getLicenseBySpdxIdAndName("Apache-2.0", Optional.empty()); + assertEquals("Apache-2.0", result.getSpdxId()); + assertEquals("Apache License 2.0", result.getLicenseName()); + assertEquals("UNREVIEWED", result.getAccess()); + } + + @Test + public void getLicenseBySpdxIdAndNameTest_createNewLicense() + throws NoSuchFieldException, + IllegalAccessException, + IOException, + URISyntaxException { + Field osoriDbUrl = licenseService.getClass().getDeclaredField("osoriDbUrl"); + osoriDbUrl.setAccessible(true); + osoriDbUrl.set(licenseService, "http://127.0.0.1:8080"); + + HttpURLConnection mockConnection = Mockito.mock(HttpURLConnection.class); + when(mockConnection.getResponseCode()).thenReturn(200); + + LPVSLicenseService.OsoriConnection mockOsoriConnection = + Mockito.mock(LPVSLicenseService.OsoriConnection.class); + Field osoriConnection = licenseService.getClass().getDeclaredField("osoriConnection"); + osoriConnection.setAccessible(true); + osoriConnection.set(licenseService, mockOsoriConnection); + + when(mockOsoriConnection.createConnection(anyString(), anyString())) + .thenReturn(mockConnection); + + Path path = + Paths.get( + Objects.requireNonNull( + getClass() + .getClassLoader() + .getResource("osori_db_response2.json")) + .toURI()); + + when(mockConnection.getInputStream()).thenReturn(Files.newInputStream(path)); + when(licenseRepository.saveAndFlush(Mockito.any(LPVSLicense.class))) + .thenAnswer(i -> i.getArguments()[0]); + + LPVSLicense result = + licenseService.getLicenseBySpdxIdAndName("Apache-2.0", Optional.empty()); + assertEquals("Apache-2.0", result.getSpdxId()); + assertEquals("Apache-2.0", result.getLicenseName()); + assertEquals("UNREVIEWED", result.getAccess()); + } + + @Test + public void getLicenseBySpdxIdAndNameTest_emptyOsoriUrl_N() + throws NoSuchFieldException, + IllegalAccessException, + IOException, + URISyntaxException { + when(licenseRepository.saveAndFlush(Mockito.any(LPVSLicense.class))) + .thenAnswer(i -> i.getArguments()[0]); + LPVSLicense result = + licenseService.getLicenseBySpdxIdAndName("Apache-2.0", Optional.empty()); + assertEquals("Apache-2.0", result.getSpdxId()); + assertEquals("Apache-2.0", result.getLicenseName()); + assertEquals("UNREVIEWED", result.getAccess()); + } + + @Test + public void getLicenseBySpdxIdAndNameTest_errorCodeInOSORI_N() + throws NoSuchFieldException, + IllegalAccessException, + IOException, + URISyntaxException { + Field osoriDbUrl = licenseService.getClass().getDeclaredField("osoriDbUrl"); + osoriDbUrl.setAccessible(true); + osoriDbUrl.set(licenseService, "http://127.0.0.1:8080"); + + HttpURLConnection mockConnection = Mockito.mock(HttpURLConnection.class); + when(mockConnection.getResponseCode()).thenReturn(400); + + LPVSLicenseService.OsoriConnection mockOsoriConnection = + Mockito.mock(LPVSLicenseService.OsoriConnection.class); + Field osoriConnection = licenseService.getClass().getDeclaredField("osoriConnection"); + osoriConnection.setAccessible(true); + osoriConnection.set(licenseService, mockOsoriConnection); + + when(mockOsoriConnection.createConnection(anyString(), anyString())) + .thenReturn(mockConnection); + when(licenseRepository.saveAndFlush(Mockito.any(LPVSLicense.class))) + .thenAnswer(i -> i.getArguments()[0]); + + LPVSLicense result = + licenseService.getLicenseBySpdxIdAndName("Apache-2.0", Optional.empty()); + assertEquals("Apache-2.0", result.getSpdxId()); + assertEquals("Apache-2.0", result.getLicenseName()); + assertEquals("UNREVIEWED", result.getAccess()); + } + } + + @Nested + class TestOsoriConnection { + + @Test + public void testCreateConnection() throws IOException { + String osoriDbUrl = "https://ossori.com"; + String licenseSpdxId = "Apache-2.0"; + LPVSLicenseService.OsoriConnection connection = + new LPVSLicenseService.OsoriConnection(); + HttpURLConnection httpURLConnection = + connection.createConnection(osoriDbUrl, licenseSpdxId); + assertEquals( + osoriDbUrl + "/api/v1/user/licenses/spdx_identifier?searchWord=Apache-2.0", + httpURLConnection.getURL().toString()); + } + + @Test + public void testCreateConnectionThrowsIOException_N() { + String licenseSpdxId = "Apache-2.0"; + LPVSLicenseService.OsoriConnection connection = + new LPVSLicenseService.OsoriConnection(); + assertThrows(IOException.class, () -> connection.createConnection(null, licenseSpdxId)); + } + } } diff --git a/src/test/java/com/lpvs/service/LPVSQueueServiceTest.java b/src/test/java/com/lpvs/service/LPVSQueueServiceTest.java index 2a961a8e..48aa2248 100644 --- a/src/test/java/com/lpvs/service/LPVSQueueServiceTest.java +++ b/src/test/java/com/lpvs/service/LPVSQueueServiceTest.java @@ -327,7 +327,8 @@ void setUp() { .thenReturn(licenseNameTest); mockLicenseService = mock(LPVSLicenseService.class); - when(mockLicenseService.checkLicense(licenseNameTest)).thenReturn(lpvsLicenseTest); + when(mockLicenseService.getLicenseBySpdxIdAndName(licenseNameTest, Optional.empty())) + .thenReturn(lpvsLicenseTest); mockDetectService = mock(LPVSDetectService.class); try { @@ -358,7 +359,8 @@ public void testProcessWebHook____DeletionAbsentLicensePresent() throws Exceptio verify(mockGitHubService, times(1)).getPullRequestFiles(webhookConfigMain); verify(mockGitHubService, times(1)).getRepositoryLicense(webhookConfigMain); - verify(mockLicenseService, times(2)).checkLicense(licenseNameTest); + verify(mockLicenseService, times(2)) + .getLicenseBySpdxIdAndName(licenseNameTest, Optional.empty()); try { verify(mockDetectService, times(1)) .runScan(webhookConfigMain, filePathTestNoDeletion); @@ -420,7 +422,8 @@ void setUp() { .thenReturn(licenseNameTest); mockLicenseService = mock(LPVSLicenseService.class); - when(mockLicenseService.checkLicense(licenseNameTest)).thenReturn(lpvsLicenseTest); + when(mockLicenseService.getLicenseBySpdxIdAndName(licenseNameTest, Optional.empty())) + .thenReturn(lpvsLicenseTest); mockDetectService = mock(LPVSDetectService.class); try { @@ -452,7 +455,8 @@ public void testProcessWebHook____DeletionPresentLicensePresent() throws Excepti verify(mockGitHubService, times(1)).getPullRequestFiles(webhookConfigMain); verify(mockGitHubService, times(1)).getRepositoryLicense(webhookConfigMain); - verify(mockLicenseService, times(2)).checkLicense(licenseNameTest); + verify(mockLicenseService, times(2)) + .getLicenseBySpdxIdAndName(licenseNameTest, Optional.empty()); try { verify(mockDetectService, times(1)) .runScan(webhookConfigMain, filePathTestWithDeletionTruncated); @@ -511,7 +515,8 @@ void setUp() { .thenReturn(licenseNameTest); mockLicenseService = mock(LPVSLicenseService.class); - when(mockLicenseService.checkLicense(licenseNameTest)).thenReturn(null); + when(mockLicenseService.getLicenseBySpdxIdAndName(licenseNameTest, Optional.empty())) + .thenReturn(null); when(mockLicenseService.findLicenseByName(licenseNameTest)).thenReturn(lpvsLicenseTest); mockDetectService = mock(LPVSDetectService.class); @@ -546,7 +551,8 @@ public void testProcessWebHook__DeletionAbsentLicenseFound() throws Exception { verify(mockGitHubService, times(1)).getPullRequestFiles(webhookConfigMain); verify(mockGitHubService, times(1)).getRepositoryLicense(webhookConfigMain); - verify(mockLicenseService, times(1)).checkLicense(licenseNameTest); + verify(mockLicenseService, times(1)) + .getLicenseBySpdxIdAndName(licenseNameTest, Optional.empty()); verify(mockLicenseService, times(2)).findLicenseByName(licenseNameTest); try { verify(mockDetectService, times(1)) @@ -609,7 +615,8 @@ void setUp() { .thenReturn(licenseNameTest); mockLicenseService = mock(LPVSLicenseService.class); - when(mockLicenseService.checkLicense(licenseNameTest)).thenReturn(null); + when(mockLicenseService.getLicenseBySpdxIdAndName(licenseNameTest, Optional.empty())) + .thenReturn(null); when(mockLicenseService.findLicenseByName(licenseNameTest)).thenReturn(lpvsLicenseTest); mockDetectService = mock(LPVSDetectService.class); @@ -642,7 +649,8 @@ public void testProcessWebHook__DeletionPresentLicenseFound() throws Exception { verify(mockGitHubService, times(1)).getPullRequestFiles(webhookConfigMain); verify(mockGitHubService, times(1)).getRepositoryLicense(webhookConfigMain); - verify(mockLicenseService, times(1)).checkLicense(licenseNameTest); + verify(mockLicenseService, times(1)) + .getLicenseBySpdxIdAndName(licenseNameTest, Optional.empty()); verify(mockLicenseService, times(2)).findLicenseByName(licenseNameTest); try { verify(mockDetectService, times(1)) @@ -705,7 +713,8 @@ void setUp() { .thenReturn(licenseNameTest); mockLicenseService = mock(LPVSLicenseService.class); - when(mockLicenseService.checkLicense(licenseNameTest)).thenReturn(null); + when(mockLicenseService.getLicenseBySpdxIdAndName(licenseNameTest, Optional.empty())) + .thenReturn(null); when(mockLicenseService.findLicenseByName(licenseNameTest)).thenReturn(null); mockDetectService = mock(LPVSDetectService.class); @@ -737,7 +746,8 @@ public void testProcessWebHook__DeletionAbsentLicenseNull() throws Exception { verify(mockGitHubService, times(1)).getPullRequestFiles(webhookConfigMain); verify(mockGitHubService, times(1)).getRepositoryLicense(webhookConfigMain); - verify(mockLicenseService, times(1)).checkLicense(licenseNameTest); + verify(mockLicenseService, times(1)) + .getLicenseBySpdxIdAndName(licenseNameTest, Optional.empty()); verify(mockLicenseService, times(1)).findLicenseByName(licenseNameTest); try { verify(mockDetectService, times(1)) @@ -800,7 +810,8 @@ void setUp() { .thenReturn(licenseNameTest); mockLicenseService = mock(LPVSLicenseService.class); - when(mockLicenseService.checkLicense(licenseNameTest)).thenReturn(null); + when(mockLicenseService.getLicenseBySpdxIdAndName(licenseNameTest, Optional.empty())) + .thenReturn(null); when(mockLicenseService.findLicenseByName(licenseNameTest)).thenReturn(null); mockDetectService = mock(LPVSDetectService.class); @@ -833,7 +844,8 @@ public void testProcessWebHook__DeletionAbsentLicenseNull() throws Exception { verify(mockGitHubService, times(1)).getPullRequestFiles(webhookConfigMain); verify(mockGitHubService, times(1)).getRepositoryLicense(webhookConfigMain); - verify(mockLicenseService, times(1)).checkLicense(licenseNameTest); + verify(mockLicenseService, times(1)) + .getLicenseBySpdxIdAndName(licenseNameTest, Optional.empty()); verify(mockLicenseService, times(1)).findLicenseByName(licenseNameTest); try { verify(mockDetectService, times(1)) diff --git a/src/test/java/com/lpvs/service/scan/scanner/LPVSScanossDetectServiceTest.java b/src/test/java/com/lpvs/service/scan/scanner/LPVSScanossDetectServiceTest.java index 658825b7..d70294cb 100644 --- a/src/test/java/com/lpvs/service/scan/scanner/LPVSScanossDetectServiceTest.java +++ b/src/test/java/com/lpvs/service/scan/scanner/LPVSScanossDetectServiceTest.java @@ -58,15 +58,6 @@ public void setUp() throws URISyntaxException, IOException { .toURI()), Paths.get(destinationPath + File.separator + resourcePath), StandardCopyOption.REPLACE_EXISTING); - Mockito.when(licenseService.findLicenseBySPDX("MIT")) - .thenReturn( - new LPVSLicense() { - { - setLicenseName("MIT"); - setLicenseId(1L); - setSpdxId("MIT"); - } - }); scanossDetectService = new LPVSScanossDetectService(false, licenseService, lpvsLicenseRepository); } @@ -88,6 +79,15 @@ public void testCheckLicense() { .thenAnswer(i -> i.getArguments()[0]); ReflectionTestUtils.setField( licenseService, "licenseConflictsSource", licenseConflictsSource); + Mockito.when(licenseService.getLicenseBySpdxIdAndName(anyString(), any())) + .thenReturn( + new LPVSLicense() { + { + setLicenseName("MIT"); + setLicenseId(1L); + setSpdxId("MIT"); + } + }); Assertions.assertNotNull(scanossDetectService.checkLicenses(lpvsQueue)); } @@ -103,6 +103,15 @@ public void testCheckLicenseHeadCommitSHA() { .thenAnswer(i -> i.getArguments()[0]); ReflectionTestUtils.setField( licenseService, "licenseConflictsSource", licenseConflictsSource); + Mockito.when(licenseService.getLicenseBySpdxIdAndName(anyString(), any())) + .thenReturn( + new LPVSLicense() { + { + setLicenseName("MIT"); + setLicenseId(1L); + setSpdxId("MIT"); + } + }); webhookConfig.setHeadCommitSHA(""); Assertions.assertNotNull(scanossDetectService.checkLicenses(webhookConfig)); } diff --git a/src/test/java/com/lpvs/util/LPVSPayloadUtilTest.java b/src/test/java/com/lpvs/util/LPVSPayloadUtilTest.java index d7e2e4c0..4b7e3795 100644 --- a/src/test/java/com/lpvs/util/LPVSPayloadUtilTest.java +++ b/src/test/java/com/lpvs/util/LPVSPayloadUtilTest.java @@ -6,6 +6,7 @@ */ package com.lpvs.util; +import com.lpvs.entity.LPVSLicense; import com.lpvs.entity.LPVSQueue; import com.lpvs.entity.enums.LPVSPullRequestAction; import org.junit.jupiter.api.BeforeEach; @@ -25,6 +26,37 @@ public class LPVSPayloadUtilTest { + @Nested + class TestConvertOsoriDbResponseToLicense { + @Test + public void testConvertOsoriDbResponseToLicense() { + String payload = + "{\"code\":\"200\",\"messageList\":{\"detailInfo\":[{\"name\":\"Apache License 2.0\",\"spdx_identifier\":\"Apache-2.0\",\"webpage\":\"https://spdx.org/licenses/Apache-2.0.html\",\"nicknameList\":[\"Android-Apache-2.0\",\"Apache 2\"],\"webpageList\":null,\"restrictionList\":null}]},\"success\":true}"; + LPVSLicense expectedLicense = new LPVSLicense(); + expectedLicense.setLicenseName("Apache License 2.0"); + expectedLicense.setSpdxId("Apache-2.0"); + expectedLicense.setAccess("UNREVIEWED"); + expectedLicense.setAlternativeNames("Android-Apache-2.0,Apache 2"); + + LPVSLicense actualLicense = LPVSPayloadUtil.convertOsoriDbResponseToLicense(payload); + + assertNotNull(actualLicense); + assertEquals(expectedLicense.getLicenseName(), actualLicense.getLicenseName()); + assertEquals(expectedLicense.getSpdxId(), actualLicense.getSpdxId()); + assertEquals(expectedLicense.getAccess(), actualLicense.getAccess()); + assertEquals( + expectedLicense.getAlternativeNames(), actualLicense.getAlternativeNames()); + } + + @Test + public void testConvertOsoriDbResponseToLicense_withInvalidPayload_N() { + String payload = + "{\"code\":\"200\",\"messageList\":{\"detailInfo\":[{\"name\":\"Apache License 2.0\",\"spdx_identifier\":\"Apache-2.0\",\"webpage\":\"https://spdx.org/licenses/Apache-2.0.html\",\"webpageList\":null,\"restrictionList\":null}]},\"success\":true}"; + LPVSLicense actualLicense = LPVSPayloadUtil.convertOsoriDbResponseToLicense(payload); + assertNull(actualLicense); + } + } + @Nested class TestGetGitHubWebhookConfig__ForkTrue { String json_to_test; diff --git a/src/test/resources/osori_db_response1.json b/src/test/resources/osori_db_response1.json new file mode 100644 index 00000000..0865fc29 --- /dev/null +++ b/src/test/resources/osori_db_response1.json @@ -0,0 +1 @@ +{"code":"200","messageList":{"detailInfo":[{"name":"Apache License 2.0","obligation_disclosing_src":"NONE","obligation_notification":true,"spdx_identifier":"Apache-2.0","webpage":"https://spdx.org/licenses/Apache-2.0.html","description":"To distribute the software, copyright and license notice is required.\n\n","description_ko":null,"license_text":"Apache License\nVersion 2.0, January 2004\nhttp://www.apache.org/licenses/\n\nTERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n1. Definitions.\n\n\"License\" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.\n\n\"Licensor\" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.\n\n\"Legal Entity\" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, \"control\" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.\n\n\"You\" (or \"Your\") shall mean an individual or Legal Entity exercising permissions granted by this License.\n\n\"Source\" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.\n\n\"Object\" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.\n\n\"Work\" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).\n\n\"Derivative Works\" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.\n\n\"Contribution\" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, \"submitted\" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as \"Not a Contribution.\"\n\n\"Contributor\" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.\n\n2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.\n\n3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.\n\n4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:\n\n (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and\n\n (b) You must cause any modified files to carry prominent notices stating that You changed the files; and\n\n (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and\n\n (d) If the Work includes a \"NOTICE\" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.\n\n You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.\n\n5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.\n\n6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.\n\n7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.\n\n8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.\n\n9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.\n\nEND OF TERMS AND CONDITIONS\n\nAPPENDIX: How to apply the Apache License to your work.\n\nTo apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets \"[]\" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same \"printed page\" as the copyright notice for easier identification within third-party archives.\n\nCopyright [yyyy] [name of copyright owner]\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.","osi_approval":true,"modifier":"4","created_date":"2023-10-24 15:46:20","modified_date":"2024-04-11 12:00:42","reviewed":true,"nicknameList":["Android-Apache-2.0","Apache 2","Apache 2.0","Apache 2.0 license","Apache License (v2.0)","Apache License v2","Apache License v2.0","Apache License Version 2.0","Apache License Version 2.0 January 2004","Apache Public License 2.0","Apache Software License (Apache 2.0)","Apache Software License (Apache License 2.0)","Apache Software License - Version 2.0","Apache v2","Apache v2.0","Apache Version 2.0","Apache-2.0 License","APACHE2","ASF 2.0","http://www.apache.org/licenses/LICENSE-2.0.txt","https://www.apache.org/licenses/LICENSE-2.0","https://www.apache.org/licenses/LICENSE-2.0.txt","the Apache License ASL Version 2.0","The Apache License Version 2.0","The Apache Software License Version 2.0"],"webpageList":null,"restrictionList":null}]},"success":true} \ No newline at end of file diff --git a/src/test/resources/osori_db_response2.json b/src/test/resources/osori_db_response2.json new file mode 100644 index 00000000..9875c2f9 --- /dev/null +++ b/src/test/resources/osori_db_response2.json @@ -0,0 +1 @@ +{"code":"200","messageList":{"detailInfo":[]},"success":true} \ No newline at end of file