pep 0.3.1

Policy Enforcement Point - OIDC authentication and authorization library
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
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
//! Cedar-based ABAC authorizer for fine-grained access control
//!
//! This module provides the core `CedarAuthorizer` which loads Cedar policies,
//! builds entities from JWT claims and resource information, and evaluates
//! authorization decisions.
//!
//! # Example
//!
//! ```rust,ignore
//! use pep::cedar::{CedarAuthorizer, CedarConfig};
//!
//! let config = CedarConfig::default();
//! let authorizer = CedarAuthorizer::new(config)?;
//!
//! let request = Request::new(
//!     principal_uid,
//!     action_uid,
//!     resource_uid,
//!     Context::empty(),
//!     None,
//! )?;
//!
//! let response = authorizer.is_allowed(&request);
//! assert!(response.allowed());
//! ```

use cedar_policy::{Authorizer, Decision, Entities, PolicySet, Request, Response, Schema, Validator, ValidationMode};
use std::path::Path;
use std::str::FromStr;
use std::sync::Arc;

use super::config::CedarConfig;
use super::error::{CedarError, CedarResult};
use super::schema;

/// Authorization response wrapping Cedar's native response
#[derive(Debug, Clone)]
pub struct CedarResponse {
    /// Whether the request is allowed
    allowed: bool,
    /// Policy IDs that contributed to the decision
    matched_policies: Vec<String>,
    /// Whether there were evaluation errors
    has_errors: bool,
    /// Error messages if any
    errors: Vec<String>,
}

impl CedarResponse {
    /// Whether the authorization request was allowed
    pub fn allowed(&self) -> bool {
        self.allowed
    }

    /// Policy IDs that contributed to the decision
    pub fn matched_policies(&self) -> &[String] {
        &self.matched_policies
    }

    /// Whether there were evaluation errors
    pub fn has_errors(&self) -> bool {
        self.has_errors
    }

    /// Error messages from evaluation
    pub fn errors(&self) -> &[String] {
        &self.errors
    }
}

impl From<Response> for CedarResponse {
    fn from(response: Response) -> Self {
        let allowed = response.decision() == Decision::Allow;
        let matched_policies = response
            .diagnostics()
            .reason()
            .map(|id| id.to_string())
            .collect();
        let errors: Vec<String> = response
            .diagnostics()
            .errors()
            .map(|e| e.to_string())
            .collect();
        let has_errors = !errors.is_empty();

        CedarResponse {
            allowed,
            matched_policies,
            has_errors,
            errors,
        }
    }
}

/// Cedar-based ABAC authorizer
///
/// Loads Cedar policies from files or inline strings and evaluates
/// authorization requests against them.
pub struct CedarAuthorizer {
    authorizer: Authorizer,
    policies: Arc<PolicySet>,
    entities: Arc<Entities>,
}

impl CedarAuthorizer {
    /// Create a new CedarAuthorizer with the given configuration
    ///
    /// Loads policies from the configured policy source and initializes
    /// the Cedar authorizer engine. If `schema_path` is set and
    /// `validate_on_load` is true, policies are validated against the schema.
    pub fn new(config: CedarConfig) -> CedarResult<Self> {
        let schema = Self::load_schema(&config)?;
        let policies = Self::load_policies(&config, schema.as_ref())?;
        let entities = Entities::empty();

        Ok(Self {
            authorizer: Authorizer::new(),
            policies: Arc::new(policies),
            entities: Arc::new(entities),
        })
    }

    /// Create a new CedarAuthorizer with pre-loaded entities
    pub fn with_entities(config: CedarConfig, entities: Entities) -> CedarResult<Self> {
        let schema = Self::load_schema(&config)?;
        let policies = Self::load_policies(&config, schema.as_ref())?;

        Ok(Self {
            authorizer: Authorizer::new(),
            policies: Arc::new(policies),
            entities: Arc::new(entities),
        })
    }

    /// Create a new CedarAuthorizer from a policy string (useful for testing)
    pub fn from_policy_str(policy_str: &str) -> CedarResult<Self> {
        let policies: PolicySet = policy_str
            .parse()
            .map_err(|e| CedarError::PolicyLoad(format!("Failed to parse policy: {}", e)))?;

        Ok(Self {
            authorizer: Authorizer::new(),
            policies: Arc::new(policies),
            entities: Arc::new(Entities::empty()),
        })
    }

    /// Evaluate whether a request is allowed
    ///
    /// Takes a Cedar `Request` and evaluates it against the loaded policies
    /// and entities.
    pub fn is_allowed(&self, request: &Request) -> CedarResponse {
        let response = self
            .authorizer
            .is_authorized(request, &self.policies, &self.entities);
        CedarResponse::from(response)
    }

    /// Evaluate with custom entities (for per-request entity building)
    pub fn is_allowed_with_entities(
        &self,
        request: &Request,
        entities: &Entities,
    ) -> CedarResponse {
        let response = self
            .authorizer
            .is_authorized(request, &self.policies, entities);
        CedarResponse::from(response)
    }

