openiwan 0.3.0

An iWAN client and protocol library
Documentation
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
use super::http::{HttpRequest, HttpResponse, HttpTransport};
use super::security;
use crate::{Error, Result};
use serde::{Deserialize, Serialize};
use std::time::Duration;
use zeroize::Zeroizing;

#[derive(Clone)]
pub struct KeepaliveCredentials {
    pub access_token: Zeroizing<String>,
    pub refresh_token: Zeroizing<String>,
    pub app_id: String,
    pub app_secret: Zeroizing<String>,
    pub device_id: String,
}

impl std::fmt::Debug for KeepaliveCredentials {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("KeepaliveCredentials")
            .field("access_token", &"[REDACTED]")
            .field("refresh_token", &"[REDACTED]")
            .field("app_id", &self.app_id)
            .field("app_secret", &"[REDACTED]")
            .field("device_id", &self.device_id)
            .finish()
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct KeepaliveRequest {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub domain: Option<String>,
    #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")]
    pub service_type: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub oem_name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub device_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub server_id: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub serverlist_version: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path_metrics: Option<PathMetrics>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path_metrics_ts: Option<PathMetricsTs>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PathMetrics {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub iwan: Option<IwanMetrics>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sr: Option<SrMetrics>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct IwanMetrics {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub active: Option<IwanActive>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub servers: Option<Vec<IwanServerMetric>>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct IwanActive {
    pub server_id: i32,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct IwanServerMetric {
    pub server_id: i32,
    pub latency_ms: i32,
    #[serde(default)]
    pub latency_us: i32,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SrMetrics {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub active: Option<SrActive>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sites: Option<Vec<SrSiteMetric>>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct SrActive {
    pub group_id: i32,
    pub sr_id: i32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SrSiteMetric {
    pub id: i32,
    pub sr: Vec<SrPathMetric>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SrPathMetric {
    pub id: i32,
    pub latency_ms: i32,
    #[serde(default)]
    pub latency_us: i32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub full_path: Option<SrFullPathMetric>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct SrFullPathMetric {
    pub rtt_ms: i32,
    #[serde(default)]
    pub rtt_us: i32,
    pub loss_pct: i32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PathMetricsTs {
    pub sample_ts_ms: Vec<i64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub iwan: Option<IwanMetricsTs>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sr: Option<SrMetricsTs>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct IwanMetricsTs {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub active: Option<IwanActive>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub servers: Option<Vec<IwanServerMetricTs>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IwanServerMetricTs {
    pub server_id: i32,
    pub latency_us: Vec<Option<i32>>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SrMetricsTs {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub active: Option<SrActive>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub sites: Option<Vec<SrSiteMetricTs>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SrSiteMetricTs {
    pub id: i32,
    pub sr: Vec<SrPathMetricTs>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SrPathMetricTs {
    pub id: i32,
    pub latency_us: Vec<Option<i32>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub full_path: Option<SrFullPathMetricTs>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SrFullPathMetricTs {
    pub rtt_us: Vec<Option<i32>>,
    pub loss_pct: Vec<Option<i32>>,
}

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct KeepaliveResponse {
    #[serde(default)]
    pub timestamp: Option<String>,
    #[serde(default)]
    pub posture_ack: Option<PostureAck>,
    #[serde(default)]
    pub posture: Option<PostureUpdate>,
    #[serde(default)]
    pub device_binding: Option<DeviceBinding>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PostureAck {
    pub status: String,
    pub user_notice: UserNotice,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct UserNotice {
    pub reason_codes: Vec<Value>,
    pub title: String,
    pub message: String,
    pub title_en: String,
    pub message_en: String,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PostureUpdate {
    pub version: String,
    pub updated: bool,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DeviceBinding {
    pub action: String,
    #[serde(default)]
    pub reason: Option<String>,
}

use serde_json::Value;

pub fn send<T: HttpTransport>(
    transport: &T,
    endpoint: &str,
    credentials: &KeepaliveCredentials,
    request: &KeepaliveRequest,
) -> Result<KeepaliveResponse> {
    let body = serde_json::to_vec(request)
        .map_err(|error| Error::Controller(format!("serialize keepalive request: {error}")))?;
    let mut last_error = None;
    for _ in 0..2 {
        let response = match execute_once(transport, endpoint, credentials, &body) {
            Ok(response) => response,
            Err(error) => {
                last_error = Some(error);
                continue;
            }
        };
        match response.status {
            200 => match serde_json::from_slice(&response.body) {
                Ok(response) => return Ok(response),
                Err(error) => {
                    last_error = Some(Error::Controller(format!(
                        "invalid keepalive response: {error}"
                    )));
                }
            },
            401 => return Err(Error::ControllerUnauthorized),
            status => {
                last_error = Some(Error::Controller(format!(
                    "keepalive returned HTTP {status}"
                )));
            }
        }
    }
    Err(last_error.expect("two keepalive attempts always produce an error"))
}

fn execute_once<T: HttpTransport>(
    transport: &T,
    endpoint: &str,
    credentials: &KeepaliveCredentials,
    body: &[u8],
) -> Result<HttpResponse> {
    let mut authentication = security::mobile_api_headers_with_credentials(
        "POST",
        endpoint,
        body,
        &credentials.app_id,
        credentials.app_secret.as_str(),
    )?;
    let mut headers = vec![
        ("Content-Type".into(), "application/json".into()),
        ("X-Mobile-Api-Version".into(), "3".into()),
        (
            "Authorization".into(),
            format!("Bearer {}", credentials.access_token.as_str()),
        ),
    ];
    headers.append(&mut authentication);
    transport.execute(HttpRequest {
        method: "POST",
        url: endpoint.to_owned(),
        headers,
        body: body.to_vec(),
        timeout: Some(Duration::from_secs(5)),
    })
}

pub fn sign_request(
    endpoint: &str,
    exact_body: &[u8],
    timestamp: &str,
    nonce: &str,
    app_secret: &[u8],
) -> Result<String> {
    security::sign_http_request("POST", endpoint, exact_body, timestamp, nonce, app_secret)
}

pub fn canonical_request(
    endpoint: &str,
    exact_body: &[u8],
    timestamp: &str,
    nonce: &str,
) -> Result<String> {
    security::canonical_http_request("POST", endpoint, exact_body, timestamp, nonce)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::managed::http::HttpResponse;
    use std::collections::VecDeque;
    use std::sync::Mutex;
    use std::sync::atomic::{AtomicUsize, Ordering};

    #[test]
    fn matches_protocol_hmac_vector() {
        let endpoint = "https://controller.example/keepalive?b=two&a=one%20x&a=ignored&plus=a+b";
        let canonical = canonical_request(
            endpoint,
            br#"{"x":1}"#,
            "1700000000",
            "000102030405060708090a0b0c0d0e0f",
        )
        .unwrap();
        assert_eq!(
            canonical,
            "POST\n/keepalive\na=one x&b=two&plus=a b\n\
             5041bf1f713df204784353e82f6a4a535931cb64f1f4b4a5aeaffcb720918b22\n\
             1700000000\n000102030405060708090a0b0c0d0e0f"
        );
        assert_eq!(
            sign_request(
                endpoint,
                br#"{"x":1}"#,
                "1700000000",
                "000102030405060708090a0b0c0d0e0f",
                b"test-secret",
            )
            .unwrap(),
            "33c627d0d8fdfe78b4e57d2ca1113628647d9c1e71d8b6c03f2e958733f1aa79"
        );
    }

    #[test]
    fn path_metric_timestamp_requires_sample_array() {
        assert!(serde_json::from_str::<PathMetricsTs>(r#"{"iwan":{}}"#).is_err());
    }

    struct RetryTransport {
        calls: AtomicUsize,
        requests: Mutex<Vec<HttpRequest>>,
    }

    impl HttpTransport for RetryTransport {
        fn execute(&self, request: HttpRequest) -> Result<HttpResponse> {
            self.requests.lock().unwrap().push(request);
            if self.calls.fetch_add(1, Ordering::Relaxed) == 0 {
                Err(Error::Http("first transport failure".into()))
            } else {
                Ok(HttpResponse {
                    status: 200,
                    body: b"{}".to_vec(),
                })
            }
        }
    }

    #[test]
    fn retries_one_transport_failure_with_fresh_auth_headers() {
        let transport = RetryTransport {
            calls: AtomicUsize::new(0),
            requests: Mutex::new(Vec::new()),
        };
        let credentials = KeepaliveCredentials {
            access_token: Zeroizing::new("access".into()),
            refresh_token: Zeroizing::new("refresh".into()),
            app_id: "app".into(),
            app_secret: Zeroizing::new("secret".into()),
            device_id: "device".into(),
        };
        let request = KeepaliveRequest {
            domain: Some("example".into()),
            service_type: Some("device".into()),
            oem_name: Some("panabit".into()),
            device_id: Some("device".into()),
            ..KeepaliveRequest::default()
        };
        send(
            &transport,
            "https://controller.example/keepalive",
            &credentials,
            &request,
        )
        .unwrap();
        let requests = transport.requests.lock().unwrap();
        assert_eq!(requests.len(), 2);
        assert_eq!(requests[0].body, requests[1].body);
        assert!(
            requests[0]
                .headers
                .iter()
                .any(|header| header == &("X-Mobile-Api-Version".into(), "3".into()))
        );
        let nonce = header_value(&requests[0], "X-Auth-Nonce").as_bytes();
        assert_eq!(nonce.len(), 32);
        assert!(
            nonce
                .iter()
                .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(byte))
        );
        assert_ne!(
            header_value(&requests[0], "X-Auth-Nonce"),
            header_value(&requests[1], "X-Auth-Nonce")
        );
        assert_ne!(
            header_value(&requests[0], "X-Auth-Sign"),
            header_value(&requests[1], "X-Auth-Sign")
        );
    }

    struct StatusTransport {
        calls: AtomicUsize,
        statuses: Mutex<VecDeque<u16>>,
    }

    impl HttpTransport for StatusTransport {
        fn execute(&self, _request: HttpRequest) -> Result<HttpResponse> {
            self.calls.fetch_add(1, Ordering::Relaxed);
            Ok(HttpResponse {
                status: self.statuses.lock().unwrap().pop_front().unwrap(),
                body: b"{}".to_vec(),
            })
        }
    }

    #[test]
    fn retries_one_non_success_status() {
        let transport = StatusTransport {
            calls: AtomicUsize::new(0),
            statuses: Mutex::new(VecDeque::from([500, 200])),
        };
        send(
            &transport,
            "https://controller.example/keepalive",
            &test_credentials(),
            &KeepaliveRequest::default(),
        )
        .unwrap();
        assert_eq!(transport.calls.load(Ordering::Relaxed), 2);
    }

    #[test]
    fn does_not_retry_unauthorized() {
        let transport = StatusTransport {
            calls: AtomicUsize::new(0),
            statuses: Mutex::new(VecDeque::from([401, 200])),
        };
        let error = send(
            &transport,
            "https://controller.example/keepalive",
            &test_credentials(),
            &KeepaliveRequest::default(),
        )
        .unwrap_err();
        assert!(matches!(error, Error::ControllerUnauthorized));
        assert_eq!(transport.calls.load(Ordering::Relaxed), 1);
    }

    fn header_value<'a>(request: &'a HttpRequest, name: &str) -> &'a str {
        request
            .headers
            .iter()
            .find(|(header_name, _)| header_name == name)
            .unwrap()
            .1
            .as_str()
    }

    fn test_credentials() -> KeepaliveCredentials {
        KeepaliveCredentials {
            access_token: Zeroizing::new("access".into()),
            refresh_token: Zeroizing::new("refresh".into()),
            app_id: "app".into(),
            app_secret: Zeroizing::new("secret".into()),
            device_id: "device".into(),
        }
    }
}