use crate::tlv;
use anyhow;
use serde_json;
use crate::clusters::helpers::{serialize_opt_bytes_as_hex, serialize_opt_vec_bytes_as_hex};
#[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>>>,
}
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()?)
}
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()?)
}
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()?)
}
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()?)
}
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()?)
}
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()?)
}
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()?)
}
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()?)
}
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()?)
}
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"))
}
}
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)
}
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"))
}
}
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)
}
pub fn decode_attribute_json(cluster_id: u32, attribute_id: u32, tlv_value: &crate::tlv::TlvItemValue) -> String {
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),
}
}
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>,
}
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"))
}
}
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"))
}
}
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"))
}
}
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"))
}
}
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"))
}
}
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"))
}
}