1use clap::Args;
18use miette::{IntoDiagnostic, Report, Result, WrapErr};
19use owo_colors::OwoColorize;
20use serde::de::{DeserializeSeed, IntoDeserializer};
21use serde::{Deserialize, Deserializer};
22use std::collections::BTreeSet;
23use std::io::{BufReader, Write};
24use std::path::Path;
25
26use cedar_policy::*;
27
28use crate::{load_entities, CedarExitCode, OptionalSchemaArgs, PoliciesArgs, RequestJSON};
29
30#[derive(Args, Debug)]
31pub struct RunTestsArgs {
32 #[command(flatten)]
34 pub policies: PoliciesArgs,
35 #[arg(long, value_name = "FILE")]
37 pub tests: String,
38 #[command(flatten)]
39 pub schema: OptionalSchemaArgs,
40}
41
42#[derive(Clone, Debug)]
43enum TestResult {
44 Pass,
45 Fail(String),
46}
47
48fn compare_test_decisions(test: &TestCase, ans: &Response) -> TestResult {
50 if ans.decision() == test.decision.into() {
51 let mut errors = Vec::new();
52 let reason = ans.diagnostics().reason().collect::<BTreeSet<_>>();
53
54 let missing_reason = test
56 .reason
57 .iter()
58 .filter(|r| !reason.contains(&PolicyId::new(r)))
59 .collect::<Vec<_>>();
60
61 if !missing_reason.is_empty() {
62 errors.push(format!(
63 "missing reason(s): {}",
64 missing_reason
65 .into_iter()
66 .map(|r| format!("`{r}`"))
67 .collect::<Vec<_>>()
68 .join(", ")
69 ));
70 }
71
72 let num_errors = ans.diagnostics().errors().count();
74 if num_errors != test.num_errors {
75 errors.push(format!(
76 "expected {} error(s), but got {} runtime error(s){}",
77 test.num_errors,
78 num_errors,
79 if num_errors == 0 {
80 "".to_string()
81 } else {
82 format!(
83 ": {}",
84 ans.diagnostics()
85 .errors()
86 .map(|e| e.to_string())
87 .collect::<Vec<_>>()
88 .join(", ")
89 )
90 },
91 ));
92 }
93
94 if errors.is_empty() {
95 TestResult::Pass
96 } else {
97 TestResult::Fail(errors.join("; "))
98 }
99 } else {
100 TestResult::Fail(format!(
101 "expected {:?}, got {:?}",
102 test.decision,
103 ans.decision()
104 ))
105 }
106}
107
108fn run_one_test(
111 policies: &PolicySet,
112 test: &serde_json::Value,
113 validator: Option<&Validator>,
114 test_file_dir: &Path,
115) -> Result<TestResult> {
116 let test = CheckedTestCaseSeed {
117 schema: validator.map(Validator::schema),
118 test_file_dir,
119 }
120 .deserialize(test.into_deserializer())
121 .into_diagnostic()?;
122 if let Some(validator) = validator {
123 let val_res = validator.validate(policies, cedar_policy::ValidationMode::Strict);
124 if !val_res.validation_passed_without_warnings() {
125 return Err(Report::new(val_res).wrap_err("policy set validation failed"));
126 }
127 }
128 let ans = Authorizer::new().is_authorized(&test.request, policies, &test.entities);
129 Ok(compare_test_decisions(&test, &ans))
130}
131
132fn run_tests_inner(args: &RunTestsArgs) -> Result<CedarExitCode> {
133 let policies = args.policies.get_policy_set()?;
134 let tests = load_partial_tests(&args.tests)?;
135 let validator = args.schema.get_schema()?.map(Validator::new);
136
137 let test_file_dir = Path::new(&args.tests)
138 .parent()
139 .unwrap_or_else(|| Path::new("."));
140
141 let mut total_fails: usize = 0;
142
143 println!("running {} test(s)", tests.len());
144 for test in tests.iter() {
145 if let Some(name) = test["name"].as_str() {
146 print!(" test {name} ... ");
147 } else {
148 print!(" test (unnamed) ... ");
149 }
150 std::io::stdout().flush().into_diagnostic()?;
151 match run_one_test(&policies, test, validator.as_ref(), test_file_dir) {
152 Ok(TestResult::Pass) => {
153 println!(
154 "{}",
155 "ok".if_supports_color(owo_colors::Stream::Stdout, |s| s.green())
156 );
157 }
158 Ok(TestResult::Fail(reason)) => {
159 total_fails += 1;
160 println!(
161 "{}: {}",
162 "fail".if_supports_color(owo_colors::Stream::Stdout, |s| s.red()),
163 reason
164 );
165 }
166 Err(e) => {
167 total_fails += 1;
168 println!(
169 "{}:\n {:?}",
170 "error".if_supports_color(owo_colors::Stream::Stdout, |s| s.red()),
171 e
172 );
173 }
174 }
175 }
176
177 println!(
178 "results: {} {}, {} {}",
179 tests.len() - total_fails,
180 if total_fails == 0 {
181 "passed"
182 .if_supports_color(owo_colors::Stream::Stdout, |s| s.green())
183 .to_string()
184 } else {
185 "passed".to_string()
186 },
187 total_fails,
188 if total_fails != 0 {
189 "failed"
190 .if_supports_color(owo_colors::Stream::Stdout, |s| s.red())
191 .to_string()
192 } else {
193 "failed".to_string()
194 },
195 );
196
197 Ok(if total_fails != 0 {
198 CedarExitCode::Failure
199 } else {
200 CedarExitCode::Success
201 })
202}
203
204pub fn run_tests(args: &RunTestsArgs) -> CedarExitCode {
205 run_tests_inner(args).unwrap_or_else(|e| {
206 println!("{e:?}");
207 CedarExitCode::Failure
208 })
209}
210
211#[derive(Copy, Clone, Debug, Deserialize)]
212enum ExpectedDecision {
213 #[serde(rename = "allow")]
214 Allow,
215 #[serde(rename = "deny")]
216 Deny,
217}
218
219impl From<ExpectedDecision> for Decision {
220 fn from(value: ExpectedDecision) -> Self {
221 match value {
222 ExpectedDecision::Allow => Decision::Allow,
223 ExpectedDecision::Deny => Decision::Deny,
224 }
225 }
226}
227
228#[derive(Clone, Debug, Deserialize)]
229struct UncheckedTestCase {
230 request: RequestJSON,
231 entities: serde_json::Value,
232 decision: ExpectedDecision,
233 reason: Vec<String>,
234 num_errors: usize,
235}
236
237#[derive(Clone, Debug)]
238struct TestCase {
239 request: Request,
240 entities: Entities,
241 decision: ExpectedDecision,
242 reason: Vec<String>,
243 num_errors: usize,
244}
245
246struct CheckedTestCaseSeed<'a> {
247 schema: Option<&'a Schema>,
248 test_file_dir: &'a Path,
249}
250
251impl<'de, 'a> DeserializeSeed<'de> for CheckedTestCaseSeed<'a> {
252 type Value = TestCase;
253
254 fn deserialize<D>(self, deserializer: D) -> std::result::Result<Self::Value, D::Error>
255 where
256 D: Deserializer<'de>,
257 {
258 let UncheckedTestCase {
259 request,
260 entities,
261 decision,
262 reason,
263 num_errors,
264 } = UncheckedTestCase::deserialize(deserializer)?;
265
266 let principal = request
267 .principal
268 .ok_or_else(|| serde::de::Error::missing_field("principal"))?;
269 let principal = principal.parse().map_err(|e| {
270 serde::de::Error::custom(format!("failed to parse principal `{principal}`: {e}",))
271 })?;
272
273 let action = request
274 .action
275 .ok_or_else(|| serde::de::Error::missing_field("action"))?;
276 let action = action.parse().map_err(|e| {
277 serde::de::Error::custom(format!("failed to parse action `{action}`: {e}",))
278 })?;
279
280 let resource = request
281 .resource
282 .ok_or_else(|| serde::de::Error::missing_field("resource"))?;
283 let resource = resource.parse().map_err(|e| {
284 serde::de::Error::custom(format!("failed to parse resource `{resource}`: {e}",))
285 })?;
286
287 let context =
288 Context::from_json_value(request.context.clone(), self.schema.zip(Some(&action)))
289 .map_err(|e| {
290 serde::de::Error::custom(format!(
291 "failed to parse context `{}`: {}",
292 request.context, e
293 ))
294 })?;
295
296 let request = Request::new(principal, action, resource, context, self.schema)
297 .map_err(|e| serde::de::Error::custom(format!("failed to create request: {e}")))?;
298
299 let entities = if let Some(entities_file) = entities.as_str() {
300 let entities_path = self.test_file_dir.join(entities_file);
301
302 let canonical_path = entities_path.canonicalize().map_err(|e| {
303 serde::de::Error::custom(format!(
304 "failed to canonicalize path `{}`: {e}",
305 entities_path.display()
306 ))
307 })?;
308
309 let canonical_dir = self.test_file_dir.canonicalize().map_err(|e| {
310 serde::de::Error::custom(format!(
311 "failed to canonicalize test file directory `{}`: {e}",
312 self.test_file_dir.display()
313 ))
314 })?;
315
316 if !canonical_path.starts_with(&canonical_dir) {
317 return Err(serde::de::Error::custom(format!(
318 "entities file `{}` is outside of the test file directory `{}`",
319 canonical_path.display(),
320 canonical_dir.display()
321 )));
322 }
323
324 load_entities(canonical_path, self.schema).map_err(|e| {
325 serde::de::Error::custom(format!(
326 "failed to load entities from file `{}`: {e}",
327 entities_file
328 ))
329 })?
330 } else {
331 Entities::from_json_value(entities, self.schema)
332 .map_err(|e| serde::de::Error::custom(format!("failed to parse entities: {e}")))?
333 };
334
335 Ok(TestCase {
336 request,
337 entities,
338 decision,
339 reason,
340 num_errors,
341 })
342 }
343}
344
345fn load_partial_tests(tests_filename: impl AsRef<Path>) -> Result<Vec<serde_json::Value>> {
348 let f = std::fs::OpenOptions::new()
349 .read(true)
350 .open(tests_filename.as_ref())
351 .into_diagnostic()
352 .wrap_err_with(|| {
353 format!(
354 "failed to open test file {}",
355 tests_filename.as_ref().display()
356 )
357 })?;
358 let reader = BufReader::new(f);
359 serde_json::from_reader(reader)
360 .into_diagnostic()
361 .wrap_err_with(|| {
362 format!(
363 "failed to parse tests from file {}",
364 tests_filename.as_ref().display()
365 )
366 })
367}
368
369#[cfg(test)]
370mod tests {
371 use super::*;
372 use crate::utils::test_utils::render_err;
373
374 fn schema() -> Schema {
375 Schema::from_cedarschema_str(
376 "entity User; entity Photo; action view appliesTo { principal: [User], resource: [Photo] };",
377 )
378 .expect("test schema should parse")
379 .0
380 }
381
382 fn deserialize(
383 schema: Option<&Schema>,
384 request: serde_json::Value,
385 ) -> Result<TestCase, String> {
386 let test = serde_json::json!({
387 "request": request,
388 "entities": [],
389 "decision": "deny",
390 "reason": [],
391 "num_errors": 0,
392 });
393 CheckedTestCaseSeed {
394 schema,
395 test_file_dir: &std::path::Path::new("."),
396 }
397 .deserialize(test.into_deserializer())
398 .into_diagnostic()
399 .map_err(|e| render_err(&e))
400 }
401
402 #[test]
403 fn bad_principal() {
404 let request = serde_json::json!({
405 "principal": "not an euid",
406 "action": "Action::\"view\"",
407 "resource": "Photo::\"pic\"",
408 "context": {},
409 });
410 insta::assert_snapshot!(
411 deserialize(None, request).unwrap_err(),
412 @" × failed to parse principal `not an euid`: unexpected token `an`"
413 );
414 }
415
416 #[test]
417 fn bad_action() {
418 let request = serde_json::json!({
419 "principal": "User::\"alice\"",
420 "action": "not an euid",
421 "resource": "Photo::\"pic\"",
422 "context": {},
423 });
424 insta::assert_snapshot!(
425 deserialize(None, request).unwrap_err(),
426 @" × failed to parse action `not an euid`: unexpected token `an`"
427 );
428 }
429
430 #[test]
431 fn bad_resource() {
432 let request = serde_json::json!({
433 "principal": "User::\"alice\"",
434 "action": "Action::\"view\"",
435 "resource": "not an euid",
436 "context": {},
437 });
438 insta::assert_snapshot!(
439 deserialize(None, request).unwrap_err(),
440 @" × failed to parse resource `not an euid`: unexpected token `an`"
441 );
442 }
443
444 #[test]
445 fn action_not_in_schema() {
446 let request = serde_json::json!({
447 "principal": "User::\"alice\"",
448 "action": "Action::\"delete\"",
449 "resource": "Photo::\"pic\"",
450 "context": {},
451 });
452
453 insta::assert_snapshot!(
454 deserialize(Some(&schema()), request).unwrap_err(),
455 @r#" × failed to parse context `{}`: action `Action::"delete"` is not defined in the supplied schema"#
456 );
457 }
458
459 #[test]
460 fn principal_invalid_for_action() {
461 let request = serde_json::json!({
462 "principal": "Photo::\"pic\"",
463 "action": "Action::\"view\"",
464 "resource": "Photo::\"pic\"",
465 "context": {},
466 });
467
468 insta::assert_snapshot!(
469 deserialize(Some(&schema()), request).unwrap_err(),
470 @r#" × failed to create request: principal type `Photo` is not valid for `Action::"view"`"#
471 );
472 }
473
474 #[test]
475 fn bad_context() {
476 let request = serde_json::json!({
478 "principal": "User::\"alice\"",
479 "action": "Action::\"view\"",
480 "resource": "Photo::\"pic\"",
481 "context": { "unexpected": true },
482 });
483
484 insta::assert_snapshot!(
486 deserialize(Some(&schema()), request).unwrap_err(),
487 @" × failed to parse context `{\"unexpected\":true}`: while parsing context, record attribute `unexpected` should not exist according to the schema"
488 );
489 }
490
491 #[test]
492 fn entities_from_file_not_found() {
493 let request = serde_json::json!({
494 "principal": "User::\"alice\"",
495 "action": "Action::\"view\"",
496 "resource": "Photo::\"pic\"",
497 "context": {},
498 });
499 let test = serde_json::json!({
500 "request": request,
501 "entities": "nonexistent.json",
502 "decision": "deny",
503 "reason": [],
504 "num_errors": 0,
505 });
506 let result = CheckedTestCaseSeed {
507 schema: None,
508 test_file_dir: &std::path::Path::new("."),
509 }
510 .deserialize(test.into_deserializer());
511
512 assert!(result.is_err());
513 let err_msg = result.unwrap_err().to_string();
514 assert!(err_msg.contains("nonexistent.json"));
515 }
516
517 #[test]
518 fn entities_path_traversal_attack() {
519 use std::fs;
520 use std::fs::File;
521 use std::io::Write;
522
523 let request = serde_json::json!({
524 "principal": "User::\"alice\"",
525 "action": "Action::\"view\"",
526 "resource": "Photo::\"pic\"",
527 "context": {},
528 });
529
530 let temp_dir = tempfile::tempdir().expect("failed to create temp dir");
531
532 let test_subdir = temp_dir.path().join("tests");
534 fs::create_dir(&test_subdir).expect("failed to create test subdir");
535
536 let outside_file = temp_dir.path().join("outside.json");
538 let mut file = File::create(&outside_file).expect("failed to create outside file");
539 writeln!(file, "[]").expect("failed to write outside file");
540
541 let test = serde_json::json!({
543 "request": request,
544 "entities": "../outside.json",
545 "decision": "deny",
546 "reason": [],
547 "num_errors": 0,
548 });
549
550 let result = CheckedTestCaseSeed {
551 schema: None,
552 test_file_dir: test_subdir.as_path(),
553 }
554 .deserialize(test.into_deserializer());
555
556 assert!(result.is_err());
557 let err_msg = result.unwrap_err().to_string();
558 assert!(err_msg.contains("outside of the test file directory"));
559 }
560
561 #[test]
562 fn entities_from_file_valid() {
563 use std::fs::File;
564 use std::io::Write;
565
566 let request = serde_json::json!({
567 "principal": "User::\"alice\"",
568 "action": "Action::\"view\"",
569 "resource": "Photo::\"pic\"",
570 "context": {},
571 });
572 let test = serde_json::json!({
573 "request": request,
574 "entities": "entities.json",
575 "decision": "deny",
576 "reason": [],
577 "num_errors": 0,
578 });
579
580 let temp_dir = tempfile::tempdir().expect("failed to create temp dir");
581 let entities_path = temp_dir.path().join("entities.json");
582 let mut file = File::create(&entities_path).expect("failed to create entities file");
583 writeln!(file, "[]").expect("failed to write entities file");
584
585 let result = CheckedTestCaseSeed {
586 schema: None,
587 test_file_dir: temp_dir.path(),
588 }
589 .deserialize(test.into_deserializer());
590
591 assert!(result.is_ok());
592 let test_case = result.unwrap();
593 assert_eq!(test_case.reason, Vec::<String>::new());
594 assert_eq!(test_case.num_errors, 0);
595 }
596
597 #[test]
598 fn entities_from_inline_json() {
599 let request = serde_json::json!({
600 "principal": "User::\"alice\"",
601 "action": "Action::\"view\"",
602 "resource": "Photo::\"pic\"",
603 "context": {},
604 });
605 let test = serde_json::json!({
606 "request": request,
607 "entities": [],
608 "decision": "deny",
609 "reason": [],
610 "num_errors": 0,
611 });
612
613 let result = CheckedTestCaseSeed {
614 schema: None,
615 test_file_dir: &std::path::Path::new("."),
616 }
617 .deserialize(test.into_deserializer());
618
619 assert!(result.is_ok());
620 let test_case = result.unwrap();
621 assert_eq!(test_case.reason, Vec::<String>::new());
622 assert_eq!(test_case.num_errors, 0);
623 }
624
625 #[test]
626 fn entities_from_inline_json_with_schema() {
627 let request = serde_json::json!({
628 "principal": "User::\"alice\"",
629 "action": "Action::\"view\"",
630 "resource": "Photo::\"pic\"",
631 "context": {},
632 });
633 let test = serde_json::json!({
634 "request": request,
635 "entities": [],
636 "decision": "deny",
637 "reason": [],
638 "num_errors": 0,
639 });
640
641 let result = CheckedTestCaseSeed {
642 schema: Some(&schema()),
643 test_file_dir: &std::path::Path::new("."),
644 }
645 .deserialize(test.into_deserializer());
646
647 assert!(result.is_ok());
648 }
649}