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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
// Copyright 2024 The Fuchsia Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use base64::engine::general_purpose::STANDARD;
use base64::Engine as _;
use indexmap::IndexMap;
use num_traits::FromPrimitive;
use serde::{Deserialize, Serialize};
use std::fs::read_to_string;
use std::path::Path;
use tee_internal::{Identity, Login, Uuid};

// Maps to GlobalPlatform TEE Internal Core API Section 4.4: Property Access Functions
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PropType {
    BinaryBlock,
    UnsignedInt32,
    UnsignedInt64,
    Boolean,
    Uuid,
    Identity,
    String,
}

#[derive(Clone, Debug, thiserror::Error)]
pub enum PropertyError {
    #[error("Bad format: Unable to parse type: {prop_type:?} from value: {value}")]
    BadFormat { prop_type: PropType, value: String },
    #[error("Item not found: {name}")]
    ItemNotFound { name: String },
    // Callers following Internal Core API spec should panic on this error.
    #[error("Generic TeeProperty error: {msg}")]
    Generic { msg: String },
}

#[derive(Debug, Deserialize, Serialize)]
pub struct TeeProperty {
    name: String,
    prop_type: PropType,
    value: String,
}

pub type TeeProperties = Vec<TeeProperty>;

// Maps to GlobalPlatform TEE Internal Core API Section 4.2.4: Property Set Pseudo-Handles
// TeePropSetTeeImplementation = 0xFFFFFFFD,
// TeePropSetCurrentClient = 0xFFFFFFFE,
// TeePropsetCurrentTA = 0xFFFFFFFF,
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PropSetType {
    TeeImplementation,
    CurrentClient,
    CurrentTA,
}

pub type PropertiesMap = IndexMap<String, (PropType, String)>;

#[allow(dead_code)]
pub struct PropSet {
    prop_set_type: PropSetType,
    properties: PropertiesMap,
}

impl PropSet {
    #[cfg(test)]
    pub(crate) fn new(prop_set_type: PropSetType, properties: PropertiesMap) -> Self {
        Self { prop_set_type, properties }
    }

    pub fn from_config_file(
        config_path: &Path,
        prop_set: PropSetType,
    ) -> Result<Self, PropertyError> {
        match read_to_string(config_path) {
            Ok(config_string) => Self::from_config_string(&config_string, prop_set),
            Err(e) => Err(PropertyError::Generic { msg: e.to_string() }),
        }
    }

    pub fn from_config_string(
        config_string: &str,
        prop_set: PropSetType,
    ) -> Result<Self, PropertyError> {
        let props: TeeProperties = match serde_json5::from_str(config_string) {
            Ok(tee_props) => tee_props,
            Err(e) => return Err(PropertyError::Generic { msg: e.to_string() }),
        };
        let mut property_map = IndexMap::new();

        for property in props {
            property_map.insert(property.name, (property.prop_type, property.value));
        }

        Ok(Self { prop_set_type: prop_set, properties: property_map })
    }

    fn get_value(&self, prop_name: String) -> Result<String, PropertyError> {
        match self.properties.get(&prop_name) {
            Some((_, val)) => Ok(val.clone()),
            None => Err(PropertyError::ItemNotFound { name: prop_name }),
        }
    }

    pub fn get_string_property(&self, prop_name: String) -> Result<String, PropertyError> {
        self.get_value(prop_name)
    }

    pub fn get_boolean_property(&self, prop_name: String) -> Result<bool, PropertyError> {
        parse_bool(self.get_value(prop_name)?)
    }

    pub fn get_uint32_property(&self, prop_name: String) -> Result<u32, PropertyError> {
        parse_uint32(self.get_value(prop_name)?)
    }

    pub fn get_uint64_property(&self, prop_name: String) -> Result<u64, PropertyError> {
        parse_uint64(self.get_value(prop_name)?)
    }

    pub fn get_binary_block_property(&self, prop_name: String) -> Result<Vec<u8>, PropertyError> {
        parse_binary_block(self.get_value(prop_name)?)
    }

    pub fn get_uuid_property(&self, prop_name: String) -> Result<Uuid, PropertyError> {
        parse_uuid(self.get_value(prop_name)?)
    }

