tr064 0.1.2

Vendor-neutral client for the TR-064 (UPnP/SOAP) device management protocol
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
//! The client against a fake device on the loopback interface.

use std::collections::HashMap;
use std::fmt::Write as _;
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, AtomicUsize, Ordering};
use std::time::Duration;

use axum::Router;
use axum::extract::State;
use axum::http::header::{AUTHORIZATION, CONTENT_TYPE, WWW_AUTHENTICATE};
use axum::http::{HeaderMap, HeaderValue, Method, StatusCode, Uri};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use md5::{Digest as _, Md5};
use tr064::{Client, Error, SecretString, Service, Url};

const DESCRIPTION: &str = include_str!("data/tr64desc.xml");
const SCPD: &str = include_str!("data/deviceinfoSCPD.xml");
const SERVICE_TYPE: &str = "urn:dslforum-org:service:DeviceInfo:1";

#[derive(Default)]
struct Device {
    requests: AtomicUsize,
    nonce: AtomicU32,
}

impl Device {
    fn requests(&self) -> usize {
        self.requests.load(Ordering::SeqCst)
    }

    fn nonce(&self) -> String {
        format!("nonce-{}", self.nonce.load(Ordering::SeqCst))
    }

    /// Whether the request carries a valid answer to the current challenge.
    fn authorized(&self, headers: &HeaderMap, method: &Method, uri: &str) -> bool {
        let Some(params) = headers
            .get(AUTHORIZATION)
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.strip_prefix("Digest "))
            .map(|v| {
                v.split(", ")
                    .filter_map(|p| p.split_once('='))
                    .map(|(k, v)| (k.to_owned(), v.trim_matches('"').to_owned()))
                    .collect::<HashMap<_, _>>()
            })
        else {
            return false;
        };
        let ha1 = md5_hex("user:test:secret");
        let ha2 = md5_hex(&format!("{method}:{uri}"));
        let expected = md5_hex(&format!(
            "{ha1}:{}:{}:{}:auth:{ha2}",
            self.nonce(),
            params["nc"],
            params["cnonce"]
        ));
        params["username"] == "user"
            && params["uri"] == uri
            && params["nonce"] == self.nonce()
            && params["response"] == expected
    }

    fn challenge(&self) -> Response {
        let mut headers = HeaderMap::new();
        headers.append(
            WWW_AUTHENTICATE,
            HeaderValue::from_static("Basic realm=\"test\""),
        );
        headers.append(
            WWW_AUTHENTICATE,
            HeaderValue::from_str(&format!(
                r#"Digest realm="test", nonce="{}", qop="auth", algorithm=MD5"#,
                self.nonce()
            ))
            .unwrap(),
        );
        (StatusCode::UNAUTHORIZED, headers).into_response()
    }
}

fn md5_hex(data: &str) -> String {
    Md5::digest(data.as_bytes())
        .iter()
        .fold(String::new(), |mut s, b| {
            let _ = write!(s, "{b:02x}");
            s
        })
}

fn envelope(body: &str) -> String {
    format!(
        r#"<?xml version="1.0"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body>{body}</s:Body></s:Envelope>"#
    )
}

