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
/*
 * 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.
 */

#![expect(
    clippy::panic,
    clippy::unwrap_used,
    clippy::expect_used,
    reason = "testing code"
)]

//! Shared test utilities.

/// Describes the contents of an error message. Fields are based on the contents
/// of `miette::Diagnostic`.
#[derive(Debug)]
pub struct ExpectedErrorMessage<'a> {
    /// Expected contents of `Display`, or expected prefix of `Display` if `prefix` is `true`
    error: &'a str,
    /// Expected contents of `help()`, or `None` if no help, or expected prefix of `help()` if `prefix` is `true`
    help: Option<&'a str>,
    /// If `true`, then `error`, `help`, and `source` are interpreted as expected
    /// prefixes of the relevant messages, and [`expect_err()`] will allow the
    /// actual messages to have additional characters after the ones that are expected.
    prefix: bool,
    /// Expected text that is underlined by miette (text found at the error's
    /// source location(s)) plus (optional) help text associated with the
    /// underline.
    /// If this is an empty vec, we expect the error to have no associated
    /// source location.
    /// If this is a vec with one or more elements, we expect the same number of
    /// miette `labels` in the same order, and the vec elements represent the
    /// expected contents of the labels.
    underlines: Vec<(&'a str, Option<&'a str>)>,
    /// A message describing the cause of this error
    source: Option<&'a str>,
}

/// Builder struct for [`ExpectedErrorMessage`]
#[derive(Debug)]
pub struct ExpectedErrorMessageBuilder<'a> {
    /// ExpectedErrorMessage::error
    error: &'a str,
    /// ExpectedErrorMessage::help
    help: Option<&'a str>,
    /// ExpectedErrorMessage::prefix
    prefix: bool,
    /// ExpectedErrorMessage::underlines
    underlines: Vec<(&'a str, Option<&'a str>)>,
    /// ExpectedErrorMessage::source
    source: Option<&'a str>,
}

impl<'a> ExpectedErrorMessageBuilder<'a> {
    /// Create a builder expecting the given main error message (contents of
    /// `Display`)
    pub fn error(msg: &'a str) -> Self {
        Self {
            error: msg,
            help: None,
            prefix: false,
            underlines: vec![],
            source: None,
        }
    }

    /// Create a builder expecting the main error message (contents of
    /// `Display`) to _start with_ the given text.
    ///
    /// (If you later add expected help text to this builder, that will
    /// also be an expected prefix, not the entire expected help text.)
    pub fn error_starts_with(msg: &'a str) -> Self {
        Self {
            error: msg,
            help: None,
            prefix: true,
            underlines: vec![],
            source: None,
        }
    }

    /// Add expected contents of `help()`, or expected prefix of `help()` if
    /// this builder was originally constructed with `error_starts_with()`
    pub fn help(self, msg: &'a str) -> Self {
        Self {
            help: Some(msg),
            ..self
        }
    }

    /// Add expected underlined text. The error message will be expected to have
    /// exactly one miette label, and the underlined portion should be `snippet`.
    /// The underlined text should have no associated label text.
    pub fn exactly_one_underline(self, snippet: &'a str) -> Self {
        Self {
            underlines: vec![(snippet, None)],
            ..self
        }
    }

    /// Add expected underlined text. The error message will be expected to have
    /// exactly one miette label, and the underlined portion should be `snippet`.
    /// The label text is expected to match `label`.
    pub fn exactly_one_underline_with_label(self, snippet: &'a str, label: &'a str) -> Self {
        Self {
            underlines: vec![(snippet, Some(label))],
            ..self
        }
    }

    /// Add expected underlined text. The error message will be expected to have
    /// exactly two miette labels, and the underlined portions should be `snippet1`
    /// and `snippet2`, in that order.
    /// Both labels should have no associated label text.
    pub fn exactly_two_underlines(self, snippet1: &'a str, snippet2: &'a str) -> Self {
        Self {
            underlines: vec![(snippet1, None), (snippet2, None)],
            ..self
        }
    }

