fxa_client/internal/
oauth.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
5pub mod access_token;
6pub mod attached_clients;
7use super::scopes;
8use super::{
9    http_client::{AuthorizationRequestParameters, OAuthTokenResponse},
10    scoped_keys::ScopedKeysFlow,
11    util, FirefoxAccount,
12};
13use crate::internal::state_manager::StoredAuthState;
14use crate::{
15    debug, info, warn, AuthorizationParameters, AuthorizationStatus, Error, FxaServer, Result,
16};
17pub use access_token::AccessTokenInfo;
18use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
19use jwcrypto::{EncryptionAlgorithm, EncryptionParameters};
20use rate_limiter::RateLimiter;
21use rc_crypto::digest;
22use serde_derive::*;
23use std::collections::{HashMap, HashSet};
24use url::Url;
25// Special redirect urn based on the OAuth native spec, signals that the
26// WebChannel flow is used
27pub const OAUTH_WEBCHANNEL_REDIRECT: &str = "urn:ietf:wg:oauth:2.0:oob:oauth-redirect-webchannel";
28
29impl FirefoxAccount {
30    /// Check whether every requested scope has been granted to the account's refresh token.
31    pub fn has_scope(&self, scope: &str) -> bool {
32        let mut requested = scope.split_ascii_whitespace().peekable();
33        if requested.peek().is_none() {
34            return false;
35        }
36        match self.state.refresh_token() {
37            Some(refresh_token) => requested.all(|s| refresh_token.scopes.contains(s)),
38            None => false,
39        }
40    }
41
42    /// Extracts and stores the session token from a WebChannel login JSON payload.
43    /// The JSON payload is the `data` object from the `fxaccounts:login` WebChannel command.
44    pub fn handle_web_channel_login(&mut self, json_payload: &str) -> Result<()> {
45        let data: serde_json::Value = serde_json::from_str(json_payload)?;
46        let token = data
47            .get("sessionToken")
48            .and_then(|v| v.as_str())
49            .ok_or(Error::NoSessionToken)?;
50        self.state.set_session_token(token.to_string());
51        Ok(())
52    }
53
54    /// Extracts the session token from a WebChannel password change JSON payload, exchanges it
55    /// for a new refresh token.
56    pub fn handle_web_channel_password_change(&mut self, json_payload: &str) -> Result<()> {
57        self.with_network_retry("handle_web_channel_password_change", |s| {
58            s._handle_web_channel_password_change(json_payload)
59        })
60    }
61
62    fn _handle_web_channel_password_change(&mut self, json_payload: &str) -> Result<()> {
63        let data: serde_json::Value = serde_json::from_str(json_payload)?;
64        let token = data
65            .get("sessionToken")
66            .and_then(|v| v.as_str())
67            .ok_or(Error::NoSessionToken)?;
68        // Grab the current device before the token swap since destroying the old refresh token
69        // tears down its associated device record server-side.
70        let old_device_info = match self.get_current_device() {
71            Ok(maybe_device) => maybe_device,
72            Err(err) => {
73                warn!(
74                    "Error fetching current device before password change: {:?}",
75                    err
76                );
77                None
78            }
79        };
80        self.handle_session_token_change(token)?;
81        if let Some(ref device_info) = old_device_info {
82            if let Err(err) = self.replace_device(
83                &device_info.display_name,
84                &device_info.device_type,
85                &device_info.push_subscription,
86                &device_info.available_commands,
87            ) {
88                warn!(
89                    "Device information restoration failed after password change: {:?}",
90                    err
91                );
92            } else {
93                info!("Restored device information with new refresh token");
94            }
95        }
96        Ok(())
97    }
98
99    /// Retrieve the current session token from state
100    pub fn get_session_token(&self) -> Result<String> {
101        match self.state.session_token() {
102            Some(session_token) => Ok(session_token.to_string()),
103            None => Err(Error::NoSessionToken),
104        }
105    }
106
107    /// Builds a complete `signedInUser` JSON object for a WebChannel `fxaccounts:fxa_status`
108    /// response. Returns `None` if no session token is stored.
109    /// `email` and `uid` are read from the cached profile; `verified` is always true because
110    /// the account state machine only completes authentication for verified accounts.
111    pub fn get_signed_in_user_for_web_channel(&self) -> Option<String> {
112        let token = self.state.session_token()?;
113        let profile = self.state.last_seen_profile();
114        let email = profile.map(|p| p.response.email.as_str());
115        let uid = profile.map(|p| p.response.uid.as_str());
116        Some(
117            serde_json::json!({
118                "sessionToken": token,
119                "email": email,
120                "uid": uid,
121                "verified": true,
122            })
123            .to_string(),
124        )
125    }
126
127    /// Check authorization status for this application.
128    ///
129    /// Call this method to validate the current auth tokens. This checks that all expected tokens
130    /// are present and also validates the refresh token with the FxA server.
131    pub fn check_authorization_status(&mut self) -> AuthorizationStatus {
132        self.with_network_retry("check_authorization_status", |s| {
133            s._check_authorization_status()
134        })
135        // Real auth errors are handled inside `_check_authorization_status`.
136        // If we see a failure here, it means there was a network error and we should return
137        // `Unknown`.
138        .unwrap_or(AuthorizationStatus::Unknown)
139    }
140
141    fn _check_authorization_status(&mut self) -> Result<AuthorizationStatus> {
142        let StoredAuthState::Valid { refresh_token } = self.state.stored_auth_state() else {
143            return Ok(AuthorizationStatus::Invalid);
144        };
145        if self.auth_circuit_breaker.check().is_err() {
146            // Circuit breaker tripped, return `Unknown` instead of sending another network request.
147            // https://bugzilla.mozilla.org/show_bug.cgi?id=2084267
148            return Ok(AuthorizationStatus::Unknown);
149        }
150        let resp = self
151            .client
152            .check_refresh_token_status(self.state.config(), &refresh_token.token)?;
153        if resp.active {
154            Ok(AuthorizationStatus::Valid)
155        } else {
156            Ok(AuthorizationStatus::Invalid)
157        }
158    }
159
160    /// Initiate a pairing flow and return a URL that should be navigated to.
161    ///
162    /// * `pairing_url` - A pairing URL obtained by scanning a QR code produced by
163    ///   the pairing authority.
164    /// * `scopes` - Space-separated list of requested scopes by the pairing supplicant.
165    /// * `entrypoint` - The entrypoint to be used for data collection
166    /// * `metrics` - Optional parameters for metrics
167    pub fn begin_pairing_flow(
168        &mut self,
169        pairing_url: &str,
170        service: &str,
171        scopes: &[&str],
172        entrypoint: &str,
173    ) -> Result<String> {
174        self.with_network_retry("begin_pairing_flow", |s| {
175            s._begin_pairing_flow(pairing_url, service, scopes, entrypoint)
176        })
177    }
178
179    fn _begin_pairing_flow(
180        &mut self,
181        pairing_url: &str,
182        service: &str,
183        scopes: &[&str],
184        entrypoint: &str,
185    ) -> Result<String> {
186        self.cancel_existing_oauth_flows();
187        let mut url = self.state.config().pair_supp_url()?;
188        url.query_pairs_mut().append_pair("entrypoint", entrypoint);
189        if !service.is_empty() {
190            url.query_pairs_mut().append_pair("service", service);
191        }
192        let pairing_url = util::parse_url(pairing_url, "begin_pairing_flow")?;
193        if url.host_str() != pairing_url.host_str() {
194            let fxa_server = FxaServer::from(&url);
195            let pairing_fxa_server = FxaServer::from(&pairing_url);
196            return Err(Error::OriginMismatch(format!(
197                "fxa-server: {fxa_server}, pairing-url-fxa-server: {pairing_fxa_server}"
198            )));
199        }
200        url.set_fragment(pairing_url.fragment());
201        self.oauth_flow(url, scopes)
202    }
203
204    /// Initiate an OAuth login flow and return a URL that should be navigated to.
205    ///
206    /// * `scopes` - Space-separated list of requested scopes.
207    /// * `entrypoint` - The entrypoint to be used for metrics
208    /// * `metrics` - Optional metrics parameters
209    ///
210    /// Note that you can use this to either perform an initial signin, or use this on
211    /// an already signed in account to get more scopes for that account.
212    /// When obtaining more scopes, only the new scopes needed should be requested
213    /// rather than the union of all scopes - this is because asking for a scope with
214    /// keys (eg, sync) would force the UI to go through a different UI flow - eg, always
215    /// asking for your password, even though the new scopes requested doesn't actually
216    /// require that. This code therefore knows how to merge the scopes at the end of the
217    /// flow, so the end result remains a new refresh token with the union of scopes.
218    pub fn begin_oauth_flow(
219        &mut self,
220        service: &str,
221        scopes: &[&str],
222        entrypoint: &str,
223    ) -> Result<String> {
224        self.with_network_retry("begin_oauth_flow", |s| {
225            s._begin_oauth_flow(service, scopes, entrypoint)
226        })
227    }
228
229    fn _begin_oauth_flow(
230        &mut self,
231        service: &str,
232        scopes: &[&str],
233        entrypoint: &str,
234    ) -> Result<String> {
235        self.cancel_existing_oauth_flows();
236        let needs_reauth =
237            self.state.last_seen_profile().is_some() && self.state.session_token().is_none();
238        let mut url = if needs_reauth {
239            // must be in a needs-reauth or other odd state. Not clear this is strictly needed.
240            // further, this is still somewhat wrong in a "needs reauth" state - there we will be
241            // looking to get back all scopes we previously had - and it's not really expected the client
242            // knows that. We probably need to stash the old scopes when we enter the needsreauth
243            // state. But that's a todo.
244            self.state.config().oauth_force_auth_url()?
245        } else {
246            self.state.config().authorization_endpoint()?
247        };
248
249        info!("starting oauth flow via {url} for service={service:?}, scopes={scopes:?}, entrypoint={entrypoint:?}");
250        url.query_pairs_mut()
251            .append_pair("action", "email")
252            .append_pair("response_type", "code")
253            .append_pair("entrypoint", entrypoint);
254
255        if !service.is_empty() {
256            url.query_pairs_mut().append_pair("service", service);
257        }
258        if let Some(cached_profile) = self.state.last_seen_profile() {
259            url.query_pairs_mut()
260                .append_pair("email", &cached_profile.response.email);
261        }
262
263        debug!("oauth flow final set of requested scopes now {scopes:?}");
264        self.oauth_flow(url, scopes)
265    }
266
267    /// Fetch an OAuth code for a particular client using a session token from the account state.
268    ///
269    /// * `auth_params` Authorization parameters  which includes:
270    ///     *  `client_id` - OAuth client id.
271    ///     *  `scope` - list of requested scopes.
272    ///     *  `state` - OAuth state.
273    ///     *  `access_type` - Type of OAuth access, can be "offline" and "online"
274    ///     *  `pkce_params` - Optional PKCE parameters for public clients (`code_challenge` and `code_challenge_method`)
275    ///     *  `keys_jwk` - Optional JWK used to encrypt scoped keys
276    pub fn authorize_code_using_session_token(
277        &self,
278        auth_params: AuthorizationParameters,
279    ) -> Result<String> {
280        let session_token = self.get_session_token()?;
281
282        // Validate request to ensure that the client is actually allowed to request
283        // the scopes they requested
284        let allowed_scopes = self.client.get_scoped_key_data(
285            self.state.config(),
286            &session_token,
287            &auth_params.client_id,
288            &auth_params.scope.join(" "),
289        )?;
290
291        if let Some(not_allowed_scope) = auth_params
292            .scope
293            .iter()
294            .find(|scope| !allowed_scopes.contains_key(*scope))
295        {
296            return Err(Error::ScopeNotAllowed(
297                auth_params.client_id.clone(),
298                not_allowed_scope.clone(),
299            ));
300        }
301
302        let keys_jwe = if let Some(keys_jwk) = auth_params.keys_jwk {
303            let mut scoped_keys = HashMap::new();
304            allowed_scopes
305                .iter()
306                .try_for_each(|(scope, _)| -> Result<()> {
307                    scoped_keys.insert(
308                        scope,
309                        self.state
310                            .get_scoped_key(scope)
311                            .ok_or_else(|| Error::NoScopedKey(scope.clone()))?,
312                    );
313                    Ok(())
314                })?;
315            let scoped_keys = serde_json::to_string(&scoped_keys)?;
316            let keys_jwk = URL_SAFE_NO_PAD.decode(keys_jwk)?;
317            let jwk = serde_json::from_slice(&keys_jwk)?;
318            Some(jwcrypto::encrypt_to_jwe(
319                scoped_keys.as_bytes(),
320                EncryptionParameters::ECDH_ES {
321                    enc: EncryptionAlgorithm::A256GCM,
322                    peer_jwk: &jwk,
323                },
324            )?)
325        } else {
326            None
327        };
328        let auth_request_params = AuthorizationRequestParameters {
329            client_id: auth_params.client_id,
330            scope: auth_params.scope.join(" "),
331            state: auth_params.state,
332            access_type: auth_params.access_type,
333            code_challenge: auth_params.code_challenge,
334            code_challenge_method: auth_params.code_challenge_method,
335            keys_jwe,
336        };
337
338        let resp = self.client.create_authorization_code_using_session_token(
339            self.state.config(),
340            &session_token,
341            auth_request_params,
342        )?;
343
344        Ok(resp.code)
345    }
346
347    fn oauth_flow(&mut self, mut url: Url, scopes: &[&str]) -> Result<String> {
348        self.clear_access_token_cache();
349        let state = util::random_base64_url_string(16)?;
350        let code_verifier = util::random_base64_url_string(43)?;
351        let code_challenge = digest::digest(&digest::SHA256, code_verifier.as_bytes())?;
352        let code_challenge = URL_SAFE_NO_PAD.encode(code_challenge);
353        let scoped_keys_flow = ScopedKeysFlow::with_random_key()?;
354        let jwk = scoped_keys_flow.get_public_key_jwk()?;
355        let jwk_json = serde_json::to_string(&jwk)?;
356        let keys_jwk = URL_SAFE_NO_PAD.encode(jwk_json);
357        url.query_pairs_mut()
358            .append_pair("client_id", &self.state.config().client_id)
359            .append_pair("state", &state)
360            .append_pair("code_challenge_method", "S256")
361            .append_pair("code_challenge", &code_challenge)
362            .append_pair("access_type", "offline")
363            .append_pair("keys_jwk", &keys_jwk);
364
365        if !scopes.is_empty() {
366            url.query_pairs_mut()
367                .append_pair("scope", &scopes.join(" "));
368        }
369        if self.state.config().redirect_uri == OAUTH_WEBCHANNEL_REDIRECT {
370            url.query_pairs_mut()
371                .append_pair("context", "oauth_webchannel_v1");
372        } else {
373            url.query_pairs_mut()
374                .append_pair("redirect_uri", &self.state.config().redirect_uri);
375        }
376
377        self.state.begin_oauth_flow(
378            state,
379            OAuthFlow {
380                scoped_keys_flow: Some(scoped_keys_flow),
381                code_verifier,
382            },
383        );
384        Ok(url.to_string())
385    }
386
387    /// Complete an OAuth flow initiated in `begin_oauth_flow` or `begin_pairing_flow`.
388    /// The `code` and `state` parameters can be obtained by parsing out the
389    /// redirect URL after a successful login.
390    ///
391    /// **💾 This method alters the persisted account state.**
392    pub fn complete_oauth_flow(&mut self, code: &str, state: &str) -> Result<()> {
393        self.clear_access_token_cache();
394        let oauth_flow = match self.state.pop_oauth_flow(state) {
395            Some(oauth_flow) => oauth_flow,
396            None => return Err(Error::UnknownOAuthState),
397        };
398        let resp = self.with_network_retry("complete_oauth_flow", |s| {
399            // Note: only wrap this part in `with_network_retry`, since we can't retry popping the
400            // oauth flow.  Also, if we can't retry `pop_oauth_flow`, then we also can't retry
401            // `handle_oauth_response` since `scoped_keys_flow` is not cloneable.
402            s.client.create_refresh_token_using_authorization_code(
403                s.state.config(),
404                s.state.session_token(),
405                code,
406                &oauth_flow.code_verifier,
407            )
408        })?;
409        info!(
410            "complete oauth flow - new session token={}, new refresh token={}",
411            resp.session_token.is_some(),
412            resp.refresh_token.is_some()
413        );
414        self.handle_oauth_response(resp, oauth_flow.scoped_keys_flow)?;
415        Ok(())
416    }
417
418    /// Cancel any in-progress oauth flows
419    pub fn cancel_existing_oauth_flows(&mut self) {
420        self.state.clear_oauth_flows();
421    }
422
423    pub(crate) fn handle_oauth_response(
424        &mut self,
425        resp: OAuthTokenResponse,
426        scoped_keys_flow: Option<ScopedKeysFlow>,
427    ) -> Result<()> {
428        // These are the keys granted by *this* response - any invariants about scopes vs keys
429        // must be checked after we've fully merged the scopes and keys.
430        let scoped_keys = match resp.keys_jwe {
431            Some(ref jwe) => {
432                let scoped_keys_flow = scoped_keys_flow.ok_or(Error::ApiClientError(
433                    "Got a JWE but have no JWK to decrypt it.",
434                ))?;
435                let decrypted_keys = scoped_keys_flow.decrypt_keys_jwe(jwe)?;
436                let scoped_keys: serde_json::Map<String, serde_json::Value> =
437                    serde_json::from_str(&decrypted_keys)?;
438                scoped_keys
439                    .into_iter()
440                    .map(|(scope, key)| Ok((scope, serde_json::from_value(key)?)))
441                    .collect::<Result<Vec<_>>>()?
442            }
443            None => vec![],
444        };
445
446        // We are only interested in the refresh token at this time because we
447        // don't want to return an over-scoped access token.
448        // Let's be good citizens and destroy this access token.
449        if let Err(err) = self
450            .client
451            .destroy_access_token(self.state.config(), &resp.access_token)
452        {
453            warn!("Access token destruction failure: {:?}", err);
454        }
455        let old_refresh_token = self.state.refresh_token().cloned();
456        let mut new_refresh_token = RefreshToken::new(
457            resp.refresh_token
458                .ok_or(Error::ApiClientError("No refresh token in response"))?,
459            resp.scope,
460        );
461        // Destroying a refresh token also destroys its associated device,
462        // grab the device information for replication later.
463        let old_device_info = match old_refresh_token {
464            Some(_) => match self.get_current_device() {
465                Ok(maybe_device) => maybe_device,
466                Err(err) => {
467                    warn!("Error while getting previous device information: {:?}", err);
468                    None
469                }
470            },
471            None => None,
472        };
473
474        if let Some(ref old_refresh_token) = old_refresh_token {
475            // As described in the docs for `begin_oauth_flow`, we now have a new refresh token,
476            // but only with new scopes we explicitly requested.
477            // We possibly had an old refresh token with only the scopes we had before.
478            // In that scenario, we need to create yet another refresh token with merged scopes.
479            let existing_scopes = &old_refresh_token.scopes;
480            let all_scopes: HashSet<_> = existing_scopes
481                .union(&new_refresh_token.scopes)
482                .cloned()
483                .collect();
484            if all_scopes != new_refresh_token.scopes {
485                if let Some(session_token) = self.state.session_token() {
486                    info!("New refresh token is missing some of our old scopes, upgrading");
487                    // We'd prefer to call `exchange_token_for_scope` instead of `create_refresh_token_using_session_token`,
488                    // but that's not currently setup correctly for this.
489                    // NOTE: when we *do* call `exchange_token_for_scope` we shouldn't need to do the device reregistration
490                    // this as that's handled by the server in that scenario.
491                    let scopes_slice = all_scopes.iter().map(|s| s.as_ref()).collect::<Vec<&str>>();
492                    let merged_refresh_token_resp =
493                        self.client.create_refresh_token_using_session_token(
494                            self.state.config(),
495                            session_token,
496                            &scopes_slice,
497                        )?;
498                    let Some(merged_refresh_token_str) = merged_refresh_token_resp.refresh_token
499                    else {
500                        log::error!("server failed to give a new refresh token");
501                        return Err(Error::NoRefreshToken);
502                    };
503
504                    // now destroy the one we got from this response.
505                    if let Err(err) = self
506                        .client
507                        .destroy_refresh_token(self.state.config(), &new_refresh_token.token)
508                    {
509                        warn!(
510                            "Refresh token destruction failure of new refresh token: {:?}",
511                            err
512                        );
513                    }
514
515                    new_refresh_token = RefreshToken::new(
516                        merged_refresh_token_str,
517                        merged_refresh_token_resp.scope,
518                    );
519                } else {
520                    warn!("New refresh token is missing some of our old scopes, but don't have a session token to use to upgrade");
521                }
522            } else {
523                // this seems odd, but I guess not bad?
524                info!("New refresh token has the same scopes we started with");
525            }
526
527            // In order to keep 1 and only 1 refresh token alive per client instance,
528            // we also destroy the old refresh token.
529            if let Err(err) = self
530                .client
531                .destroy_refresh_token(self.state.config(), &old_refresh_token.token)
532            {
533                warn!(
534                    "Refresh token destruction failure of old refresh token: {:?}",
535                    err
536                );
537            }
538            // and clear the old refresh token from our state, just in case we encounter an error before
539            // we've set the new one as current.
540            self.state.clear_refresh_token();
541        }
542
543        // Evaluate the sync-key invariant against the final state: the scopes the merged
544        // refresh token actually carries, and every key we'll hold afterwards (keys from this
545        // response plus keys we already had for other scopes).
546        let sync_scope_granted = new_refresh_token.scopes.contains(scopes::OLD_SYNC);
547        let have_sync_key = scoped_keys
548            .iter()
549            .any(|(scope, _)| scope == scopes::OLD_SYNC)
550            || self.state.get_scoped_key(scopes::OLD_SYNC).is_some();
551        if sync_scope_granted && !have_sync_key {
552            error_support::report_error!(
553                "fxa-client-scoped-key",
554                "Sync scope granted, but no sync scoped key held (final scopes: {})",
555                new_refresh_token
556                    .scopes
557                    .iter()
558                    .cloned()
559                    .collect::<Vec<_>>()
560                    .join(", ")
561            );
562        }
563
564        self.state
565            .complete_oauth_flow(scoped_keys, new_refresh_token, resp.session_token);
566        if let Some(ref device_info) = old_device_info {
567            if let Err(err) = self.replace_device(
568                &device_info.display_name,
569                &device_info.device_type,
570                &device_info.push_subscription,
571                &device_info.available_commands,
572            ) {
573                warn!("Device information restoration failed: {:?}", err);
574            }
575            info!("restored device information with new refresh token");
576        }
577        Ok(())
578    }
579
580    /// Typically called during a password change flow.
581    /// Invalidates all tokens and fetches a new refresh token.
582    /// Because the old refresh token is not valid anymore, we can't do like `handle_oauth_response`
583    /// and re-create the device, so it is the responsibility of the caller to do so after we're
584    /// done.
585    ///
586    /// **💾 This method alters the persisted account state.**
587    pub fn handle_session_token_change(&mut self, session_token: &str) -> Result<()> {
588        let old_refresh_token = self.state.refresh_token().ok_or(Error::NoRefreshToken)?;
589        let scopes: Vec<&str> = old_refresh_token.scopes.iter().map(AsRef::as_ref).collect();
590        let resp = self.client.create_refresh_token_using_session_token(
591            self.state.config(),
592            session_token,
593            &scopes,
594        )?;
595        let new_refresh_token = resp
596            .refresh_token
597            .ok_or(Error::ApiClientError("No refresh token in response"))?;
598        self.state.update_tokens(
599            session_token.to_owned(),
600            RefreshToken {
601                token: new_refresh_token,
602                scopes: resp.scope.split(' ').map(ToString::to_string).collect(),
603            },
604        );
605        self.clear_devices_and_attached_clients_cache();
606        Ok(())
607    }
608}
609
610const AUTH_CIRCUIT_BREAKER_CAPACITY: u8 = 5;
611const AUTH_CIRCUIT_BREAKER_RENEWAL_RATE: f32 = 3.0 / 60.0 / 1000.0; // 3 tokens every minute.
612
613#[derive(Clone, Copy)]
614pub(crate) struct AuthCircuitBreaker {
615    rate_limiter: RateLimiter,
616}
617
618impl Default for AuthCircuitBreaker {
619    fn default() -> Self {
620        AuthCircuitBreaker {
621            rate_limiter: RateLimiter::new(
622                AUTH_CIRCUIT_BREAKER_CAPACITY,
623                AUTH_CIRCUIT_BREAKER_RENEWAL_RATE,
624            ),
625        }
626    }
627}
628
629impl AuthCircuitBreaker {
630    pub(crate) fn check(&mut self) -> Result<()> {
631        if !self.rate_limiter.check() {
632            return Err(Error::AuthCircuitBreakerError);
633        }
634        Ok(())
635    }
636}
637
638impl TryFrom<Url> for AuthorizationParameters {
639    type Error = Error;
640
641    fn try_from(url: Url) -> Result<Self> {
642        let query_map: HashMap<String, String> = url.query_pairs().into_owned().collect();
643        let scope = query_map
644            .get("scope")
645            .cloned()
646            .ok_or(Error::MissingUrlParameter("scope"))?;
647        let client_id = query_map
648            .get("client_id")
649            .cloned()
650            .ok_or(Error::MissingUrlParameter("client_id"))?;
651        let state = query_map
652            .get("state")
653            .cloned()
654            .ok_or(Error::MissingUrlParameter("state"))?;
655        let access_type = query_map
656            .get("access_type")
657            .cloned()
658            .ok_or(Error::MissingUrlParameter("access_type"))?;
659        let code_challenge = query_map.get("code_challenge").cloned();
660        let code_challenge_method = query_map.get("code_challenge_method").cloned();
661        let keys_jwk = query_map.get("keys_jwk").cloned();
662        Ok(Self {
663            client_id,
664            scope: scope.split_whitespace().map(|s| s.to_string()).collect(),
665            state,
666            access_type,
667            code_challenge,
668            code_challenge_method,
669            keys_jwk,
670        })
671    }
672}
673
674#[derive(Clone, Serialize, Deserialize)]
675pub struct RefreshToken {
676    pub token: String,
677    pub scopes: HashSet<String>,
678}
679
680impl RefreshToken {
681    pub fn new(token: String, scopes: String) -> Self {
682        Self {
683            token,
684            scopes: scopes
685                .split_ascii_whitespace()
686                .map(ToString::to_string)
687                .collect(),
688        }
689    }
690}
691
692impl std::fmt::Debug for RefreshToken {
693    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
694        f.debug_struct("RefreshToken")
695            .field("scopes", &self.scopes)
696            .finish()
697    }
698}
699
700pub struct OAuthFlow {
701    pub scoped_keys_flow: Option<ScopedKeysFlow>,
702    pub code_verifier: String,
703}
704
705#[cfg(test)]
706impl FirefoxAccount {
707    pub fn set_session_token(&mut self, session_token: &str) {
708        self.state.set_session_token(session_token.to_owned());
709    }
710}
711
712#[cfg(test)]
713mod tests {
714    use super::super::{http_client::*, Config};
715    use super::*;
716    use mockall::predicate::always;
717    use mockall::predicate::eq;
718    use std::borrow::Cow;
719    use std::collections::HashMap;
720    use std::sync::Arc;
721
722    #[test]
723    fn test_has_scope() {
724        nss_as::ensure_initialized();
725        let mut fxa =
726            FirefoxAccount::with_config(Config::stable_dev("12345678", "https://foo.bar"));
727        // No refresh token -> false.
728        assert!(!fxa.has_scope("profile"));
729        fxa.state.force_refresh_token(RefreshToken {
730            token: "rt".to_owned(),
731            scopes: ["profile", "sync"].iter().map(|s| s.to_string()).collect(),
732        });
733        fxa.state.force_session_token("test-session-token");
734        assert!(fxa.has_scope("profile"));
735        assert!(fxa.has_scope("sync profile"));
736        assert!(fxa.has_scope("profile sync ")); // trailing whitespace too
737        assert!(!fxa.has_scope("sync unknown")); // one missing -> false
738        assert!(!fxa.has_scope("")); // empty -> false
739    }
740
741    #[test]
742    fn test_oauth_flow_url_without_scopes() {
743        nss_as::ensure_initialized();
744        let config = Config::new_with_mock_well_known_fxa_client_configuration(
745            "https://mock-fxa.example.com",
746            "12345678",
747            "https://foo.bar",
748        );
749        let mut fxa = FirefoxAccount::with_config(config);
750        let url = fxa
751            .begin_oauth_flow("", &[], "test_oauth_flow_url")
752            .unwrap();
753        let flow_url = Url::parse(&url).unwrap();
754        let params: HashMap<String, String> = flow_url.query_pairs().into_owned().collect();
755
756        assert!(!params.contains_key("scope"));
757    }
758
759    #[test]
760    fn test_oauth_flow_url() {
761        nss_as::ensure_initialized();
762        let config = Config::new_with_mock_well_known_fxa_client_configuration(
763            "https://mock-fxa.example.com",
764            "12345678",
765            "https://foo.bar",
766        );
767        let mut fxa = FirefoxAccount::with_config(config);
768        let url = fxa
769            .begin_oauth_flow("", &["profile"], "test_oauth_flow_url")
770            .unwrap();
771        let flow_url = Url::parse(&url).unwrap();
772
773        assert_eq!(flow_url.path(), "/authorization");
774
775        assert_eq!(flow_url.query_pairs().count(), 11);
776        let params: HashMap<String, String> = flow_url.query_pairs().into_owned().collect();
777        assert_eq!(params["action"], "email");
778        assert_eq!(params["response_type"], "code");
779        assert_eq!(params["entrypoint"], "test_oauth_flow_url");
780        assert_eq!(params["client_id"], "12345678");
781        assert_eq!(params["scope"], "profile");
782        assert_eq!(params["state"].len(), 22);
783        assert_eq!(params["code_challenge_method"], "S256");
784        assert_eq!(params["code_challenge"].len(), 43);
785        assert_eq!(params["access_type"], "offline");
786        assert_eq!(params["keys_jwk"].len(), 168);
787        assert_eq!(params["redirect_uri"], "https://foo.bar");
788    }
789
790    #[test]
791    fn test_force_auth_url() {
792        nss_as::ensure_initialized();
793        let config = Config::stable_dev("12345678", "https://foo.bar");
794        let mut fxa = FirefoxAccount::with_config(config);
795        let email = "test@example.com";
796        fxa.add_cached_profile("123", email);
797        let url = fxa
798            .begin_oauth_flow("", &["profile"], "test_force_auth_url")
799            .unwrap();
800        let url = Url::parse(&url).unwrap();
801        assert_eq!(url.path(), "/oauth/force_auth");
802        let mut pairs = url.query_pairs();
803        assert_eq!(
804            pairs.find(|e| e.0 == "email"),
805            Some((Cow::Borrowed("email"), Cow::Borrowed(email),))
806        );
807    }
808
809    #[test]
810    fn test_webchannel_context_url() {
811        nss_as::ensure_initialized();
812        const SCOPES: &[&str] = &["https://identity.mozilla.com/apps/oldsync"];
813        let config = Config::new_with_mock_well_known_fxa_client_configuration(
814            "https://mock-fxa.example.com",
815            "12345678",
816            "urn:ietf:wg:oauth:2.0:oob:oauth-redirect-webchannel",
817        );
818        let mut fxa = FirefoxAccount::with_config(config);
819        let url = fxa
820            .begin_oauth_flow("", SCOPES, "test_webchannel_context_url")
821            .unwrap();
822        let url = Url::parse(&url).unwrap();
823        let query_params: HashMap<_, _> = url.query_pairs().into_owned().collect();
824        let context = &query_params["context"];
825        assert_eq!(context, "oauth_webchannel_v1");
826        assert_eq!(query_params.get("redirect_uri"), None);
827    }
828
829    #[test]
830    fn test_webchannel_pairing_context_url() {
831        nss_as::ensure_initialized();
832        const SCOPES: &[&str] = &["https://identity.mozilla.com/apps/oldsync"];
833        const PAIRING_URL: &str = "https://accounts.firefox.com/pair#channel_id=658db7fe98b249a5897b884f98fb31b7&channel_key=1hIDzTj5oY2HDeSg_jA2DhcOcAn5Uqq0cAYlZRNUIo4";
834
835        let config = Config::new(
836            "https://accounts.firefox.com",
837            "12345678",
838            "urn:ietf:wg:oauth:2.0:oob:oauth-redirect-webchannel",
839        );
840        let mut fxa = FirefoxAccount::with_config(config);
841        let url = fxa
842            .begin_pairing_flow(
843                PAIRING_URL,
844                "service",
845                SCOPES,
846                "test_webchannel_pairing_context_url",
847            )
848            .unwrap();
849        let url = Url::parse(&url).unwrap();
850        let query_params: HashMap<_, _> = url.query_pairs().into_owned().collect();
851        let context = &query_params["context"];
852        assert_eq!(context, "oauth_webchannel_v1");
853        assert_eq!(query_params.get("redirect_uri"), None);
854    }
855
856    #[test]
857    fn test_pairing_flow_url() {
858        nss_as::ensure_initialized();
859        const SCOPES: &[&str] = &["https://identity.mozilla.com/apps/oldsync"];
860        const PAIRING_URL: &str = "https://accounts.firefox.com/pair#channel_id=658db7fe98b249a5897b884f98fb31b7&channel_key=1hIDzTj5oY2HDeSg_jA2DhcOcAn5Uqq0cAYlZRNUIo4";
861        const EXPECTED_URL: &str = "https://accounts.firefox.com/pair/supp?client_id=12345678&redirect_uri=https%3A%2F%2Ffoo.bar&scope=https%3A%2F%2Fidentity.mozilla.com%2Fapps%2Foldsync&state=SmbAA_9EA5v1R2bgIPeWWw&code_challenge_method=S256&code_challenge=ZgHLPPJ8XYbXpo7VIb7wFw0yXlTa6MUOVfGiADt0JSM&access_type=offline&keys_jwk=eyJjcnYiOiJQLTI1NiIsImt0eSI6IkVDIiwieCI6Ing5LUltQjJveDM0LTV6c1VmbW5sNEp0Ti14elV2eFZlZXJHTFRXRV9BT0kiLCJ5IjoiNXBKbTB3WGQ4YXdHcm0zREl4T1pWMl9qdl9tZEx1TWlMb1RkZ1RucWJDZyJ9#channel_id=658db7fe98b249a5897b884f98fb31b7&channel_key=1hIDzTj5oY2HDeSg_jA2DhcOcAn5Uqq0cAYlZRNUIo4";
862
863        let config = Config::new(
864            "https://accounts.firefox.com",
865            "12345678",
866            "https://foo.bar",
867        );
868
869        let mut fxa = FirefoxAccount::with_config(config);
870        let url = fxa
871            .begin_pairing_flow(PAIRING_URL, "", SCOPES, "test_pairing_flow_url")
872            .unwrap();
873        let flow_url = Url::parse(&url).unwrap();
874        let expected_parsed_url = Url::parse(EXPECTED_URL).unwrap();
875
876        assert_eq!(flow_url.host_str(), Some("accounts.firefox.com"));
877        assert_eq!(flow_url.path(), "/pair/supp");
878        assert_eq!(flow_url.fragment(), expected_parsed_url.fragment());
879
880        assert_eq!(flow_url.query_pairs().count(), 9);
881        let params: HashMap<String, String> = flow_url.query_pairs().into_owned().collect();
882        assert_eq!(params["entrypoint"], "test_pairing_flow_url");
883        assert_eq!(params["client_id"], "12345678");
884        assert_eq!(params["scope"], "https://identity.mozilla.com/apps/oldsync");
885        assert_eq!(params["state"].len(), 22);
886        assert_eq!(params["code_challenge_method"], "S256");
887        assert_eq!(params["code_challenge"].len(), 43);
888        assert_eq!(params["access_type"], "offline");
889        assert_eq!(params["keys_jwk"].len(), 168);
890        assert_eq!(params["redirect_uri"], "https://foo.bar");
891    }
892
893    #[test]
894    fn test_pairing_flow_origin_mismatch() {
895        nss_as::ensure_initialized();
896        static PAIRING_URL: &str = "https://bad.origin.com/pair#channel_id=foo&channel_key=bar";
897        let config = Config::stable_dev("12345678", "https://foo.bar");
898        let mut fxa = FirefoxAccount::with_config(config);
899        let url = fxa.begin_pairing_flow(
900            PAIRING_URL,
901            "service",
902            &["https://identity.mozilla.com/apps/oldsync"],
903            "test_pairiong_flow_origin_mismatch",
904        );
905
906        assert!(url.is_err());
907
908        match url {
909            Ok(_) => {
910                panic!("should have error");
911            }
912            Err(err) => match err {
913                Error::OriginMismatch { .. } => {}
914                _ => panic!("error not OriginMismatch"),
915            },
916        }
917    }
918
919    #[test]
920    fn test_check_authorization_status() {
921        nss_as::ensure_initialized();
922        let config = Config::stable_dev("12345678", "https://foo.bar");
923        let mut fxa = FirefoxAccount::with_config(config);
924
925        let refresh_token_scopes = std::collections::HashSet::new();
926        fxa.state.force_refresh_token(RefreshToken {
927            token: "refresh_token".to_owned(),
928            scopes: refresh_token_scopes,
929        });
930        fxa.state.force_session_token("test-session-token");
931
932        let mut client = MockFxAClient::new();
933        client
934            .expect_check_refresh_token_status()
935            .with(always(), eq("refresh_token"))
936            .times(1)
937            .returning(|_, _| Ok(IntrospectResponse { active: true }));
938        fxa.set_client(Arc::new(client));
939
940        assert_eq!(fxa.check_authorization_status(), AuthorizationStatus::Valid);
941    }
942
943    #[test]
944    fn test_check_authorization_status_circuit_breaker() {
945        nss_as::ensure_initialized();
946        let config = Config::stable_dev("12345678", "https://foo.bar");
947        let mut fxa = FirefoxAccount::with_config(config);
948
949        let refresh_token_scopes = std::collections::HashSet::new();
950        fxa.state.force_refresh_token(RefreshToken {
951            token: "refresh_token".to_owned(),
952            scopes: refresh_token_scopes,
953        });
954        fxa.state.force_session_token("test-session-token");
955
956        let mut client = MockFxAClient::new();
957        // This copy-pasta (equivalent to `.returns(..).times(5)`) is there
958        // because `Error` is not cloneable :/
959        client
960            .expect_check_refresh_token_status()
961            .with(always(), eq("refresh_token"))
962            .returning(|_, _| Ok(IntrospectResponse { active: true }));
963        client
964            .expect_check_refresh_token_status()
965            .with(always(), eq("refresh_token"))
966            .returning(|_, _| Ok(IntrospectResponse { active: true }));
967        client
968            .expect_check_refresh_token_status()
969            .with(always(), eq("refresh_token"))
970            .returning(|_, _| Ok(IntrospectResponse { active: true }));
971        client
972            .expect_check_refresh_token_status()
973            .with(always(), eq("refresh_token"))
974            .returning(|_, _| Ok(IntrospectResponse { active: true }));
975        client
976            .expect_check_refresh_token_status()
977            .with(always(), eq("refresh_token"))
978            .returning(|_, _| Ok(IntrospectResponse { active: true }));
979        //mockall expects calls to be processed in the order they are registered. So, no need for to use a method like expect_check_refresh_token_status_calls_in_order()
980        fxa.set_client(Arc::new(client));
981
982        for _ in 0..5 {
983            assert_eq!(fxa.check_authorization_status(), AuthorizationStatus::Valid)
984        }
985        // After the circuit breaker trips, the check_authorization_status() should return an
986        // inconclusive result
987        assert_eq!(
988            fxa.check_authorization_status(),
989            AuthorizationStatus::Unknown
990        );
991
992        // A tripped circuit breaker is inconclusive and must not move us to AuthIssues.
993        fxa.device_config = Some(crate::DeviceConfig {
994            name: "test".to_owned(),
995            device_type: crate::DeviceType::Mobile,
996            capabilities: vec![],
997        });
998        fxa.auth_state = crate::FxaState::Connected;
999        let state = fxa
1000            .process_event(crate::FxaEvent::CheckAuthorizationStatus)
1001            .unwrap();
1002        assert_eq!(state, crate::FxaState::Connected);
1003    }
1004
1005    use crate::internal::scopes::{self, OLD_SYNC};
1006
1007    #[test]
1008    fn test_auth_code_pair_valid_not_allowed_scope() {
1009        nss_as::ensure_initialized();
1010        let config = Config::stable_dev("12345678", "https://foo.bar");
1011        let mut fxa = FirefoxAccount::with_config(config);
1012        fxa.set_session_token("session");
1013        let mut client = MockFxAClient::new();
1014        let not_allowed_scope = "https://identity.mozilla.com/apps/lockbox";
1015        let expected_scopes = scopes::OLD_SYNC
1016            .chars()
1017            .chain(std::iter::once(' '))
1018            .chain(not_allowed_scope.chars())
1019            .collect::<String>();
1020        client
1021            .expect_get_scoped_key_data()
1022            .with(always(), eq("session"), eq("12345678"), eq(expected_scopes))
1023            .times(1)
1024            .returning(|_, _, _, _| {
1025                Err(Error::RemoteError {
1026                    code: 400,
1027                    errno: 163,
1028                    error: "Invalid Scopes".to_string(),
1029                    message: "Not allowed to request scopes".to_string(),
1030                    info: "fyi, there was a server error".to_string(),
1031                })
1032            });
1033        fxa.set_client(Arc::new(client));
1034        let auth_params = AuthorizationParameters {
1035            client_id: "12345678".to_string(),
1036            scope: vec![scopes::OLD_SYNC.to_string(), not_allowed_scope.to_string()],
1037            state: "somestate".to_string(),
1038            access_type: "offline".to_string(),
1039            code_challenge: None,
1040            code_challenge_method: None,
1041            keys_jwk: None,
1042        };
1043        let res = fxa.authorize_code_using_session_token(auth_params);
1044        assert!(res.is_err());
1045        let err = res.unwrap_err();
1046        if let Error::RemoteError {
1047            code,
1048            errno,
1049            error: _,
1050            message: _,
1051            info: _,
1052        } = err
1053        {
1054            assert_eq!(code, 400);
1055            assert_eq!(errno, 163); // Requested scopes not allowed
1056        } else {
1057            panic!("Should return an error from the server specifying that the requested scopes are not allowed");
1058        }
1059    }
1060
1061    #[test]
1062    fn test_auth_code_pair_invalid_scope_not_allowed() {
1063        nss_as::ensure_initialized();
1064        let config = Config::stable_dev("12345678", "https://foo.bar");
1065        let mut fxa = FirefoxAccount::with_config(config);
1066        fxa.set_session_token("session");
1067        let mut client = MockFxAClient::new();
1068        let invalid_scope = "IamAnInvalidScope";
1069        let expected_scopes = scopes::OLD_SYNC
1070            .chars()
1071            .chain(std::iter::once(' '))
1072            .chain(invalid_scope.chars())
1073            .collect::<String>();
1074        client
1075            .expect_get_scoped_key_data()
1076            .with(always(), eq("session"), eq("12345678"), eq(expected_scopes))
1077            .times(1)
1078            .returning(|_, _, _, _| {
1079                let mut server_ret = HashMap::new();
1080                server_ret.insert(
1081                    scopes::OLD_SYNC.to_string(),
1082                    ScopedKeyDataResponse {
1083                        key_rotation_secret: "IamASecret".to_string(),
1084                        key_rotation_timestamp: 100,
1085                        identifier: "".to_string(),
1086                    },
1087                );
1088                Ok(server_ret)
1089            });
1090        fxa.set_client(Arc::new(client));
1091
1092        let auth_params = AuthorizationParameters {
1093            client_id: "12345678".to_string(),
1094            scope: vec![scopes::OLD_SYNC.to_string(), invalid_scope.to_string()],
1095            state: "somestate".to_string(),
1096            access_type: "offline".to_string(),
1097            code_challenge: None,
1098            code_challenge_method: None,
1099            keys_jwk: None,
1100        };
1101        let res = fxa.authorize_code_using_session_token(auth_params);
1102        assert!(res.is_err());
1103        let err = res.unwrap_err();
1104        if let Error::ScopeNotAllowed(client_id, scope) = err {
1105            assert_eq!(client_id, "12345678");
1106            assert_eq!(scope, "IamAnInvalidScope");
1107        } else {
1108            panic!("Should return an error that specifies the scope that is not allowed");
1109        }
1110    }
1111
1112    #[test]
1113    fn test_auth_code_pair_scope_not_in_state() {
1114        nss_as::ensure_initialized();
1115        let config = Config::stable_dev("12345678", "https://foo.bar");
1116        let mut fxa = FirefoxAccount::with_config(config);
1117        fxa.set_session_token("session");
1118        let mut client = MockFxAClient::new();
1119        client
1120            .expect_get_scoped_key_data()
1121            .with(
1122                always(),
1123                eq("session"),
1124                eq("12345678"),
1125                eq(scopes::OLD_SYNC),
1126            )
1127            .times(1)
1128            .returning(|_, _, _, _| {
1129                let mut server_ret = HashMap::new();
1130                server_ret.insert(
1131                    scopes::OLD_SYNC.to_string(),
1132                    ScopedKeyDataResponse {
1133                        key_rotation_secret: "IamASecret".to_string(),
1134                        key_rotation_timestamp: 100,
1135                        identifier: "".to_string(),
1136                    },
1137                );
1138                Ok(server_ret)
1139            });
1140        fxa.set_client(Arc::new(client));
1141        let auth_params = AuthorizationParameters {
1142            client_id: "12345678".to_string(),
1143            scope: vec![scopes::OLD_SYNC.to_string()],
1144            state: "somestate".to_string(),
1145            access_type: "offline".to_string(),
1146            code_challenge: None,
1147            code_challenge_method: None,
1148            keys_jwk: Some("IAmAVerySecretKeysJWkInBase64".to_string()),
1149        };
1150        let res = fxa.authorize_code_using_session_token(auth_params);
1151        assert!(res.is_err());
1152        let err = res.unwrap_err();
1153        if let Error::NoScopedKey(scope) = err {
1154            assert_eq!(scope, scopes::OLD_SYNC.to_string());
1155        } else {
1156            panic!("Should return an error that specifies the scope that is not in the state");
1157        }
1158    }
1159
1160    #[test]
1161    fn test_handle_web_channel_login_sets_session_token() {
1162        nss_as::ensure_initialized();
1163        let config = Config::stable_dev("12345678", "https://foo.bar");
1164        let mut fxa = FirefoxAccount::with_config(config);
1165        fxa.handle_web_channel_login(
1166            r#"{"sessionToken":"mock_session_token","uid":"mock_uid","email":"mock@example.com","verified":true}"#,
1167        )
1168        .unwrap();
1169        assert_eq!(fxa.get_session_token().unwrap(), "mock_session_token");
1170    }
1171
1172    #[test]
1173    fn test_oauth_request_sent_with_session_when_available() {
1174        nss_as::ensure_initialized();
1175        let config = Config::new_with_mock_well_known_fxa_client_configuration(
1176            "mock-fxa.example.com",
1177            "12345678",
1178            "https://foo.bar",
1179        );
1180        let mut fxa = FirefoxAccount::with_config(config);
1181        let url = fxa
1182            .begin_oauth_flow("", &[OLD_SYNC, "profile"], "test_entrypoint")
1183            .unwrap();
1184        let url = Url::parse(&url).unwrap();
1185        let state = url.query_pairs().find(|(name, _)| name == "state").unwrap();
1186        let mut client = MockFxAClient::new();
1187
1188        client
1189            .expect_create_refresh_token_using_authorization_code()
1190            .withf(|_, session_token, code, _| {
1191                matches!(session_token, Some("mock_session_token")) && code == "mock_code"
1192            })
1193            .times(1)
1194            .returning(|_, _, _, _| {
1195                Ok(OAuthTokenResponse {
1196                    keys_jwe: None,
1197                    refresh_token: Some("refresh_token".to_string()),
1198                    session_token: None,
1199                    expires_in: 1,
1200                    scope: "profile".to_string(),
1201                    access_token: "access_token".to_string(),
1202                })
1203            });
1204        client
1205            .expect_destroy_access_token()
1206            .with(always(), always())
1207            .times(1)
1208            .returning(|_, _| Ok(()));
1209        fxa.set_client(Arc::new(client));
1210        fxa.set_session_token("mock_session_token");
1211
1212        fxa.complete_oauth_flow("mock_code", state.1.as_ref())
1213            .unwrap();
1214    }
1215
1216    fn make_mock_device(name: &str) -> GetDeviceResponse {
1217        use sync15::DeviceType;
1218        GetDeviceResponse {
1219            common: DeviceResponseCommon {
1220                id: "device1".into(),
1221                display_name: name.to_string(),
1222                device_type: DeviceType::Desktop,
1223                push_subscription: None,
1224                available_commands: HashMap::new(),
1225                push_endpoint_expired: false,
1226            },
1227            is_current_device: true,
1228            location: DeviceLocation {
1229                city: None,
1230                country: None,
1231                state: None,
1232                state_code: None,
1233            },
1234            last_access_time: None,
1235        }
1236    }
1237
1238    fn make_mock_update_device_response() -> UpdateDeviceResponse {
1239        use sync15::DeviceType;
1240        UpdateDeviceResponse {
1241            id: "device1".into(),
1242            display_name: "Test Device".to_string(),
1243            device_type: DeviceType::Desktop,
1244            push_subscription: None,
1245            available_commands: HashMap::new(),
1246            push_endpoint_expired: false,
1247        }
1248    }
1249
1250    // Test that when we complete an oauth flow while already having a refresh token with
1251    // different scopes, the new token is merged with the old scopes and the device is restored.
1252    #[test]
1253    fn test_complete_oauth_flow_merges_scopes_and_restores_device() {
1254        nss_as::ensure_initialized();
1255        let config = Config::new_with_mock_well_known_fxa_client_configuration(
1256            "mock-fxa.example.com",
1257            "12345678",
1258            "https://foo.bar",
1259        );
1260        let mut fxa = FirefoxAccount::with_config(config);
1261
1262        // Start a flow before setting state, to register the pending oauth flow.
1263        let url = fxa
1264            .begin_oauth_flow("", &["new_scope"], "test_entrypoint")
1265            .unwrap();
1266        let url = Url::parse(&url).unwrap();
1267        let state = url.query_pairs().find(|(name, _)| name == "state").unwrap();
1268
1269        // Pre-populate: existing refresh token (different scope) and a session token.
1270        fxa.state.force_refresh_token(RefreshToken {
1271            token: "old_refresh".to_string(),
1272            scopes: ["profile".to_string()].into(),
1273        });
1274        fxa.set_session_token("mock_session_token");
1275
1276        let mut client = MockFxAClient::new();
1277
1278        // 1. Exchange auth code — returns narrow token with only the new scope.
1279        client
1280            .expect_create_refresh_token_using_authorization_code()
1281            .times(1)
1282            .returning(|_, _, _, _| {
1283                Ok(OAuthTokenResponse {
1284                    keys_jwe: None,
1285                    refresh_token: Some("new_narrow_refresh".to_string()),
1286                    session_token: None,
1287                    expires_in: 3600,
1288                    scope: "new_scope".to_string(),
1289                    access_token: "access_token".to_string(),
1290                })
1291            });
1292
1293        // 2. Destroy the over-scoped access token.
1294        client
1295            .expect_destroy_access_token()
1296            .with(always(), always())
1297            .times(1)
1298            .returning(|_, _| Ok(()));
1299
1300        // 3. Fetch current device so it can be restored after token swap.
1301        client
1302            .expect_get_devices()
1303            .with(always(), eq("old_refresh"))
1304            .times(1)
1305            .returning(|_, _| Ok(vec![make_mock_device("Test Device")]));
1306
1307        // 4. Get merged refresh token covering both old and new scopes.
1308        client
1309            .expect_create_refresh_token_using_session_token()
1310            .withf(|_, session_token, _| session_token == "mock_session_token")
1311            .times(1)
1312            .returning(|_, _, _| {
1313                Ok(OAuthTokenResponse {
1314                    keys_jwe: None,
1315                    refresh_token: Some("merged_refresh".to_string()),
1316                    session_token: None,
1317                    expires_in: 3600,
1318                    scope: "profile new_scope".to_string(),
1319                    access_token: "access_token2".to_string(),
1320                })
1321            });
1322
1323        // 5. Destroy the narrow new token (replaced by the merged one).
1324        client
1325            .expect_destroy_refresh_token()
1326            .with(always(), eq("new_narrow_refresh"))
1327            .times(1)
1328            .returning(|_, _| Ok(()));
1329
1330        // 6. Destroy the old refresh token.
1331        client
1332            .expect_destroy_refresh_token()
1333            .with(always(), eq("old_refresh"))
1334            .times(1)
1335            .returning(|_, _| Ok(()));
1336
1337        // 7. Restore the device record using the new merged refresh token.
1338        client
1339            .expect_update_device_record()
1340            .times(1)
1341            .returning(|_, _, _| Ok(make_mock_update_device_response()));
1342
1343        fxa.set_client(Arc::new(client));
1344
1345        fxa.complete_oauth_flow("mock_code", state.1.as_ref())
1346            .unwrap();
1347
1348        let scopes = &fxa.state.refresh_token().unwrap().scopes;
1349        assert!(
1350            scopes.contains("profile"),
1351            "expected profile scope, got {scopes:?}"
1352        );
1353        assert!(
1354            scopes.contains("new_scope"),
1355            "expected new_scope, got {scopes:?}"
1356        );
1357        assert_eq!(scopes.len(), 2);
1358    }
1359
1360    // Test that when the new refresh token already covers all existing scopes, no merge
1361    // is performed (no extra token request), but the old token is still destroyed and
1362    // the device is restored.
1363    #[test]
1364    fn test_complete_oauth_flow_no_merge_when_scopes_match() {
1365        nss_as::ensure_initialized();
1366        let config = Config::new_with_mock_well_known_fxa_client_configuration(
1367            "mock-fxa.example.com",
1368            "12345678",
1369            "https://foo.bar",
1370        );
1371        let mut fxa = FirefoxAccount::with_config(config);
1372
1373        let url = fxa
1374            .begin_oauth_flow("", &["profile"], "test_entrypoint")
1375            .unwrap();
1376        let url = Url::parse(&url).unwrap();
1377        let state = url.query_pairs().find(|(name, _)| name == "state").unwrap();
1378
1379        fxa.state.force_refresh_token(RefreshToken {
1380            token: "old_refresh".to_string(),
1381            scopes: ["profile".to_string()].into(),
1382        });
1383        fxa.set_session_token("mock_session_token");
1384
1385        let mut client = MockFxAClient::new();
1386
1387        // 1. Exchange auth code — returns token with same scopes as before.
1388        client
1389            .expect_create_refresh_token_using_authorization_code()
1390            .times(1)
1391            .returning(|_, _, _, _| {
1392                Ok(OAuthTokenResponse {
1393                    keys_jwe: None,
1394                    refresh_token: Some("new_refresh".to_string()),
1395                    session_token: None,
1396                    expires_in: 3600,
1397                    scope: "profile".to_string(),
1398                    access_token: "access_token".to_string(),
1399                })
1400            });
1401
1402        // 2. Destroy the over-scoped access token.
1403        client
1404            .expect_destroy_access_token()
1405            .with(always(), always())
1406            .times(1)
1407            .returning(|_, _| Ok(()));
1408
1409        // 3. Fetch current device for restoration.
1410        client
1411            .expect_get_devices()
1412            .with(always(), eq("old_refresh"))
1413            .times(1)
1414            .returning(|_, _| Ok(vec![make_mock_device("Test Device")]));
1415
1416        // No create_refresh_token_using_session_token — scopes already match.
1417        // No destroy of the new token — it becomes our token directly.
1418
1419        // 4. Destroy only the old refresh token.
1420        client
1421            .expect_destroy_refresh_token()
1422            .with(always(), eq("old_refresh"))
1423            .times(1)
1424            .returning(|_, _| Ok(()));
1425
1426        // 5. Restore the device record.
1427        client
1428            .expect_update_device_record()
1429            .times(1)
1430            .returning(|_, _, _| Ok(make_mock_update_device_response()));
1431
1432        fxa.set_client(Arc::new(client));
1433
1434        fxa.complete_oauth_flow("mock_code", state.1.as_ref())
1435            .unwrap();
1436
1437        let scopes = &fxa.state.refresh_token().unwrap().scopes;
1438        assert_eq!(scopes, &["profile".to_string()].into());
1439    }
1440
1441    // Test that adding a non-sync scope to an account that is already signed in with sync
1442    // retains the sync scoped key we already hold, even though this response carries no keys.
1443    #[test]
1444    fn test_complete_oauth_flow_retains_existing_sync_key_when_adding_scope() {
1445        nss_as::ensure_initialized();
1446        let config = Config::new_with_mock_well_known_fxa_client_configuration(
1447            "mock-fxa.example.com",
1448            "12345678",
1449            "https://foo.bar",
1450        );
1451        let mut fxa = FirefoxAccount::with_config(config);
1452
1453        // Start a flow requesting only a new, non-sync scope.
1454        let url = fxa
1455            .begin_oauth_flow("", &["new_scope"], "test_entrypoint")
1456            .unwrap();
1457        let url = Url::parse(&url).unwrap();
1458        let state = url.query_pairs().find(|(name, _)| name == "state").unwrap();
1459
1460        // Pre-populate: signed in with the sync scope, holding its scoped key, plus a session
1461        // token so the scope merge can happen.
1462        fxa.state.force_refresh_token(RefreshToken {
1463            token: "old_refresh".to_string(),
1464            scopes: [OLD_SYNC.to_string()].into(),
1465        });
1466        fxa.state.insert_scoped_key(
1467            OLD_SYNC,
1468            crate::ScopedKey {
1469                kty: "oct".to_string(),
1470                scope: OLD_SYNC.to_string(),
1471                k: "existing_sync_key_material".to_string(),
1472                kid: "existing_sync_kid".to_string(),
1473            },
1474        );
1475        fxa.set_session_token("mock_session_token");
1476
1477        let mut client = MockFxAClient::new();
1478
1479        // 1. Exchange auth code — narrow token with only the new scope and no keys.
1480        client
1481            .expect_create_refresh_token_using_authorization_code()
1482            .times(1)
1483            .returning(|_, _, _, _| {
1484                Ok(OAuthTokenResponse {
1485                    keys_jwe: None,
1486                    refresh_token: Some("new_narrow_refresh".to_string()),
1487                    session_token: None,
1488                    expires_in: 3600,
1489                    scope: "new_scope".to_string(),
1490                    access_token: "access_token".to_string(),
1491                })
1492            });
1493
1494        // 2. Destroy the over-scoped access token.
1495        client
1496            .expect_destroy_access_token()
1497            .with(always(), always())
1498            .times(1)
1499            .returning(|_, _| Ok(()));
1500
1501        // 3. Fetch current device so it can be restored after the token swap.
1502        client
1503            .expect_get_devices()
1504            .with(always(), eq("old_refresh"))
1505            .times(1)
1506            .returning(|_, _| Ok(vec![make_mock_device("Test Device")]));
1507
1508        // 4. Get merged refresh token covering both the old sync scope and the new scope.
1509        client
1510            .expect_create_refresh_token_using_session_token()
1511            .withf(|_, session_token, _| session_token == "mock_session_token")
1512            .times(1)
1513            .returning(|_, _, _| {
1514                Ok(OAuthTokenResponse {
1515                    keys_jwe: None,
1516                    refresh_token: Some("merged_refresh".to_string()),
1517                    session_token: None,
1518                    expires_in: 3600,
1519                    scope: format!("{OLD_SYNC} new_scope"),
1520                    access_token: "access_token2".to_string(),
1521                })
1522            });
1523
1524        // 5. Destroy the narrow new token (replaced by the merged one).
1525        client
1526            .expect_destroy_refresh_token()
1527            .with(always(), eq("new_narrow_refresh"))
1528            .times(1)
1529            .returning(|_, _| Ok(()));
1530
1531        // 6. Destroy the old refresh token.
1532        client
1533            .expect_destroy_refresh_token()
1534            .with(always(), eq("old_refresh"))
1535            .times(1)
1536            .returning(|_, _| Ok(()));
1537
1538        // 7. Restore the device record.
1539        client
1540            .expect_update_device_record()
1541            .times(1)
1542            .returning(|_, _, _| Ok(make_mock_update_device_response()));
1543
1544        fxa.set_client(Arc::new(client));
1545
1546        fxa.complete_oauth_flow("mock_code", state.1.as_ref())
1547            .unwrap();
1548
1549        // The sync key we already held must survive, even though this flow carried no keys.
1550        let sync_key = fxa
1551            .state
1552            .get_scoped_key(OLD_SYNC)
1553            .expect("sync scoped key should be retained");
1554        assert_eq!(sync_key.k, "existing_sync_key_material");
1555
1556        // And the merged refresh token should carry both scopes.
1557        let scopes = &fxa.state.refresh_token().unwrap().scopes;
1558        assert!(
1559            scopes.contains(OLD_SYNC),
1560            "expected sync scope, got {scopes:?}"
1561        );
1562        assert!(
1563            scopes.contains("new_scope"),
1564            "expected new_scope, got {scopes:?}"
1565        );
1566        assert_eq!(scopes.len(), 2);
1567    }
1568}