trust_tasks_rs/validate.rs
1//! Runtime JSON Schema validation for Trust Task payloads.
2//!
3//! Available behind the `validate` Cargo feature. The codegen inlines each
4//! spec's `payload.schema.json` as a string constant and emits a
5//! [`ValidatedPayload`] impl so callers can validate any inbound value
6//! against the on-the-wire schema, not just the structural shape serde
7//! recovers.
8//!
9//! ```ignore
10//! # #[cfg(feature = "validate")]
11//! # fn demo() -> Result<(), trust_tasks_rs::validate::ValidationError> {
12//! use trust_tasks_rs::{specs::acl::grant::v0_2, validate::ValidatedPayload};
13//!
14//! let value: serde_json::Value = serde_json::json!({
15//! "entry": {
16//! "subject": "did:web:alice.example",
17//! "role": "admin",
18//! "act": { "scope": "all" },
19//! "keys": { "scope": "all" },
20//! "capabilities": { "scope": "ceiling" }
21//! }
22//! });
23//! v0_2::Payload::validate_value(&value)?;
24//! # Ok(())
25//! # }
26//! ```
27//!
28//! This is belt-and-suspenders: most schema constraints fall out of typify's
29//! generated struct shapes, but cross-cutting checks (regex `pattern`,
30//! `minItems` on optional arrays, conditional schemas) only hold up under a
31//! true schema validator.
32
33use std::fmt;
34
35use serde_json::Value;
36use thiserror::Error;
37
38use crate::payload::Payload;
39
40/// A payload type whose original JSON Schema is embedded at compile time and
41/// available for runtime validation.
42///
43/// Implemented automatically by the codegen for every generated request and
44/// response payload type.
45pub trait ValidatedPayload: Payload {
46 /// Validate `value` against [`Payload::PAYLOAD_SCHEMA`].
47 ///
48 /// Returns [`ValidationError`] with the collected schema-validation
49 /// errors when the value does not conform. Where the payload type
50 /// carries no schema (`PAYLOAD_SCHEMA` is `None` — the hand-modelled
51 /// `trust-task-error`), there is nothing to check and this succeeds:
52 /// the Rust type the value deserialized into is itself the constraint.
53 ///
54 /// The compiled schema is cached process-wide (see [`SchemaValidator`]),
55 /// so only the first call for a type pays for compiling it.
56 fn validate_value(value: &Value) -> Result<(), ValidationError> {
57 match Self::PAYLOAD_SCHEMA {
58 Some(schema) => SHARED.check(schema, value),
59 None => Ok(()),
60 }
61 }
62}
63
64/// Every [`Payload`] is validatable, because every `Payload` carries its
65/// schema (or states that it has none).
66///
67/// Before 0.9.0 this trait declared its own `SCHEMA_JSON` const and the
68/// codegen emitted one impl per generated type. The schema now lives on
69/// `Payload` itself — reachable without the `validate` feature, since a
70/// `&'static str` costs nothing — and this blanket impl replaces roughly
71/// three hundred generated impl blocks.
72impl<P: Payload> ValidatedPayload for P {}
73
74/// Compile `schema_json` as a JSON Schema and validate `value` against it.
75///
76/// Compilation is performed every call. To validate many documents, use a
77/// [`SchemaValidator`], which compiles each schema once and keeps it.
78///
79/// # ⚠ Schema-validation DoS surface (SPEC §12.3)
80///
81/// `schema_json` MUST be trusted by the caller. The underlying
82/// `jsonschema` crate compiles `pattern` keywords through a regex engine
83/// that supports backtracking, so a malicious schema can carry a
84/// `pattern` such as `"^(a+)+$"` and validation will consume unbounded
85/// CPU on otherwise-innocuous strings.
86///
87/// The codegen-emitted [`ValidatedPayload`] impls satisfy this rule
88/// trivially because the schemas are inlined as string constants from the
89/// repo at codegen time and frozen at build time. If you call this function directly
90/// with a schema obtained from any other source — content-negotiating
91/// a URI over the network, accepting a private-spec submission per
92/// SPEC §6.5, etc. — you MUST authenticate the schema's source and
93/// SHOULD apply a per-validation timeout outside this call.
94pub fn against_schema(schema_json: &str, value: &Value) -> Result<(), ValidationError> {
95 run(&compile(schema_json)?, value)
96}
97
98fn compile(schema_json: &str) -> Result<jsonschema::Validator, ValidationError> {
99 let schema_value: Value =
100 serde_json::from_str(schema_json).map_err(ValidationError::schema_parse)?;
101 jsonschema::options()
102 .with_draft(jsonschema::Draft::Draft202012)
103 .build(&schema_value)
104 .map_err(|e| ValidationError::schema_compile(e.to_string()))
105}
106
107fn run(compiled: &jsonschema::Validator, value: &Value) -> Result<(), ValidationError> {
108 let messages: Vec<String> = compiled.iter_errors(value).map(|e| e.to_string()).collect();
109 if !messages.is_empty() {
110 return Err(ValidationError::instance(messages));
111 }
112 Ok(())
113}
114
115/// The cache [`ValidatedPayload::validate_value`] and
116/// [`DeclaredErrorCode::check_details`](crate::DeclaredErrorCode::check_details) share.
117pub(crate) static SHARED: SchemaValidator = SchemaValidator::new();
118
119/// A [`PayloadValidator`] over the `jsonschema` crate (JSON Schema draft
120/// 2020-12) that compiles each schema once and keeps it — the validator
121/// [`PayloadPolicy::Validate`] wants.
122///
123/// The schemas it is handed are `Payload::PAYLOAD_SCHEMA` constants, which
124/// never move; the compiled validator is cached by the schema text's address
125/// and confirmed against its content, so a document pays for evaluation only,
126/// never for parsing and compiling a schema of tens of KB and its `pattern`
127/// regexes. One instance serves every task; keep it for the life of the
128/// consumer — a `static` works:
129///
130/// ```rust
131/// use trust_tasks_rs::{validate::SchemaValidator, PayloadPolicy};
132///
133/// static VALIDATOR: SchemaValidator = SchemaValidator::new();
134/// let policy = PayloadPolicy::Validate(&VALIDATOR);
135/// # let _ = policy;
136/// ```
137///
138/// The SPEC §12.3 caution on [`against_schema`] applies: hand it only
139/// schemas whose source you trust.
140///
141/// [`PayloadValidator`]: crate::PayloadValidator
142/// [`PayloadPolicy::Validate`]: crate::PayloadPolicy::Validate
143pub struct SchemaValidator {
144 compiled: crate::schema_cache::SchemaCache<jsonschema::Validator>,
145}
146
147impl SchemaValidator {
148 /// An empty cache.
149 pub const fn new() -> Self {
150 Self {
151 compiled: crate::schema_cache::SchemaCache::new(),
152 }
153 }
154
155 /// Validate `value` against `schema_json`, compiling the schema on first
156 /// use.
157 pub fn check(&self, schema_json: &str, value: &Value) -> Result<(), ValidationError> {
158 let compiled = self.compiled.get_or_try_insert(schema_json, compile)?;
159 run(&compiled, value)
160 }
161}
162
163impl Default for SchemaValidator {
164 fn default() -> Self {
165 Self::new()
166 }
167}
168
169impl fmt::Debug for SchemaValidator {
170 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
171 f.debug_struct("SchemaValidator").finish_non_exhaustive()
172 }
173}
174
175impl crate::PayloadValidator for SchemaValidator {
176 fn validate(&self, schema_json: &str, payload: &Value) -> Result<(), String> {
177 self.check(schema_json, payload).map_err(|e| e.to_string())
178 }
179}
180
181/// One or more schema-validation problems encountered while checking a value.
182#[derive(Debug, Error)]
183pub struct ValidationError {
184 kind: ErrorKind,
185 messages: Vec<String>,
186}
187
188#[derive(Debug)]
189enum ErrorKind {
190 /// The embedded schema JSON failed to parse.
191 SchemaParse,
192 /// The schema parsed but failed to compile under Draft 2020-12.
193 SchemaCompile,
194 /// The instance failed validation against a well-formed schema.
195 Instance,
196}
197
198impl ValidationError {
199 fn schema_parse(e: serde_json::Error) -> Self {
200 Self {
201 kind: ErrorKind::SchemaParse,
202 messages: vec![e.to_string()],
203 }
204 }
205
206 fn schema_compile(message: String) -> Self {
207 Self {
208 kind: ErrorKind::SchemaCompile,
209 messages: vec![message],
210 }
211 }
212
213 fn instance(messages: Vec<String>) -> Self {
214 Self {
215 kind: ErrorKind::Instance,
216 messages,
217 }
218 }
219
220 /// The collected per-error messages from the validator, in source order.
221 pub fn messages(&self) -> &[String] {
222 &self.messages
223 }
224}
225
226impl fmt::Display for ValidationError {
227 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
228 let label = match self.kind {
229 ErrorKind::SchemaParse => "schema JSON did not parse",
230 ErrorKind::SchemaCompile => "schema did not compile",
231 ErrorKind::Instance => "payload failed schema validation",
232 };
233 write!(f, "{label}: {}", self.messages.join("; "))
234 }
235}
236
237#[cfg(test)]
238mod tests {
239 use super::*;
240 use crate::PayloadValidator;
241 use serde_json::json;
242
243 static SCHEMA: &str = r#"{
244 "$schema": "https://json-schema.org/draft/2020-12/schema",
245 "type": "object",
246 "required": ["name"],
247 "properties": { "name": { "type": "string", "pattern": "^[a-z]+$" } }
248 }"#;
249
250 #[test]
251 fn schema_validator_accepts_and_refuses_as_against_schema_does() {
252 let validator = SchemaValidator::new();
253 for value in [json!({"name": "ok"}), json!({"name": "NO"}), json!({})] {
254 assert_eq!(
255 validator.check(SCHEMA, &value).is_ok(),
256 against_schema(SCHEMA, &value).is_ok(),
257 "{value}"
258 );
259 }
260 assert!(validator.validate(SCHEMA, &json!({"name": "ok"})).is_ok());
261 let reason = validator.validate(SCHEMA, &json!({})).unwrap_err();
262 assert!(
263 reason.contains("payload failed schema validation"),
264 "{reason}"
265 );
266 }
267
268 #[test]
269 fn schema_validator_compiles_each_schema_once() {
270 let validator = SchemaValidator::new();
271 for _ in 0..3 {
272 validator.check(SCHEMA, &json!({"name": "ok"})).unwrap();
273 }
274 assert_eq!(validator.compiled.len(), 1);
275 }
276
277 #[test]
278 fn a_schema_that_does_not_parse_is_an_error_every_time() {
279 let validator = SchemaValidator::new();
280 for _ in 0..2 {
281 let err = validator.check("{", &json!({})).unwrap_err();
282 assert!(err.to_string().contains("did not parse"), "{err}");
283 }
284 assert_eq!(validator.compiled.len(), 0);
285 }
286}