matc 0.1.2

Matter protocol library (controller side)
Documentation
//! Matter TLV encoders and decoders for TLS Certificate Management Cluster
//! Cluster ID: 0x0801
//!
//! This file is automatically generated from TLSCertificateManagement.xml

use crate::tlv;
use anyhow;
use serde_json;


// Import serialization helpers for octet strings
use crate::clusters::helpers::{serialize_opt_bytes_as_hex, serialize_opt_vec_bytes_as_hex};

// Struct definitions

#[derive(Debug, serde::Serialize)]
pub struct TLSCert {
    pub caid: Option<u8>,
    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
    pub certificate: Option<Vec<u8>>,
}

#[derive(Debug, serde::Serialize)]
pub struct TLSClientCertificateDetail {
    pub ccdid: Option<u8>,
    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
    pub client_certificate: Option<Vec<u8>>,
    #[serde(serialize_with = "serialize_opt_vec_bytes_as_hex")]
    pub intermediate_certificates: Option<Vec<Vec<u8>>>,
}

// Command encoders

/// Encode ProvisionRootCertificate command (0x00)
pub fn encode_provision_root_certificate(certificate: Vec<u8>, caid: Option<u8>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::OctetString(certificate)).into(),
        (1, tlv::TlvItemValueEnc::UInt8(caid.unwrap_or(0))).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode FindRootCertificate command (0x02)
pub fn encode_find_root_certificate(caid: Option<u8>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(caid.unwrap_or(0))).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode LookupRootCertificate command (0x04)
pub fn encode_lookup_root_certificate(fingerprint: Vec<u8>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::OctetString(fingerprint)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode RemoveRootCertificate command (0x06)
pub fn encode_remove_root_certificate(caid: u8) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(caid)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode ClientCSR command (0x07)
pub fn encode_client_csr(nonce: Vec<u8>, ccdid: Option<u8>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::OctetString(nonce)).into(),
        (1, tlv::TlvItemValueEnc::UInt8(ccdid.unwrap_or(0))).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode ProvisionClientCertificate command (0x09)
pub fn encode_provision_client_certificate(ccdid: u8, client_certificate: Vec<u8>, intermediate_certificates: Vec<Vec<u8>>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(ccdid)).into(),
        (1, tlv::TlvItemValueEnc::OctetString(client_certificate)).into(),
        (2, tlv::TlvItemValueEnc::StructAnon(intermediate_certificates.into_iter().map(|v| (0, tlv::TlvItemValueEnc::OctetString(v)).into()).collect())).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode FindClientCertificate command (0x0A)
pub fn encode_find_client_certificate(ccdid: Option<u8>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(ccdid.unwrap_or(0))).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode LookupClientCertificate command (0x0C)
pub fn encode_lookup_client_certificate(fingerprint: Vec<u8>) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::OctetString(fingerprint)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

/// Encode RemoveClientCertificate command (0x0E)
pub fn encode_remove_client_certificate(ccdid: u8) -> anyhow::Result<Vec<u8>> {
    let tlv = tlv::TlvItemEnc {
        tag: 0,
        value: tlv::TlvItemValueEnc::StructInvisible(vec![
        (0, tlv::TlvItemValueEnc::UInt8(ccdid)).into(),
        ]),
    };
    Ok(tlv.encode()?)
}

// Attribute decoders

/// Decode MaxRootCertificates attribute (0x0000)
pub fn decode_max_root_certificates(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u8)
    } else {
        Err(anyhow::anyhow!("Expected UInt8"))
    }
}

/// Decode ProvisionedRootCertificates attribute (0x0001)
pub fn decode_provisioned_root_certificates(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<TLSCert>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(TLSCert {
                caid: item.get_int(&[0]).map(|v| v as u8),
                certificate: item.get_octet_string_owned(&[1]),
            });
        }
    }
    Ok(res)
}

/// Decode MaxClientCertificates attribute (0x0002)
pub fn decode_max_client_certificates(inp: &tlv::TlvItemValue) -> anyhow::Result<u8> {
    if let tlv::TlvItemValue::Int(v) = inp {
        Ok(*v as u8)
    } else {
        Err(anyhow::anyhow!("Expected UInt8"))
    }
}

