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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
//! C509 General Name
//!
//! For more information about `GeneralName`,
//! visit [C509 Certificate](https://datatracker.ietf.org/doc/draft-ietf-cose-cbor-encoded-cert/09/)

use std::fmt::Debug;

use minicbor::{encode::Write, Decode, Decoder, Encode, Encoder};
use serde::{Deserialize, Serialize};
use strum_macros::{EnumDiscriminants, EnumIs};

use super::{
    data::{get_gn_from_int, get_gn_value_type_from_int, get_int_from_gn},
    other_name_hw_module::OtherNameHardwareModuleName,
};
use crate::{name::Name, oid::C509oid};

/// A struct represents a `GeneralName`.
/// ```cddl
/// GeneralName = ( GeneralNameType : int, GeneralNameValue : any )
/// ```
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct GeneralName {
    /// A registered general name type.
    gn_type: GeneralNameTypeRegistry,
    /// A general name value.
    value: GeneralNameValue,
}

#[allow(dead_code)]
impl GeneralName {
    /// Create a new instance of `GeneralName`.
    #[must_use]
    pub fn new(gn_type: GeneralNameTypeRegistry, value: GeneralNameValue) -> Self {
        Self { gn_type, value }
    }

    /// Get the `GeneralName` type.
    #[must_use]
    pub fn get_gn_type(&self) -> &GeneralNameTypeRegistry {
        &self.gn_type
    }

    /// Get the value of the `GeneralName` in `GeneralNameValue`.
    #[must_use]
    pub fn get_gn_value(&self) -> &GeneralNameValue {
        &self.value
    }
}

impl Encode<()> for GeneralName {
    fn encode<W: Write>(
        &self, e: &mut Encoder<W>, ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        // Encode GeneralNameType as int
        let i = get_int_from_gn(self.gn_type).map_err(minicbor::encode::Error::message)?;
        e.i16(i)?;
        // Encode GeneralNameValue as its type
        self.value.encode(e, ctx)?;
        Ok(())
    }
}

impl Decode<'_, ()> for GeneralName {
    fn decode(d: &mut Decoder<'_>, _ctx: &mut ()) -> Result<Self, minicbor::decode::Error> {
        if minicbor::data::Type::U8 == d.datatype()? || minicbor::data::Type::I8 == d.datatype()? {
            let i = d.i16()?;
            let gn = get_gn_from_int(i).map_err(minicbor::decode::Error::message)?;
            let value_type =
                get_gn_value_type_from_int(i).map_err(minicbor::decode::Error::message)?;
            Ok(GeneralName::new(
                gn,
                GeneralNameValue::decode(d, &mut value_type.get_type())?,
            ))
        } else {
            // GeneralName is not type int
            Err(minicbor::decode::Error::message(
                "GeneralName id type invalid, expected int",
            ))
        }
    }
}

// -----------------GeneralNameTypeRegistry------------------------

/// Enum of `GeneralName` registered in table Section 9.9 C509.
#[allow(clippy::module_name_repetitions)]
#[derive(Debug, Copy, PartialEq, Clone, Eq, Hash, EnumIs, Deserialize, Serialize)]
pub enum GeneralNameTypeRegistry {
    /// An otherName with `BundleEID`.
    OtherNameBundleEID, // EID
    /// An otherName with `SmtpUTF8Mailbox`.
    OtherNameSmtpUTF8Mailbox,
    /// An otherName with `HardwareModuleName`.
    OtherNameHardwareModuleName,
    /// An otherName.
    OtherName,
    /// A rfc822Name.
    Rfc822Name,
    /// A dNSName.
    DNSName,
    /// A directoryName.
    DirectoryName,
    /// A uniformResourceIdentifier.
    UniformResourceIdentifier,
    /// An iPAddress.
    IPAddress,
    /// A registeredID.
    RegisteredID,
}

// -------------------GeneralNameValue----------------------

/// An enum of possible value types for `GeneralName`.
#[allow(clippy::module_name_repetitions)]
#[derive(Debug, PartialEq, Clone, EnumDiscriminants, Deserialize, Serialize)]
#[strum_discriminants(name(GeneralNameValueType))]
#[serde(rename_all = "snake_case")]
pub enum GeneralNameValue {
    /// A text string.
    Text(String),
    /// A otherName + hardwareModuleName.
    OtherNameHWModuleName(OtherNameHardwareModuleName),
    /// A bytes.
    Bytes(Vec<u8>),
    /// An OID
    Oid(C509oid),
    /// Name
    Name(Name),
    /// An unsupported value.
    Unsupported,
}

/// Trait for `GeneralNameValueType`
trait GeneralNameValueTrait {
    /// Get the type of the `GeneralNameValueType`.
    fn get_type(&self) -> GeneralNameValueType;
}

impl GeneralNameValueTrait for GeneralNameValueType {
    fn get_type(&self) -> GeneralNameValueType {
        *self
    }
}

