cmw 0.1.2

Rust implementation of CMW
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
// Copyright 2025 Contributors to the Veraison project.
// SPDX-License-Identifier: Apache-2.0

//! Collection CMW: map of keys → nested CMW, with optional "__cmwc_t" type.

use crate::{
    cmw::{Error, Kind},
    CMW,
};
use iri_string::types::UriStr;
use minicbor::{data::Type as CborType, encode::Write, Decoder, Encode, Encoder};
use regex::Regex;
use serde_json::{Map as JsonMap, Value as JsonValue};
use std::{
    collections::BTreeMap,
    fmt::{self, Display},
    str::FromStr,
};

/// Format enum: JSON/CBOR record, collection, or CBOR Tag.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Format {
    Json,
    Cbor,
}

impl fmt::Display for Format {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            Format::Json => "JSON collection",
            Format::Cbor => "CBOR collection",
        };
        write!(f, "{s}")
    }
}

/// A collection key: either a String or u64.
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum Label {
    Str(String),
    Uint(u64),
}

impl fmt::Display for Label {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Label::Str(s) => write!(f, "{s}"),
            Label::Uint(u) => write!(f, "{u}"),
        }
    }
}

impl From<&str> for Label {
    fn from(val: &str) -> Self {
        Self::Str(val.into())
    }
}

impl From<String> for Label {
    fn from(val: String) -> Self {
        Self::Str(val)
    }
}

impl From<u64> for Label {
    fn from(val: u64) -> Self {
        Self::Uint(val)
    }
}

