cedar-policy-core 4.10.0

Core implementation of the Cedar policy language
Documentation
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
/*
 * 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.
 */

//! Scope constraint types for PST.
//!
//! These types represent the principal, action, and resource scope constraints
//! in a Cedar policy head:
//!
//! ```cedar
//! permit (
//!   principal == User::"alice",       // PrincipalConstraint::Eq
//!   action == Action::"view",         // ActionConstraint::Eq
//!   resource in Album::"vacation"     // ResourceConstraint::In
//! );
//! ```

use super::err::error_body::LinkingError;
use super::expr::{EntityType, EntityUID, SlotId};
use std::collections::HashMap;

/// Entity UID or template slot.
///
/// Used in principal and resource constraints where either a concrete entity
/// or a template slot is allowed.
///
/// ```cedar
/// principal == User::"alice"      // EntityOrSlot::Entity
/// principal == ?principal         // EntityOrSlot::Slot
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum EntityOrSlot {
    /// A concrete entity UID
    Entity(EntityUID),
    /// A template slot
    Slot(SlotId),
}

impl EntityOrSlot {
    /// Fill in any slot using the values in `vals`.
    fn link(self, vals: &HashMap<SlotId, EntityUID>) -> Result<EntityOrSlot, LinkingError> {
        match self {
            EntityOrSlot::Entity(_) => Ok(self),
            EntityOrSlot::Slot(slot) => match vals.get(&slot) {
                Some(uid) => Ok(EntityOrSlot::Entity(uid.clone())),
                None => Err(LinkingError::MissedSlot { slot }),
            },
        }
    }
}

/// Principal scope constraint.
///
/// ```cedar
/// principal,                              // Any
/// principal == User::"alice",             // Eq(Entity)
/// principal == ?principal,                // Eq(Slot)
/// principal in Group::"admins",           // In(Entity)
/// principal is User,                      // Is
/// principal is User in Group::"admins",   // IsIn
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PrincipalConstraint {
    /// `principal` — matches any principal
    Any,
    /// `principal == <entity_or_slot>`
    Eq(EntityOrSlot),
    /// `principal in <entity_or_slot>`
    In(EntityOrSlot),
    /// `principal is <type>`
    Is(EntityType),
    /// `principal is <type> in <entity_or_slot>`
    IsIn(EntityType, EntityOrSlot),
}

impl PrincipalConstraint {
    /// Fill in any slots in this constraint using the values in `vals`.
    pub fn link(self, vals: &HashMap<SlotId, EntityUID>) -> Result<Self, LinkingError> {
        match self {
            PrincipalConstraint::Any => Ok(PrincipalConstraint::Any),
            PrincipalConstraint::Eq(eos) => Ok(PrincipalConstraint::Eq(eos.link(vals)?)),
            PrincipalConstraint::In(eos) => Ok(PrincipalConstraint::In(eos.link(vals)?)),
            PrincipalConstraint::Is(et) => Ok(PrincipalConstraint::Is(et)),
            PrincipalConstraint::IsIn(et, eos) => {
                Ok(PrincipalConstraint::IsIn(et, eos.link(vals)?))
            }
        }
    }

    /// Test whether the constraint contains any slots.
    pub fn has_slot(&self) -> bool {
        matches!(
            self,
            PrincipalConstraint::Eq(EntityOrSlot::Slot(_))
                | PrincipalConstraint::In(EntityOrSlot::Slot(_))
                | PrincipalConstraint::IsIn(_, EntityOrSlot::Slot(_))
        )
    }

    /// Get the slot, if any
    pub fn slot(&self) -> Option<SlotId> {
        match self {
            PrincipalConstraint::Eq(EntityOrSlot::Slot(s))
            | PrincipalConstraint::In(EntityOrSlot::Slot(s))
            | PrincipalConstraint::IsIn(_, EntityOrSlot::Slot(s)) => Some(*s),
            _ => None,
        }
    }
}

