1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
//! C509 Attribute
//!
//! ```cddl
//! Attribute = ( attributeType: int, attributeValue: text ) //
//! ( attributeType: ~oid, attributeValue: bytes ) //
//! ( attributeType: pen, attributeValue: bytes )
//! ```
//!
//! For more information about Attribute,
//! visit [C509 Certificate](https://datatracker.ietf.org/doc/draft-ietf-cose-cbor-encoded-cert/09/)

use std::str::FromStr;

use asn1_rs::Oid;
use minicbor::{encode::Write, Decode, Decoder, Encode, Encoder};
use serde::{Deserialize, Deserializer, Serialize};

use super::data::{get_oid_from_int, ATTRIBUTES_LOOKUP};
use crate::oid::{C509oid, C509oidRegistered};

/// A struct of C509 `Attribute`
#[derive(Debug, Clone, PartialEq)]
pub struct Attribute {
    /// A registered OID of C509 `Attribute`.
    registered_oid: C509oidRegistered,
    /// A flag to indicate whether the value can have multiple value.
    multi_value: bool,
    /// A value of C509 `Attribute` can be a vector of text or bytes.
    value: Vec<AttributeValue>,
}

impl Attribute {
    /// Create a new instance of `Attribute`.
    #[must_use]
    pub fn new(oid: Oid<'static>) -> Self {
        Self {
            registered_oid: C509oidRegistered::new(oid, ATTRIBUTES_LOOKUP.get_int_to_oid_table()),
            multi_value: false,
            value: Vec::new(),
        }
    }

    /// Add a value to `Attribute`.
    pub fn add_value(&mut self, value: AttributeValue) {
        self.value.push(value);
    }

    /// Get the registered OID of `Attribute`.
    pub(crate) fn get_registered_oid(&self) -> &C509oidRegistered {
        &self.registered_oid
    }

    /// Get the value of `Attribute`.
    pub(crate) fn get_value(&self) -> &Vec<AttributeValue> {
        &self.value
    }

    /// Set whether `Attribute` can be PEN encoded.
    pub(crate) fn set_pen_supported(self) -> Self {
        Self {
            registered_oid: self.registered_oid.pen_encoded(),
            multi_value: self.multi_value,
            value: self.value,
        }
    }

    /// Set whether `Attribute` can have multiple value.
    pub(crate) fn set_multi_value(mut self) -> Self {
        self.multi_value = true;
        self
    }
}

/// A helper struct for deserialize and serialize `Attribute`.
#[derive(Debug, Deserialize, Serialize)]
struct Helper {
    /// An OID value in string.
    oid: String,
    /// A value of C509 `Attribute` can be a vector of text or bytes.
    value: Vec<AttributeValue>,
}

impl<'de> Deserialize<'de> for Attribute {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where D: Deserializer<'de> {
        let helper = Helper::deserialize(deserializer)?;
        let oid =
            Oid::from_str(&helper.oid).map_err(|e| serde::de::Error::custom(format!("{e:?}")))?;
        let mut attr = Attribute::new(oid);
        for value in helper.value {
            attr.add_value(value);
        }
        Ok(attr)
    }
}

impl Serialize for Attribute {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where S: serde::Serializer {
        let helper = Helper {
            oid: self.registered_oid.get_c509_oid().get_oid().to_string(),
            value: self.value.clone(),
        };
        helper.serialize(serializer)
    }
}

impl Encode<()> for Attribute {
    fn encode<W: Write>(
        &self, e: &mut Encoder<W>, ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        // Encode CBOR int if available
        if let Some(&oid) = self
            .registered_oid
            .get_table()
            .get_map()
            .get_by_right(&self.registered_oid.get_c509_oid().get_oid())
        {
            e.i16(oid)?;
        } else {
            // Encode unwrapped CBOR OID or CBOR PEN
            self.registered_oid.get_c509_oid().encode(e, ctx)?;
        }

        // Check if the attribute value is empty
        if self.value.is_empty() {
            return Err(minicbor::encode::Error::message("Attribute value is empty"));
        }

        // If multi-value attributes, encode it as array
        if self.multi_value {
            e.array(self.value.len() as u64)?;
        }

        // Encode each value in the attribute
        for value in &self.value {
            value.encode(e, ctx)?;
        }

        Ok(())
    }
}

