Repository navigation
Expand file tree
/
Copy pathBasicAuthorizationEngine.java
More file actions
350 lines (313 loc) · 15.5 KB
/
Copy pathBasicAuthorizationEngine.java
File metadata and controls
350 lines (313 loc) · 15.5 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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/*
* 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.CedarJson.objectReader;
import static com.cedarpolicy.CedarJson.objectWriter;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import com.cedarpolicy.loader.LibraryLoader;
import com.cedarpolicy.model.AuthorizationResponse;
import com.cedarpolicy.model.EntityValidationRequest;
import com.cedarpolicy.model.LevelValidationRequest;
import com.cedarpolicy.model.PartialAuthorizationResponse;
import com.cedarpolicy.model.TypeAwarePartialAuthorizationResponse;
import com.cedarpolicy.model.ValidationRequest;
import com.cedarpolicy.model.ValidationResponse;
import com.cedarpolicy.model.entity.Entities;
import com.cedarpolicy.model.entity.Entity;
import com.cedarpolicy.model.entity.PartialEntities;
import com.cedarpolicy.model.entity.PartialEntity;
import com.cedarpolicy.model.exception.AuthException;
import com.cedarpolicy.model.exception.BadRequestException;
import com.cedarpolicy.model.exception.InternalException;
import com.cedarpolicy.model.exception.MissingExperimentalFeatureException;
import com.cedarpolicy.model.DetailedError;
import com.cedarpolicy.model.policy.PolicySet;
import com.cedarpolicy.value.Value;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/** An authorization engine that is compiled in process. Communicated with via JNI. */
public final class BasicAuthorizationEngine implements AuthorizationEngine {
static {
LibraryLoader.loadLibrary();
String jniVersion = getCedarJNIVersion();
String langVersion = AuthorizationEngine.getCedarLangVersion();
if (!jniVersion.equals(langVersion)) {
throw new ExceptionInInitializerError(
"Error, Java Cedar Language version is " + langVersion
+ " but JNI Cedar Language version is " + jniVersion);
}
}
/** Construct a basic authorization engine. */
public BasicAuthorizationEngine() {
}
@Override
public AuthorizationResponse isAuthorized(com.cedarpolicy.model.AuthorizationRequest q,
PolicySet policySet, Set<Entity> entities) throws AuthException {
// Use the stateful (cached) path only if the policy set is cached AND
// any provided schema is also cached. Fall back to the uncached path
// otherwise to avoid silently skipping schema validation.
Optional<String> policySetKey = policySet.cacheKey();
if (policySetKey.isPresent()) {
boolean hasSchema = q.schema.isPresent();
Optional<String> schemaKey = hasSchema ? q.schema.get().cacheKey() : Optional.empty();
if (!hasSchema || schemaKey.isPresent()) {
StatefulAuthRequest statefulReq = new StatefulAuthRequest(
q, policySetKey.get(), schemaKey.orElse(null), entities);
try {
return call("StatefulAuthorizationOperation", AuthorizationResponse.class, statefulReq);
} catch (AuthException e) {
if (e.getMessage() != null && e.getMessage().contains("not found")) {
// Cache entry was evicted; fall back to uncached path
} else {
throw e;
}
}
}
}
final AuthorizationRequest request = new AuthorizationRequest(q, policySet, entities);
return call("AuthorizationOperation", AuthorizationResponse.class, request);
}
/**
* Overloaded method to accept Entities object
*/
@Override
public AuthorizationResponse isAuthorized(com.cedarpolicy.model.AuthorizationRequest q,
PolicySet policySet, Entities entities) throws AuthException {
return isAuthorized(q, policySet, entities.getEntities());
}
@Experimental(ExperimentalFeature.PARTIAL_EVALUATION)
@Override
public PartialAuthorizationResponse isAuthorizedPartial(com.cedarpolicy.model.PartialAuthorizationRequest q,
PolicySet policySet, Set<Entity> entities) throws AuthException {
try {
final PartialAuthorizationRequest request = new PartialAuthorizationRequest(q, policySet, entities);
return call("AuthorizationPartialOperation", PartialAuthorizationResponse.class, request);
} catch (InternalException e) {
throw ExperimentalFeature.PARTIAL_EVALUATION.translateIfDisabled(e);
}
}
/**
* Overloaded method to accept Entities object
*/
@Experimental(ExperimentalFeature.PARTIAL_EVALUATION)
@Override
public PartialAuthorizationResponse isAuthorizedPartial(com.cedarpolicy.model.PartialAuthorizationRequest q,
PolicySet policySet, Entities entities) throws AuthException {
return isAuthorizedPartial(q, policySet, entities.getEntities());
}
@Experimental(ExperimentalFeature.TYPE_AWARE_PARTIAL_EVALUATION)
@Override
public TypeAwarePartialAuthorizationResponse isAuthorizedTypeAwarePartial(
com.cedarpolicy.model.TypeAwarePartialAuthorizationRequest q, PolicySet policySet,
PartialEntities entities) throws AuthException {
var response = call("AuthorizationTypeAwarePartialOperation",
TypeAwarePartialAuthorizationResponse.class,
new TypeAwarePartialAuthorizationRequest(q, policySet, entities));
throwIfFeatureDisabled(response.getErrors().orElse(List.of()));
return response.withInputs(q, policySet, entities, this);
}
@Experimental(ExperimentalFeature.TYPE_AWARE_PARTIAL_EVALUATION)
@Override
public AuthorizationResponse reauthorize(com.cedarpolicy.model.TypeAwarePartialAuthorizationRequest request,
PolicySet policySet, PartialEntities partialEntities,
com.cedarpolicy.model.AuthorizationRequest concreteRequest, Entities entities) throws AuthException {
var response = call("TypeAwarePartialReauthorizeOperation", AuthorizationResponse.class,
new TypeAwarePartialReauthorizeRequest(request, policySet, partialEntities, concreteRequest, entities));
throwIfFeatureDisabled(response.errors.map(e -> (List<DetailedError>) e).orElse(List.of()));
return response;
}
/**
* The native library reports a disabled experimental feature as a failure answer rather than a thrown exception,
* because {@link #call} converts every native error into an {@link AuthException}. Recognising the token here is
* what turns it back into {@link MissingExperimentalFeatureException}.
*/
private static void throwIfFeatureDisabled(List<DetailedError> errors) throws AuthException {
for (var error : errors) {
var translated = ExperimentalFeature.TYPE_AWARE_PARTIAL_EVALUATION
.translateIfDisabled(new InternalException(error.message));
if (translated instanceof MissingExperimentalFeatureException) {
throw translated;
}
}
}
@Override
public ValidationResponse validate(ValidationRequest q) throws AuthException {
return call("ValidateOperation", ValidationResponse.class, q);
}
@Override
public ValidationResponse validateWithLevel(LevelValidationRequest q) throws AuthException {
return call("ValidateWithLevelOperation", ValidationResponse.class, q);
}
@Override
public void validateEntities(EntityValidationRequest q) throws AuthException {
EntityValidationResponse entityValidationResponse = call("ValidateEntities", EntityValidationResponse.class, q);
if (!entityValidationResponse.success) {
if (entityValidationResponse.isInternal) {
throw new InternalException(entityValidationResponse.errors.toArray(new String[0]));
} else {
throw new BadRequestException(entityValidationResponse.errors.toArray(new String[0]));
}
}
}
private static <REQ, RESP> RESP call(String operation, Class<RESP> responseClass, REQ request)
throws AuthException {
try {
final String fullRequest = objectWriter().writeValueAsString(request);
final String response = callCedarJNI(operation, fullRequest);
return objectReader().readValue(response, responseClass);
} catch (JsonProcessingException e) {
throw new AuthException("JSON Serialization Error", e);
} catch (IllegalArgumentException e) {
throw new AuthException("Authorization error caused by illegal argument exception.", e);
} catch (IOException e) {
throw new AuthException("JSON Deserialization Error", e);
}
}
/**
* The result of processing an EntityValidationRequest.
*/
@JsonIgnoreProperties({"result"}) // Ignore only the 'result' field
private static final class EntityValidationResponse {
/** A string that indicates if the operation was successful.*/
private final boolean success;
/** A boolean flag that indicates whether the error is internal.*/
private final boolean isInternal;
/** A list of error messages encountered during the operation.*/
private final List<String> errors;
/**
* Parameterized constructor for initializing all fields of EntityValidationResponse.
*
* @param success A boolean indicating success status.
* @param isInternal A boolean indicating if the error is internal.
* @param errors A list of error messages.
*/
@JsonCreator
@SuppressFBWarnings
EntityValidationResponse(
@JsonProperty("success") boolean success,
@JsonProperty("isInternal") boolean isInternal,
@JsonProperty("errors") List<String> errors) {
this.success = success;
this.isInternal = isInternal;
this.errors = errors;
}
}
private static class AuthorizationRequest extends com.cedarpolicy.model.AuthorizationRequest {
@JsonProperty private final PolicySet policies;
@JsonProperty private final Set<Entity> entities;
AuthorizationRequest(com.cedarpolicy.model.AuthorizationRequest request, PolicySet policySet, Set<Entity> entities) {
super(
request.principalEUID,
request.actionEUID,
request.resourceEUID,
request.context,
request.schema,
request.enableRequestValidation);
this.policies = policySet;
this.entities = entities;
}
}
@JsonInclude(JsonInclude.Include.NON_ABSENT)
private static final class TypeAwarePartialAuthorizationRequest
extends com.cedarpolicy.model.TypeAwarePartialAuthorizationRequest {
@JsonProperty private final PolicySet policies;
@JsonProperty private final Set<PartialEntity> entities;
TypeAwarePartialAuthorizationRequest(com.cedarpolicy.model.TypeAwarePartialAuthorizationRequest request,
PolicySet policySet, PartialEntities entities) {
super(request);
this.policies = policySet;
this.entities = entities.getEntities();
}
}
/** The partial payload plus the completed request and entities Cedar validates it against. */
@JsonInclude(JsonInclude.Include.NON_ABSENT)
private static final class TypeAwarePartialReauthorizeRequest
extends com.cedarpolicy.model.TypeAwarePartialAuthorizationRequest {
@JsonProperty private final PolicySet policies;
@JsonProperty private final Set<PartialEntity> entities;
@JsonProperty private final com.cedarpolicy.model.AuthorizationRequest concreteRequest;
@JsonProperty private final Set<Entity> concreteEntities;
TypeAwarePartialReauthorizeRequest(com.cedarpolicy.model.TypeAwarePartialAuthorizationRequest request,
PolicySet policySet, PartialEntities partialEntities,
com.cedarpolicy.model.AuthorizationRequest concreteRequest, Entities concreteEntities) {
super(request);
this.policies = policySet;
this.entities = partialEntities.getEntities();
this.concreteRequest = concreteRequest;
this.concreteEntities = concreteEntities.getEntities();
}
}
@JsonInclude(JsonInclude.Include.NON_ABSENT)
private static final class PartialAuthorizationRequest extends com.cedarpolicy.model.PartialAuthorizationRequest {
@JsonProperty private final PolicySet policies;
@JsonProperty private final Set<Entity> entities;
PartialAuthorizationRequest(com.cedarpolicy.model.PartialAuthorizationRequest request, PolicySet policySet, Set<Entity> entities) {
super(
request.principal,
request.action,
request.resource,
request.context,
request.schema,
request.enableRequestValidation);
this.policies = policySet;
this.entities = entities;
}
}
@JsonInclude(JsonInclude.Include.NON_ABSENT)
private static final class StatefulAuthRequest {
@JsonProperty final Object principal;
@JsonProperty final Object action;
@JsonProperty final Object resource;
@JsonProperty final Optional<Map<String, Value>> context;
@JsonProperty final String preparsedPolicySetId;
@JsonProperty final String preparsedSchemaName;
@JsonProperty final boolean validateRequest;
@JsonProperty final Set<Entity> entities;
StatefulAuthRequest(com.cedarpolicy.model.AuthorizationRequest request,
String policySetId, String schemaName, Set<Entity> entities) {
this.principal = request.principalEUID;
this.action = request.actionEUID;
this.resource = request.resourceEUID;
this.context = request.context;
this.preparsedPolicySetId = policySetId;
this.preparsedSchemaName = schemaName;
this.validateRequest = request.enableRequestValidation;
this.entities = entities;
}
}
/**
* Call out to the Rust implementation.
*
* @param call Call type ("AuthorizationOperation" or "ValidateOperation").
* @param input Request input in JSON format as a String
* @return The response (permit / deny for authorization, valid / invalid for validation)
*/
private static native String callCedarJNI(String call, String input);
/**
* Get the Cedar language major version supported by the JNI (e.g., "1.2")
*
* @return The Cedar language version supported by the JNI
*/
private static native String getCedarJNIVersion();
}