    /// Reload policies from the configured source
    pub fn reload_policies(&mut self, config: &CedarConfig) -> CedarResult<()> {
        let schema = Self::load_schema(config)?;
        let policies = Self::load_policies(config, schema.as_ref())?;
        self.policies = Arc::new(policies);
        Ok(())
    }

    /// Get a reference to the current policy set
    pub fn policies(&self) -> &PolicySet {
        &self.policies
    }

    /// Get a reference to the current entities
    pub fn entities(&self) -> &Entities {
        &self.entities
    }

    /// Load schema from config if schema_path is set
    fn load_schema(config: &CedarConfig) -> CedarResult<Option<Schema>> {
        if let Some(ref schema_path) = config.schema_path {
            let schema = schema::load_schema(schema_path)?;
            Ok(Some(schema))
        } else {
            Ok(None)
        }
    }

    /// Load policies from the configuration, optionally validating against a schema
    fn load_policies(config: &CedarConfig, schema: Option<&Schema>) -> CedarResult<PolicySet> {
        let mut policy_set = PolicySet::new();
        let policy_path = &config.policy_path;
        let path = Path::new(policy_path);

        if path.is_dir() {
            Self::load_policies_from_dir(&mut policy_set, path)?;
        } else if path.exists() {
            let content = std::fs::read_to_string(path).map_err(|e| {
                CedarError::PolicyLoad(format!("Failed to read policy file {:?}: {}", path, e))
            })?;
            let file_stem = path
                .file_stem()
                .and_then(|s| s.to_str())
                .unwrap_or("unknown");
            let source = PolicySet::from_str(&content).map_err(|e| {
                CedarError::PolicyLoad(format!("Failed to parse policy file {:?}: {}", path, e))
            })?;
            for policy in source.policies() {
                let new_id = cedar_policy::PolicyId::new(format!(
                    "file_{}_{}",
                    file_stem,
                    policy.id().to_string().trim_start_matches("policy")
                ));
                let text = policy.to_string();
                let reparsed = cedar_policy::Policy::parse(Some(new_id), &text).map_err(|e| {
                    CedarError::PolicyLoad(format!("Failed to re-parse policy from {:?}: {}", path, e))
                })?;
                policy_set.add(reparsed).map_err(|e| {
                    CedarError::PolicyLoad(format!("Failed to add policy from {:?}: {}", path, e))
                })?;
            }
        } else {
            return Err(CedarError::PolicyLoad(format!(
                "Policy path does not exist: {:?}",
                path
            )));
        }

        // Validate policies against schema if both are available
        if let (Some(schema), true) = (schema, config.validate_on_load) {
            let validator = Validator::new(schema.clone());
            let validation = validator.validate(&policy_set, ValidationMode::default());
            if !validation.validation_passed() {
                let errors: Vec<String> = validation
                    .validation_errors()
                    .map(|e| e.to_string())
                    .collect();
                return Err(CedarError::Validation(format!(
                    "Policy validation failed:\n{}",
                    errors.join("\n")
                )));
            }
        }

        Ok(policy_set)
    }

