Skip to main content

spodes_rs/classes/
data_protection.rs

1use crate::interface::InterfaceClass;
2use crate::obis::ObisCode;
3use crate::types::attrs::ProtectionObject;
4use crate::types::{BerError, CosemDataType};
5use serde::{Deserialize, Serialize};
6use std::any::Any;
7
8/// Configuration structure used to build a [`DataProtection`] object.
9#[derive(Clone, Serialize, Deserialize, Debug)]
10pub struct DataProtectionConfig {
11    /// Attribute 1: the object's logical name (OBIS code).
12    pub logical_name: ObisCode,
13    /// Attribute 2: protected data buffer (octet-string).
14    pub protection_buffer: Vec<u8>,
15    /// Attribute 3: array of protection object list entries.
16    pub protection_object_list: Vec<ProtectionObject>,
17    /// Attribute 4: array of GET protection parameters.
18    pub protection_parameters_get: Vec<Vec<u8>>,
19    /// Attribute 5: array of SET protection parameters.
20    pub protection_parameters_set: Vec<Vec<u8>>,
21    /// Attribute 6: the protection required for the operations (enum).
22    pub required_protection: u8,
23}
24
25/// `Data protection` interface class (class_id = 30, version = 0) per
26/// IEC 62056-6-2 ยง4.4.9. Provides end-to-end protection of grouped attributes
27/// and method invocations.
28///
29/// The actual cryptographic protection (compression / encryption /
30/// authentication / digital signature) belongs to the ciphering layer, which is
31/// not implemented here. The three methods therefore validate their parameters
32/// and return best-effort results.
33#[derive(Clone, Serialize, Deserialize, Debug)]
34pub struct DataProtection {
35    logical_name: ObisCode,
36    protection_buffer: Vec<u8>,
37    protection_object_list: Vec<ProtectionObject>,
38    protection_parameters_get: Vec<Vec<u8>>,
39    protection_parameters_set: Vec<Vec<u8>>,
40    required_protection: u8,
41}
42
43impl DataProtection {
44    /// Builds a new [`DataProtection`] from its configuration.
45    pub fn new(config: DataProtectionConfig) -> Self {
46        DataProtection {
47            logical_name: config.logical_name,
48            protection_buffer: config.protection_buffer,
49            protection_object_list: config.protection_object_list,
50            protection_parameters_get: config.protection_parameters_get,
51            protection_parameters_set: config.protection_parameters_set,
52            required_protection: config.required_protection,
53        }
54    }
55
56    /// Method 1: `get_protected_attributes` โ€” returns the protected data built
57    /// from the object list. Best-effort: returns the current protection buffer.
58    fn get_protected_attributes(&self, _data: CosemDataType) -> CosemDataType {
59        CosemDataType::OctetString(self.protection_buffer.clone())
60    }
61
62    /// Method 2: `set_protected_attributes` โ€” applies protected attribute values.
63    /// Best-effort: stores the supplied protected data into the buffer.
64    fn set_protected_attributes(&mut self, data: CosemDataType) -> Result<CosemDataType, String> {
65        match data {
66            CosemDataType::OctetString(bytes) => {
67                self.protection_buffer = bytes;
68                Ok(CosemDataType::Null)
69            }
70            CosemDataType::Structure(_) => Ok(CosemDataType::Null),
71            _ => Err("set_protected_attributes expects an octet-string or structure".to_string()),
72        }
73    }
74
75    /// Method 3: `invoke_protected_method` โ€” invokes a protected method.
76    /// Best-effort: succeeds after validating a parameter is present.
77    fn invoke_protected_method(_data: CosemDataType) -> CosemDataType {
78        CosemDataType::Null
79    }
80}
81
82impl InterfaceClass for DataProtection {
83    fn class_id(&self) -> u16 {
84        30
85    }
86
87    fn version(&self) -> u8 {
88        0
89    }
90
91    fn logical_name(&self) -> &ObisCode {
92        &self.logical_name
93    }
94
95    fn attributes(&self) -> Vec<(u8, CosemDataType)> {
96        vec![
97            (1, CosemDataType::OctetString(self.logical_name.to_bytes())),
98            (2, CosemDataType::OctetString(self.protection_buffer.clone())),
99            (3, CosemDataType::Array(self.protection_object_list.iter().cloned().map(CosemDataType::from).collect())),
100            (
101                4,
102                CosemDataType::Array(
103                    self.protection_parameters_get.iter().cloned().map(CosemDataType::OctetString).collect(),
104                ),
105            ),
106            (
107                5,
108                CosemDataType::Array(
109                    self.protection_parameters_set.iter().cloned().map(CosemDataType::OctetString).collect(),
110                ),
111            ),
112            (6, CosemDataType::Enum(self.required_protection)),
113        ]
114    }
115
116    fn methods(&self) -> Vec<(u8, String)> {
117        vec![
118            (1, "get_protected_attributes".to_string()),
119            (2, "set_protected_attributes".to_string()),
120            (3, "invoke_protected_method".to_string()),
121        ]
122    }
123
124    fn serialize_ber(&self, buf: &mut Vec<u8>) -> Result<(), BerError> {
125        let mut seq_buf = Vec::new();
126        CosemDataType::LongUnsigned(self.class_id()).serialize_ber(&mut seq_buf)?;
127        for (_, attr) in self.attributes() {
128            attr.serialize_ber(&mut seq_buf)?;
129        }
130        buf.push(0x02); // structure [2]
131        write_length(1 + self.attributes().len(), buf); // length = element count
132        buf.extend_from_slice(&seq_buf);
133        Ok(())
134    }
135
136    fn deserialize_ber(&mut self, data: &[u8]) -> Result<(), BerError> {
137        let (tlv, rest) = CosemDataType::deserialize_ber(data)?;
138        if !rest.is_empty() {
139            return Err(BerError::InvalidTag);
140        }
141        let CosemDataType::Structure(seq) = tlv else {
142            return Err(BerError::InvalidTag);
143        };
144        // class_id + 6 attributes.
145        if seq.len() != 7 {
146            return Err(BerError::InvalidLength);
147        }
148        if let CosemDataType::LongUnsigned(class_id) = seq[0] {
149            if class_id != self.class_id() {
150                return Err(BerError::InvalidValue);
151            }
152        } else {
153            return Err(BerError::InvalidTag);
154        }
155        if let CosemDataType::OctetString(obis) = &seq[1] {
156            if obis.len() == 6 {
157                self.logical_name = ObisCode::new(obis[0], obis[1], obis[2], obis[3], obis[4], obis[5]);
158            } else {
159                return Err(BerError::InvalidLength);
160            }
161        } else {
162            return Err(BerError::InvalidTag);
163        }
164        self.protection_buffer = match &seq[2] {
165            CosemDataType::OctetString(v) => v.clone(),
166            _ => return Err(BerError::InvalidTag),
167        };
168        self.protection_object_list = take_po_array(&seq[3])?;
169        self.protection_parameters_get = take_octet_string_array(&seq[4])?;
170        self.protection_parameters_set = take_octet_string_array(&seq[5])?;
171        self.required_protection = match seq[6] {
172            CosemDataType::Enum(v) => v,
173            _ => return Err(BerError::InvalidTag),
174        };
175        Ok(())
176    }
177
178    fn invoke_method(&mut self, method_id: u8, params: Option<CosemDataType>) -> Result<CosemDataType, String> {
179        let params = params.ok_or("Missing method parameter")?;
180        match method_id {
181            1 => Ok(self.get_protected_attributes(params)),
182            2 => self.set_protected_attributes(params),
183            3 => Ok(Self::invoke_protected_method(params)),
184            _ => Err(format!("Method {method_id} not supported for Data protection")),
185        }
186    }
187
188    fn as_any(&self) -> &dyn Any {
189        self
190    }
191}
192
193fn take_po_array(value: &CosemDataType) -> Result<Vec<ProtectionObject>, BerError> {
194    match value {
195        CosemDataType::Array(list) => {
196            list.iter().map(|item| ProtectionObject::try_from(item).map_err(|_| BerError::InvalidValue)).collect()
197        }
198        _ => Err(BerError::InvalidTag),
199    }
200}
201
202fn take_octet_string_array(value: &CosemDataType) -> Result<Vec<Vec<u8>>, BerError> {
203    match value {
204        CosemDataType::Array(list) => list
205            .iter()
206            .map(|item| match item {
207                CosemDataType::OctetString(v) => Ok(v.clone()),
208                _ => Err(BerError::InvalidTag),
209            })
210            .collect(),
211        _ => Err(BerError::InvalidTag),
212    }
213}
214
215/// Writes a BER length octet (short or long form).
216#[allow(clippy::cast_possible_truncation)] // length < 128 and num_octets in 1..=8 always fit u8
217fn write_length(length: usize, buf: &mut Vec<u8>) {
218    if length < 128 {
219        buf.push(length as u8);
220    } else {
221        let bytes = (length as u64).to_be_bytes();
222        let first_non_zero = bytes.iter().position(|&b| b != 0).unwrap_or(7);
223        let num_octets = 8 - first_non_zero;
224        buf.push(0x80 | num_octets as u8);
225        buf.extend_from_slice(&bytes[first_non_zero..]);
226    }
227}
228
229#[cfg(test)]
230mod tests {
231    use super::*;
232
233    fn sample() -> DataProtection {
234        DataProtection::new(DataProtectionConfig {
235            logical_name: ObisCode::new(0, 0, 30, 0, 0, 255),
236            protection_buffer: vec![0x01, 0x02, 0x03],
237            protection_object_list: vec![],
238            protection_parameters_get: vec![],
239            protection_parameters_set: vec![],
240            required_protection: 1,
241        })
242    }
243
244    #[test]
245    fn class_id_and_attributes() {
246        let obj = sample();
247        assert_eq!(obj.class_id(), 30);
248        assert_eq!(obj.version(), 0);
249        assert_eq!(obj.attributes().len(), 6);
250        assert_eq!(obj.methods().len(), 3);
251    }
252
253    #[test]
254    fn round_trip() {
255        let obj = sample();
256        let mut buf = Vec::new();
257        obj.serialize_ber(&mut buf).unwrap();
258        let mut decoded = sample();
259        decoded.required_protection = 9;
260        decoded.deserialize_ber(&buf).unwrap();
261        assert_eq!(decoded.attributes(), obj.attributes());
262    }
263
264    #[test]
265    fn get_and_set_protection_buffer() {
266        let mut obj = sample();
267        assert_eq!(
268            obj.invoke_method(1, Some(CosemDataType::Null)).unwrap(),
269            CosemDataType::OctetString(vec![0x01, 0x02, 0x03])
270        );
271        obj.invoke_method(2, Some(CosemDataType::OctetString(vec![0xAA, 0xBB]))).unwrap();
272        assert_eq!(obj.attributes()[1].1, CosemDataType::OctetString(vec![0xAA, 0xBB]));
273    }
274}