Skip to main content

stateknot_core/
schema.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Stable identities for local, digest-pinned JSON schemas.
5
6use std::{fmt, str::FromStr};
7
8use fluent_uri::Uri;
9use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
10use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
11use thiserror::Error;
12
13use crate::{Digest, Version};
14
15const SCHEMA_ID_PATTERN: &str = "^https://[^?#]+$";
16
17/// A normalized, absolute HTTPS identifier for a schema resource.
18///
19/// A schema ID is an identity, never an instruction to fetch over the network.
20/// `StateKnot` resolves it only from an explicitly populated local registry and
21/// verifies schema bytes against a pinned [`Digest`].
22#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
23pub struct SchemaId(Box<str>);
24
25impl SchemaId {
26    /// Maximum encoded length in bytes.
27    pub const MAX_LEN: usize = 512;
28
29    /// Returns the canonical URI text.
30    #[must_use]
31    pub fn as_str(&self) -> &str {
32        &self.0
33    }
34}
35
36impl fmt::Debug for SchemaId {
37    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
38        formatter
39            .debug_tuple("SchemaId")
40            .field(&self.as_str())
41            .finish()
42    }
43}
44
45impl fmt::Display for SchemaId {
46    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
47        formatter.write_str(self.as_str())
48    }
49}
50
51impl AsRef<str> for SchemaId {
52    fn as_ref(&self) -> &str {
53        self.as_str()
54    }
55}
56
57impl FromStr for SchemaId {
58    type Err = SchemaIdError;
59
60    fn from_str(value: &str) -> Result<Self, Self::Err> {
61        if value.is_empty() {
62            return Err(SchemaIdError::Empty);
63        }
64        if value.len() > Self::MAX_LEN {
65            return Err(SchemaIdError::TooLong {
66                max: Self::MAX_LEN,
67                actual: value.len(),
68            });
69        }
70
71        let uri = Uri::parse(value).map_err(|_| SchemaIdError::InvalidUri)?;
72        let scheme = uri.scheme().as_str();
73        if !scheme.eq_ignore_ascii_case("https") {
74            return Err(SchemaIdError::UnsupportedScheme);
75        }
76
77        let authority = uri.authority().ok_or(SchemaIdError::MissingAuthority)?;
78        if authority.host().is_empty() {
79            return Err(SchemaIdError::MissingAuthority);
80        }
81        if authority.userinfo().is_some() {
82            return Err(SchemaIdError::UserInfoNotAllowed);
83        }
84        if uri.query().is_some() {
85            return Err(SchemaIdError::QueryNotAllowed);
86        }
87        if uri.fragment().is_some() {
88            return Err(SchemaIdError::FragmentNotAllowed);
89        }
90
91        if uri.normalize().as_str() != value {
92            return Err(SchemaIdError::NonCanonical);
93        }
94
95        Ok(Self(value.into()))
96    }
97}
98
99impl Serialize for SchemaId {
100    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
101    where
102        S: Serializer,
103    {
104        serializer.serialize_str(self.as_str())
105    }
106}
107
108impl<'de> Deserialize<'de> for SchemaId {
109    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
110    where
111        D: Deserializer<'de>,
112    {
113        deserializer.deserialize_str(SchemaIdVisitor)
114    }
115}
116
117struct SchemaIdVisitor;
118
119impl de::Visitor<'_> for SchemaIdVisitor {
120    type Value = SchemaId;
121
122    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
123        formatter.write_str("a normalized absolute HTTPS schema identifier")
124    }
125
126    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
127    where
128        E: de::Error,
129    {
130        value.parse().map_err(E::custom)
131    }
132}
133
134impl JsonSchema for SchemaId {
135    fn schema_name() -> std::borrow::Cow<'static, str> {
136        "SchemaId".into()
137    }
138
139    fn schema_id() -> std::borrow::Cow<'static, str> {
140        concat!(module_path!(), "::SchemaId").into()
141    }
142
143    fn json_schema(_: &mut SchemaGenerator) -> Schema {
144        json_schema!({
145            "type": "string",
146            "format": "uri",
147            "minLength": 9,
148            "maxLength": 512,
149            "pattern": SCHEMA_ID_PATTERN
150        })
151    }
152
153    fn inline_schema() -> bool {
154        true
155    }
156}
157
158/// Validation failure for a [`SchemaId`].
159#[derive(Clone, Debug, Eq, Error, PartialEq)]
160#[non_exhaustive]
161pub enum SchemaIdError {
162    /// The identifier was empty.
163    #[error("schema identifier must not be empty")]
164    Empty,
165
166    /// The identifier exceeded [`SchemaId::MAX_LEN`].
167    #[error("schema identifier is {actual} bytes; maximum is {max}")]
168    TooLong {
169        /// Maximum accepted byte length.
170        max: usize,
171        /// Observed byte length.
172        actual: usize,
173    },
174
175    /// The text was not an absolute RFC 3986 URI.
176    #[error("schema identifier must be an absolute RFC 3986 URI")]
177    InvalidUri,
178
179    /// The URI did not use the supported HTTPS scheme.
180    #[error("schema identifier must use HTTPS")]
181    UnsupportedScheme,
182
183    /// The HTTPS URI did not contain a non-empty authority host.
184    #[error("schema identifier must contain an HTTPS authority host")]
185    MissingAuthority,
186
187    /// URI user information was present.
188    #[error("schema identifier must not contain user information")]
189    UserInfoNotAllowed,
190
191    /// A query component was present, including an empty query.
192    #[error("schema identifier must not contain a query")]
193    QueryNotAllowed,
194
195    /// A fragment component was present, including an empty fragment.
196    #[error("schema identifier must not contain a fragment")]
197    FragmentNotAllowed,
198
199    /// The input did not already use its normalized RFC 3986 spelling.
200    #[error("schema identifier must use normalized RFC 3986 text")]
201    NonCanonical,
202}
203
204/// An immutable reference to canonical JSON schema bytes.
205///
206/// The explicit version supports compatibility policy, while the digest
207/// prevents a reused URI or version from silently changing validation
208/// behavior.
209#[derive(Clone, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
210#[serde(deny_unknown_fields)]
211pub struct SchemaReference {
212    id: SchemaId,
213    version: Version,
214    digest: Digest,
215}
216
217impl SchemaReference {
218    /// Constructs an immutable schema reference from validated components.
219    #[must_use]
220    pub const fn new(id: SchemaId, version: Version, digest: Digest) -> Self {
221        Self {
222            id,
223            version,
224            digest,
225        }
226    }
227
228    /// Returns the stable schema identifier.
229    #[must_use]
230    pub const fn id(&self) -> &SchemaId {
231        &self.id
232    }
233
234    /// Returns the explicitly pinned schema version.
235    #[must_use]
236    pub const fn version(&self) -> Version {
237        self.version
238    }
239
240    /// Returns the digest of the canonical schema bytes.
241    #[must_use]
242    pub const fn digest(&self) -> Digest {
243        self.digest
244    }
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250    use serde_json::{Value, from_value, json, to_value};
251
252    const RUN_EVENT_ID: &str = "https://stateknot.github.io/schema/run-event/1.0.0";
253
254    #[test]
255    fn schema_ids_accept_only_normalized_https_uris() {
256        for value in [
257            RUN_EVENT_ID,
258            "https://schemas.example.com/tool/input/2.3.4",
259            "https://schemas.example.com:8443/a%20b/1.0.0",
260        ] {
261            let id = value.parse::<SchemaId>().unwrap();
262            assert_eq!(id.as_str(), value);
263            assert_eq!(id.to_string(), value);
264            assert_eq!(to_value(&id).unwrap(), Value::from(value));
265        }
266    }
267
268    #[test]
269    fn schema_ids_reject_ambiguous_or_active_uris() {
270        for value in [
271            "schema/run-event/1.0.0",
272            "http://example.com/schema/1.0.0",
273            "HTTPS://example.com/schema/1.0.0",
274            "https://EXAMPLE.com/schema/1.0.0",
275            "https:/schema/1.0.0",
276            "https://user@example.com/schema/1.0.0",
277            "https://example.com/schema/1.0.0?",
278            "https://example.com/schema/1.0.0?profile=full",
279            "https://example.com/schema/1.0.0#",
280            "https://example.com/schema/1.0.0#part",
281            "https://example.com/a/../schema/1.0.0",
282            "https://example.com:443/schema/1.0.0",
283            "https://例子.example/schema/1.0.0",
284        ] {
285            assert!(value.parse::<SchemaId>().is_err(), "accepted {value:?}");
286        }
287
288        let oversized = format!("https://example.com/{}", "a".repeat(SchemaId::MAX_LEN));
289        assert_eq!(
290            oversized.parse::<SchemaId>(),
291            Err(SchemaIdError::TooLong {
292                max: SchemaId::MAX_LEN,
293                actual: oversized.len(),
294            })
295        );
296    }
297
298    #[test]
299    fn schema_id_serde_and_schema_enforce_the_wire_contract() {
300        let id = RUN_EVENT_ID.parse::<SchemaId>().unwrap();
301        assert_eq!(from_value::<SchemaId>(json!(RUN_EVENT_ID)).unwrap(), id);
302        assert!(from_value::<SchemaId>(json!(42)).is_err());
303        assert!(from_value::<SchemaId>(Value::Null).is_err());
304
305        let schema = to_value(schemars::schema_for!(SchemaId)).unwrap();
306        assert_eq!(schema["type"], "string");
307        assert_eq!(schema["format"], "uri");
308        assert_eq!(schema["minLength"], 9);
309        assert_eq!(schema["maxLength"], SchemaId::MAX_LEN);
310        assert_eq!(schema["pattern"], SCHEMA_ID_PATTERN);
311    }
312
313    #[test]
314    fn schema_references_bind_id_version_and_digest() {
315        let id = RUN_EVENT_ID.parse::<SchemaId>().unwrap();
316        let version = Version::new(1, 0, 0);
317        let digest = Digest::sha256(b"canonical schema");
318        let reference = SchemaReference::new(id.clone(), version, digest);
319
320        assert_eq!(reference.id(), &id);
321        assert_eq!(reference.version(), version);
322        assert_eq!(reference.digest(), digest);
323
324        let encoded = to_value(&reference).unwrap();
325        assert_eq!(
326            encoded,
327            json!({
328                "id": RUN_EVENT_ID,
329                "version": "1.0.0",
330                "digest": digest.to_string(),
331            })
332        );
333        assert_eq!(from_value::<SchemaReference>(encoded).unwrap(), reference);
334    }
335
336    #[test]
337    fn schema_references_reject_missing_extra_or_invalid_fields() {
338        let digest = Digest::sha256(b"canonical schema").to_string();
339        for invalid in [
340            json!({"id": RUN_EVENT_ID, "version": "1.0.0"}),
341            json!({"id": RUN_EVENT_ID, "version": "1.0.0", "digest": digest, "extra": true}),
342            json!({"id": "http://example.com/schema", "version": "1.0.0", "digest": digest}),
343            json!({"id": RUN_EVENT_ID, "version": "v1", "digest": digest}),
344            json!({"id": RUN_EVENT_ID, "version": "1.0.0", "digest": "sha256:00"}),
345        ] {
346            assert!(
347                from_value::<SchemaReference>(invalid.clone()).is_err(),
348                "accepted {invalid}"
349            );
350        }
351    }
352
353    #[test]
354    fn schema_reference_schema_is_closed() {
355        let schema = to_value(schemars::schema_for!(SchemaReference)).unwrap();
356        assert_eq!(schema["type"], "object");
357        assert_eq!(schema["additionalProperties"], false);
358        assert_eq!(schema["required"], json!(["id", "version", "digest"]));
359        assert_eq!(schema["properties"]["id"]["format"], "uri");
360    }
361}