    /// Recursively load .cedar policy files from a directory
    fn load_policies_from_dir(policy_set: &mut PolicySet, dir: &Path) -> CedarResult<()> {
        let entries = std::fs::read_dir(dir)
            .map_err(|e| CedarError::PolicyLoad(format!("Failed to read policy directory: {}", e)))?;

        let mut count = 0usize;
        for entry in entries {
            let entry = entry
                .map_err(|e| CedarError::PolicyLoad(format!("Failed to read directory entry: {}", e)))?;
            let path = entry.path();

            if path.is_dir() {
                Self::load_policies_from_dir(policy_set, &path)?;
            } else if path.extension().map_or(false, |ext| ext == "cedar") {
                let content = std::fs::read_to_string(&path)
                    .map_err(|e| CedarError::PolicyLoad(format!("Failed to read policy file {:?}: {}", path, e)))?;

                // Parse the entire file as a PolicySet (supports multiple policies per file).
                // Cedar's PolicySet::from_str() handles single or multiple policies, as well
                // as comments and blank lines, so we prefer it over Policy::parse().
                let file_policy_set: PolicySet = content.parse().map_err(|e| {
                    CedarError::PolicyLoad(format!(
                        "Failed to parse policy file {:?}: {}",
                        path, e
                    ))
                })?;

                for policy in file_policy_set.policies() {
                    // Re-key each policy with a deterministic id derived from the file name
                    let new_id = cedar_policy::PolicyId::new(format!(
                        "file_{}_{}",
                        path.file_stem().and_then(|s| s.to_str()).unwrap_or("unknown"),
                        count
                    ));
                    let re_parsed = cedar_policy::Policy::parse(Some(new_id), policy.to_string().as_str())
                        .map_err(|e| CedarError::PolicyLoad(format!(
                            "Failed to re-parse policy {} from {:?}: {}",
                            policy.id(), path, e
                        )))?;
                    policy_set
                        .add(re_parsed)
                        .map_err(|e| CedarError::PolicyLoad(format!("Failed to add policy from {:?}: {}", path, e)))?;
                    count += 1;
                }
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use cedar_policy::{Context, EntityUid};

    fn parse_uid(s: &str) -> EntityUid {
        s.parse().unwrap()
    }

    #[test]
    fn test_basic_permit() {
        let policy = r#"
            permit(
                principal == User::"alice",
                action == Action::"view",
                resource == File::"doc1"
            );
        "#;

        let authorizer = CedarAuthorizer::from_policy_str(policy).unwrap();

        let request = Request::new(
            parse_uid(r#"User::"alice""#),
            parse_uid(r#"Action::"view""#),
            parse_uid(r#"File::"doc1""#),
            Context::empty(),
            None,
        )
        .unwrap();

        let response = authorizer.is_allowed(&request);
        assert!(response.allowed());
    }

    #[test]
    fn test_basic_deny() {
        let policy = r#"
            permit(
                principal == User::"alice",
                action == Action::"view",
                resource == File::"doc1"
            );
        "#;

        let authorizer = CedarAuthorizer::from_policy_str(policy).unwrap();

        let request = Request::new(
            parse_uid(r#"User::"bob""#),
            parse_uid(r#"Action::"view""#),
            parse_uid(r#"File::"doc1""#),
            Context::empty(),
            None,
        )
        .unwrap();

        let response = authorizer.is_allowed(&request);
        assert!(!response.allowed());
    }

    #[test]
    fn test_forbid_overrides_permit() {
        let policy = r#"
            permit(
                principal,
                action == Action::"view",
                resource
            );
            forbid(
                principal == User::"bob",
                action == Action::"view",
                resource
            );
        "#;

        let authorizer = CedarAuthorizer::from_policy_str(policy).unwrap();

        // Alice should be allowed (permit, no forbid)
        let request = Request::new(
            parse_uid(r#"User::"alice""#),
            parse_uid(r#"Action::"view""#),
            parse_uid(r#"File::"doc1""#),
            Context::empty(),
            None,
        )
        .unwrap();
        assert!(authorizer.is_allowed(&request).allowed());

        // Bob should be denied (forbid overrides permit)
        let request = Request::new(
            parse_uid(r#"User::"bob""#),
            parse_uid(r#"Action::"view""#),
            parse_uid(r#"File::"doc1""#),
            Context::empty(),
            None,
        )
        .unwrap();
        assert!(!authorizer.is_allowed(&request).allowed());
    }

    #[test]
    fn test_role_based_policy() {
        let policy = r#"
            permit(
                principal in Group::"Admins",
                action == Action::"delete",
                resource == Project::"*"
            );
        "#;

        let authorizer = CedarAuthorizer::from_policy_str(policy).unwrap();

        let request = Request::new(
            parse_uid(r#"User::"alice""#),
            parse_uid(r#"Action::"delete""#),
            parse_uid(r#"Project::"my-project""#),
            Context::empty(),
            None,
        )
        .unwrap();

        // Without entity hierarchy, "in" won't match
        let response = authorizer.is_allowed(&request);
        assert!(!response.allowed());
    }

    #[test]
    fn test_context_based_policy() {
        let policy = r#"
            permit(
                principal,
                action == Action::"view",
                resource
            ) when {
                context.status == "active"
            };
        "#;

        let authorizer = CedarAuthorizer::from_policy_str(policy).unwrap();

        // With matching context
        let context_json = serde_json::json!({"status": "active"});
        let context = Context::from_json_value(context_json, None).unwrap();
        let request = Request::new(
            parse_uid(r#"User::"alice""#),
            parse_uid(r#"Action::"view""#),
            parse_uid(r#"Task::"task-1""#),
            context,
            None,
        )
        .unwrap();

        let response = authorizer.is_allowed(&request);
        assert!(response.allowed());
    }

    #[test]
    fn test_invalid_policy_fails() {
        let result = CedarAuthorizer::from_policy_str("invalid policy syntax!!!");
        assert!(result.is_err());
    }

    #[test]
    fn test_response_properties() {
        let policy = r#"
            permit(
                principal == User::"alice",
                action == Action::"view",
                resource
            );
        "#;

        let authorizer = CedarAuthorizer::from_policy_str(policy).unwrap();

        let request = Request::new(
            parse_uid(r#"User::"alice""#),
            parse_uid(r#"Action::"view""#),
            parse_uid(r#"File::"doc1""#),
            Context::empty(),
            None,
        )
        .unwrap();

        let response = authorizer.is_allowed(&request);
        assert!(response.allowed());
        assert!(!response.has_errors());
    }
}