use heapless::Vec;
use crate::error::{Error, ErrorCode, Result};
use crate::msg::{CaseAuthenticatedTag, FabricId, NodeId};
use crate::tlv::{ContainerKind, Element, Tag, TlvReader, TlvWriter, Value};
pub const MAX_RDNS: usize = 5;
pub const MAX_NOC_CATS: usize = 3;
const PRINTABLE_STRING_OFFSET: u8 = 0x80;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
#[non_exhaustive]
pub enum DnAttributeKind {
CommonName = 1,
Surname = 2,
SerialNum = 3,
CountryName = 4,
LocalityName = 5,
StateOrProvinceName = 6,
OrgName = 7,
OrgUnitName = 8,
Title = 9,
Name = 10,
GivenName = 11,
Initials = 12,
GenQualifier = 13,
DnQualifier = 14,
Pseudonym = 15,
DomainComponent = 16,
MatterNodeId = 17,
MatterFirmwareSigningId = 18,
MatterIcacId = 19,
MatterRcacId = 20,
MatterFabricId = 21,
MatterNocCat = 22,
MatterVvsId = 23,
}
impl DnAttributeKind {
#[must_use]
pub const fn from_tag(tag: u8) -> Option<Self> {
Some(match tag {
1 => Self::CommonName,
2 => Self::Surname,
3 => Self::SerialNum,
4 => Self::CountryName,
5 => Self::LocalityName,
6 => Self::StateOrProvinceName,
7 => Self::OrgName,
8 => Self::OrgUnitName,
9 => Self::Title,
10 => Self::Name,
11 => Self::GivenName,
12 => Self::Initials,
13 => Self::GenQualifier,
14 => Self::DnQualifier,
15 => Self::Pseudonym,
16 => Self::DomainComponent,
17 => Self::MatterNodeId,
18 => Self::MatterFirmwareSigningId,
19 => Self::MatterIcacId,
20 => Self::MatterRcacId,
21 => Self::MatterFabricId,
22 => Self::MatterNocCat,
23 => Self::MatterVvsId,
_ => return None,
})
}
#[must_use]
pub const fn tag(self) -> u8 {
self as u8
}
#[must_use]
pub const fn is_string(self) -> bool {
(self as u8) <= 16
}
#[must_use]
pub const fn is_matter_specific(self) -> bool {
!self.is_string()
}
#[must_use]
pub const fn has_printable_string_form(self) -> bool {
matches!(self as u8, 1..=15)
}
#[must_use]
pub const fn scalar_octets(self) -> Option<usize> {
match self {
Self::MatterNocCat => Some(4),
_ if self.is_matter_specific() => Some(8),
_ => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DnAttribute<'a> {
pub kind: DnAttributeKind,
pub printable_string: bool,
pub value: DnValue<'a>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DnValue<'a> {
Str(&'a str),
Uint(u64),
}
impl<'a> DnAttribute<'a> {
#[must_use]
pub const fn string(kind: DnAttributeKind, value: &'a str) -> Self {
Self {
kind,
printable_string: false,
value: DnValue::Str(value),
}
}
#[must_use]
pub const fn printable(kind: DnAttributeKind, value: &'a str) -> Self {
Self {
kind,
printable_string: true,
value: DnValue::Str(value),
}
}
#[must_use]
pub const fn uint(kind: DnAttributeKind, value: u64) -> Self {
Self {
kind,
printable_string: false,
value: DnValue::Uint(value),
}
}
#[must_use]
pub const fn node_id(id: NodeId) -> Self {
Self::uint(DnAttributeKind::MatterNodeId, id.0)
}
#[must_use]
pub const fn fabric_id(id: FabricId) -> Self {
Self::uint(DnAttributeKind::MatterFabricId, id.0)
}
#[must_use]
pub const fn noc_cat(cat: CaseAuthenticatedTag) -> Self {
Self::uint(DnAttributeKind::MatterNocCat, cat.0 as u64)
}
#[must_use]
pub const fn tag(&self) -> u8 {
if self.printable_string {
self.kind.tag().wrapping_add(PRINTABLE_STRING_OFFSET)
} else {
self.kind.tag()
}
}
#[must_use]
pub const fn as_uint(&self) -> Option<u64> {
match self.value {
DnValue::Uint(v) => Some(v),
DnValue::Str(_) => None,
}
}
#[must_use]
pub const fn as_str(&self) -> Option<&'a str> {
match self.value {
DnValue::Str(s) => Some(s),
DnValue::Uint(_) => None,
}
}
pub fn validate(&self) -> Result<()> {
match (self.kind.is_string(), self.value) {
(true, DnValue::Str(_)) => {}
(false, DnValue::Uint(v)) => {
if self.kind.scalar_octets() == Some(4) && v > u64::from(u32::MAX) {
return Err(Error::new(ErrorCode::CertInvalid));
}
}
_ => return Err(Error::new(ErrorCode::CertInvalid)),
}
if self.printable_string && !self.kind.has_printable_string_form() {
return Err(Error::new(ErrorCode::CertInvalid));
}
Ok(())
}
pub fn encode(&self, writer: &mut TlvWriter<'_>) -> Result<()> {
self.validate()?;
let tag = Tag::Context(self.tag());
match self.value {
DnValue::Str(s) => writer.utf8(tag, s),
DnValue::Uint(v) => writer.unsigned(tag, v),
}
}
pub fn decode(element: &Element<'a>) -> Result<Self> {
let Some(raw_tag) = element.tag.context() else {
return Err(Error::new(ErrorCode::CertInvalid));
};
let printable_string = raw_tag >= PRINTABLE_STRING_OFFSET;
let base = raw_tag.wrapping_sub(if printable_string {
PRINTABLE_STRING_OFFSET
} else {
0
});
let Some(kind) = DnAttributeKind::from_tag(base) else {
return Err(Error::new(ErrorCode::CertInvalid));
};
let value = match element.value {
Value::Utf8(s) => DnValue::Str(s),
Value::Unsigned(v) => DnValue::Uint(v),
_ => return Err(Error::new(ErrorCode::CertInvalid)),
};
let attribute = Self {
kind,
printable_string,
value,
};
attribute.validate()?;
Ok(attribute)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DistinguishedName<'a> {
attributes: Vec<DnAttribute<'a>, MAX_RDNS>,
}
impl<'a> DistinguishedName<'a> {
#[must_use]
pub const fn new() -> Self {
Self {
attributes: Vec::new(),
}
}
pub fn push(&mut self, attribute: DnAttribute<'a>) -> Result<()> {
attribute.validate()?;
self.attributes
.push(attribute)
.map_err(|_| Error::new(ErrorCode::CertInvalid))
}
#[must_use]
pub fn attributes(&self) -> &[DnAttribute<'a>] {
&self.attributes
}
#[must_use]
pub fn len(&self) -> usize {
self.attributes.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.attributes.is_empty()
}
#[must_use]
pub fn count(&self, kind: DnAttributeKind) -> usize {
self.attributes.iter().filter(|a| a.kind == kind).count()
}
#[must_use]
pub fn single_uint(&self, kind: DnAttributeKind) -> Option<u64> {
let mut found = None;
for attribute in &self.attributes {
if attribute.kind == kind {
if found.is_some() {
return None;
}
found = attribute.as_uint();
}
}
found
}
#[must_use]
pub fn node_id(&self) -> Option<NodeId> {
self.single_uint(DnAttributeKind::MatterNodeId).map(NodeId)
}
#[must_use]
pub fn fabric_id(&self) -> Option<FabricId> {
self.single_uint(DnAttributeKind::MatterFabricId)
.map(FabricId)
}
#[must_use]
#[expect(
clippy::cast_possible_truncation,
reason = "a NOC CAT is the low 32 bits of a matter-noc-cat DN value (§6.5.6.3)"
)]
pub fn noc_cats(&self) -> Vec<CaseAuthenticatedTag, MAX_NOC_CATS> {
let mut out = Vec::new();
for attribute in &self.attributes {
if attribute.kind == DnAttributeKind::MatterNocCat
&& let Some(value) = attribute.as_uint()
{
let _ = out.push(CaseAuthenticatedTag(value as u32));
}
}
out
}
pub fn encode(&self, writer: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
if self.attributes.is_empty() {
return Err(Error::new(ErrorCode::CertInvalid));
}
writer.start_list(tag)?;
for attribute in &self.attributes {
attribute.encode(writer)?;
}
writer.end_container()
}
pub fn decode(reader: &mut TlvReader<'a>) -> Result<Self> {
let mut dn = Self::new();
loop {
let Some(element) = reader.next_element()? else {
return Err(Error::new(ErrorCode::CertInvalid));
};
if element.value == Value::EndOfContainer {
break;
}
dn.push(DnAttribute::decode(&element)?)?;
}
if dn.attributes.is_empty() {
return Err(Error::new(ErrorCode::CertInvalid));
}
Ok(dn)
}
}
pub const DN_CONTAINER: ContainerKind = ContainerKind::List;