    pub fn get_identity_property(&self, prop_name: String) -> Result<Identity, PropertyError> {
        parse_identity(self.get_value(prop_name)?)
    }

    pub fn get_property_name_at_index(&self, index: usize) -> Result<String, PropertyError> {
        match self.properties.get_index(index) {
            Some((prop_name, (_, _))) => Ok(prop_name.to_string()),
            None => Err(PropertyError::ItemNotFound { name: format!("item at index {}", index) }),
        }
    }

    pub fn get_property_type_at_index(&self, index: usize) -> Result<PropType, PropertyError> {
        match self.properties.get_index(index) {
            Some((_, (prop_type, _))) => Ok(prop_type.clone()),
            None => Err(PropertyError::ItemNotFound { name: format!("item at index {}", index) }),
        }
    }
}

pub struct PropEnumerator {
    properties: Option<PropSet>,
    index: usize,
}

impl PropEnumerator {
    pub fn new() -> Self {
        Self { properties: None, index: 0 }
    }

    // Spec indicates that callers should start() before doing other operations.
    // This impl doesn't need to do any functional work here since the initial state is valid.
    pub fn start(&mut self, propset: PropSet) {
        self.properties = Some(propset);
        self.index = 0;
    }

    pub fn restart(&mut self) {
        self.index = 0;
    }

    pub fn next(&mut self) -> Result<(), PropertyError> {
        if self.properties.is_none() {
            return Err(PropertyError::ItemNotFound {
                name: "enumerator has not been started".to_string(),
            });
        }
        self.index = self.index + 1;
        Ok(())
    }

    pub fn get_property_name(&self) -> Result<String, PropertyError> {
        // This will return ItemNotFound when going out-of-bounds, compliant with spec.
        self.get_props()?.get_property_name_at_index(self.index)
    }

    pub fn get_property_type(&self) -> Result<PropType, PropertyError> {
        // This will return ItemNotFound when going out-of-bounds, compliant with spec.
        self.get_props()?.get_property_type_at_index(self.index)
    }

    pub fn get_property_as_string(&self) -> Result<String, PropertyError> {
        let prop_name = self.get_property_name()?;
        self.get_props()?.get_string_property(prop_name)
    }

    pub fn get_property_as_bool(&self) -> Result<bool, PropertyError> {
        let prop_name = self.get_property_name()?;
        self.get_props()?.get_boolean_property(prop_name)
    }

    pub fn get_property_as_u32(&self) -> Result<u32, PropertyError> {
        let prop_name = self.get_property_name()?;
        self.get_props()?.get_uint32_property(prop_name)
    }

    pub fn get_property_as_u64(&self) -> Result<u64, PropertyError> {
        let prop_name = self.get_property_name()?;
        self.get_props()?.get_uint64_property(prop_name)
    }

    pub fn get_property_as_binary_block(&self) -> Result<Vec<u8>, PropertyError> {
        let prop_name = self.get_property_name()?;
        self.get_props()?.get_binary_block_property(prop_name)
    }

    pub fn get_property_as_uuid(&self) -> Result<Uuid, PropertyError> {
        let prop_name = self.get_property_name()?;
        self.get_props()?.get_uuid_property(prop_name)
    }

    pub fn get_property_as_identity(&self) -> Result<Identity, PropertyError> {
        let prop_name = self.get_property_name()?;
        self.get_props()?.get_identity_property(prop_name)
    }

    fn get_props(&self) -> Result<&PropSet, PropertyError> {
        match &self.properties {
            Some(prop_set) => Ok(prop_set),
            None => Err(PropertyError::ItemNotFound {
                name: "enumerator has not been started".to_string(),
            }),
        }
    }
}

// These parsing functions define format of value strings expected in config files.
fn parse_bool(value: String) -> Result<bool, PropertyError> {
    match value.parse::<bool>() {
        Ok(val) => Ok(val),
        Err(_) => Err(PropertyError::BadFormat { prop_type: PropType::Boolean, value }),
    }
}

// TODO(https://fxbug.dev/369916290): Support the full list of integer value encodings (See 4.4 in
// the spec).
fn parse_uint32(value: String) -> Result<u32, PropertyError> {
    match value.parse::<u32>() {
        Ok(val) => Ok(val),
        Err(_) => Err(PropertyError::BadFormat { prop_type: PropType::UnsignedInt32, value }),
    }
}

