1use core::fmt::Display;
21use core::num::NonZeroU8;
22use core::ops::RangeInclusive;
23
24use cfg_if::cfg_if;
25
26use num::FromPrimitive;
27use num_derive::FromPrimitive;
28
29use crate::dm::{Access, ClusterId, DeviceType, EndptId, NodeId, Privilege};
30use crate::error::{Error, ErrorCode};
31use crate::fabric::Fabrics;
32use crate::im::GenericPath;
33use crate::session::{SessionMode, MAX_CAT_IDS_PER_NOC};
34use crate::tlv::{
35 FromTLV, Nullable, TLVElement, TLVTag, TLVWrite, TlvError, TlvErrorCode, ToTLV, TLV,
36};
37use crate::utils::init::{init, Init};
38use crate::utils::storage::Vec;
39
40cfg_if! {
41 if #[cfg(feature = "max-subjects-per-acl-32")] {
42 pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 32;
44 } else if #[cfg(feature = "max-subjects-per-acl-16")] {
45 pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 16;
47 } else if #[cfg(feature = "max-subjects-per-acl-8")] {
48 pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 8;
50 } else if #[cfg(feature = "max-subjects-per-acl-7")] {
51 pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 7;
53 } else if #[cfg(feature = "max-subjects-per-acl-6")] {
54 pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 6;
56 } else if #[cfg(feature = "max-subjects-per-acl-5")] {
57 pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 5;
59 } else if #[cfg(feature = "max-subjects-per-acl-4")] {
60 pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 4;
62 } else if #[cfg(feature = "max-subjects-per-acl-3")] {
63 pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 3;
65 } else if #[cfg(feature = "max-subjects-per-acl-2")] {
66 pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 2;
68 } else if #[cfg(feature = "max-subjects-per-acl-1")] {
69 pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 1;
71 } else {
72 pub const MAX_SUBJECTS_PER_ACL_ENTRY: usize = 4;
74 }
75}
76
77cfg_if! {
78 if #[cfg(feature = "max-targets-per-acl-32")] {
79 pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 32;
81 } else if #[cfg(feature = "max-targets-per-acl-16")] {
82 pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 16;
84 } else if #[cfg(feature = "max-targets-per-acl-8")] {
85 pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 8;
87 } else if #[cfg(feature = "max-targets-per-acl-7")] {
88 pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 7;
90 } else if #[cfg(feature = "max-targets-per-acl-6")] {
91 pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 6;
93 } else if #[cfg(feature = "max-targets-per-acl-5")] {
94 pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 5;
96 } else if #[cfg(feature = "max-targets-per-acl-4")] {
97 pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 4;
99 } else if #[cfg(feature = "max-targets-per-acl-3")] {
100 pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 3;
102 } else if #[cfg(feature = "max-targets-per-acl-2")] {
103 pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 2;
105 } else if #[cfg(feature = "max-targets-per-acl-1")] {
106 pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 1;
108 } else {
109 pub const MAX_TARGETS_PER_ACL_ENTRY: usize = 3;
111 }
112}
113
114cfg_if! {
115 if #[cfg(feature = "max-acls-per-fabric-32")] {
116 pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 32;
118 } else if #[cfg(feature = "max-acls-per-fabric-16")] {
119 pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 16;
121 } else if #[cfg(feature = "max-acls-per-fabric-8")] {
122 pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 8;
124 } else if #[cfg(feature = "max-acls-per-fabric-7")] {
125 pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 7;
127 } else if #[cfg(feature = "max-acls-per-fabric-6")] {
128 pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 6;
130 } else if #[cfg(feature = "max-acls-per-fabric-5")] {
131 pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 5;
133 } else if #[cfg(feature = "max-acls-per-fabric-4")] {
134 pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 4;
136 } else if #[cfg(feature = "max-acls-per-fabric-3")] {
137 pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 3;
139 } else if #[cfg(feature = "max-acls-per-fabric-2")] {
140 pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 2;
142 } else if #[cfg(feature = "max-acls-per-fabric-1")] {
143 pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 1;
145 } else {
146 pub const MAX_ACL_ENTRIES_PER_FABRIC: usize = 4;
148 }
149}
150
151#[derive(FromPrimitive, Copy, Clone, PartialEq, Debug)]
154#[cfg_attr(feature = "defmt", derive(defmt::Format))]
155#[repr(u8)]
156pub enum AuthMode {
159 Pase = 1,
161 Case = 2,
163 Group = 3,
165}
166
167impl FromTLV<'_> for AuthMode {
168 fn from_tlv(t: &TLVElement) -> Result<Self, TlvError>
169 where
170 Self: Sized,
171 {
172 Self::from_u8(t.u8()?).ok_or(TlvErrorCode::InvalidValue.into())
173 }
174}
175
176impl ToTLV for AuthMode {
177 fn to_tlv<W: TLVWrite>(&self, tag: &TLVTag, mut tw: W) -> Result<(), TlvError> {
178 tw.u8(tag, *self as _)
179 }
180
181 fn tlv_iter(&self, tag: TLVTag) -> impl Iterator<Item = Result<TLV<'_>, TlvError>> {
182 TLV::u8(tag, *self as _).into_tlv_iter()
183 }
184}
185
186#[derive(FromPrimitive, Copy, Clone, PartialEq, Eq, Debug)]
191#[cfg_attr(feature = "defmt", derive(defmt::Format))]
192#[repr(u8)]
193pub enum AuxiliaryType {
194 System = 0,
196 Groupcast = 1,
198}
199
200impl FromTLV<'_> for AuxiliaryType {
201 fn from_tlv(t: &TLVElement) -> Result<Self, TlvError>
202 where
203 Self: Sized,
204 {
205 Self::from_u8(t.u8()?).ok_or(TlvErrorCode::InvalidValue.into())
206 }
207}
208
209impl ToTLV for AuxiliaryType {
210 fn to_tlv<W: TLVWrite>(&self, tag: &TLVTag, mut tw: W) -> Result<(), TlvError> {
211 tw.u8(tag, *self as _)
212 }
213
214 fn tlv_iter(&self, tag: TLVTag) -> impl Iterator<Item = Result<TLV<'_>, TlvError>> {
215 TLV::u8(tag, *self as _).into_tlv_iter()
216 }
217}
218
219const MAX_ACCESSOR_SUBJECTS: usize = 1 + MAX_CAT_IDS_PER_NOC;
221
222pub const NOC_CAT_SUBJECT_PREFIX: u64 = 0xFFFF_FFFD_0000_0000;
224pub const NOC_CAT_SUBJECT_MASK: u64 = 0xFFFF_FFFF_0000_0000;
225
226const NOC_CAT_ID_MASK: u64 = 0xFFFF_0000;
227const NOC_CAT_VERSION_MASK: u64 = 0xFFFF;
228
229const NODE_ID_RANGE: RangeInclusive<u64> = 1..=0xFFFF_FFEF_FFFF_FFFF;
231
232pub fn is_noc_cat(id: u64) -> bool {
234 ((id & NOC_CAT_SUBJECT_MASK) == NOC_CAT_SUBJECT_PREFIX)
235 && ((id & (NOC_CAT_ID_MASK | NOC_CAT_VERSION_MASK)) > 0)
236}
237
238fn get_noc_cat_id(id: u64) -> u64 {
240 (id & NOC_CAT_ID_MASK) >> 16
241}
242
243fn get_noc_cat_version(id: u64) -> u64 {
245 id & NOC_CAT_VERSION_MASK
246}
247
248pub fn gen_noc_cat(id: u16, version: u16) -> u32 {
251 ((id as u32) << 16) | version as u32
252}
253
254pub fn is_node(id: u64) -> bool {
256 NODE_ID_RANGE.contains(&id)
257}
258
259pub struct AccessorSubjects([u64; MAX_ACCESSOR_SUBJECTS]);
261
262impl AccessorSubjects {
263 pub fn new(id: u64) -> Self {
266 let mut a = Self(Default::default());
267 a.0[0] = id;
268 a
269 }
270
271 pub fn add_catid(&mut self, subject: u32) -> Result<(), Error> {
273 for (i, val) in self.0.iter().enumerate() {
274 if *val == 0 {
275 self.0[i] = NOC_CAT_SUBJECT_PREFIX | (subject as u64);
276 return Ok(());
277 }
278 }
279 Err(ErrorCode::ResourceExhausted.into())
280 }
281
282 pub fn matches(&self, acl_subject: u64) -> bool {
285 for v in self.0.iter() {
286 if *v == 0 {
287 continue;
288 }
289
290 if *v == acl_subject {
291 return true;
292 } else {
293 if is_noc_cat(*v)
295 && is_noc_cat(acl_subject)
296 && (get_noc_cat_id(*v) == get_noc_cat_id(acl_subject))
297 && (get_noc_cat_version(*v) >= get_noc_cat_version(acl_subject))
298 {
299 return true;
300 }
301 }
302 }
303
304 false
305 }
306}
307
308impl Display for AccessorSubjects {
309 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::result::Result<(), core::fmt::Error> {
310 write!(f, "[")?;
311 for i in self.0 {
312 if is_noc_cat(i) {
313 write!(f, "CAT({} - {})", get_noc_cat_id(i), get_noc_cat_version(i))?;
314 } else if i != 0 {
315 write!(f, "{}, ", i)?;
316 }
317 }
318 write!(f, "]")
319 }
320}
321
322#[cfg(feature = "defmt")]
323impl defmt::Format for AccessorSubjects {
324 fn format(&self, f: defmt::Formatter) {
325 defmt::write!(f, "[");
326 for i in self.0 {
327 if is_noc_cat(i) {
328 defmt::write!(f, "CAT({} - {})", get_noc_cat_id(i), get_noc_cat_version(i));
329 } else if i != 0 {
330 defmt::write!(f, "{}, ", i);
331 }
332 }
333 defmt::write!(f, "]")
334 }
335}
336
337pub struct SubjectDescriptor {
342 pub fab_idx: u8,
344 aux_acl_enabled: bool,
346 subjects: AccessorSubjects,
348 auth_mode: Option<AuthMode>,
350}
351
352impl SubjectDescriptor {
353 pub fn for_session(
360 session_mode: &SessionMode,
361 peer_node_id: Option<NodeId>,
362 aux_acl_enabled: bool,
363 ) -> Self {
364 match session_mode {
365 SessionMode::Case {
366 fab_idx, cat_ids, ..
367 } => {
368 let mut subject = AccessorSubjects::new(peer_node_id.unwrap_or_default());
369 for i in *cat_ids {
370 if i != 0 {
371 let _ = subject.add_catid(i);
372 }
373 }
374 Self::new(
375 fab_idx.get(),
376 aux_acl_enabled,
377 subject,
378 Some(AuthMode::Case),
379 )
380 }
381 SessionMode::Pase { fab_idx } => Self::new(
382 *fab_idx,
383 aux_acl_enabled,
384 AccessorSubjects::new(1),
385 Some(AuthMode::Pase),
386 ),
387 SessionMode::Group { fab_idx, group_id } => Self::new(
388 fab_idx.get(),
389 aux_acl_enabled,
390 AccessorSubjects::new(*group_id as u64),
391 Some(AuthMode::Group),
392 ),
393 SessionMode::PlainText => Self::new(0, aux_acl_enabled, AccessorSubjects::new(1), None),
394 }
395 }
396
397 pub const fn new(
405 fab_idx: u8,
406 aux_acl_enabled: bool,
407 subjects: AccessorSubjects,
408 auth_mode: Option<AuthMode>,
409 ) -> Self {
410 Self {
411 fab_idx,
412 aux_acl_enabled,
413 subjects,
414 auth_mode,
415 }
416 }
417
418 pub fn fab_idx(&self) -> Result<NonZeroU8, Error> {
419 NonZeroU8::new(self.fab_idx).ok_or(ErrorCode::UnsupportedAccess.into())
420 }
421
422 pub const fn aux_acl_enabled(&self) -> bool {
424 self.aux_acl_enabled
425 }
426
427 pub const fn subjects(&self) -> &AccessorSubjects {
429 &self.subjects
430 }
431
432 pub const fn auth_mode(&self) -> Option<AuthMode> {
434 self.auth_mode
435 }
436
437 pub fn is_endpoint_accessible(&self, endpoint_id: EndptId, fabrics: &Fabrics) -> bool {
442 if self.auth_mode != Some(AuthMode::Group) {
443 return true;
444 }
445
446 #[cfg(feature = "groups")]
449 {
450 let group_id = self.subjects.0[0] as u16;
451
452 let Some(fab_idx) = core::num::NonZeroU8::new(self.fab_idx) else {
453 return false;
454 };
455
456 let Some(fabric) = fabrics.get(fab_idx) else {
457 return false;
458 };
459
460 fabric
461 .groups()
462 .get(group_id)
463 .is_some_and(|e| e.endpoints.contains(&endpoint_id))
464 }
465
466 #[cfg(not(feature = "groups"))]
471 {
472 let _ = (endpoint_id, fabrics);
473 false
474 }
475 }
476
477 pub fn peer_node_id(&self) -> Option<u64> {
479 if matches!(self.auth_mode, Some(AuthMode::Case)) {
480 let id = self.subjects.0[0];
481 if is_node(id) {
482 Some(id)
483 } else {
484 None
485 }
486 } else {
487 None
488 }
489 }
490}
491
492#[derive(Debug)]
494#[cfg_attr(feature = "defmt", derive(defmt::Format))]
495pub struct AccessDesc<'a> {
496 path: GenericPath,
498 target_perms: Option<Access>,
500 operation: Access,
502 device_types: &'a [DeviceType],
506}
507
508pub struct AccessReq<'a> {
510 accessor: &'a SubjectDescriptor,
512 object: AccessDesc<'a>,
514}
515
516impl<'a> AccessReq<'a> {
517 pub const fn new(
525 accessor: &'a SubjectDescriptor,
526 path: GenericPath,
527 operation: Access,
528 device_types: &'a [DeviceType],
529 ) -> Self {
530 AccessReq {
531 accessor,
532 object: AccessDesc {
533 path,
534 target_perms: None,
535 operation,
536 device_types,
537 },
538 }
539 }
540
541 pub fn accessor(&self) -> &SubjectDescriptor {
543 self.accessor
544 }
545
546 pub fn operation(&self) -> Access {
548 self.object.operation
549 }
550
551 pub fn set_target_perms(&mut self, perms: Access) {
556 self.object.target_perms = Some(perms);
557 }
558
559 pub fn allow(&self, fabrics: &Fabrics) -> bool {
565 let allow = fabrics.allow(self, self.accessor.aux_acl_enabled());
566
567 #[cfg(feature = "groups")]
568 let allow = allow || self.allow_groupcast_auxiliary(fabrics);
569
570 allow
571 }
572
573 #[cfg(feature = "groups")]
579 fn allow_groupcast_auxiliary(&self, fabrics: &Fabrics) -> bool {
580 if !self.accessor.aux_acl_enabled() {
581 return false;
582 }
583
584 if self.accessor.auth_mode != Some(AuthMode::Group) {
585 return false;
586 }
587
588 let Ok(fab_idx) = self.accessor.fab_idx() else {
589 return false;
590 };
591
592 let Some(fabric) = fabrics.get(fab_idx) else {
593 return false;
594 };
595
596 let Some(endpoint) = self.object.path.endpoint else {
598 return false;
599 };
600
601 let granted = fabric.groups().iter().any(|entry| {
602 entry.has_aux_acl()
603 && entry.endpoints.contains(&endpoint)
604 && self.accessor.subjects.matches(entry.group_id as u64)
605 });
606
607 granted
608 && self
609 .object
610 .target_perms
611 .is_some_and(|access| access.is_ok(self.object.operation, Privilege::OPERATE))
612 }
613}
614
615#[derive(FromTLV, ToTLV, Clone, Debug, PartialEq)]
617#[cfg_attr(feature = "defmt", derive(defmt::Format))]
618pub struct Target {
619 pub cluster: Option<ClusterId>,
620 pub endpoint: Option<EndptId>,
621 pub device_type: Option<u32>,
622}
623
624impl Target {
625 pub const fn new(
627 endpoint: Option<EndptId>,
628 cluster: Option<ClusterId>,
629 device_type: Option<u32>,
630 ) -> Self {
631 Self {
632 cluster,
633 endpoint,
634 device_type,
635 }
636 }
637}
638
639#[derive(ToTLV, FromTLV, Clone, Debug, PartialEq)]
641#[cfg_attr(feature = "defmt", derive(defmt::Format))]
642#[tlvargs(start = 1)]
643pub struct AclEntry {
644 privilege: Privilege,
646 auth_mode: AuthMode,
648 subjects: Nullable<Vec<u64, MAX_SUBJECTS_PER_ACL_ENTRY>>,
650 targets: Nullable<Vec<Target, MAX_TARGETS_PER_ACL_ENTRY>>,
652 auxiliary_type: Option<AuxiliaryType>,
654 #[tagval(crate::im::FABRIC_INDEX_TAG)]
657 pub fab_idx: Option<NonZeroU8>,
658}
659
660impl AclEntry {
661 pub const fn new(
663 fab_idx: Option<NonZeroU8>,
664 privilege: Privilege,
665 auth_mode: AuthMode,
666 ) -> Self {
667 Self {
668 fab_idx,
669 privilege,
670 auth_mode,
671 subjects: Nullable::none(),
672 targets: Nullable::none(),
673 auxiliary_type: None,
674 }
675 }
676
677 pub fn init(
680 fab_idx: Option<NonZeroU8>,
681 privilege: Privilege,
682 auth_mode: AuthMode,
683 ) -> impl Init<Self> {
684 init!(Self {
685 fab_idx,
686 privilege,
687 auth_mode,
688 subjects <- Nullable::init_none(),
689 targets <- Nullable::init_none(),
690 auxiliary_type: None,
691 })
692 }
693
694 pub fn normalize(&mut self) {
697 if self
698 .subjects
699 .as_opt_ref()
700 .map(|subjects| subjects.is_empty())
701 .unwrap_or(false)
702 {
703 self.subjects.clear();
704 }
705
706 if self
707 .targets
708 .as_opt_ref()
709 .map(|targets| targets.is_empty())
710 .unwrap_or(false)
711 {
712 self.targets.clear();
713 }
714 }
715
716 pub fn privilege(&self) -> Privilege {
718 self.privilege
719 }
720
721 pub fn set_privilege(&mut self, privilege: Privilege) {
723 self.privilege = privilege;
724 }
725
726 pub fn auth_mode(&self) -> AuthMode {
728 self.auth_mode
729 }
730
731 pub fn set_auth_mode(&mut self, auth_mode: AuthMode) {
733 self.auth_mode = auth_mode;
734 }
735
736 pub fn subjects(&self) -> Nullable<&[u64]> {
738 Nullable::new(self.subjects.as_opt_ref().map(|v| v.as_slice()))
739 }
740
741 pub fn targets(&self) -> Nullable<&[Target]> {
743 Nullable::new(self.targets.as_opt_ref().map(|v| v.as_slice()))
744 }
745
746 pub fn auxiliary_type(&self) -> Option<AuxiliaryType> {
748 self.auxiliary_type
749 }
750
751 pub fn allow(&self, req: &AccessReq, aux_acl_enabled: bool) -> bool {
757 self.match_accessor(req.accessor) && self.match_access_desc(&req.object, aux_acl_enabled)
758 }
759
760 pub fn add_subject(&mut self, subject: u64) -> Result<(), Error> {
762 if self.subjects.is_none() {
763 self.subjects.reinit(Nullable::init_some(Vec::init()));
764 }
765
766 unwrap!(self.subjects.as_opt_mut())
767 .push(subject)
768 .map_err(|_| ErrorCode::ResourceExhausted.into())
769 }
770
771 pub fn add_subject_catid(&mut self, cat_id: u32) -> Result<(), Error> {
773 self.add_subject(NOC_CAT_SUBJECT_PREFIX | cat_id as u64)
774 }
775
776 pub fn add_target(&mut self, target: Target) -> Result<(), Error> {
778 if self.targets.is_none() {
779 self.targets.reinit(Nullable::init_some(Vec::init()));
780 }
781
782 unwrap!(self.targets.as_opt_mut())
783 .push(target)
784 .map_err(|_| ErrorCode::ResourceExhausted.into())
785 }
786
787 fn match_accessor(&self, accessor: &SubjectDescriptor) -> bool {
788 if Some(self.auth_mode) != accessor.auth_mode {
789 return false;
790 }
791
792 let allow = self.subjects().as_opt_ref().is_none_or(|subjects| {
793 subjects.is_empty() || subjects.iter().any(|s| accessor.subjects.matches(*s))
796 });
797
798 allow
800 && self
801 .fab_idx
802 .map(|fab_idx| fab_idx.get() == accessor.fab_idx)
803 .unwrap_or(false)
804 }
805
806 fn match_access_desc(&self, object: &AccessDesc, aux_acl_enabled: bool) -> bool {
807 if aux_acl_enabled
813 && matches!(self.auth_mode, AuthMode::Group)
814 && object.path.endpoint == Some(crate::dm::ROOT_ENDPOINT_ID)
815 && self
816 .targets
817 .as_opt_ref()
818 .is_none_or(|targets| targets.is_empty())
819 {
820 return false;
821 }
822
823 let allow = self.targets.as_opt_ref().is_none_or(|targets| {
824 targets.is_empty()
827 || targets.iter().any(|t| {
828 let endpoint_match = t.endpoint.is_none() || t.endpoint == object.path.endpoint;
829 let cluster_match = t.cluster.is_none() || t.cluster == object.path.cluster;
830 let device_type_match = match t.device_type {
834 Some(dt) => object
835 .device_types
836 .iter()
837 .any(|endpoint_dt| endpoint_dt.dtype as u32 == dt),
838 None => true,
839 };
840 endpoint_match && cluster_match && device_type_match
841 })
842 });
843
844 if allow {
845 if let Some(access) = object.target_perms {
847 access.is_ok(object.operation, self.privilege)
848 } else {
849 false
850 }
851 } else {
852 false
853 }
854 }
855}
856
857#[cfg(test)]
858#[allow(clippy::bool_assert_comparison)]
859pub(crate) mod tests {
860 use core::num::NonZeroU8;
861
862 use crate::acl::{gen_noc_cat, AccessorSubjects};
863 use crate::dm::{Access, Privilege};
864 use crate::error::Error;
865 use crate::fabric::Fabrics;
866 use crate::im::GenericPath;
867
868 use super::{AccessReq, AclEntry, AuthMode, SubjectDescriptor, Target};
869
870 pub(crate) const FAB_1: NonZeroU8 = match NonZeroU8::new(1) {
871 Some(f) => f,
872 None => ::core::unreachable!(),
873 };
874
875 pub(crate) const FAB_2: NonZeroU8 = match NonZeroU8::new(2) {
876 Some(f) => f,
877 None => ::core::unreachable!(),
878 };
879
880 fn add_fabric(fabrics: &mut Fabrics) {
881 fabrics.add_with_post_init(|_| Ok(())).unwrap();
883 }
884
885 fn add_acl(fabrics: &mut Fabrics, fab_idx: NonZeroU8, entry: AclEntry) -> Result<usize, Error> {
886 fabrics.fabric_mut(fab_idx)?.acl_add(entry)
887 }
888
889 fn remove_all_acl(fabrics: &mut Fabrics, fab_idx: NonZeroU8) {
890 fabrics.fabric_mut(fab_idx).unwrap().acl_remove_all()
891 }
892
893 #[test]
894 fn test_basic_empty_subject_target() {
895 let mut fabrics = Fabrics::new();
896 let accessor = SubjectDescriptor::new(
897 0,
898 false,
899 AccessorSubjects::new(112233),
900 Some(AuthMode::Pase),
901 );
902 let path = GenericPath::new(Some(1), Some(1234), None);
903 let mut req_pase = AccessReq::new(&accessor, path, Access::READ, &[]);
904 req_pase.set_target_perms(Access::RWVA);
905
906 assert!(req_pase.allow(&fabrics));
908
909 let accessor = SubjectDescriptor::new(
910 2,
911 false,
912 AccessorSubjects::new(112233),
913 Some(AuthMode::Case),
914 );
915 let path = GenericPath::new(Some(1), Some(1234), None);
916 let mut req = AccessReq::new(&accessor, path, Access::READ, &[]);
917 req.set_target_perms(Access::RWVA);
918
919 assert_eq!(req.allow(&fabrics), false);
921
922 add_fabric(&mut fabrics);
924
925 let new = AclEntry::new(None, Privilege::VIEW, AuthMode::Pase);
927 assert!(add_acl(&mut fabrics, FAB_1, new).is_err());
928
929 let new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
931 assert_eq!(add_acl(&mut fabrics, FAB_1, new).unwrap(), 0);
932 assert_eq!(req.allow(&fabrics), false);
933
934 assert!(req_pase.allow(&fabrics));
936
937 add_fabric(&mut fabrics);
939
940 let new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
942 assert_eq!(add_acl(&mut fabrics, FAB_2, new).unwrap(), 0);
943 assert_eq!(req.allow(&fabrics), true);
944 }
945
946 #[test]
947 fn test_subject() {
948 let mut fabrics = Fabrics::new();
949
950 add_fabric(&mut fabrics);
952
953 let accessor = SubjectDescriptor::new(
954 1,
955 false,
956 AccessorSubjects::new(112233),
957 Some(AuthMode::Case),
958 );
959 let path = GenericPath::new(Some(1), Some(1234), None);
960 let mut req = AccessReq::new(&accessor, path, Access::READ, &[]);
961 req.set_target_perms(Access::RWVA);
962
963 let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
965 new.add_subject(112232).unwrap();
966 assert_eq!(add_acl(&mut fabrics, FAB_1, new).unwrap(), 0);
967 assert_eq!(req.allow(&fabrics), false);
968
969 let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
971 new.add_subject(112233).unwrap();
972 assert_eq!(add_acl(&mut fabrics, FAB_1, new).unwrap(), 1);
973 assert_eq!(req.allow(&fabrics), true);
974 }
975
976 #[test]
977 fn test_cat() {
978 let mut fabrics = Fabrics::new();
979
980 add_fabric(&mut fabrics);
982
983 let allow_cat = 0xABCD;
984 let disallow_cat = 0xCAFE;
985 let v2 = 2;
986 let v3 = 3;
987 let mut subjects = AccessorSubjects::new(112233);
989 subjects.add_catid(gen_noc_cat(allow_cat, v2)).unwrap();
990
991 let accessor = SubjectDescriptor::new(1, false, subjects, Some(AuthMode::Case));
992 let path = GenericPath::new(Some(1), Some(1234), None);
993 let mut req = AccessReq::new(&accessor, path, Access::READ, &[]);
994 req.set_target_perms(Access::RWVA);
995
996 let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
998 new.add_subject_catid(gen_noc_cat(disallow_cat, v2))
999 .unwrap();
1000 add_acl(&mut fabrics, FAB_1, new).unwrap();
1001 assert_eq!(req.allow(&fabrics), false);
1002
1003 let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
1005 new.add_subject_catid(gen_noc_cat(allow_cat, v3)).unwrap();
1006 add_acl(&mut fabrics, FAB_1, new).unwrap();
1007 assert_eq!(req.allow(&fabrics), false);
1008
1009 let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
1011 new.add_subject_catid(gen_noc_cat(allow_cat, v2)).unwrap();
1012 add_acl(&mut fabrics, FAB_1, new).unwrap();
1013 assert_eq!(req.allow(&fabrics), true);
1014 }
1015
1016 #[test]
1017 fn test_cat_version() {
1018 let mut fabrics = Fabrics::new();
1019
1020 add_fabric(&mut fabrics);
1022
1023 let allow_cat = 0xABCD;
1024 let disallow_cat = 0xCAFE;
1025 let v2 = 2;
1026 let v3 = 3;
1027 let mut subjects = AccessorSubjects::new(112233);
1029 subjects.add_catid(gen_noc_cat(allow_cat, v3)).unwrap();
1030
1031 let accessor = SubjectDescriptor::new(1, false, subjects, Some(AuthMode::Case));
1032 let path = GenericPath::new(Some(1), Some(1234), None);
1033 let mut req = AccessReq::new(&accessor, path, Access::READ, &[]);
1034 req.set_target_perms(Access::RWVA);
1035
1036 let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
1038 new.add_subject_catid(gen_noc_cat(disallow_cat, v2))
1039 .unwrap();
1040 add_acl(&mut fabrics, FAB_1, new).unwrap();
1041 assert_eq!(req.allow(&fabrics), false);
1042
1043 let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
1045 new.add_subject_catid(gen_noc_cat(allow_cat, v2)).unwrap();
1046 add_acl(&mut fabrics, FAB_1, new).unwrap();
1047 assert_eq!(req.allow(&fabrics), true);
1048 }
1049
1050 #[test]
1051 fn test_target() {
1052 let mut fabrics = Fabrics::new();
1053
1054 add_fabric(&mut fabrics);
1056
1057 let accessor = SubjectDescriptor::new(
1058 1,
1059 false,
1060 AccessorSubjects::new(112233),
1061 Some(AuthMode::Case),
1062 );
1063 let path = GenericPath::new(Some(1), Some(1234), None);
1064 let mut req = AccessReq::new(&accessor, path, Access::READ, &[]);
1065 req.set_target_perms(Access::RWVA);
1066
1067 let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
1069 new.add_target(Target {
1070 cluster: Some(2),
1071 endpoint: Some(4567),
1072 device_type: None,
1073 })
1074 .unwrap();
1075 add_acl(&mut fabrics, FAB_1, new).unwrap();
1076 assert_eq!(req.allow(&fabrics), false);
1077
1078 let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
1080 new.add_target(Target {
1081 cluster: Some(1234),
1082 endpoint: None,
1083 device_type: None,
1084 })
1085 .unwrap();
1086 add_acl(&mut fabrics, FAB_1, new).unwrap();
1087 assert_eq!(req.allow(&fabrics), true);
1088
1089 remove_all_acl(&mut fabrics, FAB_1);
1091
1092 let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
1094 new.add_target(Target {
1095 cluster: None,
1096 endpoint: Some(1),
1097 device_type: None,
1098 })
1099 .unwrap();
1100 add_acl(&mut fabrics, FAB_1, new).unwrap();
1101 assert_eq!(req.allow(&fabrics), true);
1102
1103 remove_all_acl(&mut fabrics, FAB_1);
1105
1106 let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
1108 new.add_target(Target {
1109 cluster: Some(1234),
1110 endpoint: Some(1),
1111 device_type: None,
1112 })
1113 .unwrap();
1114 new.add_subject(112233).unwrap();
1115 add_acl(&mut fabrics, FAB_1, new).unwrap();
1116 assert_eq!(req.allow(&fabrics), true);
1117 }
1118
1119 #[test]
1120 fn test_privilege() {
1121 let mut fabrics = Fabrics::new();
1122
1123 add_fabric(&mut fabrics);
1125
1126 let accessor = SubjectDescriptor::new(
1127 1,
1128 false,
1129 AccessorSubjects::new(112233),
1130 Some(AuthMode::Case),
1131 );
1132 let path = GenericPath::new(Some(1), Some(1234), None);
1133
1134 let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
1136 new.add_target(Target {
1137 cluster: Some(1234),
1138 endpoint: Some(1),
1139 device_type: None,
1140 })
1141 .unwrap();
1142 new.add_subject(112233).unwrap();
1143 add_acl(&mut fabrics, FAB_1, new).unwrap();
1144
1145 let mut req = AccessReq::new(&accessor, path.clone(), Access::WRITE, &[]);
1147 req.set_target_perms(Access::RWVA);
1148 assert_eq!(req.allow(&fabrics), false);
1149
1150 let mut new = AclEntry::new(None, Privilege::ADMIN, AuthMode::Case);
1152 new.add_target(Target {
1153 cluster: Some(1234),
1154 endpoint: Some(1),
1155 device_type: None,
1156 })
1157 .unwrap();
1158 new.add_subject(112233).unwrap();
1159 add_acl(&mut fabrics, FAB_1, new).unwrap();
1160
1161 let mut req = AccessReq::new(&accessor, path, Access::WRITE, &[]);
1163 req.set_target_perms(Access::RWVA);
1164 assert_eq!(req.allow(&fabrics), true);
1165 }
1166
1167 #[test]
1168 fn test_delete_for_fabric() {
1169 let mut fabrics = Fabrics::new();
1170
1171 add_fabric(&mut fabrics);
1173
1174 add_fabric(&mut fabrics);
1176
1177 let path = GenericPath::new(Some(1), Some(1234), None);
1178 let accessor2 = SubjectDescriptor::new(
1179 1,
1180 false,
1181 AccessorSubjects::new(112233),
1182 Some(AuthMode::Case),
1183 );
1184 let mut req1 = AccessReq::new(&accessor2, path.clone(), Access::READ, &[]);
1185 req1.set_target_perms(Access::RWVA);
1186 let accessor3 = SubjectDescriptor::new(
1187 2,
1188 false,
1189 AccessorSubjects::new(112233),
1190 Some(AuthMode::Case),
1191 );
1192 let mut req2 = AccessReq::new(&accessor3, path, Access::READ, &[]);
1193 req2.set_target_perms(Access::RWVA);
1194
1195 let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
1197 new.add_subject(112233).unwrap();
1198 assert_eq!(add_acl(&mut fabrics, FAB_1, new).unwrap(), 0);
1199
1200 let mut new = AclEntry::new(None, Privilege::VIEW, AuthMode::Case);
1202 new.add_subject(112233).unwrap();
1203 assert_eq!(add_acl(&mut fabrics, FAB_2, new).unwrap(), 0);
1204
1205 assert_eq!(req1.allow(&fabrics), true);
1207 assert_eq!(req2.allow(&fabrics), true);
1208 remove_all_acl(&mut fabrics, FAB_1);
1209 assert_eq!(req1.allow(&fabrics), false);
1210 assert_eq!(req2.allow(&fabrics), true);
1211 }
1212
1213 #[test]
1217 fn test_aux_wildcard_group_excludes_root_endpoint() {
1218 let mut fabrics = Fabrics::new();
1219 add_fabric(&mut fabrics);
1220
1221 const GROUP_ID: u64 = 0x12AB;
1222
1223 let mut entry = AclEntry::new(None, Privilege::OPERATE, AuthMode::Group);
1225 entry.add_subject(GROUP_ID).unwrap();
1226 add_acl(&mut fabrics, FAB_1, entry).unwrap();
1227
1228 let accessor = SubjectDescriptor::new(
1229 FAB_1.get(),
1230 false,
1231 AccessorSubjects::new(GROUP_ID),
1232 Some(AuthMode::Group),
1233 );
1234
1235 let ep0 = GenericPath::new(Some(0), Some(1234), None);
1236 let ep1 = GenericPath::new(Some(1), Some(1234), None);
1237
1238 for path in [ep0.clone(), ep1.clone()] {
1240 let mut req = AccessReq::new(&accessor, path, Access::WRITE, &[]);
1241 req.set_target_perms(Access::WO);
1242 assert!(req.allow(&fabrics));
1243 }
1244
1245 let accessor = SubjectDescriptor::new(
1246 FAB_1.get(),
1247 true,
1248 AccessorSubjects::new(GROUP_ID),
1249 Some(AuthMode::Group),
1250 );
1251
1252 let mut req = AccessReq::new(&accessor, ep0.clone(), Access::WRITE, &[]);
1254 req.set_target_perms(Access::WO);
1255 assert!(!req.allow(&fabrics));
1256
1257 let mut req = AccessReq::new(&accessor, ep1, Access::WRITE, &[]);
1259 req.set_target_perms(Access::WO);
1260 assert!(req.allow(&fabrics));
1261
1262 remove_all_acl(&mut fabrics, FAB_1);
1264 let mut entry = AclEntry::new(None, Privilege::OPERATE, AuthMode::Group);
1265 entry.add_subject(GROUP_ID).unwrap();
1266 entry.add_target(Target::new(Some(0), None, None)).unwrap();
1267 add_acl(&mut fabrics, FAB_1, entry).unwrap();
1268
1269 let mut req = AccessReq::new(&accessor, ep0, Access::WRITE, &[]);
1270 req.set_target_perms(Access::WO);
1271 assert!(req.allow(&fabrics));
1272 }
1273}