1use heapless::Vec;
22
23use crate::error::{Error, ErrorCode, Result};
24use crate::msg::{CaseAuthenticatedTag, FabricId, NodeId};
25use crate::tlv::{ContainerKind, Element, Tag, TlvReader, TlvWriter, Value};
26
27pub const MAX_RDNS: usize = 5;
30
31pub const MAX_NOC_CATS: usize = 3;
33
34const PRINTABLE_STRING_OFFSET: u8 = 0x80;
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
41#[repr(u8)]
42#[non_exhaustive]
43pub enum DnAttributeKind {
44 CommonName = 1,
46 Surname = 2,
48 SerialNum = 3,
50 CountryName = 4,
52 LocalityName = 5,
54 StateOrProvinceName = 6,
56 OrgName = 7,
58 OrgUnitName = 8,
60 Title = 9,
62 Name = 10,
64 GivenName = 11,
66 Initials = 12,
68 GenQualifier = 13,
70 DnQualifier = 14,
72 Pseudonym = 15,
74 DomainComponent = 16,
76 MatterNodeId = 17,
78 MatterFirmwareSigningId = 18,
80 MatterIcacId = 19,
82 MatterRcacId = 20,
84 MatterFabricId = 21,
86 MatterNocCat = 22,
88 MatterVvsId = 23,
90}
91
92impl DnAttributeKind {
93 #[must_use]
95 pub const fn from_tag(tag: u8) -> Option<Self> {
96 Some(match tag {
97 1 => Self::CommonName,
98 2 => Self::Surname,
99 3 => Self::SerialNum,
100 4 => Self::CountryName,
101 5 => Self::LocalityName,
102 6 => Self::StateOrProvinceName,
103 7 => Self::OrgName,
104 8 => Self::OrgUnitName,
105 9 => Self::Title,
106 10 => Self::Name,
107 11 => Self::GivenName,
108 12 => Self::Initials,
109 13 => Self::GenQualifier,
110 14 => Self::DnQualifier,
111 15 => Self::Pseudonym,
112 16 => Self::DomainComponent,
113 17 => Self::MatterNodeId,
114 18 => Self::MatterFirmwareSigningId,
115 19 => Self::MatterIcacId,
116 20 => Self::MatterRcacId,
117 21 => Self::MatterFabricId,
118 22 => Self::MatterNocCat,
119 23 => Self::MatterVvsId,
120 _ => return None,
121 })
122 }
123
124 #[must_use]
126 pub const fn tag(self) -> u8 {
127 self as u8
128 }
129
130 #[must_use]
133 pub const fn is_string(self) -> bool {
134 (self as u8) <= 16
135 }
136
137 #[must_use]
139 pub const fn is_matter_specific(self) -> bool {
140 !self.is_string()
141 }
142
143 #[must_use]
148 pub const fn has_printable_string_form(self) -> bool {
149 matches!(self as u8, 1..=15)
150 }
151
152 #[must_use]
158 pub const fn scalar_octets(self) -> Option<usize> {
159 match self {
160 Self::MatterNocCat => Some(4),
161 _ if self.is_matter_specific() => Some(8),
162 _ => None,
163 }
164 }
165}
166
167#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169pub struct DnAttribute<'a> {
170 pub kind: DnAttributeKind,
172 pub printable_string: bool,
176 pub value: DnValue<'a>,
178}
179
180#[derive(Debug, Clone, Copy, PartialEq, Eq)]
182pub enum DnValue<'a> {
183 Str(&'a str),
185 Uint(u64),
187}
188
189impl<'a> DnAttribute<'a> {
190 #[must_use]
192 pub const fn string(kind: DnAttributeKind, value: &'a str) -> Self {
193 Self {
194 kind,
195 printable_string: false,
196 value: DnValue::Str(value),
197 }
198 }
199
200 #[must_use]
202 pub const fn printable(kind: DnAttributeKind, value: &'a str) -> Self {
203 Self {
204 kind,
205 printable_string: true,
206 value: DnValue::Str(value),
207 }
208 }
209
210 #[must_use]
212 pub const fn uint(kind: DnAttributeKind, value: u64) -> Self {
213 Self {
214 kind,
215 printable_string: false,
216 value: DnValue::Uint(value),
217 }
218 }
219
220 #[must_use]
222 pub const fn node_id(id: NodeId) -> Self {
223 Self::uint(DnAttributeKind::MatterNodeId, id.0)
224 }
225
226 #[must_use]
228 pub const fn fabric_id(id: FabricId) -> Self {
229 Self::uint(DnAttributeKind::MatterFabricId, id.0)
230 }
231
232 #[must_use]
234 pub const fn noc_cat(cat: CaseAuthenticatedTag) -> Self {
235 Self::uint(DnAttributeKind::MatterNocCat, cat.0 as u64)
236 }
237
238 #[must_use]
240 pub const fn tag(&self) -> u8 {
241 if self.printable_string {
242 self.kind.tag().wrapping_add(PRINTABLE_STRING_OFFSET)
243 } else {
244 self.kind.tag()
245 }
246 }
247
248 #[must_use]
250 pub const fn as_uint(&self) -> Option<u64> {
251 match self.value {
252 DnValue::Uint(v) => Some(v),
253 DnValue::Str(_) => None,
254 }
255 }
256
257 #[must_use]
259 pub const fn as_str(&self) -> Option<&'a str> {
260 match self.value {
261 DnValue::Str(s) => Some(s),
262 DnValue::Uint(_) => None,
263 }
264 }
265
266 pub fn validate(&self) -> Result<()> {
271 match (self.kind.is_string(), self.value) {
272 (true, DnValue::Str(_)) => {}
273 (false, DnValue::Uint(v)) => {
274 if self.kind.scalar_octets() == Some(4) && v > u64::from(u32::MAX) {
275 return Err(Error::new(ErrorCode::CertInvalid));
276 }
277 }
278 _ => return Err(Error::new(ErrorCode::CertInvalid)),
279 }
280 if self.printable_string && !self.kind.has_printable_string_form() {
281 return Err(Error::new(ErrorCode::CertInvalid));
282 }
283 Ok(())
284 }
285
286 pub fn encode(&self, writer: &mut TlvWriter<'_>) -> Result<()> {
288 self.validate()?;
289 let tag = Tag::Context(self.tag());
290 match self.value {
291 DnValue::Str(s) => writer.utf8(tag, s),
292 DnValue::Uint(v) => writer.unsigned(tag, v),
293 }
294 }
295
296 pub fn decode(element: &Element<'a>) -> Result<Self> {
298 let Some(raw_tag) = element.tag.context() else {
299 return Err(Error::new(ErrorCode::CertInvalid));
300 };
301 let printable_string = raw_tag >= PRINTABLE_STRING_OFFSET;
302 let base = raw_tag.wrapping_sub(if printable_string {
303 PRINTABLE_STRING_OFFSET
304 } else {
305 0
306 });
307 let Some(kind) = DnAttributeKind::from_tag(base) else {
308 return Err(Error::new(ErrorCode::CertInvalid));
309 };
310 let value = match element.value {
311 Value::Utf8(s) => DnValue::Str(s),
312 Value::Unsigned(v) => DnValue::Uint(v),
313 _ => return Err(Error::new(ErrorCode::CertInvalid)),
314 };
315 let attribute = Self {
316 kind,
317 printable_string,
318 value,
319 };
320 attribute.validate()?;
321 Ok(attribute)
322 }
323}
324
325#[derive(Debug, Clone, Default, PartialEq, Eq)]
327pub struct DistinguishedName<'a> {
328 attributes: Vec<DnAttribute<'a>, MAX_RDNS>,
329}
330
331impl<'a> DistinguishedName<'a> {
332 #[must_use]
335 pub const fn new() -> Self {
336 Self {
337 attributes: Vec::new(),
338 }
339 }
340
341 pub fn push(&mut self, attribute: DnAttribute<'a>) -> Result<()> {
346 attribute.validate()?;
347 self.attributes
348 .push(attribute)
349 .map_err(|_| Error::new(ErrorCode::CertInvalid))
350 }
351
352 #[must_use]
354 pub fn attributes(&self) -> &[DnAttribute<'a>] {
355 &self.attributes
356 }
357
358 #[must_use]
360 pub fn len(&self) -> usize {
361 self.attributes.len()
362 }
363
364 #[must_use]
366 pub fn is_empty(&self) -> bool {
367 self.attributes.is_empty()
368 }
369
370 #[must_use]
372 pub fn count(&self, kind: DnAttributeKind) -> usize {
373 self.attributes.iter().filter(|a| a.kind == kind).count()
374 }
375
376 #[must_use]
382 pub fn single_uint(&self, kind: DnAttributeKind) -> Option<u64> {
383 let mut found = None;
384 for attribute in &self.attributes {
385 if attribute.kind == kind {
386 if found.is_some() {
387 return None;
388 }
389 found = attribute.as_uint();
390 }
391 }
392 found
393 }
394
395 #[must_use]
397 pub fn node_id(&self) -> Option<NodeId> {
398 self.single_uint(DnAttributeKind::MatterNodeId).map(NodeId)
399 }
400
401 #[must_use]
403 pub fn fabric_id(&self) -> Option<FabricId> {
404 self.single_uint(DnAttributeKind::MatterFabricId)
405 .map(FabricId)
406 }
407
408 #[must_use]
410 #[expect(
411 clippy::cast_possible_truncation,
412 reason = "a NOC CAT is the low 32 bits of a matter-noc-cat DN value (§6.5.6.3)"
413 )]
414 pub fn noc_cats(&self) -> Vec<CaseAuthenticatedTag, MAX_NOC_CATS> {
415 let mut out = Vec::new();
416 for attribute in &self.attributes {
417 if attribute.kind == DnAttributeKind::MatterNocCat
418 && let Some(value) = attribute.as_uint()
419 {
420 let _ = out.push(CaseAuthenticatedTag(value as u32));
423 }
424 }
425 out
426 }
427
428 pub fn encode(&self, writer: &mut TlvWriter<'_>, tag: Tag) -> Result<()> {
430 if self.attributes.is_empty() {
431 return Err(Error::new(ErrorCode::CertInvalid));
432 }
433 writer.start_list(tag)?;
434 for attribute in &self.attributes {
435 attribute.encode(writer)?;
436 }
437 writer.end_container()
438 }
439
440 pub fn decode(reader: &mut TlvReader<'a>) -> Result<Self> {
442 let mut dn = Self::new();
443 loop {
444 let Some(element) = reader.next_element()? else {
445 return Err(Error::new(ErrorCode::CertInvalid));
446 };
447 if element.value == Value::EndOfContainer {
448 break;
449 }
450 dn.push(DnAttribute::decode(&element)?)?;
451 }
452 if dn.attributes.is_empty() {
453 return Err(Error::new(ErrorCode::CertInvalid));
454 }
455 Ok(dn)
456 }
457}
458
459pub const DN_CONTAINER: ContainerKind = ContainerKind::List;