fxa_client/internal/
device.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5use std::{
6    cell::Cell,
7    collections::{HashMap, HashSet},
8};
9
10pub use super::http_client::{GetDeviceResponse as Device, PushSubscription};
11use super::{
12    commands::{self, IncomingDeviceCommand, PrivateCommandKeys, PublicCommandKeys},
13    http_client::{
14        DeviceUpdateRequest, DeviceUpdateRequestBuilder, PendingCommand, UpdateDeviceResponse,
15    },
16    scopes, telemetry, util, CachedResponse, FirefoxAccount,
17};
18use crate::{info, warn, DeviceCapability, Error, LocalDevice, Result};
19use sync15::DeviceType;
20
21// An devices response is considered fresh for `DEVICES_FRESHNESS_THRESHOLD` ms.
22const DEVICES_FRESHNESS_THRESHOLD: u64 = 60_000; // 1 minute
23
24thread_local! {
25    /// The maximum size, in bytes, of a command payload. The FxA server may
26    /// reject requests to invoke commands with payloads exceeding this size.
27    ///
28    /// Defaults to 16 KB; overridden in tests.
29    pub static COMMAND_MAX_PAYLOAD_SIZE: Cell<usize> = const { Cell::new(16 * 1024) }
30}
31
32/// The reason we are fetching commands.
33#[derive(Clone, Copy)]
34pub enum CommandFetchReason {
35    /// We are polling in-case we've missed some.
36    Poll,
37    /// We got a push notification with the index of the message.
38    Push(u64),
39}
40
41impl FirefoxAccount {
42    /// Fetches the list of devices from the current account including
43    /// the current one.
44    ///
45    /// * `ignore_cache` - If set to true, bypass the in-memory cache
46    ///   and fetch devices from the server.
47    pub fn get_devices(&mut self, ignore_cache: bool) -> Result<Vec<Device>> {
48        if let Some(d) = &self.devices_cache {
49            if !ignore_cache && util::now() < d.cached_at + DEVICES_FRESHNESS_THRESHOLD {
50                return Ok(d.response.clone());
51            }
52        }
53
54        let refresh_token = self.get_refresh_token()?;
55        let response = self
56            .client
57            .get_devices(self.state.config(), refresh_token)?;
58
59        self.devices_cache = Some(CachedResponse {
60            response: response.clone(),
61            cached_at: util::now(),
62            etag: "".into(),
63        });
64
65        Ok(response)
66    }
67
68    pub fn get_current_device(&mut self) -> Result<Option<Device>> {
69        Ok(self
70            .get_devices(false)?
71            .into_iter()
72            .find(|d| d.is_current_device))
73    }
74
75    /// Replaces the internal set of "tracked" device capabilities by re-registering
76    /// new capabilities and returns a set of device commands to register with the
77    /// server.
78    fn register_capabilities(
79        &mut self,
80        capabilities: &[DeviceCapability],
81    ) -> Result<HashMap<String, String>> {
82        let mut commands = HashMap::new();
83        for capability in capabilities.iter().collect::<HashSet<_>>() {
84            match capability {
85                DeviceCapability::SendTab => {
86                    let send_tab_command_data =
87                        self.generate_command_data(DeviceCapability::SendTab)?;
88                    commands.insert(
89                        commands::send_tab::COMMAND_NAME.to_owned(),
90                        send_tab_command_data,
91                    );
92                }
93                DeviceCapability::CloseTabs => {
94                    let close_tabs_command_data =
95                        self.generate_command_data(DeviceCapability::CloseTabs)?;
96                    commands.insert(
97                        commands::close_tabs::COMMAND_NAME.to_owned(),
98                        close_tabs_command_data,
99                    );
100                }
101            }
102        }
103        Ok(commands)
104    }
105
106    /// Initializes our own device, most of the time this will be called right after logging-in
107    /// for the first time.
108    ///
109    /// **💾 This method alters the persisted account state.**
110    pub fn initialize_device(
111        &mut self,
112        name: &str,
113        device_type: DeviceType,
114        capabilities: &[DeviceCapability],
115    ) -> Result<LocalDevice> {
116        self.with_network_retry("initialize_device", |s| {
117            s._initialize_device(name, device_type, capabilities)
118        })
119    }
120
121    fn _initialize_device(
122        &mut self,
123        name: &str,
124        device_type: DeviceType,
125        capabilities: &[DeviceCapability],
126    ) -> Result<LocalDevice> {
127        self.state
128            .set_device_capabilities(capabilities.iter().cloned());
129        let commands = self.register_capabilities(capabilities)?;
130        let update = DeviceUpdateRequestBuilder::new()
131            .display_name(name)
132            .device_type(&device_type)
133            .available_commands(&commands)
134            .build();
135        self.update_device(update)
136    }
137
138    /// Register a set of device capabilities against the current device.
139    ///
140    /// As the only capability is Send Tab now, its command is registered with the server.
141    /// Don't forget to also call this if the Sync Keys change as they
142    /// encrypt the Send Tab command data.
143    ///
144    /// **💾 This method alters the persisted account state.**
145    pub fn ensure_capabilities(
146        &mut self,
147        capabilities: &[DeviceCapability],
148    ) -> Result<LocalDevice> {
149        self.with_network_retry("ensure_capabilities", |s| {
150            s._ensure_capabilities(capabilities)
151        })
152    }
153
154    fn _ensure_capabilities(&mut self, capabilities: &[DeviceCapability]) -> Result<LocalDevice> {
155        self.state
156            .set_device_capabilities(capabilities.iter().cloned());
157        // Don't re-register if we already have exactly those capabilities.
158        if let Some(local_device) = self.state.server_local_device_info() {
159            if capabilities == local_device.capabilities {
160                return Ok(local_device.clone());
161            }
162        }
163        let commands = self.register_capabilities(capabilities)?;
164        let update = DeviceUpdateRequestBuilder::new()
165            .available_commands(&commands)
166            .build();
167        self.update_device(update)
168    }
169
170    /// Re-register the device capabilities, this should only be used internally.
171    pub(crate) fn reregister_current_capabilities(&mut self) -> Result<()> {
172        let capabilities: Vec<_> = self.state.device_capabilities().iter().cloned().collect();
173        let commands = self.register_capabilities(&capabilities)?;
174        let update = DeviceUpdateRequestBuilder::new()
175            .available_commands(&commands)
176            .build();
177        self.update_device(update)?;
178        Ok(())
179    }
180
181    pub(crate) fn invoke_command(
182        &self,
183        command: &str,
184        target: &Device,
185        payload: &serde_json::Value,
186        ttl: Option<u64>,
187    ) -> Result<()> {
188        let refresh_token = self.get_refresh_token()?;
189        self.client.invoke_command(
190            self.state.config(),
191            refresh_token,
192            command,
193            &target.id,
194            payload,
195            ttl,
196        )
197    }
198
199    /// Poll and parse any pending available command for our device.
200    /// This should be called semi-regularly as the main method of
201    /// commands delivery (push) can sometimes be unreliable on mobile devices.
202    /// Typically called even when a push notification is received, so that
203    /// any prior messages for which a push didn't arrive are still handled.
204    ///
205    /// **💾 This method alters the persisted account state.**
206    pub fn poll_device_commands(
207        &mut self,
208        reason: CommandFetchReason,
209    ) -> Result<Vec<IncomingDeviceCommand>> {
210        let last_command_index = self.state.last_handled_command_index().unwrap_or(0);
211        // We increment last_command_index by 1 because the server response includes the current index.
212        self.fetch_and_parse_commands(last_command_index + 1, None, reason)
213    }
214
215    pub fn get_command_for_index(&mut self, index: u64) -> Result<IncomingDeviceCommand> {
216        let refresh_token = self.get_refresh_token()?;
217        let pending_commands =
218            self.client
219                .get_pending_commands(self.state.config(), refresh_token, index, Some(1))?;
220        self.parse_commands_messages(pending_commands.messages, CommandFetchReason::Push(index))?
221            .into_iter()
222            .next()
223            .ok_or_else(|| Error::CommandNotFound)
224    }
225
226    fn fetch_and_parse_commands(
227        &mut self,
228        index: u64,
229        limit: Option<u64>,
230        reason: CommandFetchReason,
231    ) -> Result<Vec<IncomingDeviceCommand>> {
232        let refresh_token = self.get_refresh_token()?;
233        let pending_commands =
234            self.client
235                .get_pending_commands(self.state.config(), refresh_token, index, limit)?;
236        if pending_commands.messages.is_empty() {
237            return Ok(Vec::new());
238        }
239        info!("Handling {} messages", pending_commands.messages.len());
240        let device_commands = self.parse_commands_messages(pending_commands.messages, reason)?;
241        self.state
242            .set_last_handled_command_index(pending_commands.index);
243        Ok(device_commands)
244    }
245
246    fn parse_commands_messages(
247        &mut self,
248        messages: Vec<PendingCommand>,
249        reason: CommandFetchReason,
250    ) -> Result<Vec<IncomingDeviceCommand>> {
251        let devices = self.get_devices(false)?;
252        let parsed_commands = messages
253            .into_iter()
254            .filter_map(|msg| match self.parse_command(msg, &devices, reason) {
255                Ok(device_command) => Some(device_command),
256                Err(e) => {
257                    error_support::report_error!(
258                        "fxa-client-command",
259                        "Error while processing command: {}",
260                        e
261                    );
262                    None
263                }
264            })
265            .collect();
266        Ok(parsed_commands)
267    }
268
269    fn parse_command(
270        &mut self,
271        command: PendingCommand,
272        devices: &[Device],
273        reason: CommandFetchReason,
274    ) -> Result<IncomingDeviceCommand> {
275        let telem_reason = match reason {
276            CommandFetchReason::Poll => telemetry::ReceivedReason::Poll,
277            CommandFetchReason::Push(index) if command.index < index => {
278                telemetry::ReceivedReason::PushMissed
279            }
280            _ => telemetry::ReceivedReason::Push,
281        };
282        let command_data = command.data;
283        let sender = command_data
284            .sender
285            .and_then(|s| devices.iter().find(|i| i.id == s).cloned());
286        match command_data.command.as_str() {
287            commands::send_tab::COMMAND_NAME => {
288                self.handle_send_tab_command(sender, command_data.payload, telem_reason)
289            }
290            commands::close_tabs::COMMAND_NAME => {
291                self.handle_close_tabs_command(sender, command_data.payload, telem_reason)
292            }
293            _ => Err(Error::UnknownCommand(command_data.command)),
294        }
295    }
296
297    pub fn set_device_name(&mut self, name: &str) -> Result<LocalDevice> {
298        let update = DeviceUpdateRequestBuilder::new().display_name(name).build();
299        self.update_device(update)
300    }
301
302    pub fn clear_device_name(&mut self) -> Result<()> {
303        let update = DeviceUpdateRequestBuilder::new()
304            .clear_display_name()
305            .build();
306        self.update_device(update)?;
307        Ok(())
308    }
309
310    pub fn set_push_subscription(
311        &mut self,
312        push_subscription: PushSubscription,
313    ) -> Result<LocalDevice> {
314        let update = DeviceUpdateRequestBuilder::new()
315            .push_subscription(&push_subscription)
316            .build();
317        self.update_device(update)
318    }
319
320    pub(crate) fn replace_device(
321        &mut self,
322        display_name: &str,
323        device_type: &DeviceType,
324        push_subscription: &Option<PushSubscription>,
325        commands: &HashMap<String, String>,
326    ) -> Result<()> {
327        self.state.clear_server_local_device_info();
328        let mut builder = DeviceUpdateRequestBuilder::new()
329            .display_name(display_name)
330            .device_type(device_type)
331            .available_commands(commands);
332        if let Some(push_subscription) = push_subscription {
333            builder = builder.push_subscription(push_subscription)
334        }
335        self.update_device(builder.build())?;
336        Ok(())
337    }
338
339    fn update_device(&mut self, update: DeviceUpdateRequest<'_>) -> Result<LocalDevice> {
340        let refresh_token = self.get_refresh_token()?;
341        let res = self
342            .client
343            .update_device_record(self.state.config(), refresh_token, update);
344        match res {
345            Ok(resp) => {
346                self.state.set_current_device_id(resp.id.clone());
347                let local_device = LocalDevice::from(resp);
348                self.state
349                    .update_server_local_device_info(local_device.clone());
350                Ok(local_device)
351            }
352            Err(err) => {
353                // We failed to write an update to the server.
354                // Clear local state so that we'll be sure to retry later.
355                self.state.clear_server_local_device_info();
356                Err(err)
357            }
358        }
359    }
360
361    /// Retrieve the current device id from state
362    pub fn get_current_device_id(&mut self) -> Result<String> {
363        match self.state.current_device_id() {
364            Some(ref device_id) => Ok(device_id.to_string()),
365            None => Err(Error::NoCurrentDeviceId),
366        }
367    }
368
369    /// Generate the command to be registered with the server for
370    /// the given capability.
371    ///
372    /// **💾 This method alters the persisted account state.**
373    pub(crate) fn generate_command_data(&mut self, capability: DeviceCapability) -> Result<String> {
374        let own_keys = self.load_or_generate_command_keys(capability)?;
375        let public_keys: PublicCommandKeys = own_keys.into();
376        let oldsync_key = self.get_scoped_key(scopes::OLD_SYNC)?;
377        public_keys.as_command_data(oldsync_key)
378    }
379
380    fn load_or_generate_command_keys(
381        &mut self,
382        capability: DeviceCapability,
383    ) -> Result<PrivateCommandKeys> {
384        match capability {
385            DeviceCapability::SendTab => self.load_or_generate_send_tab_keys(),
386            DeviceCapability::CloseTabs => self.load_or_generate_close_tabs_keys(),
387        }
388    }
389}
390
391impl TryFrom<String> for DeviceCapability {
392    type Error = Error;
393
394    fn try_from(command: String) -> Result<Self> {
395        match command.as_str() {
396            commands::send_tab::COMMAND_NAME => Ok(DeviceCapability::SendTab),
397            commands::close_tabs::COMMAND_NAME => Ok(DeviceCapability::CloseTabs),
398            _ => Err(Error::UnknownCommand(command)),
399        }
400    }
401}
402
403impl From<UpdateDeviceResponse> for LocalDevice {
404    fn from(resp: UpdateDeviceResponse) -> Self {
405        Self {
406            id: resp.id,
407            display_name: resp.display_name,
408            device_type: resp.device_type,
409            capabilities: resp
410                .available_commands
411                .into_keys()
412                .filter_map(|command| match command.try_into() {
413                    Ok(capability) => Some(capability),
414                    Err(e) => {
415                        warn!("While parsing UpdateDeviceResponse: {e}");
416                        None
417                    }
418                })
419                .collect(),
420            push_subscription: resp.push_subscription.map(Into::into),
421            push_endpoint_expired: resp.push_endpoint_expired,
422        }
423    }
424}
425
426impl TryFrom<Device> for crate::Device {
427    type Error = Error;
428    fn try_from(d: Device) -> Result<Self> {
429        let capabilities: Vec<_> = d
430            .available_commands
431            .keys()
432            .filter_map(|k| match k.as_str() {
433                commands::send_tab::COMMAND_NAME => Some(DeviceCapability::SendTab),
434                commands::close_tabs::COMMAND_NAME => Some(DeviceCapability::CloseTabs),
435                _ => None,
436            })
437            .collect();
438        Ok(crate::Device {
439            id: d.common.id,
440            display_name: d.common.display_name,
441            device_type: d.common.device_type,
442            capabilities,
443            push_subscription: d.common.push_subscription.map(Into::into),
444            push_endpoint_expired: d.common.push_endpoint_expired,
445            is_current_device: d.is_current_device,
446            last_access_time: d.last_access_time.map(TryFrom::try_from).transpose()?,
447        })
448    }
449}
450
451#[cfg(test)]
452mod tests {
453    use super::*;
454    use crate::internal::http_client::*;
455    use crate::internal::oauth::RefreshToken;
456    use crate::internal::Config;
457    use crate::ScopedKey;
458    use mockall::predicate::always;
459    use mockall::predicate::eq;
460    use nss_as::ensure_initialized;
461    use std::collections::HashSet;
462    use std::sync::Arc;
463
464    fn setup() -> FirefoxAccount {
465        ensure_initialized();
466
467        // I'd love to be able to configure a single mocked client here,
468        // but can't work out how to do that within the typesystem.
469        let config = Config::stable_dev("12345678", "https://foo.bar");
470        let mut fxa = FirefoxAccount::with_config(config);
471        fxa.state.force_refresh_token(RefreshToken {
472            token: "refreshtok".to_string(),
473            scopes: HashSet::default(),
474        });
475        fxa.state.insert_scoped_key("https://identity.mozilla.com/apps/oldsync", ScopedKey {
476            kty: "oct".to_string(),
477            scope: "https://identity.mozilla.com/apps/oldsync".to_string(),
478            k: "kMtwpVC0ZaYFJymPza8rXK_0CgCp3KMwRStwGfBRBDtL6hXRDVJgQFaoOQ2dimw0Bko5WVv2gNTy7RX5zFYZHg".to_string(),
479            kid: "1542236016429-Ox1FbJfFfwTe5t-xq4v2hQ".to_string(),
480        });
481        fxa
482    }
483
484    #[test]
485    fn test_ensure_capabilities_does_not_hit_the_server_if_nothing_has_changed() {
486        let mut fxa = setup();
487
488        // Do an initial call to ensure_capabilities().
489        let mut client = MockFxAClient::new();
490        client
491            .expect_update_device_record()
492            .with(always(), eq("refreshtok"), always())
493            .times(1)
494            .returning(|_, _, _| {
495                Ok(UpdateDeviceResponse {
496                    id: "device1".to_string(),
497                    display_name: "".to_string(),
498                    device_type: DeviceType::Desktop,
499                    push_subscription: None,
500                    available_commands: HashMap::from([(
501                        commands::send_tab::COMMAND_NAME.to_owned(),
502                        "fake-command-data".to_owned(),
503                    )]),
504                    push_endpoint_expired: false,
505                })
506            });
507        fxa.set_client(Arc::new(client));
508        fxa.ensure_capabilities(&[DeviceCapability::SendTab])
509            .unwrap();
510        let saved = fxa.to_json().unwrap();
511
512        // Do another call with the same capabilities.
513        // The MockFxAClient will panic if it tries to hit the network again, which it shouldn't.
514        fxa.ensure_capabilities(&[DeviceCapability::SendTab])
515            .unwrap();
516
517        // Do another call with the same capabilities , after restoring from disk.
518        // The MockFxAClient will panic if it tries to hit the network, which it shouldn't.
519        let mut restored = FirefoxAccount::from_json(&saved).unwrap();
520        restored.set_client(Arc::new(MockFxAClient::new()));
521        restored
522            .ensure_capabilities(&[DeviceCapability::SendTab])
523            .unwrap();
524    }
525
526    #[test]
527    fn test_ensure_capabilities_updates_the_server_if_capabilities_increase() {
528        let mut fxa = setup();
529
530        // Do an initial call to ensure_capabilities().
531        let mut client = MockFxAClient::new();
532        client
533            .expect_update_device_record()
534            .with(always(), eq("refreshtok"), always())
535            .times(1)
536            .returning(|_, _, _| {
537                Ok(UpdateDeviceResponse {
538                    id: "device1".to_string(),
539                    display_name: "".to_string(),
540                    device_type: DeviceType::Desktop,
541                    push_subscription: None,
542                    available_commands: HashMap::default(),
543                    push_endpoint_expired: false,
544                })
545            });
546        fxa.set_client(Arc::new(client));
547
548        fxa.ensure_capabilities(&[]).unwrap();
549        let saved = fxa.to_json().unwrap();
550
551        // Do another call with reduced capabilities.
552        let mut client = MockFxAClient::new();
553        client
554            .expect_update_device_record()
555            .with(always(), eq("refreshtok"), always())
556            .times(1)
557            .returning(|_, _, _| {
558                Ok(UpdateDeviceResponse {
559                    id: "device1".to_string(),
560                    display_name: "".to_string(),
561                    device_type: DeviceType::Desktop,
562                    push_subscription: None,
563                    available_commands: HashMap::from([(
564                        commands::send_tab::COMMAND_NAME.to_owned(),
565                        "fake-command-data".to_owned(),
566                    )]),
567                    push_endpoint_expired: false,
568                })
569            });
570        fxa.set_client(Arc::new(client));
571
572        fxa.ensure_capabilities(&[DeviceCapability::SendTab])
573            .unwrap();
574
575        // Do another call with the same capabilities , after restoring from disk.
576        // The MockFxAClient will panic if it tries to hit the network, which it shouldn't.
577        let mut restored = FirefoxAccount::from_json(&saved).unwrap();
578        let mut client = MockFxAClient::new();
579        client
580            .expect_update_device_record()
581            .with(always(), eq("refreshtok"), always())
582            .returning(|_, _, _| {
583                Ok(UpdateDeviceResponse {
584                    id: "device1".to_string(),
585                    display_name: "".to_string(),
586                    device_type: DeviceType::Desktop,
587                    push_subscription: None,
588                    available_commands: HashMap::from([(
589                        commands::send_tab::COMMAND_NAME.to_owned(),
590                        "fake-command-data".to_owned(),
591                    )]),
592                    push_endpoint_expired: false,
593                })
594            });
595        restored.set_client(Arc::new(client));
596
597        restored
598            .ensure_capabilities(&[DeviceCapability::SendTab])
599            .unwrap();
600    }
601
602    #[test]
603    fn test_ensure_capabilities_updates_the_server_if_capabilities_reduce() {
604        let mut fxa = setup();
605
606        // Do an initial call to ensure_capabilities().
607        let mut client = MockFxAClient::new();
608        client
609            .expect_update_device_record()
610            .with(always(), eq("refreshtok"), always())
611            .times(1)
612            .returning(|_, _, _| {
613                Ok(UpdateDeviceResponse {
614                    id: "device1".to_string(),
615                    display_name: "".to_string(),
616                    device_type: DeviceType::Desktop,
617                    push_subscription: None,
618                    available_commands: HashMap::from([(
619                        commands::send_tab::COMMAND_NAME.to_owned(),
620                        "fake-command-data".to_owned(),
621                    )]),
622                    push_endpoint_expired: false,
623                })
624            });
625        fxa.set_client(Arc::new(client));
626
627        fxa.ensure_capabilities(&[DeviceCapability::SendTab])
628            .unwrap();
629        let saved = fxa.to_json().unwrap();
630
631        // Do another call with reduced capabilities.
632        let mut client = MockFxAClient::new();
633        client
634            .expect_update_device_record()
635            .with(always(), eq("refreshtok"), always())
636            .times(1)
637            .returning(|_, _, _| {
638                Ok(UpdateDeviceResponse {
639                    id: "device1".to_string(),
640                    display_name: "".to_string(),
641                    device_type: DeviceType::Desktop,
642                    push_subscription: None,
643                    available_commands: HashMap::default(),
644                    push_endpoint_expired: false,
645                })
646            });
647        fxa.set_client(Arc::new(client));
648
649        fxa.ensure_capabilities(&[]).unwrap();
650
651        // Do another call with the same capabilities , after restoring from disk.
652        // The MockFxAClient will panic if it tries to hit the network, which it shouldn't.
653        let mut restored = FirefoxAccount::from_json(&saved).unwrap();
654        let mut client = MockFxAClient::new();
655        client
656            .expect_update_device_record()
657            .with(always(), eq("refreshtok"), always())
658            .times(1)
659            .returning(|_, _, _| {
660                Ok(UpdateDeviceResponse {
661                    id: "device1".to_string(),
662                    display_name: "".to_string(),
663                    device_type: DeviceType::Desktop,
664                    push_subscription: None,
665                    available_commands: HashMap::default(),
666                    push_endpoint_expired: false,
667                })
668            });
669        restored.set_client(Arc::new(client));
670
671        restored.ensure_capabilities(&[]).unwrap();
672    }
673
674    #[test]
675    fn test_ensure_capabilities_will_reregister_after_new_login_flow() {
676        let mut fxa = setup();
677
678        // Do an initial call to ensure_capabilities().
679        let mut client = MockFxAClient::new();
680        client
681            .expect_update_device_record()
682            .with(always(), eq("refreshtok"), always())
683            .times(1)
684            .returning(|_, _, _| {
685                Ok(UpdateDeviceResponse {
686                    id: "device1".to_string(),
687                    display_name: "".to_string(),
688                    device_type: DeviceType::Desktop,
689                    push_subscription: None,
690                    available_commands: HashMap::from([(
691                        commands::send_tab::COMMAND_NAME.to_owned(),
692                        "fake-command-data".to_owned(),
693                    )]),
694                    push_endpoint_expired: false,
695                })
696            });
697        fxa.set_client(Arc::new(client));
698        fxa.ensure_capabilities(&[DeviceCapability::SendTab])
699            .unwrap();
700
701        // Fake that we've completed a new login flow.
702        // (which annoyingly makes a bunch of network requests)
703        let mut client = MockFxAClient::new();
704        client
705            .expect_destroy_access_token()
706            .with(always(), always())
707            .times(1)
708            .returning(|_, _| {
709                Err(Error::RemoteError {
710                    code: 500,
711                    errno: 999,
712                    error: "server error".to_string(),
713                    message: "this will be ignored anyway".to_string(),
714                    info: "".to_string(),
715                })
716            });
717        client
718            .expect_get_devices()
719            .with(always(), always())
720            .times(1)
721            .returning(|_, _| {
722                Err(Error::RemoteError {
723                    code: 500,
724                    errno: 999,
725                    error: "server error".to_string(),
726                    message: "this will be ignored anyway".to_string(),
727                    info: "".to_string(),
728                })
729            });
730        client
731            .expect_destroy_refresh_token()
732            .with(always(), always())
733            .times(1)
734            .returning(|_, _| {
735                Err(Error::RemoteError {
736                    code: 500,
737                    errno: 999,
738                    error: "server error".to_string(),
739                    message: "this will be ignored anyway".to_string(),
740                    info: "".to_string(),
741                })
742            });
743        fxa.set_client(Arc::new(client));
744
745        fxa.handle_oauth_response(
746            OAuthTokenResponse {
747                keys_jwe: None,
748                refresh_token: Some("newRefreshTok".to_string()),
749                session_token: None,
750                expires_in: 12345,
751                scope: "profile".to_string(),
752                access_token: "accesstok".to_string(),
753            },
754            None,
755        )
756        .unwrap();
757
758        assert!(fxa.state.server_local_device_info().is_none());
759
760        // Do another call with the same capabilities.
761        // It should re-register, as server-side state may have changed.
762        let mut client = MockFxAClient::new();
763        client
764            .expect_update_device_record()
765            .with(always(), eq("newRefreshTok"), always())
766            .times(1)
767            .returning(|_, _, _| {
768                Ok(UpdateDeviceResponse {
769                    id: "device1".to_string(),
770                    display_name: "".to_string(),
771                    device_type: DeviceType::Desktop,
772                    push_subscription: None,
773                    available_commands: HashMap::from([(
774                        commands::send_tab::COMMAND_NAME.to_owned(),
775                        "fake-command-data".to_owned(),
776                    )]),
777                    push_endpoint_expired: false,
778                })
779            });
780        fxa.set_client(Arc::new(client));
781        fxa.ensure_capabilities(&[DeviceCapability::SendTab])
782            .unwrap();
783    }
784
785    #[test]
786    fn test_ensure_capabilities_updates_the_server_if_previous_attempt_failed() {
787        let mut fxa = setup();
788
789        // Do an initial call to ensure_capabilities(), that fails.
790        let mut client = MockFxAClient::new();
791        client
792            .expect_update_device_record()
793            .with(always(), eq("refreshtok"), always())
794            .times(1)
795            .returning(|_, _, _| {
796                Err(Error::RemoteError {
797                    code: 500,
798                    errno: 999,
799                    error: "server error".to_string(),
800                    message: "this will be ignored anyway".to_string(),
801                    info: "".to_string(),
802                })
803            });
804        fxa.set_client(Arc::new(client));
805
806        fxa.ensure_capabilities(&[DeviceCapability::SendTab])
807            .unwrap_err();
808
809        // Do another call, which should re-attempt the update.
810        let mut client = MockFxAClient::new();
811        client
812            .expect_update_device_record()
813            .with(always(), eq("refreshtok"), always())
814            .times(1)
815            .returning(|_, _, _| {
816                Ok(UpdateDeviceResponse {
817                    id: "device1".to_string(),
818                    display_name: "".to_string(),
819                    device_type: DeviceType::Desktop,
820                    push_subscription: None,
821                    available_commands: HashMap::from([(
822                        commands::send_tab::COMMAND_NAME.to_owned(),
823                        "fake-command-data".to_owned(),
824                    )]),
825                    push_endpoint_expired: false,
826                })
827            });
828        fxa.set_client(Arc::new(client));
829
830        fxa.ensure_capabilities(&[DeviceCapability::SendTab])
831            .unwrap();
832    }
833
834    #[test]
835    fn test_get_devices() {
836        let mut fxa = setup();
837        let mut client = MockFxAClient::new();
838        client
839            .expect_get_devices()
840            .with(always(), always())
841            .times(1)
842            .returning(|_, _| {
843                Ok(vec![Device {
844                    common: DeviceResponseCommon {
845                        id: "device1".into(),
846                        display_name: "".to_string(),
847                        device_type: DeviceType::Desktop,
848                        push_subscription: None,
849                        available_commands: HashMap::new(),
850                        push_endpoint_expired: true,
851                    },
852                    is_current_device: true,
853                    location: DeviceLocation {
854                        city: None,
855                        country: None,
856                        state: None,
857                        state_code: None,
858                    },
859                    last_access_time: None,
860                }])
861            });
862
863        fxa.set_client(Arc::new(client));
864        assert!(fxa.devices_cache.is_none());
865
866        assert!(fxa.get_devices(false).is_ok());
867        assert!(fxa.devices_cache.is_some());
868
869        let cache = fxa.devices_cache.clone().unwrap();
870        assert!(!cache.response.is_empty());
871        assert!(cache.cached_at > 0);
872
873        let cached_devices = cache.response;
874        assert_eq!(cached_devices[0].id, "device1".to_string());
875
876        // Check that a second call to get_devices doesn't hit the server
877        assert!(fxa.get_devices(false).is_ok());
878        assert!(fxa.devices_cache.is_some());
879
880        let cache2 = fxa.devices_cache.unwrap();
881        let cached_devices2 = cache2.response;
882
883        assert_eq!(cache.cached_at, cache2.cached_at);
884        assert_eq!(cached_devices.len(), cached_devices2.len());
885        assert_eq!(cached_devices[0].id, cached_devices2[0].id);
886    }
887
888    #[test]
889    fn test_get_devices_network_errors() {
890        let mut fxa = setup();
891        let mut client = MockFxAClient::new();
892        client
893            .expect_get_devices()
894            .with(always(), always())
895            .times(1)
896            .returning(|_, _| {
897                Err(Error::RemoteError {
898                    code: 500,
899                    errno: 101,
900                    error: "Did not work!".to_owned(),
901                    message: "Did not work!".to_owned(),
902                    info: "Did not work!".to_owned(),
903                })
904            });
905
906        fxa.set_client(Arc::new(client));
907        assert!(fxa.devices_cache.is_none());
908
909        let res = fxa.get_devices(false);
910
911        assert!(res.is_err());
912        assert!(fxa.devices_cache.is_none());
913    }
914}