Skip to main content

hyprstream_core/services/oauth/xrpc/
record_validation.rs

1//! Validation of the two enabled posting schemas and their pinned reference
2//! closure. No schema discovery, permissions, network fetches or data rewriting.
3use std::collections::BTreeMap;
4use std::sync::LazyLock;
5
6use chrono::Datelike as _;
7use serde_json::Value;
8use unicode_segmentation::UnicodeSegmentation as _;
9
10#[derive(Debug)]
11pub(super) enum Error {
12    Invalid,
13    SchemaUnavailable,
14}
15
16type Result<T> = std::result::Result<T, Error>;
17
18macro_rules! schema {
19    ($path:literal) => {
20        include_str!(concat!(
21            env!("CARGO_MANIFEST_DIR"),
22            "/../../lexicons/upstream/atproto/",
23            $path,
24            ".json"
25        ))
26    };
27}
28
29static SCHEMAS: LazyLock<Result<BTreeMap<String, Value>>> = LazyLock::new(|| {
30    [
31        schema!("app/bsky/feed/post"),
32        schema!("app/bsky/actor/profile"),
33        schema!("app/bsky/embed/defs"),
34        schema!("app/bsky/embed/external"),
35        schema!("app/bsky/embed/gallery"),
36        schema!("app/bsky/embed/images"),
37        schema!("app/bsky/embed/record"),
38        schema!("app/bsky/embed/recordWithMedia"),
39        schema!("app/bsky/embed/video"),
40        schema!("app/bsky/richtext/facet"),
41        schema!("com/atproto/label/defs"),
42        schema!("com/atproto/repo/strongRef"),
43    ]
44    .into_iter()
45    .map(|text| {
46        let value: Value = serde_json::from_str(text).map_err(|_| Error::SchemaUnavailable)?;
47        let id = value
48            .get("id")
49            .and_then(Value::as_str)
50            .ok_or(Error::SchemaUnavailable)?
51            .to_owned();
52        Ok((id, value))
53    })
54    .collect()
55});
56
57pub(super) fn validate(collection: &str, value: &Value) -> Result<()> {
58    let schemas = SCHEMAS.as_ref().map_err(|_| Error::SchemaUnavailable)?;
59    validate_ref(schemas, collection, value, 0)
60}
61
62fn validate_ref(
63    schemas: &BTreeMap<String, Value>,
64    reference: &str,
65    value: &Value,
66    depth: usize,
67) -> Result<()> {
68    let (nsid, name) = reference.split_once('#').unwrap_or((reference, "main"));
69    let schema = schemas
70        .get(nsid)
71        .and_then(|s| s.get("defs"))
72        .and_then(|s| s.get(name))
73        .ok_or(Error::SchemaUnavailable)?;
74    if schema.get("type").and_then(Value::as_str) == Some("record") {
75        check(value.get("$type").and_then(Value::as_str) == Some(nsid))?;
76        validate_value(
77            schemas,
78            nsid,
79            schema.get("record").ok_or(Error::SchemaUnavailable)?,
80            value,
81            depth,
82        )
83    } else {
84        validate_value(schemas, nsid, schema, value, depth)
85    }
86}
87
88fn check(valid: bool) -> Result<()> {
89    if valid {
90        Ok(())
91    } else {
92        Err(Error::Invalid)
93    }
94}
95
96fn bounds(schema: &Value, minimum: &str, maximum: &str, size: usize) -> Result<()> {
97    check(
98        schema
99            .get(minimum)
100            .and_then(Value::as_u64)
101            .is_none_or(|n| size as u64 >= n)
102            && schema
103                .get(maximum)
104                .and_then(Value::as_u64)
105                .is_none_or(|n| size as u64 <= n),
106    )
107}
108
109fn resolve(nsid: &str, reference: &str) -> String {
110    if reference.starts_with('#') {
111        format!("{nsid}{reference}")
112    } else {
113        reference.to_owned()
114    }
115}
116
117fn validate_value(
118    schemas: &BTreeMap<String, Value>,
119    nsid: &str,
120    schema: &Value,
121    value: &Value,
122    depth: usize,
123) -> Result<()> {
124    check(depth <= 128)?;
125    check(schema.get("const").is_none_or(|expected| expected == value))?;
126    check(
127        schema
128            .get("enum")
129            .and_then(Value::as_array)
130            .is_none_or(|allowed| allowed.contains(value)),
131    )?;
132    match schema
133        .get("type")
134        .and_then(Value::as_str)
135        .ok_or(Error::SchemaUnavailable)?
136    {
137        "object" => {
138            let object = value.as_object().ok_or(Error::Invalid)?;
139            if let Some(required) = schema.get("required").and_then(Value::as_array) {
140                for key in required {
141                    check(object.contains_key(key.as_str().ok_or(Error::SchemaUnavailable)?))?;
142                }
143            }
144            for (key, field) in schema
145                .get("properties")
146                .and_then(Value::as_object)
147                .ok_or(Error::SchemaUnavailable)?
148            {
149                if let Some(value) = object.get(key) {
150                    let nullable = schema
151                        .get("nullable")
152                        .and_then(Value::as_array)
153                        .is_some_and(|fields| fields.contains(&Value::String(key.clone())));
154                    if !(nullable && value.is_null()) {
155                        validate_value(schemas, nsid, field, value, depth + 1)?;
156                    }
157                }
158            }
159            // Lexicon objects are extensible. Unrecognized properties still
160            // pass through the existing complete AT data-model/codec checks.
161            Ok(())
162        }
163        "array" => {
164            let items = value.as_array().ok_or(Error::Invalid)?;
165            bounds(schema, "minLength", "maxLength", items.len())?;
166            let item_schema = schema.get("items").ok_or(Error::SchemaUnavailable)?;
167            for item in items {
168                validate_value(schemas, nsid, item_schema, item, depth + 1)?;
169            }
170            Ok(())
171        }
172        "string" => {
173            let text = value.as_str().ok_or(Error::Invalid)?;
174            bounds(schema, "minLength", "maxLength", text.len())?;
175            bounds(
176                schema,
177                "minGraphemes",
178                "maxGraphemes",
179                text.graphemes(true).count(),
180            )?;
181            match schema.get("format").and_then(Value::as_str) {
182                Some(format) => check(valid_format(format, text)),
183                None => Ok(()),
184            }
185        }
186        "integer" => {
187            let n = value.as_i64().ok_or(Error::Invalid)?;
188            check(
189                schema
190                    .get("minimum")
191                    .and_then(Value::as_i64)
192                    .is_none_or(|min| n >= min)
193                    && schema
194                        .get("maximum")
195                        .and_then(Value::as_i64)
196                        .is_none_or(|max| n <= max),
197            )
198        }
199        "ref" => {
200            let reference = schema
201                .get("ref")
202                .and_then(Value::as_str)
203                .ok_or(Error::SchemaUnavailable)?;
204            validate_ref(schemas, &resolve(nsid, reference), value, depth + 1)
205        }
206        "union" => {
207            let discriminator = value
208                .get("$type")
209                .and_then(Value::as_str)
210                .ok_or(Error::Invalid)?;
211            let (id, fragment) = discriminator.split_once('#').unwrap_or((discriminator, ""));
212            check(
213                valid_nsid(id)
214                    && (fragment.is_empty()
215                        || (fragment != "main"
216                            && fragment
217                                .bytes()
218                                .all(|b| b.is_ascii_alphanumeric() || b == b'_'))),
219            )?;
220            let refs = schema
221                .get("refs")
222                .and_then(Value::as_array)
223                .ok_or(Error::SchemaUnavailable)?;
224            for reference in refs {
225                let reference = resolve(nsid, reference.as_str().ok_or(Error::SchemaUnavailable)?);
226                if reference == discriminator {
227                    return validate_ref(schemas, &reference, value, depth + 1);
228                }
229            }
230            // Open unions accept future variants, without claiming their schema
231            // is known. Closed unions cannot introduce new alternatives.
232            check(schema.get("closed").and_then(Value::as_bool) != Some(true))
233        }
234        "blob" => {
235            check(value.get("$type").and_then(Value::as_str) == Some("blob"))?;
236            let link = value.get("ref").ok_or(Error::Invalid)?;
237            let cid =
238                crate::services::public_repo::json_to_dag_cbor(link).map_err(|_| Error::Invalid)?;
239            check(
240                matches!(cid, hyprstream_pds::dag_cbor::DagCbor::Link(cid) if cid.as_bytes().get(1) == Some(&0x55)),
241            )?;
242            let size = value
243                .get("size")
244                .and_then(Value::as_u64)
245                .ok_or(Error::Invalid)?;
246            check(
247                size > 0
248                    && schema
249                        .get("maxSize")
250                        .and_then(Value::as_u64)
251                        .is_none_or(|max| size <= max),
252            )?;
253            let mime = value
254                .get("mimeType")
255                .and_then(Value::as_str)
256                .ok_or(Error::Invalid)?;
257            check(
258                !mime.is_empty()
259                    && schema
260                        .get("accept")
261                        .and_then(Value::as_array)
262                        .is_none_or(|types| {
263                            types.iter().any(|t| {
264                                t.as_str().is_some_and(|t| {
265                                    t == "*/*"
266                                        || t == mime
267                                        || t.strip_suffix("/*").is_some_and(|prefix| {
268                                            mime.strip_prefix(prefix).is_some_and(|rest| {
269                                                rest.starts_with('/') && rest.len() > 1
270                                            })
271                                        })
272                                })
273                            })
274                        }),
275            )
276        }
277        _ => Err(Error::SchemaUnavailable),
278    }
279}
280
281fn valid_nsid(value: &str) -> bool {
282    let Some((authority, name)) = value.rsplit_once('.') else {
283        return false;
284    };
285    value.len() <= 317
286        && valid_dns_labels(authority)
287        && authority
288            .as_bytes()
289            .first()
290            .is_some_and(u8::is_ascii_alphabetic)
291        && (1..=63).contains(&name.len())
292        && name.as_bytes().first().is_some_and(u8::is_ascii_alphabetic)
293        && name.bytes().all(|b| b.is_ascii_alphanumeric())
294}
295
296pub(super) fn valid_handle(value: &str) -> bool {
297    valid_dns_labels(value)
298        && value
299            .rsplit('.')
300            .next()
301            .is_some_and(|tld| tld.as_bytes().first().is_some_and(u8::is_ascii_alphabetic))
302}
303
304fn valid_dns_labels(value: &str) -> bool {
305    value.len() <= 253
306        && value.contains('.')
307        && value.split('.').all(|part| {
308            (1..=63).contains(&part.len())
309                && !part.starts_with('-')
310                && !part.ends_with('-')
311                && part.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
312        })
313}
314
315fn valid_did(value: &str) -> bool {
316    let Some((method, id)) = value.strip_prefix("did:").and_then(|s| s.split_once(':')) else {
317        return false;
318    };
319    value.len() <= 2048
320        && !method.is_empty()
321        && method.bytes().all(|b| b.is_ascii_lowercase())
322        && !id.is_empty()
323        && !id.ends_with([':', '%'])
324        && id
325            .bytes()
326            .all(|b| b.is_ascii_alphanumeric() || b"._:%-".contains(&b))
327}
328
329fn valid_at_uri(value: &str) -> bool {
330    let Some(rest) = value.strip_prefix("at://") else {
331        return false;
332    };
333    let mut parts = rest.split('/');
334    let authority = parts.next().unwrap_or_default();
335    value.len() <= 8192
336        && (valid_did(authority) || valid_handle(authority))
337        && parts.next().is_none_or(valid_nsid)
338        && parts
339            .next()
340            .is_none_or(|key| hyprstream_pds::atproto_cbor::AtprotoRecordKey::new(key).is_ok())
341        && parts.next().is_none()
342}
343
344fn valid_format(format: &str, text: &str) -> bool {
345    match format {
346        "cid" => {
347            crate::services::public_repo::json_to_dag_cbor(&serde_json::json!({"$link": text}))
348                .is_ok()
349        }
350        "did" => valid_did(text),
351        "at-uri" => valid_at_uri(text),
352        "uri" => {
353            text.len() <= 8192 && (valid_at_uri(text) || uriparse::URI::try_from(text).is_ok())
354        }
355        "language" => language_tags::LanguageTag::parse(text).is_ok(),
356        "datetime" => {
357            static DATETIME: LazyLock<std::result::Result<regex::Regex, regex::Error>> =
358                LazyLock::new(|| {
359                    regex::Regex::new(
360                        r"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]+)?(Z|[+-][0-9]{2}:[0-9]{2})$",
361                    )
362                });
363            !text.ends_with("-00:00")
364                && DATETIME
365                    .as_ref()
366                    .is_ok_and(|pattern| pattern.is_match(text))
367                && chrono::DateTime::parse_from_rfc3339(text)
368                    .is_ok_and(|dt| dt.with_timezone(&chrono::Utc).year() >= 0)
369        }
370        _ => false,
371    }
372}