use core::cell::RefCell;
use crate::acl::{Acl, AuthMode, Entry, Target};
use crate::config::Config;
use crate::dm::{
Access, AccessQualities, AttributeDescriptor, ClusterDescriptor, CommandDescriptor,
EventDescriptor, EventPriority, Privilege, Resolved,
};
use crate::im::{
AttributeId, ClusterHandler, ClusterId, EventId, InteractionContext, Status, WriteOp,
};
use crate::msg::{FabricIndex, NodeId};
use crate::tlv::{ContainerKind, Tag, TlvReader, TlvWriter, Value};
use super::Cluster;
pub const ID: ClusterId = 0x001F;
pub const REVISION: u16 = 3;
pub const ACL: AttributeId = 0x0000;
pub const EXTENSION: AttributeId = 0x0001;
pub const SUBJECTS_PER_ENTRY: AttributeId = 0x0002;
pub const TARGETS_PER_ENTRY: AttributeId = 0x0003;
pub const ENTRIES_PER_FABRIC: AttributeId = 0x0004;
pub const ACCESS_CONTROL_ENTRY_CHANGED: EventId = 0x0000;
pub const FABRIC_INDEX_FIELD: u8 = 254;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ChangeType {
Changed = 0,
Added = 1,
Removed = 2,
}
const ATTRIBUTES: &[AttributeDescriptor] = &[
AttributeDescriptor::read_write(ACL).with_access(
Access::read_write_with(Privilege::Administer, Privilege::Administer)
.with_qualities(AccessQualities::FABRIC_SCOPED),
),
AttributeDescriptor::read_only(SUBJECTS_PER_ENTRY),
AttributeDescriptor::read_only(TARGETS_PER_ENTRY),
AttributeDescriptor::read_only(ENTRIES_PER_FABRIC),
];
const NO_COMMANDS: &[CommandDescriptor] = &[];
const EVENTS: &[EventDescriptor] =
&[EventDescriptor::new(ACCESS_CONTROL_ENTRY_CHANGED).with_priority(EventPriority::Info)];
#[must_use]
pub const fn cluster() -> ClusterDescriptor<'static> {
ClusterDescriptor {
id: ID,
revision: REVISION,
feature_map: 0,
attributes: ATTRIBUTES,
accepted_commands: NO_COMMANDS,
generated_commands: &[],
events: EVENTS,
}
}
const PENDING: usize = 8;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EntryChanged<const S: usize, const T: usize> {
pub admin_node_id: Option<NodeId>,
pub admin_passcode_id: Option<u16>,
pub change_type: ChangeType,
pub latest_value: Option<Entry<S, T>>,
pub fabric_index: FabricIndex,
}
impl<const S: usize, const T: usize> EntryChanged<S, T> {
#[must_use]
pub fn for_session(
ctx: &InteractionContext<'_>,
change_type: ChangeType,
latest_value: Option<Entry<S, T>>,
) -> Self {
let (admin_node_id, admin_passcode_id) = match ctx.peer_node_id {
Some(node_id) => (Some(node_id), None),
None => (None, Some(0)),
};
let fabric_index = ctx.fabric_index.unwrap_or(FabricIndex(0));
Self {
admin_node_id,
admin_passcode_id,
change_type,
latest_value,
fabric_index,
}
}
#[must_use]
pub fn for_fabric(mut self, fabric_index: FabricIndex) -> Self {
self.fabric_index = fabric_index;
self
}
pub fn encode(&self, w: &mut TlvWriter<'_>, tag: Tag) -> crate::error::Result<()> {
w.start_structure(tag)?;
match self.admin_node_id {
Some(id) => w.unsigned(Tag::Context(1), id.0)?,
None => w.null(Tag::Context(1))?,
}
match self.admin_passcode_id {
Some(id) => w.unsigned(Tag::Context(2), u64::from(id))?,
None => w.null(Tag::Context(2))?,
}
w.unsigned(Tag::Context(3), self.change_type as u64)?;
match &self.latest_value {
Some(entry) => write_entry(w, Tag::Context(4), entry)?,
None => w.null(Tag::Context(4))?,
}
w.unsigned(
Tag::Context(FABRIC_INDEX_FIELD),
u64::from(self.fabric_index.0),
)?;
w.end_container()
}
}
fn write_entry<const S: usize, const T: usize>(
w: &mut TlvWriter<'_>,
tag: Tag,
entry: &Entry<S, T>,
) -> crate::error::Result<()> {
w.start_structure(tag)?;
w.unsigned(Tag::Context(1), privilege_value(entry.privilege))?;
w.unsigned(Tag::Context(2), entry.auth_mode as u64)?;
if entry.subjects.is_empty() {
w.null(Tag::Context(3))?;
} else {
w.start_array(Tag::Context(3))?;
for subject in &entry.subjects {
w.unsigned(Tag::Anonymous, subject.0)?;
}
w.end_container()?;
}
if entry.targets.is_empty() {
w.null(Tag::Context(4))?;
} else {
w.start_array(Tag::Context(4))?;
for target in &entry.targets {
w.start_structure(Tag::Anonymous)?;
match target.cluster {
Some(id) => w.unsigned(Tag::Context(0), u64::from(id))?,
None => w.null(Tag::Context(0))?,
}
match target.endpoint {
Some(id) => w.unsigned(Tag::Context(1), u64::from(id))?,
None => w.null(Tag::Context(1))?,
}
match target.device_type {
Some(id) => w.unsigned(Tag::Context(2), u64::from(id))?,
None => w.null(Tag::Context(2))?,
}
w.end_container()?;
}
w.end_container()?;
}
w.unsigned(
Tag::Context(FABRIC_INDEX_FIELD),
u64::from(entry.fabric_index.0),
)?;
w.end_container()
}
#[derive(Debug)]
pub struct AccessControl<'a, C: Config, const N: usize, const S: usize, const T: usize> {
acl: &'a RefCell<Acl<C, N, S, T>>,
pending: RefCell<heapless::Vec<EntryChanged<S, T>, PENDING>>,
}
impl<'a, C: Config, const N: usize, const S: usize, const T: usize> AccessControl<'a, C, N, S, T> {
#[must_use]
pub fn new(acl: &'a RefCell<Acl<C, N, S, T>>) -> Self {
Self {
acl,
pending: RefCell::new(heapless::Vec::new()),
}
}
#[must_use]
pub const fn acl(&self) -> &'a RefCell<Acl<C, N, S, T>> {
self.acl
}
pub fn add_admin_for_fabric(
&self,
fabric: FabricIndex,
subject: NodeId,
ctx: &InteractionContext<'_>,
) -> crate::error::Result<()> {
self.acl
.borrow_mut()
.add_admin_for_fabric(fabric, subject)?;
let entry = self.acl.borrow().of_fabric(fabric).last().cloned();
self.record(EntryChanged::for_session(ctx, ChangeType::Added, entry).for_fabric(fabric));
Ok(())
}
pub fn take_changes(&self) -> heapless::Vec<EntryChanged<S, T>, PENDING> {
core::mem::take(&mut self.pending.borrow_mut())
}
fn record(&self, change: EntryChanged<S, T>) {
let mut pending = self.pending.borrow_mut();
if pending.is_full() {
let _ = pending.remove(0);
}
let _ = pending.push(change);
}
fn visible(ctx: &InteractionContext<'_>, index: FabricIndex) -> bool {
!ctx.fabric_filtered || ctx.fabric_index == Some(index)
}
fn read_acl(
&self,
ctx: &InteractionContext<'_>,
w: &mut TlvWriter<'_>,
tag: Tag,
) -> Result<(), Status> {
let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
let acl = self.acl.borrow();
full(w.start_array(tag))?;
for entry in acl.entries().filter(|e| Self::visible(ctx, e.fabric_index)) {
full(write_entry(w, Tag::Anonymous, entry))?;
}
full(w.end_container())
}
}
const fn privilege_value(privilege: Privilege) -> u64 {
match privilege {
Privilege::View => 1,
Privilege::ProxyView => 2,
Privilege::Operate => 3,
Privilege::Manage => 4,
Privilege::Administer => 5,
}
}
const fn privilege_from_value(value: u64) -> Option<Privilege> {
match value {
1 => Some(Privilege::View),
2 => Some(Privilege::ProxyView),
3 => Some(Privilege::Operate),
4 => Some(Privilege::Manage),
5 => Some(Privilege::Administer),
_ => None,
}
}
fn decode_entry<const S: usize, const T: usize>(
reader: &mut TlvReader<'_>,
fabric_index: FabricIndex,
) -> Result<Entry<S, T>, Status> {
let mut privilege = None;
let mut auth_mode = None;
let mut subjects = heapless::Vec::new();
let mut targets = heapless::Vec::new();
loop {
let Some(element) = reader.next_element().map_err(|_| Status::InvalidAction)? else {
return Err(Status::InvalidAction);
};
if element.value == Value::EndOfContainer {
break;
}
match element.tag.context() {
Some(1) => {
let value = element.unsigned().map_err(|_| Status::ConstraintError)?;
privilege = Some(privilege_from_value(value).ok_or(Status::ConstraintError)?);
}
Some(2) => {
let value = element.unsigned().map_err(|_| Status::ConstraintError)?;
let narrowed = u8::try_from(value).map_err(|_| Status::ConstraintError)?;
auth_mode = Some(AuthMode::from_value(narrowed).ok_or(Status::ConstraintError)?);
}
Some(3) => {
if element.value.is_null() {
continue;
}
if element.value.container() != Some(ContainerKind::Array) {
return Err(Status::InvalidAction);
}
loop {
let Some(item) = reader.next_element().map_err(|_| Status::InvalidAction)?
else {
return Err(Status::InvalidAction);
};
if item.value == Value::EndOfContainer {
break;
}
let id = item.unsigned().map_err(|_| Status::ConstraintError)?;
subjects
.push(NodeId(id))
.map_err(|_| Status::ResourceExhausted)?;
}
}
Some(4) => {
if element.value.is_null() {
continue;
}
if element.value.container() != Some(ContainerKind::Array) {
return Err(Status::InvalidAction);
}
loop {
let Some(item) = reader.next_element().map_err(|_| Status::InvalidAction)?
else {
return Err(Status::InvalidAction);
};
if item.value == Value::EndOfContainer {
break;
}
if item.value.container() != Some(ContainerKind::Structure) {
return Err(Status::InvalidAction);
}
targets
.push(decode_target(reader)?)
.map_err(|_| Status::ResourceExhausted)?;
}
}
_ => reader
.skip_value(&element)
.map_err(|_| Status::InvalidAction)?,
}
}
Ok(Entry {
fabric_index,
privilege: privilege.ok_or(Status::InvalidAction)?,
auth_mode: auth_mode.ok_or(Status::InvalidAction)?,
subjects,
targets,
})
}
fn decode_target(reader: &mut TlvReader<'_>) -> Result<Target, Status> {
let mut target = Target::default();
loop {
let Some(element) = reader.next_element().map_err(|_| Status::InvalidAction)? else {
return Err(Status::InvalidAction);
};
if element.value == Value::EndOfContainer {
break;
}
if element.value.is_null() {
continue;
}
let value = element.unsigned().map_err(|_| Status::ConstraintError)?;
match element.tag.context() {
Some(0) => {
target.cluster = Some(u32::try_from(value).map_err(|_| Status::ConstraintError)?);
}
Some(1) => {
target.endpoint = Some(u16::try_from(value).map_err(|_| Status::ConstraintError)?);
}
Some(2) => {
target.device_type =
Some(u32::try_from(value).map_err(|_| Status::ConstraintError)?);
}
_ => {}
}
}
if !target.is_valid() {
return Err(Status::ConstraintError);
}
Ok(target)
}
impl<C: Config, const N: usize, const S: usize, const T: usize> ClusterHandler
for AccessControl<'_, C, N, S, T>
{
fn on_lifecycle(&self, event: crate::im::Lifecycle) {
if let crate::im::Lifecycle::FabricRemoved(fabric) = event {
self.acl.borrow_mut().remove_fabric(fabric);
}
}
fn read(
&self,
resolved: &Resolved<'_>,
ctx: &InteractionContext<'_>,
w: &mut TlvWriter<'_>,
tag: Tag,
) -> Result<(), Status> {
let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
match resolved.attribute {
ACL => self.read_acl(ctx, w, tag),
SUBJECTS_PER_ENTRY => full(w.unsigned(tag, S as u64)),
TARGETS_PER_ENTRY => full(w.unsigned(tag, T as u64)),
ENTRIES_PER_FABRIC => full(w.unsigned(
tag,
<Acl<C, N, S, T> as crate::config::Capacity>::PER_FABRIC as u64,
)),
_ => Err(Status::UnsupportedAttribute),
}
}
fn write(
&self,
resolved: &Resolved<'_>,
data: &[u8],
op: WriteOp,
ctx: &InteractionContext<'_>,
) -> Result<(), Status> {
if resolved.attribute != ACL {
return Err(Status::UnsupportedWrite);
}
let Some(fabric_index) = ctx.fabric_index else {
return Err(Status::UnsupportedAccess);
};
let mut reader = TlvReader::new_in(data, ContainerKind::Structure);
let element = reader
.next_element()
.map_err(|_| Status::InvalidAction)?
.ok_or(Status::InvalidAction)?;
let mut acl = self.acl.borrow_mut();
match op {
WriteOp::Replace => {
if element.value.container() != Some(ContainerKind::Array) {
return Err(Status::InvalidAction);
}
let mut replacement: heapless::Vec<Entry<S, T>, N> = heapless::Vec::new();
loop {
let Some(item) = reader.next_element().map_err(|_| Status::InvalidAction)?
else {
return Err(Status::InvalidAction);
};
if item.value == Value::EndOfContainer {
break;
}
if item.value.container() != Some(ContainerKind::Structure) {
return Err(Status::InvalidAction);
}
replacement
.push(decode_entry(&mut reader, fabric_index)?)
.map_err(|_| Status::ResourceExhausted)?;
}
let removed: heapless::Vec<Entry<S, T>, PENDING> =
acl.of_fabric(fabric_index).take(PENDING).cloned().collect();
acl.replace_fabric(fabric_index, replacement)
.map_err(|_| Status::ConstraintError)?;
let added: heapless::Vec<Entry<S, T>, PENDING> =
acl.of_fabric(fabric_index).take(PENDING).cloned().collect();
drop(acl);
let mut old_entries = removed.into_iter();
let mut new_entries = added.into_iter();
loop {
let (change_type, entry) = match (new_entries.next(), old_entries.next()) {
(Some(entry), Some(_)) => (ChangeType::Changed, entry),
(Some(entry), None) => (ChangeType::Added, entry),
(None, Some(entry)) => (ChangeType::Removed, entry),
(None, None) => break,
};
self.record(EntryChanged::for_session(ctx, change_type, Some(entry)));
}
}
WriteOp::Append => {
if element.value.container() != Some(ContainerKind::Structure) {
return Err(Status::InvalidAction);
}
let entry = decode_entry::<S, T>(&mut reader, fabric_index)?;
let recorded = entry.clone();
acl.add(entry).map_err(|e| match e.code() {
crate::ErrorCode::NoSpace => Status::ResourceExhausted,
_ => Status::ConstraintError,
})?;
drop(acl);
self.record(EntryChanged::for_session(
ctx,
ChangeType::Added,
Some(recorded),
));
}
}
Ok(())
}
}
impl<C: Config, const N: usize, const S: usize, const T: usize> Cluster
for AccessControl<'_, C, N, S, T>
{
const ID: ClusterId = ID;
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::DefaultConfig;
type TestAcl = Acl<DefaultConfig>;
#[test]
fn the_wire_values_are_section_9_10_5_2s_and_not_the_enums_order() {
assert_eq!(privilege_value(Privilege::View), 1);
assert_eq!(privilege_value(Privilege::ProxyView), 2);
assert_eq!(privilege_value(Privilege::Operate), 3);
assert_eq!(privilege_value(Privilege::Administer), 5);
for value in 1..=5u64 {
let privilege = privilege_from_value(value).expect("defined");
assert_eq!(privilege_value(privilege), value, "round trips");
}
assert!(privilege_from_value(0).is_none());
assert!(privilege_from_value(6).is_none());
}
#[test]
fn the_descriptor_needs_administer_in_both_directions() {
let descriptor = cluster();
let acl = descriptor.attribute(ACL).expect("ACL attribute");
assert_eq!(acl.access.read, Some(Privilege::Administer));
assert_eq!(acl.access.write, Some(Privilege::Administer));
assert!(acl.access.is_fabric_scoped());
}
#[test]
fn the_minima_are_reported_from_the_list_that_holds_them() {
let acl = RefCell::new(TestAcl::new());
let cluster_impl = AccessControl::<_, 20, 4, 3>::new(&acl);
assert_eq!(cluster_impl.acl().borrow().len(), 0);
assert_eq!(<TestAcl as crate::config::Capacity>::PER_FABRIC, 4);
const {
assert!(
<TestAcl as crate::config::Capacity>::TOTAL
>= <TestAcl as crate::config::Capacity>::PER_FABRIC * DefaultConfig::FABRICS
);
}
}
}