Skip to main content

auths_id/attestation/
json_schema_encoder.rs

1use crate::error::StorageError;
2use auths_verifier::core::Attestation;
3use jsonschema;
4use serde_json::{Value, to_vec_pretty};
5
6/// An encoder that validates an Attestation's optional `payload` field
7/// against a provided JSON schema before serializing the entire Attestation.
8#[derive(Clone, Debug)]
9pub struct JsonSchemaValidatingEncoder {
10    schema_value: Value,
11}
12
13impl JsonSchemaValidatingEncoder {
14    /// Creates a new validating encoder which will use the provided schema.
15    pub fn new(schema_value: Value) -> Self {
16        Self { schema_value }
17    }
18
19    /// Validates the `att.payload` against the stored schema (if payload exists)
20    /// and then serializes the entire `att` struct to pretty JSON bytes.
21    ///
22    /// Returns `Err` if schema validation fails for an existing payload, or if
23    /// final JSON serialization fails.
24    pub fn encode(&self, att: &Attestation) -> Result<Vec<u8>, StorageError> {
25        if let Some(payload_value) = &att.payload
26            && !jsonschema::is_valid(&self.schema_value, payload_value)
27        {
28            let error_details = match jsonschema::validate(&self.schema_value, payload_value) {
29                Ok(_) => "Unknown validation error".to_string(),
30                Err(validation_error) => {
31                    format!(
32                        "Path '/payload{}': {:?}",
33                        validation_error.instance_path(),
34                        validation_error.kind()
35                    )
36                }
37            };
38            return Err(StorageError::SchemaValidation(error_details));
39        }
40
41        Ok(to_vec_pretty(att)?)
42    }
43}