1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use crate::{error::*, scoped_keys::ScopedKey, scopes, FirefoxAccount};
use ffi_support::IntoFfi;
use serde_derive::*;
use std::time::Instant;

// Values to pass back to calling code over the FFI.

#[derive(Serialize, Deserialize, PartialEq, Debug, Clone, Default)]
pub struct FxAMigrationResult {
    pub total_duration: u128,
}

pub enum MigrationState {
    // No in-flight migration.
    None,
    // An in-flight migration that will copy the sessionToken.
    CopySessionToken,
    // An in-flight migration that will re-use the sessionToken.
    ReuseSessionToken,
}

unsafe impl IntoFfi for MigrationState {
    type Value = u8;
    fn ffi_default() -> u8 {
        0
    }
    fn into_ffi_value(self) -> u8 {
        match self {
            MigrationState::None => 0,
            MigrationState::CopySessionToken => 1,
            MigrationState::ReuseSessionToken => 2,
        }
    }
}

// Migration-related data that we may need to serialize in the persisted account state.

#[derive(Clone, Serialize, Deserialize)]
pub struct MigrationData {
    k_xcs: String,
    k_sync: String,
    copy_session_token: bool,
    session_token: String,
}

impl FirefoxAccount {
    /// Migrate from a logged-in with a sessionToken Firefox Account.
    ///
    /// * `session_token` - Hex-formatted session token.
    /// * `k_xcs` - Hex-formatted kXCS.
    /// * `k_sync` - Hex-formatted kSync.
    /// * `copy_session_token` - If true then the provided 'session_token' will be duplicated
    ///     and the resulting session will use a new session token. If false, the provided
    ///     token will be reused.
    ///
    /// This method remembers the provided token details and may persist them in the
    /// account state if it encounters a temporary failure such as a network error.
    /// Calling code is expected to store the updated state even if an error is thrown.
    ///
    /// **💾 This method alters the persisted account state.**
    pub fn migrate_from_session_token(
        &mut self,
        session_token: &str,
        k_sync: &str,
        k_xcs: &str,
        copy_session_token: bool,
    ) -> Result<FxAMigrationResult> {
        // if there is already a session token on account, we error out.
        if self.state.session_token.is_some() {
            return Err(ErrorKind::IllegalState("Session Token is already set.").into());
        }

        self.state.in_flight_migration = Some(MigrationData {
            k_sync: k_sync.to_string(),
            k_xcs: k_xcs.to_string(),
            copy_session_token,
            session_token: session_token.to_string(),
        });

        self.try_migration()
    }

    /// Check if the client is in a pending migration state
    pub fn is_in_migration_state(&self) -> MigrationState {
        match self.state.in_flight_migration {
            None => MigrationState::None,
            Some(MigrationData {
                copy_session_token: true,
                ..
            }) => MigrationState::CopySessionToken,
            Some(MigrationData {
                copy_session_token: false,
                ..
            }) => MigrationState::ReuseSessionToken,
        }
    }

    pub fn try_migration(&mut self) -> Result<FxAMigrationResult> {
        let import_start = Instant::now();

        match self.network_migration() {
            Ok(_) => {}
            Err(err) => {
                match err.kind() {
                    ErrorKind::RemoteError {
                        code: 500..=599, ..
                    }
                    | ErrorKind::RemoteError { code: 429, .. }
                    | ErrorKind::RequestError(_) => {
                        // network errors that will allow hopefully migrate later
                        log::warn!("Network error: {:?}", err);
                        return Err(err);
                    }
                    _ => {
                        // probably will not recover

                        self.state.in_flight_migration = None;

                        return Err(err);
                    }
                };
            }
        }

        self.state.in_flight_migration = None;

        let metrics = FxAMigrationResult {
            total_duration: import_start.elapsed().as_millis(),
        };

        Ok(metrics)
    }