/// Resource scope constraint (same shape as [`PrincipalConstraint`]).
///
/// ```cedar
/// resource,                               // Any
/// resource == Photo::"pic.jpg",           // Eq(Entity)
/// resource == ?resource,                  // Eq(Slot)
/// resource in Album::"vacation",          // In(Entity)
/// resource is Photo,                      // Is
/// resource is Photo in Album::"vacation", // IsIn
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResourceConstraint {
    /// `resource` — matches any resource
    Any,
    /// `resource == <entity_or_slot>`
    Eq(EntityOrSlot),
    /// `resource in <entity_or_slot>`
    In(EntityOrSlot),
    /// `resource is <type>`
    Is(EntityType),
    /// `resource is <type> in <entity_or_slot>`
    IsIn(EntityType, EntityOrSlot),
}

impl ResourceConstraint {
    /// Fill in any slots in this constraint using the values in `vals`.
    pub fn link(self, vals: &HashMap<SlotId, EntityUID>) -> Result<Self, LinkingError> {
        match self {
            ResourceConstraint::Any => Ok(ResourceConstraint::Any),
            ResourceConstraint::Eq(eos) => Ok(ResourceConstraint::Eq(eos.link(vals)?)),
            ResourceConstraint::In(eos) => Ok(ResourceConstraint::In(eos.link(vals)?)),
            ResourceConstraint::Is(et) => Ok(ResourceConstraint::Is(et)),
            ResourceConstraint::IsIn(et, eos) => Ok(ResourceConstraint::IsIn(et, eos.link(vals)?)),
        }
    }

    /// Test whether the constraint contains any slots.
    pub fn has_slot(&self) -> bool {
        matches!(
            self,
            ResourceConstraint::Eq(EntityOrSlot::Slot(_))
                | ResourceConstraint::In(EntityOrSlot::Slot(_))
                | ResourceConstraint::IsIn(_, EntityOrSlot::Slot(_)),
        )
    }

    /// Get the slot, if any
    pub fn slot(&self) -> Option<SlotId> {
        match self {
            ResourceConstraint::Eq(EntityOrSlot::Slot(s))
            | ResourceConstraint::In(EntityOrSlot::Slot(s))
            | ResourceConstraint::IsIn(_, EntityOrSlot::Slot(s)) => Some(*s),
            _ => None,
        }
    }
}

/// Action scope constraint.
///
/// ```cedar
/// action,                                                     // Any
/// action == Action::"view",                                   // Eq
/// action in [Action::"view", Action::"edit"],                 // In
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ActionConstraint {
    /// `action` — matches any action
    Any,
    /// `action == <entity_uid>`
    Eq(EntityUID),
    /// `action in [<entity_uid>, ...]`
    In(Vec<EntityUID>),
}

impl ActionConstraint {
    /// Actions cannot contain slots, so linking is a no-op.
    pub fn link(self, _vals: &HashMap<SlotId, EntityUID>) -> Result<Self, LinkingError> {
        Ok(self)
    }

    /// Actions cannot contains slots: returns false
    pub fn has_slot(&self) -> bool {
        false
    }

    /// Action cannot have slots
    pub fn slot(&self) -> Option<SlotId> {
        None
    }
}

impl std::fmt::Display for EntityOrSlot {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EntityOrSlot::Entity(uid) => write!(f, "{}", uid),
            EntityOrSlot::Slot(slot) => write!(f, "{}", slot),
        }
    }
}

impl std::fmt::Display for PrincipalConstraint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PrincipalConstraint::Any => write!(f, ""),
            PrincipalConstraint::Eq(eos) => write!(f, "== {}", eos),
            PrincipalConstraint::In(eos) => write!(f, "in {}", eos),
            PrincipalConstraint::Is(et) => write!(f, "is {}", et),
            PrincipalConstraint::IsIn(et, eos) => write!(f, "is {} in {}", et, eos),
        }
    }
}

