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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
use crate::{
    attribute, dialect,
    meta::v1::{CommonMetadata, CommonMetadataMut, ScopedMetadata},
    serde::{is_default, Base64Standard},
    translator, Dialect, Section, Translator,
};
use chrono::{DateTime, Utc};
use core::fmt::{self, Formatter};
use serde::{de::MapAccess, Deserialize, Deserializer, Serialize};
use serde_json::{Map, Value};
use std::{cmp::Ordering, collections::HashMap};

/// A device.
#[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
pub struct Device {
    pub metadata: ScopedMetadata,
    #[serde(default)]
    #[serde(skip_serializing_if = "Map::is_empty")]
    pub spec: Map<String, Value>,
    #[serde(default)]
    #[serde(skip_serializing_if = "Map::is_empty")]
    pub status: Map<String, Value>,
}

translator!(Device);

impl AsRef<dyn CommonMetadata> for Device {
    fn as_ref(&self) -> &(dyn CommonMetadata + 'static) {
        &self.metadata
    }
}

impl AsMut<dyn CommonMetadataMut> for Device {
    fn as_mut(&mut self) -> &mut (dyn CommonMetadataMut + 'static) {
        &mut self.metadata
    }
}

impl Device {
    /// Validate if a device is enabled
    pub fn validate_device(&self) -> bool {
        match self.section::<DeviceSpecCore>() {
            // found "core", decoded successfully -> check
            Some(Ok(core)) => {
                if core.disabled {
                    return false;
                }
            }
            // found "core", but could not decode -> fail
            Some(Err(_)) => {
                return false;
            }
            // no "core" section
            _ => {}
        };

        // done
        true
    }

    /// Create an minimal device object from the an application name and a device name
    pub fn new<A, D>(application: A, device: D) -> Self
    where
        A: AsRef<str>,
        D: AsRef<str>,
    {
        Device {
            metadata: ScopedMetadata {
                application: application.as_ref().into(),
                name: device.as_ref().into(),
                ..Default::default()
            },
            ..Default::default()
        }
    }

    /// Insert a credential entry to the credentials of a device.
    /// If there are no credentials already existing an array is created
    /// if there is an error deserializing the existing data an error is returned
    pub fn add_credential(&mut self, credential: Credential) -> Result<(), serde_json::Error> {
        // TODO: Remove before drg version 0.12.x
        self.update_section::<DeviceSpecCredentials, _>(|mut auth| {
            auth.credentials.push(credential.clone());
            auth
        })?;
        self.update_section::<DeviceSpecAuthentication, _>(|mut auth| {
            auth.credentials.push(credential);
            auth
        })
    }

    /// Retrieve the credentials of this device
    pub fn get_credentials(&self) -> Option<Vec<Credential>> {
        let credentials = match self.section::<DeviceSpecAuthentication>() {
            Some(Ok(auth)) => auth.credentials,
            _ => match self.section::<DeviceSpecCredentials>() {
                Some(Ok(credentials)) => credentials.credentials,
                _ => {
                    return None;
                }
            },
        };
        Some(credentials)
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
pub struct DeviceSpecCore {
    #[serde(default)]
    #[serde(skip_serializing_if = "is_default")]
    pub disabled: bool,
}

attribute!(pub DeviceSpecCore[DeviceEnabled:bool] => |core| match core {
    Some(Ok(core)) => core.disabled,
    // failed to decode
    Some(Err(_)) => false,
    // no "core" section
    None => true,
});
attribute!(pub DeviceSpecCommands[Commands:Vec<Command>] => |commands| match commands {
    Some(Ok(commands)) => commands.commands,
    _ => vec![],
});
attribute!(pub DeviceSpecCommands[FirstCommand:Option<Command>] => |commands| match commands {
    Some(Ok(commands)) => commands.commands.get(0).cloned(),
    _ => None,
});

impl Dialect for DeviceSpecCore {
    fn key() -> &'static str {
        "core"
    }
    fn section() -> Section {
        Section::Spec
    }
}

/// Configured device credentials.
#[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
pub struct DeviceSpecCredentials {
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub credentials: Vec<Credential>,
}

impl Dialect for DeviceSpecCredentials {
    fn key() -> &'static str {
        "credentials"
    }
    fn section() -> Section {
        Section::Spec
    }
}

/// A single credential entry.
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
pub enum Credential {
    #[serde(rename = "user")]
    UsernamePassword {
        username: String,
        password: Password,
        #[serde(default)]
        unique: bool,
    },
    #[serde(rename = "pass")]
    Password(Password),
    #[serde(rename = "cert")]
    Certificate(String),
    #[serde(rename = "psk")]
    PreSharedKey(PreSharedKey),
}

