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//!   Nothing else changes: the simulator does not know which settings a
18//!   device changes along with them, like the options of a feature it
19//!   turns off. Tests inject such side effects themselves.
20//! - Paths to list documents, like the one `X_AVM-DE_GetHostListPath`
21//!   returns, hold a session ID, and the documents are served for it.
22//! - The web interface has a session login, `/login_sid.lua`, with a
23//!   PBKDF2 challenge, and serves the documents of the REST API, like
24//!   `/api/v0/smarthome/overview`, the pages of `/data.lua`, like
25//!   `ecoStat`, and the statistics of Smart Home devices of
26//!   `/webservices/homeautoswitch.lua`, for the open session. Like the
27//!   device, the page `log` remembers the category of its last field
28//!   `filter` and lists only its entries, see [`Sim::log_filter`].
29//! - Tests can [inject](Sim::inject) UPnP errors, delays, discarded writes,
30//!   side effects of writes, counters that grow, a locked login, calls that
31//!   break off, restarts and pages that fail, and read the [requests](Sim::requests) the
32//!   server got.
33//! - [`CallMonitor`] replays scripted lines of the call monitor, drops the
34//!   connection between sessions and sends lines that are not valid.
35//!
36//! ```no_run
37//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
38//! use fritz_sim::{Fixture, Injection, Sim};
39//!
40//! let sim = Sim::start(Fixture::bundled("fritzbox-7690/8.25")?).await?;
41//! let client = sim.client().build()?;
42//! let description = client.description().await?;
43//! let wlan = description.service("WLANConfiguration1")?;
44//! client.call(wlan, "SetEnable", &[("NewEnable", "0")]).await?;
45//! assert_eq!(sim.state("WLANConfiguration1", "Enable").as_deref(), Some("0"));
46//!
47//! sim.inject(Injection::fault("WLANConfiguration1", "SetEnable", 866));
48//! assert!(client.call(wlan, "SetEnable", &[("NewEnable", "1")]).await.is_err());
49//! # Ok(())
50//! # }
51//! ```
52
53use std::future::IntoFuture as _;
54use std::io;
55use std::net::{Ipv4Addr, SocketAddr};
56use std::pin::Pin;
57use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
58use std::task::{Context, Poll};
59use std::time::Duration;
60
61use axum::Router;
62use axum::body::{Body, Bytes, HttpBody};
63use axum::extract::State;
64use axum::http::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, WWW_AUTHENTICATE};
65use axum::http::{HeaderMap, Method, StatusCode, Uri};
66use axum::response::{IntoResponse, Response};
67use tokio::task::JoinHandle;
68use tr064::{ClientBuilder, Fingerprint, SecretString, Service, Url};
69
70mod auth;
71mod callmonitor;
72mod device;
73pub mod dns;
74mod fixture;
75mod soap;
76mod tls;
77mod web;
78
79pub use callmonitor::CallMonitor;
80use device::{Device, Fault, Hooks, short_id};
81pub use fixture::{Answer, Error, Fixture};
82use tls::TlsListener;
83use web::Web;
84
85/// The user name the simulator accepts by default.
86pub const USERNAME: &str = "fritz-sim";
87/// The password the simulator accepts by default.
88pub const PASSWORD: &str = "fritz-sim-password";
89
90const XML: &str = r#"text/xml; charset="utf-8""#;
91
92/// How the simulator listens and whom it lets in.
93#[derive(Debug, Clone)]
94pub struct Options {
95    /// Port 0 picks a free port.
96    pub address: SocketAddr,
97    pub username: String,
98    pub password: String,
99    /// Serve HTTPS with a new self-signed certificate, see
100    /// [`Sim::fingerprint`].
101    pub https: bool,
102}
103
104impl Default for Options {
105    /// A free port on the loopback interface, plain HTTP, with [`USERNAME`]
106    /// and [`PASSWORD`].
107    fn default() -> Self {
108        Self {
109            address: SocketAddr::from((Ipv4Addr::LOCALHOST, 0)),
110            username: USERNAME.to_owned(),
111            password: PASSWORD.to_owned(),
112            https: false,
113        }
114    }
115}
116
117/// A change to how the simulator behaves, until
118/// [cleared](Sim::clear_injections).
119#[derive(Debug, Clone, PartialEq, Eq)]
120#[non_exhaustive]
121pub enum Injection {
122    /// Calls of an action fail with a UPnP error once their arguments are
123    /// valid. `service` is any reference [`Service::matches`] accepts, like
124    /// `WLANConfiguration1`.
125    Fault {
126        service: String,
127        action: String,
128        code: u16,
129    },
130    /// Every response is sent after a delay, to make clients time out.
131    Delay(Duration),
132    /// Writes succeed, but change nothing.
133    DiscardWrites,
134    /// A write of an action also sets a state variable of the same service,
135    /// like a device that resets the settings of a feature when it is
136    /// turned off. Discarded writes set nothing.
137    SideEffect {
138        service: String,
139        action: String,
140        variable: String,
141        value: String,
142    },
143    /// The account is locked: every login fails, even with the right
144    /// password.
145    LockLogin,
146    /// Every call of a getter that answers a state variable of a service
147    /// first adds `step` to it, like a counter of bytes, and wraps around
148    /// at `wrap`, or at 2^64 without it.
149    Counter {
150        service: String,
151        variable: String,
152        step: u64,
153        wrap: Option<u64>,
154    },
155    /// Calls of an action break off without an answer, like a connection
156    /// that fails while the call is sent. The call changes nothing.
157    Disconnect { service: String, action: String },
158    /// Calls of an action answer with a body that ends early, like a
159    /// connection that closes while the answer is sent. The call changes
160    /// nothing.
161    Truncate { service: String, action: String },
162    /// A call of `Reboot` of `DeviceConfig1` restarts the device: it
163    /// answers the call, breaks off the next `down` requests without an
164    /// answer, and then answers again, with the uptime of `DeviceInfo1`
165    /// `GetInfo` reset to 0. With `serial`, another device comes back: it
166    /// answers this serial number.
167    Reboot { down: u32, serial: Option<String> },
168    /// Posts of the page `page` of `/data.lua` whose form field `field` is
169    /// `value` fail with 500, after the page took the form, like a page
170    /// that remembers its filter but breaks off its answer.
171    FailPage {
172        page: String,
173        field: String,
174        value: String,
175    },
176}
177
178impl Injection {
179    /// Calls of `action` of `service` break off without an answer.
180    pub fn disconnect(service: impl Into<String>, action: impl Into<String>) -> Self {
181        Self::Disconnect {
182            service: service.into(),
183            action: action.into(),
184        }
185    }
186
187    /// Calls of `action` of `service` answer with a body that ends early.
188    pub fn truncate(service: impl Into<String>, action: impl Into<String>) -> Self {
189        Self::Truncate {
190            service: service.into(),
191            action: action.into(),
192        }
193    }
194
195    /// A call of `Reboot` restarts the device, which breaks off the next
196    /// `down` requests.
197    pub fn reboot(down: u32) -> Self {
198        Self::Reboot { down, serial: None }
199    }
200
201    /// Posts of `page` with `value` in the form field `field` fail.
202    pub fn fail_page(
203        page: impl Into<String>,
204        field: impl Into<String>,
205        value: impl Into<String>,
206    ) -> Self {
207        Self::FailPage {
208            page: page.into(),
209            field: field.into(),
210            value: value.into(),
211        }
212    }
213
214    /// Calls of `action` of `service` fail with the UPnP error `code`.
215    pub fn fault(service: impl Into<String>, action: impl Into<String>, code: u16) -> Self {
216        Self::Fault {
217            service: service.into(),
218            action: action.into(),
219            code,
220        }
221    }
222
223    /// Writes of `action` of `service` also set the state `variable` of
224    /// that service to `value`.
225    pub fn side_effect(
226        service: impl Into<String>,
227        action: impl Into<String>,
228        variable: impl Into<String>,
229        value: impl Into<String>,
230    ) -> Self {
231        Self::SideEffect {
232            service: service.into(),
233            action: action.into(),
234            variable: variable.into(),
235            value: value.into(),
236        }
237    }
238
239    /// Every read of the state `variable` of `service` adds `step` to it
240    /// first, wrapping around at `wrap`.
241    pub fn counter(
242        service: impl Into<String>,
243        variable: impl Into<String>,
244        step: u64,
245        wrap: Option<u64>,
246    ) -> Self {
247        Self::Counter {
248            service: service.into(),
249            variable: variable.into(),
250            step,
251            wrap,
252        }
253    }
254}
255
256/// A request the simulator got.
257#[derive(Debug, Clone, PartialEq, Eq)]
258pub struct Request {
259    pub method: String,
260    pub path: String,
261    /// The action, for action calls.
262    pub action: Option<String>,
263    /// The input arguments, for action calls.
264    pub arguments: Vec<(String, String)>,
265    /// Whether the request carried valid credentials.
266    pub authorized: bool,
267}
268
269/// A running simulator. It stops when dropped.
270#[derive(Debug)]
271pub struct Sim {
272    url: Url,
273    fingerprint: Option<Fingerprint>,
274    shared: Arc<Shared>,
275    server: JoinHandle<io::Result<()>>,
276}
277
278impl Sim {
279    /// Serves `fixture` on a free port of the loopback interface, with
280    /// [`USERNAME`] and [`PASSWORD`].
281    ///
282    /// # Errors
283    ///
284    /// The errors of binding the port.
285    pub async fn start(fixture: Fixture) -> io::Result<Self> {
286        Self::start_with(fixture, Options::default()).await
287    }
288
289    /// Serves `fixture` as configured.
290    ///
291    /// # Errors
292    ///
293    /// The errors of binding the address.
294    pub async fn start_with(fixture: Fixture, options: Options) -> io::Result<Self> {
295        let listener = tokio::net::TcpListener::bind(options.address).await?;
296        let scheme = if options.https { "https" } else { "http" };
297        let url = Url::parse(&format!("{scheme}://{}", listener.local_addr()?))
298            .map_err(io::Error::other)?;
299        let https = options.https;
300        let shared = Arc::new(Shared {
301            options,
302            inner: Mutex::new(Inner {
303                web: Web::new(&fixture.pages),
304                device: Device::new(fixture),
305                injections: Vec::new(),
306                requests: Vec::new(),
307                down: 0,
308            }),
309        });
310        let app = Router::new()
311            .fallback(handle)
312            .with_state(Arc::clone(&shared));
313        let (server, fingerprint) = if https {
314            let (listener, fingerprint) = TlsListener::new(listener);
315            let server = tokio::spawn(axum::serve(listener, app).into_future());
316            (server, Some(fingerprint))
317        } else {
318            (tokio::spawn(axum::serve(listener, app).into_future()), None)
319        };
320        Ok(Self {
321            url,
322            fingerprint,
323            shared,
324            server,
325        })
326    }
327
328    /// The base URL, like `http://127.0.0.1:49000`.
329    pub fn url(&self) -> &Url {
330        &self.url
331    }
332
333    /// The fingerprint of the certificate, if the simulator serves HTTPS.
334    pub fn fingerprint(&self) -> Option<Fingerprint> {
335        self.fingerprint
336    }
337
338    /// A client builder for the simulator, with its credentials and, for
339    /// HTTPS, its certificate pinned.
340    pub fn client(&self) -> ClientBuilder {
341        let options = &self.shared.options;
342        let builder = tr064::Client::builder(self.url.clone()).credentials(
343            options.username.clone(),
344            SecretString::from(options.password.clone()),
345        );
346        match self.fingerprint {
347            Some(fingerprint) => builder.pin(fingerprint),
348            None => builder,
349        }
350    }
351
352    /// Changes how the simulator behaves from the next request on.
353    pub fn inject(&self, injection: Injection) {
354        self.shared.lock().injections.push(injection);
355    }
356
357    /// Removes all injections.
358    pub fn clear_injections(&self) {
359        self.shared.lock().injections.clear();
360    }
361
362    /// The requests the simulator got so far, oldest first.
363    pub fn requests(&self) -> Vec<Request> {
364        self.shared.lock().requests.clone()
365    }
366
367    /// The category the page `log` of the web interface remembers, like
368    /// `net`: the value of its last field `filter`, or else of `filter` in
369    /// the page of the fixture. `None` if neither is there.
370    pub fn log_filter(&self) -> Option<String> {
371        self.shared.lock().web.log_filter().map(str::to_owned)
372    }
373
374    /// The value of a state variable of a service, like `Enable` of
375    /// `WLANConfiguration1`. `service` is any reference
376    /// [`Service::matches`] accepts.
377    pub fn state(&self, service: &str, variable: &str) -> Option<String> {
378        let inner = self.shared.lock();
379        let service = inner.device.fixture.description.service(service).ok()?;
380        inner
381            .device
382            .state(short_id(service), variable)
383            .map(str::to_owned)
384    }
385}
386
387impl Drop for Sim {
388    fn drop(&mut self) {
389        self.server.abort();
390    }
391}
392
393#[derive(Debug)]
394struct Shared {
395    options: Options,
396    inner: Mutex<Inner>,
397}
398
399#[derive(Debug)]
400struct Inner {
401    device: Device,
402    web: Web,
403    injections: Vec<Injection>,
404    requests: Vec<Request>,
405    /// The number of requests to break off while the device restarts.
406    down: u32,
407}
408
409impl Shared {
410    fn lock(&self) -> MutexGuard<'_, Inner> {
411        self.inner.lock().unwrap_or_else(PoisonError::into_inner)
412    }
413
414    /// Answers a request, and the delay before the answer.
415    fn respond(
416        &self,
417        method: &Method,
418        uri: &Uri,
419        headers: &HeaderMap,
420        body: &str,
421    ) -> (Response, Duration) {
422        let mut inner = self.lock();
423        let path = uri.path();
424        let call = (method == Method::POST)
425            .then(|| soap::parse(body))
426            .flatten();
427        let locked = inner.injections.contains(&Injection::LockLogin);
428        let authorized = !locked
429            && auth::verify(
430                headers.get(AUTHORIZATION).and_then(|v| v.to_str().ok()),
431                &auth::Expected {
432                    username: &self.options.username,
433                    password: &self.options.password,
434                    nonce: NONCE,
435                    method: method.as_str(),
436                    uri: uri.path_and_query().map_or(path, |p| p.as_str()),
437                },
438            );
439        inner.requests.push(Request {
440            method: method.to_string(),
441            path: path.to_owned(),
442            action: call.as_ref().map(|c| c.action.clone()),
443            arguments: call.as_ref().map_or_default(|c| c.arguments.clone()),
444            authorized,
445        });
446        let delay = inner
447            .injections
448            .iter()
449            .map(|i| match i {
450                Injection::Delay(delay) => *delay,
451                _ => Duration::ZERO,
452            })
453            .sum();
454        let response = match *method {
455            _ if inner.down > 0 => {
456                inner.down -= 1;
457                broken()
458            }
459            _ if path == web::LOGIN => inner.web.login(method, body, &self.options, locked),
460            _ if path.starts_with(web::API) => {
461                let Inner { web, device, .. } = &*inner;
462                web.api(&device.fixture.api, method, path, headers)
463            }
464            _ if path == web::DATA => {
465                let Inner {
466                    web,
467                    device,
468                    injections,
469                    ..
470                } = &mut *inner;
471                web.page(&device.fixture.pages, injections, method, body)
472            }
473            _ if path == web::HOMEAUTO => {
474                inner.web.stats(&inner.device.fixture.stats, method, body)
475            }
476            Method::GET => inner.document(path, uri.query()),
477            Method::POST if !authorized => (
478                StatusCode::UNAUTHORIZED,
479                [(WWW_AUTHENTICATE, auth::challenge(NONCE))],
480            )
481                .into_response(),
482            Method::POST => inner.control(path, headers, call),
483            _ => StatusCode::METHOD_NOT_ALLOWED.into_response(),
484        };
485        (response, delay)
486    }
487}
488
489/// The nonce of every challenge. Clients may reuse it as long as they
490/// like.
491const NONCE: &str = "F1A2B3C4D5E6F708";
492
493/// The session ID in the paths of list documents, in place of the `***` the
494/// fixture recorded.
495const SESSION: &str = "5e55104d0c0ffee5";
496
497impl Inner {
498    /// The device description, a service description, or a list document
499    /// for the [session](SESSION).
500    fn document(&self, path: &str, query: Option<&str>) -> Response {
501        let fixture = &self.device.fixture;
502        let name = path.trim_start_matches('/');
503        if let Some(list) = name
504            .strip_suffix(".lua")
505            .and_then(|stem| fixture.lists.get(stem))
506        {
507            let session = query
508                .into_iter()
509                .flat_map(|q| q.split('&'))
510                .any(|p| p == format!("sid={SESSION}"));
511            return if session {
512                list.clone().into_response()
513            } else {
514                StatusCode::FORBIDDEN.into_response()
515            };
516        }
517        let xml = match name {
518            "tr64desc.xml" => Some(&fixture.description_xml),
519            name => fixture.scpds.get(name).map(|(xml, _)| xml),
520        };
521        match xml {
522            Some(xml) => ([(CONTENT_TYPE, XML)], xml.clone()).into_response(),
523            None => StatusCode::NOT_FOUND.into_response(),
524        }
525    }
526
527    /// Answers an authorized action call.
528    fn control(&mut self, path: &str, headers: &HeaderMap, call: Option<soap::Call>) -> Response {
529        let service = self
530            .device
531            .fixture
532            .description
533            .services()
534            .find(|s| s.control_url == path)
535            .cloned();
536        let Some(service) = service else {
537            return StatusCode::NOT_FOUND.into_response();
538        };
539        let Some(call) = call else {
540            return StatusCode::BAD_REQUEST.into_response();
541        };
542        let soap_action = headers
543            .get("SOAPAction")
544            .and_then(|v| v.to_str().ok())
545            .unwrap_or_default()
546            .trim_matches('"');
547        let expected = format!("{}#{}", service.service_type, call.action);
548        let result = if soap_action == expected && call.service_type == service.service_type {
549            if let Some(response) = self.breaks(&service, &call.action) {
550                return response;
551            }
552            let hooks = self.hooks(&service, &call.action);
553            let result = self
554                .device
555                .call(&service, &call.action, &call.arguments, &hooks);
556            if result.is_ok() {
557                self.reboot(&service, &call.action);
558            }
559            result
560        } else {
561            Err(Fault::new(401))
562        };
563        match result {
564            Ok(mut out) => {
565                for (_, value) in &mut out {
566                    *value = value.replace("sid=***", &format!("sid={SESSION}"));
567                }
568                let xml = soap::response(&service.service_type, &call.action, &out);
569                ([(CONTENT_TYPE, XML)], xml).into_response()
570            }
571            Err(fault) => (
572                StatusCode::INTERNAL_SERVER_ERROR,
573                [(CONTENT_TYPE, XML)],
574                soap::fault(&fault),
575            )
576                .into_response(),
577        }
578    }
579
580    /// The broken answer to calls of `action`, if they break off.
581    fn breaks(&self, service: &Service, action: &str) -> Option<Response> {
582        self.injections.iter().find_map(|i| match i {
583            Injection::Disconnect {
584                service: reference,
585                action: name,
586            } if name == action && service.matches(reference) => Some(broken()),
587            Injection::Truncate {
588                service: reference,
589                action: name,
590            } if name == action && service.matches(reference) => Some(truncated()),
591            _ => None,
592        })
593    }
594
595    /// Restarts the device after a call of `Reboot`, if a test
596    /// [injected](Injection::Reboot) it. `None` if not.
597    fn reboot(&mut self, service: &Service, action: &str) -> Option<()> {
598        (action == "Reboot" && service.matches("DeviceConfig1")).then_some(())?;
599        let reboot = self
600            .injections
601            .iter()
602            .find(|i| matches!(i, Injection::Reboot { .. }));
603        let Some(Injection::Reboot { down, serial }) = reboot.cloned() else {
604            return None;
605        };
606        self.down = down;
607        let device = &mut self.device;
608        device.set_output("DeviceInfo1", "GetInfo", "NewUpTime", "0")?;
609        device.set_output("DeviceInfo1", "GetInfo", "NewSerialNumber", &serial?)
610    }
611
612    fn hooks(&self, service: &Service, action: &str) -> Hooks {
613        let fault = self.injections.iter().find_map(|i| match i {
614            Injection::Fault {
615                service: reference,
616                action: name,
617                code,
618            } if name == action && service.matches(reference) => Some(Fault::new(*code)),
619            _ => None,
620        });
621        let side_effects = self
622            .injections
623            .iter()
624            .filter_map(|i| match i {
625                Injection::SideEffect {
626                    service: reference,
627                    action: name,
628                    variable,
629                    value,
630                } if name == action && service.matches(reference) => {
631                    Some((variable.clone(), value.clone()))
632                }
633                _ => None,
634            })
635            .collect();
636        let counters = self
637            .injections
638            .iter()
639            .filter_map(|i| match i {
640                Injection::Counter {
641                    service: reference,
642                    variable,
643                    step,
644                    wrap,
645                } if service.matches(reference) => Some((variable.clone(), *step, *wrap)),
646                _ => None,
647            })
648            .collect();
649        Hooks {
650            fault,
651            discard_writes: self.injections.contains(&Injection::DiscardWrites),
652            side_effects,
653            counters,
654        }
655    }
656}
657
658/// A response that breaks off: its body fails before it ends, so the
659/// client gets no answer.
660fn broken() -> Response {
661    (StatusCode::OK, [(CONTENT_LENGTH, "1")], Body::new(Broken)).into_response()
662}
663
664/// A response whose SOAP envelope ends early.
665fn truncated() -> Response {
666    (StatusCode::OK, "<?xml version=\"1.0\"?><s:Envelope").into_response()
667}
668
669/// A body that fails.
670struct Broken;
671
672impl HttpBody for Broken {
673    type Data = Bytes;
674    type Error = io::Error;
675
676    fn poll_frame(
677        self: Pin<&mut Self>,
678        _: &mut Context<'_>,
679    ) -> Poll<Option<Result<http_body::Frame<Bytes>, io::Error>>> {
680        Poll::Ready(Some(Err(io::ErrorKind::ConnectionReset.into())))
681    }
682}
683
684async fn handle(
685    State(shared): State<Arc<Shared>>,
686    method: Method,
687    uri: Uri,
688    headers: HeaderMap,
689    body: String,
690) -> Response {
691    let (response, delay) = shared.respond(&method, &uri, &headers, &body);
692    tokio::time::sleep(delay).await;
693    response
694}
695
696#[cfg(test)]
697mod tests {
698    use super::*;
699
700    const FIXTURE: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/fixtures/fritzbox-7690/8.25");
701    const WLAN: &str = "urn:dslforum-org:service:WLANConfiguration:1";
702    const CONTROL: &str = "/upnp/control/wlanconfig1";
703
704    fn inner() -> Inner {
705        Inner {
706            device: Device::new(Fixture::load(FIXTURE).unwrap()),
707            web: Web::default(),
708            injections: Vec::new(),
709            requests: Vec::new(),
710            down: 0,
711        }
712    }
713
714    /// A call of `GetInfo`.
715    fn call(service_type: &str) -> soap::Call {
716        soap::Call {
717            service_type: service_type.to_owned(),
718            action: "GetInfo".to_owned(),
719            arguments: Vec::new(),
720        }
721    }
722
723    fn soap_action(value: &str) -> HeaderMap {
724        let mut headers = HeaderMap::new();
725        headers.insert("SOAPAction", value.parse().unwrap());
726        headers
727    }
728
729    #[test]
730    fn answers_calls_that_match_the_service() {
731        let headers = soap_action(&format!("\"{WLAN}#GetInfo\""));
732        let response = inner().control(CONTROL, &headers, Some(call(WLAN)));
733        assert_eq!(response.status(), StatusCode::OK);
734    }
735
736    #[test]
737    fn rejects_calls_that_do_not_match_the_service() {
738        let mut inner = inner();
739        let right = soap_action(&format!("{WLAN}#GetInfo"));
740        let wrong = soap_action(&format!("{WLAN}#SetEnable"));
741        for (headers, service_type) in [
742            (&wrong, WLAN),
743            (&HeaderMap::new(), WLAN),
744            (&right, "urn:other"),
745        ] {
746            let response = inner.control(CONTROL, headers, Some(call(service_type)));
747            assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
748        }
749        let response = inner.control("/upnp/control/missing", &right, Some(call(WLAN)));
750        assert_eq!(response.status(), StatusCode::NOT_FOUND);
751        let response = inner.control(CONTROL, &right, None);
752        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
753    }
754
755    #[test]
756    fn allows_only_get_and_post() {
757        let shared = Shared {
758            options: Options::default(),
759            inner: Mutex::new(inner()),
760        };
761        let uri = Uri::from_static("/tr64desc.xml");
762        let (response, delay) = shared.respond(&Method::PUT, &uri, &HeaderMap::new(), "");
763        assert_eq!(response.status(), StatusCode::METHOD_NOT_ALLOWED);
764        assert_eq!(delay, Duration::ZERO);
765        assert_eq!(shared.lock().requests[0].method, "PUT");
766    }
767}