Skip to main content

fritz_sim/
lib.rs

1//! Stateful fake TR-064 server, built from recorded fixtures. Used by tests
2//! only: every write test runs against it, never against a real device.
3//!
4//! [`Sim::start`] serves a [`Fixture`] on the loopback interface: the device
5//! description and the service descriptions without authentication, and
6//! the action calls with HTTP Digest authentication.
7//!
8//! - Calls are checked against the service description: an unknown action
9//!   fails with UPnP error 401, missing or unknown arguments with 402, and
10//!   values that don't fit the data type or the allowed values with 600.
11//!   Like the devices, it doesn't check the allowed range.
12//! - Getters answer as recorded. Getters with an index answer the recorded
13//!   entry, or 713 if there is none.
14//! - Every argument refers to a state variable. Calls of other actions, like
15//!   `SetEnable`, write their input arguments into these variables, and the
16//!   getters that read the same variables answer with the new values.
17//! - Paths to list documents, like the one `X_AVM-DE_GetHostListPath`
18//!   returns, hold a session ID, and the documents are served for it.
19//! - The web interface has a session login, `/login_sid.lua`, with a
20//!   PBKDF2 challenge, and serves the documents of the REST API, like
21//!   `/api/v0/smarthome/overview`, for the open session.
22//! - Tests can [inject](Sim::inject) UPnP errors, delays, discarded writes
23//!   and a locked login, and read the [requests](Sim::requests) the server
24//!   got.
25//!
26//! ```no_run
27//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
28//! use fritz_sim::{Fixture, Injection, Sim};
29//!
30//! let sim = Sim::start(Fixture::bundled("fritzbox-7690/8.25")?).await?;
31//! let client = sim.client().build()?;
32//! let description = client.description().await?;
33//! let wlan = description.service("WLANConfiguration1")?;
34//! client.call(wlan, "SetEnable", &[("NewEnable", "0")]).await?;
35//! assert_eq!(sim.state("WLANConfiguration1", "Enable").as_deref(), Some("0"));
36//!
37//! sim.inject(Injection::fault("WLANConfiguration1", "SetEnable", 866));
38//! assert!(client.call(wlan, "SetEnable", &[("NewEnable", "1")]).await.is_err());
39//! # Ok(())
40//! # }
41//! ```
42
43use std::future::IntoFuture as _;
44use std::io;
45use std::net::{Ipv4Addr, SocketAddr};
46use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
47use std::time::Duration;
48
49use axum::Router;
50use axum::extract::State;
51use axum::http::header::{AUTHORIZATION, CONTENT_TYPE, WWW_AUTHENTICATE};
52use axum::http::{HeaderMap, Method, StatusCode, Uri};
53use axum::response::{IntoResponse, Response};
54use tokio::task::JoinHandle;
55use tr064::{ClientBuilder, Fingerprint, SecretString, Service, Url};
56
57mod auth;
58mod device;
59mod fixture;
60mod soap;
61mod tls;
62mod web;
63
64use device::{Device, Fault, Hooks, short_id};
65pub use fixture::{Answer, Error, Fixture};
66use tls::TlsListener;
67use web::Web;
68
69/// The user name the simulator accepts by default.
70pub const USERNAME: &str = "fritz-sim";
71/// The password the simulator accepts by default.
72pub const PASSWORD: &str = "fritz-sim-password";
73
74const XML: &str = r#"text/xml; charset="utf-8""#;
75
76/// How the simulator listens and whom it lets in.
77#[derive(Debug, Clone)]
78pub struct Options {
79    /// Port 0 picks a free port.
80    pub address: SocketAddr,
81    pub username: String,
82    pub password: String,
83    /// Serve HTTPS with a new self-signed certificate, see
84    /// [`Sim::fingerprint`].
85    pub https: bool,
86}
87
88impl Default for Options {
89    /// A free port on the loopback interface, plain HTTP, with [`USERNAME`]
90    /// and [`PASSWORD`].
91    fn default() -> Self {
92        Self {
93            address: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
94            username: USERNAME.to_owned(),
95            password: PASSWORD.to_owned(),
96            https: false,
97        }
98    }
99}
100
101/// A change to how the simulator behaves, until
102/// [cleared](Sim::clear_injections).
103#[derive(Debug, Clone, PartialEq, Eq)]
104#[non_exhaustive]
105pub enum Injection {
106    /// Calls of an action fail with a UPnP error once their arguments are
107    /// valid. `service` is any reference [`Service::matches`] accepts, like
108    /// `WLANConfiguration1`.
109    Fault {
110        service: String,
111        action: String,
112        code: u16,
113    },
114    /// Every response is sent after a delay, to make clients time out.
115    Delay(Duration),
116    /// Writes succeed, but change nothing.
117    DiscardWrites,
118    /// The account is locked: every login fails, even with the right
119    /// password.
120    LockLogin,
121}
122
123impl Injection {
124    /// Calls of `action` of `service` fail with the UPnP error `code`.
125    pub fn fault(service: impl Into<String>, action: impl Into<String>, code: u16) -> Self {
126        Self::Fault {
127            service: service.into(),
128            action: action.into(),
129            code,
130        }
131    }
132}
133
134/// A request the simulator got.
135#[derive(Debug, Clone, PartialEq, Eq)]
136pub struct Request {
137    pub method: String,
138    pub path: String,
139    /// The action, for action calls.
140    pub action: Option<String>,
141    /// The input arguments, for action calls.
142    pub arguments: Vec<(String, String)>,
143    /// Whether the request carried valid credentials.
144    pub authorized: bool,
145}
146
147/// A running simulator. It stops when dropped.
148#[derive(Debug)]
149pub struct Sim {
150    url: Url,
151    fingerprint: Option<Fingerprint>,
152    shared: Arc<Shared>,
153    server: JoinHandle<io::Result<()>>,
154}
155
156impl Sim {
157    /// Serves `fixture` on a free port of the loopback interface, with
158    /// [`USERNAME`] and [`PASSWORD`].
159    ///
160    /// # Errors
161    ///
162    /// The errors of binding the port.
163    pub async fn start(fixture: Fixture) -> io::Result<Self> {
164        Self::start_with(fixture, Options::default()).await
165    }
166
167    /// Serves `fixture` as configured.
168    ///
169    /// # Errors
170    ///
171    /// The errors of binding the address.
172    pub async fn start_with(fixture: Fixture, options: Options) -> io::Result<Self> {
173        let listener = tokio::net::TcpListener::bind(options.address).await?;
174        let scheme = if options.https { "https" } else { "http" };
175        let url = Url::parse(&format!("{scheme}://{}", listener.local_addr()?))
176            .map_err(io::Error::other)?;
177        let https = options.https;
178        let shared = Arc::new(Shared {
179            options,
180            inner: Mutex::new(Inner {
181                device: Device::new(fixture),
182                web: Web::default(),
183                injections: Vec::new(),
184                requests: Vec::new(),
185            }),
186        });
187        let app = Router::new()
188            .fallback(handle)
189            .with_state(Arc::clone(&shared));
190        let (server, fingerprint) = if https {
191            let (listener, fingerprint) = TlsListener::new(listener);
192            let server = tokio::spawn(axum::serve(listener, app).into_future());
193            (server, Some(fingerprint))
194        } else {
195            (tokio::spawn(axum::serve(listener, app).into_future()), None)
196        };
197        Ok(Self {
198            url,
199            fingerprint,
200            shared,
201            server,
202        })
203    }
204
205    /// The base URL, like `http://127.0.0.1:49000`.
206    pub fn url(&self) -> &Url {
207        &self.url
208    }
209
210    /// The fingerprint of the certificate, if the simulator serves HTTPS.
211    pub fn fingerprint(&self) -> Option<Fingerprint> {
212        self.fingerprint
213    }
214
215    /// A client builder for the simulator, with its credentials and, for
216    /// HTTPS, its certificate pinned.
217    pub fn client(&self) -> ClientBuilder {
218        let options = &self.shared.options;
219        let builder = tr064::Client::builder(self.url.clone()).credentials(
220            options.username.clone(),
221            SecretString::from(options.password.clone()),
222        );
223        match self.fingerprint {
224            Some(fingerprint) => builder.pin(fingerprint),
225            None => builder,
226        }
227    }
228
229    /// Changes how the simulator behaves from the next request on.
230    pub fn inject(&self, injection: Injection) {
231        self.shared.lock().injections.push(injection);
232    }
233
234    /// Removes all injections.
235    pub fn clear_injections(&self) {
236        self.shared.lock().injections.clear();
237    }
238
239    /// The requests the simulator got so far, oldest first.
240    pub fn requests(&self) -> Vec<Request> {
241        self.shared.lock().requests.clone()
242    }
243
244    /// The value of a state variable of a service, like `Enable` of
245    /// `WLANConfiguration1`. `service` is any reference
246    /// [`Service::matches`] accepts.
247    pub fn state(&self, service: &str, variable: &str) -> Option<String> {
248        let inner = self.shared.lock();
249        let service = inner.device.fixture.description.service(service).ok()?;
250        inner
251            .device
252            .state(short_id(service), variable)
253            .map(str::to_owned)
254    }
255}
256
257impl Drop for Sim {
258    fn drop(&mut self) {
259        self.server.abort();
260    }
261}
262
263#[derive(Debug)]
264struct Shared {
265    options: Options,
266    inner: Mutex<Inner>,
267}
268
269#[derive(Debug)]
270struct Inner {
271    device: Device,
272    web: Web,
273    injections: Vec<Injection>,
274    requests: Vec<Request>,
275}
276
277impl Shared {
278    fn lock(&self) -> MutexGuard<'_, Inner> {
279        self.inner.lock().unwrap_or_else(PoisonError::into_inner)
280    }
281
282    /// Answers a request, and the delay before the answer.
283    fn respond(
284        &self,
285        method: &Method,
286        uri: &Uri,
287        headers: &HeaderMap,
288        body: &str,
289    ) -> (Response, Duration) {
290        let mut inner = self.lock();
291        let path = uri.path();
292        let call = (method == Method::POST)
293            .then(|| soap::parse(body))
294            .flatten();
295        let locked = inner.injections.contains(&Injection::LockLogin);
296        let authorized = !locked
297            && auth::verify(
298                headers.get(AUTHORIZATION).and_then(|v| v.to_str().ok()),
299                &auth::Expected {
300                    username: &self.options.username,
301                    password: &self.options.password,
302                    nonce: NONCE,
303                    method: method.as_str(),
304                    uri: uri.path_and_query().map_or(path, |p| p.as_str()),
305                },
306            );
307        inner.requests.push(Request {
308            method: method.to_string(),
309            path: path.to_owned(),
310            action: call.as_ref().map(|c| c.action.clone()),
311            arguments: call.as_ref().map_or_default(|c| c.arguments.clone()),
312            authorized,
313        });
314        let delay = inner
315            .injections
316            .iter()
317            .map(|i| match i {
318                Injection::Delay(delay) => *delay,
319                _ => Duration::ZERO,
320            })
321            .sum();
322        let response = match *method {
323            _ if path == web::LOGIN => inner.web.login(method, body, &self.options, locked),
324            _ if path.starts_with(web::API) => {
325                let Inner { web, device, .. } = &*inner;
326                web.api(&device.fixture.api, method, path, headers)
327            }
328            Method::GET => inner.document(path, uri.query()),
329            Method::POST if !authorized => (
330                StatusCode::UNAUTHORIZED,
331                [(WWW_AUTHENTICATE, auth::challenge(NONCE))],
332            )
333                .into_response(),
334            Method::POST => inner.control(path, headers, call),
335            _ => StatusCode::METHOD_NOT_ALLOWED.into_response(),
336        };
337        (response, delay)
338    }
339}
340
341/// The nonce of every challenge. Clients may reuse it as long as they
342/// like.
343const NONCE: &str = "F1A2B3C4D5E6F708";
344
345/// The session ID in the paths of list documents, in place of the `***` the
346/// fixture recorded.
347const SESSION: &str = "5e55104d0c0ffee5";
348
349impl Inner {
350    /// The device description, a service description, or a list document
351    /// for the [session](SESSION).
352    fn document(&self, path: &str, query: Option<&str>) -> Response {
353        let fixture = &self.device.fixture;
354        let name = path.trim_start_matches('/');
355        if let Some(list) = name
356            .strip_suffix(".lua")
357            .and_then(|stem| fixture.lists.get(stem))
358        {
359            let session = query
360                .into_iter()
361                .flat_map(|q| q.split('&'))
362                .any(|p| p == format!("sid={SESSION}"));
363            return if session {
364                list.clone().into_response()
365            } else {
366                StatusCode::FORBIDDEN.into_response()
367            };
368        }
369        let xml = match name {
370            "tr64desc.xml" => Some(&fixture.description_xml),
371            name => fixture.scpds.get(name).map(|(xml, _)| xml),
372        };
373        match xml {
374            Some(xml) => ([(CONTENT_TYPE, XML)], xml.clone()).into_response(),
375            None => StatusCode::NOT_FOUND.into_response(),
376        }
377    }
378
379    /// Answers an authorized action call.
380    fn control(&mut self, path: &str, headers: &HeaderMap, call: Option<soap::Call>) -> Response {
381        let service = self
382            .device
383            .fixture
384            .description
385            .services()
386            .find(|s| s.control_url == path)
387            .cloned();
388        let Some(service) = service else {
389            return StatusCode::NOT_FOUND.into_response();
390        };
391        let Some(call) = call else {
392            return StatusCode::BAD_REQUEST.into_response();
393        };
394        let soap_action = headers
395            .get("SOAPAction")
396            .and_then(|v| v.to_str().ok())
397            .unwrap_or_default()
398            .trim_matches('"');
399        let expected = format!("{}#{}", service.service_type, call.action);
400        let result = if soap_action == expected && call.service_type == service.service_type {
401            let hooks = self.hooks(&service, &call.action);
402            self.device
403                .call(&service, &call.action, &call.arguments, &hooks)
404        } else {
405            Err(Fault::new(401))
406        };
407        match result {
408            Ok(mut out) => {
409                for (_, value) in &mut out {
410                    *value = value.replace("sid=***", &format!("sid={SESSION}"));
411                }
412                let xml = soap::response(&service.service_type, &call.action, &out);
413                ([(CONTENT_TYPE, XML)], xml).into_response()
414            }
415            Err(fault) => (
416                StatusCode::INTERNAL_SERVER_ERROR,
417                [(CONTENT_TYPE, XML)],
418                soap::fault(&fault),
419            )
420                .into_response(),
421        }
422    }
423
424    fn hooks(&self, service: &Service, action: &str) -> Hooks {
425        let fault = self.injections.iter().find_map(|i| match i {
426            Injection::Fault {
427                service: reference,
428                action: name,
429                code,
430            } if name == action && service.matches(reference) => Some(Fault::new(*code)),
431            _ => None,
432        });
433        Hooks {
434            fault,
435            discard_writes: self.injections.contains(&Injection::DiscardWrites),
436        }
437    }
438}
439
440async fn handle(
441    State(shared): State<Arc<Shared>>,
442    method: Method,
443    uri: Uri,
444    headers: HeaderMap,
445    body: String,
446) -> Response {
447    let (response, delay) = shared.respond(&method, &uri, &headers, &body);
448    tokio::time::sleep(delay).await;
449    response
450}
451
452#[cfg(test)]
453mod tests {
454    use super::*;
455
456    const FIXTURE: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/fixtures/fritzbox-7690/8.25");
457    const WLAN: &str = "urn:dslforum-org:service:WLANConfiguration:1";
458    const CONTROL: &str = "/upnp/control/wlanconfig1";
459
460    fn inner() -> Inner {
461        Inner {
462            device: Device::new(Fixture::load(FIXTURE).unwrap()),
463            web: Web::default(),
464            injections: Vec::new(),
465            requests: Vec::new(),
466        }
467    }
468
469    /// A call of `GetInfo`.
470    fn call(service_type: &str) -> soap::Call {
471        soap::Call {
472            service_type: service_type.to_owned(),
473            action: "GetInfo".to_owned(),
474            arguments: Vec::new(),
475        }
476    }
477
478    fn soap_action(value: &str) -> HeaderMap {
479        let mut headers = HeaderMap::new();
480        headers.insert("SOAPAction", value.parse().unwrap());
481        headers
482    }
483
484    #[test]
485    fn answers_calls_that_match_the_service() {
486        let headers = soap_action(&format!("\"{WLAN}#GetInfo\""));
487        let response = inner().control(CONTROL, &headers, Some(call(WLAN)));
488        assert_eq!(response.status(), StatusCode::OK);
489    }
490
491    #[test]
492    fn rejects_calls_that_do_not_match_the_service() {
493        let mut inner = inner();
494        let right = soap_action(&format!("{WLAN}#GetInfo"));
495        let wrong = soap_action(&format!("{WLAN}#SetEnable"));
496        for (headers, service_type) in [
497            (&wrong, WLAN),
498            (&HeaderMap::new(), WLAN),
499            (&right, "urn:other"),
500        ] {
501            let response = inner.control(CONTROL, headers, Some(call(service_type)));
502            assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
503        }
504        let response = inner.control("/upnp/control/missing", &right, Some(call(WLAN)));
505        assert_eq!(response.status(), StatusCode::NOT_FOUND);
506        let response = inner.control(CONTROL, &right, None);
507        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
508    }
509
510    #[test]
511    fn allows_only_get_and_post() {
512        let shared = Shared {
513            options: Options::default(),
514            inner: Mutex::new(inner()),
515        };
516        let uri = Uri::from_static("/tr64desc.xml");
517        let (response, delay) = shared.respond(&Method::PUT, &uri, &HeaderMap::new(), "");
518        assert_eq!(response.status(), StatusCode::METHOD_NOT_ALLOWED);
519        assert_eq!(delay, Duration::ZERO);
520        assert_eq!(shared.lock().requests[0].method, "PUT");
521    }
522}