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
//! C509 Alternative Name uses for Subject Alternative Name extension and
//! Issuer Alternative Name extension.

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

use crate::general_names::{
    general_name::{GeneralName, GeneralNameTypeRegistry, GeneralNameValue},
    GeneralNames,
};

/// Alternative Name extension.
/// Can be interpreted as a `GeneralNames / text`
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct AlternativeName(GeneralNamesOrText);

impl AlternativeName {
    /// Create a new instance of `AlternativeName` given value.
    #[must_use]
    pub fn new(value: GeneralNamesOrText) -> Self {
        Self(value)
    }

    /// Get the inner of Alternative Name.
    #[must_use]
    pub fn get_inner(&self) -> &GeneralNamesOrText {
        &self.0
    }
}

impl Encode<()> for AlternativeName {
    fn encode<W: Write>(
        &self, e: &mut Encoder<W>, ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        self.0.encode(e, ctx)
    }
}

impl Decode<'_, ()> for AlternativeName {
    fn decode(d: &mut Decoder<'_>, ctx: &mut ()) -> Result<Self, minicbor::decode::Error> {
        GeneralNamesOrText::decode(d, ctx).map(AlternativeName::new)
    }
}

// ------------------GeneralNamesOrText--------------------

/// Enum for type that can be a `GeneralNames` or a text use in `AlternativeName`.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum GeneralNamesOrText {
    /// A value of `GeneralNames`.
    GeneralNames(GeneralNames),
    /// A text string.
    Text(String),
}

impl Encode<()> for GeneralNamesOrText {
    fn encode<W: Write>(
        &self, e: &mut Encoder<W>, ctx: &mut (),
    ) -> Result<(), minicbor::encode::Error<W::Error>> {
        match self {
            GeneralNamesOrText::GeneralNames(gns) => {
                let gn = gns
                    .get_inner()
                    .first()
                    .ok_or(minicbor::encode::Error::message("GeneralNames is empty"))?;
                // Check whether there is only 1 item in the array which is a DNSName
                if gns.get_inner().len() == 1 && gn.get_gn_type().is_dns_name() {
                    gn.get_gn_value().encode(e, ctx)?;
                } else {
                    gns.encode(e, ctx)?;
                }
            },
            GeneralNamesOrText::Text(text) => {
                e.str(text)?;
            },
        }
        Ok(())
    }
}

impl Decode<'_, ()> for GeneralNamesOrText {
    fn decode(d: &mut Decoder<'_>, ctx: &mut ()) -> Result<Self, minicbor::decode::Error> {
        match d.datatype()? {
            // If it is a string it is a GeneralNames with only 1 DNSName
            minicbor::data::Type::String => {
                let gn_dns = GeneralName::new(
                    GeneralNameTypeRegistry::DNSName,
                    GeneralNameValue::Text(d.str()?.to_string()),
                );
                let mut gns = GeneralNames::new();
                gns.add_gn(gn_dns);
                Ok(GeneralNamesOrText::GeneralNames(gns))
            },
            minicbor::data::Type::Array => {
                Ok(GeneralNamesOrText::GeneralNames(GeneralNames::decode(
                    d, ctx,
                )?))
            },
            _ => {
                Err(minicbor::decode::Error::message(
                    "Invalid type for AlternativeName",
                ))
            },
        }
    }
}

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

#[cfg(test)]
mod test_alt_name {
    use super::*;
    use crate::general_names::general_name::{
        GeneralName, GeneralNameTypeRegistry, GeneralNameValue,
    };

    #[test]
    fn encode_only_dns() {
        let mut buffer = Vec::new();
        let mut encoder = Encoder::new(&mut buffer);
        let mut gns = GeneralNames::new();
        gns.add_gn(GeneralName::new(
            GeneralNameTypeRegistry::DNSName,
            GeneralNameValue::Text("example.com".to_string()),
        ));
        let alt_name = AlternativeName::new(GeneralNamesOrText::GeneralNames(gns));
        alt_name
            .encode(&mut encoder, &mut ())
            .expect("Failed to encode AlternativeName");
        // "example.com": 0x6b6578616d706c652e636f6d
        assert_eq!(hex::encode(buffer.clone()), "6b6578616d706c652e636f6d");

        let mut decoder = Decoder::new(&buffer);
        let decoded_alt_name = AlternativeName::decode(&mut decoder, &mut ())
            .expect("Failed to decode Alternative Name");
        assert_eq!(decoded_alt_name, alt_name);
    }

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

        let alt_name = AlternativeName::new(GeneralNamesOrText::Text("example.com".to_string()));
        alt_name
            .encode(&mut encoder, &mut ())
            .expect("Failed to encode AlternativeName");
        // "example.com": 0x6b6578616d706c652e636f6d
        assert_eq!(hex::encode(buffer.clone()), "6b6578616d706c652e636f6d");

        // If only text, it should be GeneralNames with only 1 DNSName
        let mut gns = GeneralNames::new();
        gns.add_gn(GeneralName::new(
            GeneralNameTypeRegistry::DNSName,
            GeneralNameValue::Text("example.com".to_string()),
        ));

        let mut decoder = Decoder::new(&buffer);
        let decoded_alt_name = AlternativeName::decode(&mut decoder, &mut ())
            .expect("Failed to decode Alternative Name");
        assert_eq!(
            decoded_alt_name,
            AlternativeName::new(GeneralNamesOrText::GeneralNames(gns))
        );
    }
}