/// Meta entry (key + kind).
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Meta {
    pub key: Label,
    pub kind: Kind,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Type(String);

impl Type {
    pub fn new<S: Into<String>>(s: S) -> Result<Self, Error> {
        let s = s.into();
        Self::validate(&s)?;
        Ok(Type(s))
    }

    /// Validate collection type: must be a URI or an absolute OID.
    fn validate(s: &str) -> Result<(), Error> {
        let oid_re = Regex::new(r"^([0-2])(([.]0)|([.][1-9][0-9]*))*$").unwrap();

        if oid_re.is_match(s) {
            return Ok(());
        }
        if UriStr::new(s).is_ok() {
            return Ok(());
        }
        Err(Error::InvalidData(format!(
            "invalid collection type: {:?}. MUST be URI or OID",
            s
        )))
    }
}

impl Display for Type {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl FromStr for Type {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::new(s)
    }
}

/// The Collection structure.
#[derive(Clone, Debug)]
pub struct Collection {
    cmap: BTreeMap<Label, CMW>,
    ctyp: Option<Type>,
    pub(crate) format: Option<Format>,
}

impl PartialEq for Collection {
    fn eq(&self, other: &Self) -> bool {
        self.ctyp == other.ctyp && self.cmap == other.cmap
    }
}

impl Collection {
    /// Create new collection with optional type.
    pub fn new(ctyp: Option<Type>, format: Option<Format>) -> Result<Self, Error> {
        Ok(Collection {
            cmap: BTreeMap::new(),
            ctyp,
            format,
        })
    }

    pub fn get_type(&self) -> Option<&Type> {
        self.ctyp.as_ref()
    }

    pub fn add_item(&mut self, key: Label, node: CMW) -> Result<(), Error> {
        // Validate key (string must not be "__cmwc_t" or empty/whitespace).
        match &key {
            Label::Str(s) => {
                if s.trim().is_empty() {
                    return Err(Error::InvalidData(
                        "bad collection key: empty or whitespace only".into(),
                    ));
                }
                if s == "__cmwc_t" {
                    return Err(Error::InvalidData(
                        "bad collection key: __cmwc_t is reserved".into(),
                    ));
                }
            }
            Label::Uint(_) => {}
        }
        self.cmap.insert(key, node);
        Ok(())
    }

    pub fn get_item(&self, key: &Label) -> Option<&CMW> {
        self.cmap.get(key)
    }

    pub fn validate(&self) -> Result<(), Error> {
        if self.cmap.is_empty() {
            return Err(Error::InvalidData("empty CMW collection".into()));
        }
        for (k, v) in &self.cmap {
            if let Err(e) = v.validate() {
                return Err(Error::InvalidData(format!(
                    "invalid collection at key {:?}: {}",
                    k, e
                )));
            }
        }
        Ok(())
    }

    pub fn get_meta(&self) -> Vec<Meta> {
        let mut metas: Vec<Meta> = self
            .cmap
            .iter()
            .map(|(k, v)| Meta {
                key: k.clone(),
                kind: v.kind(),
            })
            .collect();
        metas.sort_by(|a, b| {
            let ka = match &a.key {
                Label::Str(s) => s.clone(),
                Label::Uint(u) => format!("##{}", u),
            };
            let kb = match &b.key {
                Label::Str(s) => s.clone(),
                Label::Uint(u) => format!("##{}", u),
            };
            ka.cmp(&kb)
        });
        metas
    }

    /// Serialize as JSON: object with string keys.
    pub fn marshal_json(&self) -> Result<Vec<u8>, Error> {
        let val = self.to_json_value()?;
        Ok(serde_json::to_vec(&val)?)
    }

    /// Convert to [serde_json::Value]
    pub fn to_json_value(&self) -> Result<JsonValue, Error> {
        let mut map: JsonMap<String, JsonValue> = JsonMap::new();
        if let Some(ref c) = self.ctyp {
            map.insert("__cmwc_t".into(), JsonValue::String(c.to_string()));
        }
        for (k, v) in &self.cmap {
            if let Label::Str(k) = k {
                let v = v.to_json_value()?;
                if !matches!(v, JsonValue::Array(_) | JsonValue::Object(_)) {
                    Err(Error::Unexpected(
                        "in collection, value is not a json-record or a json-collection"
                            .to_string(),
                    ))?;
                }
                map.insert(k.clone(), v);
            } else {
                Err(Error::InvalidData(
                    "JSON collection, key error: want string".into(),
                ))?;
            }
        }
        Ok(map.into())
    }

    /// Deserialize from JSON bytes.
    pub fn unmarshal_json(b: &[u8]) -> Result<Self, Error> {
        let raw: JsonValue = serde_json::from_slice(b).map_err(Error::Json)?;
        Self::from_json_value(&raw)
    }

    /// Construct using [serde_json::Value]
    pub fn from_json_value(v: &JsonValue) -> Result<Self, Error> {
        let obj = v
            .as_object()
            .ok_or_else(|| Error::InvalidData("want JSON object start".to_string()))?;
        let mut col = Collection::new(None, None)?;
        for (key, val) in obj {
            if key == "__cmwc_t" {
                if let JsonValue::String(s) = val {
                    col.ctyp = Some(Type::from_str(s)?);
                    continue;
                } else {
                    return Err(Error::InvalidData("invalid JSON collection type".into()));
                }
            }
            col.cmap
                .insert(Label::Str(key.clone()), CMW::from_json_value(val)?);
        }
        col.format = Some(Format::Json);
        Ok(col)
    }

    /// Serialize as CBOR: map with string/u64 keys.
    pub fn marshal_cbor(&self) -> Result<Vec<u8>, Error> {
        let buf = Vec::new();
        let mut encoder = Encoder::new(buf);
        self.marshal_cbor_to_encoder(&mut encoder)?;
        Ok(encoder.into_writer())
    }

    pub(crate) fn marshal_cbor_to_encoder<W: Write>(
        &self,
        encoder: &mut Encoder<W>,
    ) -> Result<(), Error> {
        let meta = self.get_meta();
        let _ = encoder.map(meta.len() as u64).or(Err(Error::CborEncode(
            "starting CBOR collection map".to_string(),
        )))?;
        if let Some(ref c) = self.ctyp {
            encoder.str("__cmwc_t").or(Err(Error::CborEncode(
                "serializing CBOR collection type".to_string(),
            )))?;
            encoder.str(&c.to_string()).or(Err(Error::CborEncode(
                "serializing CBOR collection type".to_string(),
            )))?;
        }
        for (k, v) in &self.cmap {
            match k {
                Label::Str(s) => encoder.str(s).or(Err(Error::CborEncode(
                    "serializing a collection key (string)".to_string(),
                )))?,
                Label::Uint(u) => encoder.u64(*u).or(Err(Error::CborEncode(
                    "serializing a collection key (int)".to_string(),
                )))?,
            };
            v.encode(encoder, &mut ())
                .or(Err(Error::CborEncode("serializing nested CMW".to_string())))?;
        }
        Ok(())
    }

    /// Deserialize from CBOR bytes.
    pub fn unmarshal_cbor(b: &[u8]) -> Result<Self, Error> {
        let mut decoder = Decoder::new(b);
        Self::unmarshal_from_cbor_decoder(&mut decoder)
    }

    pub(crate) fn unmarshal_from_cbor_decoder(decoder: &mut Decoder<'_>) -> Result<Self, Error> {
        let mut col = Collection::new(None, None)?;
        let _ = decoder
            .map()
            .map_err(|e| Error::CborDecode(format!("decoding collection map: {e}")))?;
        loop {
            let key_type: CborType = match decoder.datatype() {
                Ok(t) => t,
                Err(e) if e.is_end_of_input() => break,
                Err(e) => {
                    return Err(Error::InvalidData(format!(
                        "decoding collection key type: {e}"
                    )))
                }
            };
            match key_type {
                CborType::String => {
                    let ks = decoder
                        .str()
                        .map_err(|e| Error::CborDecode(format!("decoding CBOR string key: {e}")))?;

                    if ks == "__cmwc_t" {
                        let collection_type = decoder.str().map_err(|e| {
                            Error::CborDecode(format!("decoding CBOR collection type: {e}"))
                        })?;
                        col.ctyp = Some(Type::from_str(collection_type)?);
                        continue;
                    }

                    let nested = decoder
                        .decode()
                        .map_err(|e| Error::CborDecode(format!("decoding CBOR nested CMW: {e}")))?;
                    col.cmap.insert(Label::Str(ks.to_string()), nested);
                }
                CborType::Int
                | CborType::I16
                | CborType::I32
                | CborType::I64
                | CborType::I8
                | CborType::U16
                | CborType::U32
                | CborType::U64
                | CborType::U8 => {
                    let ui = decoder
                        .u64()
                        .map_err(|e| Error::CborDecode(format!("decoding CBOR uint key: {e}")))?;
                    let nested = decoder
                        .decode()
                        .map_err(|e| Error::CborDecode(format!("decoding CBOR nested CMW: {e}")))?;
                    col.cmap.insert(Label::Uint(ui), nested);
                }
                _ => {
                    return Err(Error::InvalidData(format!(
                        "unknown collection key type: want string or uint: {:?}",
                        key_type
                    )))
                }
            }
        }
        col.format = Some(Format::Cbor);
        Ok(col)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{cmw::CMW, monad::Monad};
    use std::str::FromStr;

    // Helper: create a dummy CMW instance wrapping a Monad.
    fn dummy_cmw() -> CMW {
        // Using new_cf as in your tests, with dummy data.
        Monad::new_cf(30001, vec![0x01, 0x02, 0x03], None)
            .expect("Failed to create dummy Monad")
            .into()
    }

    fn dummy_cmw_collection() -> CMW {
        let mut c =
            Collection::new(None, Some(Format::Json)).expect("failed to create dummy collection");
        c.add_item("bar".into(), dummy_cmw())
            .expect("failed to add monad to collection");
        c.into()
    }

    #[test]
    fn test_validate_collection_type() {
        Type::validate("tag:example.com,2024:composite-attester").unwrap();
        assert!(Type::validate("urn:ietf:rfc:rfc9999").is_ok());
        assert!(Type::validate("http://www.ietf.org/rfc/rfc2396.txt").is_ok());
        assert!(Type::validate("1.2.3.4").is_ok());
        assert!(Type::validate("").is_err());
        assert!(Type::validate("a/b/c").is_err());
        assert!(Type::validate(".2.3.4").is_err());
    }

    #[test]
    fn test_new_collection_no_type() {
        let collection = Collection::new(None, Some(Format::Json))
            .expect("Failed to create collection without type");
        assert!(collection.get_type().is_none());
    }

    #[test]
    fn test_new_collection_with_valid_type() {
        let type_str = "tag:example.com,2024:composite-attester";
        let type_ = Type::from_str(type_str).expect("Failed to parse type");
        let collection = Collection::new(Some(type_.clone()), Some(Format::Cbor))
            .expect("Failed to create collection with type");
        assert_eq!(collection.get_type(), Some(&type_));
    }

    #[test]
    fn test_add_and_get_item() {
        let mut collection =
            Collection::new(None, Some(Format::Json)).expect("Failed to create collection");
        let key = Label::Str("test".to_string());
        let cmw_item = dummy_cmw();
        collection
            .add_item(key.clone(), cmw_item.clone())
            .expect("Failed to add item");
        let retrieved = collection.get_item(&key);
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap(), &cmw_item);
    }

    #[test]
    fn test_validate_empty_collection() {
        let collection =
            Collection::new(None, Some(Format::Json)).expect("Failed to create collection");
        let result = collection.validate();
        assert!(result.is_err());
    }

    #[test]
    fn test_get_meta_sorted() {
        let mut collection =
            Collection::new(None, Some(Format::Cbor)).expect("Failed to create collection");
        // Add items with keys in non-sorted order.
        let key1 = Label::Str("b_key".to_string());
        let key2 = Label::Str("a_key".to_string());
        collection
            .add_item(key1, dummy_cmw())
            .expect("Failed to add item");
        collection
            .add_item(key2, dummy_cmw())
            .expect("Failed to add item");
        let meta = collection.get_meta();
        assert_eq!(meta.len(), 2);
        // Meta should be sorted (by key display).
        let first_key = match &meta[0].key {
            Label::Str(s) => s,
            _ => "",
        };
        assert_eq!(first_key, "a_key");
    }

    #[test]
    fn test_json_roundtrip() {
        let type_str = "tag:example.com,2024:composite-attester";
        let type_ = Type::from_str(type_str).expect("Failed to parse type");
        let mut collection =
            Collection::new(Some(type_), Some(Format::Json)).expect("Failed to create collection");
        collection
            .add_item("item1".into(), dummy_cmw())
            .expect("Failed to add item");
        collection
            .add_item("item2".to_string().into(), dummy_cmw_collection())
            .expect("Failed to add item");
        // Marshal the collection to JSON bytes.
        let json_bytes = collection
            .marshal_json()
            .expect("Failed to marshal collection to JSON");
        println!("{}", String::from_utf8(json_bytes.clone()).unwrap());
        // Unmarshal the JSON bytes back into a collection.
        let collection2 = Collection::unmarshal_json(&json_bytes)
            .expect("Failed to unmarshal JSON into collection");
        assert_eq!(collection, collection2);
    }

    #[test]
    fn test_cbor_roundtrip() {
        let type_str = "tag:example.com,2024:composite-attester";
        let type_ = Type::from_str(type_str).expect("Failed to parse type");
        let mut collection =
            Collection::new(Some(type_), Some(Format::Cbor)).expect("Failed to create collection");
        collection
            .add_item("item1".into(), dummy_cmw())
            .expect("Failed to add item");
        collection
            .add_item(42.into(), dummy_cmw())
            .expect("Failed to add item");
        // Marshal the collection to CBOR bytes.
        let cbor_bytes = collection
            .marshal_cbor()
            .expect("Failed to marshal collection to CBOR");
        // Unmarshal the CBOR bytes back into a collection.
        let collection2 = Collection::unmarshal_cbor(&cbor_bytes)
            .expect("Failed to unmarshal CBOR into collection");
        assert_eq!(collection, collection2);
    }

    #[test]
    fn test_json_string_invalid() {
        let coll_as_string = r#"{"collection":["monad.type/sample","AAAA"]}"#;
        let val_obj: serde_json::Value = serde_json::from_slice(coll_as_string.as_bytes()).unwrap();
        let coll = Collection::from_json_value(&val_obj).unwrap();
        let ser_coll = String::from_utf8(coll.marshal_json().unwrap()).unwrap();
        assert_eq!(coll_as_string, ser_coll);

        // check if passing the json object inside a json string fails
        let val_str: serde_json::Value = serde_json::json!(coll_as_string);
        assert!(Collection::from_json_value(&val_str).is_err())
    }

    #[test]
    fn test_json_non_str_label() {
        let mut collection = Collection::new(None, None).expect("Failed to create collection");
        // integer label not allowed in json collection
        collection
            .add_item(42.into(), dummy_cmw())
            .expect("Failed to add item");

        let res = collection.marshal_json();
        assert!(
            matches!(res, Err(Error::InvalidData(_))),
            "marshal json with non-string label should give error"
        );
    }
}