// TODO(https://fxbug.dev/369916290): Support the full list of integer value encodings (See 4.4 in
// the spec).
fn parse_uint64(value: String) -> Result<u64, PropertyError> {
    match value.parse::<u64>() {
        Ok(val) => Ok(val),
        Err(_) => Err(PropertyError::BadFormat { prop_type: PropType::UnsignedInt64, value }),
    }
}

fn parse_binary_block(value: String) -> Result<Vec<u8>, PropertyError> {
    // The string is expected to be base64 encoded.
    match STANDARD.decode(value.clone()) {
        Ok(bytes) => Ok(Vec::from(bytes)),
        Err(_) => Err(PropertyError::BadFormat { prop_type: PropType::BinaryBlock, value }),
    }
}

fn parse_uuid(value: String) -> Result<Uuid, PropertyError> {
    match uuid::Uuid::parse_str(&value) {
        Ok(uuid) => {
            let (time_low, time_mid, time_hi_and_version, clock_seq_and_node) = uuid.as_fields();
            Ok(Uuid {
                time_low: time_low,
                time_mid: time_mid,
                time_hi_and_version: time_hi_and_version,
                clock_seq_and_node: *clock_seq_and_node,
            })
        }
        Err(_) => Err(PropertyError::BadFormat { prop_type: PropType::Uuid, value }),
    }
}

fn parse_identity(value: String) -> Result<Identity, PropertyError> {
    // Encoded as `integer (':' uuid)?`.
    let (login_str, uuid) = match value.split_once(':') {
        Some((login_str, uuid_str)) => (login_str, parse_uuid(uuid_str.to_string())?),
        None => (value.as_str(), Uuid::default()),
    };
    let login_val = match login_str.parse::<u32>() {
        Ok(val) => val,
        Err(_) => return Err(PropertyError::BadFormat { prop_type: PropType::Identity, value }),
    };
    let login = Login::from_u32(login_val)
        .ok_or(PropertyError::BadFormat { prop_type: PropType::Identity, value })?;
    Ok(Identity { login, uuid })
}

// TODO(b/366015756): Parsing logic should be fuzzed for production-hardening.
#[cfg(test)]
pub mod tests {
    use super::*;

    const TEST_PROP_NAME_STRING: &str = "gpd.tee.test.string";
    const TEST_PROP_NAME_BOOL: &str = "gpd.tee.test.bool";
    const TEST_PROP_NAME_U32: &str = "gpd.tee.test.u32";
    const TEST_PROP_NAME_U64: &str = "gpd.tee.test.u64";
    const TEST_PROP_NAME_BINARY_BLOCK: &str = "gpd.tee.test.binaryBlock";
    const TEST_PROP_NAME_UUID: &str = "gpd.tee.test.uuid";
    const TEST_PROP_NAME_IDENTITY: &str = "gpd.tee.test.identity";

    const TEST_PROP_VAL_STRING: &str = "asdf";
    const TEST_PROP_VAL_BOOL: &str = "true";
    const TEST_PROP_VAL_U32: &str = "57";
    const TEST_PROP_VAL_U64: &str = "4294967296"; // U32::MAX + 1
    const TEST_PROP_VAL_BINARY_BLOCK: &str = "ZnVjaHNpYQ=="; // base64 encoding of "fuchsia"

    const TEST_PROP_VAL_UUID: &str = "5b9e0e40-2636-11e1-ad9e-0002a5d5c51b"; // OS Test TA UUID
    const TEST_PROP_UUID: Uuid = Uuid {
        time_low: 0x5b9e0e40,
        time_mid: 0x2636,
        time_hi_and_version: 0x11e1,
        clock_seq_and_node: [0xad, 0x9e, 0x00, 0x02, 0xa5, 0xd5, 0xc5, 0x1b],
    };

    // TODO(https://fxbug.dev/369916290): Spell as 0xf0000000 when hex encodings are supported.
    const TEST_PROP_VAL_IDENTITY: &str = "4026531840:5b9e0e40-2636-11e1-ad9e-0002a5d5c51b";
    const TEST_PROP_IDENTITY: Identity =
        Identity { login: Login::TrustedApp, uuid: TEST_PROP_UUID };

