-
Notifications
You must be signed in to change notification settings - Fork 10
/
astarte.rs
297 lines (269 loc) · 9.5 KB
/
astarte.rs
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
/*
* This file is part of Edgehog.
*
* Copyright 2022 SECO Mind Srl
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
use astarte_sdk::builder::AstarteOptions;
use astarte_sdk::types::AstarteType;
use astarte_sdk::{registration, AstarteError, AstarteSdk, Clientbound};
use async_trait::async_trait;
use serde::Serialize;
use crate::data::Publisher;
use crate::error::DeviceManagerError;
use crate::repository::file_state_repository::FileStateRepository;
use crate::repository::StateRepository;
use crate::{get_hardware_id_from_dbus, DeviceManagerOptions};
#[derive(Clone)]
pub struct Astarte {
pub device_sdk: AstarteSdk,
}
#[async_trait]
impl Publisher for Astarte {
async fn send_object<T: 'static>(
&self,
interface_name: &str,
interface_path: &str,
data: T,
) -> Result<(), AstarteError>
where
T: Serialize + Send,
{
self.device_sdk
.send_object(interface_name, interface_path, data)
.await
}
async fn send(
&self,
interface_name: &str,
interface_path: &str,
data: AstarteType,
) -> Result<(), AstarteError> {
self.device_sdk
.send(interface_name, interface_path, data)
.await
}
async fn on_event(&mut self) -> Result<Clientbound, AstarteError> {
self.device_sdk.poll().await
}
}
impl Astarte {
pub async fn new(sdk_options: AstarteOptions) -> Result<Astarte, DeviceManagerError> {
let device = AstarteSdk::new(&sdk_options).await?;
Ok(Astarte { device_sdk: device })
}
}
pub async fn astarte_map_options(
opts: &DeviceManagerOptions,
) -> Result<AstarteOptions, DeviceManagerError> {
let device_id: String = get_device_id(opts.device_id.clone()).await?;
let store_directory = opts.store_directory.to_owned();
let credentials_secret: String = get_credentials_secret(
&device_id,
&opts,
FileStateRepository::new(store_directory, format!("credentials_{}.json", device_id)),
)
.await?;
let mut sdk_options = AstarteOptions::new(
&opts.realm,
&device_id,
&credentials_secret,
&opts.pairing_url,
);
if Some(true) == opts.astarte_ignore_ssl {
sdk_options.ignore_ssl_errors();
}
Ok(sdk_options
.interface_directory(&opts.interfaces_directory)?
.build())
}
async fn get_device_id(opt_device_id: Option<String>) -> Result<String, DeviceManagerError> {
if let Some(device_id) = opt_device_id {
Ok(device_id)
} else {
get_hardware_id_from_dbus().await
}
}
async fn get_credentials_secret(
device_id: &str,
opts: &DeviceManagerOptions,
cred_state_repo: impl StateRepository<String>,
) -> Result<String, DeviceManagerError> {
if let Some(secret) = opts.credentials_secret.clone() {
Ok(secret)
} else if cred_state_repo.exists() {
get_credentials_secret_from_persistence(cred_state_repo)
} else if let Some(token) = opts.pairing_token.clone() {
get_credentials_secret_from_registration(device_id, &token, opts, cred_state_repo).await
} else {
Err(DeviceManagerError::FatalError(
"Missing arguments".to_string(),
))
}
}
fn get_credentials_secret_from_persistence(
cred_state_repo: impl StateRepository<String>,
) -> Result<String, DeviceManagerError> {
Ok(cred_state_repo.read().expect("Unable to read secret"))
}
async fn get_credentials_secret_from_registration(
device_id: &str,
token: &str,
opts: &DeviceManagerOptions,
cred_state_repo: impl StateRepository<String>,
) -> Result<String, DeviceManagerError> {
let registration =
registration::register_device(token, &opts.pairing_url, &opts.realm, &device_id).await;
if let Ok(credentials_secret) = registration {
cred_state_repo
.write(&credentials_secret)
.expect("Unable to write secret");
Ok(credentials_secret)
} else {
Err(DeviceManagerError::FatalError("Pairing error".to_string()))
}
}
#[cfg(test)]
mod tests {
use crate::repository::MockStateRepository;
use crate::{DeviceManagerError, DeviceManagerOptions};
use crate::data::astarte::{
get_credentials_secret, get_credentials_secret_from_registration, get_device_id,
};
#[tokio::test]
async fn device_id_test() {
assert_eq!(
get_device_id(Some("target".to_string())).await.unwrap(),
"target".to_string()
);
}
#[tokio::test]
async fn credentials_secret_test() {
let state_mock = MockStateRepository::<String>::new();
let options = DeviceManagerOptions {
realm: "".to_string(),
device_id: None,
credentials_secret: Some("credentials_secret".to_string()),
pairing_url: "".to_string(),
pairing_token: None,
interfaces_directory: "".to_string(),
store_directory: "".to_string(),
download_directory: "".to_string(),
astarte_ignore_ssl: Some(false),
telemetry_config: vec![],
};
assert_eq!(
get_credentials_secret("device_id", &options, state_mock)
.await
.unwrap(),
"credentials_secret".to_string()
);
}
#[tokio::test]
async fn not_enough_arguments_credentials_secret_test() {
let mut state_mock = MockStateRepository::<String>::new();
state_mock.expect_exists().returning(|| false);
let options = DeviceManagerOptions {
realm: "".to_string(),
device_id: None,
credentials_secret: None,
pairing_url: "".to_string(),
pairing_token: None,
interfaces_directory: "".to_string(),
store_directory: "".to_string(),
download_directory: "".to_string(),
astarte_ignore_ssl: Some(false),
telemetry_config: vec![],
};
assert!(get_credentials_secret("device_id", &options, state_mock)
.await
.is_err());
}
#[tokio::test]
#[should_panic(expected = "Unable to read secret: FatalError(\"\")")]
async fn get_credentials_secret_persistence_fail() {
let mut state_mock = MockStateRepository::<String>::new();
state_mock.expect_exists().returning(|| true);
state_mock
.expect_read()
.returning(move || Err(DeviceManagerError::FatalError("".to_owned())));
let options = DeviceManagerOptions {
realm: "".to_string(),
device_id: Some("device_id".to_owned()),
credentials_secret: None,
pairing_url: "".to_string(),
pairing_token: None,
interfaces_directory: "".to_string(),
store_directory: "".to_string(),
download_directory: "".to_string(),
astarte_ignore_ssl: Some(false),
telemetry_config: vec![],
};
assert!(get_credentials_secret("device_id", &options, state_mock)
.await
.is_err());
}
#[tokio::test]
async fn get_credentials_secret_persistence_success() {
let mut state_mock = MockStateRepository::<String>::new();
state_mock.expect_exists().returning(|| true);
state_mock
.expect_read()
.returning(move || Ok("cred_secret".to_owned()));
let options = DeviceManagerOptions {
realm: "".to_string(),
device_id: Some("device_id".to_owned()),
credentials_secret: None,
pairing_url: "".to_string(),
pairing_token: None,
interfaces_directory: "".to_string(),
store_directory: "".to_string(),
download_directory: "".to_string(),
astarte_ignore_ssl: Some(false),
telemetry_config: vec![],
};
assert!(get_credentials_secret("device_id", &options, state_mock)
.await
.is_ok());
}
#[tokio::test]
async fn get_credentials_secret_from_registration_fail() {
let options = DeviceManagerOptions {
realm: "".to_string(),
device_id: Some("device_id".to_owned()),
credentials_secret: Some("credentials_secret".to_string()),
pairing_url: "".to_string(),
pairing_token: None,
interfaces_directory: "./".to_string(),
store_directory: "".to_string(),
download_directory: "".to_string(),
astarte_ignore_ssl: Some(false),
telemetry_config: vec![],
};
let state_mock = MockStateRepository::<String>::new();
let cred_result =
get_credentials_secret_from_registration("", "", &options, state_mock).await;
assert!(cred_result.is_err());
match cred_result.err().unwrap() {
DeviceManagerError::FatalError(val) => {
assert_eq!(val, "Pairing error".to_owned())
}
_ => {
panic!("Wrong DeviceManagerError type");
}
};
}
}