denki 0.1.2

CLI for controlling TP-Link smart home devices — denki (電気) means electricity in Japanese
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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
use std::fmt;

use log::debug;
use reqwest::cookie::Cookie;
use reqwest::{Client, StatusCode, Url};
use serde::de::DeserializeOwned;

use crate::tapo_vendor::Error;
use crate::tapo_vendor::TapoResponseError;
use crate::tapo_vendor::requests::TapoRequest;
use crate::tapo_vendor::responses::TapoResponseExt;

use super::aes_ssl_protocol::{AesSslLogin, AesSslProtocol};
use super::klap_protocol::KlapProtocol;
use super::tpap_protocol::{TpapInfo, TpapProtocol};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DeviceFamily {
    Smart,
    SmartCam,
}

/// The authentication protocol used to communicate with a Tapo device.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum AuthProtocol {
    /// AES-based protocol over HTTPS with nonce-based authentication.
    /// Used by IP cameras, hubs, and doorbells. A camera hub that is reached
    /// by its IP address, and a device that announces it in discovery, is
    /// logged in to over this protocol only.
    AesSsl,
    /// KLAP (Key-Length-Authentication Protocol). Uses a handshake-derived
    /// symmetric cipher for request/response encryption.
    Klap,
    /// TPAP. Logs in with SPAKE2+ and encrypts requests and responses with
    /// AES-CCM. A device that announces it in discovery says how it wants
    /// to be logged in to as well, and is logged in to over this protocol
    /// only.
    TpapAnnounced(TpapInfo),
    /// TPAP first, and AES SSL if the device does not take that login. For
    /// a camera that is reached by its IP address, which gives no hint of
    /// the protocol it takes.
    TpapThenAesSsl,
    /// No protocol hint is available. The device is asked whether it speaks
    /// TPAP, and KLAP is used when it does not.
    Unknown,
}

enum ActiveProtocol {
    AesSsl(AesSslProtocol),
    Klap(KlapProtocol),
    Tpap(Box<TpapProtocol>),
}

pub(crate) struct TapoProtocol {
    client: Client,
    device_family: DeviceFamily,
    active: Option<ActiveProtocol>,
}

impl Clone for TapoProtocol {
    fn clone(&self) -> Self {
        // Intentionally drops session: cloned clients must re-discover and re-login.
        Self {
            client: self.client.clone(),
            device_family: self.device_family,
            active: None,
        }
    }
}

impl TapoProtocol {
    pub fn new(client: Client) -> Self {
        Self {
            client,
            // Overwritten by login() before any caller can read it,
            // because ApiClient::protocol() guards against pre-login access.
            device_family: DeviceFamily::Smart,
            active: None,
        }
    }

    pub fn device_family(&self) -> DeviceFamily {
        self.device_family
    }

    /// Logs in to the device at `ip_address` and returns the IP address and
    /// the port that it was reached at. An `http_port` is the port that the
    /// device announces its web server on, and only a KLAP login and the
    /// TPAP discover, both over plain HTTP, take it. A TPAP login takes the
    /// port that the device announces for TPAP.
    pub async fn login(
        &mut self,
        ip_address: &str,
        http_port: Option<u16>,
        username: &str,
        password: &str,
        device_family: DeviceFamily,
        auth_protocol: AuthProtocol,
    ) -> Result<(String, u16), Error> {
        self.device_family = device_family;

        if self.active.is_none() {
            let active = match auth_protocol {
                AuthProtocol::AesSsl => {
                    debug!("Using AES SSL protocol...");
                    ActiveProtocol::AesSsl(AesSslProtocol::new(self.client.clone()))
                }
                // A camera that is reached by its IP address is logged in
                // to while finding out which protocol it takes, so there is
                // nothing left to do after that.
                AuthProtocol::TpapThenAesSsl => {
                    return self
                        .login_tpap_then_aes_ssl(ip_address, username, password)
                        .await;
                }
                AuthProtocol::Klap => {
                    debug!("Using KLAP protocol (from discovery hint)...");
                    ActiveProtocol::Klap(KlapProtocol::new(self.client.clone()))
                }
                AuthProtocol::TpapAnnounced(info) => {
                    debug!("Using TPAP protocol (from discovery hint)...");
                    ActiveProtocol::Tpap(Box::new(TpapProtocol::new(
                        self.client.clone(),
                        info,
                        device_family,
                    )))
                }
                AuthProtocol::Unknown => {
                    let address = host_with_port(ip_address, http_port, 80);
                    match TpapProtocol::discover(&self.client, &address).await? {
                        Some(info) => {
                            debug!("Using TPAP protocol (negotiated)...");
                            ActiveProtocol::Tpap(Box::new(TpapProtocol::new(
                                self.client.clone(),
                                info,
                                device_family,
                            )))
                        }
                        None => {
                            debug!("Using KLAP protocol (negotiated)...");
                            ActiveProtocol::Klap(KlapProtocol::new(self.client.clone()))
                        }
                    }
                }
            };
            self.active = Some(active);
        }

        let url = match &self.active {
            Some(ActiveProtocol::AesSsl(_)) => format!("https://{ip_address}"),
            // A TPAP discover and a KLAP login reach the device at the same
            // address, so a KLAP login that follows a discover that found no
            // TPAP must take the address that the discover took.
            Some(ActiveProtocol::Klap(_)) => {
                format!("http://{}/app", host_with_port(ip_address, http_port, 80))
            }
            Some(ActiveProtocol::Tpap(p)) => p.info().url(ip_address)?,
            None => unreachable!(),
        };
        let address = url_address(&url)?;

        match &mut self.active {
            Some(ActiveProtocol::AesSsl(p)) => {
                p.login(url, username, password).await?.into_result()?
            }
            Some(ActiveProtocol::Klap(p)) => p.login(url, username, password).await?,
            Some(ActiveProtocol::Tpap(p)) => p.login(url, username, password).await?,
            None => unreachable!(),
        }

        Ok(address)
    }

