ash_jsonapi/validation.rs
1//! Validating request documents before they reach your code.
2//!
3//! JSON:API wraps a resource in a
4//! `{"data":{"type","id","attributes","relationships"}}` envelope. This
5//! module builds a JSON Schema for that envelope from your resource's
6//! [`Schema`](crate::Schema) plus a JSON Schema for its attributes, and
7//! checks request bodies against it.
8//!
9//! ```ignore
10//! let validator = DocumentValidator::builder(&todo_schema)
11//! .attributes(serde_json::json!({
12//! "type": "object",
13//! "properties": { "message": { "type": "string" } },
14//! "required": ["message"],
15//! }))
16//! .build()?;
17//!
18//! let json = validator.parse(&body, &ctx)?; // Vec<JsonApiError> on failure
19//! ```
20//!
21//! The pay-off is the errors. Each failure is reported with its instance
22//! location as a JSON Pointer, which is exactly what JSON:API's
23//! `source.pointer` is — so one malformed body comes back as a complete error
24//! document, pointing at every member that caused it, with no per-field
25//! checks written by hand.
26//!
27//! # `format`
28//!
29//! JSON Schema 2020-12 treats `format` as an annotation, so `"format":
30//! "email"` checks nothing by default. This crate asserts it instead: a
31//! request schema that names a format is stating a rule, and a rule that
32//! silently does nothing is worse than none. `date`, `date-time`, `time`,
33//! `duration`, `email`, `idn-email`, `hostname`, `ipv4`, `ipv6`, `uuid`,
34//! `json-pointer` and `relative-json-pointer` are checked;
35//! [`ValidatorBuilder::format`] supplies a check for anything else, and
36//! [`ValidatorBuilder::annotate_formats`] turns assertion off.
37//!
38//! With [`resource!`](crate::resource!), a field typed
39//! [`Formatted<Email>`](crate::Formatted) declares and asserts the format in
40//! one place.
41//!
42//! Using `ash-domain`? [`DocumentValidator::for_create`] derives the
43//! attribute schema from a `ResourceSchema`, so there is nothing to write.
44
45use ash_jsonschema::validator::CompileError;
46use ash_jsonschema::validator::Mode;
47use ash_jsonschema::{Schema, SchemaError, Validator};
48
49use crate::context::Context;
50use crate::error::JsonApiError;
51use crate::serialize::{RelationshipDef, Schema as ResourceDef};
52
53/// Why a validator could not be built from a resource schema.
54///
55/// A startup failure in every case: the schema is fixed once the domain is
56/// registered, so this cannot fire at request time.
57#[derive(Debug)]
58pub enum BuildError {
59 /// The derived schema is not valid JSON Schema 2020-12.
60 Schema(SchemaError),
61 /// `ash-domain`'s attribute schema did not deserialize.
62 Attributes(serde_json::Error),
63 /// The schema is valid but could not be compiled into a validator.
64 Compile(CompileError),
65}
66
67impl std::fmt::Display for BuildError {
68 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69 match self {
70 Self::Schema(err) => write!(f, "derived schema is invalid: {err}"),
71 Self::Attributes(err) => write!(f, "attribute schema did not parse: {err}"),
72 Self::Compile(err) => write!(f, "schema did not compile: {err}"),
73 }
74 }
75}
76
77impl std::error::Error for BuildError {}
78
79impl From<SchemaError> for BuildError {
80 fn from(err: SchemaError) -> Self {
81 Self::Schema(err)
82 }
83}
84
85impl From<serde_json::Error> for BuildError {
86 fn from(err: serde_json::Error) -> Self {
87 Self::Attributes(err)
88 }
89}
90
91impl From<CompileError> for BuildError {
92 fn from(err: CompileError) -> Self {
93 Self::Compile(err)
94 }
95}
96
97/// Validates create documents for one resource.
98pub struct DocumentValidator {
99 validator: Validator,
100}
101
102/// A caller-supplied `format` check, as stored until the validator is built.
103type FormatCheck = Box<dyn Fn(&str) -> bool + Send + Sync>;
104
105/// Builds a [`DocumentValidator`] for one resource.
106///
107/// Created by [`DocumentValidator::builder`].
108pub struct ValidatorBuilder<'a, S: ResourceDef> {
109 schema: &'a S,
110 attributes: serde_json::Value,
111 hidden: Vec<String>,
112 assert_formats: bool,
113 formats: Vec<(String, FormatCheck)>,
114}
115
116impl<'a, S: ResourceDef> ValidatorBuilder<'a, S> {
117 /// The JSON Schema an `attributes` object must satisfy.
118 ///
119 /// Anything JSON Schema 2020-12 accepts — usually an `object` with
120 /// `properties` and `required`.
121 #[must_use]
122 pub fn attributes(mut self, schema: serde_json::Value) -> Self {
123 self.attributes = schema;
124 self
125 }
126
127 /// Drop these properties from the attribute schema.
128 ///
129 /// For fields your storage has but the wire format does not: the primary
130 /// key (JSON:API carries it in the envelope) and any foreign key behind a
131 /// relationship (carried as linkage).
132 #[must_use]
133 pub fn hide(mut self, names: impl IntoIterator<Item = impl Into<String>>) -> Self {
134 self.hidden.extend(names.into_iter().map(Into::into));
135 self
136 }
137
138 /// Stop asserting `format`, leaving it an annotation.
139 ///
140 /// JSON Schema 2020-12 makes `format` an annotation by default, and
141 /// ash-jsonschema follows that. This crate turns assertion *on*, because
142 /// a resource declaring `format: "email"` in a request schema means it
143 /// wants the check — an unasserted `format` is a validation rule that
144 /// silently does nothing.
145 ///
146 /// Turn it off when a schema is shared with a consumer that only
147 /// annotates, so both ends agree on what is accepted.
148 ///
149 /// Asserted: `date`, `date-time`, `time`, `duration`, `email`,
150 /// `idn-email`, `hostname`, `ipv4`, `ipv6`, `uuid`, `json-pointer` and
151 /// `relative-json-pointer`. Any other name stays an annotation unless you
152 /// give it a check with [`format`](Self::format).
153 #[must_use]
154 pub fn annotate_formats(mut self) -> Self {
155 self.assert_formats = false;
156 self
157 }
158
159 /// Assert one `format` with a check of your own.
160 ///
161 /// For a format the specification does not define — an internal id
162 /// shape, a tenant-scoped key — or to replace a built-in check with a
163 /// stricter one:
164 ///
165 /// ```ignore
166 /// DocumentValidator::builder(&schema)
167 /// .attributes(attributes)
168 /// .format("employee-id", |value| {
169 /// value.strip_prefix("E-").is_some_and(|n| n.len() == 6)
170 /// })
171 /// .build()?
172 /// ```
173 ///
174 /// The schema stays ordinary JSON Schema: another validator annotates
175 /// `"format": "employee-id"` where this one asserts it. The check only
176 /// ever sees strings, since `format` says nothing about other types.
177 #[must_use]
178 pub fn format<F>(mut self, name: impl Into<String>, check: F) -> Self
179 where
180 F: Fn(&str) -> bool + Send + Sync + 'static,
181 {
182 self.formats.push((name.into(), Box::new(check)));
183 self
184 }
185
186 /// Compile the validator.
187 ///
188 /// Do this once at startup: a schema that will not compile should stop
189 /// the service rather than surface as a 500 on the first request.
190 pub fn build(mut self) -> Result<DocumentValidator, BuildError> {
191 if let Some(properties) = self
192 .attributes
193 .get_mut("properties")
194 .and_then(|p| p.as_object_mut())
195 {
196 properties.retain(|name, _| !self.hidden.iter().any(|hidden| hidden == name));
197 }
198
199 let mut resource = Schema::object()
200 .required_property(
201 "type",
202 Schema::string().constant(self.schema.name().to_string()),
203 )
204 .required_property("attributes", Schema::from_value(self.attributes)?);
205
206 let relationships = self.schema.relationships();
207 if !relationships.is_empty() {
208 resource = resource.property("relationships", relationships_schema(relationships)?);
209 }
210
211 let document = Schema::object()
212 .required_property("data", resource.build()?)
213 .build()?;
214
215 // Formats are asserted rather than annotated: a resource that
216 // declares `format: "email"` on a request attribute is stating a
217 // rule, and an unasserted format is a rule that does nothing.
218 let mut validator = Validator::builder(&document);
219 if self.assert_formats {
220 validator = validator.assert_formats();
221 }
222 for (name, check) in self.formats {
223 validator = validator.format(name, move |value| check(value));
224 }
225
226 Ok(DocumentValidator {
227 validator: validator.build()?,
228 })
229 }
230}
231
232impl DocumentValidator {
233 /// Start building a validator for `schema`.
234 pub fn builder<S: ResourceDef>(schema: &S) -> ValidatorBuilder<'_, S> {
235 ValidatorBuilder {
236 schema,
237 attributes: serde_json::json!({ "type": "object" }),
238 hidden: Vec::new(),
239 assert_formats: true,
240 formats: Vec::new(),
241 }
242 }
243
244 /// Parse a raw body and check it in one step.
245 ///
246 /// The usual entry point: a body that is not JSON at all is a 422 like
247 /// any other malformed document, so a handler has one failure path
248 /// rather than two.
249 pub fn parse(&self, body: &str, ctx: &Context) -> Result<serde_json::Value, Vec<JsonApiError>> {
250 let json: serde_json::Value = serde_json::from_str(body).map_err(|err| {
251 vec![JsonApiError::invalid(
252 ctx,
253 format!("malformed JSON: {err}"),
254 "",
255 )]
256 })?;
257
258 self.check(&json, ctx)?;
259 Ok(json)
260 }
261
262 /// Check one request body.
263 ///
264 /// Every failure becomes a JSON:API error carrying the pointer at the
265 /// member that caused it and the request's correlation id.
266 pub fn check(&self, body: &serde_json::Value, ctx: &Context) -> Result<(), Vec<JsonApiError>> {
267 let outcome = self.validator.validate(body, Mode::All);
268 if outcome.errors.is_empty() {
269 return Ok(());
270 }
271
272 Err(outcome
273 .errors
274 .iter()
275 .map(|error| {
276 // The validator's instance location is already a JSON Pointer
277 // into the document, which is what source.pointer wants.
278 JsonApiError::invalid(ctx, error.message(), error.instance_location.clone())
279 })
280 .collect())
281 }
282}
283
284/// `relationships`: one optional linkage object per declared relationship.
285fn relationships_schema<R: RelationshipDef>(defs: &[R]) -> Result<Schema, SchemaError> {
286 let mut relationships = Schema::object();
287
288 for rel in defs {
289 let identifier = Schema::object()
290 .required_property("type", Schema::string().constant(rel.target().to_string()))
291 .required_property("id", Schema::string().min_length(1))
292 .build()?;
293
294 // A to-many relationship's linkage is an array of identifiers; a
295 // to-one is a single object. The schema says which, so a client
296 // sending the wrong shape is told exactly that.
297 let data = if rel.is_to_many() {
298 Schema::array().items(identifier).build()?
299 } else {
300 identifier
301 };
302
303 relationships = relationships.property(
304 rel.name().to_string(),
305 Schema::object().required_property("data", data).build()?,
306 );
307 }
308
309 relationships.build()
310}