Skip to main content

cedar_policy_core/entities/json/
context.rs

1/*
2 * Copyright Cedar Contributors
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      https://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use super::{JsonDeserializationError, JsonDeserializationErrorContext, SchemaType, ValueParser};
18use crate::ast::{Context, ContextCreationError};
19use crate::extensions::Extensions;
20use miette::Diagnostic;
21use std::collections::HashMap;
22use thiserror::Error;
23
24/// Trait for schemas that can inform the parsing of Context data
25pub trait ContextSchema {
26    /// `SchemaType` (expected to be a `Record`) for the context.
27    fn context_type(&self) -> SchemaType;
28}
29
30/// Simple type that implements `ContextSchema` by expecting an empty context
31#[derive(Debug, Clone)]
32pub struct NullContextSchema;
33impl ContextSchema for NullContextSchema {
34    fn context_type(&self) -> SchemaType {
35        SchemaType::Record {
36            attrs: HashMap::new(),
37            open_attrs: false,
38        }
39    }
40}
41
42/// Struct used to parse context from JSON.
43#[derive(Debug, Clone)]
44pub struct ContextJsonParser<'e, 's, S: ContextSchema = NullContextSchema> {
45    /// If a `schema` is present, this will inform the parsing: for instance, it
46    /// will allow `__entity` and `__extn` escapes to be implicit.
47    /// It will also ensure that the produced `Context` fully conforms to the
48    /// `schema` -- for instance, it will error if attributes have the wrong
49    /// types (e.g., string instead of integer), or if required attributes are
50    /// missing or superfluous attributes are provided.
51    schema: Option<&'s S>,
52
53    /// Extensions which are active for the JSON parsing.
54    extensions: Extensions<'e>,
55}
56
57impl<'e, 's, S: ContextSchema> ContextJsonParser<'e, 's, S> {
58    /// Create a new `ContextJsonParser`.
59    ///
60    /// If a `schema` is present, this will inform the parsing: for instance, it
61    /// will allow `__entity` and `__extn` escapes to be implicit.
62    /// It will also ensure that the produced `Context` fully conforms to the
63    /// `schema` -- for instance, it will error if attributes have the wrong
64    /// types (e.g., string instead of integer), or if required attributes are
65    /// missing or superfluous attributes are provided.
66    pub fn new(schema: Option<&'s S>, extensions: Extensions<'e>) -> Self {
67        Self { schema, extensions }
68    }
69
70    /// Parse context JSON (in `&str` form) into a `Context` object
71    pub fn from_json_str(&self, json: &str) -> Result<Context, ContextJsonDeserializationError> {
72        let val = serde_json::from_str(json).map_err(JsonDeserializationError::Serde)?;
73        self.from_json_value(val)
74    }
75
76    /// Parse context JSON (in `serde_json::Value` form) into a `Context` object
77    pub fn from_json_value(
78        &self,
79        json: serde_json::Value,
80    ) -> Result<Context, ContextJsonDeserializationError> {
81        let vparser = ValueParser::new(self.extensions);
82        let expected_ty = self.schema.map(|s| s.context_type());
83        let rexpr = vparser.val_into_restricted_expr(json, expected_ty.as_ref(), || {
84            JsonDeserializationErrorContext::Context
85        })?;
86        Context::from_expr(rexpr.as_borrowed(), self.extensions)
87            .map_err(ContextJsonDeserializationError::ContextCreation)
88    }
89
90    /// Parse context JSON (in `std::io::Read` form) into a `Context` object
91    pub fn from_json_file(
92        &self,
93        json: impl std::io::Read,
94    ) -> Result<Context, ContextJsonDeserializationError> {
95        let val = serde_json::from_reader(json).map_err(JsonDeserializationError::from)?;
96        self.from_json_value(val)
97    }
98}
99
100/// Errors possible when deserializing request context from JSON
101#[derive(Debug, Diagnostic, Error)]
102pub enum ContextJsonDeserializationError {
103    /// Any JSON deserialization error
104    ///
105    /// (Note: as of this writing, `JsonDeserializationError` actually contains
106    /// many variants that aren't possible here)
107    #[error("while parsing context, {0}")]
108    #[diagnostic(transparent)]
109    JsonDeserialization(#[from] JsonDeserializationError),
110    /// Error constructing the `Context` itself
111    #[error(transparent)]
112    #[diagnostic(transparent)]
113    ContextCreation(#[from] ContextCreationError),
114}