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

Add vers range validation before compilation #455

Merged
merged 4 commits into from
Nov 27, 2023
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 @@ -118,7 +118,14 @@ public CelPolicyScript compile(final String scriptSrc, final CacheMode cacheMode

final Ast ast = astIssuesTuple.getAst();
final Program program = environment.program(ast);
final MultiValuedMap<Type, String> requirements = analyzeRequirements(CEL.astToCheckedExpr(ast));
final var expr = CEL.astToCheckedExpr(ast);
final MultiValuedMap<Type, String> requirements = analyzeRequirements(expr);

// perform vers range validity
if (requirements.get(TYPE_PROJECT).contains("version") || requirements.get(TYPE_COMPONENT).contains("version")) {
final var visitor = new CelPolicyScriptVisitor(expr.getTypeMapMap());
visitor.visitVersRangeCheck(expr.getExpr());
sahibamittal marked this conversation as resolved.
Show resolved Hide resolved
}

script = new CelPolicyScript(program, requirements);
if (cacheMode == CacheMode.CACHE) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,27 @@
import alpine.common.logging.Logger;
import com.google.api.expr.v1alpha1.Expr;
import com.google.api.expr.v1alpha1.Type;
import io.github.nscuro.versatile.Vers;
import io.github.nscuro.versatile.VersException;
import org.apache.commons.collections4.MultiValuedMap;
import org.apache.commons.collections4.multimap.HashSetValuedHashMap;
import org.projectnessie.cel.common.CELError;
import org.projectnessie.cel.common.Errors;
import org.projectnessie.cel.common.Location;
import org.projectnessie.cel.tools.ScriptCreateException;

import java.util.ArrayDeque;
import java.util.Collections;
import java.util.Deque;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.google.api.expr.v1alpha1.Expr.ExprKindCase.CONST_EXPR;
import static org.projectnessie.cel.Issues.newIssues;
import static org.projectnessie.cel.common.Source.newTextSource;

class CelPolicyScriptVisitor {

private static final Logger LOGGER = Logger.getLogger(CelPolicyScriptVisitor.class);
Expand Down Expand Up @@ -106,6 +117,38 @@ private void visitStruct(final Expr expr) {
logExpr(expr);
}

public void visitVersRangeCheck(final Expr expr) throws ScriptCreateException {
for (Expr argExpr : expr.getCallExpr().getArgsList()) {
if (argExpr.hasCallExpr()) {
validateVersRange(argExpr.getCallExpr());
visitVersRangeCheck(argExpr);
}
if (argExpr.hasComprehensionExpr()) {
var argCallExpr = argExpr.getComprehensionExpr();
if (argCallExpr.hasLoopStep()) {
validateVersRange(argCallExpr.getLoopStep().getCallExpr());
visitVersRangeCheck(argCallExpr.getLoopStep());
}
}
}
}

private static void validateVersRange(Expr.Call callExpr) throws ScriptCreateException {
if (callExpr.getFunction().equals("matches_range") && !callExpr.getArgsList().isEmpty()
&& callExpr.getArgsList().get(0).getExprKindCase() == CONST_EXPR) {
var versArg = callExpr.getArgsList().get(0).getConstExpr().getStringValue();
try {
Vers.parse(versArg).validate();
} catch (VersException e) {
throw new ScriptCreateException("Failed to parse the vers range ", newIssues(new Errors(newTextSource(versArg))
.append(Collections.singletonList(
new CELError(e, Location.newLocation(1, 1), e.getMessage())
))
));
}
}
}

private void logExpr(final Expr expr) {
LOGGER.debug("Visiting %s (id=%d, fieldStack=%s, fieldTypeStack=%s, functionStack=%s)"
.formatted(expr.getExprKindCase(), expr.getId(), selectFieldStack, selectOperandTypeStack, callFunctionStack));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import org.apache.commons.codec.digest.DigestUtils;
import org.dependencytrack.policy.cel.CelPolicyScriptHost.CacheMode;
import org.junit.Test;
import org.projectnessie.cel.tools.ScriptCreateException;

import java.util.Collection;
import java.util.Map;
Expand All @@ -16,6 +17,8 @@
import static org.dependencytrack.policy.cel.CelPolicyLibrary.TYPE_LICENSE_GROUP;
import static org.dependencytrack.policy.cel.CelPolicyLibrary.TYPE_PROJECT;
import static org.dependencytrack.policy.cel.CelPolicyLibrary.TYPE_VULNERABILITY;
import static org.junit.Assert.assertThrows;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;

public class CelPolicyScriptHostTest {

Expand Down Expand Up @@ -81,4 +84,24 @@ public void testRequirementsAnalysis() throws Exception {
"severity");
}

@Test
public void testVisitVersRangeCheck() {
var exception = assertThrows(ScriptCreateException.class, () -> CelPolicyScriptHost.getInstance().compile("""
project.name == "foo" && project.matches_range("vers:generic<1")
""", CacheMode.NO_CACHE));
assertThat(exception.getMessage()).contains("Failed to parse the vers range");

assertThrows(ScriptCreateException.class, () -> CelPolicyScriptHost.getInstance().compile("""
component.matches_range("vers:generic<1") == "foo" && project.matches_range("vers:generic<1")
""", CacheMode.NO_CACHE));

exception = assertThrows(ScriptCreateException.class, () -> CelPolicyScriptHost.getInstance().compile("""
component.name == "foo" || vulns.exists(vuln, vuln.id == "foo" && component.matches_range("versgeneric/<1"))
""", CacheMode.NO_CACHE));
assertThat(exception.getMessage()).contains("vers string does not contain a URI scheme separator");

assertDoesNotThrow(() -> CelPolicyScriptHost.getInstance().compile("""
project.matches_range("vers:generic/<1")
""", CacheMode.NO_CACHE));
}
}