    fn network_migration(&mut self) -> Result<()> {
        let migration_data = match self.state.in_flight_migration {
            Some(ref data) => data.clone(),
            None => {
                return Err(ErrorKind::NoMigrationData.into());
            }
        };

        // If we need to copy the sessionToken, do that first so we can use it
        // for subsequent requests. TODO: we should store the duplicated token
        // in the account state in case we fail in later steps, but need to remember
        // the original value of `copy_session_token` if we do so.
        let migration_session_token = if migration_data.copy_session_token {
            let duplicate_session = self
                .client
                .duplicate_session(&self.state.config, &migration_data.session_token)?;

            duplicate_session.session_token
        } else {
            migration_data.session_token.to_string()
        };

        // Synthesize a scoped key from our kSync.
        // Do this before creating OAuth tokens because it doesn't have any side-effects,
        // so it's low-consequence if we fail in later steps.
        let k_sync = hex::decode(&migration_data.k_sync)?;
        let k_sync = base64::encode_config(&k_sync, base64::URL_SAFE_NO_PAD);
        let k_xcs = hex::decode(&migration_data.k_xcs)?;
        let k_xcs = base64::encode_config(&k_xcs, base64::URL_SAFE_NO_PAD);
        let scoped_key_data = self.client.scoped_key_data(
            &self.state.config,
            &migration_session_token,
            &self.state.config.client_id,
            scopes::OLD_SYNC,
        )?;
        let oldsync_key_data = scoped_key_data.get(scopes::OLD_SYNC).ok_or_else(|| {
            ErrorKind::IllegalState("The session token doesn't have access to kSync!")
        })?;
        let kid = format!("{}-{}", oldsync_key_data.key_rotation_timestamp, k_xcs);
        let k_sync_scoped_key = ScopedKey {
            kty: "oct".to_string(),
            scope: scopes::OLD_SYNC.to_string(),
            k: k_sync,
            kid,
        };

        // Trade our session token for a refresh token.
        let oauth_response = self.client.refresh_token_with_session_token(
            &self.state.config,
            &migration_session_token,
            &[scopes::PROFILE, scopes::OLD_SYNC],
        )?;

        // Store the new tokens in the account state.
        // We do this all at one at the end to avoid leaving partial state.
        self.state.session_token = Some(migration_session_token);
        self.handle_oauth_response(oauth_response, None)?;
        self.state
            .scoped_keys
            .insert(scopes::OLD_SYNC.to_string(), k_sync_scoped_key);

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{http_client::*, Config};
    use std::collections::HashMap;
    use std::sync::Arc;

    fn setup() -> FirefoxAccount {
        // I'd love to be able to configure a single mocked client here,
        // but can't work out how to do that within the typesystem.
        let config = Config::stable_dev("12345678", "https://foo.bar");
        FirefoxAccount::with_config(config)
    }

    #[test]
    fn test_migration_can_retry_after_network_errors() {
        let mut fxa = setup();

        assert!(matches!(fxa.is_in_migration_state(), MigrationState::None));

        // Initial attempt fails with a server-side failure, which we can retry.
        let mut client = FxAClientMock::new();
        client
            .expect_duplicate_session(mockiato::Argument::any, |arg| arg.partial_eq("session"))
            .returns_once(Err(ErrorKind::RemoteError {
                code: 500,
                errno: 999,
                error: "server error".to_string(),
                message: "there was a server error".to_string(),
                info: "fyi, there was a server error".to_string(),
            }
            .into()));
        fxa.set_client(Arc::new(client));

        let err = fxa
            .migrate_from_session_token("session", "aabbcc", "ddeeff", true)
            .unwrap_err();
        assert!(matches!(err.kind(), ErrorKind::RemoteError { code: 500, .. }));
        assert!(matches!(
            fxa.is_in_migration_state(),
            MigrationState::CopySessionToken
        ));

        // Retrying can succeed.
        // It makes a lot of network requests, so we have a lot to mock!
        let mut client = FxAClientMock::new();
        client
            .expect_duplicate_session(mockiato::Argument::any, |arg| arg.partial_eq("session"))
            .returns_once(Ok(DuplicateTokenResponse {
                uid: "userid".to_string(),
                session_token: "dup_session".to_string(),
                verified: true,
                auth_at: 12345,
            }));
        let mut key_data = HashMap::new();
        key_data.insert(
            scopes::OLD_SYNC.to_string(),
            ScopedKeyDataResponse {
                identifier: scopes::OLD_SYNC.to_string(),
                key_rotation_secret: "00000000000000000000000000000000".to_string(),
                key_rotation_timestamp: 12345,
            },
        );
        client
            .expect_scoped_key_data(
                mockiato::Argument::any,
                |arg| arg.partial_eq("dup_session"),
                |arg| arg.partial_eq("12345678"),
                |arg| arg.partial_eq(scopes::OLD_SYNC),
            )
            .returns_once(Ok(key_data));
        client
            .expect_refresh_token_with_session_token(
                mockiato::Argument::any,
                |arg| arg.partial_eq("dup_session"),
                |arg| arg.unordered_vec_eq([scopes::PROFILE, scopes::OLD_SYNC].to_vec()),
            )
            .returns_once(Ok(OAuthTokenResponse {
                keys_jwe: None,
                refresh_token: Some("refresh".to_string()),
                session_token: None,
                expires_in: 12345,
                scope: "profile oldsync".to_string(),
                access_token: "access".to_string(),
            }));
        client
            .expect_destroy_access_token(mockiato::Argument::any, |arg| arg.partial_eq("access"))
            .returns_once(Ok(()));
        fxa.set_client(Arc::new(client));

        fxa.try_migration().unwrap();
        assert!(matches!(fxa.is_in_migration_state(), MigrationState::None));
    }

    #[test]
    fn test_migration_cannot_retry_after_other_errors() {
        let mut fxa = setup();

        assert!(matches!(fxa.is_in_migration_state(), MigrationState::None));

        let mut client = FxAClientMock::new();
        client
            .expect_duplicate_session(mockiato::Argument::any, |arg| arg.partial_eq("session"))
            .returns_once(Err(ErrorKind::RemoteError {
                code: 400,
                errno: 102,
                error: "invalid token".to_string(),
                message: "the token was invalid".to_string(),
                info: "fyi, the provided token was invalid".to_string(),
            }
            .into()));
        fxa.set_client(Arc::new(client));

        let err = fxa
            .migrate_from_session_token("session", "aabbcc", "ddeeff", true)
            .unwrap_err();
        assert!(matches!(err.kind(), ErrorKind::RemoteError { code: 400, .. }));
        assert!(matches!(fxa.is_in_migration_state(), MigrationState::None));
    }

    #[test]
    fn try_migration_fails_if_nothing_in_flight() {
        let mut fxa = setup();

        assert!(matches!(fxa.is_in_migration_state(), MigrationState::None));

        let err = fxa.try_migration().unwrap_err();
        assert!(matches!(err.kind(), ErrorKind::NoMigrationData));
        assert!(matches!(fxa.is_in_migration_state(), MigrationState::None));
    }

    #[test]
    fn test_migration_state_remembers_whether_to_copy_session_token() {
        let mut fxa = setup();

        assert!(matches!(fxa.is_in_migration_state(), MigrationState::None));

        let mut client = FxAClientMock::new();
        client
            .expect_scoped_key_data(
                mockiato::Argument::any,
                |arg| arg.partial_eq("session"),
                |arg| arg.partial_eq("12345678"),
                |arg| arg.partial_eq(scopes::OLD_SYNC),
            )
            .returns_once(Err(ErrorKind::RemoteError {
                code: 500,
                errno: 999,
                error: "server error".to_string(),
                message: "there was a server error".to_string(),
                info: "fyi, there was a server error".to_string(),
            }
            .into()));
        fxa.set_client(Arc::new(client));

        let err = fxa
            .migrate_from_session_token("session", "aabbcc", "ddeeff", false)
            .unwrap_err();
        assert!(matches!(err.kind(), ErrorKind::RemoteError { code: 500, .. }));
        assert!(matches!(
            fxa.is_in_migration_state(),
            MigrationState::ReuseSessionToken
        ));

        // Retrying should fail again in the same way (as opposed to, say, trying
        // to duplicate the sessionToken rather than reusing it).
        let mut client = FxAClientMock::new();
        client
            .expect_scoped_key_data(
                mockiato::Argument::any,
                |arg| arg.partial_eq("session"),
                |arg| arg.partial_eq("12345678"),
                |arg| arg.partial_eq(scopes::OLD_SYNC),
            )
            .returns_once(Err(ErrorKind::RemoteError {
                code: 500,
                errno: 999,
                error: "server error".to_string(),
                message: "there was a server error".to_string(),
                info: "fyi, there was a server error".to_string(),
            }
            .into()));
        fxa.set_client(Arc::new(client));

        let err = fxa.try_migration().unwrap_err();
        assert!(matches!(err.kind(), ErrorKind::RemoteError { code: 500, .. }));
        assert!(matches!(
            fxa.is_in_migration_state(),
            MigrationState::ReuseSessionToken
        ));
    }
}