    fn create_test_prop_map() -> PropertiesMap {
        let mut props: IndexMap<String, (PropType, String)> = IndexMap::new();
        props.insert(
            TEST_PROP_NAME_STRING.to_string(),
            (PropType::String, TEST_PROP_VAL_STRING.to_string()),
        );
        props.insert(
            TEST_PROP_NAME_BOOL.to_string(),
            (PropType::Boolean, TEST_PROP_VAL_BOOL.to_string()),
        );
        props.insert(
            TEST_PROP_NAME_U32.to_string(),
            (PropType::UnsignedInt32, TEST_PROP_VAL_U32.to_string()),
        );
        props.insert(
            TEST_PROP_NAME_U64.to_string(),
            (PropType::UnsignedInt64, TEST_PROP_VAL_U64.to_string()),
        );
        props.insert(
            TEST_PROP_NAME_BINARY_BLOCK.to_string(),
            (PropType::BinaryBlock, TEST_PROP_VAL_BINARY_BLOCK.to_string()),
        );
        props.insert(
            TEST_PROP_NAME_UUID.to_string(),
            (PropType::Uuid, TEST_PROP_VAL_UUID.to_string()),
        );
        props.insert(
            TEST_PROP_NAME_IDENTITY.to_string(),
            (PropType::Identity, TEST_PROP_VAL_IDENTITY.to_string()),
        );
        props
    }

    fn create_test_prop_set() -> PropSet {
        PropSet::new(PropSetType::TeeImplementation, create_test_prop_map())
    }

    #[test]
    pub fn test_load_config_from_string() {
        let config_json = r#"[
            {
                "name": "gpd.tee.asdf",
                "prop_type": "boolean",
                "value": "true"
            },
            {
                "name": "gpd.tee.other",
                "prop_type": "binary_block",
                "value": "testingzz"
            }
        ]
        "#;

        let prop_set: PropSet =
            PropSet::from_config_string(config_json, PropSetType::TeeImplementation)
                .expect("loading config");

