rs-matter 0.2.0

Native Rust implementation of the Matter (Smart-Home) ecosystem
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
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
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
/*
 *
 *    Copyright (c) 2022-2026 Project CHIP Authors
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

//! This module contains the implementation of the `rs-matter` Access Control List (ACL)

use core::fmt::Display;
use core::num::NonZeroU8;
use core::ops::RangeInclusive;

use cfg_if::cfg_if;

use num_derive::FromPrimitive;

use crate::dm::clusters::acl::{
    AccessControlAuxiliaryTypeEnum, AccessControlEntryAuthModeEnum,
    AccessControlEntryPrivilegeEnum, AccessControlEntryStruct, AccessControlEntryStructBuilder,
};
use crate::dm::{Access, ClusterId, DeviceType, EndptId, NodeId, Privilege};
use crate::error::{Error, ErrorCode};
use crate::im::GenericPath;
use crate::tlv::{FromTLV, Nullable, TLVBuilderParent, TLVElement, TLVTag, TLVWrite, ToTLV, TLV};
use crate::transport::session::{Session, SessionMode, MAX_CAT_IDS_PER_NOC};
use crate::utils::init::{init, Init, IntoFallibleInit};
use crate::utils::storage::Vec;
use crate::Matter;

cfg_if! {
    if #[cfg(feature = "max-subjects-per-acl-32")] {
        /// Max subjects per ACL entry
        pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 32;
    } else if #[cfg(feature = "max-subjects-per-acl-16")] {
        /// Max subjects per ACL entry
        pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 16;
    } else if #[cfg(feature = "max-subjects-per-acl-8")] {
        /// Max subjects per ACL entry
        pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 8;
    } else if #[cfg(feature = "max-subjects-per-acl-7")] {
        /// Max subjects per ACL entry
        pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 7;
    } else if #[cfg(feature = "max-subjects-per-acl-6")] {
        /// Max subjects per ACL entry
        pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 6;
    } else if #[cfg(feature = "max-subjects-per-acl-5")] {
        /// Max subjects per ACL entry
        pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 5;
    } else if #[cfg(feature = "max-subjects-per-acl-4")] {
        /// Max subjects per ACL entry
        pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 4;
    } else if #[cfg(feature = "max-subjects-per-acl-3")] {
        /// Max subjects per ACL entry
        pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 3;
    } else if #[cfg(feature = "max-subjects-per-acl-2")] {
        /// Max subjects per ACL entry
        pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 2;
    } else if #[cfg(feature = "max-subjects-per-acl-1")] {
        /// Max subjects per ACL entry
        pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 1;
    } else {
        /// Max subjects per ACL entry
        pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 4;
    }
}

cfg_if! {
    if #[cfg(feature = "max-targets-per-acl-32")] {
        /// Max targets per ACL entry
        pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 32;
    } else if #[cfg(feature = "max-targets-per-acl-16")] {
        /// Max targets per ACL entry
        pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 16;
    } else if #[cfg(feature = "max-targets-per-acl-8")] {
        /// Max targets per ACL entry
        pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 8;
    } else if #[cfg(feature = "max-targets-per-acl-7")] {
        /// Max targets per ACL entry
        pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 7;
    } else if #[cfg(feature = "max-targets-per-acl-6")] {
        /// Max targets per ACL entry
        pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 6;
    } else if #[cfg(feature = "max-targets-per-acl-5")] {
        /// Max targets per ACL entry
        pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 5;
    } else if #[cfg(feature = "max-targets-per-acl-4")] {
        /// Max targets per ACL entry
        pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 4;
    } else if #[cfg(feature = "max-targets-per-acl-3")] {
        /// Max targets per ACL entry
        pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 3;
    } else if #[cfg(feature = "max-targets-per-acl-2")] {
        /// Max targets per ACL entry
        pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 2;
    } else if #[cfg(feature = "max-targets-per-acl-1")] {
        /// Max targets per ACL entry
        pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 1;
    } else {
        /// Max targets per ACL entry
        pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 3;
    }
}

cfg_if! {
    if #[cfg(feature = "max-acls-per-fabric-32")] {
        /// Max ACL entries per fabric
        pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 32;
    } else if #[cfg(feature = "max-acls-per-fabric-16")] {
        /// Max ACL entries per fabric
        pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 16;
    } else if #[cfg(feature = "max-acls-per-fabric-8")] {
        /// Max ACL entries per fabric
        pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 8;
    } else if #[cfg(feature = "max-acls-per-fabric-7")] {
        /// Max ACL entries per fabric
        pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 7;
    } else if #[cfg(feature = "max-acls-per-fabric-6")] {
        /// Max ACL entries per fabric
        pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 6;
    } else if #[cfg(feature = "max-acls-per-fabric-5")] {
        /// Max ACL entries per fabric
        pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 5;
    } else if #[cfg(feature = "max-acls-per-fabric-4")] {
        /// Max ACL entries per fabric
        pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 4;
    } else if #[cfg(feature = "max-acls-per-fabric-3")] {
        /// Max ACL entries per fabric
        pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 3;
    } else if #[cfg(feature = "max-acls-per-fabric-2")] {
        /// Max ACL entries per fabric
        pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 2;
    } else if #[cfg(feature = "max-acls-per-fabric-1")] {
        /// Max ACL entries per fabric
        pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 1;
    } else {
        /// Max ACL entries per fabric
        pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 4;
    }
}

/// An enum modeling the different authentication modes
// TODO: Check if this and the SessionMode can be combined into some generic data structure
#[derive(FromPrimitive, Copy, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[repr(u8)]
pub enum AuthMode {
    /// PASE authentication
    Pase = AccessControlEntryAuthModeEnum::PASE as _,
    /// CASE authentication
    Case = AccessControlEntryAuthModeEnum::CASE as _,
    /// Group authentication
    Group = AccessControlEntryAuthModeEnum::Group as _,
}

impl FromTLV<'_> for AuthMode {
    fn from_tlv(t: &TLVElement) -> Result<Self, Error>
    where
        Self: Sized,
    {
        Ok(AccessControlEntryAuthModeEnum::from_tlv(t)?.into())
    }
}

impl ToTLV for AuthMode {
    fn to_tlv<W: TLVWrite>(&self, tag: &TLVTag, mut tw: W) -> Result<(), Error> {
        AccessControlEntryAuthModeEnum::from(*self).to_tlv(tag, &mut tw)
    }

    fn tlv_iter(&self, tag: TLVTag) -> impl Iterator<Item = Result<TLV<'_>, Error>> {
        TLV::u8(tag, AccessControlEntryAuthModeEnum::from(*self) as _).into_tlv_iter()
    }
}

impl From<AuthMode> for AccessControlEntryAuthModeEnum {
    fn from(value: AuthMode) -> Self {
        match value {
            AuthMode::Pase => AccessControlEntryAuthModeEnum::PASE,
            AuthMode::Case => AccessControlEntryAuthModeEnum::CASE,
            AuthMode::Group => AccessControlEntryAuthModeEnum::Group,
        }
    }
}

impl From<AccessControlEntryAuthModeEnum> for AuthMode {
    fn from(value: AccessControlEntryAuthModeEnum) -> Self {
        match value {
            AccessControlEntryAuthModeEnum::PASE => AuthMode::Pase,
            AccessControlEntryAuthModeEnum::CASE => AuthMode::Case,
            AccessControlEntryAuthModeEnum::Group => AuthMode::Group,
        }
    }
}

/// An accessor can have as many identities: one node id and up to MAX_CAT_IDS_PER_NOC
const MAX_ACCESSOR_SUBJECTS: usize = 1 + MAX_CAT_IDS_PER_NOC;

/// The CAT Prefix used in Subjects
pub const NOC_CAT_SUBJECT_PREFIX: u64 = 0xFFFF_FFFD_0000_0000;
pub const NOC_CAT_SUBJECT_MASK: u64 = 0xFFFF_FFFF_0000_0000;

const NOC_CAT_ID_MASK: u64 = 0xFFFF_0000;
const NOC_CAT_VERSION_MASK: u64 = 0xFFFF;

/// The Node ID min range
const NODE_ID_RANGE: RangeInclusive<u64> = 1..=0xFFFF_FFEF_FFFF_FFFF;

/// Is this identifier a NOC CAT
pub(crate) fn is_noc_cat(id: u64) -> bool {
    ((id & NOC_CAT_SUBJECT_MASK) == NOC_CAT_SUBJECT_PREFIX)
        && ((id & (NOC_CAT_ID_MASK | NOC_CAT_VERSION_MASK)) > 0)
}

/// Get the 16-bit NOC CAT id from the identifier
fn get_noc_cat_id(id: u64) -> u64 {
    (id & NOC_CAT_ID_MASK) >> 16
}

/// Get the 16-bit NOC CAT version from the identifier
fn get_noc_cat_version(id: u64) -> u64 {
    id & NOC_CAT_VERSION_MASK
}

/// Generate CAT that is embeddedable in the NoC
/// This only generates the 32-bit CAT ID
pub fn gen_noc_cat(id: u16, version: u16) -> u32 {
    ((id as u32) << 16) | version as u32
}

/// Is this identifier a node id
pub(crate) fn is_node(id: u64) -> bool {
    NODE_ID_RANGE.contains(&id)
}

/// The Subjects that identify the Accessor
pub struct AccessorSubjects([u64; MAX_ACCESSOR_SUBJECTS]);

impl AccessorSubjects {
    /// Create a new AccessorSubjects object
    /// The first subject is the node id
    pub fn new(id: u64) -> Self {
        let mut a = Self(Default::default());
        a.0[0] = id;
        a
    }

    /// Add a CAT id to the AccessorSubjects
    pub fn add_catid(&mut self, subject: u32) -> Result<(), Error> {
        for (i, val) in self.0.iter().enumerate() {
            if *val == 0 {
                self.0[i] = NOC_CAT_SUBJECT_PREFIX | (subject as u64);
                return Ok(());
            }
        }
        Err(ErrorCode::ResourceExhausted.into())
    }

    /// Match the acl_subject with any of the current subjects
    /// If a NOC CAT is specified, CAT aware matching is also performed
    pub fn matches(&self, acl_subject: u64) -> bool {
        for v in self.0.iter() {
            if *v == 0 {
                continue;
            }

            if *v == acl_subject {
                return true;
            } else {
                // NOC CAT match
                if is_noc_cat(*v)
                    && is_noc_cat(acl_subject)
                    && (get_noc_cat_id(*v) == get_noc_cat_id(acl_subject))
                    && (get_noc_cat_version(*v) >= get_noc_cat_version(acl_subject))
                {
                    return true;
                }
            }
        }

        false
    }
}

impl Display for AccessorSubjects {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::result::Result<(), core::fmt::Error> {
        write!(f, "[")?;
        for i in self.0 {
            if is_noc_cat(i) {
                write!(f, "CAT({} - {})", get_noc_cat_id(i), get_noc_cat_version(i))?;
            } else if i != 0 {
                write!(f, "{}, ", i)?;
            }
        }
        write!(f, "]")
    }
}

#[cfg(feature = "defmt")]
impl defmt::Format for AccessorSubjects {
    fn format(&self, f: defmt::Formatter) {
        defmt::write!(f, "[");
        for i in self.0 {
            if is_noc_cat(i) {
                defmt::write!(f, "CAT({} - {})", get_noc_cat_id(i), get_noc_cat_version(i));
            } else if i != 0 {
                defmt::write!(f, "{}, ", i);
            }
        }
        defmt::write!(f, "]")
    }
}

/// The Accessor Object
pub struct Accessor<'a> {
    /// The fabric index of the accessor
    pub(crate) fab_idx: u8,
    /// Accessor's subject: could be node-id, NoC CAT, group id
    subjects: AccessorSubjects,
    /// The auth mode of this session. Might be `None` for plain-text sessions
    auth_mode: Option<AuthMode>,
    // Necessary so as to get access to the fabric manager to perform the access check in AccessReq::allow()
    // as well as for a few other ACL related operations.
    matter: &'a Matter<'a>,
}

impl<'a> Accessor<'a> {
    /// Create a new Accessor object for the given session
    pub fn for_session(session: &Session, matter: &'a Matter<'a>) -> Self {
        match session.get_session_mode() {
            SessionMode::Case {
                fab_idx, cat_ids, ..
            } => {
                let mut subject =
                    AccessorSubjects::new(session.get_peer_node_id().unwrap_or_default());
                for i in *cat_ids {
                    if i != 0 {
                        let _ = subject.add_catid(i);
                    }
                }
                Accessor::new(fab_idx.get(), subject, Some(AuthMode::Case), matter)
            }
            SessionMode::Pase { fab_idx } => Accessor::new(
                *fab_idx,
                AccessorSubjects::new(1),
                Some(AuthMode::Pase),
                matter,
            ),
            SessionMode::Group { fab_idx, group_id } => Accessor::new(
                fab_idx.get(),
                AccessorSubjects::new(*group_id as u64),
                Some(AuthMode::Group),
                matter,
            ),
            SessionMode::PlainText => Accessor::new(0, AccessorSubjects::new(1), None, matter),
        }
    }

    /// Create a new Accessor object
    ///
    /// # Arguments
    /// - `fab_idx`: The fabric index of the accessor (0 means no fabric index)
    /// - `subjects`: The subjects of the accessor
    /// - `auth_mode`: The auth mode of the accessor
    /// - `matter`: The Matter instance
    pub const fn new(
        fab_idx: u8,
        subjects: AccessorSubjects,
        auth_mode: Option<AuthMode>,
        matter: &'a Matter<'a>,
    ) -> Self {
        Self {
            fab_idx,
            subjects,
            auth_mode,
            matter,
        }
    }

    pub fn fab_idx(&self) -> Result<NonZeroU8, Error> {
        NonZeroU8::new(self.fab_idx).ok_or(ErrorCode::UnsupportedAccess.into())
    }

    /// Return the subjects of the accessor
    pub const fn subjects(&self) -> &AccessorSubjects {
        &self.subjects
    }

    /// Return the auth mode of the accessor
    pub const fn auth_mode(&self) -> Option<AuthMode> {
        self.auth_mode
    }

    /// Return whether the given endpoint is accessible for this accessor.
    ///
    /// For group sessions, only endpoints that are members of the group are accessible.
    /// For all other session types, all endpoints are accessible.
    pub fn is_endpoint_accessible(&self, endpoint_id: EndptId) -> bool {
        if self.auth_mode != Some(AuthMode::Group) {
            return true;
        }

        let group_id = self.subjects.0[0] as u16;

        let Some(fab_idx) = core::num::NonZeroU8::new(self.fab_idx) else {
            return false;
        };

        self.matter.with_state(|state| {
            let Some(fabric) = state.fabrics.get(fab_idx) else {
                return false;
            };

            fabric
                .groups()
                .get(group_id)
                .is_some_and(|e| e.endpoints.contains(&endpoint_id))
        })
    }

    /// Return the Operational Node ID of the accessor, if any
    pub fn node_id(&self) -> Option<NodeId> {
        let fab_idx = NonZeroU8::new(self.fab_idx)?;

        self.matter
            .with_state(|state| state.fabrics.get(fab_idx).map(|fabric| fabric.node_id()))
    }

    /// Return the peer node ID (admin node ID) for CASE sessions, or None for PASE/other sessions.
    pub fn peer_node_id(&self) -> Option<u64> {
        if matches!(self.auth_mode, Some(AuthMode::Case)) {
            let id = self.subjects.0[0];
            if is_node(id) {
                Some(id)
            } else {
                None
            }
        } else {
            None
        }
    }
}

/// Access Descriptor Object
#[derive(Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct AccessDesc<'a> {
    /// The object to be acted upon
    path: GenericPath,
    /// The target permissions
    target_perms: Option<Access>,
    // The operation being done
    // TODO: Currently this is Access, but we need a way to represent the 'invoke' somehow too
    operation: Access,
    /// The device types of the endpoint hosting `path`. Used by ACL `Target`
    /// entries that filter by `DeviceType` (Matter Core spec).
    /// Empty when the access target's endpoint is unknown / not yet expanded.
    device_types: &'a [DeviceType],
}

/// Access Request Object
pub struct AccessReq<'a> {
    /// The accessor requesting access
    accessor: &'a Accessor<'a>,
    /// The object being accessed
    object: AccessDesc<'a>,
}

impl<'a> AccessReq<'a> {
    /// Create an access request object.
    ///
    /// An access request specifies the _accessor_ attempting to access _path_
    /// with _operation_. `device_types` lists the device types declared by
    /// the endpoint that hosts `path`; pass an empty slice when this is not
    /// applicable (e.g. for unit tests that don't exercise `DeviceType` ACL
    /// targets).
    pub const fn new(accessor: &'a Accessor, path: GenericPath, operation: Access) -> Self {
        Self::new_with_device_types(accessor, path, operation, &[])
    }

    /// Create an access request object that also carries the device types of
    /// the access target's endpoint, so that ACL entries with a `Target` of
    /// kind `DeviceType` can be evaluated.
    pub const fn new_with_device_types(
        accessor: &'a Accessor,
        path: GenericPath,
        operation: Access,
        device_types: &'a [DeviceType],
    ) -> Self {
        AccessReq {
            accessor,
            object: AccessDesc {
                path,
                target_perms: None,
                operation,
                device_types,
            },
        }
    }

    /// Return the accessor of the request
    pub fn accessor(&self) -> &Accessor<'_> {
        self.accessor
    }

    /// Return the operation of the request
    pub fn operation(&self) -> Access {
        self.object.operation
    }

    /// Add target's permissions to the request
    ///
    /// The permissions that are associated with the target (identified by the
    /// path in the AccessReq) are added to the request
    pub fn set_target_perms(&mut self, perms: Access) {
        self.object.target_perms = Some(perms);
    }

    /// Check if access is allowed
    ///
    /// This checks all the ACL list to identify if any of the ACLs provides the
    /// _accessor_ the necessary privileges to access the target as per its
    /// permissions
    pub fn allow(&self) -> bool {
        self.accessor
            .matter
            .with_state(|state| state.fabrics.allow(self))
    }
}

/// The target object
#[derive(FromTLV, ToTLV, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct Target {
    pub cluster: Option<ClusterId>,
    pub endpoint: Option<EndptId>,
    pub device_type: Option<u32>,
}

impl Target {
    /// Create a new target object
    pub const fn new(
        endpoint: Option<EndptId>,
        cluster: Option<ClusterId>,
        device_type: Option<u32>,
    ) -> Self {
        Self {
            cluster,
            endpoint,
            device_type,
        }
    }
}

/// The ACL entry object
#[derive(ToTLV, FromTLV, Clone, Debug, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[tlvargs(start = 1)]
pub struct AclEntry {
    /// The privilege of the entry
    privilege: Privilege,
    /// The auth mode of the entry
    auth_mode: AuthMode,
    /// The subjects of the entry
    subjects: Nullable<Vec<u64, MAX_SUBJECTS_PER_ACL_ENTRY>>,
    /// The targets of the entry
    targets: Nullable<Vec<Target, MAX_TARGETS_PER_ACL_ENTRY>>,
    // TODO: Figure out what this is, document and use
    auxiliary_type: Option<AccessControlAuxiliaryTypeEnum>,
    // Note that this field will always be `Some(NN)` when the entry is persisted in storage,
    // however, it will be `None` when the entry is coming from the other peer.
    #[tagval(crate::im::encoding::FABRIC_INDEX_TAG)]
    pub fab_idx: Option<NonZeroU8>,
}

impl AclEntry {
    /// Create a new ACL entry object
    pub const fn new(
        fab_idx: Option<NonZeroU8>,
        privilege: Privilege,
        auth_mode: AuthMode,
    ) -> Self {
        Self {
            fab_idx,
            privilege,
            auth_mode,
            subjects: Nullable::none(),
            targets: Nullable::none(),
            auxiliary_type: None,
        }
    }

    /// Return an initializer for an ACL entry object
    /// using the given fabric index, privilege and auth mode as input
    pub fn init(
        fab_idx: Option<NonZeroU8>,
        privilege: Privilege,
        auth_mode: AuthMode,
    ) -> impl Init<Self> {
        init!(Self {
            fab_idx,
            privilege,
            auth_mode,
            subjects <- Nullable::init_none(),
            targets <- Nullable::init_none(),
            auxiliary_type: None,
        })
    }

    /// Return an initializer for an ACL entry object
    /// using the given fabric index and TLV entry struct as input
    pub fn init_with<'a>(
        fab_idx: NonZeroU8,
        entry: &'a AccessControlEntryStruct<'a>,
    ) -> impl Init<Self, Error> + 'a {
        Self::init(Some(fab_idx), Privilege::empty(), AuthMode::Pase)
            .into_fallible()
            .chain(|e| {
                let auth_mode = entry.auth_mode().map_err(|_| ErrorCode::ConstraintError)?.ok_or(ErrorCode::ConstraintError)?;
                let privilege = entry.privilege().map_err(|_| ErrorCode::ConstraintError)?.ok_or(ErrorCode::ConstraintError)?;
                let subjects = entry.subjects().map_err(|_| ErrorCode::ConstraintError)?.ok_or(ErrorCode::ConstraintError)?;
                let targets = entry.targets().map_err(|_| ErrorCode::ConstraintError)?.ok_or(ErrorCode::ConstraintError)?;
                let auxiliary_type = entry.auxiliary_type().map_err(|_| ErrorCode::ConstraintError)?;

                if
                    // As per spec, PASE auth mode is reserved for future use
                    matches!(auth_mode, AccessControlEntryAuthModeEnum::PASE)
                    // As per spec, Group auth mode cannot have Admin privilege
                    || matches!(auth_mode, AccessControlEntryAuthModeEnum::Group) && matches!(privilege, AccessControlEntryPrivilegeEnum::Administer)
                {
                    Err(ErrorCode::ConstraintError)?;
                }

                e.privilege = privilege.into();
                e.auth_mode = auth_mode.into();
                e.auxiliary_type = auxiliary_type;

                // Start with null subjects and targets
                // so that we can keep those to null if we receive empty subjects' array or empty targets' array
                // This is what the YAML tests expect
                e.subjects.clear();
                e.targets.clear();

                if let Some(subjects) = subjects.into_option() {
                    for subject in subjects {
                        if e.subjects.is_none() {
                            // Initialize our subjects to non-null lazily, only if we have at least one incoming subject
                            // This ensures that if the incoming subjects is empty, we keep our subjects as null
                            // which is what the YAML tests expect, even if we internally treat null and empty subjects the same way
                            e.subjects.reinit(Nullable::init_some(Vec::init()));
                        }

                        let esubjects = unwrap!(e.subjects.as_opt_mut());

                        let subject = subject?;

                        if matches!(auth_mode, AccessControlEntryAuthModeEnum::CASE) && !is_node(subject) && !is_noc_cat(subject) {
                            // As per spec, CASE auth mode only allows node ids and NOC CATs as subjects
                            Err(ErrorCode::ConstraintError)?;
                        }

                        if matches!(auth_mode, AccessControlEntryAuthModeEnum::Group) {
                            // Per Matter Core spec: for Group auth mode, the
                            // subject SHALL be a valid 16-bit Group ID. Group ID 0 is reserved
                            // and MUST NOT be used; values larger than `u16::MAX` are also invalid.
                            if subject == 0 || subject > u16::MAX as u64 {
                                Err(ErrorCode::ConstraintError)?;
                            }
                        }

                        // As per spec, on too many subjects we should return a FAILURE status code
                        // `ErrorCode::BufferTooSmall` translates to a generic FAILURE status code
                        esubjects
                            .push(subject)
                            .map_err(|_| ErrorCode::BufferTooSmall)?;
                    }
                }

                if let Some(targets) = targets.into_option() {
                    for target in targets {
                        if e.targets.is_none() {
                            // Initialize our targets to non-null lazily, only if we have at least one incoming target
                            // This ensures that if the incoming targets is empty, we keep our targets as null
                            // which is what the YAML tests expect, even if we internally treat null and empty targets the same way
                            e.targets.reinit(Nullable::init_some(Vec::init()));
                        }

                        let etargets = unwrap!(e.targets.as_opt_mut());

                        let target = target?;

                        // Matter Core spec (AccessControlTargetStruct):
                        // - At least one of cluster, endpoint or deviceType SHALL be present.
                        // - If endpoint is present, deviceType SHALL NOT be present (and vice
                        //   versa). cluster may be combined with either endpoint or deviceType.
                        let has_endpoint = target.endpoint()?.is_some();
                        let has_cluster = target.cluster()?.is_some();
                        let has_device_type = target.device_type()?.is_some();

                        if (!has_endpoint && !has_cluster && !has_device_type)
                            || (has_endpoint && has_device_type)
                        {
                            Err(ErrorCode::ConstraintError)?;
                        }

                        // As per spec, on too many targets we should return a FAILURE status code
                        // `ErrorCode::BufferTooSmall` translates to a generic FAILURE status code
                        etargets
                            .push(Target::new(
                                target.endpoint()?.into_option(),
                                target.cluster()?.into_option(),
                                target.device_type()?.into_option(),
                            ))
                            .map_err(|_| ErrorCode::BufferTooSmall)?;
                    }
                }

                Ok(())
            })
    }

    /// Return the data of the ACL entry object
    /// into the provided TLV builder
    pub fn read_into<P: TLVBuilderParent>(
        &self,
        accessing_fab_idx: u8,
        fab_idx: Option<u8>,
        builder: AccessControlEntryStructBuilder<P>,
    ) -> Result<P, Error> {
        let same_fab_idx = Some(accessing_fab_idx) == fab_idx;

        builder
            .privilege(same_fab_idx.then(|| self.privilege.into()))?
            .auth_mode(same_fab_idx.then(|| self.auth_mode.into()))?
            .subjects()?
            .with_some_if(same_fab_idx, |builder| {
                builder.with_non_null(self.subjects(), |subjects, mut builder| {
                    for subject in *subjects {
                        builder = builder.push(subject)?;
                    }

                    builder.end()
                })
            })?
            .targets()?
            .with_some_if(same_fab_idx, |builder| {
                builder.with_non_null(self.targets(), |targets, mut builder| {
                    for target in *targets {
                        builder = builder
                            .push()?
                            .cluster(Nullable::new(target.cluster))?
                            .endpoint(Nullable::new(target.endpoint))?
                            .device_type(Nullable::new(target.device_type))?
                            .end()?;
                    }

                    builder.end()
                })
            })?
            .auxiliary_type(self.auxiliary_type())?
            .fabric_index(fab_idx)?
            .end()
    }

    /// Normalize the ACL entry by converting non-null but empty
    /// subjects/targets to null, as the spec and YAML tests expect
    pub fn normalize(&mut self) {
        if self
            .subjects
            .as_opt_ref()
            .map(|subjects| subjects.is_empty())
            .unwrap_or(false)
        {
            self.subjects.clear();
        }

        if self
            .targets
            .as_opt_ref()
            .map(|targets| targets.is_empty())
            .unwrap_or(false)
        {
            self.targets.clear();
        }
    }

    /// Return the auth mode of the ACL entry
    pub fn auth_mode(&self) -> AuthMode {
        self.auth_mode
    }

    /// Return the subjects of the ACL entry
    pub fn subjects(&self) -> Nullable<&[u64]> {
        Nullable::new(self.subjects.as_opt_ref().map(|v| v.as_slice()))
    }

    /// Return the targets of the ACL entry
    pub fn targets(&self) -> Nullable<&[Target]> {
        Nullable::new(self.targets.as_opt_ref().map(|v| v.as_slice()))
    }

    pub fn auxiliary_type(&self) -> Option<AccessControlAuxiliaryTypeEnum> {
        self.auxiliary_type
    }

    /// Check if the ACL entry allows access to the given accessor and object
    pub fn allow(&self, req: &AccessReq) -> bool {
        self.match_accessor(req.accessor) && self.match_access_desc(&req.object)
    }

    /// Add a subject to the ACL entry
    pub fn add_subject(&mut self, subject: u64) -> Result<(), Error> {
        if self.subjects.is_none() {
            self.subjects.reinit(Nullable::init_some(Vec::init()));
        }

        unwrap!(self.subjects.as_opt_mut())
            .push(subject)
            .map_err(|_| ErrorCode::ResourceExhausted.into())
    }

    /// Add a CAT id to the ACL entry
    pub fn add_subject_catid(&mut self, cat_id: u32) -> Result<(), Error> {
        self.add_subject(NOC_CAT_SUBJECT_PREFIX | cat_id as u64)
    }

    /// Add a target to the ACL entry
    pub fn add_target(&mut self, target: Target) -> Result<(), Error> {
        if self.targets.is_none() {
            self.targets.reinit(Nullable::init_some(Vec::init()));
        }

        unwrap!(self.targets.as_opt_mut())
            .push(target)
            .map_err(|_| ErrorCode::ResourceExhausted.into())
    }

    fn match_accessor(&self, accessor: &Accessor) -> bool {
        if Some(self.auth_mode) != accessor.auth_mode {
            return false;
        }

        let allow = self.subjects().as_opt_ref().is_none_or(|subjects| {
            // Subjects array null or empty implies allow for all subjects
            // Otherwise, check if the accessor's subject matches any of the ACL entry's subjects
            subjects.is_empty() || subjects.iter().any(|s| accessor.subjects.matches(*s))
        });

        // true if both are true
        allow
            && self
                .fab_idx
                .map(|fab_idx| fab_idx.get() == accessor.fab_idx)
                .unwrap_or(false)
    }

    fn match_access_desc(&self, object: &AccessDesc) -> bool {
        let allow = self.targets.as_opt_ref().is_none_or(|targets| {
            // Targets array null or empty implies allow for all targets
            // Otherwise, check if the target matches any of the ACL entry's targets
            targets.is_empty()
                || targets.iter().any(|t| {
                    let endpoint_match = t.endpoint.is_none() || t.endpoint == object.path.endpoint;
                    let cluster_match = t.cluster.is_none() || t.cluster == object.path.cluster;
                    // When `Target.device_type` is set, the access target's endpoint
                    // must declare a matching device type in its `DeviceTypeList`
                    // (Matter Core spec).
                    let device_type_match = match t.device_type {
                        Some(dt) => object
                            .device_types
                            .iter()
                            .any(|endpoint_dt| endpoint_dt.dtype as u32 == dt),
                        None => true,
                    };
                    endpoint_match && cluster_match && device_type_match
                })
        });

        if allow {
            // Check that the object's access allows this operation with this privilege
            if let Some(access) = object.target_perms {
                access.is_ok(object.operation, self.privilege)
            } else {
                false
            }
        } else {
            false
        }
    }
}

#[cfg(test)]
#[allow(clippy::bool_assert_comparison)]
pub(crate) mod tests {
    use core::num::NonZeroU8;

    use crate::acl::{gen_noc_cat, AccessorSubjects};
    use crate::dm::{Access, Privilege};
    use crate::error::Error;
    use crate::im::GenericPath;
    use crate::test::test_matter;
    use crate::Matter;

    use super::{AccessReq, Accessor, AclEntry, AuthMode, Target};

    pub(crate) const FAB_1: NonZeroU8 = match NonZeroU8::new(1) {
        Some(f) => f,
        None => ::core::unreachable!(),
    };

    pub(crate) const FAB_2: NonZeroU8 = match NonZeroU8::new(2) {
        Some(f) => f,
        None => ::core::unreachable!(),
    };

    fn add_fabric(matter: &Matter<'_>) {
        matter.with_state(|state| {
            // Add fabric with ID 1
            state.fabrics.add_with_post_init(|_| Ok(())).unwrap();
        })
    }

    fn add_acl(matter: &Matter<'_>, fab_idx: NonZeroU8, entry: AclEntry) -> Result<usize, Error> {
        matter.with_state(|state| state.fabrics.fabric_mut(fab_idx)?.acl_add(entry))
    }

    fn remove_all_acl(matter: &Matter<'_>, fab_idx: NonZeroU8) {
        matter.with_state(|state| state.fabrics.fabric_mut(fab_idx).unwrap().acl_remove_all())
    }

    #[test]
    fn test_basic_empty_subject_target() {
        let matter = test_matter();
        let accessor = Accessor::new(
            0,
            AccessorSubjects::new(112233),
            Some(AuthMode::Pase),
            &matter,
        );
        let path = GenericPath::new(Some(1), Some(1234), None);
        let mut req_pase = AccessReq::new(&accessor, path, Access::READ);
        req_pase.set_target_perms(Access::RWVA);

        // Always allow for PASE sessions
        assert!(req_pase.allow());

        let accessor = Accessor::new(
            2,
            AccessorSubjects::new(112233),
            Some(AuthMode::Case),
            &matter,
        );
        let path = GenericPath::new(Some(1), Some(1234), None);
        let mut req = AccessReq::new(&accessor, path, Access::READ);
        req.set_target_perms(Access::RWVA);

        // Default deny for CASE
        assert_eq!(req.allow(), false);

        // Add fabric with ID 1
        add_fabric(&matter);

        // Deny adding invalid auth mode (PASE is reserved for future)
        let new = AclEntry::new(None, Privilege::VIEW, AuthMode::Pase);
        assert!(add_acl(&matter, FAB_1, new).is_err());

        // Deny for fab idx mismatch
        let new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
        assert_eq!(add_acl(&matter, FAB_1, new).unwrap(), 0);
        assert_eq!(req.allow(), false);

        // Always allow for PASE sessions
        assert!(req_pase.allow());

        // Add fabric with ID 2
        add_fabric(&matter);

        // Allow
        let new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
        assert_eq!(add_acl(&matter, FAB_2, new).unwrap(), 0);
        assert_eq!(req.allow(), true);
    }

    #[test]
    fn test_subject() {
        let matter = test_matter();

        // Add fabric with ID 1
        add_fabric(&matter);

        let accessor = Accessor::new(
            1,
            AccessorSubjects::new(112233),
            Some(AuthMode::Case),
            &matter,
        );
        let path = GenericPath::new(Some(1), Some(1234), None);
        let mut req = AccessReq::new(&accessor, path, Access::READ);
        req.set_target_perms(Access::RWVA);

        // Deny for subject mismatch
        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
        new.add_subject(112232).unwrap();
        assert_eq!(add_acl(&matter, FAB_1, new).unwrap(), 0);
        assert_eq!(req.allow(), false);

        // Allow for subject match - target is wildcard
        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
        new.add_subject(112233).unwrap();
        assert_eq!(add_acl(&matter, FAB_1, new).unwrap(), 1);
        assert_eq!(req.allow(), true);
    }

    #[test]
    fn test_cat() {
        let matter = test_matter();

        // Add fabric with ID 1
        add_fabric(&matter);

        let allow_cat = 0xABCD;
        let disallow_cat = 0xCAFE;
        let v2 = 2;
        let v3 = 3;
        // Accessor has nodeif and CAT 0xABCD_0002
        let mut subjects = AccessorSubjects::new(112233);
        subjects.add_catid(gen_noc_cat(allow_cat, v2)).unwrap();

        let accessor = Accessor::new(1, subjects, Some(AuthMode::Case), &matter);
        let path = GenericPath::new(Some(1), Some(1234), None);
        let mut req = AccessReq::new(&accessor, path, Access::READ);
        req.set_target_perms(Access::RWVA);

        // Deny for CAT id mismatch
        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
        new.add_subject_catid(gen_noc_cat(disallow_cat, v2))
            .unwrap();
        add_acl(&matter, FAB_1, new).unwrap();
        assert_eq!(req.allow(), false);

        // Deny of CAT version mismatch
        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
        new.add_subject_catid(gen_noc_cat(allow_cat, v3)).unwrap();
        add_acl(&matter, FAB_1, new).unwrap();
        assert_eq!(req.allow(), false);

        // Allow for CAT match
        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
        new.add_subject_catid(gen_noc_cat(allow_cat, v2)).unwrap();
        add_acl(&matter, FAB_1, new).unwrap();
        assert_eq!(req.allow(), true);
    }

    #[test]
    fn test_cat_version() {
        let matter = test_matter();

        // Add fabric with ID 1
        add_fabric(&matter);

        let allow_cat = 0xABCD;
        let disallow_cat = 0xCAFE;
        let v2 = 2;
        let v3 = 3;
        // Accessor has nodeif and CAT 0xABCD_0003
        let mut subjects = AccessorSubjects::new(112233);
        subjects.add_catid(gen_noc_cat(allow_cat, v3)).unwrap();

        let accessor = Accessor::new(1, subjects, Some(AuthMode::Case), &matter);
        let path = GenericPath::new(Some(1), Some(1234), None);
        let mut req = AccessReq::new(&accessor, path, Access::READ);
        req.set_target_perms(Access::RWVA);

        // Deny for CAT id mismatch
        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
        new.add_subject_catid(gen_noc_cat(disallow_cat, v2))
            .unwrap();
        add_acl(&matter, FAB_1, new).unwrap();
        assert_eq!(req.allow(), false);

        // Allow for CAT match and version more than ACL version
        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
        new.add_subject_catid(gen_noc_cat(allow_cat, v2)).unwrap();
        add_acl(&matter, FAB_1, new).unwrap();
        assert_eq!(req.allow(), true);
    }

    #[test]
    fn test_target() {
        let matter = test_matter();

        // Add fabric with ID 1
        add_fabric(&matter);

        let accessor = Accessor::new(
            1,
            AccessorSubjects::new(112233),
            Some(AuthMode::Case),
            &matter,
        );
        let path = GenericPath::new(Some(1), Some(1234), None);
        let mut req = AccessReq::new(&accessor, path, Access::READ);
        req.set_target_perms(Access::RWVA);

        // Deny for target mismatch
        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
        new.add_target(Target {
            cluster: Some(2),
            endpoint: Some(4567),
            device_type: None,
        })
        .unwrap();
        add_acl(&matter, FAB_1, new).unwrap();
        assert_eq!(req.allow(), false);

        // Allow for cluster match - subject wildcard
        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
        new.add_target(Target {
            cluster: Some(1234),
            endpoint: None,
            device_type: None,
        })
        .unwrap();
        add_acl(&matter, FAB_1, new).unwrap();
        assert_eq!(req.allow(), true);

        // Clean state
        remove_all_acl(&matter, FAB_1);

        // Allow for endpoint match - subject wildcard
        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
        new.add_target(Target {
            cluster: None,
            endpoint: Some(1),
            device_type: None,
        })
        .unwrap();
        add_acl(&matter, FAB_1, new).unwrap();
        assert_eq!(req.allow(), true);

        // Clean state
        remove_all_acl(&matter, FAB_1);

        // Allow for exact match
        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
        new.add_target(Target {
            cluster: Some(1234),
            endpoint: Some(1),
            device_type: None,
        })
        .unwrap();
        new.add_subject(112233).unwrap();
        add_acl(&matter, FAB_1, new).unwrap();
        assert_eq!(req.allow(), true);
    }

    #[test]
    fn test_privilege() {
        let matter = test_matter();

        // Add fabric with ID 1
        add_fabric(&matter);

        let accessor = Accessor::new(
            1,
            AccessorSubjects::new(112233),
            Some(AuthMode::Case),
            &matter,
        );
        let path = GenericPath::new(Some(1), Some(1234), None);

        // Create an Exact Match ACL with View privilege
        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
        new.add_target(Target {
            cluster: Some(1234),
            endpoint: Some(1),
            device_type: None,
        })
        .unwrap();
        new.add_subject(112233).unwrap();
        add_acl(&matter, FAB_1, new).unwrap();

        // Write on an RWVA without admin access - deny
        let mut req = AccessReq::new(&accessor, path.clone(), Access::WRITE);
        req.set_target_perms(Access::RWVA);
        assert_eq!(req.allow(), false);

        // Create an Exact Match ACL with Admin privilege
        let mut new = AclEntry::new(None, Privilege::ADMIN, AuthMode::Case);
        new.add_target(Target {
            cluster: Some(1234),
            endpoint: Some(1),
            device_type: None,
        })
        .unwrap();
        new.add_subject(112233).unwrap();
        add_acl(&matter, FAB_1, new).unwrap();

        // Write on an RWVA with admin access - allow
        let mut req = AccessReq::new(&accessor, path, Access::WRITE);
        req.set_target_perms(Access::RWVA);
        assert_eq!(req.allow(), true);
    }

    #[test]
    fn test_delete_for_fabric() {
        let matter = test_matter();

        // Add fabric with ID 1
        add_fabric(&matter);

        // Add fabric with ID 2
        add_fabric(&matter);

        let path = GenericPath::new(Some(1), Some(1234), None);
        let accessor2 = Accessor::new(
            1,
            AccessorSubjects::new(112233),
            Some(AuthMode::Case),
            &matter,
        );
        let mut req1 = AccessReq::new(&accessor2, path.clone(), Access::READ);
        req1.set_target_perms(Access::RWVA);
        let accessor3 = Accessor::new(
            2,
            AccessorSubjects::new(112233),
            Some(AuthMode::Case),
            &matter,
        );
        let mut req2 = AccessReq::new(&accessor3, path, Access::READ);
        req2.set_target_perms(Access::RWVA);

        // Allow for subject match - target is wildcard - Fabric idx 2
        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
        new.add_subject(112233).unwrap();
        assert_eq!(add_acl(&matter, FAB_1, new).unwrap(), 0);

        // Allow for subject match - target is wildcard - Fabric idx 3
        let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
        new.add_subject(112233).unwrap();
        assert_eq!(add_acl(&matter, FAB_2, new).unwrap(), 0);

        // Req for Fabric idx 1 gets denied, and that for Fabric idx 2 is allowed
        assert_eq!(req1.allow(), true);
        assert_eq!(req2.allow(), true);
        remove_all_acl(&matter, FAB_1);
        assert_eq!(req1.allow(), false);
        assert_eq!(req2.allow(), true);
    }
}