Skip to content

Commit

Permalink
fix: even more tests
Browse files Browse the repository at this point in the history
Signed-off-by: san-zrl <[email protected]>
  • Loading branch information
san-zrl committed Oct 4, 2024
1 parent 2daae1b commit 0a578df
Show file tree
Hide file tree
Showing 11 changed files with 427 additions and 27 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,6 @@ public class CryptoAssetProperties implements Serializable {
@Pattern(regexp = "^([0-2])((\\.0)|(\\.[1-9][0-9]*))*$", message = "The OID must be a valid")
private String oid;

public long getId() {
return id;
}

public AssetType getAssetType() {
return assetType;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@

import alpine.persistence.PaginatedResult;
import alpine.resources.AlpineRequest;
import jakarta.validation.constraints.NotNull;

public class CryptoAssetQueryManager extends QueryManager implements IQueryManager {

Expand All @@ -54,18 +55,13 @@ public class CryptoAssetQueryManager extends QueryManager implements IQueryManag
super(pm, request);
}

private static final String globalFilter = setGlobalFilter();
private static String setGlobalFilter() {
return "bomReference == null";
}

/**
* Returns a complete list of all CryptoAssets
* @return a List of CryptoAssets
*/
@SuppressWarnings("unchecked")
public List<Component> getAllCryptoAssets() {
final Query<Component> query = pm.newQuery(Component.class, globalFilter + " && (classifier == :asset)");
final Query<Component> query = pm.newQuery(Component.class, "(classifier == :asset)");
query.getFetchPlan().setMaxFetchDepth(3);
return (List<Component>) query.execute(Classifier.CRYPTOGRAPHIC_ASSET);
}
Expand All @@ -78,7 +74,7 @@ public List<Component> getAllCryptoAssets() {
*/
@SuppressWarnings("unchecked")
public List<Component> getAllCryptoAssets(Project project) {
final Query<Component> query = pm.newQuery(Component.class, globalFilter + " && (project == :project) && (classifier == :asset)");
final Query<Component> query = pm.newQuery(Component.class, "(project == :project) && (classifier == :asset)");
query.getFetchPlan().setMaxFetchDepth(3);
query.setOrdering("name asc");
return (List<Component>)query.execute(project, Classifier.CRYPTOGRAPHIC_ASSET);
Expand All @@ -89,17 +85,14 @@ public List<Component> getAllCryptoAssets(Project project) {
* @param identity the asset identity to query against
* @return a list of components
*/
public PaginatedResult getCryptoAssets(ComponentIdentity identity) {
if (identity == null) {
return null;
}
public PaginatedResult getCryptoAssets(@NotNull ComponentIdentity identity) {
Pair<ArrayList<String>, HashMap<String, Object>> queryProp = buildIdentityQuery(identity);
String filter = String.join(" && ", queryProp.getKey());
return loadComponents(filter, queryProp.getValue());
}

private PaginatedResult loadComponents(String queryFilter, Map<String, Object> params) {
var query = pm.newQuery(Component.class, globalFilter);
var query = pm.newQuery(Component.class);
query.getFetchPlan().setMaxFetchDepth(3);
if (orderBy == null) {
query.setOrdering("id asc");
Expand All @@ -108,11 +101,7 @@ private PaginatedResult loadComponents(String queryFilter, Map<String, Object> p
return execute(query, params);
}

private Pair<ArrayList<String>, HashMap<String, Object>> buildIdentityQuery(ComponentIdentity identity) {
if (identity == null) {
return null;
}

private Pair<ArrayList<String>, HashMap<String, Object>> buildIdentityQuery(@NotNull ComponentIdentity identity) {
final var queryFilterElements = new ArrayList<String>();
final var queryParams = new HashMap<String, Object>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
import alpine.server.resources.AlpineResource;
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 io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
Expand Down Expand Up @@ -67,6 +69,10 @@

@Path("/v1/crypto")
@Tag(name = "crypto")
@SecurityRequirements({
@SecurityRequirement(name = "ApiKeyAuth"),
@SecurityRequirement(name = "BearerAuth")
})
public class CryptoAssetsResource extends AlpineResource {

@GET
Expand All @@ -85,7 +91,7 @@ public class CryptoAssetsResource extends AlpineResource {
),
@ApiResponse(responseCode = "401", description = "Unauthorized"),
@ApiResponse(responseCode = "403", description = "Access to the specified crypto asset is forbidden"),
@ApiResponse(responseCode = "404", description = "The rypto asset could not be found")
@ApiResponse(responseCode = "404", description = "The crypto asset could not be found.")
})
public Response getAllCryptoAssetsOfAProject(@PathParam("uuid") String uuid) {
try (QueryManager qm = new QueryManager(getAlpineRequest())) {
Expand Down Expand Up @@ -118,7 +124,6 @@ public Response getAllCryptoAssetsOfAProject(@PathParam("uuid") String uuid) {
@ApiResponse(
responseCode = "200",
description = "A crypto asset",
headers = @Header(name = TOTAL_COUNT_HEADER, description = "The total number of crypto assets", schema = @Schema(format = "integer")),
content = @Content(schema = @Schema(implementation = Component.class))
),
@ApiResponse(responseCode = "401", description = "Unauthorized"),
Expand All @@ -134,13 +139,14 @@ public Response getCryptoAssetByUuid(
if (component != null && component.getClassifier() == Classifier.CRYPTOGRAPHIC_ASSET) {
final Project project = component.getProject();
if (qm.hasAccess(super.getPrincipal(), project)) {
qm.getPersistenceManager().getFetchPlan().setMaxFetchDepth(3);
final Component asset = qm.detach(Component.class, component.getId()); // TODO: Force project to be loaded. It should be anyway, but JDO seems to be having issues here.
return Response.ok(asset).build();
} else {
return Response.status(Response.Status.FORBIDDEN).entity("Access to the specified crypto asset is forbidden").build();
}
} else {
return Response.status(Response.Status.NOT_FOUND).entity("The crypto asset could not be found").build();
return Response.status(Response.Status.NOT_FOUND).entity("The crypto asset could not be found.").build();
}
}
}
Expand Down Expand Up @@ -289,6 +295,7 @@ public Response createComponent(@PathParam("uuid") String uuid, Component jsonCo
description = "The updated component",
content = @Content(schema = @Schema(implementation = Component.class))
),
@ApiResponse(responseCode = "400", description = "No data for crypto asset properties provided"),
@ApiResponse(responseCode = "401", description = "Unauthorized"),
@ApiResponse(responseCode = "403", description = "Access to the specified component is forbidden"),
@ApiResponse(responseCode = "404", description = "The UUID of the component could not be found"),
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 @@ -52,6 +52,7 @@ public abstract class ResourceTest {
protected final String V1_BOM = "/v1/bom";
protected final String V1_CALCULATOR = "/v1/calculator";
protected final String V1_COMPONENT = "/v1/component";
protected final String V1_CRYPTO = "/v1/crypto";
protected final String V1_DEPENDENCY_GRAPH = "/v1/dependencyGraph";
protected final String V1_CONFIG_PROPERTY = "/v1/configProperty";
protected final String V1_CWE = "/v1/cwe";
Expand Down
51 changes: 51 additions & 0 deletions src/test/java/org/dependencytrack/model/CipherSuiteTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/*
* 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.model;

import java.util.List;

import org.junit.Assert;
import org.junit.Test;


public class CipherSuiteTest {

@Test
public void testCipherSuite() {
CipherSuite cs = new CipherSuite();
String name = "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384";
List<String> algorithms = List.of(
"crypto/algorithm/[email protected]",
"crypto/algorithm/[email protected]",
"crypto/algorithm/[email protected]",
"crypto/algorithm/[email protected]"
);
List<String> identifiers = List.of("a", "b", "c", "d");
String location = "httpclient/src/main/java/org/apache/http/impl/auth/NTLMEngineImpl.java";

Check warning on line 40 in src/test/java/org/dependencytrack/model/CipherSuiteTest.java

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

src/test/java/org/dependencytrack/model/CipherSuiteTest.java#L40

Avoid unused local variables such as 'location'.
String addittionalContext = "javax.crypto.spec.SecretKeySpec#<init>([BLjava/lang/String;)V";

Check warning on line 41 in src/test/java/org/dependencytrack/model/CipherSuiteTest.java

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

src/test/java/org/dependencytrack/model/CipherSuiteTest.java#L41

Avoid unused local variables such as 'addittionalContext'.
String bomRef = "471d7b60-0e38-4373-9e66-799d9fbea5de";

Check warning on line 42 in src/test/java/org/dependencytrack/model/CipherSuiteTest.java

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

src/test/java/org/dependencytrack/model/CipherSuiteTest.java#L42

Avoid unused local variables such as 'bomRef'.
cs.setAlgorithms(algorithms);
cs.setName(name);
cs.setIdentifiers(identifiers);

Assert.assertEquals(algorithms, cs.getAlgorithms());
Assert.assertEquals(name, cs.getName());
Assert.assertEquals(identifiers, cs.getIdentifiers());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,11 @@ public class CryptoAlgorithmPropertiesTest {

@Test
public void testCryptoAlgorithmProperties() {
String curve = "Curve25519";
CryptoAlgorithmProperties cap = new CryptoAlgorithmProperties();
cap.setPrimitive(Primitive.AE);
cap.setParameterSetIdentifier("128");
cap.setCurve(curve);
cap.setExecutionEnvironment(ExecutionEnvironment.SOFTWARE_PLAIN_RAM);
cap.setImplementationPlatform(ImplementationPlatform.X86_64);
cap.setCertificationLevel(CertificationLevel.NONE);
Expand All @@ -50,6 +52,7 @@ public void testCryptoAlgorithmProperties() {

Assert.assertEquals(Primitive.AE, cap.getPrimitive());
Assert.assertEquals("128", cap.getParameterSetIdentifier());
Assert.assertEquals(curve, cap.getCurve());
Assert.assertEquals(ExecutionEnvironment.SOFTWARE_PLAIN_RAM, cap.getExecutionEnvironment());
Assert.assertEquals(ImplementationPlatform.X86_64, cap.getImplementationPlatform());
Assert.assertEquals(CertificationLevel.NONE, cap.getCertificationLevel());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ public void testCryptoRelatedMaterialProperties() {
rel.setSecuredByMechanism(Mechanism.SOFTWARE);

Assert.assertEquals(RelatedCryptoMaterialType.DIGEST, rel.getType());
Assert.assertEquals(identifier, rel.getIdentifier());
Assert.assertEquals(State.ACTIVE, rel.getState());
Assert.assertEquals(algorithmRef, rel.getAlgorithmRef());
Assert.assertEquals(DateUtil.fromISO8601(creationDate), rel.getCreationDate());
Assert.assertEquals(DateUtil.fromISO8601(activationDate), rel.getActivationDate());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public void testOccurrence() {
Assert.assertEquals((Integer)42, o.getOffset());
Assert.assertEquals(location, o.getLocation());
Assert.assertEquals(addittionalContext, o.getAdditionalContext());
Assert.assertEquals((Integer)0, o.getSymbol());
Assert.assertEquals(bomRef, o.getBomRef());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/*
* 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.persistence;

import org.cyclonedx.model.component.crypto.enums.AssetType;
import org.cyclonedx.model.component.crypto.enums.Primitive;
import org.dependencytrack.PersistenceCapableTest;
import org.dependencytrack.model.Classifier;
import org.dependencytrack.model.Component;
import org.dependencytrack.model.ComponentIdentity;
import org.dependencytrack.model.CryptoAlgorithmProperties;
import org.dependencytrack.model.CryptoAssetProperties;
import org.dependencytrack.model.Project;

import org.junit.Test;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

public class CryptoAssetQueryManagerTest extends PersistenceCapableTest {

private Component persistCryptoAsset() {
final var project = new Project();
project.setName("acme-app");
project.setVersion("1.0.0");
qm.persist(project);

final var component = new Component();
component.setProject(project);
component.setName("acme-crypto");
component.setVersion("1.0.0");
component.setClassifier(Classifier.CRYPTOGRAPHIC_ASSET);
component.setBomRef("x");

CryptoAlgorithmProperties cap = new CryptoAlgorithmProperties();
cap.setPrimitive(Primitive.AE);
cap.setParameterSetIdentifier("128");

CryptoAssetProperties cp = new CryptoAssetProperties();
cp.setAssetType(AssetType.ALGORITHM);
cp.setAlgorithmProperties(cap);

component.setCryptoAssetProperties(cp);
return qm.persist(component);
}

@Test
public void TestGetAllCryptoAssets() {

Check notice on line 65 in src/test/java/org/dependencytrack/persistence/CryptoAssetQueryManagerTest.java

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

src/test/java/org/dependencytrack/persistence/CryptoAssetQueryManagerTest.java#L65

The JUnit 4 test method name 'TestGetAllCryptoAssets' doesn't match '[a-z][a-zA-Z0-9]*'
Component component = persistCryptoAsset();
List<Component> components = qm.getAllCryptoAssets();
assertThat(components).isNotNull();
assertThat(components).hasSize(1);
assertThat(components).satisfiesExactlyInAnyOrder(c -> {
assertThat(c.getClassifier()).isEqualTo(component.getClassifier());
assertThat(c.getCryptoAssetProperties()).isEqualTo(component.getCryptoAssetProperties());
});
}

@Test
public void TestGetAllCryptoAssetsPerProject() {

Check notice on line 77 in src/test/java/org/dependencytrack/persistence/CryptoAssetQueryManagerTest.java

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

src/test/java/org/dependencytrack/persistence/CryptoAssetQueryManagerTest.java#L77

The JUnit 4 test method name 'TestGetAllCryptoAssetsPerProject' doesn't match '[a-z][a-zA-Z0-9]*'
Component component = persistCryptoAsset();
List<Component> components = qm.getAllCryptoAssets(component.getProject());
assertThat(components).isNotNull();
assertThat(components).hasSize(1);
assertThat(components).satisfiesExactlyInAnyOrder(c -> {
assertThat(c.getClassifier()).isEqualTo(component.getClassifier());
assertThat(c.getCryptoAssetProperties()).isEqualTo(component.getCryptoAssetProperties());
});
}

@Test
public void TestGetAllCryptoAssetByIdentity() {

Check notice on line 89 in src/test/java/org/dependencytrack/persistence/CryptoAssetQueryManagerTest.java

View check run for this annotation

Codacy Production / Codacy Static Code Analysis

src/test/java/org/dependencytrack/persistence/CryptoAssetQueryManagerTest.java#L89

The JUnit 4 test method name 'TestGetAllCryptoAssetByIdentity' doesn't match '[a-z][a-zA-Z0-9]*'
Component component = persistCryptoAsset();
List<Component> components = qm.getCryptoAssets(new ComponentIdentity(AssetType.ALGORITHM)).getList(Component.class);
assertThat(components).isNotNull();
assertThat(components).hasSize(1);
assertThat(components).satisfiesExactlyInAnyOrder(c -> {
assertThat(c.getClassifier()).isEqualTo(component.getClassifier());
assertThat(c.getCryptoAssetProperties()).isEqualTo(component.getCryptoAssetProperties());
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ private Project prepareProject() throws MalformedPackageURLException {
}

@Test
public void getComponentByUuidTest() {
public void getCryptoAssetByUuidTest() {
Project project = qm.createProject("Acme Application", null, null, null, null, null, true, false);
Component component = new Component();
component.setProject(project);
Expand All @@ -148,7 +148,7 @@ public void getComponentByUuidTest() {
}

@Test
public void getComponentByInvalidUuidTest() {
public void getCryptoAssetByInvalidUuidTest() {
Response response = jersey.target(V1_COMPONENT + "/" + UUID.randomUUID())
.request().header(X_API_KEY, apiKey).get(Response.class);
Assert.assertEquals(404, response.getStatus(), 0);
Expand Down Expand Up @@ -387,7 +387,7 @@ public void getComponentByIdentityWithCoordinatesTest() {
componentA.setPurl("pkg:maven/groupB/nameB@versionB?baz=qux");
componentB = qm.createComponent(componentB, false);

final Response response = jersey.target(V1_COMPONENT + "/identity")
final Response response = jersey.target(V1_COMPONENT + "/identity").property(FILTER, projectB)
.queryParam("group", "groupB")
.queryParam("name", "nameB")
.queryParam("version", "versionB")
Expand Down
Loading

0 comments on commit 0a578df

Please sign in to comment.