impl Encode<()> for GeneralNameValue {
    fn encode<W: Write>(
        &self, e: &mut Encoder<W>, ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        match self {
            GeneralNameValue::Text(value) => {
                e.str(value)?;
            },
            GeneralNameValue::Bytes(value) => {
                e.bytes(value)?;
            },
            GeneralNameValue::Oid(value) => {
                value.encode(e, ctx)?;
            },
            GeneralNameValue::OtherNameHWModuleName(value) => {
                value.encode(e, ctx)?;
            },
            GeneralNameValue::Name(value) => {
                Name::encode(value, e, ctx)?;
            },
            GeneralNameValue::Unsupported => {
                return Err(minicbor::encode::Error::message(
                    "Cannot encode unsupported GeneralName value",
                ))
            },
        };
        Ok(())
    }
}
impl<C> Decode<'_, C> for GeneralNameValue
where C: GeneralNameValueTrait + Debug
{
    fn decode(d: &mut Decoder<'_>, ctx: &mut C) -> Result<Self, minicbor::decode::Error> {
        match ctx.get_type() {
            GeneralNameValueType::Text => {
                let value = d.str()?.to_string();
                Ok(GeneralNameValue::Text(value))
            },
            GeneralNameValueType::Bytes => {
                let value = d.bytes()?.to_vec();
                Ok(GeneralNameValue::Bytes(value))
            },
            GeneralNameValueType::Oid => {
                let value = C509oid::decode(d, &mut ())?;
                Ok(GeneralNameValue::Oid(value))
            },
            GeneralNameValueType::OtherNameHWModuleName => {
                let value = OtherNameHardwareModuleName::decode(d, &mut ())?;
                Ok(GeneralNameValue::OtherNameHWModuleName(value))
            },
            GeneralNameValueType::Name => {
                let value = Name::decode(d, &mut ())?;
                Ok(GeneralNameValue::Name(value))
            },
            GeneralNameValueType::Unsupported => {
                Err(minicbor::decode::Error::message(
                    "Cannot decode Unsupported GeneralName value",
                ))
            },
        }
    }
}

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

#[cfg(test)]
mod test_general_name {
    use std::net::Ipv4Addr;

    use asn1_rs::oid;

    use super::*;

    #[test]
    fn encode_decode_text() {
        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(&mut buffer);

        let gn = GeneralName::new(
            GeneralNameTypeRegistry::DNSName,
            GeneralNameValue::Text("example.com".to_string()),
        );
        gn.encode(&mut encoder, &mut ())
            .expect("Failed to encode GeneralName");
        // DNSName: 0x02
        // "example.com": 0x6b6578616d706c652e636f6d
        assert_eq!(hex::encode(buffer.clone()), "026b6578616d706c652e636f6d");

        let mut decoder = Decoder::new(&buffer);
        let gn_decoded =
            GeneralName::decode(&mut decoder, &mut ()).expect("Failed to decode GeneralName");
        assert_eq!(gn_decoded, gn);
    }

    #[test]
    fn encode_decode_hw_module_name() {
        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(&mut buffer);

        let hw = OtherNameHardwareModuleName::new(oid!(2.16.840 .1 .101 .3 .4 .2 .1), vec![
            0x01, 0x02, 0x03, 0x04,
        ]);
        let gn = GeneralName::new(
            GeneralNameTypeRegistry::OtherNameHardwareModuleName,
            GeneralNameValue::OtherNameHWModuleName(hw),
        );
        gn.encode(&mut encoder, &mut ())
            .expect("Failed to encode GeneralName");
        // OtherNameHardwareModuleName: 0x20
        // [ ~oid, bytes ] = 0x82496086480165030402014401020304
        assert_eq!(
            hex::encode(buffer.clone()),
            "2082496086480165030402014401020304"
        );

        let mut decoder = Decoder::new(&buffer);
        let gn_decoded =
            GeneralName::decode(&mut decoder, &mut ()).expect("Failed to decode GeneralName");
        assert_eq!(gn_decoded, gn);
    }

    #[test]
    fn encode_decode_ip() {
        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(&mut buffer);

        let ipv4 = Ipv4Addr::new(192, 168, 1, 1);
        let gn = GeneralName::new(
            GeneralNameTypeRegistry::IPAddress,
            GeneralNameValue::Bytes(ipv4.octets().to_vec()),
        );

        gn.encode(&mut encoder, &mut ())
            .expect("Failed to encode GeneralName");
        // IPAddress: 0x07
        // 192.168.1.1 bytes: 0x44c0a8010
        assert_eq!(hex::encode(buffer.clone()), "0744c0a80101");

        let mut decoder = Decoder::new(&buffer);
        let gn_decoded =
            GeneralName::decode(&mut decoder, &mut ()).expect("Failed to decode GeneralName");
        assert_eq!(gn_decoded, gn);
    }

    #[test]
    fn encode_decode_oid() {
        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(&mut buffer);

        let gn = GeneralName::new(
            GeneralNameTypeRegistry::RegisteredID,
            GeneralNameValue::Oid(C509oid::new(oid!(2.16.840 .1 .101 .3 .4 .2 .1))),
        );
        gn.encode(&mut encoder, &mut ())
            .expect("Failed to encode GeneralName");
        // RegisteredID: 0x08
        // oid: 49608648016503040201
        assert_eq!(hex::encode(buffer.clone()), "0849608648016503040201");

        let mut decoder = Decoder::new(&buffer);
        let gn_decoded =
            GeneralName::decode(&mut decoder, &mut ()).expect("Failed to decode GeneralName");
        assert_eq!(gn_decoded, gn);
    }

    #[test]
    fn encode_decode_mismatch_type() {
        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(&mut buffer);

        let gn = GeneralName::new(
            GeneralNameTypeRegistry::OtherNameSmtpUTF8Mailbox,
            GeneralNameValue::Oid(C509oid::new(oid!(2.16.840 .1 .101 .3 .4 .2 .1))),
        );
        gn.encode(&mut encoder, &mut ())
            .expect("Failed to encode GeneralName");
        // OtherNameSmtpUTF8Mailbox: 0x21
        // oid: 49608648016503040201
        assert_eq!(hex::encode(buffer.clone()), "2149608648016503040201");

        let mut decoder = Decoder::new(&buffer);
        // Decode should fail, because rely on the int value
        GeneralName::decode(&mut decoder, &mut ()).expect_err("Failed to decode GeneralName");
    }
}