fxa_client/
auth.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
5//! # Signing in and out
6//!
7//! Signing in and out is driven through the state machine: by sending the relevant
8//! [`FxaEvent`] to [`FirefoxAccount::process_event`].
9//!
10//! The Firefox Accounts system supports two methods for connecting an application
11//! to a user's account:
12//!
13//!    - A traditional OAuth flow, where the user is directed to a webpage to enter
14//!      their account credentials and then redirected back to the application.
15//!      This is driven by the [`FxaEvent::BeginOAuthFlow`] and
16//!      [`FxaEvent::CompleteOAuthFlow`] events.
17//!
18//!    - A device pairing flow, where the user scans a QRCode presented by another
19//!      app that is already connected to the account, which then directs them to
20//!      a webpage for a simplified signing flow. This is driven by the
21//!      [`FxaEvent::BeginPairingFlow`] event.
22//!
23//! Technical details of the pairing flow can be found in the [Firefox Accounts
24//! documentation hub](https://mozilla.github.io/ecosystem-platform/docs/features/firefox-accounts/pairing).
25
26use crate::{ApiResult, DeviceConfig, Error, FirefoxAccount};
27use error_support::handle_error;
28
29#[uniffi::export]
30impl FirefoxAccount {
31    /// Get the current state
32    pub fn get_state(&self) -> FxaState {
33        self.internal.lock().get_state()
34    }
35
36    /// Process an event (login, logout, etc).
37    ///
38    /// On success, returns the new state.
39    /// On error, the state will remain the same.
40    #[handle_error(Error)]
41    pub fn process_event(&self, event: FxaEvent) -> ApiResult<FxaState> {
42        self.internal.lock().process_event(event)
43    }
44
45    /// Stores the session token from a WebChannel login JSON payload without exposing it
46    /// to the browser layer.
47    ///
48    /// The `json_payload` is the `data` object from the `fxaccounts:login` WebChannel
49    /// command. The session token is extracted and stored internally; callers never hold
50    /// the raw token value.
51    ///
52    /// **💾 This method alters the persisted account state.**
53    #[handle_error(Error)]
54    pub fn handle_web_channel_login(&self, json_payload: String) -> ApiResult<()> {
55        self.internal.lock().handle_web_channel_login(&json_payload)
56    }
57
58    /// Get the URL at which to begin a device-pairing signin flow.
59    ///
60    /// If the user wants to sign in using device pairing, call this method and then
61    /// direct them to visit the resulting URL on an already-signed-in device. Doing
62    /// so will trigger the other device to show a QR code to be scanned, and the result
63    /// from said QR code can be passed to the [`FxaEvent::BeginPairingFlow`] event.
64    #[handle_error(Error)]
65    pub fn get_pairing_authority_url(&self) -> ApiResult<String> {
66        self.internal.lock().get_pairing_authority_url()
67    }
68
69    /// Check authorization status for this application.
70    ///
71    /// **💾 This method alters the persisted account state.**
72    ///
73    /// Call this method to validate the current auth tokens. This checks that all expected tokens
74    /// are present and also validates the refresh token with the FxA server.
75    pub fn check_authorization_status(&self) -> AuthorizationStatus {
76        self.internal.lock().check_authorization_status()
77    }
78
79    /// Disconnect from the user's account.
80    ///
81    /// **💾 This method alters the persisted account state.**
82    ///
83    /// This method destroys any tokens held by the client, effectively disconnecting
84    /// from the user's account. Applications should call this when the user opts to
85    /// sign out.
86    ///
87    /// The persisted account state after calling this method will contain only the
88    /// user's last-seen profile information, if any. This may be useful in helping
89    /// the user to reconnect to their account. If reconnecting to the same account
90    /// is not desired then the application should discard the persisted account state.
91    pub fn disconnect(&self) {
92        self.internal.lock().disconnect()
93    }
94
95    /// Update the state based on authentication issues.
96    ///
97    /// **💾 This method alters the persisted account state.**
98    ///
99    /// Call this if you know there's an authentication / authorization issue that requires the
100    /// user to re-authenticated.  It transitions the user to the [FxaState.AuthIssues] state.
101    pub fn on_auth_issues(&self) {
102        self.internal.lock().on_auth_issues()
103    }
104
105    /// Used by the application to test auth token issues
106    pub fn simulate_temporary_auth_token_issue(&self) {
107        self.internal.lock().simulate_temporary_auth_token_issue()
108    }
109
110    /// Used by the application to test auth token issues
111    pub fn simulate_permanent_auth_token_issue(&self) {
112        self.internal.lock().simulate_permanent_auth_token_issue()
113    }
114}
115
116#[derive(uniffi::Enum, PartialEq, Eq, Debug)]
117/// Result of the `check_authorization_status()` method.
118pub enum AuthorizationStatus {
119    Valid,
120    Invalid,
121    /// The request failed, we don't know if the refresh token is good or bad
122    Unknown,
123}
124
125#[derive(uniffi::Enum, Clone, Debug, PartialEq, Eq)]
126/// Fxa state
127///
128/// These are the states of [crate::FxaStateMachine] that consumers observe.
129pub enum FxaState {
130    /// The state machine needs to be initialized via [Event::Initialize].
131    Uninitialized,
132    /// User has not connected to FxA or has logged out
133    Disconnected,
134    /// User is currently performing an OAuth flow.
135    ///
136    /// Initial state is what we transition to if the flow is cancelled or fails.
137    Authenticating {
138        oauth_url: String,
139        initial_state: Box<FxaState>,
140    },
141    /// User is currently connected to FxA
142    Connected,
143    /// User was connected to FxA, but we observed issues with the auth tokens.
144    /// The user needs to reauthenticate before the account can be used.
145    AuthIssues,
146}
147
148#[derive(uniffi::Enum, Clone, Debug, PartialEq, Eq)]
149/// Fxa event
150///
151/// These are the events that consumers send to [crate::FxaStateMachine::process_event]
152pub enum FxaEvent {
153    /// Initialize the state machine.  This must be the first event sent.
154    Initialize { device_config: DeviceConfig },
155    /// Begin an oauth flow
156    ///
157    /// If successful, the state machine will transition the [FxaState::Authenticating].  The next
158    /// step is to navigate the user to the `oauth_url` and let them sign and authorize the client.
159    ///
160    /// This event is valid for the `Disconnected`, `AuthIssues`, and `Authenticating` states.  If
161    /// the state machine is in the `Authenticating` state, then this will forget the current OAuth
162    /// flow and start a new one.
163    BeginOAuthFlow {
164        service: String,
165        scopes: Vec<String>,
166        entrypoint: String,
167    },
168    /// Begin an oauth flow using a URL from a pairing code
169    ///
170    /// If successful, the state machine will transition the [FxaState::Authenticating].  The next
171    /// step is to navigate the user to the `oauth_url` and let them sign and authorize the client.
172    ///
173    /// This event is valid for the `Disconnected`, `AuthIssues`, and `Authenticating` states.  If
174    /// the state machine is in the `Authenticating` state, then this will forget the current OAuth
175    /// flow and start a new one.
176    BeginPairingFlow {
177        pairing_url: String,
178        service: String,
179        scopes: Vec<String>,
180        entrypoint: String,
181    },
182    /// Complete an OAuth flow.
183    ///
184    /// Send this event after the user has navigated through the OAuth flow and has reached the
185    /// redirect URI.  Extract `code` and `state` from the query parameters or web channel.  If
186    /// successful the state machine will transition to [FxaState::Connected].
187    ///
188    /// This event is valid for the `Authenticating` state.
189    CompleteOAuthFlow { code: String, state: String },
190    /// Cancel an OAuth flow.
191    ///
192    /// Use this to cancel an in-progress OAuth, returning to [FxaState::Disconnected] so the
193    /// process can begin again.
194    ///
195    /// This event is valid for the `Authenticating` state.
196    CancelOAuthFlow,
197    /// Check the authorization status for a connected account.
198    ///
199    /// This event is only valid for the `Connected` state.  In other states, this event is ignored.
200    ///
201    /// Send this when issues are detected with the auth tokens for a connected account.  It will
202    /// double check for authentication issues with the account.  If it detects them, the state
203    /// machine will transition to [FxaState::AuthIssues].  From there you can start an OAuth flow
204    /// again to re-connect the user.
205    ///
206    /// If the request fails, for example from a network error, then the user will stay in the
207    /// current state.
208    CheckAuthorizationStatus,
209    /// An `fxaccounts:change_password` WebChannel message arrived on the device that just changed
210    /// its password. `json_payload` is the `data` object of that message and contains the new
211    /// session token. The state machine swaps the session token for a new refresh token and
212    /// re-initialises the device record.
213    ///
214    /// This event is valid for the `Connected` and `AuthIssues` states. In `Authenticating` it
215    /// is a no-op so the in-progress OAuth flow is not disrupted.
216    WebChannelPasswordChange { json_payload: String },
217    /// Disconnect the user
218    ///
219    /// Send this when the user is asking to be logged out.  The state machine will transition to
220    /// [FxaState::Disconnected].
221    ///
222    /// This event is valid for the `Connected` state.
223    Disconnect,
224    /// Force a call to [FirefoxAccount::get_profile]
225    ///
226    /// This is used for testing the auth/network retry code, since it hits the network and
227    /// requires and auth token.
228    ///
229    /// This event is valid for the `Connected` state.
230    CallGetProfile,
231}