    /// Add expected underlined text. The error message will be expected to have
    /// exactly this many miette labels, and for each label (a, b), the underlined
    /// portion should be `a` and the label text should be `b` (or `None` for no
    /// label text).
    pub fn with_underlines_or_labels(
        self,
        labels: impl IntoIterator<Item = (&'a str, Option<&'a str>)>,
    ) -> Self {
        Self {
            underlines: labels.into_iter().collect(),
            ..self
        }
    }

    /// Add expected contents of `source()`, or expected prefix of `source()` if
    /// this builder was originally constructed with `error_starts_with()`
    pub fn source(self, msg: &'a str) -> Self {
        Self {
            source: Some(msg),
            ..self
        }
    }

    /// Build the [`ExpectedErrorMessage`]
    pub fn build(self) -> ExpectedErrorMessage<'a> {
        ExpectedErrorMessage {
            error: self.error,
            help: self.help,
            prefix: self.prefix,
            underlines: self.underlines,
            source: self.source,
        }
    }
}

impl<'a> ExpectedErrorMessage<'a> {
    /// Return a boolean indicating whether a given error matches this expected message.
    /// (If you want to assert that it matches, use [`expect_err()`] instead,
    /// for much better assertion-failure messages.)
    pub fn matches(&self, error: &impl miette::Diagnostic) -> bool {
        self.matches_error(error)
            && self.matches_help(error)
            && self.matches_source(error)
            && self.matches_underlines(error)
    }

    /// Internal helper: whether the main error message matches
    fn matches_error(&self, error: &impl miette::Diagnostic) -> bool {
        let e_string = error.to_string();
        if self.prefix {
            e_string.starts_with(self.error)
        } else {
            e_string == self.error
        }
    }

    /// Internal helper: assert the main error message matches
    #[track_caller]
    fn expect_error_matches(&self, src: impl Into<OriginalInput<'a>>, error: &miette::Report) {
        let e_string = error.to_string();
        if self.prefix {
            assert!(
                e_string.starts_with(self.error),
                "for the following input:\n{}\nfor the following error:\n{error:?}\n\nactual error did not start with the expected prefix\n  actual error: {error}\n  expected prefix: {}", // the Debug representation of miette::Report is the pretty one
                src.into(),
                self.error,
            );
        } else {
            assert_eq!(
                &e_string,
                self.error,
                "for the following input:\n{}\nfor the following error:\n{error:?}\n\nactual error did not match expected", // assert_eq! will print the actual and expected messages
                src.into(),
            );
        }
    }

    /// Internal helper: whether the help message matches
    fn matches_help(&self, error: &impl miette::Diagnostic) -> bool {
        let h_string = error.help().map(|h| h.to_string());
        if self.prefix {
            match (h_string.as_deref(), self.help) {
                (Some(actual), Some(expected)) => actual.starts_with(expected),
                (None, None) => true,
                _ => false,
            }
        } else {
            h_string.as_deref() == self.help
        }
    }

    /// Internal helper: whether the source message matches
    fn matches_source(&self, error: &impl miette::Diagnostic) -> bool {
        let s_string = error.source().map(|s| s.to_string());
        if self.prefix {
            match (s_string.as_deref(), self.source) {
                (Some(actual), Some(expected)) => actual.starts_with(expected),
                (None, None) => true,
                _ => false,
            }
        } else {
            s_string.as_deref() == self.source
        }
    }

