summaryrefslogtreecommitdiffstats
path: root/crates/core/tedge_mapper/src/sm_c8y_mapper/http_proxy.rs
blob: 277b0a1133882c218e72432f47d21d97ad8d7b56 (plain)
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
use crate::sm_c8y_mapper::error::SMCumulocityMapperError;
use crate::sm_c8y_mapper::json_c8y::{
    C8yCreateEvent, C8yManagedObject, C8yUpdateSoftwareListResponse, InternalIdResponse,
};
use crate::sm_c8y_mapper::mapper::SmartRestLogEvent;
use async_trait::async_trait;
use c8y_smartrest::smartrest_deserializer::SmartRestJwtResponse;
use chrono::{DateTime, Local};
use mqtt_client::{Client, MqttClient, Topic};
use reqwest::Url;
use std::time::Duration;
use tedge_config::{C8yUrlSetting, ConfigSettingAccessorStringExt, DeviceIdSetting, TEdgeConfig};
use tracing::{error, info, instrument};

const RETRY_TIMEOUT_SECS: u64 = 60;

/// An HttpProxy handles http requests to C8y on behalf of the device.
#[async_trait]
pub trait C8YHttpProxy {
    async fn init(&mut self) -> Result<(), SMCumulocityMapperError>;

    fn url_is_in_my_tenant_domain(&self, url: &str) -> bool;

    async fn get_jwt_token(&self) -> Result<SmartRestJwtResponse, SMCumulocityMapperError>;

    async fn send_software_list_http(
        &self,
        c8y_software_list: &C8yUpdateSoftwareListResponse,
    ) -> Result<(), SMCumulocityMapperError>;

    async fn upload_log_binary(&self, log_content: &str)
        -> Result<String, SMCumulocityMapperError>;
}

/// Define a C8y endpoint
pub struct C8yEndPoint {
    c8y_host: String,
    device_id: String,
    c8y_internal_id: String,
}

impl C8yEndPoint {
    fn new(c8y_host: &str, device_id: &str, c8y_internal_id: &str) -> C8yEndPoint {
        C8yEndPoint {
            c8y_host: c8y_host.into(),
            device_id: device_id.into(),
            c8y_internal_id: c8y_internal_id.into(),
        }
    }

    fn get_url_for_sw_list(&self) -> String {
        let mut url_update_swlist = String::new();
        url_update_swlist.push_str("https://");
        url_update_swlist.push_str(&self.c8y_host);
        url_update_swlist.push_str("/inventory/managedObjects/");
        url_update_swlist.push_str(&self.c8y_internal_id);

        url_update_swlist
    }

    fn get_url_for_get_id(&self) -> String {
        let mut url_get_id = String::new();
        url_get_id.push_str("https://");
        url_get_id.push_str(&self.c8y_host);
        url_get_id.push_str("/identity/externalIds/c8y_Serial/");
        url_get_id.push_str(&self.device_id);

        url_get_id
    }

    fn get_url_for_create_event(&self) -> String {
        let mut url_create_event = String::new();
        url_create_event.push_str("https://");
        url_create_event.push_str(&self.c8y_host);
        url_create_event.push_str("/event/events/");

        url_create_event
    }

    fn get_url_for_event_binary_upload(&self, event_id: &str) -> String {
        let mut url_event_binary = self.get_url_for_create_event();
        url_event_binary.push_str(event_id);
        url_event_binary.push_str("/binaries");

        url_event_binary
    }

    fn url_is_in_my_tenant_domain(&self, url: &str) -> bool {
        // c8y URL may contain either `Tenant Name` or Tenant Id` so they can be one of following options:
        // * <tenant_name>.<domain> eg: sample.c8y.io
        // * <tenant_id>.<domain> eg: t12345.c8y.io
        // These URLs may be both equivalent and point to the same tenant.
        // We are going to remove that and only check if the domain is the same.
        let tenant_uri = &self.c8y_host;
        let url_host = match Url::parse(url) {
            Ok(url) => match url.host() {
                Some(host) => host.to_string(),
                None => return false,
            },
            Err(_err) => {
                return false;
            }
        };

        let url_domain = url_host.splitn(2, '.').collect::<Vec<&str>>();
        let tenant_domain = tenant_uri.splitn(2, '.').collect::<Vec<&str>>();
        if url_domain.get(1) == tenant_domain.get(1) {
            return true;
        }
        false
    }
}