async fn control(State(device): State<Arc<Device>>, headers: HeaderMap, body: String) -> Response {
    device.requests.fetch_add(1, Ordering::SeqCst);
    if !device.authorized(&headers, &Method::POST, "/upnp/control/deviceinfo") {
        return device.challenge();
    }
    let action = headers["SOAPAction"]
        .to_str()
        .unwrap()
        .strip_prefix(&format!("\"{SERVICE_TYPE}#"))
        .and_then(|a| a.strip_suffix('"'))
        .unwrap()
        .to_owned();
    assert_eq!(headers[CONTENT_TYPE], r#"text/xml; charset="utf-8""#);
    let request = roxmltree::Document::parse(&body).unwrap();
    let call = request
        .descendants()
        .find(|n| n.tag_name().name() == action)
        .unwrap();
    assert_eq!(call.tag_name().namespace(), Some(SERVICE_TYPE));
    let response = |inner: &str| {
        envelope(&format!(
            r#"<u:{action}Response xmlns:u="{SERVICE_TYPE}">{inner}</u:{action}Response>"#
        ))
    };
    match action.as_str() {
        "GetInfo" => response(
            "<NewManufacturerName>Example</NewManufacturerName><NewUpTime>42</NewUpTime><NewEmpty/>",
        )
        .into_response(),
        "Echo" => {
            let value = call
                .children()
                .find(|n| n.tag_name().name() == "NewValue")
                .and_then(|n| n.text())
                .unwrap_or_default()
                .replace('&', "&amp;")
                .replace('<', "&lt;");
            response(&format!("<NewValue>{value}</NewValue>")).into_response()
        }
        "Fail" => (
            StatusCode::INTERNAL_SERVER_ERROR,
            envelope(
                "<s:Fault><faultcode>s:Client</faultcode><faultstring>UPnPError</faultstring>\
                 <detail><UPnPError xmlns=\"urn:schemas-upnp-org:control-1-0\">\
                 <errorCode>606</errorCode><errorDescription>Action not authorized</errorDescription>\
                 </UPnPError></detail></s:Fault>",
            ),
        )
            .into_response(),
        "Broken" => (StatusCode::INTERNAL_SERVER_ERROR, "oops").into_response(),
        "Teapot" => StatusCode::IM_A_TEAPOT.into_response(),
        "Wrong" => envelope("<OtherResponse/>").into_response(),
        "NoBody" => "<s:Envelope xmlns:s=\"x\"/>".into_response(),
        _ => StatusCode::BAD_REQUEST.into_response(),
    }
}

async fn protected(State(device): State<Arc<Device>>, headers: HeaderMap, uri: Uri) -> Response {
    device.requests.fetch_add(1, Ordering::SeqCst);
    let uri = uri.path_and_query().unwrap().as_str();
    if device.authorized(&headers, &Method::GET, uri) {
        "welcome".into_response()
    } else {
        device.challenge()
    }
}

async fn start() -> (Url, Arc<Device>) {
    let device = Arc::new(Device::default());
    let app = Router::new()
        .route("/tr64desc.xml", get(|| async { DESCRIPTION }))
        .route("/deviceinfoSCPD.xml", get(|| async { SCPD }))
        .route("/upnp/control/deviceinfo", post(control))
        .route("/protected", get(protected))
        .route(
            "/expire",
            get(|State(device): State<Arc<Device>>| async move {
                device.nonce.fetch_add(1, Ordering::SeqCst);
            }),
        )
        .route(
            "/basic",
            get(|| async {
                (
                    StatusCode::UNAUTHORIZED,
                    [(WWW_AUTHENTICATE, "Basic realm=\"test\"")],
                )
            }),
        )
        .route("/no-challenge", get(|| async { StatusCode::UNAUTHORIZED }))
        .route(
            "/session",
            get(|headers: HeaderMap| async move {
                if headers.get("Authorization").and_then(|v| v.to_str().ok()) == Some("Token abc") {
                    "session".into_response()
                } else {
                    StatusCode::FORBIDDEN.into_response()
                }
            }),
        )
        .route(
            "/form",
            post(|headers: HeaderMap, body: String| async move {
                let kind = headers
                    .get(CONTENT_TYPE)
                    .unwrap()
                    .to_str()
                    .unwrap()
                    .to_owned();
                format!("{kind} {body}")
            }),
        )
        .with_state(Arc::clone(&device));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let url = Url::parse(&format!("http://{}", listener.local_addr().unwrap())).unwrap();
    tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
    (url, device)
}

fn client(url: Url, password: &str) -> Client {
    Client::builder(url)
        .credentials("user", SecretString::from(password))
        .timeout(Duration::from_secs(5))
        .build()
        .unwrap()
}

async fn device_info(client: &Client) -> Service {
    let description = client.description().await.unwrap();
    description.service("DeviceInfo1").unwrap().clone()
}

#[tokio::test]
async fn fetches_description_and_scpd() {
    let (url, _) = start().await;
    let client = Client::builder(url).build().unwrap();
    let service = device_info(&client).await;
    let scpd = client.scpd(&service).await.unwrap();
    assert!(scpd.action("GetInfo").is_some());
}

#[tokio::test]
async fn calls_action_with_digest_auth() {
    let (url, device) = start().await;
    let client = client(url, "secret");
    let service = device_info(&client).await;

    let out = client.call(&service, "GetInfo", &[]).await.unwrap();
    assert_eq!(out.get("NewManufacturerName"), Some("Example"));
    assert_eq!(out.get("NewUpTime"), Some("42"));
    assert_eq!(out.get("NewEmpty"), Some(""));
    assert_eq!(out.get("NewMissing"), None);
    assert_eq!(out.len(), 3);
    assert!(!out.is_empty());
    assert_eq!(
        out.iter().map(|(name, _)| name).collect::<Vec<_>>(),
        ["NewManufacturerName", "NewUpTime", "NewEmpty"]
    );
    // The first call answers the challenge, the second reuses the answer.
    assert_eq!(device.requests(), 2);
    client.call(&service, "GetInfo", &[]).await.unwrap();
    assert_eq!(device.requests(), 3);
}

#[tokio::test]
async fn escapes_argument_values() {
    let (url, _) = start().await;
    let client = client(url, "secret");
    let service = device_info(&client).await;
    let value = r#"a<b & "c" 'd' >"#;
    let out = client
        .call(&service, "Echo", &[("NewValue", value)])
        .await
        .unwrap();
    let pairs: Vec<_> = out.into_iter().collect();
    assert_eq!(pairs, [("NewValue".to_owned(), value.to_owned())]);
}

#[tokio::test]
async fn answers_new_challenge_when_nonce_expires() {
    let (url, device) = start().await;
    let client = client(url, "secret");
    assert_eq!(client.get("/protected?x=1").await.unwrap(), "welcome");
    assert_eq!(device.requests(), 2);
    client.get("/expire").await.unwrap();
    assert_eq!(client.get("/protected?x=1").await.unwrap(), "welcome");
    assert_eq!(device.requests(), 4);
}

#[tokio::test]
async fn stops_after_rejected_password() {
    let (url, device) = start().await;
    let client = client(url, "wrong");
    let err = client.get("/protected").await.unwrap_err();
    assert!(matches!(err, Error::AuthenticationFailed));
    assert_eq!(err.to_string(), "the device rejected the credentials");
    assert_eq!(device.requests(), 2);
}

#[tokio::test]
async fn requires_credentials() {
    let (url, device) = start().await;
    let client = Client::builder(url).build().unwrap();
    let err = client.get("/protected").await.unwrap_err();
    assert!(matches!(err, Error::CredentialsRequired));
    assert_eq!(err.to_string(), "the device requires credentials");
    assert_eq!(device.requests(), 1);
}

#[tokio::test]
async fn rejects_unsupported_challenges() {
    let (url, _) = start().await;
    let client = client(url, "secret");
    let err = client.get("/basic").await.unwrap_err();
    assert_eq!(
        err.to_string(),
        "unsupported authentication challenge: Basic realm=\"test\""
    );
    let err = client.get("/no-challenge").await.unwrap_err();
    assert_eq!(
        err.to_string(),
        "unsupported authentication challenge: no WWW-Authenticate header"
    );
}

#[tokio::test]
async fn sends_additional_headers() {
    let (url, _) = start().await;
    let client = Client::builder(url).build().unwrap();
    let body = client
        .get_with_headers("/session", &[("Authorization", "Token abc")])
        .await
        .unwrap();
    assert_eq!(body, "session");
    let err = client.get("/session").await.unwrap_err();
    assert!(matches!(err, Error::Status { status: 403, .. }), "{err:?}");
    let err = client
        .get_with_headers("/session", &[("in valid", "x")])
        .await
        .unwrap_err();
    assert!(matches!(err, Error::Http(_)), "{err:?}");
}

#[tokio::test]
async fn posts_forms() {
    let (url, _) = start().await;
    let client = Client::builder(url).build().unwrap();
    let body = client
        .post_form("/form", &[("username", "a b"), ("response", "x&y=z")])
        .await
        .unwrap();
    assert_eq!(
        body,
        "application/x-www-form-urlencoded username=a+b&response=x%26y%3Dz"
    );
    let err = client
        .post_form("http://192.0.2.1/form", &[])
        .await
        .unwrap_err();
    assert!(matches!(err, Error::InvalidUrl(_)), "{err:?}");
}

#[tokio::test]
async fn reports_upnp_errors() {
    let (url, _) = start().await;
    let client = client(url, "secret");
    let service = device_info(&client).await;
    let err = client.call(&service, "Fail", &[]).await.unwrap_err();
    assert!(matches!(err, Error::Upnp { code: 606, .. }));
    assert_eq!(err.to_string(), "UPnP error 606: Action not authorized");
}

#[tokio::test]
async fn reports_http_status() {
    let (url, _) = start().await;
    let client = client(url.clone(), "secret");
    let service = device_info(&client).await;
    let control = url.join("/upnp/control/deviceinfo").unwrap();
    for (action, status) in [("Broken", 500), ("Teapot", 418)] {
        let err = client.call(&service, action, &[]).await.unwrap_err();
        assert_eq!(
            err.to_string(),
            format!("HTTP status {status} from {control}")
        );
    }
    let err = client.get("/missing").await.unwrap_err();
    assert!(matches!(err, Error::Status { status: 404, .. }));
}

#[tokio::test]
async fn rejects_unexpected_responses() {
    let (url, _) = start().await;
    let client = client(url, "secret");
    let service = device_info(&client).await;
    let err = client.call(&service, "Wrong", &[]).await.unwrap_err();
    assert_eq!(
        err.to_string(),
        "invalid response: no <WrongResponse> in the SOAP Body"
    );
    let err = client.call(&service, "NoBody", &[]).await.unwrap_err();
    assert_eq!(err.to_string(), "invalid response: no SOAP Body");
}

#[tokio::test]
async fn rejects_invalid_names_before_sending() {
    let (url, device) = start().await;
    let client = client(url, "secret");
    let service = device_info(&client).await;
    let err = client.call(&service, "Get Info", &[]).await.unwrap_err();
    assert_eq!(err.to_string(), r#"invalid action name "Get Info""#);
    let err = client
        .call(&service, "GetInfo", &[("1st", "x")])
        .await
        .unwrap_err();
    assert_eq!(err.to_string(), r#"invalid argument name "1st""#);
    let err = client.call(&service, "", &[]).await.unwrap_err();
    assert_eq!(err.to_string(), r#"invalid action name """#);
    assert_eq!(device.requests(), 0);
}

#[tokio::test]
async fn keeps_requests_on_the_device() {
    let (url, _) = start().await;
    let client = client(url.clone(), "secret");
    let err = client.get("http://192.0.2.1/x").await.unwrap_err();
    assert_eq!(
        err.to_string(),
        format!(
            "invalid URL: http://192.0.2.1/x is not on the device {}",
            url.origin().ascii_serialization()
        )
    );
    let err = client.get("http://[::1").await.unwrap_err();
    assert_eq!(
        err.to_string(),
        r#"invalid URL: "http://[::1": invalid IPv6 address"#
    );
}

#[tokio::test]
async fn reports_unreachable_devices() {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let url = Url::parse(&format!("http://{}", listener.local_addr().unwrap())).unwrap();
    drop(listener);
    let err = Client::builder(url)
        .build()
        .unwrap()
        .get("/")
        .await
        .unwrap_err();
    assert!(matches!(err, Error::Http(_)));
    assert!(err.to_string().starts_with("HTTP request failed: "));
}

/// Shows every value except those of names with `Secret`.
#[derive(Debug)]
struct ShowPlain;

impl tr064::Redact for ShowPlain {
    fn argument(&self, _: &Service, _: &str, name: &str, value: &str) -> String {
        self.parameter(name, value)
    }

    fn parameter(&self, name: &str, value: &str) -> String {
        if name.contains("Secret") {
            tr064::HIDDEN.to_owned()
        } else {
            value.to_owned()
        }
    }
}

/// Collects the log.
#[derive(Clone, Default)]
struct Log(Arc<std::sync::Mutex<Vec<u8>>>);

impl std::io::Write for Log {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.0.lock().unwrap().extend_from_slice(buf);
        Ok(buf.len())
    }

    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

impl Log {
    fn text(&self) -> String {
        String::from_utf8(self.0.lock().unwrap().clone()).unwrap()
    }
}

/// A cache in memory that records the descriptions it gets.
#[derive(Debug, Default)]
struct Memory {
    scpds: std::sync::Mutex<HashMap<String, tr064::Scpd>>,
    descriptions: std::sync::Mutex<Vec<String>>,
}

impl tr064::DescriptionCache for Memory {
    fn scpd(&self, description: &str, url: &str) -> Option<tr064::Scpd> {
        self.descriptions
            .lock()
            .unwrap()
            .push(description.to_owned());
        self.scpds.lock().unwrap().get(url).cloned()
    }

    fn store(&self, description: &str, url: &str, xml: &str, scpd: &tr064::Scpd) {
        assert_eq!(description, DESCRIPTION);
        assert_eq!(xml, SCPD);
        self.scpds
            .lock()
            .unwrap()
            .insert(url.to_owned(), scpd.clone());
    }
}

#[tokio::test]
async fn logs_requests_without_secrets() {
    let log = Log::default();
    let writer = log.clone();
    let subscriber = tracing_subscriber::fmt()
        .with_max_level(tracing::Level::TRACE)
        .with_writer(move || writer.clone())
        .finish();
    // Global: a subscriber of one thread can miss events whose callsites
    // other tests registered first. The other tests may log here too.
    tracing::subscriber::set_global_default(subscriber).unwrap();

    let (url, _) = start().await;
    let client = Client::builder(url.clone())
        .credentials("user", SecretString::from("secret"))
        .redact(Arc::new(ShowPlain))
        .build()
        .unwrap();
    let service = device_info(&client).await;
    client
        .call(&service, "Echo", &[("NewValue", "plain")])
        .await
        .unwrap();
    client
        .call(&service, "Echo", &[("NewSecret", "hidden-value")])
        .await
        .unwrap();
    client
        .get("/protected?NewSecret=token-value&x=1")
        .await
        .unwrap();
    client.get("/expire").await.unwrap();
    client.get("/protected").await.unwrap();
    client.get("/basic").await.unwrap_err();
    client.get("/missing").await.unwrap_err();
    let wrong = self::client(url.clone(), "wrong-password");
    wrong.get("/protected").await.unwrap_err();
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let gone = Url::parse(&format!("http://{}", listener.local_addr().unwrap())).unwrap();
    drop(listener);
    let client = Client::builder(gone).build().unwrap();
    client.get("/").await.unwrap_err();

    let text = log.text();
    let control = format!(
        "url=http://{}/upnp/control/deviceinfo action=\"{SERVICE_TYPE}#Echo\" status=200",
        url.authority()
    );
    for expected in [
        "INFO tr064::client: request method=GET url=http://",
        "/tr64desc.xml status=200",
        &control,
        r#"call action="Echo" arguments=NewValue="plain""#,
        r#"answer action="Echo" arguments=NewValue="plain""#,
        r#"arguments=NewSecret="***""#,
        "/protected?NewSecret=***&x=1 status=200",
        "document bytes=7",
        r#"the device asks for Digest authentication challenge=realm="test", algorithm=MD5, qop=auth"#,
        "answering the previous Digest challenge again",
        "the device accepted the Digest answer",
        "the device rejected the Digest answer",
        "/basic error=unsupported authentication challenge",
        "/missing status=404",
        "request failed method=GET url=http://127.0.0.1:",
        "error=HTTP request failed: ",
    ] {
        assert!(text.contains(expected), "{expected} in {text}");
    }
    for secret in [
        "hidden-value",
        "token-value",
        "wrong-password",
        "nonce-",
        "cnonce",
        "response=",
        "Authorization",
    ] {
        assert!(!text.contains(secret), "{secret} in {text}");
    }
}

#[tokio::test]
async fn asks_the_cache_after_the_description() {
    let (url, _) = start().await;
    let cache = Arc::new(Memory::default());
    let client = Client::builder(url).cache(cache.clone()).build().unwrap();

    // Without a description, the cache is not asked.
    let description = tr064::DeviceDescription::parse(DESCRIPTION).unwrap();
    let mut service = description.service("DeviceInfo1").unwrap().clone();
    let fetched = client.scpd(&service).await.unwrap();
    assert!(cache.descriptions.lock().unwrap().is_empty());
    assert!(cache.scpds.lock().unwrap().is_empty());

    // After it, the client stores what it fetches, and then takes it from
    // the cache without a request: the URL does not exist.
    device_info(&client).await;
    assert_eq!(client.scpd(&service).await.unwrap(), fetched);
    let stored = cache.scpds.lock().unwrap().remove(&service.scpd_url);
    service.scpd_url = "/missing.xml".to_owned();
    cache
        .scpds
        .lock()
        .unwrap()
        .insert(service.scpd_url.clone(), stored.unwrap());
    assert_eq!(client.scpd(&service).await.unwrap(), fetched);
    assert_eq!(*cache.descriptions.lock().unwrap(), [DESCRIPTION; 2]);
}