    /// Logs in to a camera: over TPAP, and over AES SSL if the device does
    /// not take that login. A camera that takes TPAP does so whether or not
    /// it takes AES SSL, at the same URL, so both are tried at the one that
    /// TPAP names. It does not announce TPAP when asked, so it is not asked.
    async fn login_tpap_then_aes_ssl(
        &mut self,
        ip_address: &str,
        username: &str,
        password: &str,
    ) -> Result<(String, u16), Error> {
        let info = TpapInfo::camera();
        let url = info.url(ip_address)?;
        let address = url_address(&url)?;

        debug!("Using TPAP protocol (tried first)...");
        let mut tpap = TpapProtocol::new(self.client.clone(), info, self.device_family);

        let tpap_error = match tpap.login(url.clone(), username, password).await {
            Ok(()) => {
                self.active = Some(ActiveProtocol::Tpap(Box::new(tpap)));
                return Ok(address);
            }
            Err(error) if !falls_back_to_aes_ssl(&error) => return Err(error),
            Err(error) => error,
        };

        debug!("Using AES SSL protocol (TPAP login refused)...");
        let mut aes_ssl = AesSslProtocol::new(self.client.clone());

        match aes_ssl.login(url, username, password).await {
            Ok(AesSslLogin::LoggedIn) => {
                self.active = Some(ActiveProtocol::AesSsl(aes_ssl));
                Ok(address)
            }
            // The device takes neither login, and of the two errors the one
            // of the TPAP login says why.
            Ok(AesSslLogin::Refused(_)) => Err(tpap_error),
            // Both logins took the password as wrong, and the error of the
            // TPAP login also warns that the device locks itself.
            Err(Error::Tapo(TapoResponseError::Unauthorized {
                kind: "HASH_MISMATCH",
                ..
            })) if is_tpap_credentials(&tpap_error) => Err(tpap_error),
            Err(error) => Err(error),
        }
    }

    pub async fn refresh_session(&mut self, username: &str, password: &str) -> Result<(), Error> {
        match &mut self.active {
            Some(ActiveProtocol::AesSsl(p)) => p.refresh_session(username, password).await,
            Some(ActiveProtocol::Klap(p)) => p.refresh_session(username, password).await,
            Some(ActiveProtocol::Tpap(p)) => p.refresh_session(username, password).await,
            None => Err(anyhow::anyhow!(
                "Cannot refresh session: protocol not yet initialized (login first)"
            )
            .into()),
        }
    }

    pub async fn execute_request<R>(&self, request: TapoRequest) -> Result<Option<R>, Error>
    where
        R: fmt::Debug + DeserializeOwned + TapoResponseExt,
    {
        match &self.active {
            Some(ActiveProtocol::AesSsl(p)) => p.execute_request(request).await,
            Some(ActiveProtocol::Klap(p)) => p.execute_request(request).await,
            Some(ActiveProtocol::Tpap(p)) => p.execute_request(request).await,
            None => Err(anyhow::anyhow!(
                "Cannot execute request: protocol not yet initialized (login first)"
            )
            .into()),
        }
    }

