forked from cedar-policy/cedar-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterface.rs
More file actions
1759 lines (1587 loc) · 62.3 KB
/
interface.rs
File metadata and controls
1759 lines (1587 loc) · 62.3 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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* 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.
*/
use cedar_policy::entities_errors::EntitiesError;
#[cfg(feature = "partial-eval")]
use cedar_policy::ffi::is_authorized_partial_json_str;
use cedar_policy::ffi::{
schema_to_json, schema_to_text, PolicySet as PolicySetFFI, Schema as FFISchema,
SchemaToJsonAnswer, SchemaToTextAnswer,
};
use cedar_policy::{
ffi::{is_authorized_json_str, validate_json_str},
Entities, EntityUid, Policy, PolicySet, Schema, Template,
};
use cedar_policy_formatter::{policies_str_to_pretty, Config};
use jni::{
objects::{JClass, JObject, JString, JValueGen, JValueOwned},
sys::{jstring, jvalue},
JNIEnv,
};
use jni_fn::jni_fn;
use serde::{Deserialize, Serialize};
use serde_json::{from_str, Value};
use std::{error::Error, str::FromStr, thread};
use crate::{
answer::Answer,
jmap::Map,
jset::Set,
objects::{JEntityId, JEntityTypeName, JEntityUID, JPolicy, Object},
utils::raise_npe,
};
use crate::{helpers::validate_with_level_json_str, objects::JFormatterConfig};
type Result<T> = std::result::Result<T, Box<dyn Error>>;
const V0_AUTH_OP: &str = "AuthorizationOperation";
#[cfg(feature = "partial-eval")]
const V0_AUTH_PARTIAL_OP: &str = "AuthorizationPartialOperation";
const V0_VALIDATE_OP: &str = "ValidateOperation";
const V0_VALIDATE_LEVEL_OP: &str = "ValidateWithLevelOperation";
const V0_VALIDATE_ENTITIES: &str = "ValidateEntities";
fn build_err_obj(env: &JNIEnv<'_>, err: &str) -> jstring {
env.new_string(
serde_json::to_string(&Answer::fail_bad_request(vec![format!(
"Failed {} Java string",
err
)]))
.expect("could not serialise response"),
)
.expect("error creating Java string")
.into_raw()
}
fn call_cedar_in_thread(call_str: String, input_str: String) -> String {
call_cedar(&call_str, &input_str)
}
/// JNI entry point for authorization and validation requests
#[jni_fn("com.cedarpolicy.BasicAuthorizationEngine")]
pub fn callCedarJNI(
mut env: JNIEnv<'_>,
_class: JClass<'_>,
j_call: JString<'_>,
j_input: JString<'_>,
) -> jstring {
let j_call_str: String = match env.get_string(&j_call) {
Ok(call_str) => call_str.into(),
_ => return build_err_obj(&env, "getting"),
};
let mut j_input_str: String = match env.get_string(&j_input) {
Ok(s) => s.into(),
Err(_) => return build_err_obj(&env, "parsing"),
};
j_input_str.push(' ');
let handle = thread::spawn(move || call_cedar_in_thread(j_call_str, j_input_str));
let result = match handle.join() {
Ok(s) => s,
Err(e) => format!("Authorization thread failed {e:?}"),
};
let res = env.new_string(result);
match res {
Ok(r) => r.into_raw(),
_ => env
.new_string(
serde_json::to_string(&Answer::fail_internally(
"Failed creating Java string".to_string(),
))
.expect("could not serialise response"),
)
.expect("error creating Java string")
.into_raw(),
}
}
/// JNI entry point to get the Cedar version
#[jni_fn("com.cedarpolicy.BasicAuthorizationEngine")]
pub fn getCedarJNIVersion(env: JNIEnv<'_>) -> jstring {
env.new_string("4.0")
.expect("error creating Java string")
.into_raw()
}
pub(crate) fn call_cedar(call: &str, input: &str) -> String {
let result = match call {
V0_AUTH_OP => is_authorized_json_str(input),
#[cfg(feature = "partial-eval")]
V0_AUTH_PARTIAL_OP => is_authorized_partial_json_str(input),
V0_VALIDATE_OP => validate_json_str(input),
V0_VALIDATE_ENTITIES => json_validate_entities(&input),
V0_VALIDATE_LEVEL_OP => validate_with_level_json_str(input),
_ => {
let ires = Answer::fail_internally(format!("unsupported operation: {}", call));
serde_json::to_string(&ires)
}
};
result.unwrap_or_else(|err| {
panic!("failed to handle call {call} with input {input}\nError: {err}")
})
}
#[derive(Serialize, Deserialize)]
struct ValidateEntityCall {
schema: Value,
entities: Value,
}
pub fn json_validate_entities(input: &str) -> serde_json::Result<String> {
let ans = validate_entities(input)?;
serde_json::to_string(&ans)
}
/// public string-based JSON interface to be invoked by FFIs. Takes in a `ValidateEntityCall` and (if successful)
/// returns unit value () which is null value when serialized to json.
pub fn validate_entities(input: &str) -> serde_json::Result<Answer> {
let validate_entity_call = from_str::<ValidateEntityCall>(&input)?;
let schema = match validate_entity_call.schema {
Value::String(cedarschema_str) => match Schema::from_cedarschema_str(&cedarschema_str) {
Ok(s) => s.0,
Err(e) => return Ok(Answer::fail_bad_request(vec![e.to_string()])),
},
cedarschema_json_obj => match Schema::from_json_value(cedarschema_json_obj) {
Ok(s) => s,
Err(e) => return Ok(Answer::fail_bad_request(vec![e.to_string()])),
},
};
match Entities::from_json_value(validate_entity_call.entities, Some(&schema)) {
Err(error) => {
let err_message = match error {
EntitiesError::Serialization(err) => err.to_string(),
EntitiesError::Deserialization(err) => err.to_string(),
EntitiesError::Duplicate(err) => err.to_string(),
EntitiesError::TransitiveClosureError(err) => err.to_string(),
EntitiesError::InvalidEntity(err) => err.to_string(),
};
Ok(Answer::fail_bad_request(vec![err_message]))
}
Ok(_entities) => Ok(Answer::Success {
result: "null".to_string(),
}),
}
}
#[derive(Debug, Serialize, Deserialize)]
struct JavaInterfaceCall {
pub call: String,
arguments: String,
}
fn jni_failed(env: &mut JNIEnv<'_>, e: &dyn Error) -> jvalue {
// If we already generated an exception, then let that go up the stack
// Otherwise, generate a cedar InternalException and return null
if !env.exception_check().unwrap_or_default() {
// We have to unwrap here as we're doing exception handling
// If we don't have the heap space to create an exception, the only valid move is ending the process
env.throw_new(
"com/cedarpolicy/model/exception/InternalException",
format!("Internal JNI Error: {e}"),
)
.unwrap();
}
JValueOwned::Object(JObject::null()).as_jni()
}
/// Public string-based JSON interface to parse a schema in Cedar's JSON format
#[jni_fn("com.cedarpolicy.model.schema.Schema")]
pub fn parseJsonSchemaJni<'a>(mut env: JNIEnv<'a>, _: JClass, schema_jstr: JString<'a>) -> jvalue {
match parse_json_schema_internal(&mut env, schema_jstr) {
Ok(v) => v.as_jni(),
Err(e) => jni_failed(&mut env, e.as_ref()),
}
}
/// public string-based JSON interface to parse a schema in Cedar's cedar-readable format
#[jni_fn("com.cedarpolicy.model.schema.Schema")]
pub fn parseCedarSchemaJni<'a>(mut env: JNIEnv<'a>, _: JClass, schema_jstr: JString<'a>) -> jvalue {
match parse_cedar_schema_internal(&mut env, schema_jstr) {
Ok(v) => v.as_jni(),
Err(e) => jni_failed(&mut env, e.as_ref()),
}
}
fn parse_json_schema_internal<'a>(
env: &mut JNIEnv<'a>,
schema_jstr: JString<'a>,
) -> Result<JValueOwned<'a>> {
if schema_jstr.is_null() {
raise_npe(env)
} else {
let schema_jstring = env.get_string(&schema_jstr)?;
let schema_string = String::from(schema_jstring);
match Schema::from_json_str(&schema_string) {
Err(e) => Err(Box::new(e)),
Ok(_) => Ok(JValueGen::Object(env.new_string("success")?.into())),
}
}
}
fn parse_cedar_schema_internal<'a>(
env: &mut JNIEnv<'a>,
schema_jstr: JString<'a>,
) -> Result<JValueOwned<'a>> {
if schema_jstr.is_null() {
raise_npe(env)
} else {
let schema_jstring = env.get_string(&schema_jstr)?;
let schema_string = String::from(schema_jstring);
match Schema::from_cedarschema_str(&schema_string) {
Err(e) => Err(Box::new(e)),
Ok(_) => Ok(JValueGen::Object(env.new_string("success")?.into())),
}
}
}
#[jni_fn("com.cedarpolicy.model.policy.Policy")]
pub fn parsePolicyJni<'a>(mut env: JNIEnv<'a>, _: JClass, policy_jstr: JString<'a>) -> jvalue {
match parse_policy_internal(&mut env, policy_jstr) {
Err(e) => jni_failed(&mut env, e.as_ref()),
Ok(policy_text) => policy_text.as_jni(),
}
}
fn parse_policy_internal<'a>(
env: &mut JNIEnv<'a>,
policy_jstr: JString<'a>,
) -> Result<JValueOwned<'a>> {
if policy_jstr.is_null() {
raise_npe(env)
} else {
let policy_jstring = env.get_string(&policy_jstr)?;
let policy_string = String::from(policy_jstring);
match Policy::from_str(&policy_string) {
Err(e) => Err(Box::new(e)),
Ok(p) => {
let policy_text = format!("{}", p);
Ok(JValueGen::Object(env.new_string(&policy_text)?.into()))
}
}
}
}
#[jni_fn("com.cedarpolicy.model.policy.PolicySet")]
pub fn policySetToJson<'a>(mut env: JNIEnv<'a>, _: JClass, policies_jstr: JString<'a>) -> jvalue {
match policy_set_to_json_internal(&mut env, policies_jstr) {
Err(e) => jni_failed(&mut env, e.as_ref()),
Ok(policies_set) => policies_set.as_jni(),
}
}
fn policy_set_to_json_internal<'a>(
env: &mut JNIEnv<'a>,
policy_set_jstr: JString<'a>,
) -> Result<JValueOwned<'a>> {
if policy_set_jstr.is_null() {
raise_npe(env)
} else {
let policy_set_jstring = env.get_string(&policy_set_jstr)?;
let policy_set_string = String::from(policy_set_jstring);
let policy_set_ffi: PolicySetFFI = serde_json::from_str(&policy_set_string)?;
let policy_set = policy_set_ffi
.parse()
.map_err(|err| format!("Error parsing policy set: {:?}", err))?;
let policy_set_json = serde_json::to_string(&policy_set.to_json().unwrap())?;
Ok(JValueGen::Object(env.new_string(&policy_set_json)?.into()))
}
}
#[jni_fn("com.cedarpolicy.model.policy.PolicySet")]
pub fn parsePoliciesJni<'a>(mut env: JNIEnv<'a>, _: JClass, policies_jstr: JString<'a>) -> jvalue {
match parse_policies_internal(&mut env, policies_jstr) {
Err(e) => jni_failed(&mut env, e.as_ref()),
Ok(policies_set) => policies_set.as_jni(),
}
}
fn parse_policies_internal<'a>(
env: &mut JNIEnv<'a>,
policies_jstr: JString<'a>,
) -> Result<JValueOwned<'a>> {
if policies_jstr.is_null() {
raise_npe(env)
} else {
// Parse the string into the Rust PolicySet
let policies_jstring = env.get_string(&policies_jstr)?;
let policies_string = String::from(policies_jstring);
let policy_set = PolicySet::from_str(&policies_string)?;
// Enumerate over the parsed policies
let mut policies_java_hash_set = Set::new(env)?;
for policy in policy_set.policies() {
let policy_id = format!("{}", policy.id());
let policy_text = format!("{}", policy);
let java_policy_object = JPolicy::new(
env,
&env.new_string(&policy_text)?,
&env.new_string(&policy_id)?,
)?;
let _ = policies_java_hash_set.add(env, java_policy_object);
}
let mut templates_java_hash_set = Set::new(env)?;
for template in policy_set.templates() {
let policy_id = format!("{}", template.id());
let policy_text = format!("{}", template);
let java_policy_object = JPolicy::new(
env,
&env.new_string(&policy_text)?,
&env.new_string(&policy_id)?,
)?;
let _ = templates_java_hash_set.add(env, java_policy_object);
}
let java_policy_set = create_java_policy_set(
env,
policies_java_hash_set.as_ref(),
templates_java_hash_set.as_ref(),
);
Ok(JValueGen::Object(java_policy_set))
}
}
fn create_java_policy_set<'a>(
env: &mut JNIEnv<'a>,
policies_java_hash_set: &JObject<'a>,
templates_java_hash_set: &JObject<'a>,
) -> JObject<'a> {
env.new_object(
"com/cedarpolicy/model/policy/PolicySet",
"(Ljava/util/Set;Ljava/util/Set;)V",
&[
JValueGen::Object(policies_java_hash_set),
JValueGen::Object(templates_java_hash_set),
],
)
.expect("Failed to create new PolicySet object")
}
#[jni_fn("com.cedarpolicy.model.policy.Policy")]
pub fn getPolicyAnnotationsJni<'a>(
mut env: JNIEnv<'a>,
_: JClass,
policy_jstr: JString<'a>,
) -> jvalue {
match get_policy_annotations_internal(&mut env, policy_jstr) {
Err(e) => jni_failed(&mut env, e.as_ref()),
Ok(annotations) => annotations.as_jni(),
}
}
pub fn get_policy_annotations_internal<'a>(
env: &mut JNIEnv<'a>,
policy_jstr: JString<'a>,
) -> Result<JValueOwned<'a>> {
if policy_jstr.is_null() {
raise_npe(env)
} else {
let policy_jstring = env.get_string(&policy_jstr)?;
let policy_string = String::from(policy_jstring);
match Policy::from_str(&policy_string) {
Err(e) => Err(Box::new(e)),
Ok(policy) => {
let java_map = create_java_map_from_annotations(env, policy.annotations());
Ok(JValueGen::Object(java_map))
}
}
}
}
#[jni_fn("com.cedarpolicy.model.policy.Policy")]
pub fn getTemplateAnnotationsJni<'a>(
mut env: JNIEnv<'a>,
_: JClass,
template_jstr: JString<'a>,
) -> jvalue {
match get_template_annotations_internal(&mut env, template_jstr) {
Err(e) => jni_failed(&mut env, e.as_ref()),
Ok(annotations) => annotations.as_jni(),
}
}
pub fn get_template_annotations_internal<'a>(
env: &mut JNIEnv<'a>,
template_jstr: JString<'a>,
) -> Result<JValueOwned<'a>> {
if template_jstr.is_null() {
raise_npe(env)
} else {
let template_jstring = env.get_string(&template_jstr)?;
let template_string = String::from(template_jstring);
match Template::from_str(&template_string) {
Err(e) => Err(Box::new(e)),
Ok(template) => {
let java_map = create_java_map_from_annotations(env, template.annotations());
Ok(JValueGen::Object(java_map))
}
}
}
}
fn create_java_map_from_annotations<'a, 'b>(
env: &mut JNIEnv<'a>,
annotations: impl Iterator<Item = (&'b str, &'b str)>,
) -> JObject<'a> {
let mut map = Map::new(env).unwrap();
for (annotation_key, annotation_value) in annotations {
let key: JString = env.new_string(annotation_key).unwrap().into();
let value: JString = env.new_string(annotation_value).unwrap().into();
map.put(env, key, value).unwrap();
}
map.into_inner()
}
#[jni_fn("com.cedarpolicy.model.policy.Policy")]
pub fn parsePolicyTemplateJni<'a>(
mut env: JNIEnv<'a>,
_: JClass,
template_jstr: JString<'a>,
) -> jvalue {
match parse_policy_template_internal(&mut env, template_jstr) {
Err(e) => jni_failed(&mut env, e.as_ref()),
Ok(template_text) => template_text.as_jni(),
}
}
fn parse_policy_template_internal<'a>(
env: &mut JNIEnv<'a>,
template_jstr: JString<'a>,
) -> Result<JValueOwned<'a>> {
if template_jstr.is_null() {
raise_npe(env)
} else {
let template_jstring = env.get_string(&template_jstr)?;
let template_string = String::from(template_jstring);
match Template::from_str(&template_string) {
Err(e) => Err(Box::new(e)),
Ok(template) => {
let template_text = template.to_string();
Ok(JValueGen::Object(env.new_string(&template_text)?.into()))
}
}
}
}
#[jni_fn("com.cedarpolicy.model.policy.Policy")]
pub fn toJsonJni<'a>(mut env: JNIEnv<'a>, _: JClass, policy_jstr: JString<'a>) -> jvalue {
match to_json_internal(&mut env, policy_jstr) {
Err(e) => jni_failed(&mut env, e.as_ref()),
Ok(policy_json) => policy_json.as_jni(),
}
}
fn to_json_internal<'a>(env: &mut JNIEnv<'a>, policy_jstr: JString<'a>) -> Result<JValueOwned<'a>> {
if policy_jstr.is_null() {
raise_npe(env)
} else {
let policy_jstring = env.get_string(&policy_jstr)?;
let policy_string = String::from(policy_jstring);
let policy = Policy::from_str(&policy_string)?;
let policy_json = serde_json::to_string(&policy.to_json().unwrap())?;
Ok(JValueGen::Object(env.new_string(&policy_json)?.into()))
}
}
#[jni_fn("com.cedarpolicy.model.policy.Policy")]
pub fn policyEffectJni<'a>(mut env: JNIEnv<'a>, _: JClass, policy_jstr: JString<'a>) -> jvalue {
match policy_effect_jni_internal(&mut env, policy_jstr) {
Err(e) => jni_failed(&mut env, e.as_ref()),
Ok(effect) => effect.as_jni(),
}
}
fn policy_effect_jni_internal<'a>(
env: &mut JNIEnv<'a>,
policy_jstr: JString<'a>,
) -> Result<JValueOwned<'a>> {
if policy_jstr.is_null() {
raise_npe(env)
} else {
let policy_jstring = env.get_string(&policy_jstr)?;
let policy_string = String::from(policy_jstring);
let policy = Policy::from_str(&policy_string)?;
let policy_effect = policy.effect().to_string();
Ok(JValueGen::Object(env.new_string(&policy_effect)?.into()))
}
}
#[jni_fn("com.cedarpolicy.model.policy.Policy")]
pub fn templateEffectJni<'a>(mut env: JNIEnv<'a>, _: JClass, policy_jstr: JString<'a>) -> jvalue {
match template_effect_jni_internal(&mut env, policy_jstr) {
Err(e) => jni_failed(&mut env, e.as_ref()),
Ok(effect) => effect.as_jni(),
}
}
fn template_effect_jni_internal<'a>(
env: &mut JNIEnv<'a>,
policy_jstr: JString<'a>,
) -> Result<JValueOwned<'a>> {
if policy_jstr.is_null() {
raise_npe(env)
} else {
let policy_jstring = env.get_string(&policy_jstr)?;
let policy_string = String::from(policy_jstring);
let policy = Template::from_str(&policy_string)?;
let policy_effect = policy.effect().to_string();
Ok(JValueGen::Object(env.new_string(&policy_effect)?.into()))
}
}
#[jni_fn("com.cedarpolicy.model.policy.Policy")]
pub fn fromJsonJni<'a>(mut env: JNIEnv<'a>, _: JClass, policy_json_jstr: JString<'a>) -> jvalue {
match from_json_internal(&mut env, policy_json_jstr) {
Err(e) => jni_failed(&mut env, e.as_ref()),
Ok(policy_text) => policy_text.as_jni(),
}
}
fn from_json_internal<'a>(
env: &mut JNIEnv<'a>,
policy_json_jstr: JString<'a>,
) -> Result<JValueOwned<'a>> {
if policy_json_jstr.is_null() {
raise_npe(env)
} else {
let policy_json_jstring = env.get_string(&policy_json_jstr)?;
let policy_json_string = String::from(policy_json_jstring);
let policy_json_value: Value = serde_json::from_str(&policy_json_string)?;
match Policy::from_json(None, policy_json_value) {
Err(e) => Err(Box::new(e)),
Ok(p) => {
let policy_text = format!("{}", p);
Ok(JValueGen::Object(env.new_string(&policy_text)?.into()))
}
}
}
}
#[jni_fn("com.cedarpolicy.value.EntityIdentifier")]
pub fn getEntityIdentifierRepr<'a>(mut env: JNIEnv<'a>, _: JClass, obj: JObject<'a>) -> jvalue {
match get_entity_identifier_repr_internal(&mut env, obj) {
Ok(v) => v.as_jni(),
Err(e) => jni_failed(&mut env, e.as_ref()),
}
}
fn get_entity_identifier_repr_internal<'a>(
env: &mut JNIEnv<'a>,
obj: JObject<'a>,
) -> Result<JValueOwned<'a>> {
if obj.is_null() {
raise_npe(env)
} else {
let eid = JEntityId::cast(env, obj)?;
let repr = eid.get_string_repr();
let jstring = env.new_string(repr)?.into();
Ok(JValueGen::Object(jstring))
}
}
#[jni_fn("com.cedarpolicy.value.EntityTypeName")]
pub fn parseEntityTypeName<'a>(mut env: JNIEnv<'a>, _: JClass, obj: JString<'a>) -> jvalue {
match parse_entity_type_name_internal(&mut env, obj) {
Ok(v) => v.as_jni(),
Err(e) => jni_failed(&mut env, e.as_ref()),
}
}
pub fn parse_entity_type_name_internal<'a>(
env: &mut JNIEnv<'a>,
obj: JString<'a>,
) -> Result<JValueGen<JObject<'a>>> {
if obj.is_null() {
raise_npe(env)
} else {
let jstring = env.get_string(&obj)?;
let src = String::from(jstring);
JEntityTypeName::parse(env, &src).map(Into::into)
}
}
#[jni_fn("com.cedarpolicy.value.EntityTypeName")]
pub fn getEntityTypeNameRepr<'a>(mut env: JNIEnv<'a>, _: JClass, obj: JObject<'a>) -> jvalue {
match get_entity_type_name_repr_internal(&mut env, obj) {
Ok(v) => v.as_jni(),
Err(e) => jni_failed(&mut env, e.as_ref()),
}
}
fn get_entity_type_name_repr_internal<'a>(
env: &mut JNIEnv<'a>,
obj: JObject<'a>,
) -> Result<JValueOwned<'a>> {
if obj.is_null() {
raise_npe(env)
} else {
let etype = JEntityTypeName::cast(env, obj)?;
let repr = etype.get_string_repr();
Ok(env.new_string(repr)?.into())
}
}
#[jni_fn("com.cedarpolicy.value.EntityUID")]
pub fn parseEntityUID<'a>(mut env: JNIEnv<'a>, _: JClass, obj: JString<'a>) -> jvalue {
let r = match parse_entity_uid_internal(&mut env, obj) {
Ok(v) => v.as_jni(),
Err(e) => jni_failed(&mut env, e.as_ref()),
};
r
}
fn parse_entity_uid_internal<'a>(
env: &mut JNIEnv<'a>,
obj: JString<'a>,
) -> Result<JValueOwned<'a>> {
if obj.is_null() {
raise_npe(env)
} else {
let jstring = env.get_string(&obj)?;
let src = String::from(jstring);
let obj = JEntityUID::parse(env, &src)?;
Ok(obj.into())
}
}
#[jni_fn("com.cedarpolicy.value.EntityUID")]
pub fn getEUIDRepr<'a>(
mut env: JNIEnv<'a>,
_: JClass,
type_name: JObject<'a>,
id: JObject<'a>,
) -> jvalue {
let r = match get_euid_repr_internal(&mut env, type_name, id) {
Ok(v) => v.as_jni(),
Err(e) => jni_failed(&mut env, e.as_ref()),
};
r
}
fn get_euid_repr_internal<'a>(
env: &mut JNIEnv<'a>,
type_name: JObject<'a>,
id: JObject<'a>,
) -> Result<JValueOwned<'a>> {
if type_name.is_null() || id.is_null() {
raise_npe(env)
} else {
let etype = JEntityTypeName::cast(env, type_name)?.get_rust_repr();
let id = JEntityId::cast(env, id)?.get_rust_repr();
let euid = EntityUid::from_type_name_and_id(etype, id);
let jstring = env.new_string(euid.to_string())?;
Ok(jstring.into())
}
}
#[jni_fn("com.cedarpolicy.formatter.PolicyFormatter")]
pub fn policiesStrToPretty<'a>(
mut env: JNIEnv<'a>,
_: JClass,
policies_jstr: JString<'a>,
) -> jvalue {
match policies_str_to_pretty_internal(&mut env, policies_jstr, None) {
Ok(v) => v.as_jni(),
Err(e) => jni_failed(&mut env, e.as_ref()),
}
}
#[jni_fn("com.cedarpolicy.formatter.PolicyFormatter")]
pub fn policiesStrToPrettyWithConfig<'a>(
mut env: JNIEnv<'a>,
_: JClass,
policies_jstr: JString<'a>,
config_obj: JObject<'a>,
) -> jvalue {
match policies_str_to_pretty_internal(&mut env, policies_jstr, Some(config_obj)) {
Ok(v) => v.as_jni(),
Err(e) => jni_failed(&mut env, e.as_ref()),
}
}
fn policies_str_to_pretty_internal<'a>(
env: &mut JNIEnv<'a>,
policies_jstr: JString<'a>,
config_obj: Option<JObject<'a>>,
) -> Result<JValueOwned<'a>> {
if policies_jstr.is_null() || config_obj.as_ref().is_some_and(|obj| obj.is_null()) {
raise_npe(env)
} else {
let config = if let Some(obj) = config_obj {
JFormatterConfig::cast(env, obj)?.get_rust_repr()
} else {
Config::default()
};
let policies_str = String::from(env.get_string(&policies_jstr)?);
match policies_str_to_pretty(&policies_str, &config) {
Ok(formatted_policies) => Ok(env.new_string(formatted_policies)?.into()),
Err(e) => Err(e.into()),
}
}
}
#[jni_fn("com.cedarpolicy.model.schema.Schema")]
pub fn jsonToCedarJni<'a>(mut env: JNIEnv<'a>, _: JClass, json_schema: JString<'a>) -> jvalue {
match get_cedar_schema_internal(&mut env, json_schema) {
Ok(val) => val.as_jni(),
Err(e) => jni_failed(&mut env, e.as_ref()),
}
}
pub fn get_cedar_schema_internal<'a>(
env: &mut JNIEnv<'a>,
schema_json_jstr: JString<'a>,
) -> Result<JValueOwned<'a>> {
let rust_str = env.get_string(&schema_json_jstr)?;
let schema_str = rust_str.to_str()?;
let schema: FFISchema = serde_json::from_str(schema_str)?;
let cedar_format = schema_to_text(schema);
match cedar_format {
SchemaToTextAnswer::Success { text, warnings } => {
let jstr = env.new_string(&text)?;
Ok(JValueGen::Object(JObject::from(jstr)).into())
}
SchemaToTextAnswer::Failure { errors } => {
let joined_errors = errors
.iter()
.map(|e| e.message.clone())
.collect::<Vec<_>>()
.join("; ");
Err(joined_errors.into())
}
}
}
#[jni_fn("com.cedarpolicy.model.schema.Schema")]
pub fn cedarToJsonJni<'a>(mut env: JNIEnv<'a>, _: JClass, cedar_schema: JString<'a>) -> jvalue {
match get_json_schema_internal(&mut env, cedar_schema) {
Ok(val) => val.as_jni(),
Err(e) => jni_failed(&mut env, e.as_ref()),
}
}
pub fn get_json_schema_internal<'a>(
env: &mut JNIEnv<'a>,
cedar_schema_jstr: JString<'a>,
) -> Result<JValueOwned<'a>> {
let schema_jstr = env.get_string(&cedar_schema_jstr)?;
let schema_str = schema_jstr.to_str()?;
let cedar_schema_str = FFISchema::Cedar(schema_str.into());
let json_format = schema_to_json(cedar_schema_str);
match json_format {
SchemaToJsonAnswer::Success { json, warnings: _ } => {
let json_pretty = serde_json::to_string_pretty(&json)?;
let jstr = env.new_string(&json_pretty)?;
Ok(JValueGen::Object(JObject::from(jstr)).into())
}
SchemaToJsonAnswer::Failure { errors } => {
let joined_errors = errors
.iter()
.map(|e| e.message.clone())
.collect::<Vec<_>>()
.join("; ");
Err(joined_errors.into())
}
}
}
#[cfg(test)]
pub(crate) mod jvm_based_tests {
use super::*;
use crate::jvm_test_utils::*;
use jni::JavaVM;
use std::sync::LazyLock;
pub(crate) static JVM: LazyLock<JavaVM> = LazyLock::new(|| create_jvm().unwrap());
// Static JVM to be used by all the tests. LazyLock for thread-safe lazy initialization
mod policy_tests {
use super::*;
#[track_caller]
fn policy_effect_test_util(env: &mut JNIEnv, policy: &str, expected_effect: &str) {
let policy_string = env.new_string(policy).unwrap();
let effect_result = policy_effect_jni_internal(env, policy_string).unwrap();
let effect_jstr = JString::cast(env, effect_result.l().unwrap()).unwrap();
let effect = String::from(env.get_string(&effect_jstr).unwrap());
assert_eq!(effect, expected_effect);
}
#[test]
fn policy_effect_tests() {
let mut env = JVM.attach_current_thread().unwrap();
policy_effect_test_util(&mut env, "permit(principal,action,resource);", "permit");
policy_effect_test_util(&mut env, "forbid(principal,action,resource);", "forbid");
}
#[test]
fn policy_effect_jni_internal_null() {
let mut env = JVM.attach_current_thread().unwrap();
let null_obj = JObject::null();
let result = policy_effect_jni_internal(&mut env, null_obj.into());
assert!(result.is_ok(), "Expected error on null input");
assert!(
env.exception_check().unwrap(),
"Expected Java exception due to a null input"
);
env.exception_clear().unwrap();
}
#[track_caller]
fn assert_id_annotation_eq(
env: &mut JNIEnv,
annotations: &JObject,
annotation_key: &str,
expected_annotation_value: &str,
) {
let annotation_key_jstr = env.new_string(annotation_key).unwrap();
let actual_annotation_value_obj = env
.call_method(
annotations,
"get",
"(Ljava/lang/Object;)Ljava/lang/Object;",
&[JValueGen::Object(annotation_key_jstr.as_ref())],
)
.unwrap()
.l()
.unwrap();
let actual_annotation_value_jstr =
JString::cast(env, actual_annotation_value_obj).unwrap();
let actual_annotation_value_str =
String::from(env.get_string(&actual_annotation_value_jstr).unwrap());
assert_eq!(
actual_annotation_value_str, expected_annotation_value,
"Returned annotation value should match the annotation in the policy."
)
}
#[test]
fn static_policy_annotations_tests() {
let mut env = JVM.attach_current_thread().unwrap();
let policy_string = env
.new_string("@id(\"policyID1\") @myAnnotationKey(\"myAnnotatedValue\") permit(principal,action,resource);")
.unwrap();
let annotations = get_policy_annotations_internal(&mut env, policy_string)
.unwrap()
.l()
.unwrap();
assert_id_annotation_eq(&mut env, &annotations, "id", "policyID1");
assert_id_annotation_eq(
&mut env,
&annotations,
"myAnnotationKey",
"myAnnotatedValue",
);
}
#[test]
fn template_policy_annotations_tests() {
let mut env = JVM.attach_current_thread().unwrap();
let policy_string = env
.new_string("@id(\"policyID1\") @myAnnotationKey(\"myAnnotatedValue\") permit(principal==?principal,action,resource);")
.unwrap();
let annotations = get_template_annotations_internal(&mut env, policy_string)
.unwrap()
.l()
.unwrap();
assert_id_annotation_eq(&mut env, &annotations, "id", "policyID1");
assert_id_annotation_eq(
&mut env,
&annotations,
"myAnnotationKey",
"myAnnotatedValue",
);
}
#[test]
fn get_template_annotations_internal_null() {
let mut env = JVM.attach_current_thread().unwrap();
let null_obj = JObject::null();
let result = get_template_annotations_internal(&mut env, null_obj.into());
assert!(result.is_ok(), "Expected error on null input");
assert!(
env.exception_check().unwrap(),
"Expected java exception due to a null input"
);
env.exception_clear().unwrap();
}
#[test]
fn parse_policy_internal_success_basic() {
let mut env = JVM.attach_current_thread().unwrap();
let input = r#"permit(principal,action,resource);"#;
let policy_jstr = env.new_string(input).unwrap();
let result = parse_policy_internal(&mut env, policy_jstr);
assert!(
result.is_ok(),
"Expected parse_policy_internal to succeed: {:?}",
result
);
let jvalue = result.unwrap();
let parsed_jstring = JString::cast(&mut env, jvalue.l().unwrap()).unwrap();
let actual_parsed_string = String::from(env.get_string(&parsed_jstring).unwrap());
let expected_policy_object = cedar_policy::Policy::from_str(input).unwrap();
let expected_canonical_string = expected_policy_object.to_string();
assert_eq!(
actual_parsed_string, expected_canonical_string,
"Parsed policy string should match the expected canonical format."
);
}
#[test]
fn parse_policy_template_internal_invalid_missing_template_slots() {
let mut env = JVM.attach_current_thread().unwrap();
let input = r#"permit(principal == User::"alice", action == Action::"read", resource == Resource::"file");"#;
let jstr = env.new_string(input).unwrap();
let result = parse_policy_template_internal(&mut env, jstr);
assert!(
result.is_err(),
"Expected parse_policy_template_internal to fail due to missing template slots"
);
}
#[test]
fn get_policy_annotations_internal_null() {
let mut env = JVM.attach_current_thread().unwrap();
let null_obj = JObject::null();
let result = get_policy_annotations_internal(&mut env, null_obj.into());
assert!(result.is_ok(), "Expected error on null input");
assert!(
env.exception_check().unwrap(),
"Expected java exception due to a null input"
);
env.exception_clear().unwrap();
}
#[test]
fn parse_policy_internal_null() {
let mut env = JVM.attach_current_thread().unwrap();
let null_str = JString::from(JObject::null());
let result = parse_policy_internal(&mut env, null_str);
assert!(result.is_ok(), "Expected error on null input");
assert!(
env.exception_check().unwrap(),
"Expected Java exception due to a null input"
);
env.exception_clear().unwrap();
}
#[test]
fn parse_policy_template_valid_test() {
let mut env = JVM.attach_current_thread().unwrap();
let policy_template = r#"permit(principal==?principal,action == Action::"readfile",resource==?resource );"#;
let jstr = env.new_string(policy_template).unwrap();
let result = parse_policy_template_internal(&mut env, jstr);
assert!(result.is_ok());