impl Decode<'_, ()> for Attribute {
    fn decode(d: &mut Decoder<'_>, ctx: &mut ()) -> Result<Self, minicbor::decode::Error> {
        // Handle CBOR int
        let mut attr = if d.datatype()? == minicbor::data::Type::U8 {
            let i = d.i16()?;
            let oid = get_oid_from_int(i).map_err(minicbor::decode::Error::message)?;
            Attribute::new(oid.clone())
        } else {
            // Handle unwrapped CBOR OID or CBOR PEN
            let c509_oid: C509oid = d.decode()?;
            Attribute::new(c509_oid.get_oid())
        };

        // Handle attribute value
        if d.datatype()? == minicbor::data::Type::Array {
            // When multi-value attribute
            let len = d.array()?.ok_or_else(|| {
                minicbor::decode::Error::message("Failed to get array length for attribute value")
            })?;

            if len == 0 {
                return Err(minicbor::decode::Error::message("Attribute value is empty"));
            }

            for _ in 0..len {
                attr.add_value(AttributeValue::decode(d, ctx)?);
            }
            attr = attr.set_multi_value();
        } else {
            let value = AttributeValue::decode(d, ctx)?;
            attr.add_value(value);
        }
        Ok(attr)
    }
}

// ------------------AttributeValue----------------------

/// An enum of possible value types for `Attribute`.
#[allow(clippy::module_name_repetitions)]
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AttributeValue {
    /// A text string.
    Text(String),
    /// A byte vector.
    Bytes(Vec<u8>),
}

impl Encode<()> for AttributeValue {
    fn encode<W: Write>(
        &self, e: &mut Encoder<W>, _ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        match self {
            AttributeValue::Text(text) => e.str(text)?,
            AttributeValue::Bytes(bytes) => e.bytes(bytes)?,
        };
        Ok(())
    }
}

impl Decode<'_, ()> for AttributeValue {
    fn decode(d: &mut Decoder<'_>, _ctx: &mut ()) -> Result<Self, minicbor::decode::Error> {
        match d.datatype()? {
            minicbor::data::Type::String => Ok(AttributeValue::Text(d.str()?.to_string())),
            minicbor::data::Type::Bytes => Ok(AttributeValue::Bytes(d.bytes()?.to_vec())),
            _ => {
                Err(minicbor::decode::Error::message(
                    "Invalid AttributeValue, value should be either String or Bytes",
                ))
            },
        }
    }
}

// ------------------Test----------------------

#[cfg(test)]
mod test_attribute {
    use asn1_rs::oid;

    use super::*;

    #[test]
    fn encode_decode_attribute_int() {
        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(&mut buffer);
        let mut attribute = Attribute::new(oid!(1.2.840 .113549 .1 .9 .1));
        attribute.add_value(AttributeValue::Text("example@example.com".to_string()));
        attribute
            .encode(&mut encoder, &mut ())
            .expect("Failed to encode Attribute");
        // Email Address example@example.com: 0x00736578616d706c65406578616d706c652e636f6d
        assert_eq!(
            hex::encode(buffer.clone()),
            "00736578616d706c65406578616d706c652e636f6d"
        );

        let mut decoder = Decoder::new(&buffer);
        let attribute_decoded =
            Attribute::decode(&mut decoder, &mut ()).expect("Failed to decode Attribute");
        assert_eq!(attribute_decoded, attribute);
    }

    #[test]
    fn empty_attribute_value() {
        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(&mut buffer);
        let attribute = Attribute::new(oid!(1.2.840 .113549 .1 .9 .1));
        attribute
            .encode(&mut encoder, &mut ())
            .expect_err("Failed to encode Attribute");
    }
}