    pub fn get_cookie<'a>(mut cookies: impl Iterator<Item = Cookie<'a>>) -> Result<String, Error> {
        let cookie = cookies.find(|c| c.name() == "TP_SESSIONID");

        match cookie {
            Some(cookie) => Ok(format!("{}={}", cookie.name(), cookie.value())),
            None => Err(Error::Tapo(TapoResponseError::ResponseError {
                description: "TP_SESSIONID cookie not found in response".to_string(),
            })),
        }
    }
}

/// `ip_address`, followed by `port` unless it is `default_port`, the port of
/// the scheme that the address is used with.
fn host_with_port(ip_address: &str, port: Option<u16>, default_port: u16) -> String {
    match port.filter(|port| *port != default_port) {
        Some(port) => format!("{ip_address}:{port}"),
        None => ip_address.to_string(),
    }
}

/// The host of `url` and its port, or the default port of its scheme when it
/// names none.
///
/// # Errors
///
/// Returns an error if `url` cannot be parsed or lacks a host or a port.
fn url_address(url: &str) -> Result<(String, u16), Error> {
    let parsed = Url::parse(url).map_err(|e| anyhow::anyhow!("Invalid URL {url}: {e}"))?;
    let host = parsed
        .host_str()
        .ok_or_else(|| anyhow::anyhow!("URL {url} does not name a host"))?;
    let port = parsed
        .port_or_known_default()
        .ok_or_else(|| anyhow::anyhow!("URL {url} does not name a port"))?;

    Ok((host.to_string(), port))
}

/// Whether a camera whose TPAP login failed with `error` is tried over AES
/// SSL. A device that cannot be reached is out of reach for AES SSL too,
/// and a device that has locked itself is left alone.
fn falls_back_to_aes_ssl(error: &Error) -> bool {
    match error {
        Error::Http(error) => !(error.is_connect() || error.is_timeout()),
        Error::Tapo(TapoResponseError::Unauthorized {
            kind: "TPAP_AUTH_ATTEMPTS_LIMIT",
            ..
        }) => false,
        _ => true,
    }
}

/// Whether a TPAP login failed with `error` because the password is wrong.
fn is_tpap_credentials(error: &Error) -> bool {
    matches!(
        error,
        Error::Tapo(TapoResponseError::Unauthorized {
            kind: "TPAP_CREDENTIALS",
            ..
        })
    )
}

/// The error for a request that the device answered with `status`. A device
/// that no longer knows the session answers with 401 or 403.
pub(super) fn request_error(status: StatusCode) -> Error {
    let error = match status {
        StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => {
            TapoResponseError::session_expired("SESSION_TIMEOUT")
        }
        _ => TapoResponseError::HttpError {
            status_code: status.as_u16(),
            description: "Request failed".to_string(),
        },
    };

    Error::Tapo(error)
}

#[cfg(test)]
mod tests {
    use crate::tapo_vendor::responses::validate_response;

    use super::*;

    #[test]
    fn host_with_port_names_a_port_other_than_the_default() {
        assert_eq!(host_with_port("192.168.1.100", None, 80), "192.168.1.100");
        assert_eq!(
            host_with_port("192.168.1.100", Some(80), 80),
            "192.168.1.100"
        );
        assert_eq!(
            host_with_port("192.168.1.100", Some(443), 443),
            "192.168.1.100"
        );
        assert_eq!(
            host_with_port("192.168.1.100", Some(8080), 80),
            "192.168.1.100:8080"
        );
    }

    #[test]
    fn url_address_is_the_host_and_the_port_of_the_url_or_the_default_of_its_scheme() {
        let address = |ip: &str, port| (ip.to_string(), port);

        assert_eq!(
            url_address("http://192.168.1.100/app").unwrap(),
            address("192.168.1.100", 80)
        );
        assert_eq!(
            url_address("https://192.168.1.100").unwrap(),
            address("192.168.1.100", 443)
        );
        assert_eq!(
            url_address("http://192.168.1.100:8080/app").unwrap(),
            address("192.168.1.100", 8080)
        );
    }

    #[tokio::test]
    async fn unreachable_device_does_not_fall_back_to_aes_ssl() {
        let error: Error = Client::new()
            .post("https://127.0.0.1:0/")
            .send()
            .await
            .unwrap_err()
            .into();

        assert!(!falls_back_to_aes_ssl(&error));
    }

