Skip to main content

subc_protocol/
provider_declarations.rs

1//! Bounded, provider-owned declarations fixed for a module's spawn.
2
3use std::{collections::BTreeMap, fmt};
4
5use serde::{
6    de::{IgnoredAny, MapAccess, Visitor},
7    Deserialize, Deserializer,
8};
9use serde_json::{Map, Value};
10
11use crate::{error_codes, module_id::module_id_path_hazard};
12
13/// Providers own the schemas inside these objects; readers retain unknown keys.
14pub type ProviderDeclarations = BTreeMap<String, Map<String, Value>>;
15
16/// Bound the number of providers a single manifest can address.
17pub const MAX_PROVIDER_DECLARATIONS: usize = 16;
18/// Bound each relayed provider entry's compact JSON representation.
19pub const MAX_PROVIDER_DECLARATION_BYTES: usize = 16 * 1024;
20/// Bound the complete field, including keys and JSON punctuation.
21pub const MAX_PROVIDER_DECLARATIONS_BYTES: usize = 24 * 1024;
22
23/// A safe-to-report HELLO refusal, without echoing provider-owned content.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub struct ProviderDeclarationsError(&'static str);
26
27impl ProviderDeclarationsError {
28    pub fn code(&self) -> &'static str {
29        error_codes::INVALID_PROVIDER_DECLARATIONS
30    }
31
32    pub fn field(&self) -> &'static str {
33        "provider_declarations"
34    }
35}
36
37impl fmt::Display for ProviderDeclarationsError {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        write!(f, "invalid provider_declarations: {}", self.0)
40    }
41}
42
43impl std::error::Error for ProviderDeclarationsError {}
44
45/// Run before lenient manifest decoding so malformed declarations refuse HELLO
46/// with `invalid_provider_declarations`, rather than being silently dropped.
47pub fn validate_hello_provider_declarations(
48    hello: &Value,
49) -> Result<(), ProviderDeclarationsError> {
50    match hello
51        .get("manifest")
52        .and_then(|manifest| manifest.get("provider_declarations"))
53    {
54        Some(value) => validate_provider_declarations(value),
55        None => Ok(()),
56    }
57}
58
59fn validate_provider_declarations(value: &Value) -> Result<(), ProviderDeclarationsError> {
60    let map = value
61        .as_object()
62        .ok_or(ProviderDeclarationsError("must be an object"))?;
63    if map.len() > MAX_PROVIDER_DECLARATIONS {
64        return Err(ProviderDeclarationsError("more than 16 entries"));
65    }
66    for (provider, entry) in map {
67        if module_id_path_hazard(provider).is_err() {
68            return Err(ProviderDeclarationsError("key must use module-id grammar"));
69        }
70        if !entry.is_object() {
71            return Err(ProviderDeclarationsError("values must be objects"));
72        }
73        if compact_size(entry)? > MAX_PROVIDER_DECLARATION_BYTES {
74            return Err(ProviderDeclarationsError(
75                "entry exceeds 16384 compact JSON bytes",
76            ));
77        }
78    }
79    if compact_size(value)? > MAX_PROVIDER_DECLARATIONS_BYTES {
80        return Err(ProviderDeclarationsError(
81            "field exceeds 24576 compact JSON bytes",
82        ));
83    }
84    Ok(())
85}
86
87fn compact_size(value: &Value) -> Result<usize, ProviderDeclarationsError> {
88    serde_json::to_vec(value)
89        .map(|bytes| bytes.len())
90        .map_err(|_| ProviderDeclarationsError("could not serialize compact JSON"))
91}
92
93pub(crate) fn deserialize_provider_declarations<'de, D: Deserializer<'de>>(
94    deserializer: D,
95) -> Result<Option<ProviderDeclarations>, D::Error> {
96    let value = Value::deserialize(deserializer)?;
97    validate_provider_declarations(&value).map_err(serde::de::Error::custom)?;
98    serde_json::from_value(value)
99        .map(Some)
100        .map_err(serde::de::Error::custom)
101}
102
103/// Detects the frozen key directly in a raw `catalog.update` JSON body, without
104/// decoding the update's schema or retaining its values. Even a null or invalid
105/// declaration must be refused with `catalog_update_frozen_declarations`.
106/// Malformed JSON remains a JSON error, not a declaration update.
107pub fn catalog_update_has_provider_declarations(body: &[u8]) -> serde_json::Result<bool> {
108    struct FrozenKey;
109    impl<'de> Visitor<'de> for FrozenKey {
110        type Value = bool;
111
112        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113            f.write_str("a catalog.update object")
114        }
115
116        fn visit_map<M: MapAccess<'de>>(self, mut map: M) -> Result<bool, M::Error> {
117            let mut found = false;
118            while let Some(key) = map.next_key::<String>()? {
119                found |= key == "provider_declarations";
120                map.next_value::<IgnoredAny>()?;
121            }
122            Ok(found)
123        }
124    }
125
126    let mut decoder = serde_json::Deserializer::from_slice(body);
127    let found = decoder.deserialize_map(FrozenKey)?;
128    decoder.end()?;
129    Ok(found)
130}