#[derive(Clone, Serialize, PartialEq, Eq)]
pub enum Password {
    #[serde(rename = "plain")]
    Plain(String),
    #[serde(rename = "bcrypt")]
    BCrypt(String),
    #[serde(rename = "sha512")]
    Sha512(String),
}

/// Configured device credentials.
#[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
pub struct DeviceSpecAuthentication {
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub credentials: Vec<Credential>,
}

impl Dialect for DeviceSpecAuthentication {
    fn key() -> &'static str {
        "authentication"
    }
    fn section() -> Section {
        Section::Spec
    }
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PreSharedKey {
    #[serde(with = "Base64Standard")]
    pub key: Vec<u8>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub validity: Option<Validity>,
}

impl fmt::Debug for PreSharedKey {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "key=..., validity: {:?}", self.validity)
    }
}

impl PartialOrd for PreSharedKey {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        if self.validity.is_none() && other.validity.is_none() {
            Some(Ordering::Equal)
        } else if self.validity.is_none() {
            Some(Ordering::Less)
        } else if other.validity.is_none() {
            Some(Ordering::Equal)
        } else {
            self.validity.partial_cmp(&other.validity)
        }
    }
}

impl Ord for PreSharedKey {
    fn cmp(&self, other: &Self) -> Ordering {
        // We know it never returns None
        self.partial_cmp(other).unwrap()
    }
}

#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Debug)]
pub struct Validity {
    #[serde(rename = "notBefore")]
    pub not_before: DateTime<Utc>,
    #[serde(rename = "notAfter")]
    pub not_after: DateTime<Utc>,
}

impl Validity {
    pub fn is_valid(&self, now: DateTime<Utc>) -> bool {
        self.not_before <= now && self.not_after >= now
    }
}

impl PartialOrd for Validity {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(if self.not_before < other.not_before {
            Ordering::Less
        } else if self.not_before > other.not_before {
            Ordering::Greater
        } else if self.not_after > other.not_after {
            Ordering::Less
        } else if self.not_after < other.not_after {
            Ordering::Greater
        } else {
            Ordering::Equal
        })
    }
}

impl Ord for Validity {
    fn cmp(&self, other: &Self) -> Ordering {
        // We know it never returns None
        self.partial_cmp(other).unwrap()
    }
}

impl<'de> Deserialize<'de> for Password {
    fn deserialize<D>(deserializer: D) -> Result<Self, <D as Deserializer<'de>>::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_any(PasswordVisitor)
    }
}

struct PasswordVisitor;

impl<'de> serde::de::Visitor<'de> for PasswordVisitor {
    type Value = Password;

    fn expecting(&self, formatter: &mut Formatter) -> std::fmt::Result {
        formatter.write_str("A password, by string or map")
    }

    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> {
        Ok(Password::Plain(value.to_owned()))
    }

    fn visit_string<E>(self, value: String) -> Result<Self::Value, E> {
        Ok(Password::Plain(value))
    }

    fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
    where
        V: MapAccess<'de>,
    {
        if let Some(key) = map.next_key::<String>()? {
            match key.as_str() {
                "plain" => Ok(Password::Plain(map.next_value()?)),
                "bcrypt" => Ok(Password::BCrypt(map.next_value()?)),
                "sha512" => Ok(Password::Sha512(map.next_value()?)),
                key => Err(serde::de::Error::unknown_field(
                    key,
                    &["plain", "bcrypt", "sha512"],
                )),
            }
        } else {
            Err(serde::de::Error::invalid_length(
                0,
                &"Expected exactly one field",
            ))
        }
    }
}

impl fmt::Debug for Password {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str("...")
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DeviceSpecGatewaySelector {
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub match_names: Vec<String>,
}

impl Dialect for DeviceSpecGatewaySelector {
    fn key() -> &'static str {
        "gatewaySelector"
    }
    fn section() -> Section {
        Section::Spec
    }
}

#[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
pub struct DeviceSpecCommands {
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub commands: Vec<Command>,
}

impl Dialect for DeviceSpecCommands {
    fn key() -> &'static str {
        "commands"
    }
    fn section() -> Section {
        Section::Spec
    }
}

#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
pub enum Command {
    #[serde(rename = "external")]
    External(ExternalCommandEndpoint),
}

#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq)]
pub struct ExternalCommandEndpoint {
    pub r#type: Option<String>,
    pub url: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub method: String,
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub headers: HashMap<String, String>,
}

#[derive(Clone, Debug, Default, Deserialize, Serialize, Eq, PartialEq)]
pub struct DeviceSpecAliases(
    #[serde(default)]
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub Vec<String>,
);

dialect!(DeviceSpecAliases [Section::Spec => "alias"]);

#[cfg(test)]
mod test;