-
Notifications
You must be signed in to change notification settings - Fork 171
Expand file tree
/
Copy pathpolicy.rs
More file actions
2516 lines (2250 loc) · 84.1 KB
/
Copy pathpolicy.rs
File metadata and controls
2516 lines (2250 loc) · 84.1 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 crate::ast::*;
use crate::parser::{AsLocRef, IntoMaybeLoc, Loc, MaybeLoc};
use annotation::{Annotation, Annotations};
use educe::Educe;
use itertools::Itertools;
use miette::Diagnostic;
use nonempty::{nonempty, NonEmpty};
use serde::{Deserialize, Serialize};
use smol_str::SmolStr;
use std::{
collections::{HashMap, HashSet},
str::FromStr,
sync::Arc,
};
use thiserror::Error;
#[cfg(feature = "wasm")]
extern crate tsify;
macro_rules! cfg_tolerant_ast {
($($item:item)*) => {
$(
#[cfg(feature = "tolerant-ast")]
$item
)*
};
}
cfg_tolerant_ast! {
use super::expr_allows_errors::AstExprErrorKind;
use crate::ast::expr_allows_errors::ExprWithErrsBuilder;
use crate::expr_builder::ExprBuilder;
use crate::parser::err::ParseErrors;
use crate::parser::err::ToASTError;
use crate::parser::err::ToASTErrorKind;
static DEFAULT_ANNOTATIONS: std::sync::LazyLock<Arc<Annotations>> =
std::sync::LazyLock::new(|| Arc::new(Annotations::default()));
static DEFAULT_PRINCIPAL_CONSTRAINT: std::sync::LazyLock<PrincipalConstraint> =
std::sync::LazyLock::new(PrincipalConstraint::any);
static DEFAULT_RESOURCE_CONSTRAINT: std::sync::LazyLock<ResourceConstraint> =
std::sync::LazyLock::new(ResourceConstraint::any);
static DEFAULT_ACTION_CONSTRAINT: std::sync::LazyLock<ActionConstraint> =
std::sync::LazyLock::new(ActionConstraint::any);
static DEFAULT_ERROR_EXPR: std::sync::LazyLock<Arc<Expr>> = std::sync::LazyLock::new(|| {
// Non scope constraint expression of an Error policy should also be an error
// This const represents an error expression that is part of an Error policy
// PANIC SAFETY: Infallible error type - can never fail
#[allow(clippy::unwrap_used)]
Arc::new(
<ExprWithErrsBuilder as ExprBuilder>::new()
.error(ParseErrors::singleton(ToASTError::new(
ToASTErrorKind::ASTErrorNode,
Loc::new(0..1, "ASTErrorNode".into()).into_maybe_loc(),
)))
.unwrap(),
)
});
}
/// Top level structure for a policy template.
/// Contains both the AST for template, and the list of open slots in the template.
///
/// Note that this "template" may have no slots, in which case this `Template` represents a static policy
#[derive(Clone, Hash, Eq, PartialEq, Debug)]
pub struct Template {
body: TemplateBody,
/// INVARIANT (slot cache correctness): This Vec must contain _all_ of the open slots in `body`
/// This is maintained by the only public constructors: `new()`, `new_shared()`, and `link_static_policy()`
///
/// Note that `slots` may be empty, in which case this `Template` represents a static policy
slots: Vec<Slot>,
}
impl From<Template> for TemplateBody {
fn from(val: Template) -> Self {
val.body
}
}
impl Template {
/// Checks the invariant (slot cache correctness)
///
/// This function is a no-op in release builds, but checks the invariant (and panics if it fails) in debug builds.
pub fn check_invariant(&self) {
#[cfg(debug_assertions)]
{
for slot in self.body.condition().slots() {
assert!(self.slots.contains(&slot));
}
for slot in self.slots() {
assert!(self.body.condition().slots().contains(slot));
}
}
}
/// Construct a `Template` from its components
#[allow(clippy::too_many_arguments)]
pub fn new(
id: PolicyID,
loc: MaybeLoc,
annotations: Annotations,
effect: Effect,
principal_constraint: PrincipalConstraint,
action_constraint: ActionConstraint,
resource_constraint: ResourceConstraint,
non_scope_constraint: Expr,
) -> Self {
let body = TemplateBody::new(
id,
loc,
annotations,
effect,
principal_constraint,
action_constraint,
resource_constraint,
non_scope_constraint,
);
// INVARIANT (slot cache correctness)
// This invariant is maintained in the body of the From impl
Template::from(body)
}
#[cfg(feature = "tolerant-ast")]
/// Generate a template representing a policy that is unparsable
pub fn error(id: PolicyID, loc: MaybeLoc) -> Self {
let body = TemplateBody::error(id, loc);
Template::from(body)
}
/// Construct a template from an expression/annotations that are already [`std::sync::Arc`] allocated
#[allow(clippy::too_many_arguments)]
pub fn new_shared(
id: PolicyID,
loc: MaybeLoc,
annotations: Arc<Annotations>,
effect: Effect,
principal_constraint: PrincipalConstraint,
action_constraint: ActionConstraint,
resource_constraint: ResourceConstraint,
non_scope_constraint: Arc<Expr>,
) -> Self {
let body = TemplateBody::new_shared(
id,
loc,
annotations,
effect,
principal_constraint,
action_constraint,
resource_constraint,
non_scope_constraint,
);
// INVARIANT (slot cache correctness)
// This invariant is maintained in the body of the From impl
Template::from(body)
}
/// Get the principal constraint on the body
pub fn principal_constraint(&self) -> &PrincipalConstraint {
self.body.principal_constraint()
}
/// Get the action constraint on the body
pub fn action_constraint(&self) -> &ActionConstraint {
self.body.action_constraint()
}
/// Get the resource constraint on the body
pub fn resource_constraint(&self) -> &ResourceConstraint {
self.body.resource_constraint()
}
/// Get the non-scope constraint on the body
pub fn non_scope_constraints(&self) -> &Expr {
self.body.non_scope_constraints()
}
/// Get Arc to non-scope constraint on the body
pub fn non_scope_constraints_arc(&self) -> &Arc<Expr> {
self.body.non_scope_constraints_arc()
}
/// Get the PolicyID of this template
pub fn id(&self) -> &PolicyID {
self.body.id()
}
/// Clone this Policy with a new ID
pub fn new_id(&self, id: PolicyID) -> Self {
Template {
body: self.body.new_id(id),
slots: self.slots.clone(),
}
}
/// Get the location of this policy
pub fn loc(&self) -> Option<&Loc> {
self.body.loc()
}
/// Get the `Effect` (`Permit` or `Deny`) of this template
pub fn effect(&self) -> Effect {
self.body.effect()
}
/// Get data from an annotation.
pub fn annotation(&self, key: &AnyId) -> Option<&Annotation> {
self.body.annotation(key)
}
/// Get all annotation data.
pub fn annotations(&self) -> impl Iterator<Item = (&AnyId, &Annotation)> {
self.body.annotations()
}
/// Get [`Arc`] owning the annotation data.
pub fn annotations_arc(&self) -> &Arc<Annotations> {
self.body.annotations_arc()
}
/// Get the condition expression of this template.
///
/// This will be a conjunction of the template's scope constraints (on
/// principal, resource, and action); the template's "when" conditions; and
/// the negation of each of the template's "unless" conditions.
pub fn condition(&self) -> Expr {
self.body.condition()
}
/// List of open slots in this template
pub fn slots(&self) -> impl Iterator<Item = &Slot> {
self.slots.iter()
}
/// Check if this template is a static policy
///
/// Static policies can be linked without any slots,
/// and all links will be identical.
pub fn is_static(&self) -> bool {
self.slots.is_empty()
}
/// Ensure that every slot in the template is bound by values,
/// and that no extra values are bound in values
/// This upholds invariant (values total map)
pub fn check_binding(
template: &Template,
values: &HashMap<SlotId, EntityUID>,
) -> Result<(), LinkingError> {
// Verify all slots bound
let unbound = template
.slots
.iter()
.filter(|slot| !values.contains_key(&slot.id))
.collect::<Vec<_>>();
let extra = values
.iter()
.filter_map(|(slot, _)| {
if !template
.slots
.iter()
.any(|template_slot| template_slot.id == *slot)
{
Some(slot)
} else {
None
}
})
.collect::<Vec<_>>();
if unbound.is_empty() && extra.is_empty() {
Ok(())
} else {
Err(LinkingError::from_unbound_and_extras(
unbound.into_iter().map(|slot| slot.id),
extra.into_iter().copied(),
))
}
}
/// Attempt to create a template-linked policy from this template.
/// This will fail if values for all open slots are not given.
/// `new_instance_id` is the `PolicyId` for the created template-linked policy.
pub fn link(
template: Arc<Template>,
new_id: PolicyID,
values: HashMap<SlotId, EntityUID>,
) -> Result<Policy, LinkingError> {
// INVARIANT (policy total map) Relies on check_binding to uphold the invariant
Template::check_binding(&template, &values)
.map(|_| Policy::new(template, Some(new_id), values))
}
/// Take a static policy and create a template and a template-linked policy for it.
/// They will share the same ID
pub fn link_static_policy(p: StaticPolicy) -> (Arc<Template>, Policy) {
let body: TemplateBody = p.into();
// INVARIANT (slot cache correctness):
// StaticPolicy by invariant (inline policy correctness)
// can have no slots, so it is safe to make `slots` the empty vec
let t = Arc::new(Self {
body,
slots: vec![],
});
t.check_invariant();
let p = Policy::new(Arc::clone(&t), None, HashMap::new());
(t, p)
}
}
impl From<TemplateBody> for Template {
fn from(body: TemplateBody) -> Self {
// INVARIANT: (slot cache correctness)
// Pull all the slots out of the template body's condition.
let slots = body.condition().slots().collect::<Vec<_>>();
Self { body, slots }
}
}
impl std::fmt::Display for Template {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.body)
}
}
/// Errors linking templates
#[derive(Debug, Clone, PartialEq, Eq, Diagnostic, Error)]
pub enum LinkingError {
/// An error with the slot arguments provided
// INVARIANT: `unbound_values` and `extra_values` can't both be empty
#[error(fmt = describe_arity_error)]
ArityError {
/// Error for when some Slots were not provided values
unbound_values: Vec<SlotId>,
/// Error for when more values than Slots are provided
extra_values: Vec<SlotId>,
},
/// The attempted linking failed as the template did not exist.
#[error("failed to find a template with id `{id}`")]
NoSuchTemplate {
/// [`PolicyID`] of the template we failed to find
id: PolicyID,
},
/// The new instance conflicts with an existing [`PolicyID`].
#[error("template-linked policy id `{id}` conflicts with an existing policy id")]
PolicyIdConflict {
/// [`PolicyID`] where the conflict exists
id: PolicyID,
},
}
impl LinkingError {
fn from_unbound_and_extras(
unbound: impl Iterator<Item = SlotId>,
extra: impl Iterator<Item = SlotId>,
) -> Self {
Self::ArityError {
unbound_values: unbound.collect(),
extra_values: extra.collect(),
}
}
}
fn describe_arity_error(
unbound_values: &[SlotId],
extra_values: &[SlotId],
fmt: &mut std::fmt::Formatter<'_>,
) -> std::fmt::Result {
match (unbound_values.len(), extra_values.len()) {
// PANIC SAFETY 0,0 case is not an error
#[allow(clippy::unreachable)]
(0,0) => unreachable!(),
(_unbound, 0) => write!(fmt, "the following slots were not provided as arguments: {}", unbound_values.iter().join(",")),
(0, _extra) => write!(fmt, "the following slots were provided as arguments, but did not exist in the template: {}", extra_values.iter().join(",")),
(_unbound, _extra) => write!(fmt, "the following slots were not provided as arguments: {}. The following slots were provided as arguments, but did not exist in the template: {}", unbound_values.iter().join(","), extra_values.iter().join(",")),
}
}
/// A Policy that contains:
/// - a pointer to its template
/// - a link ID (unless it's a static policy)
/// - the bound values for slots in the template
///
/// Policies are not serializable (due to the pointer), and can be serialized
/// by converting to/from LiteralPolicy
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct Policy {
/// Reference to the template
template: Arc<Template>,
/// Id of this link
///
/// None in the case that this is an instance of a Static Policy
link: Option<PolicyID>,
// INVARIANT (values total map)
// All of the slots in `template` MUST be bound by `values`
//
/// values the slots are bound to.
/// The constructor `new` is only visible in this module,
/// so it is the responsibility of callers to maintain
values: HashMap<SlotId, EntityUID>,
}
impl Policy {
/// Link a policy to its template
/// INVARIANT (values total map):
/// `values` must bind every open slot in `template`
fn new(template: Arc<Template>, link_id: Option<PolicyID>, values: SlotEnv) -> Self {
#[cfg(debug_assertions)]
{
// PANIC SAFETY: asserts (value total map invariant) which is justified at call sites
#[allow(clippy::expect_used)]
Template::check_binding(&template, &values).expect("(values total map) does not hold!");
}
Self {
template,
link: link_id,
values,
}
}
/// Build a policy with a given effect, given when clause, and unconstrained scope variables
pub fn from_when_clause(effect: Effect, when: Expr, id: PolicyID, loc: MaybeLoc) -> Self {
Self::from_when_clause_annos(
effect,
Arc::new(when),
id,
loc,
Arc::new(Annotations::default()),
)
}
/// Build a policy with a given effect, given when clause, and unconstrained scope variables
pub fn from_when_clause_annos(
effect: Effect,
when: Arc<Expr>,
id: PolicyID,
loc: MaybeLoc,
annotations: Arc<Annotations>,
) -> Self {
let t = Template::new_shared(
id,
loc,
annotations,
effect,
PrincipalConstraint::any(),
ActionConstraint::any(),
ResourceConstraint::any(),
when,
);
Self::new(Arc::new(t), None, SlotEnv::new())
}
/// Get pointer to the template for this policy
pub fn template(&self) -> &Template {
&self.template
}
/// Get pointer to the template for this policy, as an `Arc`
pub(crate) fn template_arc(&self) -> Arc<Template> {
Arc::clone(&self.template)
}
/// Get the effect (forbid or permit) of this policy.
pub fn effect(&self) -> Effect {
self.template.effect()
}
/// Get data from an annotation.
pub fn annotation(&self, key: &AnyId) -> Option<&Annotation> {
self.template.annotation(key)
}
/// Get all annotation data.
pub fn annotations(&self) -> impl Iterator<Item = (&AnyId, &Annotation)> {
self.template.annotations()
}
/// Get [`Arc`] owning annotation data.
pub fn annotations_arc(&self) -> &Arc<Annotations> {
self.template.annotations_arc()
}
/// Get the principal constraint for this policy.
///
/// By the invariant, this principal constraint will not contain
/// (unresolved) slots, so you will not get `EntityReference::Slot` anywhere
/// in it.
pub fn principal_constraint(&self) -> PrincipalConstraint {
let constraint = self.template.principal_constraint().clone();
match self.values.get(&SlotId::principal()) {
None => constraint,
Some(principal) => constraint.with_filled_slot(Arc::new(principal.clone())),
}
}
/// Get the action constraint for this policy.
pub fn action_constraint(&self) -> &ActionConstraint {
self.template.action_constraint()
}
/// Get the resource constraint for this policy.
///
/// By the invariant, this resource constraint will not contain
/// (unresolved) slots, so you will not get `EntityReference::Slot` anywhere
/// in it.
pub fn resource_constraint(&self) -> ResourceConstraint {
let constraint = self.template.resource_constraint().clone();
match self.values.get(&SlotId::resource()) {
None => constraint,
Some(resource) => constraint.with_filled_slot(Arc::new(resource.clone())),
}
}
/// Get the non-scope constraints for the policy
pub fn non_scope_constraints(&self) -> &Expr {
self.template.non_scope_constraints()
}
/// Get the [`Arc`] owning non-scope constraints for the policy
pub fn non_scope_constraints_arc(&self) -> &Arc<Expr> {
self.template.non_scope_constraints_arc()
}
/// Get the expression that represents this policy.
pub fn condition(&self) -> Expr {
self.template.condition()
}
/// Get the mapping from SlotIds to EntityUIDs for this policy. (This will
/// be empty for inline policies.)
pub fn env(&self) -> &SlotEnv {
&self.values
}
/// Get the ID of this policy.
pub fn id(&self) -> &PolicyID {
self.link.as_ref().unwrap_or_else(|| self.template.id())
}
/// Clone this policy or instance with a new ID
pub fn new_id(&self, id: PolicyID) -> Self {
match self.link {
None => Policy {
template: Arc::new(self.template.new_id(id)),
link: None,
values: self.values.clone(),
},
Some(_) => Policy {
template: self.template.clone(),
link: Some(id),
values: self.values.clone(),
},
}
}
/// Get the location of this policy
pub fn loc(&self) -> Option<&Loc> {
self.template.loc()
}
/// Returns true if this policy is an inline policy
pub fn is_static(&self) -> bool {
self.link.is_none()
}
/// Returns all the unknown entities in the policy during evaluation
pub fn unknown_entities(&self) -> HashSet<EntityUID> {
self.condition()
.unknowns()
.filter_map(
|Unknown {
name,
type_annotation,
}| {
if matches!(type_annotation, Some(Type::Entity { .. })) {
EntityUID::from_str(name.as_str()).ok()
} else {
None
}
},
)
.collect()
}
}
impl std::fmt::Display for Policy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.is_static() {
write!(f, "{}", self.template())
} else {
write!(
f,
"Template Instance of {}, slots: [{}]",
self.template().id(),
display_slot_env(self.env())
)
}
}
}
/// Map from Slot Ids to Entity UIDs which fill the slots
pub type SlotEnv = HashMap<SlotId, EntityUID>;
/// Represents either a static policy or a template linked policy.
///
/// Contains less rich information than `Policy`. In particular, this form is
/// easier to convert to/from the Protobuf representation of a `Policy`, because
/// it simply refers to the `Template` by its Id and does not contain a
/// reference to the `Template` itself.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LiteralPolicy {
/// ID of the template this policy is an instance of
template_id: PolicyID,
/// ID of this link.
/// This is `None` for static policies, and the static policy ID is defined
/// as the `template_id`
link_id: Option<PolicyID>,
/// Values of the slots
values: SlotEnv,
}
impl LiteralPolicy {
/// Create a `LiteralPolicy` representing a static policy with the given ID.
///
/// The policy set should also contain a (zero-slot) `Template` with the given ID.
pub fn static_policy(template_id: PolicyID) -> Self {
Self {
template_id,
link_id: None,
values: SlotEnv::new(),
}
}
/// Create a `LiteralPolicy` representing a template-linked policy.
///
/// The policy set should also contain the associated `Template`.
pub fn template_linked_policy(
template_id: PolicyID,
link_id: PolicyID,
values: SlotEnv,
) -> Self {
Self {
template_id,
link_id: Some(link_id),
values,
}
}
/// Get the `EntityUID` associated with the given `SlotId`, if it exists
pub fn value(&self, slot: &SlotId) -> Option<&EntityUID> {
self.values.get(slot)
}
}
// Can we verify the hash property?
impl std::hash::Hash for LiteralPolicy {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.template_id.hash(state);
// this shouldn't be a performance issue as these vectors should be small
let mut buf = self.values.iter().collect::<Vec<_>>();
buf.sort();
for (id, euid) in buf {
id.hash(state);
euid.hash(state);
}
}
}
// These would be great as property tests
#[cfg(test)]
mod hashing_tests {
use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use super::*;
fn compute_hash(ir: &LiteralPolicy) -> u64 {
let mut s = DefaultHasher::new();
ir.hash(&mut s);
s.finish()
}
fn build_template_linked_policy() -> LiteralPolicy {
let mut map = HashMap::new();
map.insert(SlotId::principal(), EntityUID::with_eid("eid"));
LiteralPolicy {
template_id: PolicyID::from_string("template"),
link_id: Some(PolicyID::from_string("id")),
values: map,
}
}
#[test]
fn hash_property_instances() {
let a = build_template_linked_policy();
let b = build_template_linked_policy();
assert_eq!(a, b);
assert_eq!(compute_hash(&a), compute_hash(&b));
}
}
/// Errors that can happen during policy reification
#[derive(Debug, Diagnostic, Error)]
pub enum ReificationError {
/// The [`PolicyID`] linked to did not exist
#[error("the id linked to does not exist")]
NoSuchTemplate(PolicyID),
/// Error linking the policy
#[error(transparent)]
#[diagnostic(transparent)]
Linking(#[from] LinkingError),
}
impl LiteralPolicy {
/// Attempt to reify this template linked policy.
/// Ensures the linked template actually exists, replaces the id with a reference to the underlying template.
/// Fails if the template does not exist.
/// Consumes the policy.
pub fn reify(
self,
templates: &HashMap<PolicyID, Arc<Template>>,
) -> Result<Policy, ReificationError> {
let template = templates
.get(&self.template_id)
.ok_or_else(|| ReificationError::NoSuchTemplate(self.template_id().clone()))?;
// INVARIANT (values total map)
Template::check_binding(template, &self.values).map_err(ReificationError::Linking)?;
Ok(Policy::new(template.clone(), self.link_id, self.values))
}
/// Lookup the euid bound by a SlotId
pub fn get(&self, id: &SlotId) -> Option<&EntityUID> {
self.values.get(id)
}
/// Get the [`PolicyID`] of this static or template-linked policy.
pub fn id(&self) -> &PolicyID {
self.link_id.as_ref().unwrap_or(&self.template_id)
}
/// Get the [`PolicyID`] of the template associated with this policy.
///
/// For static policies, this is just the static policy ID.
pub fn template_id(&self) -> &PolicyID {
&self.template_id
}
/// Is this a static policy
pub fn is_static(&self) -> bool {
self.link_id.is_none()
}
}
fn display_slot_env(env: &SlotEnv) -> String {
env.iter()
.map(|(slot, value)| format!("{slot} -> {value}"))
.join(",")
}
impl std::fmt::Display for LiteralPolicy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.is_static() {
write!(f, "Static policy w/ ID {}", self.template_id())
} else {
write!(
f,
"Template linked policy of {}, slots: [{}]",
self.template_id(),
display_slot_env(&self.values),
)
}
}
}
impl From<Policy> for LiteralPolicy {
fn from(p: Policy) -> Self {
Self {
template_id: p.template.id().clone(),
link_id: p.link,
values: p.values,
}
}
}
/// Static Policies are policy that do not come from templates.
/// They have the same structure as a template definition, but cannot contain slots
// INVARIANT: (Static Policy Correctness): A Static Policy TemplateBody must have zero slots
#[derive(Clone, Hash, Eq, PartialEq, Debug)]
pub struct StaticPolicy(TemplateBody);
impl StaticPolicy {
/// Get the `Id` of this policy.
pub fn id(&self) -> &PolicyID {
self.0.id()
}
/// Clone this policy with a new `Id`.
pub fn new_id(&self, id: PolicyID) -> Self {
StaticPolicy(self.0.new_id(id))
}
/// Get the location of this policy
pub fn loc(&self) -> Option<&Loc> {
self.0.loc()
}
/// Get the `Effect` of this policy.
pub fn effect(&self) -> Effect {
self.0.effect()
}
/// Get data from an annotation.
pub fn annotation(&self, key: &AnyId) -> Option<&Annotation> {
self.0.annotation(key)
}
/// Get all annotation data.
pub fn annotations(&self) -> impl Iterator<Item = (&AnyId, &Annotation)> {
self.0.annotations()
}
/// Get the `principal` scope constraint of this policy.
pub fn principal_constraint(&self) -> &PrincipalConstraint {
self.0.principal_constraint()
}
/// Get the `principal` scope constraint as an expression.
/// This will be a boolean-valued expression: either `true` (if the policy
/// just has `principal,`), or an equality or hierarchy constraint
pub fn principal_constraint_expr(&self) -> Expr {
self.0.principal_constraint_expr()
}
/// Get the `action` scope constraint of this policy.
pub fn action_constraint(&self) -> &ActionConstraint {
self.0.action_constraint()
}
/// Get the `action` scope constraint of this policy as an expression.
/// This will be a boolean-valued expression: either `true` (if the policy
/// just has `action,`), or an equality or hierarchy constraint
pub fn action_constraint_expr(&self) -> Expr {
self.0.action_constraint_expr()
}
/// Get the `resource` scope constraint of this policy.
pub fn resource_constraint(&self) -> &ResourceConstraint {
self.0.resource_constraint()
}
/// Get the `resource` scope constraint of this policy as an expression.
/// This will be a boolean-valued expression: either `true` (if the policy
/// just has `resource,`), or an equality or hierarchy constraint
pub fn resource_constraint_expr(&self) -> Expr {
self.0.resource_constraint_expr()
}
/// Get the non-scope constraints of this policy.
///
/// This will be a conjunction of the policy's `when` conditions and the
/// negation of each of the policy's `unless` conditions.
pub fn non_scope_constraints(&self) -> &Expr {
self.0.non_scope_constraints()
}
/// Get the condition expression of this policy.
///
/// This will be a conjunction of the policy's scope constraints (on
/// principal, resource, and action); the policy's "when" conditions; and
/// the negation of each of the policy's "unless" conditions.
pub fn condition(&self) -> Expr {
self.0.condition()
}
/// Construct a `StaticPolicy` from its components
#[allow(clippy::too_many_arguments)]
pub fn new(
id: PolicyID,
loc: MaybeLoc,
annotations: Annotations,
effect: Effect,
principal_constraint: PrincipalConstraint,
action_constraint: ActionConstraint,
resource_constraint: ResourceConstraint,
non_scope_constraints: Expr,
) -> Result<Self, UnexpectedSlotError> {
let body = TemplateBody::new(
id,
loc,
annotations,
effect,
principal_constraint,
action_constraint,
resource_constraint,
non_scope_constraints,
);
let first_slot = body.condition().slots().next();
// INVARIANT (static policy correctness), checks that no slots exists
match first_slot {
Some(slot) => Err(UnexpectedSlotError::FoundSlot(slot))?,
None => Ok(Self(body)),
}
}
}
impl TryFrom<Template> for StaticPolicy {
type Error = UnexpectedSlotError;
fn try_from(value: Template) -> Result<Self, Self::Error> {
// INVARIANT (Static policy correctness): Must ensure StaticPolicy contains no slots
let o = value.slots().next().cloned();
match o {
Some(slot_id) => Err(Self::Error::FoundSlot(slot_id)),
None => Ok(Self(value.body)),
}
}
}
impl From<StaticPolicy> for Policy {
fn from(p: StaticPolicy) -> Policy {
let (_, policy) = Template::link_static_policy(p);
policy
}
}
impl From<StaticPolicy> for Arc<Template> {
fn from(p: StaticPolicy) -> Self {
let (t, _) = Template::link_static_policy(p);
t
}
}
/// Policy datatype. This is used for both templates (in which case it contains
/// slots) and static policies (in which case it contains zero slots).
#[derive(Educe, Clone, Debug)]
#[educe(PartialEq, Eq, Hash)]
pub struct TemplateBodyImpl {
/// ID of this policy
id: PolicyID,
/// Source location spanning the entire policy
#[educe(PartialEq(ignore))]
#[educe(Hash(ignore))]
loc: MaybeLoc,
/// Annotations available for external applications, as key-value store.
/// Note that the keys are `AnyId`, so Cedar reserved words like `if` and `has`
/// are explicitly allowed as annotations.
annotations: Arc<Annotations>,
/// `Effect` of this policy
effect: Effect,
/// Scope constraint for principal. This will be a boolean-valued expression:
/// either `true` (if the policy just has `principal,`), or an equality or
/// hierarchy constraint
principal_constraint: PrincipalConstraint,
/// Scope constraint for action. This will be a boolean-valued expression:
/// either `true` (if the policy just has `action,`), or an equality or
/// hierarchy constraint
action_constraint: ActionConstraint,
/// Scope constraint for resource. This will be a boolean-valued expression:
/// either `true` (if the policy just has `resource,`), or an equality or
/// hierarchy constraint
resource_constraint: ResourceConstraint,
/// Conjunction of all of the non-scope constraints in the policy.
///
/// This will be a conjunction of the policy's `when` conditions and the
/// negation of each of the policy's `unless` conditions.
non_scope_constraints: Arc<Expr>,
}
/// Policy datatype. This is used for both templates (in which case it contains
/// slots) and static policies (in which case it contains zero slots).
#[derive(Clone, Hash, Eq, PartialEq, Debug)]
pub enum TemplateBody {
/// Represents a valid template body
TemplateBody(TemplateBodyImpl),