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 = 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> 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
74impl<S: ContextSchema> ContextJsonParser<'_, '_, S> {
75 /// Parse context JSON (in `&str` form) into a `Context` object
76 pub fn from_json_str(&self, json: &str) -> Result<Context, ContextJsonDeserializationError> {
77 let val =
78 serde_json::from_str(json).map_err(|e| JsonDeserializationError::Serde(e.into()))?;
79 self.from_json_value(val)
80 }
81
82 /// Parse context JSON (in `serde_json::Value` form) into a `Context` object
83 pub fn from_json_value(
84 &self,
85 json: serde_json::Value,
86 ) -> Result<Context, ContextJsonDeserializationError> {
87 let vparser = ValueParser::new(self.extensions);
88 let expected_ty = self.schema.map(|s| s.context_type());
89 let rexpr = vparser.val_into_restricted_expr(json, expected_ty.as_ref(), || {
90 JsonDeserializationErrorContext::Context
91 })?;
92 Context::from_expr(rexpr.as_borrowed(), self.extensions)
93 .map_err(ContextJsonDeserializationError::ContextCreation)
94 }
95
96 /// Parse context JSON (in `std::io::Read` form) into a `Context` object
97 pub fn from_json_file(
98 &self,
99 json: impl std::io::Read,
100 ) -> Result<Context, ContextJsonDeserializationError> {
101 let val = serde_json::from_reader(json).map_err(JsonDeserializationError::from)?;
102 self.from_json_value(val)
103 }
104}
105
106/// Errors possible when deserializing request context from JSON
107#[derive(Debug, Diagnostic, Error)]
108pub enum ContextJsonDeserializationError {
109 /// Any JSON deserialization error
110 ///
111 /// (Note: as of this writing, `JsonDeserializationError` actually contains
112 /// many variants that aren't possible here)
113 #[error(transparent)]
114 #[diagnostic(transparent)]
115 JsonDeserialization(#[from] JsonDeserializationError),
116 /// Error constructing the `Context` itself
117 #[error(transparent)]
118 #[diagnostic(transparent)]
119 ContextCreation(#[from] ContextCreationError),
120}