        let bool_prop_value =
            prop_set.get_boolean_property("gpd.tee.asdf".to_string()).expect("getting bool prop");
        assert_eq!(true, bool_prop_value)
    }

    #[test]
    pub fn test_load_config_from_string_failure() {
        // Invalid json (missing opening `{` for first object)
        let config_json = r#"[
                "name": "gpd.tee.asdf",
                "prop_type": "boolean",
                "value": "true"
            },
            {
                "name": "gpd.tee.other",
                "prop_type": "binary_block",
                "value": "testingzz"
            }
        ]
        "#;

        let res = PropSet::from_config_string(config_json, PropSetType::TeeImplementation);

        match res.err() {
            Some(PropertyError::Generic { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }

    // *** Enumerator Tests ***
    #[test]
    pub fn test_enumerator_query_prop_types_success() {
        let mut enumerator = PropEnumerator::new();

        // Enumerate in the order of test prop set, starting with string.
        enumerator.start(create_test_prop_set());

        let prop_name = enumerator.get_property_name().expect("getting prop name");
        assert_eq!(TEST_PROP_NAME_STRING.to_string(), prop_name);

        let prop_type = enumerator.get_property_type().expect("getting prop type");
        assert_eq!(PropType::String, prop_type);

        let prop_val = enumerator.get_property_as_string().expect("getting prop as string");
        assert_eq!(TEST_PROP_VAL_STRING.to_string(), prop_val);

        // bool.
        enumerator.next().expect("moving enumerator to next prop");

        let prop_name = enumerator.get_property_name().expect("getting prop name");
        assert_eq!(TEST_PROP_NAME_BOOL.to_string(), prop_name);

        let prop_type = enumerator.get_property_type().expect("getting prop type");
        assert_eq!(PropType::Boolean, prop_type);

        let prop_val = enumerator.get_property_as_bool().expect("getting prop as bool");
        assert_eq!(true, prop_val);

        // u32.
        enumerator.next().expect("moving enumerator to next prop");

        let prop_name = enumerator.get_property_name().expect("getting prop name");
        assert_eq!(TEST_PROP_NAME_U32.to_string(), prop_name);

        let prop_type = enumerator.get_property_type().expect("getting prop type");
        assert_eq!(PropType::UnsignedInt32, prop_type);

        let prop_val = enumerator.get_property_as_u32().expect("getting prop as u32");
        assert_eq!(57, prop_val);

        // u64.
        enumerator.next().expect("moving enumerator to next prop");

        let prop_name = enumerator.get_property_name().expect("getting prop name");
        assert_eq!(TEST_PROP_NAME_U64.to_string(), prop_name);

        let prop_type = enumerator.get_property_type().expect("getting prop type");
        assert_eq!(PropType::UnsignedInt64, prop_type);

        let prop_val = enumerator.get_property_as_u64().expect("getting prop as u64");
        assert_eq!(4294967296, prop_val);

        // Binary block.
        enumerator.next().expect("moving enumerator to next prop");

        let prop_name = enumerator.get_property_name().expect("getting prop name");
        assert_eq!(TEST_PROP_NAME_BINARY_BLOCK.to_string(), prop_name);

        let prop_type = enumerator.get_property_type().expect("getting prop type");
        assert_eq!(PropType::BinaryBlock, prop_type);

        let prop_val =
            enumerator.get_property_as_binary_block().expect("getting prop as binary block");
        let bytes_expected = STANDARD.decode("ZnVjaHNpYQ==").expect("decoding binary block string");
        assert_eq!(bytes_expected, prop_val);

        // UUID.
        enumerator.next().expect("moving enumerator to next prop");

        let prop_name = enumerator.get_property_name().expect("getting prop name");
        assert_eq!(TEST_PROP_NAME_UUID.to_string(), prop_name);

        let prop_type = enumerator.get_property_type().expect("getting prop type");
        assert_eq!(PropType::Uuid, prop_type);

        let prop_val: Uuid = enumerator.get_property_as_uuid().expect("getting prop as uuid");
        assert_eq!(TEST_PROP_UUID.time_low, prop_val.time_low);
        assert_eq!(TEST_PROP_UUID.time_mid, prop_val.time_mid);
        assert_eq!(TEST_PROP_UUID.time_hi_and_version, prop_val.time_hi_and_version);
        assert_eq!(TEST_PROP_UUID.clock_seq_and_node, prop_val.clock_seq_and_node);

        // Identity.
        enumerator.next().expect("moving enumerator to next prop");

        let prop_name = enumerator.get_property_name().expect("getting prop name");
        assert_eq!(TEST_PROP_NAME_IDENTITY.to_string(), prop_name);

        let prop_type = enumerator.get_property_type().expect("getting prop type");
        assert_eq!(PropType::Identity, prop_type);

        let prop_val: Identity =
            enumerator.get_property_as_identity().expect("getting prop as identity");
        assert_eq!(TEST_PROP_IDENTITY.login, prop_val.login);
        // This should have the same test UUID; can reuse parsed expected uuid fields.
        assert_eq!(TEST_PROP_IDENTITY.uuid.time_low, prop_val.uuid.time_low);
        assert_eq!(TEST_PROP_IDENTITY.uuid.time_mid, prop_val.uuid.time_mid);
        assert_eq!(TEST_PROP_IDENTITY.uuid.time_hi_and_version, prop_val.uuid.time_hi_and_version);
        assert_eq!(TEST_PROP_IDENTITY.uuid.clock_seq_and_node, prop_val.uuid.clock_seq_and_node);

        // Test error upon going out of bounds and attempting to query next property.
        enumerator.next().expect("moving enumerator to next prop");

        let res = enumerator.get_property_name();
        match res.err() {
            Some(PropertyError::ItemNotFound { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }

    #[test]
    pub fn test_enumerator_restart() {
        let mut enumerator = PropEnumerator::new();
        enumerator.start(create_test_prop_set());

        let prop_name = enumerator.get_property_name().expect("getting prop name");
        assert_eq!(TEST_PROP_NAME_STRING.to_string(), prop_name);

        enumerator.next().expect("moving enumerator to next prop");

        let prop_name = enumerator.get_property_name().expect("getting prop name");
        assert_eq!(TEST_PROP_NAME_BOOL.to_string(), prop_name);

        enumerator.restart();

        let prop_name = enumerator.get_property_name().expect("getting prop name");
        assert_eq!(TEST_PROP_NAME_STRING.to_string(), prop_name);
    }

    #[test]
    pub fn test_enumerator_wrong_prop_type_error() {
        let mut enumerator = PropEnumerator::new();
        enumerator.start(create_test_prop_set());

        // First value is string type and not interpretable as bool, should error.
        let res = enumerator.get_property_as_bool();
        match res.err() {
            Some(PropertyError::BadFormat { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }

        enumerator.next().expect("moving enumerator to next prop");

        // Second value is bool, not interpretable as identity, should error.
        let res = enumerator.get_property_as_identity();
        match res.err() {
            Some(PropertyError::BadFormat { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }

        // Getting the same bool value as bool should still work.
        let res = enumerator.get_property_as_bool();
        assert!(res.is_ok());
    }

    #[test]
    pub fn test_enumerator_not_started_error() {
        // This enumerator functionally starts in a usable initial state, with internal index = 0.
        // The spec says callers should call start() first though, so we error if it isn't called.
        let enumerator = PropEnumerator::new();

        let res = enumerator.get_property_name();

        // Return code should map to item not found error per spec.
        match res.err() {
            Some(PropertyError::ItemNotFound { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }

    // *** PropSet Getter Tests ***
    #[test]
    pub fn test_propset_get_not_found() {
        let prop_set = create_test_prop_set();

        let res = prop_set.get_boolean_property("name.that.isnt.there".to_string());

        match res.err() {
            Some(PropertyError::ItemNotFound { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }

    #[test]
    pub fn test_propset_get_string_success() {
        let prop_set = create_test_prop_set();

        let test_str_val = prop_set
            .get_string_property(TEST_PROP_NAME_STRING.to_string())
            .expect("getting str prop val");
        assert_eq!(TEST_PROP_VAL_STRING.to_string(), test_str_val);

        // Spec indicates that any value can be represented as string, even if it doesn't match the type.
        let test_bool_val_as_str = prop_set
            .get_string_property(TEST_PROP_NAME_BOOL.to_string())
            .expect("getting bool prop val as string");
        assert_eq!(TEST_PROP_VAL_BOOL.to_string(), test_bool_val_as_str);
    }

    #[test]
    pub fn test_propset_get_bool_success() {
        let prop_set = create_test_prop_set();

        let val = prop_set
            .get_boolean_property(TEST_PROP_NAME_BOOL.to_string())
            .expect("getting bool prop val");
        assert_eq!(true, val);
    }

    #[test]
    pub fn test_propset_get_bool_wrong_type() {
        let prop_set = create_test_prop_set();

        let res = prop_set.get_boolean_property(TEST_PROP_NAME_UUID.to_string());
        match res.err() {
            Some(PropertyError::BadFormat { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }

    #[test]
    pub fn test_propset_get_u32_success() {
        let prop_set = create_test_prop_set();

        let val = prop_set
            .get_uint32_property(TEST_PROP_NAME_U32.to_string())
            .expect("getting u32 prop val");
        assert_eq!(57, val);
    }

    #[test]
    pub fn test_propset_get_u32_wrong_type() {
        let prop_set = create_test_prop_set();

        let res = prop_set.get_uint32_property(TEST_PROP_NAME_BOOL.to_string());
        match res.err() {
            Some(PropertyError::BadFormat { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }

    #[test]
    pub fn test_propset_get_u64_success() {
        let prop_set = create_test_prop_set();

        let val = prop_set
            .get_uint64_property(TEST_PROP_NAME_U64.to_string())
            .expect("getting u64 prop val");
        assert_eq!(4294967296, val);
    }

    #[test]
    pub fn test_propset_get_u64_wrong_type() {
        let prop_set = create_test_prop_set();

        let res = prop_set.get_uint64_property(TEST_PROP_NAME_BOOL.to_string());
        match res.err() {
            Some(PropertyError::BadFormat { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }

    #[test]
    pub fn test_propset_get_binary_block_success() {
        let prop_set = create_test_prop_set();

        let val = prop_set
            .get_binary_block_property(TEST_PROP_NAME_BINARY_BLOCK.to_string())
            .expect("getting binary block prop val");

        let expected_bytes = STANDARD
            .decode(TEST_PROP_VAL_BINARY_BLOCK)
            .expect("decoding expected binary block bytes");
        assert_eq!(expected_bytes, val);
    }

    #[test]
    pub fn test_propset_get_binary_block_wrong_type() {
        let prop_set = create_test_prop_set();

        // Technically most of the test values (bool, u32, u64, string) are valid base64 strings.
        // Use the serialized identity string to trigger parse failure since it has invalid chars.
        let res = prop_set.get_binary_block_property(TEST_PROP_NAME_IDENTITY.to_string());
        match res.err() {
            Some(PropertyError::BadFormat { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }

    #[test]
    pub fn test_propset_get_uuid_success() {
        let prop_set = create_test_prop_set();

        let val = prop_set
            .get_uuid_property(TEST_PROP_NAME_UUID.to_string())
            .expect("getting uuid prop val");

        assert_eq!(TEST_PROP_UUID.time_low, val.time_low);
        assert_eq!(TEST_PROP_UUID.time_mid, val.time_mid);
        assert_eq!(TEST_PROP_UUID.time_hi_and_version, val.time_hi_and_version);
        assert_eq!(TEST_PROP_UUID.clock_seq_and_node, val.clock_seq_and_node);
    }

    #[test]
    pub fn test_propset_get_uuid_wrong_type() {
        let prop_set = create_test_prop_set();

        let res = prop_set.get_uuid_property(TEST_PROP_NAME_BOOL.to_string());
        match res.err() {
            Some(PropertyError::BadFormat { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }

    #[test]
    pub fn test_propset_get_identity_success() {
        let prop_set = create_test_prop_set();

        let val: Identity = prop_set
            .get_identity_property(TEST_PROP_NAME_IDENTITY.to_string())
            .expect("getting identity prop val");

        assert_eq!(TEST_PROP_IDENTITY.login, val.login);
        assert_eq!(TEST_PROP_IDENTITY.uuid.time_low, val.uuid.time_low);
        assert_eq!(TEST_PROP_IDENTITY.uuid.time_mid, val.uuid.time_mid);
        assert_eq!(TEST_PROP_IDENTITY.uuid.time_hi_and_version, val.uuid.time_hi_and_version);
        assert_eq!(TEST_PROP_IDENTITY.uuid.clock_seq_and_node, val.uuid.clock_seq_and_node);
    }

    #[test]
    pub fn test_propset_get_identity_wrong_type() {
        let prop_set = create_test_prop_set();

        let res = prop_set.get_identity_property(TEST_PROP_NAME_BOOL.to_string());
        match res.err() {
            Some(PropertyError::BadFormat { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }

    // *** Parsing Function Tests ***
    #[test]
    pub fn test_parse_bool_success() {
        let val_true = "true".to_string();
        let val_false = "false".to_string();

        let res_true = parse_bool(val_true).expect("parsing true");
        let res_false = parse_bool(val_false).expect("parsing false");

        assert!(res_true);
        assert!(!res_false);
    }

    #[test]
    pub fn test_parse_bool_empty_string() {
        let val = "".to_string();

        let res = parse_bool(val);

        match res.err() {
            Some(PropertyError::BadFormat { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }

    #[test]
    pub fn test_parse_bool_bad_format() {
        let val = "asdf".to_string();

        let res = parse_bool(val);

        match res.err() {
            Some(PropertyError::BadFormat { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }

    #[test]
    pub fn test_parse_bool_caps_not_accepted() {
        let val = "TRUE".to_string();

        let res = parse_bool(val);

        match res.err() {
            Some(PropertyError::BadFormat { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }

    #[test]
    pub fn test_parse_u32_success() {
        let val = "15".to_string();

        let res = parse_uint32(val).expect("parsing 15");

        assert_eq!(res, 15);
    }

    #[test]
    pub fn test_parse_u32_empty_string() {
        let val = "".to_string();

        let res = parse_uint32(val);

        match res.err() {
            Some(PropertyError::BadFormat { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }

    #[test]
    pub fn test_parse_u32_negative_value() {
        let val = "-15".to_string();

        let res = parse_uint32(val);

        match res.err() {
            Some(PropertyError::BadFormat { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }

    #[test]
    pub fn test_parse_u32_too_large() {
        // u32::MAX = 4_294_967_295u32
        let val = "4294967296".to_string();

        let res = parse_uint32(val);

        match res.err() {
            Some(PropertyError::BadFormat { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }

    #[test]
    pub fn test_parse_u32_bad_format() {
        let val = "text".to_string();

        let res = parse_uint32(val);

        match res.err() {
            Some(PropertyError::BadFormat { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }

    #[test]
    pub fn test_parse_u64_success() {
        let val = "4294967296".to_string();

        let res = parse_uint64(val).expect("parsing 4294967296");

        assert_eq!(res, 4294967296);
    }

    #[test]
    pub fn test_parse_u64_empty_string() {
        let val = "".to_string();

        let res = parse_uint64(val);

        match res.err() {
            Some(PropertyError::BadFormat { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }

    #[test]
    pub fn test_parse_u64_negative_value() {
        let val = "-15".to_string();

        let res = parse_uint64(val);

        match res.err() {
            Some(PropertyError::BadFormat { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }

    #[test]
    pub fn test_parse_u64_too_large() {
        // u64::MAX = 18_446_744_073_709_551_615u64
        let val = "18446744073709551616".to_string();

        let res = parse_uint64(val);

        match res.err() {
            Some(PropertyError::BadFormat { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }

    #[test]
    pub fn test_parse_u64_bad_format() {
        let val = "text".to_string();

        let res = parse_uint64(val);

        match res.err() {
            Some(PropertyError::BadFormat { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }

    #[test]
    pub fn test_parse_binary_block_success() {
        let bytes: [u8; 6] = [1, 2, 3, 4, 5, 6];
        let encoded = STANDARD.encode(bytes);

        let res = parse_binary_block(encoded).expect("parsing binary block");

        assert_eq!(bytes.to_vec(), res);
    }

    #[test]
    pub fn test_parse_binary_empty_string() {
        let res = parse_binary_block("".to_string());

        assert!(res.is_ok());
    }

    #[test]
    pub fn test_parse_binary_block_invalid_base64() {
        // Include characters outside of standard base64 set.
        let bad_val = "asdf&^%@".to_string();

        let res = parse_binary_block(bad_val);

        match res.err() {
            Some(PropertyError::BadFormat { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }

    #[test]
    pub fn test_parse_uuid_success() {
        let valid_uuid = "5b9e0e40-2636-11e1-ad9e-0002a5d5c51b".to_string();

        let res = parse_uuid(valid_uuid);

        assert!(res.is_ok());
    }

    #[test]
    pub fn test_parse_uuid_empty_string() {
        let res = parse_uuid("".to_string());

        match res.err() {
            Some(PropertyError::BadFormat { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }

    #[test]
    pub fn test_parse_uuid_invalid_uuid() {
        let invalid_uuid = "asdf".to_string();

        let res = parse_uuid(invalid_uuid);

        match res.err() {
            Some(PropertyError::BadFormat { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }

    #[test]
    pub fn test_parse_identity_success() {
        let res = parse_identity(TEST_PROP_VAL_IDENTITY.to_string());
        assert!(res.is_ok());
    }

    #[test]
    pub fn test_parse_identity_empty_uuid() {
        // TODO(https://fxbug.dev/369916290): Spell as 0xf0000000 when hex encodings are supported.
        let res = parse_identity("4026531840".to_string());
        assert!(res.is_ok());
        let id = res.unwrap();
        assert_eq!(Uuid::default(), id.uuid);
    }

    #[test]
    pub fn test_parse_identity_invalid_login_type() {
        // 0xefffffff is an implementation-reserved value.
        //
        // TODO(https://fxbug.dev/369916290): Spell as 0xefffffff when hex encodings are supported.
        let res = parse_identity("4026531839:5b9e0e40-2636-11e1-ad9e-0002a5d5c51b".to_string());
        match res.err() {
            Some(PropertyError::BadFormat { .. }) => (),
            _ => assert!(false, "Unexpected error type"),
        }
    }
}