-
Notifications
You must be signed in to change notification settings - Fork 143
Expand file tree
/
Copy pathapi.rs
More file actions
4834 lines (4486 loc) · 180 KB
/
api.rs
File metadata and controls
4834 lines (4486 loc) · 180 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 2022-2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* 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.
*/
//! This module contains the public library api
#![allow(
clippy::missing_panics_doc,
clippy::missing_errors_doc,
clippy::similar_names
)]
pub use ast::Effect;
pub use authorizer::Decision;
use cedar_policy_core::ast;
use cedar_policy_core::ast::RestrictedExprError;
use cedar_policy_core::authorizer;
pub use cedar_policy_core::authorizer::AuthorizationError;
use cedar_policy_core::entities;
use cedar_policy_core::entities::JsonDeserializationErrorContext;
use cedar_policy_core::entities::{ContextSchema, Dereference, JsonDeserializationError};
use cedar_policy_core::est;
pub use cedar_policy_core::evaluator::{EvaluationError, EvaluationErrorKind};
use cedar_policy_core::evaluator::{Evaluator, RestrictedEvaluator};
pub use cedar_policy_core::extensions;
use cedar_policy_core::extensions::Extensions;
use cedar_policy_core::parser;
pub use cedar_policy_core::parser::err::ParseErrors;
use cedar_policy_core::parser::SourceInfo;
use cedar_policy_core::FromNormalizedStr;
pub use cedar_policy_validator::{
TypeErrorKind, UnsupportedFeature, ValidationErrorKind, ValidationWarningKind,
};
use ref_cast::RefCast;
use serde::{Deserialize, Serialize};
use smol_str::SmolStr;
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::str::FromStr;
use thiserror::Error;
/// Identifier for a Template slot
#[repr(transparent)]
#[derive(Debug, Clone, Eq, PartialEq, PartialOrd, Ord, Hash, RefCast)]
pub struct SlotId(ast::SlotId);
impl SlotId {
/// Get the slot for `principal`
pub fn principal() -> Self {
Self(ast::SlotId::principal())
}
/// Get the slot for `resource`
pub fn resource() -> Self {
Self(ast::SlotId::resource())
}
}
impl std::fmt::Display for SlotId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl From<ast::SlotId> for SlotId {
fn from(a: ast::SlotId) -> Self {
Self(a)
}
}
impl From<SlotId> for ast::SlotId {
fn from(s: SlotId) -> Self {
s.0
}
}
/// Entity datatype
#[repr(transparent)]
#[derive(Debug, Clone, PartialEq, Eq, RefCast)]
pub struct Entity(ast::Entity);
impl Entity {
/// Create a new `Entity` with this Uid, attributes, and parents.
///
/// Attribute values are specified here as "restricted expressions".
/// See docs on `RestrictedExpression`
/// ```
/// # use cedar_policy::{Entity, EntityId, EntityTypeName, EntityUid, RestrictedExpression};
/// # use std::collections::{HashMap, HashSet};
/// # use std::str::FromStr;
/// let eid = EntityId::from_str("alice").unwrap();
/// let type_name = EntityTypeName::from_str("User").unwrap();
/// let euid = EntityUid::from_type_name_and_id(type_name, eid);
/// let attrs = HashMap::from([
/// ("age".to_string(), RestrictedExpression::from_str("21").unwrap()),
/// ("department".to_string(), RestrictedExpression::from_str("\"CS\"").unwrap()),
/// ]);
/// let parent_eid = EntityId::from_str("admin").unwrap();
/// let parent_type_name = EntityTypeName::from_str("Group").unwrap();
/// let parent_euid = EntityUid::from_type_name_and_id(parent_type_name, parent_eid);
/// let parents = HashSet::from([parent_euid]);
/// let entity = Entity::new(euid, attrs, parents);
///```
pub fn new(
uid: EntityUid,
attrs: HashMap<String, RestrictedExpression>,
parents: HashSet<EntityUid>,
) -> Self {
// note that we take a "parents" parameter here; we will compute TC when
// the `Entities` object is created
Self(ast::Entity::new(
uid.0,
attrs
.into_iter()
.map(|(k, v)| (SmolStr::from(k), v.0))
.collect(),
parents.into_iter().map(|uid| uid.0).collect(),
))
}
/// Create a new `Entity` with this Uid, no attributes, and no parents.
/// ```
/// use cedar_policy::{Entity, EntityId, EntityTypeName, EntityUid};
/// # use std::str::FromStr;
/// let eid = EntityId::from_str("alice").unwrap();
/// let type_name = EntityTypeName::from_str("User").unwrap();
/// let euid = EntityUid::from_type_name_and_id(type_name, eid);
/// let alice = Entity::with_uid(euid);
/// # assert_eq!(alice.attr("age"), None);
/// ```
pub fn with_uid(uid: EntityUid) -> Self {
Self(ast::Entity::with_uid(uid.0))
}
/// Get the Uid of this entity
/// ```
/// # use cedar_policy::{Entity, EntityId, EntityTypeName, EntityUid};
/// # use std::str::FromStr;
/// # let eid = EntityId::from_str("alice").unwrap();
/// let type_name = EntityTypeName::from_str("User").unwrap();
/// let euid = EntityUid::from_type_name_and_id(type_name, eid);
/// let alice = Entity::with_uid(euid.clone());
/// assert_eq!(alice.uid(), euid);
/// ```
pub fn uid(&self) -> EntityUid {
EntityUid(self.0.uid())
}
/// Get the value for the given attribute, or `None` if not present.
///
/// This can also return Some(Err) if the attribute had an illegal value.
/// ```
/// use cedar_policy::{Entity, EntityId, EntityTypeName, EntityUid, EvalResult,
/// RestrictedExpression};
/// use std::collections::{HashMap, HashSet};
/// use std::str::FromStr;
/// let eid = EntityId::from_str("alice").unwrap();
/// let type_name = EntityTypeName::from_str("User").unwrap();
/// let euid = EntityUid::from_type_name_and_id(type_name, eid);
/// let attrs = HashMap::from([
/// ("age".to_string(), RestrictedExpression::from_str("21").unwrap()),
/// ("department".to_string(), RestrictedExpression::from_str("\"CS\"").unwrap()),
/// ]);
/// let entity = Entity::new(euid, attrs, HashSet::new());
/// assert_eq!(entity.attr("age").unwrap(), Ok(EvalResult::Long(21)));
/// assert_eq!(entity.attr("department").unwrap(), Ok(EvalResult::String("CS".to_string())));
///```
pub fn attr(&self, attr: &str) -> Option<Result<EvalResult, EvaluationError>> {
let expr = self.0.get(attr)?;
let all_ext = Extensions::all_available();
let evaluator = RestrictedEvaluator::new(&all_ext);
Some(
evaluator
.interpret(expr.as_borrowed())
.map(EvalResult::from),
)
}
}
impl std::fmt::Display for Entity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
/// Represents an entity hierarchy, and allows looking up `Entity` objects by
/// Uid.
#[repr(transparent)]
#[derive(Debug, Clone, Default, PartialEq, Eq, RefCast)]
pub struct Entities(pub(crate) entities::Entities);
pub use entities::EntitiesError;
impl Entities {
/// Create a fresh `Entities` with no entities
/// ```
/// use cedar_policy::Entities;
/// let entities = Entities::empty();
/// ```
pub fn empty() -> Self {
Self(entities::Entities::new())
}
/// Get the `Entity` with the given Uid, if any
pub fn get(&self, uid: &EntityUid) -> Option<&Entity> {
match self.0.entity(&uid.0) {
Dereference::Residual(_) | Dereference::NoSuchEntity => None,
Dereference::Data(e) => Some(Entity::ref_cast(e)),
}
}
/// Transform the store into a partial store, where
/// attempting to dereference a non-existent `EntityUID` results in
/// a residual instead of an error.
#[must_use]
#[cfg(feature = "partial-eval")]
pub fn partial(self) -> Self {
Self(self.0.partial())
}
/// Attempt to eagerly compute the values of attributes for all entities in the slice.
/// This can fail if evaluation of the [`RestrictedExpression`] fails.
/// In a future major version, we will likely make this function automatically called via the constructor.
pub fn evaluate(self) -> Result<Self, EvaluationError> {
Ok(Self(self.0.evaluate()?))
}
/// Iterate over the `Entity`'s in the `Entities`
pub fn iter(&self) -> impl Iterator<Item = &Entity> {
self.0.iter().map(Entity::ref_cast)
}
/// Create an `Entities` object with the given entities.
/// It will error if the entities cannot be read or if the entities hierarchy is cyclic
pub fn from_entities(
entities: impl IntoIterator<Item = Entity>,
) -> Result<Self, entities::EntitiesError> {
entities::Entities::from_entities(
entities.into_iter().map(|e| e.0),
entities::TCComputation::ComputeNow,
)
.map(Entities)
}
/// Add all of the [`Entity`]s in the collection to this [`Entities`] structure, re-computing the transitive closure
/// Re-computing the transitive closure can be expensive, so it is advised to not call this method in a loop
pub fn add_entities(
self,
entities: impl IntoIterator<Item = Entity>,
) -> Result<Self, EntitiesError> {
Ok(Self(self.0.add_entities(
entities.into_iter().map(|e| e.0),
entities::TCComputation::ComputeNow,
)?))
}
/// Parse an entities JSON file (in [&str] form) and add them into this [`Entities`] structure, re-computing the transitive closure
///
/// If a `schema` is provided, this will inform the parsing: for instance, it
/// will allow `__entity` and `__extn` escapes to be implicit, and it will error
/// if attributes have the wrong types (e.g., string instead of integer).
/// Re-computing the transitive closure can be expensive, so it is advised to not call this method in a loop
pub fn add_entities_from_json_str(
self,
json: &str,
schema: Option<&Schema>,
) -> Result<Self, EntitiesError> {
let eparser = entities::EntityJsonParser::new(
schema.map(|s| cedar_policy_validator::CoreSchema::new(&s.0)),
Extensions::all_available(),
entities::TCComputation::ComputeNow,
);
let new_entities = eparser
.iter_from_json_str(json)?
.collect::<Result<Vec<_>, _>>()?;
Ok(Self(self.0.add_entities(
new_entities,
entities::TCComputation::ComputeNow,
)?))
}
/// Parse an entities JSON file (in [`serde_json::Value`] form) and add them into this [`Entities`] structure, re-computing the transitive closure
///
/// If a `schema` is provided, this will inform the parsing: for instance, it
/// will allow `__entity` and `__extn` escapes to be implicit, and it will error
/// if attributes have the wrong types (e.g., string instead of integer).
///
/// Re-computing the transitive closure can be expensive, so it is advised to not call this method in a loop
pub fn add_entities_from_json_value(
self,
json: serde_json::Value,
schema: Option<&Schema>,
) -> Result<Self, EntitiesError> {
let eparser = entities::EntityJsonParser::new(
schema.map(|s| cedar_policy_validator::CoreSchema::new(&s.0)),
Extensions::all_available(),
entities::TCComputation::ComputeNow,
);
let new_entities = eparser
.iter_from_json_value(json)?
.collect::<Result<Vec<_>, _>>()?;
Ok(Self(self.0.add_entities(
new_entities,
entities::TCComputation::ComputeNow,
)?))
}
/// Parse an entities JSON file (in [`std::io::Read`] form) and add them into this [`Entities`] structure, re-computing the transitive closure
///
/// If a `schema` is provided, this will inform the parsing: for instance, it
/// will allow `__entity` and `__extn` escapes to be implicit, and it will error
/// if attributes have the wrong types (e.g., string instead of integer).
///
/// Re-computing the transitive closure can be expensive, so it is advised to not call this method in a loop
pub fn add_entities_from_json_file(
self,
json: impl std::io::Read,
schema: Option<&Schema>,
) -> Result<Self, EntitiesError> {
let eparser = entities::EntityJsonParser::new(
schema.map(|s| cedar_policy_validator::CoreSchema::new(&s.0)),
Extensions::all_available(),
entities::TCComputation::ComputeNow,
);
let new_entities = eparser
.iter_from_json_file(json)?
.collect::<Result<Vec<_>, _>>()?;
Ok(Self(self.0.add_entities(
new_entities,
entities::TCComputation::ComputeNow,
)?))
}
/// Parse an entities JSON file (in `&str` form) into an `Entities` object
///
/// If a `schema` is provided, this will inform the parsing: for instance, it
/// will allow `__entity` and `__extn` escapes to be implicit, and it will error
/// if attributes have the wrong types (e.g., string instead of integer).
/// ```
/// use std::collections::HashMap;
/// use std::str::FromStr;
/// # use cedar_policy::{Entities, EntityId, EntityTypeName, EntityUid, EvalResult, Request,PolicySet};
/// let data =r#"
/// [
/// {
/// "uid": {"type":"User","id":"alice"},
/// "attrs": {
/// "age":19,
/// "ip_addr":{"__extn":{"fn":"ip", "arg":"10.0.1.101"}}
/// },
/// "parents": [{"type":"Group","id":"admin"}]
/// },
/// {
/// "uid": {"type":"Groupd","id":"admin"},
/// "attrs": {},
/// "parents": []
/// }
/// ]
/// "#;
/// let entities = Entities::from_json_str(data, None).unwrap();
/// let eid = EntityId::from_str("alice").unwrap();
/// let type_name: EntityTypeName = EntityTypeName::from_str("User").unwrap();
/// let euid = EntityUid::from_type_name_and_id(type_name, eid);
/// let entity = entities.get(&euid).unwrap();
/// assert_eq!(entity.attr("age").unwrap(), Ok(EvalResult::Long(19)));
/// let ip = entity.attr("ip_addr").unwrap().unwrap();
/// assert_eq!(ip, EvalResult::ExtensionValue("10.0.1.101/32".to_string()));
/// ```
pub fn from_json_str(
json: &str,
schema: Option<&Schema>,
) -> Result<Self, entities::EntitiesError> {
let eparser = entities::EntityJsonParser::new(
schema.map(|s| cedar_policy_validator::CoreSchema::new(&s.0)),
Extensions::all_available(),
entities::TCComputation::ComputeNow,
);
eparser.from_json_str(json).map(Entities)
}
/// Parse an entities JSON file (in `serde_json::Value` form) into an
/// `Entities` object
///
/// If a `schema` is provided, this will inform the parsing: for instance, it
/// will allow `__entity` and `__extn` escapes to be implicit, and it will error
/// if attributes have the wrong types (e.g., string instead of integer).
/// ```
/// use std::collections::HashMap;
/// use std::str::FromStr;
/// # use cedar_policy::{Entities, EntityId, EntityTypeName, EntityUid, EvalResult, Request,PolicySet};
/// let data =serde_json::json!(
/// [
/// {
/// "uid": {"type":"User","id":"alice"},
/// "attrs": {
/// "age":19,
/// "ip_addr":{"__extn":{"fn":"ip", "arg":"10.0.1.101"}}
/// },
/// "parents": [{"type":"Group","id":"admin"}]
/// },
/// {
/// "uid": {"type":"Groupd","id":"admin"},
/// "attrs": {},
/// "parents": []
/// }
/// ]
/// );
/// let entities = Entities::from_json_value(data, None).unwrap();
/// ```
pub fn from_json_value(
json: serde_json::Value,
schema: Option<&Schema>,
) -> Result<Self, entities::EntitiesError> {
let eparser = entities::EntityJsonParser::new(
schema.map(|s| cedar_policy_validator::CoreSchema::new(&s.0)),
Extensions::all_available(),
entities::TCComputation::ComputeNow,
);
eparser.from_json_value(json).map(Entities)
}
/// Parse an entities JSON file (in `std::io::Read` form) into an `Entities`
/// object
///
/// If a `schema` is provided, this will inform the parsing: for instance, it
/// will allow `__entity` and `__extn` escapes to be implicit, and it will error
/// if attributes have the wrong types (e.g., string instead of integer).
pub fn from_json_file(
json: impl std::io::Read,
schema: Option<&Schema>,
) -> Result<Self, entities::EntitiesError> {
let eparser = entities::EntityJsonParser::new(
schema.map(|s| cedar_policy_validator::CoreSchema::new(&s.0)),
Extensions::all_available(),
entities::TCComputation::ComputeNow,
);
eparser.from_json_file(json).map(Entities)
}
/// Is entity `a` an ancestor of entity `b`?
/// Same semantics as `b in a` in the Cedar language
pub fn is_ancestor_of(&self, a: &EntityUid, b: &EntityUid) -> bool {
match self.0.entity(&b.0) {
Dereference::Data(b) => b.is_descendant_of(&a.0),
_ => a == b, // if b doesn't exist, `b in a` is only true if `b == a`
}
}
/// Get an iterator over the ancestors of the given Euid.
/// Returns `None` if the given `Euid` does not exist.
pub fn ancestors<'a>(
&'a self,
euid: &EntityUid,
) -> Option<impl Iterator<Item = &'a EntityUid>> {
let entity = match self.0.entity(&euid.0) {
Dereference::Residual(_) | Dereference::NoSuchEntity => None,
Dereference::Data(e) => Some(e),
}?;
Some(entity.ancestors().map(EntityUid::ref_cast))
}
/// Dump an `Entities` object into an entities JSON file.
///
/// The resulting JSON will be suitable for parsing in via
/// `from_json_*`, and will be parse-able even with no `Schema`.
///
/// To read an `Entities` object from an entities JSON file, use
/// `from_json_file`.
pub fn write_to_json(
&self,
f: impl std::io::Write,
) -> std::result::Result<(), entities::EntitiesError> {
self.0.write_to_json(f)
}
}
/// Authorizer object, which provides responses to authorization queries
#[repr(transparent)]
#[derive(Debug, RefCast)]
pub struct Authorizer(authorizer::Authorizer);
impl Default for Authorizer {
fn default() -> Self {
Self::new()
}
}
impl Authorizer {
/// Create a new `Authorizer`
/// ```
/// # use cedar_policy::{Authorizer, Context, Entities, EntityId, EntityTypeName,
/// # EntityUid, Request,PolicySet};
/// # use std::str::FromStr;
/// # // create a request
/// # let p_eid = EntityId::from_str("alice").unwrap();
/// # let p_name: EntityTypeName = EntityTypeName::from_str("User").unwrap();
/// # let p = EntityUid::from_type_name_and_id(p_name, p_eid);
/// #
/// # let a_eid = EntityId::from_str("view").unwrap();
/// # let a_name: EntityTypeName = EntityTypeName::from_str("Action").unwrap();
/// # let a = EntityUid::from_type_name_and_id(a_name, a_eid);
/// #
/// # let r_eid = EntityId::from_str("trip").unwrap();
/// # let r_name: EntityTypeName = EntityTypeName::from_str("Album").unwrap();
/// # let r = EntityUid::from_type_name_and_id(r_name, r_eid);
/// #
/// # let c = Context::empty();
/// #
/// # let request: Request = Request::new(Some(p), Some(a), Some(r), c);
/// #
/// # // create a policy
/// # let s = r#"permit(
/// # principal == User::"alice",
/// # action == Action::"view",
/// # resource == Album::"trip"
/// # )when{
/// # principal.ip_addr.isIpv4()
/// # };
/// # "#;
/// # let policy = PolicySet::from_str(s).expect("policy error");
/// # // create entities
/// # let e = r#"[
/// # {
/// # "uid": {"type":"User","id":"alice"},
/// # "attrs": {
/// # "age":19,
/// # "ip_addr":{"__extn":{"fn":"ip", "arg":"10.0.1.101"}}
/// # },
/// # "parents": []
/// # }
/// # ]"#;
/// # let entities = Entities::from_json_str(e, None).expect("entity error");
/// let authorizer = Authorizer::new();
/// let r = authorizer.is_authorized(&request, &policy, &entities);
/// ```
pub fn new() -> Self {
Self(authorizer::Authorizer::new())
}
/// Returns an authorization response for `r` with respect to the given
/// `PolicySet` and `Entities`.
///
/// The language spec and Dafny model give a precise definition of how this
/// is computed.
/// ```
/// use cedar_policy::{Authorizer,Context,Entities,EntityId,EntityTypeName,
/// EntityUid, Request,PolicySet};
/// use std::str::FromStr;
///
/// // create a request
/// let p_eid = EntityId::from_str("alice").unwrap();
/// let p_name: EntityTypeName = EntityTypeName::from_str("User").unwrap();
/// let p = EntityUid::from_type_name_and_id(p_name, p_eid);
///
/// let a_eid = EntityId::from_str("view").unwrap();
/// let a_name: EntityTypeName = EntityTypeName::from_str("Action").unwrap();
/// let a = EntityUid::from_type_name_and_id(a_name, a_eid);
///
/// let r_eid = EntityId::from_str("trip").unwrap();
/// let r_name: EntityTypeName = EntityTypeName::from_str("Album").unwrap();
/// let r = EntityUid::from_type_name_and_id(r_name, r_eid);
///
/// let c = Context::empty();
///
/// let request: Request = Request::new(Some(p), Some(a), Some(r), c);
///
/// // create a policy
/// let s = r#"
/// permit (
/// principal == User::"alice",
/// action == Action::"view",
/// resource == Album::"trip"
/// )
/// when { principal.ip_addr.isIpv4() };
/// "#;
/// let policy = PolicySet::from_str(s).expect("policy error");
/// // create entities
/// let e = r#"[
/// {
/// "uid": {"type":"User","id":"alice"},
/// "attrs": {
/// "age":19,
/// "ip_addr":{"__extn":{"fn":"ip", "arg":"10.0.1.101"}}
/// },
/// "parents": []
/// }
/// ]"#;
/// let entities = Entities::from_json_str(e, None).expect("entity error");
///
/// let authorizer = Authorizer::new();
/// let r = authorizer.is_authorized(&request, &policy, &entities);
/// println!("{:?}", r);
/// ```
pub fn is_authorized(&self, r: &Request, p: &PolicySet, e: &Entities) -> Response {
self.0.is_authorized(&r.0, &p.ast, &e.0).into()
}
/// A partially evaluated authorization request.
/// The Authorizer will attempt to make as much progress as possible in the presence of unknowns.
/// If the Authorizer can reach a response, it will return that response.
/// Otherwise, it will return a list of residual policies that still need to be evaluated.
#[cfg(feature = "partial-eval")]
pub fn is_authorized_partial(
&self,
query: &Request,
policy_set: &PolicySet,
entities: &Entities,
) -> PartialResponse {
let response = self
.0
.is_authorized_core(&query.0, &policy_set.ast, &entities.0);
match response {
authorizer::ResponseKind::FullyEvaluated(a) => PartialResponse::Concrete(a.into()),
authorizer::ResponseKind::Partial(p) => PartialResponse::Residual(p.into()),
}
}
}
/// Authorization response returned from the `Authorizer`
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Response {
/// Authorization decision
decision: Decision,
/// Diagnostics providing more information on how this decision was reached
diagnostics: Diagnostics,
}
/// Authorization response returned from `is_authorized_partial`.
/// It can either be a full concrete response, or a residual response.
#[cfg(feature = "partial-eval")]
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum PartialResponse {
/// A full, concrete response.
Concrete(Response),
/// A residual response. Determining the concrete response requires further processing.
Residual(ResidualResponse),
}
/// A residual response obtained from `is_authorized_partial`.
#[cfg(feature = "partial-eval")]
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct ResidualResponse {
/// Residual policies
residuals: PolicySet,
/// Diagnostics
diagnostics: Diagnostics,
}
/// Diagnostics providing more information on how a `Decision` was reached
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Diagnostics {
/// `PolicyId`s of the policies that contributed to the decision.
/// If no policies applied to the request, this set will be empty.
reason: HashSet<PolicyId>,
/// Errors that occurred during authorization. The errors should be
/// treated as unordered, since policies may be evaluated in any order.
errors: Vec<AuthorizationError>,
}
impl From<authorizer::Diagnostics> for Diagnostics {
fn from(diagnostics: authorizer::Diagnostics) -> Self {
Self {
reason: diagnostics.reason.into_iter().map(PolicyId).collect(),
errors: diagnostics.errors,
}
}
}
impl Diagnostics {
/// Get the policies that contributed to the decision
/// ```
/// # use cedar_policy::{Authorizer, Context, Decision, Entities, EntityId, EntityTypeName,
/// # EntityUid, Request,PolicySet};
/// # use std::str::FromStr;
/// # // create a request
/// # let p_eid = EntityId::from_str("alice").unwrap();
/// # let p_name: EntityTypeName = EntityTypeName::from_str("User").unwrap();
/// # let p = EntityUid::from_type_name_and_id(p_name, p_eid);
/// #
/// # let a_eid = EntityId::from_str("view").unwrap();
/// # let a_name: EntityTypeName = EntityTypeName::from_str("Action").unwrap();
/// # let a = EntityUid::from_type_name_and_id(a_name, a_eid);
/// #
/// # let r_eid = EntityId::from_str("trip").unwrap();
/// # let r_name: EntityTypeName = EntityTypeName::from_str("Album").unwrap();
/// # let r = EntityUid::from_type_name_and_id(r_name, r_eid);
/// #
/// # let c = Context::empty();
/// #
/// # let request: Request = Request::new(Some(p), Some(a), Some(r), c);
/// #
/// # // create a policy
/// # let s = r#"permit(
/// # principal == User::"alice",
/// # action == Action::"view",
/// # resource == Album::"trip"
/// # )when{
/// # principal.ip_addr.isIpv4()
/// # };
/// # "#;
/// # let policy = PolicySet::from_str(s).expect("policy error");
/// # // create entities
/// # let e = r#"[
/// # {
/// # "uid": {"type":"User","id":"alice"},
/// # "attrs": {
/// # "age":19,
/// # "ip_addr":{"__extn":{"fn":"ip", "arg":"10.0.1.101"}}
/// # },
/// # "parents": []
/// # }
/// # ]"#;
/// # let entities = Entities::from_json_str(e, None).expect("entity error");
/// let authorizer = Authorizer::new();
/// let response = authorizer.is_authorized(&request, &policy, &entities);
/// match response.decision() {
/// Decision::Allow => println!("ALLOW"),
/// Decision::Deny => println!("DENY"),
/// }
/// println!("note: this decision was due to the following policies:");
/// for reason in response.diagnostics().reason() {
/// println!("{}", reason);
/// }
/// ```
pub fn reason(&self) -> impl Iterator<Item = &PolicyId> {
self.reason.iter()
}
/// Get the errors
/// ```
/// # use cedar_policy::{Authorizer, Context, Decision, Entities, EntityId, EntityTypeName,
/// # EntityUid, Request,PolicySet};
/// # use std::str::FromStr;
/// # // create a request
/// # let p_eid = EntityId::from_str("alice").unwrap();
/// # let p_name: EntityTypeName = EntityTypeName::from_str("User").unwrap();
/// # let p = EntityUid::from_type_name_and_id(p_name, p_eid);
/// #
/// # let a_eid = EntityId::from_str("view").unwrap();
/// # let a_name: EntityTypeName = EntityTypeName::from_str("Action").unwrap();
/// # let a = EntityUid::from_type_name_and_id(a_name, a_eid);
/// #
/// # let r_eid = EntityId::from_str("trip").unwrap();
/// # let r_name: EntityTypeName = EntityTypeName::from_str("Album").unwrap();
/// # let r = EntityUid::from_type_name_and_id(r_name, r_eid);
/// #
/// # let c = Context::empty();
/// #
/// # let request: Request = Request::new(Some(p), Some(a), Some(r), c);
/// #
/// # // create a policy
/// # let s = r#"permit(
/// # principal == User::"alice",
/// # action == Action::"view",
/// # resource == Album::"trip"
/// # )when{
/// # principal.ip_addr.isIpv4()
/// # };
/// # "#;
/// # let policy = PolicySet::from_str(s).expect("policy error");
/// # // create entities
/// # let e = r#"[
/// # {
/// # "uid": {"type":"User","id":"alice"},
/// # "attrs": {
/// # "age":19,
/// # "ip_addr":{"__extn":{"fn":"ip", "arg":"10.0.1.101"}}
/// # },
/// # "parents": []
/// # }
/// # ]"#;
/// # let entities = Entities::from_json_str(e, None).expect("entity error");
/// let authorizer = Authorizer::new();
/// let response = authorizer.is_authorized(&request, &policy, &entities);
/// match response.decision() {
/// Decision::Allow => println!("ALLOW"),
/// Decision::Deny => println!("DENY"),
/// }
/// for err in response.diagnostics().errors() {
/// println!("{}", err);
/// }
/// ```
pub fn errors(&self) -> impl Iterator<Item = &AuthorizationError> + '_ {
self.errors.iter()
}
}
impl Response {
/// Create a new `Response`
pub fn new(
decision: Decision,
reason: HashSet<PolicyId>,
errors: Vec<AuthorizationError>,
) -> Self {
Self {
decision,
diagnostics: Diagnostics { reason, errors },
}
}
/// Get the authorization decision
pub fn decision(&self) -> Decision {
self.decision
}
/// Get the authorization diagnostics
pub fn diagnostics(&self) -> &Diagnostics {
&self.diagnostics
}
}
impl From<authorizer::Response> for Response {
fn from(a: authorizer::Response) -> Self {
Self {
decision: a.decision,
diagnostics: a.diagnostics.into(),
}
}
}
#[cfg(feature = "partial-eval")]
impl ResidualResponse {
/// Create a new `ResidualResponse`
pub fn new(
residuals: PolicySet,
reason: HashSet<PolicyId>,
errors: Vec<AuthorizationError>,
) -> Self {
Self {
residuals,
diagnostics: Diagnostics { reason, errors },
}
}
/// Get the residual policies needed to reach an authorization decision.
pub fn residuals(&self) -> &PolicySet {
&self.residuals
}
/// Get the authorization diagnostics
pub fn diagnostics(&self) -> &Diagnostics {
&self.diagnostics
}
}
#[cfg(feature = "partial-eval")]
impl From<authorizer::PartialResponse> for ResidualResponse {
fn from(p: authorizer::PartialResponse) -> Self {
Self {
residuals: PolicySet::from_ast(p.residuals),
diagnostics: p.diagnostics.into(),
}
}
}
/// Used to select how a policy will be validated.
#[derive(Default, Eq, PartialEq, Copy, Clone, Debug)]
#[non_exhaustive]
pub enum ValidationMode {
/// Validate that policies do not contain any type errors, and additionally
/// have a restricted form which is amenable for analysis.
#[default]
Strict,
/// Validate that policies do not contain any type errors.
Permissive,
}
impl From<ValidationMode> for cedar_policy_validator::ValidationMode {
fn from(mode: ValidationMode) -> Self {
match mode {
ValidationMode::Strict => Self::Strict,
ValidationMode::Permissive => Self::Permissive,
}
}
}
/// Validator object, which provides policy validation and typechecking.
#[repr(transparent)]
#[derive(Debug, RefCast)]
pub struct Validator(cedar_policy_validator::Validator);
impl Validator {
/// Construct a new `Validator` to validate policies using the given
/// `Schema`.
pub fn new(schema: Schema) -> Self {
Self(cedar_policy_validator::Validator::new(schema.0))
}
/// Validate all policies in a policy set, collecting all validation errors
/// found into the returned `ValidationResult`. Each error is returned together with the
/// policy id of the policy where the error was found. If a policy id
/// included in the input policy set does not appear in the output iterator, then
/// that policy passed the validator. If the function `validation_passed`
/// returns true, then there were no validation errors found, so all
/// policies in the policy set have passed the validator.
pub fn validate<'a>(
&'a self,
pset: &'a PolicySet,
mode: ValidationMode,
) -> ValidationResult<'a> {
ValidationResult::from(self.0.validate(&pset.ast, mode.into()))
}
}
/// Contains all the type information used to construct a `Schema` that can be
/// used to validate a policy.
#[derive(Debug)]
pub struct SchemaFragment(cedar_policy_validator::ValidatorSchemaFragment);
impl SchemaFragment {
/// Extract namespaces defined in this `SchemaFragment`. Each namespace
/// entry defines the name of the namespace and the entity types and actions
/// that exist in the namespace.
pub fn namespaces(&self) -> impl Iterator<Item = Option<EntityNamespace>> + '_ {
self.0
.namespaces()
.map(|ns| ns.as_ref().map(|ns| EntityNamespace(ns.clone())))
}
/// Create an `SchemaFragment` from a JSON value (which should be an
/// object of the shape required for Cedar schemas).
pub fn from_json_value(json: serde_json::Value) -> Result<Self, SchemaError> {
Ok(Self(
cedar_policy_validator::SchemaFragment::from_json_value(json)?.try_into()?,
))
}
/// Create a `SchemaFragment` directly from a file.
pub fn from_file(file: impl std::io::Read) -> Result<Self, SchemaError> {
Ok(Self(
cedar_policy_validator::SchemaFragment::from_file(file)?.try_into()?,
))
}
}
impl TryInto<Schema> for SchemaFragment {
type Error = SchemaError;
/// Convert `SchemaFragment` into a `Schema`. To build the `Schema` we
/// need to have all entity types defined, so an error will be returned if
/// any undeclared entity types are referenced in the schema fragment.
fn try_into(self) -> Result<Schema, Self::Error> {
Ok(Schema(
cedar_policy_validator::ValidatorSchema::from_schema_fragments([self.0])?,
))
}
}
impl FromStr for SchemaFragment {
type Err = SchemaError;
/// Construct `SchemaFragment` from a string containing a schema formatted
/// in the cedar schema format. This can fail if the string is not valid
/// JSON, or if the JSON structure does not form a valid schema. This
/// function does not check for consistency in the schema (e.g., references
/// to undefined entities) because this is not required until a `Schema` is
/// constructed.
fn from_str(src: &str) -> Result<Self, Self::Err> {
Ok(Self(
serde_json::from_str::<cedar_policy_validator::SchemaFragment>(src)
.map_err(cedar_policy_validator::SchemaError::from)?
.try_into()?,
))
}
}
/// Object containing schema information used by the validator.
#[repr(transparent)]
#[derive(Debug, Clone, RefCast)]
pub struct Schema(pub(crate) cedar_policy_validator::ValidatorSchema);
impl FromStr for Schema {
type Err = SchemaError;
/// Construct a schema from a string containing a schema formatted in the
/// Cedar schema format. This can fail if it is not possible to parse a
/// schema from the strings, or if errors in values in the schema are
/// uncovered after parsing. For instance, when an entity attribute name is
/// found to not be a valid attribute name according to the Cedar
/// grammar.
fn from_str(schema_src: &str) -> Result<Self, Self::Err> {
Ok(Self(schema_src.parse()?))
}
}
impl Schema {
/// Create a `Schema` from multiple `SchemaFragment`. The individual
/// fragments may references entity types that are not declared in that
/// fragment, but all referenced entity types must be declared in some
/// fragment.
pub fn from_schema_fragments(