Skip to main content

stateknot_core/
extension.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Bounded, namespaced extension data without implicit authority.
5
6use std::{
7    borrow::Borrow,
8    collections::{BTreeMap, btree_map},
9    fmt,
10    str::FromStr,
11};
12
13use fluent_uri::Uri;
14use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
15use serde::{
16    Deserialize, Deserializer, Serialize, Serializer, de, de::DeserializeSeed, ser::SerializeMap,
17};
18use thiserror::Error;
19
20use crate::{BoundedJson, BoundedJsonError, JsonLimit, JsonLimits, SchemaReference};
21
22const REVERSE_DNS_PATTERN: &str =
23    "^[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z](?:[a-z0-9-]{0,61}[a-z0-9])?){2,}$";
24const URI_PATTERN: &str = "^(https://|urn:)";
25
26/// Namespace form used by an [`ExtensionKey`].
27#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
28pub enum ExtensionKeyKind {
29    /// A normalized HTTPS or URN identifier.
30    Uri,
31    /// A lowercase reverse-DNS name with at least three labels.
32    ReverseDns,
33}
34
35/// A stable namespace identity for one extension value.
36///
37/// URI keys are restricted to normalized HTTPS identifiers without userinfo,
38/// query, or fragment components, or normalized `urn:` identifiers with a
39/// lowercase RFC 8141 namespace identifier. URI keys are identifiers only and
40/// are never dereferenced. Reverse-DNS keys use at least three lowercase DNS
41/// labels, reserving the leading labels for the controlling organization and
42/// the remaining labels for a versioned feature name.
43#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
44pub struct ExtensionKey {
45    value: Box<str>,
46    kind: ExtensionKeyKind,
47}
48
49impl ExtensionKey {
50    /// Maximum encoded key length in bytes.
51    pub const MAX_LEN: usize = 512;
52
53    /// Parses and validates a namespaced extension key.
54    ///
55    /// # Errors
56    ///
57    /// Returns [`ExtensionKeyError`] when the key is empty, oversized,
58    /// non-canonical, uses an unsupported URI form, or violates the strict
59    /// reverse-DNS grammar.
60    pub fn new(value: impl Into<String>) -> Result<Self, ExtensionKeyError> {
61        let value = value.into();
62        validate_extension_key(&value).map(|kind| Self {
63            value: value.into_boxed_str(),
64            kind,
65        })
66    }
67
68    /// Returns the exact canonical namespace text.
69    #[must_use]
70    pub fn as_str(&self) -> &str {
71        &self.value
72    }
73
74    /// Returns the validated namespace form.
75    #[must_use]
76    pub const fn kind(&self) -> ExtensionKeyKind {
77        self.kind
78    }
79}
80
81impl AsRef<str> for ExtensionKey {
82    fn as_ref(&self) -> &str {
83        self.as_str()
84    }
85}
86
87impl Borrow<str> for ExtensionKey {
88    fn borrow(&self) -> &str {
89        self.as_str()
90    }
91}
92
93impl fmt::Debug for ExtensionKey {
94    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
95        formatter
96            .debug_struct("ExtensionKey")
97            .field("value", &self.as_str())
98            .field("kind", &self.kind)
99            .finish()
100    }
101}
102
103impl fmt::Display for ExtensionKey {
104    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
105        formatter.write_str(self.as_str())
106    }
107}
108
109impl FromStr for ExtensionKey {
110    type Err = ExtensionKeyError;
111
112    fn from_str(value: &str) -> Result<Self, Self::Err> {
113        Self::new(value)
114    }
115}
116
117impl TryFrom<String> for ExtensionKey {
118    type Error = ExtensionKeyError;
119
120    fn try_from(value: String) -> Result<Self, Self::Error> {
121        Self::new(value)
122    }
123}
124
125impl TryFrom<&str> for ExtensionKey {
126    type Error = ExtensionKeyError;
127
128    fn try_from(value: &str) -> Result<Self, Self::Error> {
129        Self::new(value)
130    }
131}
132
133impl From<ExtensionKey> for String {
134    fn from(value: ExtensionKey) -> Self {
135        value.value.into()
136    }
137}
138
139impl Serialize for ExtensionKey {
140    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
141    where
142        S: Serializer,
143    {
144        serializer.serialize_str(self.as_str())
145    }
146}
147
148impl<'de> Deserialize<'de> for ExtensionKey {
149    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
150    where
151        D: Deserializer<'de>,
152    {
153        deserializer.deserialize_string(ExtensionKeyVisitor)
154    }
155}
156
157struct ExtensionKeyVisitor;
158
159impl de::Visitor<'_> for ExtensionKeyVisitor {
160    type Value = ExtensionKey;
161
162    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
163        formatter.write_str("a normalized HTTPS/URN or lowercase reverse-DNS extension key")
164    }
165
166    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
167    where
168        E: de::Error,
169    {
170        ExtensionKey::try_from(value).map_err(E::custom)
171    }
172
173    fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
174    where
175        E: de::Error,
176    {
177        ExtensionKey::try_from(value).map_err(E::custom)
178    }
179}
180
181impl JsonSchema for ExtensionKey {
182    fn schema_name() -> std::borrow::Cow<'static, str> {
183        "ExtensionKey".into()
184    }
185
186    fn schema_id() -> std::borrow::Cow<'static, str> {
187        concat!(module_path!(), "::ExtensionKey").into()
188    }
189
190    fn json_schema(_: &mut SchemaGenerator) -> Schema {
191        json_schema!({
192            "oneOf": [
193                {
194                    "type": "string",
195                    "format": "uri",
196                    "minLength": 8,
197                    "maxLength": 512,
198                    "pattern": URI_PATTERN
199                },
200                {
201                    "type": "string",
202                    "minLength": 5,
203                    "maxLength": 512,
204                    "pattern": REVERSE_DNS_PATTERN
205                }
206            ],
207            "description": "A normalized HTTPS/URN identifier or lowercase reverse-DNS extension name. Runtime validation enforces stricter URI and per-label invariants."
208        })
209    }
210
211    fn inline_schema() -> bool {
212        true
213    }
214}
215
216/// Invalid extension namespace identity.
217#[derive(Clone, Debug, Eq, Error, PartialEq)]
218#[non_exhaustive]
219pub enum ExtensionKeyError {
220    /// The key contained no bytes.
221    #[error("extension key must not be empty")]
222    Empty,
223
224    /// The key exceeded [`ExtensionKey::MAX_LEN`].
225    #[error("extension key is {actual} bytes; maximum is {max}")]
226    TooLong {
227        /// Maximum accepted byte length.
228        max: usize,
229        /// Observed byte length.
230        actual: usize,
231    },
232
233    /// Text containing a URI separator was not a valid URI.
234    #[error("extension URI key is invalid")]
235    InvalidUri,
236
237    /// The URI scheme was not one of the supported identifier-only schemes.
238    #[error("extension URI key must use HTTPS or URN")]
239    UnsupportedUriScheme,
240
241    /// An HTTPS key did not contain a non-empty authority host.
242    #[error("HTTPS extension key must contain an authority host")]
243    MissingAuthority,
244
245    /// URI user information was present.
246    #[error("extension URI key must not contain user information")]
247    UserInfoNotAllowed,
248
249    /// A query component was present, including an empty query.
250    #[error("extension URI key must not contain a query")]
251    QueryNotAllowed,
252
253    /// A fragment component was present, including an empty fragment.
254    #[error("extension URI key must not contain a fragment")]
255    FragmentNotAllowed,
256
257    /// A URN did not contain a lowercase valid namespace and non-empty value.
258    #[error("URN extension key must contain a lowercase namespace identifier and value")]
259    InvalidUrn,
260
261    /// The URI input did not already use its normalized spelling.
262    #[error("extension URI key must use normalized RFC 3986 text")]
263    NonCanonicalUri,
264
265    /// A reverse-DNS key contained fewer than three labels.
266    #[error("reverse-DNS extension key must contain at least three labels")]
267    TooFewReverseDnsLabels,
268
269    /// A reverse-DNS label was empty or exceeded 63 bytes.
270    #[error("reverse-DNS label at index {label_index} has invalid length {actual}")]
271    InvalidReverseDnsLabelLength {
272        /// Zero-based label index.
273        label_index: usize,
274        /// Observed label byte length.
275        actual: usize,
276    },
277
278    /// A label did not begin with lowercase ASCII.
279    #[error("reverse-DNS label at index {label_index} must start with lowercase ASCII")]
280    InvalidReverseDnsLabelStart {
281        /// Zero-based label index.
282        label_index: usize,
283    },
284
285    /// A label did not end in a lowercase letter or digit.
286    #[error("reverse-DNS label at index {label_index} must end with a letter or digit")]
287    InvalidReverseDnsLabelEnd {
288        /// Zero-based label index.
289        label_index: usize,
290    },
291
292    /// A reverse-DNS byte was outside the lowercase DNS-label grammar.
293    #[error("reverse-DNS extension key contains an invalid byte at offset {index}")]
294    InvalidReverseDnsByte {
295        /// Zero-based byte offset in the full key.
296        index: usize,
297    },
298}
299
300fn validate_extension_key(value: &str) -> Result<ExtensionKeyKind, ExtensionKeyError> {
301    if value.is_empty() {
302        return Err(ExtensionKeyError::Empty);
303    }
304    if value.len() > ExtensionKey::MAX_LEN {
305        return Err(ExtensionKeyError::TooLong {
306            max: ExtensionKey::MAX_LEN,
307            actual: value.len(),
308        });
309    }
310
311    if value.contains(':') {
312        validate_uri_extension_key(value)
313    } else {
314        validate_reverse_dns_extension_key(value)
315    }
316}
317
318fn validate_uri_extension_key(value: &str) -> Result<ExtensionKeyKind, ExtensionKeyError> {
319    let uri = Uri::parse(value).map_err(|_| ExtensionKeyError::InvalidUri)?;
320    if uri.query().is_some() {
321        return Err(ExtensionKeyError::QueryNotAllowed);
322    }
323    if uri.fragment().is_some() {
324        return Err(ExtensionKeyError::FragmentNotAllowed);
325    }
326
327    let scheme = uri.scheme().as_str();
328    if scheme.eq_ignore_ascii_case("https") {
329        let authority = uri.authority().ok_or(ExtensionKeyError::MissingAuthority)?;
330        if authority.host().is_empty() {
331            return Err(ExtensionKeyError::MissingAuthority);
332        }
333        if authority.userinfo().is_some() {
334            return Err(ExtensionKeyError::UserInfoNotAllowed);
335        }
336    } else if scheme.eq_ignore_ascii_case("urn") {
337        if uri.authority().is_some() || !valid_urn_namespace_and_value(value) {
338            return Err(ExtensionKeyError::InvalidUrn);
339        }
340    } else {
341        return Err(ExtensionKeyError::UnsupportedUriScheme);
342    }
343
344    if uri.normalize().as_str() != value {
345        return Err(ExtensionKeyError::NonCanonicalUri);
346    }
347    Ok(ExtensionKeyKind::Uri)
348}
349
350fn valid_urn_namespace_and_value(value: &str) -> bool {
351    let Some(body) = value.get(4..) else {
352        return false;
353    };
354    let Some((namespace, identifier)) = body.split_once(':') else {
355        return false;
356    };
357    if !(2..=32).contains(&namespace.len()) || identifier.is_empty() {
358        return false;
359    }
360
361    let bytes = namespace.as_bytes();
362    bytes[0].is_ascii_lowercase()
363        && bytes[bytes.len() - 1].is_ascii_alphanumeric()
364        && bytes
365            .iter()
366            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'-')
367}
368
369fn validate_reverse_dns_extension_key(value: &str) -> Result<ExtensionKeyKind, ExtensionKeyError> {
370    let label_count = value.bytes().filter(|byte| *byte == b'.').count() + 1;
371    if label_count < 3 {
372        return Err(ExtensionKeyError::TooFewReverseDnsLabels);
373    }
374
375    let mut offset = 0;
376    for (label_index, label) in value.split('.').enumerate() {
377        if label.is_empty() || label.len() > 63 {
378            return Err(ExtensionKeyError::InvalidReverseDnsLabelLength {
379                label_index,
380                actual: label.len(),
381            });
382        }
383        let bytes = label.as_bytes();
384        if !bytes[0].is_ascii_lowercase() {
385            return Err(ExtensionKeyError::InvalidReverseDnsLabelStart { label_index });
386        }
387        if !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
388            return Err(ExtensionKeyError::InvalidReverseDnsLabelEnd { label_index });
389        }
390        if let Some((inner_index, _)) = bytes.iter().enumerate().find(|(_, byte)| {
391            !byte.is_ascii_lowercase() && !byte.is_ascii_digit() && **byte != b'-'
392        }) {
393            return Err(ExtensionKeyError::InvalidReverseDnsByte {
394                index: offset + inner_index,
395            });
396        }
397        offset += label.len() + 1;
398    }
399    Ok(ExtensionKeyKind::ReverseDns)
400}
401
402/// Explicit trust mode for one extension value.
403///
404/// Opaque values may be retained or forwarded only according to an adapter's
405/// negotiated profile. They cannot influence authorization, policy,
406/// deterministic execution, hashing, or capability selection. Schema-bound
407/// values carry an immutable schema identity but still require validation
408/// against a trusted local registry before any semantic use.
409#[derive(Clone, Deserialize, Eq, JsonSchema, PartialEq, Serialize)]
410#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
411pub enum ExtensionValue {
412    /// Bounded data with no registered semantic contract.
413    Opaque {
414        /// The preserved bounded value.
415        value: BoundedJson,
416    },
417    /// Data whose intended semantics are pinned to an immutable schema.
418    SchemaBound {
419        /// Immutable identity of the value's schema.
420        schema: SchemaReference,
421        /// The bounded value to validate against the local schema registry.
422        value: BoundedJson,
423    },
424}
425
426impl ExtensionValue {
427    /// Wraps bounded data without granting it registered semantics.
428    #[must_use]
429    pub const fn opaque(value: BoundedJson) -> Self {
430        Self::Opaque { value }
431    }
432
433    /// Binds bounded data to an immutable schema identity.
434    #[must_use]
435    pub const fn schema_bound(schema: SchemaReference, value: BoundedJson) -> Self {
436        Self::SchemaBound { schema, value }
437    }
438
439    /// Returns the bounded JSON value in either trust mode.
440    #[must_use]
441    pub const fn value(&self) -> &BoundedJson {
442        match self {
443            Self::Opaque { value } | Self::SchemaBound { value, .. } => value,
444        }
445    }
446
447    /// Returns the immutable schema identity when semantic use was declared.
448    #[must_use]
449    pub const fn schema(&self) -> Option<&SchemaReference> {
450        match self {
451            Self::Opaque { .. } => None,
452            Self::SchemaBound { schema, .. } => Some(schema),
453        }
454    }
455
456    /// Returns whether this value must remain semantically opaque.
457    #[must_use]
458    pub const fn is_opaque(&self) -> bool {
459        matches!(self, Self::Opaque { .. })
460    }
461
462    /// Consumes the wrapper into its optional schema and bounded value.
463    #[must_use]
464    pub fn into_parts(self) -> (Option<SchemaReference>, BoundedJson) {
465        match self {
466            Self::Opaque { value } => (None, value),
467            Self::SchemaBound { schema, value } => (Some(schema), value),
468        }
469    }
470
471    fn try_restrict(self, limits: JsonLimits) -> Result<Self, BoundedJsonError> {
472        match self {
473            Self::Opaque { value } => {
474                BoundedJson::try_from_value_with_limits(value.into_value(), limits)
475                    .map(Self::opaque)
476            }
477            Self::SchemaBound { schema, value } => {
478                BoundedJson::try_from_value_with_limits(value.into_value(), limits)
479                    .map(|value| Self::schema_bound(schema, value))
480            }
481        }
482    }
483}
484
485impl fmt::Debug for ExtensionValue {
486    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
487        match self {
488            Self::Opaque { value } => formatter
489                .debug_struct("ExtensionValue::Opaque")
490                .field("value", value)
491                .finish_non_exhaustive(),
492            Self::SchemaBound { schema, value } => formatter
493                .debug_struct("ExtensionValue::SchemaBound")
494                .field("schema", schema)
495                .field("value", value)
496                .finish_non_exhaustive(),
497        }
498    }
499}
500
501/// Configurable dimension of the bounded extension-map contract.
502#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
503#[non_exhaustive]
504pub enum ExtensionLimit {
505    /// Number of top-level extension entries.
506    Entries,
507    /// Compact encoded bytes for the complete map.
508    TotalBytes,
509    /// Encoded bytes in one namespace key.
510    KeyBytes,
511    /// One of the nested bounded JSON dimensions.
512    ValueJson(JsonLimit),
513}
514
515impl fmt::Display for ExtensionLimit {
516    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
517        match self {
518            Self::Entries => formatter.write_str("extension entries"),
519            Self::TotalBytes => formatter.write_str("extension total bytes"),
520            Self::KeyBytes => formatter.write_str("extension key bytes"),
521            Self::ValueJson(limit) => write!(formatter, "extension value {limit}"),
522        }
523    }
524}
525
526/// Validated limits that may only narrow `StateKnot`'s hard extension ceiling.
527#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
528pub struct ExtensionLimits {
529    max_entries: usize,
530    max_total_bytes: usize,
531    max_key_bytes: usize,
532    value_json_limits: JsonLimits,
533}
534
535impl ExtensionLimits {
536    /// Absolute v1 ceiling used by generic deserialization.
537    pub const HARD_MAXIMUM: Self = Self {
538        max_entries: 64,
539        max_total_bytes: 256 * 1024,
540        max_key_bytes: ExtensionKey::MAX_LEN,
541        value_json_limits: JsonLimits::DEFAULT,
542    };
543
544    /// Constructs a valid profile no wider than [`Self::HARD_MAXIMUM`].
545    ///
546    /// # Errors
547    ///
548    /// Returns [`ExtensionLimitsError`] when a scalar is zero or below its
549    /// meaningful minimum, a dimension exceeds the hard maximum, or nested
550    /// JSON limits are wider than the hard extension profile.
551    pub fn try_new(
552        max_entries: usize,
553        max_total_bytes: usize,
554        max_key_bytes: usize,
555        value_json_limits: JsonLimits,
556    ) -> Result<Self, ExtensionLimitsError> {
557        validate_extension_limit(
558            ExtensionLimit::Entries,
559            max_entries,
560            1,
561            Self::HARD_MAXIMUM.max_entries,
562        )?;
563        validate_extension_limit(
564            ExtensionLimit::TotalBytes,
565            max_total_bytes,
566            2,
567            Self::HARD_MAXIMUM.max_total_bytes,
568        )?;
569        validate_extension_limit(
570            ExtensionLimit::KeyBytes,
571            max_key_bytes,
572            1,
573            Self::HARD_MAXIMUM.max_key_bytes,
574        )?;
575        validate_value_json_limits(value_json_limits)?;
576
577        Ok(Self {
578            max_entries,
579            max_total_bytes,
580            max_key_bytes,
581            value_json_limits,
582        })
583    }
584
585    /// Returns the top-level entry ceiling.
586    #[must_use]
587    pub const fn max_entries(self) -> usize {
588        self.max_entries
589    }
590
591    /// Returns the compact complete-map byte ceiling.
592    #[must_use]
593    pub const fn max_total_bytes(self) -> usize {
594        self.max_total_bytes
595    }
596
597    /// Returns the per-key encoded byte ceiling.
598    #[must_use]
599    pub const fn max_key_bytes(self) -> usize {
600        self.max_key_bytes
601    }
602
603    /// Returns limits applied to every nested extension value.
604    #[must_use]
605    pub const fn value_json_limits(self) -> JsonLimits {
606        self.value_json_limits
607    }
608}
609
610impl Default for ExtensionLimits {
611    fn default() -> Self {
612        Self::HARD_MAXIMUM
613    }
614}
615
616fn validate_extension_limit(
617    limit: ExtensionLimit,
618    actual: usize,
619    minimum: usize,
620    maximum: usize,
621) -> Result<(), ExtensionLimitsError> {
622    if actual == 0 {
623        return Err(ExtensionLimitsError::Zero { limit });
624    }
625    if actual < minimum {
626        return Err(ExtensionLimitsError::BelowMinimum {
627            limit,
628            minimum,
629            actual,
630        });
631    }
632    if actual > maximum {
633        return Err(ExtensionLimitsError::AboveHardMaximum {
634            limit,
635            maximum,
636            actual,
637        });
638    }
639    Ok(())
640}
641
642fn validate_value_json_limits(limits: JsonLimits) -> Result<(), ExtensionLimitsError> {
643    let maximum = JsonLimits::DEFAULT;
644    for (limit, actual, maximum) in [
645        (JsonLimit::Bytes, limits.max_bytes(), maximum.max_bytes()),
646        (JsonLimit::Depth, limits.max_depth(), maximum.max_depth()),
647        (
648            JsonLimit::ContainerEntries,
649            limits.max_container_entries(),
650            maximum.max_container_entries(),
651        ),
652        (JsonLimit::Nodes, limits.max_nodes(), maximum.max_nodes()),
653        (
654            JsonLimit::StringBytes,
655            limits.max_string_bytes(),
656            maximum.max_string_bytes(),
657        ),
658        (
659            JsonLimit::ObjectKeyBytes,
660            limits.max_object_key_bytes(),
661            maximum.max_object_key_bytes(),
662        ),
663    ] {
664        if actual > maximum {
665            return Err(ExtensionLimitsError::AboveHardMaximum {
666                limit: ExtensionLimit::ValueJson(limit),
667                maximum,
668                actual,
669            });
670        }
671    }
672    Ok(())
673}
674
675/// Invalid configurable extension-map limits.
676#[derive(Clone, Debug, Eq, Error, PartialEq)]
677#[non_exhaustive]
678pub enum ExtensionLimitsError {
679    /// A scalar limit was configured as zero.
680    #[error("{limit} limit must be greater than zero")]
681    Zero {
682        /// The invalid dimension.
683        limit: ExtensionLimit,
684    },
685
686    /// A non-zero scalar could not represent the smallest valid value.
687    #[error("configured {limit} limit is {actual}; minimum is {minimum}")]
688    BelowMinimum {
689        /// The invalid dimension.
690        limit: ExtensionLimit,
691        /// Smallest meaningful value for that dimension.
692        minimum: usize,
693        /// Configured value.
694        actual: usize,
695    },
696
697    /// A configured dimension exceeded the immutable v1 hard ceiling.
698    #[error("configured {limit} limit is {actual}; hard maximum is {maximum}")]
699    AboveHardMaximum {
700        /// The invalid dimension.
701        limit: ExtensionLimit,
702        /// `StateKnot`'s hard ceiling.
703        maximum: usize,
704        /// Configured value.
705        actual: usize,
706    },
707}
708
709/// A sorted, unique, resource-bounded extension map.
710///
711/// Deserializing an extension never grants authority or activates behavior.
712/// Adapters negotiate and register supported keys separately, schema-validate
713/// every semantically used value, and either reject or retain unknown opaque
714/// values according to their protocol profile. Serialization order is the
715/// exact byte order of canonical key text.
716#[derive(Clone, Eq, PartialEq)]
717pub struct Extensions {
718    entries: BTreeMap<ExtensionKey, ExtensionValue>,
719    compact_bytes: usize,
720}
721
722impl Extensions {
723    /// Constructs a map under the immutable v1 hard ceiling.
724    ///
725    /// # Errors
726    ///
727    /// Returns [`ExtensionsError`] for duplicate keys or a count, key, nested
728    /// JSON, compact-size, or internal encoding violation.
729    pub fn try_new<I>(entries: I) -> Result<Self, ExtensionsError>
730    where
731        I: IntoIterator<Item = (ExtensionKey, ExtensionValue)>,
732    {
733        Self::try_new_with_limits(entries, ExtensionLimits::HARD_MAXIMUM)
734    }
735
736    /// Constructs a map under an explicitly narrowed limit profile.
737    ///
738    /// # Errors
739    ///
740    /// Returns [`ExtensionsError`] for duplicate keys or a count, key, nested
741    /// JSON, compact-size, or internal encoding violation.
742    pub fn try_new_with_limits<I>(
743        entries: I,
744        limits: ExtensionLimits,
745    ) -> Result<Self, ExtensionsError>
746    where
747        I: IntoIterator<Item = (ExtensionKey, ExtensionValue)>,
748    {
749        let mut map = BTreeMap::new();
750        let mut compact_bytes = 2;
751        for (key, value) in entries {
752            insert_extension(&mut map, &mut compact_bytes, key, value, limits)?;
753        }
754        Ok(Self {
755            entries: map,
756            compact_bytes,
757        })
758    }
759
760    /// Revalidates an existing map under a profile that may be narrower.
761    ///
762    /// # Errors
763    ///
764    /// Returns [`ExtensionsError`] when existing entries exceed the profile.
765    pub fn try_restrict(self, limits: ExtensionLimits) -> Result<Self, ExtensionsError> {
766        Self::try_new_with_limits(self.entries, limits)
767    }
768
769    /// Returns the number of extension entries.
770    #[must_use]
771    pub fn len(&self) -> usize {
772        self.entries.len()
773    }
774
775    /// Returns whether the map contains no extensions.
776    #[must_use]
777    pub fn is_empty(&self) -> bool {
778        self.entries.is_empty()
779    }
780
781    /// Returns the exact compact JSON byte length of the complete map.
782    #[must_use]
783    pub const fn compact_bytes(&self) -> usize {
784        self.compact_bytes
785    }
786
787    /// Looks up one canonical namespace key.
788    #[must_use]
789    pub fn get(&self, key: &str) -> Option<&ExtensionValue> {
790        self.entries.get(key)
791    }
792
793    /// Returns entries in canonical key-byte order.
794    pub fn iter(&self) -> btree_map::Iter<'_, ExtensionKey, ExtensionValue> {
795        self.entries.iter()
796    }
797
798    /// Consumes the map into entries in canonical key-byte order.
799    #[must_use]
800    pub fn into_entries(self) -> Vec<(ExtensionKey, ExtensionValue)> {
801        self.entries.into_iter().collect()
802    }
803}
804
805impl Default for Extensions {
806    fn default() -> Self {
807        Self {
808            entries: BTreeMap::new(),
809            compact_bytes: 2,
810        }
811    }
812}
813
814impl fmt::Debug for Extensions {
815    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
816        formatter
817            .debug_struct("Extensions")
818            .field("entries", &self.len())
819            .field("compact_bytes", &self.compact_bytes)
820            .finish_non_exhaustive()
821    }
822}
823
824impl<'a> IntoIterator for &'a Extensions {
825    type Item = (&'a ExtensionKey, &'a ExtensionValue);
826    type IntoIter = btree_map::Iter<'a, ExtensionKey, ExtensionValue>;
827
828    fn into_iter(self) -> Self::IntoIter {
829        self.iter()
830    }
831}
832
833impl TryFrom<Vec<(ExtensionKey, ExtensionValue)>> for Extensions {
834    type Error = ExtensionsError;
835
836    fn try_from(entries: Vec<(ExtensionKey, ExtensionValue)>) -> Result<Self, Self::Error> {
837        Self::try_new(entries)
838    }
839}
840
841fn insert_extension(
842    entries: &mut BTreeMap<ExtensionKey, ExtensionValue>,
843    compact_bytes: &mut usize,
844    key: ExtensionKey,
845    value: ExtensionValue,
846    limits: ExtensionLimits,
847) -> Result<(), ExtensionsError> {
848    if key.as_str().len() > limits.max_key_bytes {
849        return Err(ExtensionsError::KeyTooLong {
850            max: limits.max_key_bytes,
851            actual: key.as_str().len(),
852        });
853    }
854    if entries.contains_key(&key) {
855        return Err(ExtensionsError::DuplicateKey);
856    }
857    if entries.len() == limits.max_entries {
858        return Err(ExtensionsError::TooManyEntries {
859            max: limits.max_entries,
860            observed: limits.max_entries + 1,
861        });
862    }
863
864    let value = value
865        .try_restrict(limits.value_json_limits)
866        .map_err(ExtensionsError::value)?;
867    let value_bytes = serde_json::to_vec(&value)
868        .map_err(|_| ExtensionsError::InternalEncoding)?
869        .len();
870    let separator_bytes = usize::from(!entries.is_empty());
871    let next_bytes = compact_bytes
872        .saturating_add(separator_bytes)
873        .saturating_add(key.as_str().len())
874        .saturating_add(3)
875        .saturating_add(value_bytes);
876    if next_bytes > limits.max_total_bytes {
877        return Err(ExtensionsError::TotalBytesExceeded {
878            max: limits.max_total_bytes,
879            actual: next_bytes,
880        });
881    }
882
883    entries.insert(key, value);
884    *compact_bytes = next_bytes;
885    Ok(())
886}
887
888impl Serialize for Extensions {
889    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
890    where
891        S: Serializer,
892    {
893        let mut map = serializer.serialize_map(Some(self.entries.len()))?;
894        for (key, value) in &self.entries {
895            map.serialize_entry(key.as_str(), value)?;
896        }
897        map.end()
898    }
899}
900
901impl<'de> Deserialize<'de> for Extensions {
902    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
903    where
904        D: Deserializer<'de>,
905    {
906        deserializer.deserialize_map(ExtensionsVisitor)
907    }
908}
909
910struct ExtensionsVisitor;
911
912impl<'de> de::Visitor<'de> for ExtensionsVisitor {
913    type Value = Extensions;
914
915    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
916        write!(
917            formatter,
918            "a namespaced extension object containing at most {} entries",
919            ExtensionLimits::HARD_MAXIMUM.max_entries
920        )
921    }
922
923    fn visit_map<A>(self, mut source: A) -> Result<Self::Value, A::Error>
924    where
925        A: de::MapAccess<'de>,
926    {
927        let limits = ExtensionLimits::HARD_MAXIMUM;
928        let mut entries = BTreeMap::new();
929        let mut compact_bytes = 2;
930        while entries.len() < limits.max_entries {
931            let Some(key) = source.next_key::<ExtensionKey>()? else {
932                return Ok(Extensions {
933                    entries,
934                    compact_bytes,
935                });
936            };
937            if entries.contains_key(&key) {
938                return Err(de::Error::custom(ExtensionsError::DuplicateKey));
939            }
940            let value = source.next_value::<ExtensionValue>()?;
941            insert_extension(&mut entries, &mut compact_bytes, key, value, limits)
942                .map_err(de::Error::custom)?;
943        }
944
945        let _: Option<()> = source.next_key_seed(RejectExtraExtensionSeed {
946            maximum: limits.max_entries,
947        })?;
948        Ok(Extensions {
949            entries,
950            compact_bytes,
951        })
952    }
953}
954
955struct RejectExtraExtensionSeed {
956    maximum: usize,
957}
958
959impl<'de> DeserializeSeed<'de> for RejectExtraExtensionSeed {
960    type Value = ();
961
962    fn deserialize<D>(self, _deserializer: D) -> Result<Self::Value, D::Error>
963    where
964        D: Deserializer<'de>,
965    {
966        Err(de::Error::custom(ExtensionsError::TooManyEntries {
967            max: self.maximum,
968            observed: self.maximum.saturating_add(1),
969        }))
970    }
971}
972
973impl JsonSchema for Extensions {
974    fn schema_name() -> std::borrow::Cow<'static, str> {
975        "Extensions".into()
976    }
977
978    fn schema_id() -> std::borrow::Cow<'static, str> {
979        concat!(module_path!(), "::Extensions").into()
980    }
981
982    fn json_schema(generator: &mut SchemaGenerator) -> Schema {
983        json_schema!({
984            "type": "object",
985            "minProperties": 0,
986            "maxProperties": 64,
987            "propertyNames": generator.subschema_for::<ExtensionKey>(),
988            "additionalProperties": generator.subschema_for::<ExtensionValue>(),
989            "description": "A deterministically ordered extension map. StateKnot additionally enforces exact 262144-byte compact-map and nested bounded-JSON limits at runtime; deserialization alone never activates extension semantics."
990        })
991    }
992}
993
994/// Invalid bounded extension-map data.
995#[derive(Clone, Debug, Eq, Error, PartialEq)]
996#[non_exhaustive]
997pub enum ExtensionsError {
998    /// More entries were supplied than the active profile permits.
999    #[error("extension map contains at least {observed} entries; maximum is {max}")]
1000    TooManyEntries {
1001        /// Configured maximum.
1002        max: usize,
1003        /// First observed count beyond the maximum.
1004        observed: usize,
1005    },
1006
1007    /// The same canonical namespace key appeared more than once.
1008    #[error("extension map contains a duplicate namespace key")]
1009    DuplicateKey,
1010
1011    /// A valid hard-bound key exceeded a narrowed profile.
1012    #[error("extension key is {actual} bytes; active profile maximum is {max}")]
1013    KeyTooLong {
1014        /// Configured maximum.
1015        max: usize,
1016        /// Observed byte length.
1017        actual: usize,
1018    },
1019
1020    /// One nested extension value violated the active bounded JSON profile.
1021    #[error("extension value violates JSON safety limits: {source}")]
1022    Value {
1023        /// Underlying bounded JSON violation.
1024        #[source]
1025        source: BoundedJsonError,
1026    },
1027
1028    /// The exact compact map representation exceeded the active profile.
1029    #[error("extension map reached {actual} compact bytes; maximum is {max}")]
1030    TotalBytesExceeded {
1031        /// Configured maximum.
1032        max: usize,
1033        /// First observed compact length beyond the maximum.
1034        actual: usize,
1035    },
1036
1037    /// Serialization of already validated internal components unexpectedly failed.
1038    #[error("validated extension value could not be compactly encoded")]
1039    InternalEncoding,
1040}
1041
1042impl ExtensionsError {
1043    const fn value(source: BoundedJsonError) -> Self {
1044        Self::Value { source }
1045    }
1046}
1047
1048#[cfg(test)]
1049mod tests {
1050    use std::fmt::Write as _;
1051
1052    use super::*;
1053    use proptest::{collection, prelude::*};
1054    use serde_json::{Value, from_value, json, to_value};
1055
1056    use crate::{Digest, SchemaId, Version};
1057
1058    fn bounded(value: Value) -> BoundedJson {
1059        BoundedJson::try_from_value(value).unwrap()
1060    }
1061
1062    fn schema_reference() -> SchemaReference {
1063        SchemaReference::new(
1064            "https://stateknot.github.io/schema/extension/citations/1.0.0"
1065                .parse::<SchemaId>()
1066                .unwrap(),
1067            Version::new(1, 0, 0),
1068            Digest::sha256(b"canonical extension schema"),
1069        )
1070    }
1071
1072    fn opaque(value: Value) -> ExtensionValue {
1073        ExtensionValue::opaque(bounded(value))
1074    }
1075
1076    fn limits(
1077        max_entries: usize,
1078        max_total_bytes: usize,
1079        max_key_bytes: usize,
1080        value_json_limits: JsonLimits,
1081    ) -> ExtensionLimits {
1082        ExtensionLimits::try_new(
1083            max_entries,
1084            max_total_bytes,
1085            max_key_bytes,
1086            value_json_limits,
1087        )
1088        .unwrap()
1089    }
1090
1091    #[test]
1092    fn keys_accept_canonical_uri_and_reverse_dns_namespaces() {
1093        for (value, kind) in [
1094            (
1095                "https://example.com/extensions/citations/v1",
1096                ExtensionKeyKind::Uri,
1097            ),
1098            (
1099                "https://example.com:8443/extensions/a%20b/v1",
1100                ExtensionKeyKind::Uri,
1101            ),
1102            ("urn:example:extension:citations:v1", ExtensionKeyKind::Uri),
1103            ("urn:ietf:rfc:8141", ExtensionKeyKind::Uri),
1104            ("io.stateknot.feature", ExtensionKeyKind::ReverseDns),
1105            ("com.example.citations-v1", ExtensionKeyKind::ReverseDns),
1106        ] {
1107            let key = ExtensionKey::new(value).unwrap();
1108            assert_eq!(key.as_str(), value);
1109            assert_eq!(key.kind(), kind);
1110            assert_eq!(key.to_string(), value);
1111            assert_eq!(to_value(&key).unwrap(), Value::from(value));
1112            assert_eq!(from_value::<ExtensionKey>(json!(value)).unwrap(), key);
1113            assert_eq!(String::from(key), value);
1114        }
1115    }
1116
1117    #[test]
1118    fn keys_reject_ambiguous_active_or_non_canonical_namespaces() {
1119        for value in [
1120            "example.feature",
1121            "com..feature",
1122            "com.example.",
1123            "1com.example.feature",
1124            "com.Example.feature",
1125            "com.example.-feature",
1126            "com.example.feature-",
1127            "com.example.feat_ure",
1128            "com.example.feature/name",
1129            "com.example.δΎ‹",
1130            "http://example.com/extension/v1",
1131            "ftp://example.com/extension/v1",
1132            "did:example:extension",
1133            "HTTPS://example.com/extension/v1",
1134            "https://EXAMPLE.com/extension/v1",
1135            "https://example.com:443/extension/v1",
1136            "https://example.com/a/../extension/v1",
1137            "https://example.com/extension/%7eowner",
1138            "https://user@example.com/extension/v1",
1139            "https://example.com/extension/v1?profile=full",
1140            "https://example.com/extension/v1#metadata",
1141            "https:/example.com/extension/v1",
1142            "urn:a:value",
1143            "urn:Example:value",
1144            "urn:example:",
1145            "urn:example",
1146            "URN:example:value",
1147            "urn:example:value?profile=full",
1148            "urn:example:value#metadata",
1149        ] {
1150            assert!(
1151                ExtensionKey::new(value).is_err(),
1152                "accepted extension key {value:?}"
1153            );
1154        }
1155
1156        assert_eq!(ExtensionKey::new(""), Err(ExtensionKeyError::Empty));
1157        let oversized = "a".repeat(ExtensionKey::MAX_LEN + 1);
1158        assert_eq!(
1159            ExtensionKey::new(&oversized),
1160            Err(ExtensionKeyError::TooLong {
1161                max: ExtensionKey::MAX_LEN,
1162                actual: oversized.len(),
1163            })
1164        );
1165        assert!(from_value::<ExtensionKey>(json!(42)).is_err());
1166        assert!(from_value::<ExtensionKey>(Value::Null).is_err());
1167    }
1168
1169    #[test]
1170    fn key_schema_documents_both_namespace_forms() {
1171        let schema = to_value(schemars::schema_for!(ExtensionKey)).unwrap();
1172        let alternatives = schema["oneOf"].as_array().unwrap();
1173        assert_eq!(alternatives.len(), 2);
1174        assert_eq!(alternatives[0]["format"], "uri");
1175        assert_eq!(alternatives[0]["maxLength"], ExtensionKey::MAX_LEN);
1176        assert_eq!(alternatives[0]["pattern"], URI_PATTERN);
1177        assert_eq!(alternatives[1]["pattern"], REVERSE_DNS_PATTERN);
1178    }
1179
1180    #[test]
1181    fn extension_values_have_closed_explicit_trust_modes() {
1182        let secret = "credential-like-secret";
1183        let opaque = opaque(json!({ "secret": secret }));
1184        assert!(opaque.is_opaque());
1185        assert!(opaque.schema().is_none());
1186        assert_eq!(opaque.value().as_value()["secret"], secret);
1187        assert!(!format!("{opaque:?}").contains(secret));
1188        assert_eq!(
1189            to_value(&opaque).unwrap(),
1190            json!({
1191                "kind": "opaque",
1192                "value": { "secret": secret }
1193            })
1194        );
1195
1196        let reference = schema_reference();
1197        let bound = ExtensionValue::schema_bound(reference.clone(), bounded(json!([1, 2, 3])));
1198        assert!(!bound.is_opaque());
1199        assert_eq!(bound.schema(), Some(&reference));
1200        let encoded = to_value(&bound).unwrap();
1201        assert_eq!(
1202            from_value::<ExtensionValue>(encoded.clone()).unwrap(),
1203            bound
1204        );
1205        assert_eq!(encoded["kind"], "schema_bound");
1206        assert_eq!(encoded["schema"], to_value(reference.clone()).unwrap());
1207
1208        let (schema, value) = bound.into_parts();
1209        assert_eq!(schema, Some(reference));
1210        assert_eq!(value.as_value(), &json!([1, 2, 3]));
1211
1212        for invalid in [
1213            json!({ "kind": "unknown", "value": null }),
1214            json!({ "kind": "opaque" }),
1215            json!({ "kind": "opaque", "value": null, "schema": null }),
1216            json!({ "kind": "opaque", "value": null, "extra": true }),
1217            json!({ "kind": "schema_bound", "value": null }),
1218            json!({ "kind": "schema_bound", "schema": null, "value": null }),
1219            Value::Null,
1220            json!([]),
1221        ] {
1222            assert!(
1223                from_value::<ExtensionValue>(invalid.clone()).is_err(),
1224                "accepted extension value {invalid}"
1225            );
1226        }
1227    }
1228
1229    #[test]
1230    fn extension_limit_profiles_have_stable_defaults_and_minimums() {
1231        let hard = ExtensionLimits::HARD_MAXIMUM;
1232        assert_eq!(ExtensionLimits::default(), hard);
1233        assert_eq!(hard.max_entries(), 64);
1234        assert_eq!(hard.max_total_bytes(), 256 * 1024);
1235        assert_eq!(hard.max_key_bytes(), ExtensionKey::MAX_LEN);
1236        assert_eq!(hard.value_json_limits(), JsonLimits::DEFAULT);
1237
1238        for (limit, result) in [
1239            (
1240                ExtensionLimit::Entries,
1241                ExtensionLimits::try_new(
1242                    0,
1243                    hard.max_total_bytes(),
1244                    hard.max_key_bytes(),
1245                    JsonLimits::DEFAULT,
1246                ),
1247            ),
1248            (
1249                ExtensionLimit::TotalBytes,
1250                ExtensionLimits::try_new(
1251                    hard.max_entries(),
1252                    0,
1253                    hard.max_key_bytes(),
1254                    JsonLimits::DEFAULT,
1255                ),
1256            ),
1257            (
1258                ExtensionLimit::KeyBytes,
1259                ExtensionLimits::try_new(
1260                    hard.max_entries(),
1261                    hard.max_total_bytes(),
1262                    0,
1263                    JsonLimits::DEFAULT,
1264                ),
1265            ),
1266        ] {
1267            assert_eq!(result, Err(ExtensionLimitsError::Zero { limit }));
1268        }
1269
1270        assert_eq!(
1271            ExtensionLimits::try_new(1, 1, 1, JsonLimits::DEFAULT),
1272            Err(ExtensionLimitsError::BelowMinimum {
1273                limit: ExtensionLimit::TotalBytes,
1274                minimum: 2,
1275                actual: 1,
1276            })
1277        );
1278    }
1279
1280    #[test]
1281    fn extension_limit_profiles_cannot_exceed_hard_ceilings() {
1282        let hard = ExtensionLimits::HARD_MAXIMUM;
1283        for (limit, result, maximum) in [
1284            (
1285                ExtensionLimit::Entries,
1286                ExtensionLimits::try_new(
1287                    hard.max_entries() + 1,
1288                    hard.max_total_bytes(),
1289                    hard.max_key_bytes(),
1290                    JsonLimits::DEFAULT,
1291                ),
1292                hard.max_entries(),
1293            ),
1294            (
1295                ExtensionLimit::TotalBytes,
1296                ExtensionLimits::try_new(
1297                    hard.max_entries(),
1298                    hard.max_total_bytes() + 1,
1299                    hard.max_key_bytes(),
1300                    JsonLimits::DEFAULT,
1301                ),
1302                hard.max_total_bytes(),
1303            ),
1304            (
1305                ExtensionLimit::KeyBytes,
1306                ExtensionLimits::try_new(
1307                    hard.max_entries(),
1308                    hard.max_total_bytes(),
1309                    hard.max_key_bytes() + 1,
1310                    JsonLimits::DEFAULT,
1311                ),
1312                hard.max_key_bytes(),
1313            ),
1314        ] {
1315            assert_eq!(
1316                result,
1317                Err(ExtensionLimitsError::AboveHardMaximum {
1318                    limit,
1319                    maximum,
1320                    actual: maximum + 1,
1321                })
1322            );
1323        }
1324
1325        let wider_json = JsonLimits::try_new(
1326            JsonLimits::DEFAULT.max_bytes() + 1,
1327            JsonLimits::DEFAULT.max_depth(),
1328            JsonLimits::DEFAULT.max_container_entries(),
1329            JsonLimits::DEFAULT.max_nodes(),
1330            JsonLimits::DEFAULT.max_string_bytes(),
1331            JsonLimits::DEFAULT.max_object_key_bytes(),
1332        )
1333        .unwrap();
1334        assert_eq!(
1335            ExtensionLimits::try_new(1, 2, 1, wider_json),
1336            Err(ExtensionLimitsError::AboveHardMaximum {
1337                limit: ExtensionLimit::ValueJson(JsonLimit::Bytes),
1338                maximum: JsonLimits::DEFAULT.max_bytes(),
1339                actual: JsonLimits::DEFAULT.max_bytes() + 1,
1340            })
1341        );
1342    }
1343
1344    #[test]
1345    fn maps_are_sorted_unique_and_track_exact_compact_bytes() {
1346        let empty = Extensions::try_new(Vec::new()).unwrap();
1347        assert!(empty.is_empty());
1348        assert_eq!(empty, Extensions::default());
1349        assert_eq!(empty.compact_bytes(), 2);
1350        assert_eq!(serde_json::to_string(&empty).unwrap(), "{}");
1351
1352        let secret = "opaque-secret";
1353        let entries = vec![
1354            (
1355                ExtensionKey::new("urn:example:zeta:v1").unwrap(),
1356                opaque(json!({ "secret": secret })),
1357            ),
1358            (
1359                ExtensionKey::new("com.example.alpha").unwrap(),
1360                ExtensionValue::schema_bound(
1361                    schema_reference(),
1362                    bounded(json!({ "enabled": true })),
1363                ),
1364            ),
1365        ];
1366        let extensions = Extensions::try_new(entries).unwrap();
1367        let encoded = serde_json::to_vec(&extensions).unwrap();
1368
1369        assert_eq!(extensions.len(), 2);
1370        assert_eq!(extensions.compact_bytes(), encoded.len());
1371        assert!(extensions.get("com.example.alpha").is_some());
1372        assert!(extensions.get("com.example.missing").is_none());
1373        assert_eq!(
1374            extensions
1375                .iter()
1376                .map(|(key, _)| key.as_str())
1377                .collect::<Vec<_>>(),
1378            ["com.example.alpha", "urn:example:zeta:v1"]
1379        );
1380        assert_eq!(
1381            serde_json::from_slice::<Extensions>(&encoded).unwrap(),
1382            extensions
1383        );
1384
1385        let debug = format!("{extensions:?}");
1386        assert!(debug.contains("entries: 2"));
1387        assert!(!debug.contains(secret));
1388        assert!(!debug.contains("com.example.alpha"));
1389
1390        let entries = extensions.clone().into_entries();
1391        assert_eq!(entries[0].0.as_str(), "com.example.alpha");
1392        assert_eq!(Extensions::try_from(entries).unwrap(), extensions);
1393    }
1394
1395    #[test]
1396    fn map_construction_rejects_duplicates_before_capacity_errors() {
1397        let key = ExtensionKey::new("com.example.duplicate").unwrap();
1398        assert_eq!(
1399            Extensions::try_new(vec![
1400                (key.clone(), opaque(json!(1))),
1401                (key, opaque(json!(2))),
1402            ]),
1403            Err(ExtensionsError::DuplicateKey)
1404        );
1405
1406        let duplicate_at_capacity = limits(1, 1024, 128, JsonLimits::DEFAULT);
1407        let key = ExtensionKey::new("com.example.duplicate").unwrap();
1408        assert_eq!(
1409            Extensions::try_new_with_limits(
1410                vec![(key.clone(), opaque(json!(1))), (key, opaque(json!(2)))],
1411                duplicate_at_capacity,
1412            ),
1413            Err(ExtensionsError::DuplicateKey)
1414        );
1415    }
1416
1417    #[test]
1418    fn narrowed_profiles_enforce_every_map_dimension() {
1419        let first = (
1420            ExtensionKey::new("com.example.alpha").unwrap(),
1421            opaque(json!("one")),
1422        );
1423        let second = (
1424            ExtensionKey::new("com.example.beta").unwrap(),
1425            opaque(json!("two")),
1426        );
1427
1428        assert_eq!(
1429            Extensions::try_new_with_limits(
1430                vec![first.clone(), second.clone()],
1431                limits(1, 1024, 128, JsonLimits::DEFAULT),
1432            ),
1433            Err(ExtensionsError::TooManyEntries {
1434                max: 1,
1435                observed: 2,
1436            })
1437        );
1438        assert_eq!(
1439            Extensions::try_new_with_limits(
1440                vec![first.clone()],
1441                limits(1, 1024, 8, JsonLimits::DEFAULT),
1442            ),
1443            Err(ExtensionsError::KeyTooLong {
1444                max: 8,
1445                actual: first.0.as_str().len(),
1446            })
1447        );
1448
1449        let narrow_json = JsonLimits::try_new(128, 4, 8, 8, 3, 16).unwrap();
1450        assert_eq!(
1451            Extensions::try_new_with_limits(
1452                vec![(
1453                    ExtensionKey::new("com.example.alpha").unwrap(),
1454                    opaque(json!("four")),
1455                )],
1456                limits(1, 1024, 128, narrow_json),
1457            ),
1458            Err(ExtensionsError::Value {
1459                source: BoundedJsonError::StringTooLong {
1460                    maximum: 3,
1461                    actual: 4,
1462                },
1463            })
1464        );
1465
1466        let complete = Extensions::try_new(vec![first]).unwrap();
1467        let exact = complete.compact_bytes();
1468        assert_eq!(
1469            complete
1470                .clone()
1471                .try_restrict(limits(1, exact - 1, 128, JsonLimits::DEFAULT,)),
1472            Err(ExtensionsError::TotalBytesExceeded {
1473                max: exact - 1,
1474                actual: exact,
1475            })
1476        );
1477        let restricted = complete
1478            .clone()
1479            .try_restrict(limits(1, exact, 128, JsonLimits::DEFAULT))
1480            .unwrap();
1481        assert_eq!(restricted, complete);
1482        assert_eq!(restricted.compact_bytes(), exact);
1483    }
1484
1485    #[test]
1486    fn wire_duplicates_and_entry_overflow_stop_before_values_are_traversed() {
1487        let deep_value = format!("{}0{}", "[".repeat(200), "]".repeat(200));
1488        let duplicate = format!(
1489            r#"{{"com.example.key":{{"kind":"opaque","value":null}},"com.example.key":{deep_value}}}"#
1490        );
1491        let error = serde_json::from_str::<Extensions>(&duplicate).unwrap_err();
1492        assert!(error.to_string().contains("duplicate namespace key"));
1493
1494        let mut overflow = String::from("{");
1495        for index in 0..ExtensionLimits::HARD_MAXIMUM.max_entries() {
1496            if index != 0 {
1497                overflow.push(',');
1498            }
1499            write!(
1500                overflow,
1501                r#""com.example.key{index}":{{"kind":"opaque","value":null}}"#
1502            )
1503            .unwrap();
1504        }
1505        let oversized_extra_key = "x".repeat(10_000);
1506        write!(overflow, r#","{oversized_extra_key}":{deep_value}}}"#).unwrap();
1507        let error = serde_json::from_str::<Extensions>(&overflow).unwrap_err();
1508        assert!(error.to_string().contains("at least 65 entries"));
1509
1510        let nested_duplicate = r#"{
1511            "com.example.key": {
1512                "kind": "opaque",
1513                "value": {"decoded": 1, "\u0064ecoded": 2}
1514            }
1515        }"#;
1516        assert!(serde_json::from_str::<Extensions>(nested_duplicate).is_err());
1517    }
1518
1519    #[test]
1520    fn map_schema_exposes_closed_values_and_hard_entry_ceiling() {
1521        let schema = to_value(schemars::schema_for!(Extensions)).unwrap();
1522        assert_eq!(schema["type"], "object");
1523        assert_eq!(schema["minProperties"], 0);
1524        assert_eq!(
1525            schema["maxProperties"],
1526            ExtensionLimits::HARD_MAXIMUM.max_entries()
1527        );
1528        assert!(schema.get("propertyNames").is_some());
1529        assert!(schema.get("additionalProperties").is_some());
1530
1531        let value_schema = to_value(schemars::schema_for!(ExtensionValue)).unwrap();
1532        let variants = value_schema["oneOf"].as_array().unwrap();
1533        assert_eq!(variants.len(), 2);
1534        assert!(
1535            variants
1536                .iter()
1537                .all(|variant| variant["additionalProperties"] == false)
1538        );
1539    }
1540
1541    proptest! {
1542        #[test]
1543        fn insertion_order_cannot_change_wire_bytes_or_accounting(
1544            values in collection::btree_map("[a-z][a-z0-9]{0,10}", any::<i64>(), 0..20)
1545        ) {
1546            let forward = values
1547                .iter()
1548                .map(|(name, value)| {
1549                    (
1550                        ExtensionKey::new(format!("com.example.{name}")).unwrap(),
1551                        opaque(json!(value)),
1552                    )
1553                })
1554                .collect::<Vec<_>>();
1555            let reverse = forward.iter().cloned().rev().collect::<Vec<_>>();
1556            let forward = Extensions::try_new(forward).unwrap();
1557            let reverse = Extensions::try_new(reverse).unwrap();
1558            let encoded = serde_json::to_vec(&forward).unwrap();
1559
1560            prop_assert_eq!(&forward, &reverse);
1561            prop_assert_eq!(serde_json::to_vec(&reverse).unwrap(), encoded.clone());
1562            prop_assert_eq!(forward.compact_bytes(), encoded.len());
1563        }
1564    }
1565}