    #[test]
    fn locked_device_does_not_fall_back_to_aes_ssl() {
        let error = validate_response(-2101).unwrap_err();

        assert!(!falls_back_to_aes_ssl(&error));
    }

    #[test]
    fn refused_tpap_login_falls_back_to_aes_ssl() {
        // A wrong password is among them: the first request of the AES SSL
        // login does not send one, so it costs no failed login.
        for error_code in [-40209, -40210, -40401, -2203] {
            let error = validate_response(error_code).unwrap_err();

            assert!(falls_back_to_aes_ssl(&error), "{error_code}");
        }

        // What `pake_share` turns the -40401 of a camera into.
        let error = Error::Tapo(TapoResponseError::tpap_credentials());

        assert!(falls_back_to_aes_ssl(&error));
    }

    #[test]
    fn request_error_of_an_unknown_session_is_an_expired_session() {
        // A C220 answers a request of an ended session with 401.
        for status in [StatusCode::UNAUTHORIZED, StatusCode::FORBIDDEN] {
            assert!(matches!(
                request_error(status),
                Error::Tapo(TapoResponseError::Unauthorized {
                    kind: "SESSION_TIMEOUT",
                    ..
                })
            ));
        }
    }

    #[test]
    fn request_error_of_another_status_is_an_http_error() {
        assert!(matches!(
            request_error(StatusCode::INTERNAL_SERVER_ERROR),
            Error::Tapo(TapoResponseError::HttpError {
                status_code: 500,
                ..
            })
        ));
    }
}

#[cfg(test)]
mod policy_tests {
    use super::*;
    use std::time::Duration;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    #[tokio::test]
    async fn strict_policy_fixture() {
        if std::env::var_os("DENKI_TPAP_POLICY_FIXTURE").is_none() {
            return;
        }
        assert_eq!(std::env::var("DENKI_REQUIRE_TPAP").unwrap(), "1");
        for auth in [AuthProtocol::Klap, AuthProtocol::AesSsl] {
            let mut protocol = TapoProtocol::new(Client::builder().no_proxy().build().unwrap());
            let error = protocol
                .login(
                    "192.0.2.1",
                    None,
                    "sentinel-user",
                    "sentinel-pass",
                    DeviceFamily::Smart,
                    auth,
                )
                .await
                .unwrap_err();
            assert!(
                matches!(error, Error::Other(ref e) if crate::error::code(e) == "authentication_policy")
            );
        }
        // A peer can suppress TPAP discovery, but cannot make strict mode send a
        // KLAP proof. Only the credential-free discover request reaches it.
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let address = listener.local_addr().unwrap();
        let server = tokio::spawn(async move {
            let (mut socket, _) = listener.accept().await.unwrap();
            let mut request = Vec::new();
            let mut buf = [0u8; 1024];
            loop {
                let n = socket.read(&mut buf).await.unwrap();
                assert!(n > 0);
                request.extend_from_slice(&buf[..n]);
                if request.windows(b"discover".len()).any(|w| w == b"discover") {
                    break;
                }
                assert!(request.len() < 4096);
            }
            assert!(!String::from_utf8_lossy(&request).contains("sentinel"));
            socket
                .write_all(
                    b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
                )
                .await
                .unwrap();
            drop(socket);
            assert!(
                tokio::time::timeout(Duration::from_millis(150), listener.accept())
                    .await
                    .is_err()
            );
        });
        let mut protocol = TapoProtocol::new(Client::builder().no_proxy().build().unwrap());
        let error = protocol
            .login(
                "127.0.0.1",
                Some(address.port()),
                "sentinel-user",
                "sentinel-pass",
                DeviceFamily::Smart,
                AuthProtocol::Unknown,
            )
            .await
            .unwrap_err();
        assert!(
            matches!(error, Error::Other(ref e) if crate::error::code(e) == "authentication_policy")
        );
        server.await.unwrap();
    }

    #[test]
    fn strict_policy_refuses_explicit_and_negotiated_fallback_before_authentication() {
        let result = std::process::Command::new(std::env::current_exe().unwrap())
            .args([
                "--exact",
                "tapo_vendor::api::protocol::tapo_protocol::policy_tests::strict_policy_fixture",
                "--nocapture",
            ])
            .env("DENKI_TPAP_POLICY_FIXTURE", "1")
            .env("DENKI_REQUIRE_TPAP", "1")
            .output()
            .unwrap();
        assert!(
            result.status.success(),
            "{}",
            String::from_utf8_lossy(&result.stderr)
        );
        assert!(String::from_utf8_lossy(&result.stdout).contains("1 passed"));
    }
}