/// Decode ProvisionedClientCertificates attribute (0x0003)
pub fn decode_provisioned_client_certificates(inp: &tlv::TlvItemValue) -> anyhow::Result<Vec<TLSClientCertificateDetail>> {
    let mut res = Vec::new();
    if let tlv::TlvItemValue::List(v) = inp {
        for item in v {
            res.push(TLSClientCertificateDetail {
                ccdid: item.get_int(&[0]).map(|v| v as u8),
                client_certificate: item.get_octet_string_owned(&[1]),
                intermediate_certificates: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[2]) {
                        let items: Vec<Vec<u8>> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::OctetString(v) = &e.value { Some(v.clone()) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
            });
        }
    }
    Ok(res)
}


// JSON dispatcher function

/// Decode attribute value and return as JSON string
///
/// # Parameters
/// * `cluster_id` - The cluster identifier
/// * `attribute_id` - The attribute identifier
/// * `tlv_value` - The TLV value to decode
///
/// # Returns
/// JSON string representation of the decoded value or error
pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
    // Verify this is the correct cluster
    if cluster_id != 0x0801 {
        return format!("{{\"error\": \"Invalid cluster ID. Expected 0x0801, got {}\"}}", cluster_id);
    }

    match attribute_id {
        0x0000 => {
            match decode_max_root_certificates(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0001 => {
            match decode_provisioned_root_certificates(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0002 => {
            match decode_max_client_certificates(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        0x0003 => {
            match decode_provisioned_client_certificates(tlv_value) {
                Ok(value) => serde_json::to_string(&value).unwrap_or_else(|_| "null".to_string()),
                Err(e) => format!("{{\"error\": \"{}\"}}", e),
            }
        }
        _ => format!("{{\"error\": \"Unknown attribute ID: {}\"}}", attribute_id),
    }
}

/// Get list of all attributes supported by this cluster
///
/// # Returns
/// Vector of tuples containing (attribute_id, attribute_name)
pub fn get_attribute_list() -> Vec<(u32, &'static str)> {
    vec![
        (0x0000, "MaxRootCertificates"),
        (0x0001, "ProvisionedRootCertificates"),
        (0x0002, "MaxClientCertificates"),
        (0x0003, "ProvisionedClientCertificates"),
    ]
}

#[derive(Debug, serde::Serialize)]
pub struct ProvisionRootCertificateResponse {
    pub caid: Option<u8>,
}

#[derive(Debug, serde::Serialize)]
pub struct FindRootCertificateResponse {
    pub certificate_details: Option<Vec<TLSCert>>,
}

#[derive(Debug, serde::Serialize)]
pub struct LookupRootCertificateResponse {
    pub caid: Option<u8>,
}

#[derive(Debug, serde::Serialize)]
pub struct ClientCSRResponse {
    pub ccdid: Option<u8>,
    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
    pub csr: Option<Vec<u8>>,
    #[serde(serialize_with = "serialize_opt_bytes_as_hex")]
    pub nonce_signature: Option<Vec<u8>>,
}

#[derive(Debug, serde::Serialize)]
pub struct FindClientCertificateResponse {
    pub certificate_details: Option<Vec<TLSClientCertificateDetail>>,
}

#[derive(Debug, serde::Serialize)]
pub struct LookupClientCertificateResponse {
    pub ccdid: Option<u8>,
}

// Command response decoders

/// Decode ProvisionRootCertificateResponse command response (01)
pub fn decode_provision_root_certificate_response(inp: &tlv::TlvItemValue) -> anyhow::Result<ProvisionRootCertificateResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(ProvisionRootCertificateResponse {
                caid: item.get_int(&[0]).map(|v| v as u8),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode FindRootCertificateResponse command response (03)
pub fn decode_find_root_certificate_response(inp: &tlv::TlvItemValue) -> anyhow::Result<FindRootCertificateResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(FindRootCertificateResponse {
                certificate_details: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[0]) {
                        let mut items = Vec::new();
                        for list_item in l {
                            items.push(TLSCert {
                caid: list_item.get_int(&[0]).map(|v| v as u8),
                certificate: list_item.get_octet_string_owned(&[1]),
                            });
                        }
                        Some(items)
                    } else {
                        None
                    }
                },
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode LookupRootCertificateResponse command response (05)
pub fn decode_lookup_root_certificate_response(inp: &tlv::TlvItemValue) -> anyhow::Result<LookupRootCertificateResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(LookupRootCertificateResponse {
                caid: item.get_int(&[0]).map(|v| v as u8),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode ClientCSRResponse command response (08)
pub fn decode_client_csr_response(inp: &tlv::TlvItemValue) -> anyhow::Result<ClientCSRResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(ClientCSRResponse {
                ccdid: item.get_int(&[0]).map(|v| v as u8),
                csr: item.get_octet_string_owned(&[1]),
                nonce_signature: item.get_octet_string_owned(&[2]),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode FindClientCertificateResponse command response (0B)
pub fn decode_find_client_certificate_response(inp: &tlv::TlvItemValue) -> anyhow::Result<FindClientCertificateResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(FindClientCertificateResponse {
                certificate_details: {
                    if let Some(tlv::TlvItemValue::List(l)) = item.get(&[0]) {
                        let mut items = Vec::new();
                        for list_item in l {
                            items.push(TLSClientCertificateDetail {
                ccdid: list_item.get_int(&[0]).map(|v| v as u8),
                client_certificate: list_item.get_octet_string_owned(&[1]),
                intermediate_certificates: {
                    if let Some(tlv::TlvItemValue::List(l)) = list_item.get(&[2]) {
                        let items: Vec<Vec<u8>> = l.iter().filter_map(|e| { if let tlv::TlvItemValue::OctetString(v) = &e.value { Some(v.clone()) } else { None } }).collect();
                        Some(items)
                    } else {
                        None
                    }
                },
                            });
                        }
                        Some(items)
                    } else {
                        None
                    }
                },
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}

/// Decode LookupClientCertificateResponse command response (0D)
pub fn decode_lookup_client_certificate_response(inp: &tlv::TlvItemValue) -> anyhow::Result<LookupClientCertificateResponse> {
    if let tlv::TlvItemValue::List(_fields) = inp {
        let item = tlv::TlvItem { tag: 0, value: inp.clone() };
        Ok(LookupClientCertificateResponse {
                ccdid: item.get_int(&[0]).map(|v| v as u8),
        })
    } else {
        Err(anyhow::anyhow!("Expected struct fields"))
    }
}