Elffuss BraidHub

kikocis/EDC public

feat: adds policy validation in policy engine (#4428)

* feat: adds policy validation in policy engine

* chore: dependencies file

* pr suggestions
Changesetc2e44508a8623a36aca9da54bcc79418295175f8916a100b75a9a5d3ce2e1cb4
AuthorEnrico Risa <enrico.risa@gmail.com> · 2024-08-23 14:42 +02:00
CommitterGitHub <noreply@github.com> · 2024-08-23 14:42 +02:00
Parentsdbccef21426b

Browse the files at this changeset

13 files changed

modified core/common/connector-core/src/main/java/org/eclipse/edc/connector/core/CoreServicesExtension.java +3 −4
@@ -31,6 +31,7 @@
3131 import org.eclipse.edc.policy.engine.ScopeFilter;
3232 import org.eclipse.edc.policy.engine.spi.PolicyEngine;
3333 import org.eclipse.edc.policy.engine.spi.RuleBindingRegistry;
34+import org.eclipse.edc.policy.engine.validation.RuleValidator;
3435 import org.eclipse.edc.policy.model.PolicyRegistrationTypes;
3536 import org.eclipse.edc.query.CriterionOperatorRegistryImpl;
3637 import org.eclipse.edc.runtime.metamodel.annotation.BaseExtension;
@@ -59,14 +60,11 @@
5960 public class CoreServicesExtension implements ServiceExtension {
6061
6162 public static final String NAME = "Core Services";
62-
6363 private static final String DEFAULT_EDC_HOSTNAME = "localhost";
64-
6564 @Setting(value = "Connector hostname, which e.g. is used in referer urls", defaultValue = DEFAULT_EDC_HOSTNAME)
6665 public static final String EDC_HOSTNAME = "edc.hostname";
6766 @Setting(value = "The name of the claim key used to determine the participant identity", defaultValue = DEFAULT_IDENTITY_CLAIM_KEY)
6867 public static final String EDC_AGENT_IDENTITY_KEY = "edc.agent.identity.key";
69-
7068 @Inject
7169 private EventExecutorServiceContainer eventExecutorServiceContainer;
7270
@@ -142,7 +140,8 @@
142140 @Provider
143141 public PolicyEngine policyEngine() {
144142 var scopeFilter = new ScopeFilter(ruleBindingRegistry);
145- return new PolicyEngineImpl(scopeFilter);
143+ var ruleValidator = new RuleValidator(ruleBindingRegistry);
144+ return new PolicyEngineImpl(scopeFilter, ruleValidator);
146145 }
147146
148147 @Provider
modified core/common/lib/policy-engine-lib/src/main/java/org/eclipse/edc/policy/engine/PolicyEngineImpl.java +20 −1
@@ -19,6 +19,8 @@
1919 import org.eclipse.edc.policy.engine.spi.PolicyContext;
2020 import org.eclipse.edc.policy.engine.spi.PolicyEngine;
2121 import org.eclipse.edc.policy.engine.spi.RuleFunction;
22+import org.eclipse.edc.policy.engine.validation.PolicyValidator;
23+import org.eclipse.edc.policy.engine.validation.RuleValidator;
2224 import org.eclipse.edc.policy.evaluator.PolicyEvaluator;
2325 import org.eclipse.edc.policy.evaluator.RuleProblem;
2426 import org.eclipse.edc.policy.model.Duty;
@@ -30,6 +32,7 @@
3032 import org.jetbrains.annotations.NotNull;
3133
3234 import java.util.ArrayList;
35+import java.util.Collection;
3336 import java.util.HashMap;
3437 import java.util.List;
3538 import java.util.Map;
@@ -55,9 +58,11 @@
5558 private final Map<String, List<BiFunction<Policy, PolicyContext, Boolean>>> preValidators = new HashMap<>();
5659 private final Map<String, List<BiFunction<Policy, PolicyContext, Boolean>>> postValidators = new HashMap<>();
5760 private final ScopeFilter scopeFilter;
61+ private final RuleValidator ruleValidator;
5862
59- public PolicyEngineImpl(ScopeFilter scopeFilter) {
63+ public PolicyEngineImpl(ScopeFilter scopeFilter, RuleValidator ruleValidator) {
6064 this.scopeFilter = scopeFilter;
65+ this.ruleValidator = ruleValidator;
6166 }
6267
6368 @Override
@@ -129,6 +134,20 @@
129134 }
130135 }
131136
137+ @Override
138+ public Result<Void> validate(Policy policy) {
139+ var validatorBuilder = PolicyValidator.Builder.newInstance()
140+ .ruleValidator(ruleValidator);
141+
142+ constraintFunctions.values().stream()
143+ .flatMap(Collection::stream)
144+ .forEach(entry -> validatorBuilder.evaluationFunction(entry.key, entry.type, entry.function));
145+
146+ dynamicConstraintFunctions.forEach(entry -> validatorBuilder.dynamicEvaluationFunction(entry.type, entry.function));
147+
148+ return validatorBuilder.build().validate(policy);
149+ }
150+
132151 @Override
133152 @SuppressWarnings({ "unchecked", "rawtypes" })
134153 public <R extends Rule> void registerFunction(String scope, Class<R> type, String key, AtomicConstraintFunction<R> function) {
modified core/common/lib/policy-engine-lib/src/main/java/org/eclipse/edc/policy/engine/RuleBindingRegistryImpl.java +11 −6
@@ -44,12 +44,7 @@
4444
4545 @Override
4646 public boolean isInScope(String ruleType, String scope) {
47- var boundScopes = ruleBindings.get(ruleType);
48- if (boundScopes == null) {
49- boundScopes = dynamicBinders.stream()
50- .flatMap(binder -> binder.apply(ruleType).stream())
51- .collect(Collectors.toSet());
52- }
47+ var boundScopes = bindings(ruleType);
5348 if (boundScopes.contains(DELIMITED_ALL)) {
5449 return true;
5550 }
@@ -62,4 +57,14 @@
6257 return false;
6358 }
6459
60+ @Override
61+ public Set<String> bindings(String ruleType) {
62+ var boundScopes = ruleBindings.get(ruleType);
63+ if (boundScopes == null) {
64+ boundScopes = dynamicBinders.stream()
65+ .flatMap(binder -> binder.apply(ruleType).stream())
66+ .collect(Collectors.toSet());
67+ }
68+ return boundScopes;
69+ }
6570 }
added core/common/lib/policy-engine-lib/src/main/java/org/eclipse/edc/policy/engine/validation/PolicyValidator.java +255 −0
@@ -0,0 +1,255 @@
1+/*
2+ * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
3+ *
4+ * This program and the accompanying materials are made available under the
5+ * terms of the Apache License, Version 2.0 which is available at
6+ * https://www.apache.org/licenses/LICENSE-2.0
7+ *
8+ * SPDX-License-Identifier: Apache-2.0
9+ *
10+ * Contributors:
11+ * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation
12+ *
13+ */
14+
15+package org.eclipse.edc.policy.engine.validation;
16+
17+import org.eclipse.edc.policy.engine.spi.AtomicConstraintFunction;
18+import org.eclipse.edc.policy.engine.spi.DynamicAtomicConstraintFunction;
19+import org.eclipse.edc.policy.engine.spi.PolicyContext;
20+import org.eclipse.edc.policy.model.AndConstraint;
21+import org.eclipse.edc.policy.model.AtomicConstraint;
22+import org.eclipse.edc.policy.model.Constraint;
23+import org.eclipse.edc.policy.model.Duty;
24+import org.eclipse.edc.policy.model.LiteralExpression;
25+import org.eclipse.edc.policy.model.MultiplicityConstraint;
26+import org.eclipse.edc.policy.model.Operator;
27+import org.eclipse.edc.policy.model.OrConstraint;
28+import org.eclipse.edc.policy.model.Permission;
29+import org.eclipse.edc.policy.model.Policy;
30+import org.eclipse.edc.policy.model.Prohibition;
31+import org.eclipse.edc.policy.model.Rule;
32+import org.eclipse.edc.policy.model.XoneConstraint;
33+import org.eclipse.edc.spi.result.Result;
34+
35+import java.util.ArrayList;
36+import java.util.Collection;
37+import java.util.List;
38+import java.util.Map;
39+import java.util.Objects;
40+import java.util.Stack;
41+import java.util.TreeMap;
42+import java.util.stream.Collectors;
43+import java.util.stream.Stream;
44+
45+/**
46+ * Validate a policy.
47+ * <p>
48+ * The policy validator is used to validate policies against a set of configured rule bindings, {@link AtomicConstraintFunction} and {@link DynamicAtomicConstraintFunction}
49+ * <p>
50+ * The validation will fail under the following conditions:
51+ *
52+ * <ul>
53+ * <li>If a rule action is not bound to a scope.</li>
54+ * <li>If an {@link AtomicConstraint}'s left-operand is not bound to a scope.
55+ * <li>If an {@link AtomicConstraint}'s left-operand is not bound to a function.
56+ * </ul>
57+ */
58+public class PolicyValidator implements Policy.Visitor<Result<Void>>, Rule.Visitor<Result<Void>>, Constraint.Visitor<Result<Void>> {
59+
60+ private final Stack<Rule> ruleContext = new Stack<>();
61+
62+ private final Map<String, List<ConstraintFunctionEntry<Rule>>> constraintFunctions = new TreeMap<>();
63+ private final List<DynamicAtomicConstraintFunctionEntry<Rule>> dynamicConstraintFunctions = new ArrayList<>();
64+ private RuleValidator ruleValidator;
65+
66+ public Result<Void> validate(Policy policy) {
67+ return policy.accept(this);
68+ }
69+
70+ @Override
71+ public Result<Void> visitAndConstraint(AndConstraint constraint) {
72+ return validateMultiplicityConstraint(constraint);
73+ }
74+
75+ @Override
76+ public Result<Void> visitOrConstraint(OrConstraint constraint) {
77+ return validateMultiplicityConstraint(constraint);
78+ }
79+
80+ @Override
81+ public Result<Void> visitXoneConstraint(XoneConstraint constraint) {
82+ return validateMultiplicityConstraint(constraint);
83+ }
84+
85+ @Override
86+ public Result<Void> visitAtomicConstraint(AtomicConstraint constraint) {
87+ var currentRule = currentRule();
88+ var leftValue = constraint.getLeftExpression().accept(s -> s.getValue().toString());
89+ var rightValue = constraint.getRightExpression().accept(LiteralExpression::getValue);
90+
91+ return validateLeftExpression(currentRule, leftValue)
92+ .merge(validateConstraint(leftValue, constraint.getOperator(), rightValue, currentRule));
93+ }
94+
95+ @Override
96+ public Result<Void> visitPolicy(Policy policy) {
97+ return Stream.of(policy.getPermissions(), policy.getProhibitions(), policy.getObligations())
98+ .flatMap(Collection::stream)
99+ .map(rule -> rule.accept(this))
100+ .reduce(Result.success(), Result::merge);
101+ }
102+
103+ @Override
104+ public Result<Void> visitPermission(Permission policy) {
105+ var result = policy.getDuties().stream()
106+ .map(duty -> duty.accept(this))
107+ .reduce(Result.success(), Result::merge);
108+ return result.merge(validateRule(policy));
109+ }
110+
111+ @Override
112+ public Result<Void> visitProhibition(Prohibition prohibition) {
113+ return validateRule(prohibition);
114+ }
115+
116+ @Override
117+ public Result<Void> visitDuty(Duty duty) {
118+ return validateRule(duty);
119+ }
120+
121+ private Result<Void> validateMultiplicityConstraint(MultiplicityConstraint multiplicityConstraint) {
122+ return multiplicityConstraint.getConstraints().stream()
123+ .map(c -> c.accept(this))
124+ .reduce(Result.success(), Result::merge);
125+ }
126+
127+ private Result<Void> validateLeftExpression(Rule rule, String leftOperand) {
128+ if (!ruleValidator.isBounded(leftOperand)) {
129+ return Result.failure("leftOperand '%s' is not bound to any scopes: Rule { %s } ".formatted(leftOperand, rule));
130+ } else {
131+ return Result.success();
132+ }
133+ }
134+
135+ private Result<Void> validateConstraint(String leftOperand, Operator operator, Object rightOperand, Rule rule) {
136+ var functions = getFunctions(leftOperand, rule.getClass());
137+ if (functions.isEmpty()) {
138+ return Result.failure("left operand '%s' is not bound to any functions: Rule { %s }".formatted(leftOperand, rule));
139+ } else {
140+ return functions.stream()
141+ .map(f -> f.validate(operator, rightOperand, rule))
142+ .reduce(Result.success(), Result::merge);
143+ }
144+ }
145+
146+ private Result<Void> validateRule(Rule rule) {
147+ var initialResult = validateAction(rule);
148+ try {
149+ ruleContext.push(rule);
150+ return rule.getConstraints().stream()
151+ .map(constraint -> constraint.accept(this))
152+ .reduce(initialResult, Result::merge);
153+
154+ } finally {
155+ ruleContext.pop();
156+ }
157+ }
158+
159+ private Result<Void> validateAction(Rule rule) {
160+ if (rule.getAction() != null && !ruleValidator.isBounded(rule.getAction().getType())) {
161+ return Result.failure("action '%s' is not bound to any scopes: Rule { %s }".formatted(rule.getAction().getType(), rule));
162+ } else {
163+ return Result.success();
164+ }
165+ }
166+
167+ private <R extends Rule> List<AtomicConstraintFunction<Rule>> getFunctions(String key, Class<R> ruleKind) {
168+ // first look-up for an exact match
169+ var functions = constraintFunctions.getOrDefault(key, new ArrayList<>())
170+ .stream()
171+ .filter(entry -> ruleKind.isAssignableFrom(entry.type()))
172+ .map(entry -> entry.function)
173+ .collect(Collectors.toList());
174+
175+ // if not found inspect the dynamic functions
176+ if (functions.isEmpty()) {
177+ functions = dynamicConstraintFunctions
178+ .stream()
179+ .filter(f -> f.function.canHandle(key))
180+ .map(entry -> wrapDynamicFunction(key, entry.function))
181+ .toList();
182+ }
183+
184+ return functions;
185+ }
186+
187+ private <R extends Rule> AtomicConstraintFunction<R> wrapDynamicFunction(String key, DynamicAtomicConstraintFunction<R> function) {
188+ return new AtomicConstraintFunctionWrapper<>(key, function);
189+ }
190+
191+ private Rule currentRule() {
192+ return ruleContext.peek();
193+ }
194+
195+ public static class Builder {
196+ private final PolicyValidator validator;
197+
198+ private Builder() {
199+ validator = new PolicyValidator();
200+ }
201+
202+ public static PolicyValidator.Builder newInstance() {
203+ return new PolicyValidator.Builder();
204+ }
205+
206+ public Builder ruleValidator(RuleValidator ruleValidator) {
207+ validator.ruleValidator = ruleValidator;
208+ return this;
209+ }
210+
211+ @SuppressWarnings({ "unchecked", "rawtypes" })
212+ public <R extends Rule> Builder evaluationFunction(String key, Class<R> ruleKind, AtomicConstraintFunction<R> function) {
213+ validator.constraintFunctions.computeIfAbsent(key, k -> new ArrayList<>())
214+ .add(new ConstraintFunctionEntry(ruleKind, function));
215+ return this;
216+ }
217+
218+ @SuppressWarnings({ "unchecked", "rawtypes" })
219+ public <R extends Rule> Builder dynamicEvaluationFunction(Class<R> ruleKind, DynamicAtomicConstraintFunction<R> function) {
220+ validator.dynamicConstraintFunctions.add(new DynamicAtomicConstraintFunctionEntry(ruleKind, function));
221+ return this;
222+ }
223+
224+ public PolicyValidator build() {
225+ Objects.requireNonNull(validator.ruleValidator, "Rule validator should not be null");
226+ return validator;
227+ }
228+
229+ }
230+
231+ private record ConstraintFunctionEntry<R extends Rule>(
232+ Class<R> type,
233+ AtomicConstraintFunction<R> function) {
234+ }
235+
236+ private record DynamicAtomicConstraintFunctionEntry<R extends Rule>(
237+ Class<R> type,
238+ DynamicAtomicConstraintFunction<R> function) {
239+ }
240+
241+ private record AtomicConstraintFunctionWrapper<R extends Rule>(
242+ String leftOperand,
243+ DynamicAtomicConstraintFunction<R> inner) implements AtomicConstraintFunction<R> {
244+
245+ @Override
246+ public boolean evaluate(Operator operator, Object rightValue, R rule, PolicyContext context) {
247+ throw new UnsupportedOperationException("Evaluation is not supported");
248+ }
249+
250+ @Override
251+ public Result<Void> validate(Operator operator, Object rightValue, R rule) {
252+ return inner.validate(leftOperand, operator, rightValue, rule);
253+ }
254+ }
255+}
added core/common/lib/policy-engine-lib/src/main/java/org/eclipse/edc/policy/engine/validation/RuleValidator.java +36 −0
@@ -0,0 +1,36 @@
1+/*
2+ * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
3+ *
4+ * This program and the accompanying materials are made available under the
5+ * terms of the Apache License, Version 2.0 which is available at
6+ * https://www.apache.org/licenses/LICENSE-2.0
7+ *
8+ * SPDX-License-Identifier: Apache-2.0
9+ *
10+ * Contributors:
11+ * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation
12+ *
13+ */
14+
15+package org.eclipse.edc.policy.engine.validation;
16+
17+import org.eclipse.edc.policy.engine.spi.RuleBindingRegistry;
18+
19+/**
20+ * Validates rules in a {@link RuleBindingRegistry}
21+ */
22+public class RuleValidator {
23+
24+ private final RuleBindingRegistry registry;
25+
26+ public RuleValidator(RuleBindingRegistry registry) {
27+ this.registry = registry;
28+ }
29+
30+ /**
31+ * Checks if the input ruleType is bound to any scope
32+ */
33+ boolean isBounded(String ruleType) {
34+ return !registry.bindings(ruleType).isEmpty();
35+ }
36+}
modified core/common/lib/policy-engine-lib/src/test/java/org/eclipse/edc/policy/engine/PolicyEngineImplScenariosTest.java +3 −2
@@ -16,6 +16,7 @@
1616
1717 import org.eclipse.edc.policy.engine.spi.PolicyContextImpl;
1818 import org.eclipse.edc.policy.engine.spi.RuleBindingRegistry;
19+import org.eclipse.edc.policy.engine.validation.RuleValidator;
1920 import org.eclipse.edc.policy.model.Action;
2021 import org.eclipse.edc.policy.model.AtomicConstraint;
2122 import org.eclipse.edc.policy.model.LiteralExpression;
@@ -49,7 +50,7 @@
4950
5051 @BeforeEach
5152 void setUp() {
52- policyEngine = new PolicyEngineImpl(new ScopeFilter(bindingRegistry));
53+ policyEngine = new PolicyEngineImpl(new ScopeFilter(bindingRegistry), new RuleValidator(bindingRegistry));
5354 }
5455
5556 /**
@@ -141,5 +142,5 @@
141142
142143 assertThat(result.succeeded()).isTrue();
143144 }
144-
145+
145146 }
modified core/common/lib/policy-engine-lib/src/test/java/org/eclipse/edc/policy/engine/PolicyEngineImplTest.java +2 −1
@@ -18,6 +18,7 @@
1818 import org.eclipse.edc.policy.engine.spi.PolicyContextImpl;
1919 import org.eclipse.edc.policy.engine.spi.PolicyEngine;
2020 import org.eclipse.edc.policy.engine.spi.RuleBindingRegistry;
21+import org.eclipse.edc.policy.engine.validation.RuleValidator;
2122 import org.eclipse.edc.policy.model.Action;
2223 import org.eclipse.edc.policy.model.AtomicConstraint;
2324 import org.eclipse.edc.policy.model.Duty;
@@ -60,7 +61,7 @@
6061
6162 @BeforeEach
6263 void setUp() {
63- policyEngine = new PolicyEngineImpl(new ScopeFilter(bindingRegistry));
64+ policyEngine = new PolicyEngineImpl(new ScopeFilter(bindingRegistry), new RuleValidator(bindingRegistry));
6465 }
6566
6667 @Test
added core/common/lib/policy-engine-lib/src/test/java/org/eclipse/edc/policy/engine/PolicyEngineImplValidationTest.java +291 −0
@@ -0,0 +1,291 @@
1+/*
2+ * Copyright (c) 2024 Bayerische Motoren Werke Aktiengesellschaft (BMW AG)
3+ *
4+ * This program and the accompanying materials are made available under the
5+ * terms of the Apache License, Version 2.0 which is available at
6+ * https://www.apache.org/licenses/LICENSE-2.0
7+ *
8+ * SPDX-License-Identifier: Apache-2.0
9+ *
10+ * Contributors:
11+ * Bayerische Motoren Werke Aktiengesellschaft (BMW AG) - initial API and implementation
12+ *
13+ */
14+
15+package org.eclipse.edc.policy.engine;
16+
17+import org.eclipse.edc.policy.engine.spi.AtomicConstraintFunction;
18+import org.eclipse.edc.policy.engine.spi.DynamicAtomicConstraintFunction;
19+import org.eclipse.edc.policy.engine.spi.PolicyEngine;
20+import org.eclipse.edc.policy.engine.spi.RuleBindingRegistry;
21+import org.eclipse.edc.policy.engine.validation.RuleValidator;
22+import org.eclipse.edc.policy.model.Action;
23+import org.eclipse.edc.policy.model.AndConstraint;
24+import org.eclipse.edc.policy.model.AtomicConstraint;
25+import org.eclipse.edc.policy.model.Duty;
26+import org.eclipse.edc.policy.model.LiteralExpression;
27+import org.eclipse.edc.policy.model.OrConstraint;
28+import org.eclipse.edc.policy.model.Permission;
29+import org.eclipse.edc.policy.model.Policy;
30+import org.eclipse.edc.policy.model.Prohibition;
31+import org.eclipse.edc.policy.model.Rule;
32+import org.eclipse.edc.policy.model.XoneConstraint;
33+import org.eclipse.edc.spi.result.Result;
34+import org.junit.jupiter.api.BeforeEach;
35+import org.junit.jupiter.api.Test;
36+import org.junit.jupiter.api.extension.ExtensionContext;
37+import org.junit.jupiter.params.ParameterizedTest;
38+import org.junit.jupiter.params.provider.Arguments;
39+import org.junit.jupiter.params.provider.ArgumentsProvider;
40+import org.junit.jupiter.params.provider.ArgumentsSource;
41+
42+import java.util.Set;
43+import java.util.stream.Stream;
44+
45+import static org.eclipse.edc.junit.assertions.AbstractResultAssert.assertThat;
46+import static org.eclipse.edc.policy.engine.spi.PolicyEngine.ALL_SCOPES;
47+import static org.eclipse.edc.policy.model.Operator.EQ;
48+import static org.junit.jupiter.params.provider.Arguments.of;
49+import static org.mockito.ArgumentMatchers.any;
50+import static org.mockito.Mockito.mock;
51+import static org.mockito.Mockito.when;
52+
53+class PolicyEngineImplValidationTest {
54+
55+ private final RuleBindingRegistry bindingRegistry = new RuleBindingRegistryImpl();
56+ private PolicyEngine policyEngine;
57+
58+
59+ @BeforeEach
60+ void setUp() {
61+ policyEngine = new PolicyEngineImpl(new ScopeFilter(bindingRegistry), new RuleValidator(bindingRegistry));
62+ }
63+
64+ @Test
65+ void validateEmptyPolicy() {
66+ var emptyPolicy = Policy.Builder.newInstance().build();
67+
68+ var result = policyEngine.validate(emptyPolicy);
69+
70+ assertThat(result).isSucceeded();
71+ }
72+
73+ @Test
74+ void validate_whenKeyNotBoundInTheRegistryAndToFunctions() {
75+
76+ var left = new LiteralExpression("foo");
77+ var right = new LiteralExpression("bar");
78+ var constraint = AtomicConstraint.Builder.newInstance().leftExpression(left).operator(EQ).rightExpression(right).build();
79+ var permission = Permission.Builder.newInstance().constraint(constraint).build();
80+ var policy = Policy.Builder.newInstance().permission(permission).build();
81+ policyEngine.registerFunction(ALL_SCOPES, Duty.class, "foo", (op, rv, r, ctx) -> true);
82+ policyEngine.registerFunction(ALL_SCOPES, Prohibition.class, "foo", (op, rv, r, ctx) -> true);
83+
84+ var result = policyEngine.validate(policy);
85+
86+ // The foo key is not bound nor to function nor in the RuleBindingRegistry
87+ assertThat(result).isFailed().messages().hasSize(2)
88+ .anyMatch(s -> s.startsWith("leftOperand 'foo' is not bound to any scopes"))
89+ .anyMatch(s -> s.startsWith("left operand 'foo' is not bound to any functions"));
90+
91+ }
92+
93+ @ParameterizedTest
94+ @ArgumentsSource(PolicyProvider.class)
95+ void validate_whenKeyIsNotBoundInTheRegistry(Policy policy, Class<Rule> ruleClass, String key) {
96+
97+ policyEngine.registerFunction(ALL_SCOPES, ruleClass, key, (op, rv, duty, ctx) -> true);
98+
99+ var result = policyEngine.validate(policy);
100+
101+ // The input key is not bound in the RuleBindingRegistry
102+ assertThat(result).isFailed().messages().hasSize(1)
103+ .anyMatch(s -> s.startsWith("leftOperand '%s' is not bound to any scopes".formatted(key)));
104+
105+ }
106+
107+ @ParameterizedTest
108+ @ArgumentsSource(PolicyProvider.class)
109+ void validate(Policy policy, Class<Rule> ruleClass, String key) {
110+
111+
112+ bindingRegistry.bind(key, ALL_SCOPES);
113+ policyEngine.registerFunction(ALL_SCOPES, ruleClass, key, (op, rv, duty, ctx) -> true);
114+
115+ var result = policyEngine.validate(policy);
116+
117+ assertThat(result).isSucceeded();
118+
119+ }
120+
121+
122+ @ParameterizedTest
123+ @ArgumentsSource(PolicyProvider.class)
124+ void validate_withDynamicFunction(Policy policy, Class<Rule> ruleClass, String key) {
125+
126+ DynamicAtomicConstraintFunction<Rule> function = mock();
127+
128+ when(function.canHandle(key)).thenReturn(true);
129+
130+ when(function.validate(any(), any(), any(), any())).thenReturn(Result.success());
131+
132+ bindingRegistry.dynamicBind(s -> Set.of(ALL_SCOPES));
133+ policyEngine.registerFunction(ALL_SCOPES, ruleClass, function);
134+
135+ var result = policyEngine.validate(policy);
136+
137+ assertThat(result).isSucceeded();
138+
139+ }
140+
141+ @ParameterizedTest
142+ @ArgumentsSource(PolicyProvider.class)
143+ void validate_shouldFail_whenSkippingDynamicFunction(Policy policy, Class<Rule> ruleClass, String key) {
144+
145+ DynamicAtomicConstraintFunction<Rule> function = mock();
146+
147+ when(function.canHandle(key)).thenReturn(false);
148+
149+ bindingRegistry.dynamicBind(s -> Set.of(ALL_SCOPES));
150+ policyEngine.registerFunction(ALL_SCOPES, ruleClass, function);
151+
152+ var result = policyEngine.validate(policy);
153+
154+ // The input key is not bound any functions , the dynamic one cannot handle the input key
155+ assertThat(result).isFailed().messages().hasSize(1)
156+ .anyMatch(s -> s.startsWith("left operand '%s' is not bound to any functions".formatted(key)));
157+
158+ }
159+
160+ @ParameterizedTest
161+ @ArgumentsSource(PolicyProvider.class)
162+ void validate_shouldFails_withDynamicFunction(Policy policy, Class<Rule> ruleClass, String key) {
163+
164+ DynamicAtomicConstraintFunction<Rule> function = mock();
165+
166+ when(function.canHandle(key)).thenReturn(true);
167+
168+ when(function.validate(any(), any(), any(), any())).thenReturn(Result.failure("Dynamic function validation failure"));
169+
170+ bindingRegistry.dynamicBind(s -> Set.of(ALL_SCOPES));
171+ policyEngine.registerFunction(ALL_SCOPES, ruleClass, function);
172+
173+ var result = policyEngine.validate(policy);
174+
175+ assertThat(result).isFailed().detail().contains("Dynamic function validation failure");
176+
177+ }
178+
179+
180+ @ParameterizedTest
181+ @ArgumentsSource(PolicyProvider.class)
182+ void validate_shouldFail_whenFunctionValidationFails(Policy policy, Class<Rule> ruleClass, String key) {
183+
184+ AtomicConstraintFunction<Rule> function = mock();
185+
186+ when(function.validate(any(), any(), any())).thenReturn(Result.failure("Function validation failure"));
187+
188+ bindingRegistry.bind(key, ALL_SCOPES);
189+ policyEngine.registerFunction(ALL_SCOPES, ruleClass, key, function);
190+
191+ var result = policyEngine.validate(policy);
192+
193+ assertThat(result).isFailed().detail().contains("Function validation failure");
194+
195+ }
196+
197+ @Test
198+ void validate_shouldFail_whenActionIsNotBound() {
199+
200+ var leftOperand = "foo";
201+ var left = new LiteralExpression(leftOperand);
202+ var right = new LiteralExpression("bar");
203+ var constraint = AtomicConstraint.Builder.newInstance().leftExpression(left).operator(EQ).rightExpression(right).build();
204+ var permission = Permission.Builder.newInstance().constraint(constraint).action(Action.Builder.newInstance().type("use").build()).build();
205+
206+ var policy = Policy.Builder.newInstance().permission(permission).build();
207+ AtomicConstraintFunction<Permission> function = mock();
208+
209+ when(function.validate(any(), any(), any())).thenReturn(Result.success());
210+
211+ bindingRegistry.bind("foo", ALL_SCOPES);
212+ policyEngine.registerFunction(ALL_SCOPES, Permission.class, "foo", function);
213+
214+ var result = policyEngine.validate(policy);
215+
216+ // The use action is not bound in the RuleBindingRegistry
217+ assertThat(result).isFailed().detail().contains("action 'use' is not bound to any scopes");
218+
219+ }
220+
221+ @ParameterizedTest
222+ @ArgumentsSource(PolicyWithMultiplicityConstraintProvider.class)
223+ void validate_withMultiplicityConstraints(Policy policy, Class<Rule> ruleClass, String[] keys) {
224+
225+
226+ for (var key : keys) {
227+ bindingRegistry.bind(key, ALL_SCOPES);
228+ policyEngine.registerFunction(ALL_SCOPES, ruleClass, key, (op, rv, duty, ctx) -> true);
229+ }
230+
231+
232+ var result = policyEngine.validate(policy);
233+
234+ assertThat(result).isSucceeded();
235+
236+ }
237+
238+ private static class PolicyProvider implements ArgumentsProvider {
239+ @Override
240+ public Stream<? extends Arguments> provideArguments(ExtensionContext context) {
241+
242+ var leftOperand = "foo";
243+ var left = new LiteralExpression(leftOperand);
244+ var right = new LiteralExpression("bar");
245+ var constraint = AtomicConstraint.Builder.newInstance().leftExpression(left).operator(EQ).rightExpression(right).build();
246+ var prohibition = Prohibition.Builder.newInstance().constraint(constraint).build();
247+ var permission = Permission.Builder.newInstance().constraint(constraint).build();
248+ var duty = Duty.Builder.newInstance().constraint(constraint).build();
249+
250+ return Stream.of(
251+ of(Policy.Builder.newInstance().permission(permission).build(), Permission.class, leftOperand),
252+ of(Policy.Builder.newInstance().duty(duty).build(), Duty.class, leftOperand),
253+ of(Policy.Builder.newInstance().prohibition(prohibition).build(), Prohibition.class, leftOperand)
254+ );
255+ }
256+ }
257+
258+ private static class PolicyWithMultiplicityConstraintProvider implements ArgumentsProvider {
259+ @Override
260+ public Stream<? extends Arguments> provideArguments(ExtensionContext context) {
261+ var keys = new String[]{ "foo", "baz" };
262+ var firstConstraint = atomicConstraint("foo", "bar");
263+ var secondConstraint = atomicConstraint("baz", "bar");
264+
265+
266+ var orConstraints = OrConstraint.Builder.newInstance().constraint(firstConstraint).constraint(secondConstraint).build();
267+ var andConstraints = AndConstraint.Builder.newInstance().constraint(firstConstraint).constraint(secondConstraint).build();
268+ var xoneConstraint = XoneConstraint.Builder.newInstance().constraint(firstConstraint).constraint(secondConstraint).build();
269+
270+ var prohibition = Prohibition.Builder.newInstance().constraint(orConstraints).build();
271+ var permission = Permission.Builder.newInstance().constraint(andConstraints).build();
272+ var duty = Duty.Builder.newInstance().constraint(xoneConstraint).build();
273+
274+ return Stream.of(
275+ of(Policy.Builder.newInstance().permission(permission).build(), Permission.class, keys),
276+ of(Policy.Builder.newInstance().duty(duty).build(), Duty.class, keys),
277+ of(Policy.Builder.newInstance().prohibition(prohibition).build(), Prohibition.class, keys)
278+ );
279+ }
280+
281+ private AtomicConstraint atomicConstraint(String key, String value) {
282+ var left = new LiteralExpression(key);
283+ var right = new LiteralExpression(value);
284+ return AtomicConstraint.Builder.newInstance()
285+ .leftExpression(left)
286+ .operator(EQ)
287+ .rightExpression(right)
288+ .build();
289+ }
290+ }
291+}
modified core/control-plane/lib/control-plane-policies-lib/src/test/java/org/eclipse/edc/connector/controlplane/policy/contract/ContractExpiryCheckFunctionEvaluationTest.java +2 −1
@@ -23,6 +23,7 @@
2323 import org.eclipse.edc.policy.engine.spi.PolicyContextImpl;
2424 import org.eclipse.edc.policy.engine.spi.PolicyEngine;
2525 import org.eclipse.edc.policy.engine.spi.RuleBindingRegistry;
26+import org.eclipse.edc.policy.engine.validation.RuleValidator;
2627 import org.eclipse.edc.policy.model.Action;
2728 import org.eclipse.edc.policy.model.AndConstraint;
2829 import org.eclipse.edc.policy.model.AtomicConstraint;
@@ -68,7 +69,7 @@
6869 // bind/register rule to evaluate contract expiry
6970 bindingRegistry.bind("use", TRANSFER_SCOPE);
7071 bindingRegistry.bind(CONTRACT_EXPIRY_EVALUATION_KEY, TRANSFER_SCOPE);
71- policyEngine = new PolicyEngineImpl(new ScopeFilter(bindingRegistry));
72+ policyEngine = new PolicyEngineImpl(new ScopeFilter(bindingRegistry), new RuleValidator(bindingRegistry));
7273 policyEngine.registerFunction(TRANSFER_SCOPE, Permission.class, CONTRACT_EXPIRY_EVALUATION_KEY, function);
7374 }
7475
modified spi/common/policy-engine-spi/src/main/java/org/eclipse/edc/policy/engine/spi/AtomicConstraintFunction.java +16 −3
@@ -16,6 +16,7 @@
1616
1717 import org.eclipse.edc.policy.model.Operator;
1818 import org.eclipse.edc.policy.model.Rule;
19+import org.eclipse.edc.spi.result.Result;
1920
2021 /**
2122 * Invoked during policy evaluation when the left operand of an atomic constraint evaluates to a key associated with this function. The function is responsible for performing
@@ -27,11 +28,23 @@
2728 /**
2829 * Performs the evaluation.
2930 *
30- * @param operator the operation
31+ * @param operator the operation
3132 * @param rightValue the right-side expression for the constraint; the concrete type may be a string, primitive or object such as a JSON-LD encoded collection.
32- * @param rule the rule associated with the constraint
33- * @param context the policy context
33+ * @param rule the rule associated with the constraint
34+ * @param context the policy context
3435 */
3536 boolean evaluate(Operator operator, Object rightValue, R rule, PolicyContext context);
3637
38+
39+ /**
40+ * Performs a validation of an atomic constraint
41+ *
42+ * @param operator the operation
43+ * @param rightValue the right-side expression for the constraint; the concrete type may be a string, primitive or object such as a JSON-LD encoded collection
44+ * @param rule the rule associated with the constraint
45+ * @return the result of the validation
46+ */
47+ default Result<Void> validate(Operator operator, Object rightValue, R rule) {
48+ return Result.success();
49+ }
3750 }
modified spi/common/policy-engine-spi/src/main/java/org/eclipse/edc/policy/engine/spi/DynamicAtomicConstraintFunction.java +15 −0
@@ -16,6 +16,7 @@
1616
1717 import org.eclipse.edc.policy.model.Operator;
1818 import org.eclipse.edc.policy.model.Rule;
19+import org.eclipse.edc.spi.result.Result;
1920
2021 /**
2122 * Invoked during policy evaluation as when the left operand of an atomic constraint evaluates to a key that is not bound to a {@link AtomicConstraintFunction}.
@@ -42,4 +43,18 @@
4243 */
4344 boolean canHandle(Object leftValue);
4445
46+
47+ /**
48+ * Performs a validation of an atomic constraint
49+ *
50+ * @param leftValue the left-side expression for the constraint
51+ * @param operator the operation
52+ * @param rightValue the right-side expression for the constraint; the concrete type may be a string, primitive or object such as a JSON-LD encoded collection
53+ * @param rule the rule associated with the constraint
54+ * @return the result of the validation
55+ */
56+ default Result<Void> validate(Object leftValue, Operator operator, Object rightValue, R rule) {
57+ return Result.success();
58+ }
59+
4560 }
modified spi/common/policy-engine-spi/src/main/java/org/eclipse/edc/policy/engine/spi/PolicyEngine.java +5 −0
@@ -58,6 +58,11 @@
5858 */
5959 Result<Void> evaluate(String scope, Policy policy, PolicyContext context);
6060
61+ /**
62+ * Validates the given policy.
63+ */
64+ Result<Void> validate(Policy policy);
65+
6166 /**
6267 * Registers a function that is invoked when a policy contains an atomic constraint whose left operator expression evaluates to the given key for the specified scope.
6368 *
modified spi/common/policy-engine-spi/src/main/java/org/eclipse/edc/policy/engine/spi/RuleBindingRegistry.java +6 −0
@@ -42,4 +42,10 @@
4242 * Returns true of the rule type is bound to the scope; otherwise false.
4343 */
4444 boolean isInScope(String ruleType, String scope);
45+
46+
47+ /**
48+ * Returns the bindings for a rule type;
49+ */
50+ Set<String> bindings(String ruleType);
4551 }