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::{
18 err::{JsonDeserializationError, JsonDeserializationErrorContext},
19 SchemaType, ValueParser,
20};
21use crate::ast::{Context, ContextCreationError};
22use crate::extensions::Extensions;
23use miette::Diagnostic;
24use std::collections::BTreeMap;
25use thiserror::Error;
26
27/// Trait for schemas that can inform the parsing of Context data
28pub trait ContextSchema {
29 /// `SchemaType` (expected to be a `Record`) for the context.
30 fn context_type(&self) -> SchemaType;
31}
32
33/// Simple type that implements `ContextSchema` by expecting an empty context
34#[derive(Debug, Clone)]
35pub struct NullContextSchema;
36impl ContextSchema for NullContextSchema {
37 fn context_type(&self) -> SchemaType {
38 SchemaType::Record {
39 attrs: BTreeMap::new(),
40 open_attrs: false,
41 }
42 }
43}
44
45/// Struct used to parse context from JSON.
46#[derive(Debug, Clone)]
47pub struct ContextJsonParser<'e, 's, S: ContextSchema = NullContextSchema> {
48 /// If a `schema` is present, this will inform the parsing: for instance, it
49 /// will allow `__entity` and `__extn` escapes to be implicit.
50 /// It will also ensure that the produced `Context` fully conforms to the
51 /// `schema` -- for instance, it will error if attributes have the wrong
52 /// types (e.g., string instead of integer), or if required attributes are
53 /// missing or superfluous attributes are provided.
54 schema: Option<&'s S>,
55
56 /// Extensions which are active for the JSON parsing.
57 extensions: &'e Extensions<'e>,
58}
59
60impl<'e, 's, S: ContextSchema> ContextJsonParser<'e, 's, S> {
61 /// Create a new `ContextJsonParser`.
62 ///
63 /// If a `schema` is present, this will inform the parsing: for instance, it
64 /// will allow `__entity` and `__extn` escapes to be implicit.
65 /// It will also ensure that the produced `Context` fully conforms to the
66 /// `schema` -- for instance, it will error if attributes have the wrong
67 /// types (e.g., string instead of integer), or if required attributes are
68 /// missing or superfluous attributes are provided.
69 pub fn new(schema: Option<&'s S>, extensions: &'e Extensions<'e>) -> Self {
70 Self { schema, extensions }
71 }
72
73 /// Parse context JSON (in `&str` form) into a `Context` object
74 pub fn from_json_str(&self, json: &str) -> Result<Context, ContextJsonDeserializationError> {
75 let val =
76 serde_json::from_str(json).map_err(|e| JsonDeserializationError::Serde(e.into()))?;
77 self.from_json_value(val)
78 }
79
80 /// Parse context JSON (in `serde_json::Value` form) into a `Context` object
81 pub fn from_json_value(
82 &self,
83 json: serde_json::Value,
84 ) -> Result<Context, ContextJsonDeserializationError> {
85 let vparser = ValueParser::new(self.extensions);
86 let expected_ty = self.schema.map(|s| s.context_type());
87 let rexpr = vparser.val_into_restricted_expr(json, expected_ty.as_ref(), || {
88 JsonDeserializationErrorContext::Context
89 })?;
90 Context::from_expr(rexpr.as_borrowed(), self.extensions)
91 .map_err(ContextJsonDeserializationError::ContextCreation)
92 }
93
94 /// Parse context JSON (in `std::io::Read` form) into a `Context` object
95 pub fn from_json_file(
96 &self,
97 json: impl std::io::Read,
98 ) -> Result<Context, ContextJsonDeserializationError> {
99 let val = serde_json::from_reader(json).map_err(JsonDeserializationError::from)?;
100 self.from_json_value(val)
101 }
102}
103
104/// Errors possible when deserializing request context from JSON
105#[derive(Debug, Diagnostic, Error)]
106pub enum ContextJsonDeserializationError {
107 /// Any JSON deserialization error
108 ///
109 /// (Note: as of this writing, `JsonDeserializationError` actually contains
110 /// many variants that aren't possible here)
111 #[error(transparent)]
112 #[diagnostic(transparent)]
113 JsonDeserialization(#[from] JsonDeserializationError),
114 /// Error constructing the `Context` itself
115 #[error(transparent)]
116 #[diagnostic(transparent)]
117 ContextCreation(#[from] ContextCreationError),
118}