    /// Internal helper used to check help or source messages
    #[track_caller]
    fn expect_help_or_source_matches(
        &self,
        src: impl Into<OriginalInput<'a>>,
        error: &miette::Report,
        h_or_s: &str,
        actual: Option<&str>,
        expected: Option<&str>,
    ) {
        if self.prefix {
            match (actual, expected) {
                (Some(actual), Some(expected)) => {
                    assert!(
                        actual.starts_with(expected),
                        "for the following input:\n{}\nfor the following error:\n{error:?}\n\nactual {h_or_s} did not start with the expected prefix\n  actual {h_or_s}: {actual}\n  expected {h_or_s}: {expected}", // the Debug representation of miette::Report is the pretty one
                        src.into(),
                    )
                }
                (None, None) => (),
                (Some(actual), None) => panic!(
                    "for the following input:\n{}\nfor the following error:\n{error:?}\n\ndid not expect a {h_or_s} message, but found one: {actual}", // the Debug representation of miette::Report is the pretty one
                    src.into(),
                ),
                (None, Some(expected)) => panic!(
                    "for the following input:\n{}\nfor the following error:\n{error:?}\n\ndid not find a {h_or_s} message, but expected one: {expected}", // the Debug representation of miette::Report is the pretty one
                    src.into(),
                ),
            }
        } else {
            assert_eq!(
                actual,
                expected,
                "for the following input:\n{}\nfor the following error:\n{error:?}\n\nactual {h_or_s} did not match expected", // assert_eq! will print the actual and expected messages
                src.into(),
            );
        }
    }

    /// Internal helper: assert the help message matches
    #[track_caller]
    fn expect_help_matches(&self, src: impl Into<OriginalInput<'a>>, error: &miette::Report) {
        let h_string = error.help().map(|h| h.to_string());
        self.expect_help_or_source_matches(src, error, "help", h_string.as_deref(), self.help);
    }

    /// Internal helper: assert the source message matches
    #[track_caller]
    fn expect_source_matches(&self, src: impl Into<OriginalInput<'a>>, error: &miette::Report) {
        let s_string = error.source().map(|s| s.to_string());
        self.expect_help_or_source_matches(src, error, "source", s_string.as_deref(), self.source);
    }

    /// Internal helper: whether the underlines match
    fn matches_underlines(&self, err: &impl miette::Diagnostic) -> bool {
        let expected_num_labels = self.underlines.len();
        let actual_num_labels = err.labels().map(|iter| iter.count()).unwrap_or(0);
        if expected_num_labels != actual_num_labels {
            return false;
        }
        if expected_num_labels != 0 {
            let src = err
                .source_code()
                .expect("err.source_code() should be `Some` if we are expecting underlines");
            for (expected, actual) in self
                .underlines
                .iter()
                .zip(err.labels().unwrap_or_else(|| Box::new(std::iter::empty())))
            {
                let (expected_snippet, expected_label) = expected;
                let actual_snippet = {
                    let span = actual.inner();
                    std::str::from_utf8(src.read_span(span, 0, 0).expect("should read span").data())
                        .expect("should be utf8 encoded")
                };
                let actual_label = actual.label();
                if expected_snippet != &actual_snippet {
                    return false;
                }
                if expected_label != &actual_label {
                    return false;
                }
            }
        }
        true
    }

    /// Internal helper: assert the underlines match
    #[track_caller]
    fn expect_underlines_match(&self, err: &miette::Report) {
        let expected_num_labels = self.underlines.len();
        let actual_num_labels = err.labels().map(|iter| iter.count()).unwrap_or(0);
        assert_eq!(expected_num_labels, actual_num_labels, "in the following error:\n{err:?}\n\nexpected {expected_num_labels} underlines but found {actual_num_labels}"); // the Debug representation of miette::Report is the pretty one
        if expected_num_labels != 0 {
            let src = err
                .source_code()
                .expect("err.source_code() should be `Some` if we are expecting underlines");
            for (expected, actual) in self
                .underlines
                .iter()
                .zip(err.labels().unwrap_or_else(|| Box::new(std::iter::empty())))
            {
                let (expected_snippet, expected_label) = expected;
                let actual_snippet = {
                    let span = actual.inner();
                    std::str::from_utf8(src.read_span(span, 0, 0).expect("should read span").data())
                        .expect("should be utf8 encoded")
                };
                let actual_label = actual.label();
                assert_eq!(
                    expected_snippet,
                    &actual_snippet,
                    "in the following error:\n{err:?}\n\nexpected underlined portion to be:\n  {expected_snippet}\nbut it was:\n  {actual_snippet}", // the Debug representation of miette::Report is the pretty one
                );
                assert_eq!(
                    expected_label,
                    &actual_label,
                    "in the following error:\n{err:?}\n\nexpected underlined help text to be:\n  {expected_label:?}\nbut it was:\n  {actual_label:?}", // the Debug representation of miette::Report is the pretty one
                );
            }
        }
    }
}