/// An HttpProxy that uses MQTT to retrieve JWT tokens and authenticate the device
///
/// - Keep the connection info to c8y and the internal Id of the device
/// - Handle JWT requests
pub struct JwtAuthHttpProxy {
    mqtt_con: Client,
    http_con: reqwest::Client,
    end_point: C8yEndPoint,
}

impl JwtAuthHttpProxy {
    pub fn new(
        mqtt_con: Client,
        http_con: reqwest::Client,
        c8y_host: &str,
        device_id: &str,
    ) -> JwtAuthHttpProxy {
        JwtAuthHttpProxy {
            mqtt_con,
            http_con,
            end_point: C8yEndPoint {
                c8y_host: c8y_host.into(),
                device_id: device_id.into(),
                c8y_internal_id: "".into(),
            },
        }
    }

    pub fn try_new(
        mqtt_con: Client,
        tedge_config: &TEdgeConfig,
    ) -> Result<JwtAuthHttpProxy, SMCumulocityMapperError> {
        let c8y_host = tedge_config.query_string(C8yUrlSetting)?;
        let device_id = tedge_config.query_string(DeviceIdSetting)?;
        let http_con = reqwest::ClientBuilder::new().build()?;
        Ok(JwtAuthHttpProxy::new(
            mqtt_con, http_con, &c8y_host, &device_id,
        ))
    }

    async fn try_get_and_set_internal_id(&mut self) -> Result<(), SMCumulocityMapperError> {
        let token = self.get_jwt_token().await?;
        let url_get_id = self.end_point.get_url_for_get_id();

        self.end_point.c8y_internal_id = self
            .try_get_internal_id(&url_get_id, &token.token())
            .await?;

        Ok(())
    }

    async fn try_get_internal_id(
        &self,
        url_get_id: &str,
        token: &str,
    ) -> Result<String, SMCumulocityMapperError> {
        let internal_id = self
            .http_con
            .get(url_get_id)
            .bearer_auth(token)
            .send()
            .await?;
        let internal_id_response = internal_id.json::<InternalIdResponse>().await?;

        let internal_id = internal_id_response.id();
        Ok(internal_id)
    }

    /// Make a POST request to /event/events and return the event id from response body.
    /// The event id is used to upload the binary.
    fn create_log_event(&self) -> C8yCreateEvent {
        let local: DateTime<Local> = Local::now();

        let c8y_managed_object = C8yManagedObject {
            id: self.end_point.c8y_internal_id.clone(),
        };

        C8yCreateEvent::new(
            c8y_managed_object.to_owned(),
            "c8y_Logfile",
            &local.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
            "software-management",
        )
    }

    async fn get_event_id(
        &self,
        c8y_event: C8yCreateEvent,
    ) -> Result<String, SMCumulocityMapperError> {
        let token = self.get_jwt_token().await?;
        let create_event_url = self.end_point.get_url_for_create_event();

        let request = self
            .http_con
            .post(create_event_url)
            .json(&c8y_event)
            .bearer_auth(token.token())
            .header("Accept", "application/json")
            .timeout(Duration::from_millis(10000))
            .build()?;

        let response = self.http_con.execute(request).await?;
        let event_response_body = response.json::<SmartRestLogEvent>().await?;

        Ok(event_response_body.id)
    }
}

#[async_trait]
impl C8YHttpProxy for JwtAuthHttpProxy {
    fn url_is_in_my_tenant_domain(&self, url: &str) -> bool {
        self.end_point.url_is_in_my_tenant_domain(url)
    }

    #[instrument(skip(self), name = "init"<