impl std::fmt::Display for ResourceConstraint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ResourceConstraint::Any => write!(f, ""),
            ResourceConstraint::Eq(eos) => write!(f, "== {}", eos),
            ResourceConstraint::In(eos) => write!(f, "in {}", eos),
            ResourceConstraint::Is(et) => write!(f, "is {}", et),
            ResourceConstraint::IsIn(et, eos) => write!(f, "is {} in {}", et, eos),
        }
    }
}

impl std::fmt::Display for ActionConstraint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ActionConstraint::Any => write!(f, ""),
            ActionConstraint::Eq(uid) => write!(f, "== {}", uid),
            ActionConstraint::In(uids) => {
                write!(f, "in [")?;
                for (i, uid) in uids.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{}", uid)?;
                }
                write!(f, "]")
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pst::expr::Name;

    fn make_entity_uid(ty: &str, id: &str) -> EntityUID {
        EntityUID {
            ty: EntityType(Name::unqualified(ty).unwrap()),
            eid: id.into(),
        }
    }

    #[test]
    fn test_principal_constraint_display() {
        let uid = make_entity_uid("User", "alice");
        let eos = EntityOrSlot::Entity(uid.clone());
        let et = EntityType(Name::unqualified("User").unwrap());
        let etq = EntityType(Name::qualified(vec!["Admins"], "User").unwrap());
        let cases = vec![
            (PrincipalConstraint::Any, ""),
            (PrincipalConstraint::Eq(eos.clone()), "== User::\"alice\""),
            (
                PrincipalConstraint::Eq(EntityOrSlot::Slot(SlotId::Principal)),
                "== ?principal",
            ),
            (PrincipalConstraint::In(eos.clone()), "in User::\"alice\""),
            (PrincipalConstraint::Is(et.clone()), "is User"),
            (PrincipalConstraint::Is(etq), "is Admins::User"),
            (
                PrincipalConstraint::IsIn(et, eos),
                "is User in User::\"alice\"",
            ),
        ];

        for (constraint, expected) in cases {
            assert_eq!(constraint.to_string(), expected);
        }
    }

    #[test]
    fn test_resource_constraint_display() {
        let uid = make_entity_uid("File", "doc.txt");
        let eos = EntityOrSlot::Entity(uid.clone());
        let et = EntityType(Name::unqualified("File").unwrap());

        let cases = vec![
            (ResourceConstraint::Any, ""),
            (ResourceConstraint::Eq(eos.clone()), "== File::\"doc.txt\""),
            (ResourceConstraint::In(eos.clone()), "in File::\"doc.txt\""),
            (
                ResourceConstraint::Eq(EntityOrSlot::Slot(SlotId::Resource)),
                "== ?resource",
            ),
            (ResourceConstraint::Is(et.clone()), "is File"),
            (
                ResourceConstraint::IsIn(et, eos),
                "is File in File::\"doc.txt\"",
            ),
        ];

        for (constraint, expected) in cases {
            assert_eq!(constraint.to_string(), expected);
        }
    }

    #[test]
    fn test_action_constraint_display() {
        let uid1 = make_entity_uid("Action", "read");
        let uid2 = make_entity_uid("Action", "write");

        let cases = vec![
            (ActionConstraint::Any, ""),
            (ActionConstraint::Eq(uid1.clone()), "== Action::\"read\""),
            (ActionConstraint::In(vec![]), "in []"),
            (
                ActionConstraint::In(vec![uid1.clone()]),
                "in [Action::\"read\"]",
            ),
            (
                ActionConstraint::In(vec![uid1, uid2]),
                "in [Action::\"read\", Action::\"write\"]",
            ),
        ];

        for (constraint, expected) in cases {
            assert_eq!(constraint.to_string(), expected);
        }
    }

    fn make_vals() -> HashMap<SlotId, EntityUID> {
        let mut vals = HashMap::new();
        vals.insert(SlotId::Principal, make_entity_uid("User", "alice"));
        vals.insert(SlotId::Resource, make_entity_uid("File", "doc.txt"));
        vals
    }

    #[test]
    fn test_entity_or_slot_link_entity_passthrough() {
        let uid = make_entity_uid("User", "alice");
        let eos = EntityOrSlot::Entity(uid.clone());
        assert_eq!(eos.link(&make_vals()).unwrap(), EntityOrSlot::Entity(uid));
    }

    #[test]
    fn test_entity_or_slot_link_slot_resolves() {
        let eos = EntityOrSlot::Slot(SlotId::Principal);
        assert_eq!(
            eos.link(&make_vals()).unwrap(),
            EntityOrSlot::Entity(make_entity_uid("User", "alice"))
        );
    }

    #[test]
    fn test_entity_or_slot_link_missing_slot() {
        let eos = EntityOrSlot::Slot(SlotId::Resource);
        let empty = HashMap::new();
        assert!(matches!(
            eos.link(&empty),
            Err(LinkingError::MissedSlot {
                slot: SlotId::Resource
            })
        ));
    }

    #[test]
    fn test_principal_constraint_link_all_variants() {
        let vals = make_vals();
        let alice = make_entity_uid("User", "alice");
        let et = EntityType(Name::unqualified("User").unwrap());

        // Any passes through
        assert_eq!(
            PrincipalConstraint::Any.link(&vals).unwrap(),
            PrincipalConstraint::Any
        );
        // Eq with entity passes through
        assert_eq!(
            PrincipalConstraint::Eq(EntityOrSlot::Entity(alice.clone()))
                .link(&vals)
                .unwrap(),
            PrincipalConstraint::Eq(EntityOrSlot::Entity(alice.clone()))
        );
        // Eq with slot resolves
        assert_eq!(
            PrincipalConstraint::Eq(EntityOrSlot::Slot(SlotId::Principal))
                .link(&vals)
                .unwrap(),
            PrincipalConstraint::Eq(EntityOrSlot::Entity(alice.clone()))
        );
        // In with slot resolves
        assert_eq!(
            PrincipalConstraint::In(EntityOrSlot::Slot(SlotId::Principal))
                .link(&vals)
                .unwrap(),
            PrincipalConstraint::In(EntityOrSlot::Entity(alice.clone()))
        );
        // Is passes through (no slot)
        assert_eq!(
            PrincipalConstraint::Is(et.clone()).link(&vals).unwrap(),
            PrincipalConstraint::Is(et.clone())
        );
        // IsIn with slot resolves
        assert_eq!(
            PrincipalConstraint::IsIn(et.clone(), EntityOrSlot::Slot(SlotId::Principal))
                .link(&vals)
                .unwrap(),
            PrincipalConstraint::IsIn(et, EntityOrSlot::Entity(alice))
        );
    }

    #[test]
    fn test_resource_constraint_link_slot_resolves() {
        let vals = make_vals();
        let doc = make_entity_uid("File", "doc.txt");

        assert_eq!(
            ResourceConstraint::Eq(EntityOrSlot::Slot(SlotId::Resource))
                .link(&vals)
                .unwrap(),
            ResourceConstraint::Eq(EntityOrSlot::Entity(doc))
        );
    }

    #[test]
    fn test_principal_constraint_link_missing_slot() {
        let empty = HashMap::new();
        assert!(matches!(
            PrincipalConstraint::Eq(EntityOrSlot::Slot(SlotId::Principal)).link(&empty),
            Err(LinkingError::MissedSlot {
                slot: SlotId::Principal
            })
        ));
    }

    #[test]
    fn test_action_constraint_link_noop() {
        let uid = make_entity_uid("Action", "read");
        let vals = make_vals();
        assert_eq!(
            ActionConstraint::Eq(uid.clone()).link(&vals).unwrap(),
            ActionConstraint::Eq(uid)
        );
    }
}