impl std::fmt::Display for ExpectedErrorMessage<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.prefix {
            writeln!(f, "expected error to start with: {}", self.error)?;
            match self.help {
                Some(help) => writeln!(f, "expected help to start with: {help}")?,
                None => writeln!(f, "  with no help message")?,
            }
        } else {
            writeln!(f, "expected error: {}", self.error)?;
            match self.help {
                Some(help) => writeln!(f, "expected help: {help}")?,
                None => writeln!(f, "  with no help message")?,
            }
        }
        if self.underlines.is_empty() {
            writeln!(f, "and expected no source locations / underlined segments.")?;
        } else {
            writeln!(f, "and expected the following underlined segments:")?;
            for (underline, label) in &self.underlines {
                writeln!(f, "  {underline}")?;
                if let Some(label) = label {
                    writeln!(f, "  with label {label}")?
                }
            }
        }
        Ok(())
    }
}

/// Forms in which [`expect_err()`] accepts the original input text.
/// See notes on [`expect_err()`].
#[derive(Debug)]
pub enum OriginalInput<'a> {
    /// A plain string
    String(&'a str),
    /// A JSON value. We will not incur the cost of formatting this to
    /// string unless it is actually needed.
    Json(&'a serde_json::Value),
}

impl<'a> From<&'a str> for OriginalInput<'a> {
    fn from(value: &'a str) -> Self {
        Self::String(value)
    }
}

impl<'a> From<&'a serde_json::Value> for OriginalInput<'a> {
    fn from(value: &'a serde_json::Value) -> Self {
        Self::Json(value)
    }
}

impl std::fmt::Display for OriginalInput<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::String(s) => write!(f, "{s}"),
            Self::Json(val) => write!(f, "{}", serde_json::to_string_pretty(val).unwrap()),
        }
    }
}

/// Expect that the given `err` is an error with the given `ExpectedErrorMessage`.
///
/// `src` is the original input text, just for better assertion-failure messages.
/// This function accepts any `impl Into<OriginalInput>` for `src`,
/// including `&str` and `&serde_json::Value`.
#[track_caller] // report the caller's location as the location of the panic, not the location in this function
pub fn expect_err<'a>(
    src: impl Into<OriginalInput<'a>> + Copy,
    err: &miette::Report,
    msg: &ExpectedErrorMessage<'a>,
) {
    msg.expect_error_matches(src, err);
    msg.expect_help_matches(src, err);
    msg.expect_source_matches(src, err);
    msg.expect_underlines_match(err);
}

/// Assert equality of `Entities` using structural equality with the `deep_eq` method.
#[macro_export]
macro_rules! assert_deep_eq {
    ( $self:expr , $other:expr ) => {
        assert!(
            $self.deep_eq(&$other),
            "expected that {:?} would be structurally equal to {:?}",
            $self,
            $other
        )
    };
}

/// Assert inequality of `Entities` using structural equality with the `deep_eq` method.
#[macro_export]
macro_rules! assert_not_deep_eq {
    ( $self:expr , $other:expr ) => {
        assert!(
            !$self.deep_eq(&$other),
            "expected that {:?} would not be structurally equal to {:?}",
            $self,
            $other
        )
    };
}