Skip to main content

stateknot_runtime/
schema.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Offline, digest-pinned JSON Schema 2020-12 registry.
5
6use std::{collections::HashMap, sync::Arc};
7
8use jsonschema::{Draft, Registry, Validator};
9use schemars::{JsonSchema, Schema, SchemaGenerator};
10use serde_json::Value;
11use stateknot_core::{
12    BoundedJson, Digest, GraphSchemaValidationError, GraphSchemaValidator, ModelSchemaRegistry,
13    SchemaId, SchemaReference, ToolSchemaRegistry, ToolSchemaRole, ToolSchemaValidationError,
14    Version,
15};
16use thiserror::Error;
17
18const MEBIBYTE: usize = 1024 * 1024;
19const DRAFT_2020_12: &str = "https://json-schema.org/draft/2020-12/schema";
20
21/// Resource ceilings applied while an executable schema registry is built.
22#[derive(Clone, Copy, Debug, Eq, PartialEq)]
23#[allow(clippy::struct_field_names)]
24pub struct JsonSchemaRegistryLimits {
25    maximum_schemas: usize,
26    maximum_schema_bytes: usize,
27    maximum_total_bytes: usize,
28}
29
30impl JsonSchemaRegistryLimits {
31    /// Absolute implementation ceiling for registered resources.
32    pub const HARD_MAXIMUM_SCHEMAS: usize = 4096;
33    /// Absolute implementation ceiling for one canonical schema document.
34    pub const HARD_MAXIMUM_SCHEMA_BYTES: usize = 8 * MEBIBYTE;
35    /// Absolute implementation ceiling for all canonical schema documents.
36    pub const HARD_MAXIMUM_TOTAL_BYTES: usize = 256 * MEBIBYTE;
37
38    /// Constructs positive limits within implementation ceilings.
39    ///
40    /// # Errors
41    ///
42    /// Returns [`JsonSchemaRegistryLimitsError`] for zero, inconsistent, or
43    /// implementation-exceeding limits.
44    pub const fn new(
45        maximum_schemas: usize,
46        maximum_schema_bytes: usize,
47        maximum_total_bytes: usize,
48    ) -> Result<Self, JsonSchemaRegistryLimitsError> {
49        if maximum_schemas == 0 {
50            return Err(JsonSchemaRegistryLimitsError::ZeroSchemas);
51        }
52        if maximum_schema_bytes == 0 {
53            return Err(JsonSchemaRegistryLimitsError::ZeroSchemaBytes);
54        }
55        if maximum_total_bytes < maximum_schema_bytes {
56            return Err(JsonSchemaRegistryLimitsError::TotalBelowSingleSchema);
57        }
58        if maximum_schemas > Self::HARD_MAXIMUM_SCHEMAS {
59            return Err(JsonSchemaRegistryLimitsError::TooManySchemas {
60                maximum: Self::HARD_MAXIMUM_SCHEMAS,
61                actual: maximum_schemas,
62            });
63        }
64        if maximum_schema_bytes > Self::HARD_MAXIMUM_SCHEMA_BYTES {
65            return Err(JsonSchemaRegistryLimitsError::SchemaBytesTooLarge {
66                maximum: Self::HARD_MAXIMUM_SCHEMA_BYTES,
67                actual: maximum_schema_bytes,
68            });
69        }
70        if maximum_total_bytes > Self::HARD_MAXIMUM_TOTAL_BYTES {
71            return Err(JsonSchemaRegistryLimitsError::TotalBytesTooLarge {
72                maximum: Self::HARD_MAXIMUM_TOTAL_BYTES,
73                actual: maximum_total_bytes,
74            });
75        }
76        Ok(Self {
77            maximum_schemas,
78            maximum_schema_bytes,
79            maximum_total_bytes,
80        })
81    }
82
83    /// Returns the configured resource-count ceiling.
84    #[must_use]
85    pub const fn maximum_schemas(self) -> usize {
86        self.maximum_schemas
87    }
88
89    /// Returns the configured per-document canonical byte ceiling.
90    #[must_use]
91    pub const fn maximum_schema_bytes(self) -> usize {
92        self.maximum_schema_bytes
93    }
94
95    /// Returns the configured aggregate canonical byte ceiling.
96    #[must_use]
97    pub const fn maximum_total_bytes(self) -> usize {
98        self.maximum_total_bytes
99    }
100}
101
102impl Default for JsonSchemaRegistryLimits {
103    fn default() -> Self {
104        Self {
105            maximum_schemas: 1024,
106            maximum_schema_bytes: 2 * MEBIBYTE,
107            maximum_total_bytes: 64 * MEBIBYTE,
108        }
109    }
110}
111
112/// Invalid executable schema-registry limits.
113#[derive(Clone, Debug, Eq, Error, PartialEq)]
114#[non_exhaustive]
115pub enum JsonSchemaRegistryLimitsError {
116    /// A registry could contain no resources.
117    #[error("schema registry maximum schema count must be positive")]
118    ZeroSchemas,
119    /// A schema document could contain no bytes.
120    #[error("schema registry per-schema byte maximum must be positive")]
121    ZeroSchemaBytes,
122    /// The aggregate ceiling could not contain one maximum-size document.
123    #[error("schema registry total byte maximum is below its per-schema maximum")]
124    TotalBelowSingleSchema,
125    /// The resource-count ceiling exceeded the implementation bound.
126    #[error("schema registry maximum is {actual}; implementation maximum is {maximum}")]
127    TooManySchemas {
128        /// Absolute implementation maximum.
129        maximum: usize,
130        /// Rejected configured value.
131        actual: usize,
132    },
133    /// The per-document byte ceiling exceeded the implementation bound.
134    #[error("schema byte maximum is {actual}; implementation maximum is {maximum}")]
135    SchemaBytesTooLarge {
136        /// Absolute implementation maximum.
137        maximum: usize,
138        /// Rejected configured value.
139        actual: usize,
140    },
141    /// The aggregate byte ceiling exceeded the implementation bound.
142    #[error("schema aggregate byte maximum is {actual}; implementation maximum is {maximum}")]
143    TotalBytesTooLarge {
144        /// Absolute implementation maximum.
145        maximum: usize,
146        /// Rejected configured value.
147        actual: usize,
148    },
149}
150
151#[derive(Clone)]
152struct PendingSchema {
153    reference: SchemaReference,
154    document: Value,
155    canonical: Arc<[u8]>,
156}
157
158/// Mutable startup-only builder for an immutable offline schema registry.
159///
160/// Every document must name the exact reference URI in `$id`, explicitly use
161/// JSON Schema 2020-12, match the reference's SHA-256 digest after RFC 8785
162/// canonicalization, and pass meta-schema validation before it is retained.
163/// The final build eagerly compiles every validator and rejects unresolved
164/// references. No schema retrieval path exists on [`JsonSchemaRegistry`].
165#[derive(Debug)]
166pub struct JsonSchemaRegistryBuilder {
167    limits: JsonSchemaRegistryLimits,
168    schemas: Vec<PendingSchema>,
169    by_reference: HashMap<SchemaReference, usize>,
170    by_id: HashMap<String, SchemaReference>,
171    total_bytes: usize,
172}
173
174impl JsonSchemaRegistryBuilder {
175    /// Creates an empty startup builder with explicit resource ceilings.
176    #[must_use]
177    pub fn new(limits: JsonSchemaRegistryLimits) -> Self {
178        Self {
179            limits,
180            schemas: Vec::new(),
181            by_reference: HashMap::new(),
182            by_id: HashMap::new(),
183            total_bytes: 0,
184        }
185    }
186
187    /// Creates an empty startup builder with production defaults.
188    #[must_use]
189    pub fn with_default_limits() -> Self {
190        Self::new(JsonSchemaRegistryLimits::default())
191    }
192
193    /// Registers one owned schema document after integrity and dialect checks.
194    ///
195    /// A URI may identify only one immutable resource in a registry. This is
196    /// stricter than keying by the full reference because JSON Schema `$ref`
197    /// resolution uses the URI and cannot select a version or digest sideband.
198    ///
199    /// # Errors
200    ///
201    /// Returns [`JsonSchemaRegistryError`] for duplicate identity, resource
202    /// exhaustion, canonicalization/digest drift, an invalid `$id`/dialect, or
203    /// a meta-schema violation.
204    pub fn register(
205        &mut self,
206        reference: SchemaReference,
207        document: Value,
208    ) -> Result<(), JsonSchemaRegistryError> {
209        if self.schemas.len() == self.limits.maximum_schemas {
210            return Err(JsonSchemaRegistryError::TooManySchemas {
211                maximum: self.limits.maximum_schemas,
212                actual: self.limits.maximum_schemas + 1,
213            });
214        }
215        if self.by_reference.contains_key(&reference) {
216            return Err(JsonSchemaRegistryError::DuplicateReference {
217                reference: Box::new(reference),
218            });
219        }
220        let id = reference.id().as_str();
221        if let Some(existing) = self.by_id.get(id) {
222            return Err(JsonSchemaRegistryError::DuplicateId {
223                existing: Box::new(existing.clone()),
224                rejected: Box::new(reference),
225            });
226        }
227
228        let object = document
229            .as_object()
230            .ok_or(JsonSchemaRegistryError::SchemaRootNotObject)?;
231        match object.get("$schema").and_then(Value::as_str) {
232            Some(DRAFT_2020_12) => {}
233            _ => return Err(JsonSchemaRegistryError::UnsupportedDialect),
234        }
235        if object.get("$id").and_then(Value::as_str) != Some(id) {
236            return Err(JsonSchemaRegistryError::IdMismatch {
237                reference: Box::new(reference),
238            });
239        }
240
241        jsonschema::draft202012::meta::validate(&document).map_err(|source| {
242            JsonSchemaRegistryError::InvalidSchema {
243                diagnostic: source.to_string().into_boxed_str(),
244            }
245        })?;
246        let canonical = serde_json_canonicalizer::to_vec(&document)
247            .map_err(|_| JsonSchemaRegistryError::Canonicalization)?;
248        if canonical.len() > self.limits.maximum_schema_bytes {
249            return Err(JsonSchemaRegistryError::SchemaTooLarge {
250                maximum: self.limits.maximum_schema_bytes,
251                actual: canonical.len(),
252            });
253        }
254        if Digest::sha256(&canonical) != reference.digest() {
255            return Err(JsonSchemaRegistryError::DigestMismatch {
256                reference: Box::new(reference),
257            });
258        }
259        let total_bytes = self.total_bytes.checked_add(canonical.len()).ok_or(
260            JsonSchemaRegistryError::AggregateTooLarge {
261                maximum: self.limits.maximum_total_bytes,
262                actual: usize::MAX,
263            },
264        )?;
265        if total_bytes > self.limits.maximum_total_bytes {
266            return Err(JsonSchemaRegistryError::AggregateTooLarge {
267                maximum: self.limits.maximum_total_bytes,
268                actual: total_bytes,
269            });
270        }
271
272        let index = self.schemas.len();
273        self.by_id.insert(id.to_owned(), reference.clone());
274        self.by_reference.insert(reference.clone(), index);
275        self.schemas.push(PendingSchema {
276            reference,
277            document,
278            canonical: canonical.into(),
279        });
280        self.total_bytes = total_bytes;
281        Ok(())
282    }
283
284    /// Generates, pins, and registers the JSON Schema for one Rust type.
285    ///
286    /// The generated document receives the supplied canonical `$id`; its
287    /// version and RFC 8785 digest are then frozen in the returned reference.
288    /// Use that reference in the corresponding tool descriptor. At
289    /// [`stateknot_core::ToolAdapter`] construction, the frozen registry proves
290    /// that the currently compiled Rust type still matches these exact bytes.
291    ///
292    /// # Errors
293    ///
294    /// Returns [`JsonSchemaRegistryError`] when generation cannot be encoded or
295    /// when the resulting document violates any ordinary registry invariant.
296    pub fn register_rust_type<T: JsonSchema>(
297        &mut self,
298        id: SchemaId,
299        version: Version,
300    ) -> Result<SchemaReference, JsonSchemaRegistryError> {
301        let generated = SchemaGenerator::default().into_root_schema_for::<T>();
302        let mut document = serde_json::to_value(generated)
303            .map_err(|_| JsonSchemaRegistryError::GeneratedSchemaSerialization)?;
304        let object = document
305            .as_object_mut()
306            .ok_or(JsonSchemaRegistryError::SchemaRootNotObject)?;
307        object.insert("$id".to_owned(), Value::String(id.as_str().to_owned()));
308        let canonical = serde_json_canonicalizer::to_vec(&document)
309            .map_err(|_| JsonSchemaRegistryError::Canonicalization)?;
310        let reference = SchemaReference::new(id, version, Digest::sha256(canonical));
311        self.register(reference.clone(), document)?;
312        Ok(reference)
313    }
314
315    /// Freezes all resources and eagerly compiles offline validators.
316    ///
317    /// # Errors
318    ///
319    /// Returns [`JsonSchemaRegistryError`] when the registry is empty, a URI
320    /// cannot be indexed, or any local `$ref` cannot be resolved and compiled.
321    pub fn build(self) -> Result<JsonSchemaRegistry, JsonSchemaRegistryError> {
322        if self.schemas.is_empty() {
323            return Err(JsonSchemaRegistryError::Empty);
324        }
325
326        let mut registry_builder = Registry::new().draft(Draft::Draft202012);
327        for schema in &self.schemas {
328            registry_builder = registry_builder
329                .add(schema.reference.id().as_str(), schema.document.clone())
330                .map_err(|source| JsonSchemaRegistryError::RegistryPreparation {
331                    diagnostic: source.to_string().into_boxed_str(),
332                })?;
333        }
334        let registry = registry_builder.prepare().map_err(|source| {
335            JsonSchemaRegistryError::RegistryPreparation {
336                diagnostic: source.to_string().into_boxed_str(),
337            }
338        })?;
339
340        let mut entries = HashMap::with_capacity(self.schemas.len());
341        for schema in self.schemas {
342            let validator = jsonschema::draft202012::options()
343                .with_registry(&registry)
344                .should_validate_formats(true)
345                .offline()
346                .build(&schema.document)
347                .map_err(|source| JsonSchemaRegistryError::ValidatorCompilation {
348                    reference: Box::new(schema.reference.clone()),
349                    diagnostic: source.to_string().into_boxed_str(),
350                })?;
351            entries.insert(
352                schema.reference,
353                CompiledSchema {
354                    canonical: schema.canonical,
355                    validator,
356                },
357            );
358        }
359
360        Ok(JsonSchemaRegistry {
361            inner: Arc::new(JsonSchemaRegistryInner {
362                entries,
363                total_bytes: self.total_bytes,
364            }),
365        })
366    }
367}
368
369impl Default for JsonSchemaRegistryBuilder {
370    fn default() -> Self {
371        Self::with_default_limits()
372    }
373}
374
375impl std::fmt::Debug for PendingSchema {
376    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
377        formatter
378            .debug_struct("PendingSchema")
379            .field("reference", &self.reference)
380            .field("canonical_bytes", &self.canonical.len())
381            .finish_non_exhaustive()
382    }
383}
384
385struct CompiledSchema {
386    canonical: Arc<[u8]>,
387    validator: Validator,
388}
389
390struct JsonSchemaRegistryInner {
391    entries: HashMap<SchemaReference, CompiledSchema>,
392    total_bytes: usize,
393}
394
395/// Immutable, shareable registry of eagerly compiled offline validators.
396#[derive(Clone)]
397pub struct JsonSchemaRegistry {
398    inner: Arc<JsonSchemaRegistryInner>,
399}
400
401impl JsonSchemaRegistry {
402    /// Returns whether the exact URI, version, and digest are installed.
403    #[must_use]
404    pub fn contains(&self, reference: &SchemaReference) -> bool {
405        self.inner.entries.contains_key(reference)
406    }
407
408    /// Returns the number of immutable schema resources.
409    #[must_use]
410    pub fn len(&self) -> usize {
411        self.inner.entries.len()
412    }
413
414    /// Returns whether the frozen registry contains no resources.
415    #[must_use]
416    pub fn is_empty(&self) -> bool {
417        self.inner.entries.is_empty()
418    }
419
420    /// Returns the total retained canonical schema bytes.
421    #[must_use]
422    pub fn total_bytes(&self) -> usize {
423        self.inner.total_bytes
424    }
425
426    /// Returns the exact canonical document bytes for trusted diagnostics.
427    #[must_use]
428    pub fn canonical_bytes(&self, reference: &SchemaReference) -> Option<&[u8]> {
429        self.inner
430            .entries
431            .get(reference)
432            .map(|entry| entry.canonical.as_ref())
433    }
434
435    /// Validates a bounded instance and retains no instance data.
436    ///
437    /// # Errors
438    ///
439    /// Returns [`GraphSchemaValidationError::Unavailable`] when the complete
440    /// reference is absent and [`GraphSchemaValidationError::Rejected`] when
441    /// the instance violates the compiled contract.
442    pub fn validate_bounded(
443        &self,
444        reference: &SchemaReference,
445        value: &BoundedJson,
446    ) -> Result<(), GraphSchemaValidationError> {
447        let entry = self
448            .inner
449            .entries
450            .get(reference)
451            .ok_or(GraphSchemaValidationError::Unavailable)?;
452        if entry.validator.is_valid(value.as_value()) {
453            Ok(())
454        } else {
455            Err(GraphSchemaValidationError::Rejected)
456        }
457    }
458}
459
460impl std::fmt::Debug for JsonSchemaRegistry {
461    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
462        formatter
463            .debug_struct("JsonSchemaRegistry")
464            .field("schemas", &self.len())
465            .field("total_bytes", &self.total_bytes())
466            .finish_non_exhaustive()
467    }
468}
469
470impl GraphSchemaValidator for JsonSchemaRegistry {
471    fn validate(
472        &self,
473        schema: &SchemaReference,
474        value: &BoundedJson,
475    ) -> Result<(), GraphSchemaValidationError> {
476        self.validate_bounded(schema, value)
477    }
478}
479
480impl ModelSchemaRegistry for JsonSchemaRegistry {
481    fn canonical_schema_bytes(&self, schema: &SchemaReference) -> Option<&[u8]> {
482        self.canonical_bytes(schema)
483    }
484}
485
486impl ToolSchemaRegistry for JsonSchemaRegistry {
487    fn validate_type_schema(
488        &self,
489        reference: &SchemaReference,
490        role: ToolSchemaRole,
491        generated: &Schema,
492    ) -> Result<(), ToolSchemaValidationError> {
493        let mut document = serde_json::to_value(generated).map_err(tool_schema_error)?;
494        let object = document
495            .as_object_mut()
496            .ok_or_else(|| tool_schema_message("generated tool schema is not an object"))?;
497        if matches!(role, ToolSchemaRole::Input)
498            && object.get("type").and_then(Value::as_str) != Some("object")
499        {
500            return Err(tool_schema_message(
501                "generated tool input schema must have an object root",
502            ));
503        }
504        object.insert(
505            "$id".to_owned(),
506            Value::String(reference.id().as_str().to_owned()),
507        );
508        let canonical = serde_json_canonicalizer::to_vec(&document).map_err(tool_schema_error)?;
509        let installed = self
510            .canonical_bytes(reference)
511            .ok_or_else(|| tool_schema_message("tool schema reference is not installed"))?;
512        if installed != canonical {
513            return Err(tool_schema_message(
514                "generated Rust schema differs from the installed tool contract",
515            ));
516        }
517        Ok(())
518    }
519
520    fn validate_instance(
521        &self,
522        reference: &SchemaReference,
523        _role: ToolSchemaRole,
524        value: &BoundedJson,
525    ) -> Result<(), ToolSchemaValidationError> {
526        self.validate_bounded(reference, value)
527            .map_err(tool_schema_error)
528    }
529}
530
531fn tool_schema_error(
532    source: impl std::error::Error + Send + Sync + 'static,
533) -> ToolSchemaValidationError {
534    ToolSchemaValidationError::new(source)
535}
536
537fn tool_schema_message(message: &'static str) -> ToolSchemaValidationError {
538    ToolSchemaValidationError::new(std::io::Error::other(message))
539}
540
541/// Startup-time failure while constructing an offline schema registry.
542#[derive(Clone, Debug, Eq, Error, PartialEq)]
543#[non_exhaustive]
544pub enum JsonSchemaRegistryError {
545    /// Runtime execution without any trusted schema would fail open.
546    #[error("schema registry must contain at least one resource")]
547    Empty,
548    /// The configured resource count was exhausted.
549    #[error("schema registry contains {actual} resources; maximum is {maximum}")]
550    TooManySchemas {
551        /// Configured maximum.
552        maximum: usize,
553        /// First rejected count.
554        actual: usize,
555    },
556    /// The complete immutable reference was registered twice.
557    #[error("schema reference was registered more than once")]
558    DuplicateReference {
559        /// Repeated reference.
560        reference: Box<SchemaReference>,
561    },
562    /// One URI attempted to identify multiple immutable resources.
563    #[error("schema URI was reused by another version or digest")]
564    DuplicateId {
565        /// First immutable reference.
566        existing: Box<SchemaReference>,
567        /// Rejected immutable reference.
568        rejected: Box<SchemaReference>,
569    },
570    /// A schema document was not an object and could not carry identity.
571    #[error("schema document root must be an object")]
572    SchemaRootNotObject,
573    /// The exact mandatory dialect declaration was absent.
574    #[error("schema must declare JSON Schema 2020-12")]
575    UnsupportedDialect,
576    /// `$id` did not equal the normalized pinned URI.
577    #[error("schema $id does not match its immutable reference")]
578    IdMismatch {
579        /// Expected immutable reference.
580        reference: Box<SchemaReference>,
581    },
582    /// The schema did not satisfy the official meta-schema.
583    #[error("schema violates JSON Schema 2020-12: {diagnostic}")]
584    InvalidSchema {
585        /// Startup-safe schema diagnostic; no runtime instance is involved.
586        diagnostic: Box<str>,
587    },
588    /// RFC 8785 serialization unexpectedly failed.
589    #[error("schema canonicalization failed")]
590    Canonicalization,
591    /// A generated Rust schema could not be represented as JSON.
592    #[error("generated Rust schema serialization failed")]
593    GeneratedSchemaSerialization,
594    /// Canonical bytes exceeded the configured single-resource limit.
595    #[error("canonical schema is {actual} bytes; maximum is {maximum}")]
596    SchemaTooLarge {
597        /// Configured maximum.
598        maximum: usize,
599        /// Observed canonical bytes.
600        actual: usize,
601    },
602    /// Canonical schema bytes did not match the pinned digest.
603    #[error("canonical schema digest does not match its immutable reference")]
604    DigestMismatch {
605        /// Rejected immutable reference.
606        reference: Box<SchemaReference>,
607    },
608    /// Aggregate canonical bytes exceeded the configured limit.
609    #[error("schema registry contains {actual} canonical bytes; maximum is {maximum}")]
610    AggregateTooLarge {
611        /// Configured maximum.
612        maximum: usize,
613        /// Observed or saturated aggregate.
614        actual: usize,
615    },
616    /// The local resource graph could not be prepared.
617    #[error("schema registry resource preparation failed: {diagnostic}")]
618    RegistryPreparation {
619        /// Startup-safe schema diagnostic.
620        diagnostic: Box<str>,
621    },
622    /// One exact schema could not compile with offline reference resolution.
623    #[error("schema validator compilation failed: {diagnostic}")]
624    ValidatorCompilation {
625        /// Exact resource that failed compilation.
626        reference: Box<SchemaReference>,
627        /// Startup-safe schema diagnostic.
628        diagnostic: Box<str>,
629    },
630}
631
632#[cfg(test)]
633mod tests {
634    use schemars::{JsonSchema, SchemaGenerator};
635    use serde::{Deserialize, Serialize};
636    use serde_json::json;
637    use stateknot_core::{SchemaId, Version};
638
639    use super::*;
640
641    fn reference(id: &str, document: &Value) -> SchemaReference {
642        let canonical = serde_json_canonicalizer::to_vec(document).unwrap();
643        SchemaReference::new(
644            id.parse::<SchemaId>().unwrap(),
645            "1.0.0".parse::<Version>().unwrap(),
646            Digest::sha256(canonical),
647        )
648    }
649
650    #[test]
651    fn registry_is_offline_digest_pinned_and_resolves_local_resources() {
652        let address_id = "https://schemas.example.com/address/1.0.0";
653        let address = json!({
654            "$schema": DRAFT_2020_12,
655            "$id": address_id,
656            "type": "object",
657            "properties": {"postcode": {"type": "string", "pattern": "^[0-9]{5}$"}},
658            "required": ["postcode"],
659            "additionalProperties": false
660        });
661        let user_id = "https://schemas.example.com/user/1.0.0";
662        let user = json!({
663            "$schema": DRAFT_2020_12,
664            "$id": user_id,
665            "type": "object",
666            "properties": {
667                "email": {"type": "string", "format": "email"},
668                "address": {"$ref": address_id}
669            },
670            "required": ["email", "address"],
671            "additionalProperties": false
672        });
673        let address_reference = reference(address_id, &address);
674        let user_reference = reference(user_id, &user);
675        let mut builder = JsonSchemaRegistryBuilder::default();
676        builder
677            .register(address_reference.clone(), address)
678            .unwrap();
679        builder.register(user_reference.clone(), user).unwrap();
680        let registry = builder.build().unwrap();
681
682        let valid = BoundedJson::try_from_value(json!({
683            "email": "agent@example.com",
684            "address": {"postcode": "31000"}
685        }))
686        .unwrap();
687        let bad_format = BoundedJson::try_from_value(json!({
688            "email": "not-an-email",
689            "address": {"postcode": "31000"}
690        }))
691        .unwrap();
692        let bad_reference_value = BoundedJson::try_from_value(json!({
693            "email": "agent@example.com",
694            "address": {"postcode": "broken"}
695        }))
696        .unwrap();
697
698        assert_eq!(registry.len(), 2);
699        assert!(registry.total_bytes() > 0);
700        assert!(registry.canonical_bytes(&address_reference).is_some());
701        assert_eq!(registry.validate_bounded(&user_reference, &valid), Ok(()));
702        assert_eq!(
703            registry.validate_bounded(&user_reference, &bad_format),
704            Err(GraphSchemaValidationError::Rejected)
705        );
706        assert_eq!(
707            registry.validate_bounded(&user_reference, &bad_reference_value),
708            Err(GraphSchemaValidationError::Rejected)
709        );
710    }
711
712    #[test]
713    fn registration_rejects_digest_dialect_id_and_uri_aliases() {
714        let id = "https://schemas.example.com/state/1.0.0";
715        let document = json!({
716            "$schema": DRAFT_2020_12,
717            "$id": id,
718            "type": "object"
719        });
720        let exact = reference(id, &document);
721
722        let mut mismatch = JsonSchemaRegistryBuilder::default();
723        let wrong = SchemaReference::new(
724            exact.id().clone(),
725            exact.version(),
726            Digest::sha256(b"wrong"),
727        );
728        assert!(matches!(
729            mismatch.register(wrong, document.clone()),
730            Err(JsonSchemaRegistryError::DigestMismatch { .. })
731        ));
732
733        let mut dialect = document.clone();
734        dialect["$schema"] = json!("https://json-schema.org/draft/2019-09/schema");
735        assert_eq!(
736            JsonSchemaRegistryBuilder::default().register(reference(id, &dialect), dialect),
737            Err(JsonSchemaRegistryError::UnsupportedDialect)
738        );
739
740        let mut wrong_id = document.clone();
741        wrong_id["$id"] = json!("https://schemas.example.com/other/1.0.0");
742        assert!(matches!(
743            JsonSchemaRegistryBuilder::default().register(reference(id, &wrong_id), wrong_id),
744            Err(JsonSchemaRegistryError::IdMismatch { .. })
745        ));
746
747        let mut duplicate = JsonSchemaRegistryBuilder::default();
748        duplicate.register(exact.clone(), document.clone()).unwrap();
749        let alias =
750            SchemaReference::new(exact.id().clone(), "2.0.0".parse().unwrap(), exact.digest());
751        assert!(matches!(
752            duplicate.register(alias, document),
753            Err(JsonSchemaRegistryError::DuplicateId { .. })
754        ));
755    }
756
757    #[test]
758    fn build_rejects_unresolved_network_reference() {
759        let id = "https://schemas.example.com/offline/1.0.0";
760        let document = json!({
761            "$schema": DRAFT_2020_12,
762            "$id": id,
763            "$ref": "https://schemas.example.com/not-installed/1.0.0"
764        });
765        let mut builder = JsonSchemaRegistryBuilder::default();
766        builder
767            .register(reference(id, &document), document)
768            .unwrap();
769        assert!(matches!(
770            builder.build(),
771            Err(JsonSchemaRegistryError::ValidatorCompilation { .. }
772                | JsonSchemaRegistryError::RegistryPreparation { .. })
773        ));
774    }
775
776    #[test]
777    fn absent_full_reference_is_unavailable() {
778        let id = "https://schemas.example.com/value/1.0.0";
779        let document = json!({
780            "$schema": DRAFT_2020_12,
781            "$id": id,
782            "type": "integer"
783        });
784        let installed = reference(id, &document);
785        let mut builder = JsonSchemaRegistryBuilder::default();
786        builder.register(installed.clone(), document).unwrap();
787        let registry = builder.build().unwrap();
788        let missing = SchemaReference::new(
789            installed.id().clone(),
790            installed.version(),
791            Digest::sha256(b"different"),
792        );
793        let value = BoundedJson::try_from_value(json!(1)).unwrap();
794        assert_eq!(
795            registry.validate_bounded(&missing, &value),
796            Err(GraphSchemaValidationError::Unavailable)
797        );
798    }
799
800    #[test]
801    fn limits_fail_closed() {
802        assert_eq!(
803            JsonSchemaRegistryLimits::new(0, 1, 1),
804            Err(JsonSchemaRegistryLimitsError::ZeroSchemas)
805        );
806        assert_eq!(
807            JsonSchemaRegistryLimits::new(1, 2, 1),
808            Err(JsonSchemaRegistryLimitsError::TotalBelowSingleSchema)
809        );
810
811        let limits = JsonSchemaRegistryLimits::new(1, 1024, 1024).unwrap();
812        let first_id = "https://schemas.example.com/one/1.0.0";
813        let first = json!({"$schema": DRAFT_2020_12, "$id": first_id});
814        let second_id = "https://schemas.example.com/two/1.0.0";
815        let second = json!({"$schema": DRAFT_2020_12, "$id": second_id});
816        let mut builder = JsonSchemaRegistryBuilder::new(limits);
817        builder
818            .register(reference(first_id, &first), first)
819            .unwrap();
820        assert_eq!(
821            builder.register(reference(second_id, &second), second),
822            Err(JsonSchemaRegistryError::TooManySchemas {
823                maximum: 1,
824                actual: 2
825            })
826        );
827    }
828
829    #[derive(Deserialize, JsonSchema)]
830    #[serde(deny_unknown_fields)]
831    #[allow(dead_code)]
832    struct LookupInput {
833        incident_id: String,
834    }
835
836    #[derive(JsonSchema, Serialize)]
837    #[serde(deny_unknown_fields)]
838    struct LookupOutput {
839        found: bool,
840    }
841
842    #[test]
843    fn rust_type_registration_drives_exact_tool_validation() {
844        let mut builder = JsonSchemaRegistryBuilder::default();
845        let input = builder
846            .register_rust_type::<LookupInput>(
847                "https://schemas.example.com/tools/lookup/input/1.0.0"
848                    .parse()
849                    .unwrap(),
850                Version::new(1, 0, 0),
851            )
852            .unwrap();
853        let output = builder
854            .register_rust_type::<LookupOutput>(
855                "https://schemas.example.com/tools/lookup/output/1.0.0"
856                    .parse()
857                    .unwrap(),
858                Version::new(1, 0, 0),
859            )
860            .unwrap();
861        let registry = builder.build().unwrap();
862
863        registry
864            .validate_type_schema(
865                &input,
866                ToolSchemaRole::Input,
867                &SchemaGenerator::default().into_root_schema_for::<LookupInput>(),
868            )
869            .unwrap();
870        registry
871            .validate_type_schema(
872                &output,
873                ToolSchemaRole::Output,
874                &SchemaGenerator::default().into_root_schema_for::<LookupOutput>(),
875            )
876            .unwrap();
877
878        let valid = BoundedJson::try_from_value(json!({"incident_id": "INC-42"})).unwrap();
879        let invalid = BoundedJson::try_from_value(json!({"unexpected": true})).unwrap();
880        assert!(
881            registry
882                .validate_instance(&input, ToolSchemaRole::Input, &valid)
883                .is_ok()
884        );
885        assert!(
886            registry
887                .validate_instance(&input, ToolSchemaRole::Input, &invalid)
888                .is_err()
889        );
890        assert!(
891            registry
892                .validate_type_schema(
893                    &input,
894                    ToolSchemaRole::Input,
895                    &SchemaGenerator::default().into_root_schema_for::<LookupOutput>(),
896                )
897                .is_err()
898        );
899    }
900}