forked from cedar-policy/cedar-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidationTests.java
More file actions
310 lines (270 loc) · 13.2 KB
/
ValidationTests.java
File metadata and controls
310 lines (270 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
/*
* Copyright Cedar Contributors
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cedarpolicy;
import static com.cedarpolicy.TestUtil.loadSchemaResource;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.cedarpolicy.model.DetailedError;
import com.cedarpolicy.model.LevelValidationRequest;
import com.cedarpolicy.model.ValidationRequest;
import com.cedarpolicy.model.ValidationResponse;
import com.cedarpolicy.model.ValidationResponse.SuccessOrFailure;
import com.cedarpolicy.model.ValidationResponse.ValidationSuccessResponse;
import com.cedarpolicy.model.policy.LinkValue;
import com.cedarpolicy.model.policy.Policy;
import com.cedarpolicy.model.policy.PolicySet;
import com.cedarpolicy.model.policy.TemplateLink;
import com.cedarpolicy.model.schema.Schema;
import com.cedarpolicy.value.EntityUID;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/** Tests for the validator. */
public class ValidationTests {
private Schema schema;
private PolicySet policies;
private static AuthorizationEngine engine;
/** Test. */
@Test
public void givenEmptySchemaAndNoPolicyReturnsValid() {
givenSchema(EMPTY_SCHEMA);
ValidationResponse response = whenValidated();
thenIsValid(response);
ValidationResponse levelResponse = whenLevelValidated(1);
thenIsValid(levelResponse);
}
/** Test. */
@Test
public void givenExampleSchemaAndCorrectPolicyReturnsValid() {
givenSchema(PHOTOFLASH_SCHEMA);
givenPolicy(
"policy0",
"permit("
+ " principal == User::\"alice\","
+ " action == Action::\"viewPhoto\","
+ " resource == Photo::\"VacationPhoto94.jpg\""
+ ");");
ValidationResponse response = whenValidated();
thenIsValid(response);
ValidationResponse levelResponse = whenLevelValidated(1);
thenIsValid(levelResponse);
}
/** Test. */
@Test
public void givenExampleSchemaAndIncorrectPolicyReturnsValid() {
givenSchema(PHOTOFLASH_SCHEMA);
givenPolicy(
"policy0",
"permit(\n"
+ " principal == User::\"alice\","
+ " action == Action::\"viewPhoto\","
+ " resource == User::\"bob\""
+ ");");
ValidationResponse response = whenValidated();
thenIsNotValid(response);
ValidationResponse levelResponse = whenLevelValidated(1);
thenIsNotValid(levelResponse);
}
/** Test. */
@Test
public void givenInvalidPolicyThrowsBadRequestError() {
givenSchema(EMPTY_SCHEMA);
givenPolicy("policy0", "permit { }");
ValidationResponse response = whenValidated();
thenValidationFailed(response);
ValidationResponse levelResponse = whenLevelValidated(1);
thenValidationFailed(levelResponse);
}
@Test
public void validateTemplateLinkedPolicySuccessTest() {
givenSchema(LIBRARY_SCHEMA);
Set<Policy> templates = new HashSet<>();
templates.add(new Policy("permit(principal == ?principal, action, resource in ?resource);", "template0"));
templates.add(new Policy("permit(principal, action, resource in ?resource);", "template1"));
templates.add(new Policy("permit(principal == ?principal, action, resource);", "template2"));
List<TemplateLink> templateLinks = new ArrayList<>();
LinkValue principalLink = new LinkValue("?principal", EntityUID.parse("Library::User::\"Victor\"").get());
LinkValue resourceLink1 = new LinkValue("?resource",
EntityUID.parse("Library::Book::\"The black Swan\"").get());
LinkValue resourceLink2 = new LinkValue("?resource",
EntityUID.parse("Library::Book::\"Thinking Fast and Slow\"").get());
templateLinks.add(new TemplateLink("template0", "policy0", List.of(principalLink, resourceLink1)));
templateLinks.add(new TemplateLink("template1", "policy1", List.of(resourceLink2)));
templateLinks.add(new TemplateLink("template2", "policy2", List.of(principalLink)));
this.policies = new PolicySet(new HashSet<>(), templates, templateLinks);
ValidationResponse response = whenValidated();
thenIsValid(response);
ValidationResponse levelResponse = whenLevelValidated(1);
thenIsValid(levelResponse);
}
@Test
public void validateTemplateLinkedPolicyFailsWhenExpected() {
givenSchema(LIBRARY_SCHEMA);
Set<Policy> templates = new HashSet<>();
templates.add(new Policy("permit(principal == ?principal, action, resource in ?resource);", "template0"));
templates.add(new Policy("permit(principal, action, resource in ?resource);", "template1"));
templates.add(new Policy("permit(principal == ?principal, action, resource);", "template2"));
LinkValue principalLink = new LinkValue("?principal", EntityUID.parse("Library::User::\"Victor\"").get());
LinkValue resourceLink = new LinkValue("?resource", EntityUID.parse("Library::Book::\"The black Swan\"").get());
// fails if we provide a value for the wrong slot
this.policies = new PolicySet(new HashSet<>(), templates,
List.of(new TemplateLink("template1", "policy", List.of(principalLink))));
ValidationResponse response1 = whenValidated();
thenValidationFailed(response1);
ValidationResponse levelResponse1 = whenLevelValidated(1);
thenValidationFailed(levelResponse1);
// fails if we provide a value for too many slots
this.policies = new PolicySet(new HashSet<>(), templates,
List.of(new TemplateLink("template2", "policy", List.of(principalLink, resourceLink))));
ValidationResponse response2 = whenValidated();
thenValidationFailed(response2);
ValidationResponse levelResponse2 = whenLevelValidated(1);
thenValidationFailed(levelResponse2);
// fails if we don't provide a value for all slots
this.policies = new PolicySet(new HashSet<>(), templates,
List.of(new TemplateLink("template0", "policy", List.of(resourceLink))));
ValidationResponse response3 = whenValidated();
thenValidationFailed(response3);
ValidationResponse levelResponse3 = whenLevelValidated(1);
thenValidationFailed(levelResponse3);
// validation returns an error if we provide a link with the wrong type
LinkValue badLink1 = new LinkValue("?resource", EntityUID.parse("Library::User::\"Victor\"").get());
this.policies = new PolicySet(new HashSet<>(), templates,
List.of(new TemplateLink("template1", "policy", List.of(badLink1))));
ValidationResponse response4 = whenValidated();
thenIsNotValid(response4);
ValidationResponse levelResponse4 = whenLevelValidated(1);
thenIsNotValid(levelResponse4);
// validation returns an error if we provide a link with an invalid type
LinkValue badLink2 = new LinkValue("?resource", EntityUID.parse("Library::BOOK::\"The black Swan\"").get());
this.policies = new PolicySet(new HashSet<>(), templates,
List.of(new TemplateLink("template1", "policy", List.of(badLink2))));
ValidationResponse response5 = whenValidated();
thenIsNotValid(response5);
ValidationResponse levelResponse5 = whenLevelValidated(1);
thenIsNotValid(levelResponse5);
}
@Test
public void validateLevelPolicySuccessTest() {
givenSchema(LEVEL_SCHEMA);
givenPolicy(
"policy0",
"permit(\n"
+ " principal in UserGroup::\"alice_friends\",\n"
+ " action == Action::\"viewPhoto\",\n"
+ " resource\n"
+ ") when {principal in resource.owner.friend};");
ValidationResponse response = whenValidated();
thenIsValid(response);
ValidationResponse levelResponse = whenLevelValidated(2);
thenIsValid(levelResponse);
}
@Test
public void validateLevelPolicyFailsWhenExpected() {
givenSchema(LEVEL_SCHEMA);
givenPolicy(
"policy0",
"permit(\n"
+ " principal in UserGroup::\"alice_friends\",\n"
+ " action == Action::\"viewPhoto\",\n"
+ " resource\n"
+ ") when {principal in resource.owner.friend};");
ValidationResponse response = whenValidated();
thenIsValid(response);
ValidationResponse levelResponse = whenLevelValidated(1);
thenIsNotValid(levelResponse);
}
/** Test enum entity validation with valid enum values. */
@Test
public void givenEnumSchemaAndValidEnumUsageReturnsValid() {
givenSchema(ENUM_SCHEMA);
givenPolicy("policy0", "permit(" + " principal == User::\"alice\"," + " action == Action::\"UpdateTask\","
+ " resource == Task::\"task1\"" + ") when {" + " resource.status == Color::\"Red\"" + "};");
ValidationResponse response = whenValidated();
thenIsValid(response);
}
/** Test enum entity validation with invalid enum values. */
@Test
public void givenEnumSchemaAndInvalidEnumValueReturnsInvalid() {
givenSchema(ENUM_SCHEMA);
givenPolicy("policy0", "permit(" + " principal == User::\"alice\"," + " action == Action::\"UpdateTask\","
+ " resource == Task::\"task1\"" + ") when {" + " resource.status != Color::\"Purple\"" + "};");
ValidationResponse response = whenValidated();
thenIsNotValid(response);
}
private void givenSchema(Schema testSchema) {
this.schema = testSchema;
}
private void givenPolicy(String id, String policyText) {
Policy policy = new Policy(policyText, id);
this.policies = new PolicySet(Set.of(policy));
}
private ValidationResponse whenValidated() {
ValidationRequest request = new ValidationRequest(schema, policies);
return assertDoesNotThrow(() -> engine.validate(request));
}
private ValidationResponse whenLevelValidated(long maxDerefLevel) {
LevelValidationRequest request = new LevelValidationRequest(schema, policies, maxDerefLevel);
return assertDoesNotThrow(() -> engine.validateWithLevel(request));
}
private void thenIsValid(ValidationResponse response) {
assertEquals(response.type, SuccessOrFailure.Success);
final ValidationSuccessResponse success = assertDoesNotThrow(() -> response.success.get());
assertTrue(
success.validationErrors.isEmpty(),
() -> {
String errors = response.success.get().validationErrors.stream()
.map(note -> String.format("in policy %s: %s", note.getPolicyId(), note.getError()))
.collect(Collectors.joining("\n"));
return "Expected valid response but got validation errors:\n" + errors;
});
}
private void thenIsNotValid(ValidationResponse response) {
assertEquals(response.type, SuccessOrFailure.Success);
final ValidationSuccessResponse success = assertDoesNotThrow(() -> response.success.get());
assertFalse(
success.validationErrors.isEmpty(),
() -> {
return "Expected validation errors but did not find any";
});
}
private void thenValidationFailed(ValidationResponse response) {
assertEquals(response.type, SuccessOrFailure.Failure);
final List<DetailedError> errors = assertDoesNotThrow(() -> response.errors.get());
assertFalse(errors.isEmpty());
}
@BeforeAll
private static void setUp() {
engine = new BasicAuthorizationEngine();
}
@BeforeEach
private void reset() {
this.schema = null;
this.policies = new PolicySet();
}
private static final Schema EMPTY_SCHEMA = loadSchemaResource("/empty_schema.json");
private static final Schema PHOTOFLASH_SCHEMA = loadSchemaResource("/photoflash_schema.json");
private static final Schema LIBRARY_SCHEMA = loadSchemaResource("/library_schema.json");
private static final Schema LEVEL_SCHEMA = loadSchemaResource("/level_schema.json");
private static final Schema ENUM_SCHEMA = loadSchemaResource("/enum_schema.json");
}