Bug 985212 - Check if the username looks like an email address to determine what sync to use. r=rnewman, a=sledru
authorMark Hammond <mhammond@skippinet.com.au>
Mon, 24 Mar 2014 11:44:43 +1100
changeset 192451 5c8cea3942d2809a19318dbc63a1485b5f49b99e
parent 192450 a31b22a5e8a4bc09f1fe276af44f73ec7d5961ac
child 192452 040149758c6572be2bd94149a364c90d13c871fc
push id474
push userasasaki@mozilla.com
push dateMon, 02 Jun 2014 21:01:02 +0000
treeherdermozilla-release@967f4cf1b31c [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersrnewman, sledru
bugs985212
milestone30.0a2
Bug 985212 - Check if the username looks like an email address to determine what sync to use. r=rnewman, a=sledru
services/common/tests/unit/head_helpers.js
services/sync/Weave.js
services/sync/modules-testing/utils.js
services/sync/modules/service.js
services/sync/tests/unit/test_bookmark_record.js
services/sync/tests/unit/test_clients_engine.js
services/sync/tests/unit/test_clients_escape.js
services/sync/tests/unit/test_corrupt_keys.js
services/sync/tests/unit/test_errorhandler.js
services/sync/tests/unit/test_fxa_startOver.js
services/sync/tests/unit/test_healthreport.js
services/sync/tests/unit/test_hmac_error.js
services/sync/tests/unit/test_jpakeclient.js
services/sync/tests/unit/test_password_mpenabled.js
services/sync/tests/unit/test_records_crypto.js
services/sync/tests/unit/test_records_wbo.js
services/sync/tests/unit/test_resource_ua.js
services/sync/tests/unit/test_sendcredentials_controller.js
services/sync/tests/unit/test_service_attributes.js
services/sync/tests/unit/test_service_changePassword.js
services/sync/tests/unit/test_service_checkAccount.js
services/sync/tests/unit/test_service_cluster.js
services/sync/tests/unit/test_service_detect_upgrade.js
services/sync/tests/unit/test_service_getStorageInfo.js
services/sync/tests/unit/test_service_login.js
services/sync/tests/unit/test_service_passwordUTF8.js
services/sync/tests/unit/test_service_persistLogin.js
services/sync/tests/unit/test_service_sync_remoteSetup.js
services/sync/tests/unit/test_service_verifyLogin.js
services/sync/tests/unit/test_service_wipeClient.js
services/sync/tests/unit/test_status_checkSetup.js
services/sync/tests/unit/test_syncscheduler.js
services/sync/tests/unit/test_syncstoragerequest.js
services/sync/tests/unit/test_upgrade_old_sync_key.js
services/sync/tps/extensions/tps/resource/tps.jsm
--- a/services/common/tests/unit/head_helpers.js
+++ b/services/common/tests/unit/head_helpers.js
@@ -168,21 +168,20 @@ function installFakePAC() {
 }
 
 function uninstallFakePAC() {
   _("Uninstalling fake PAC.");
   let CID = PACSystemSettings.CID;
   Cm.nsIComponentRegistrar.unregisterFactory(CID, PACSystemSettings);
 }
 
-// We want to ensure the legacy provider is used for most of these tests,
-// including after a service.startOver.  The tests that know how to deal with
+// Many tests do service.startOver() and don't expect the provider type to
+// change (whereas by default, a startOver will do exactly that so FxA is
+// subsequently used). The tests that know how to deal with
 // the Firefox Accounts identity hack things to ensure that still works.
-function setDefaultIdentityConfig() {
+function ensureStartOverKeepsIdentity() {
   Cu.import("resource://gre/modules/Services.jsm");
-  Services.prefs.setBoolPref("services.sync.fxaccounts.enabled", false);
   Services.prefs.setBoolPref("services.sync-testing.startOverKeepIdentity", true);
   do_register_cleanup(function() {
-    Services.prefs.clearUserPref("services.sync.fxaccounts.enabled");
     Services.prefs.clearUserPref("services.sync-testing.startOverKeepIdentity");
   });
 }
-setDefaultIdentityConfig();
+ensureStartOverKeepsIdentity();
--- a/services/sync/Weave.js
+++ b/services/sync/Weave.js
@@ -93,33 +93,24 @@ WeaveService.prototype = {
   },
 
   /**
    * Whether Firefox Accounts is enabled.
    *
    * @return bool
    */
   get fxAccountsEnabled() {
-    // work out what identity manager to use.  This is stored in a preference;
-    // if the preference exists, we trust it.
-    let fxAccountsEnabled;
     try {
-      fxAccountsEnabled = Services.prefs.getBoolPref("services.sync.fxaccounts.enabled");
+      // Old sync guarantees '@' will never appear in the username while FxA
+      // uses the FxA email address - so '@' is the flag we use.
+      let username = Services.prefs.getCharPref(SYNC_PREFS_BRANCH + "username");
+      return !username || username.contains('@');
     } catch (_) {
-      // That pref doesn't exist - so let's assume this is a first-run.
-      // If sync already appears configured, we assume it's for the legacy
-      // provider.
-      let prefs = Services.prefs.getBranch(SYNC_PREFS_BRANCH);
-      fxAccountsEnabled = !prefs.prefHasUserValue("username");
-      Services.prefs.setBoolPref("services.sync.fxaccounts.enabled", fxAccountsEnabled);
+      return true; // No username == only allow FxA to be configured.
     }
-    // Currently we don't support toggling this pref after initialization -
-    // except when sync is reset - but this 1 exception is enough that we can't
-    // cache the value.
-    return fxAccountsEnabled;
   },
 
   /**
    * Returns whether the password engine is allowed. We explicitly disallow
    * the password engine when a master password is used to ensure those can't
    * be accessed without the master key.
    */
   get allowPasswordsEngine() {
--- a/services/sync/modules-testing/utils.js
+++ b/services/sync/modules-testing/utils.js
@@ -2,16 +2,17 @@
  * 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 strict";
 
 this.EXPORTED_SYMBOLS = [
   "btoa", // It comes from a module import.
   "encryptPayload",
+  "ensureLegacyIdentityManager",
   "setBasicCredentials",
   "makeIdentityConfig",
   "configureFxAccountIdentity",
   "configureIdentity",
   "SyncTestingInfrastructure",
   "waitForZeroTimer",
   "Promise", // from a module import
   "add_identity_test",
@@ -44,16 +45,27 @@ this.waitForZeroTimer = function waitFor
       CommonUtils.nextTick(wait);
       return;
     }
     callback();
   }
   CommonUtils.namedTimer(wait, 150, {}, "timer");
 }
 
+/**
+  * Ensure Sync is configured with the "legacy" identity provider.
+  */
+this.ensureLegacyIdentityManager = function() {
+  let ns = {};
+  Cu.import("resource://services-sync/service.js", ns);
+
+  Status.__authManager = ns.Service.identity = new IdentityManager();
+  ns.Service._clusterManager = ns.Service.identity.createClusterManager(ns.Service);
+}
+
 this.setBasicCredentials =
  function setBasicCredentials(username, password, syncKey) {
   let ns = {};
   Cu.import("resource://services-sync/service.js", ns);
 
   let auth = ns.Service.identity;
   auth.username = username;
   auth.basicPassword = password;
@@ -165,17 +177,17 @@ this.configureIdentity = function(identi
   deferred.resolve();
   return deferred.promise;
 }
 
 this.SyncTestingInfrastructure = function (server, username, password, syncKey) {
   let ns = {};
   Cu.import("resource://services-sync/service.js", ns);
 
-  let auth = ns.Service.identity;
+  ensureLegacyIdentityManager();
   let config = makeIdentityConfig();
   // XXX - hacks for the sync identity provider.
   if (username)
     config.username = username;
   if (password)
     config.sync.password = password;
   if (syncKey)
     config.sync.syncKey = syncKey;
@@ -228,17 +240,17 @@ this.add_identity_test = function(test, 
               {_message: "TEST-INFO | | " + msg + "\n"});
   }
   let ns = {};
   Cu.import("resource://services-sync/service.js", ns);
   // one task for the "old" identity manager.
   test.add_task(function() {
     note("sync");
     let oldIdentity = Status._authManager;
-    Status.__authManager = ns.Service.identity = new IdentityManager();
+    ensureLegacyIdentityManager();
     yield testFunction();
     Status.__authManager = ns.Service.identity = oldIdentity;
   });
   // another task for the FxAccounts identity manager.
   test.add_task(function() {
     note("FxAccounts");
     let oldIdentity = Status._authManager;
     Status.__authManager = ns.Service.identity = new BrowserIDManager();
--- a/services/sync/modules/service.js
+++ b/services/sync/modules/service.js
@@ -905,17 +905,16 @@ Sync11Service.prototype = {
     if (keepIdentity) {
       Svc.Obs.notify("weave:service:start-over:finish");
       return;
     }
 
     this.identity.finalize().then(
       () => {
         this.identity.username = "";
-        Services.prefs.clearUserPref("services.sync.fxaccounts.enabled");
         this.status.__authManager = null;
         this.identity = Status._authManager;
         this._clusterManager = this.identity.createClusterManager(this);
         Svc.Obs.notify("weave:service:start-over:finish");
       }
     ).then(null,
       err => {
         this._log.error("startOver failed to re-initialize the identity manager: " + err);
--- a/services/sync/tests/unit/test_bookmark_record.js
+++ b/services/sync/tests/unit/test_bookmark_record.js
@@ -2,24 +2,26 @@
  * http://creativecommons.org/publicdomain/zero/1.0/ */
 
 Cu.import("resource://gre/modules/Log.jsm");
 Cu.import("resource://services-sync/engines/bookmarks.js");
 Cu.import("resource://services-sync/keys.js");
 Cu.import("resource://services-sync/record.js");
 Cu.import("resource://services-sync/service.js");
 Cu.import("resource://services-sync/util.js");
+Cu.import("resource://testing-common/services/sync/utils.js");
 
 function prepareBookmarkItem(collection, id) {
   let b = new Bookmark(collection, id);
   b.cleartext.stuff = "my payload here";
   return b;
 }
 
 function run_test() {
+  ensureLegacyIdentityManager();
   Service.identity.username = "john@example.com";
   Service.identity.syncKey = "abcdeabcdeabcdeabcdeabcdea";
   generateNewKeys(Service.collectionKeys);
   let keyBundle = Service.identity.syncKeyBundle;
 
   let log = Log.repository.getLogger("Test");
   Log.repository.rootLogger.addAppender(new Log.DumpAppender());
 
--- a/services/sync/tests/unit/test_clients_engine.js
+++ b/services/sync/tests/unit/test_clients_engine.js
@@ -76,16 +76,17 @@ add_test(function test_bad_hmac() {
   function uploadNewKeys() {
     generateNewKeys(Service.collectionKeys);
     let serverKeys = Service.collectionKeys.asWBO("crypto", "keys");
     serverKeys.encrypt(Service.identity.syncKeyBundle);
     do_check_true(serverKeys.upload(Service.resource(Service.cryptoKeysURL)).success);
   }
 
   try {
+    ensureLegacyIdentityManager();
     let passphrase     = "abcdeabcdeabcdeabcdeabcdea";
     Service.serverURL  = server.baseURI;
     Service.login("foo", "ilovejane", passphrase);
 
     generateNewKeys(Service.collectionKeys);
 
     _("First sync, client record is uploaded");
     do_check_eq(engine.lastRecordUpload, 0);
--- a/services/sync/tests/unit/test_clients_escape.js
+++ b/services/sync/tests/unit/test_clients_escape.js
@@ -1,19 +1,21 @@
 /* Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/ */
 
 Cu.import("resource://services-sync/keys.js");
 Cu.import("resource://services-sync/record.js");
 Cu.import("resource://services-sync/service.js");
 Cu.import("resource://services-sync/util.js");
+Cu.import("resource://testing-common/services/sync/utils.js");
 
 function run_test() {
   _("Set up test fixtures.");
 
+  ensureLegacyIdentityManager();
   Service.identity.username = "john@example.com";
   Service.clusterURL = "http://fakebase/";
   let baseUri = "http://fakebase/1.1/foo/storage/";
   let pubUri = baseUri + "keys/pubkey";
   let privUri = baseUri + "keys/privkey";
 
   Service.identity.syncKey = "abcdeabcdeabcdeabcdeabcdea";
   let keyBundle = Service.identity.syncKeyBundle;
--- a/services/sync/tests/unit/test_corrupt_keys.js
+++ b/services/sync/tests/unit/test_corrupt_keys.js
@@ -199,16 +199,18 @@ add_task(function test_locally_changed_k
     yield deferred.promise;
   }
 });
 
 function run_test() {
   let logger = Log.repository.rootLogger;
   Log.repository.rootLogger.addAppender(new Log.DumpAppender());
 
+  ensureLegacyIdentityManager();
+
   run_next_test();
 }
 
 /**
  * Asynchronously check a url is visited.
  * @param url the url
  * @return {Promise}
  * @resolves When the check has been added successfully.
--- a/services/sync/tests/unit/test_errorhandler.js
+++ b/services/sync/tests/unit/test_errorhandler.js
@@ -50,16 +50,18 @@ let errorHandler = Service.errorHandler;
 
 function run_test() {
   initTestLogging("Trace");
 
   Log.repository.getLogger("Sync.Service").level = Log.Level.Trace;
   Log.repository.getLogger("Sync.SyncScheduler").level = Log.Level.Trace;
   Log.repository.getLogger("Sync.ErrorHandler").level = Log.Level.Trace;
 
+  ensureLegacyIdentityManager();
+
   run_next_test();
 }
 
 function generateCredentialsChangedFailure() {
   // Make sync fail due to changed credentials. We simply re-encrypt
   // the keys with a different Sync Key, without changing the local one.
   let newSyncKeyBundle = new SyncKeyBundle("johndoe", "23456234562345623456234562");
   let keys = Service.collectionKeys.asWBO();
--- a/services/sync/tests/unit/test_fxa_startOver.js
+++ b/services/sync/tests/unit/test_fxa_startOver.js
@@ -10,20 +10,20 @@ function run_test() {
   initTestLogging("Trace");
   run_next_test();
 }
 
 add_task(function* test_startover() {
   let oldValue = Services.prefs.getBoolPref("services.sync-testing.startOverKeepIdentity", true);
   Services.prefs.setBoolPref("services.sync-testing.startOverKeepIdentity", false);
 
+  ensureLegacyIdentityManager();
   yield configureIdentity({username: "johndoe"});
-  // The pref that forces FxA identities should not be set.
-  do_check_false(Services.prefs.getBoolPref("services.sync.fxaccounts.enabled"));
-  // And the boolean flag on the xpcom service should reflect this.
+
+  // The boolean flag on the xpcom service should reflect a legacy provider.
   let xps = Cc["@mozilla.org/weave/service;1"]
             .getService(Components.interfaces.nsISupports)
             .wrappedJSObject;
   do_check_false(xps.fxAccountsEnabled);
 
   // we expect the "legacy" provider (but can't instanceof that, as BrowserIDManager
   // extends it)
   do_check_false(Service.identity instanceof BrowserIDManager);
@@ -38,25 +38,22 @@ add_task(function* test_startover() {
   Services.obs.addObserver(function observeStartOverFinished() {
     Services.obs.removeObserver(observeStartOverFinished, "weave:service:start-over:finish");
     deferred.resolve();
   }, "weave:service:start-over:finish", false);
 
   Service.startOver();
   yield deferred.promise; // wait for the observer to fire.
 
-  // should have reset the pref that indicates if FxA is enabled.
-  do_check_true(Services.prefs.getBoolPref("services.sync.fxaccounts.enabled"));
-  // the xpcom service should agree FxA is enabled.
+  // the xpcom service should indicate FxA is enabled.
   do_check_true(xps.fxAccountsEnabled);
   // should have swapped identities.
   do_check_true(Service.identity instanceof BrowserIDManager);
   // should have clobbered the cluster URL
   do_check_eq(Service.clusterURL, "");
 
   // we should have thrown away the old identity provider and cluster manager.
   do_check_neq(oldIdentity, Service.identity);
   do_check_neq(oldClusterManager, Service._clusterManager);
 
   // reset the world.
-  Services.prefs.setBoolPref("services.sync.fxaccounts.enabled", false);
   Services.prefs.setBoolPref("services.sync-testing.startOverKeepIdentity", oldValue);
 });
--- a/services/sync/tests/unit/test_healthreport.js
+++ b/services/sync/tests/unit/test_healthreport.js
@@ -9,25 +9,16 @@ Cu.import("resource://gre/modules/Promis
 Cu.import("resource://services-sync/main.js", this);
 Cu.import("resource://services-sync/healthreport.jsm", this);
 Cu.import("resource://testing-common/services-common/logging.js", this);
 Cu.import("resource://testing-common/services/healthreport/utils.jsm", this);
 
 function run_test() {
   initTestLogging();
 
-  // A head JS file always sets the
-  // services.sync.fxaccounts.enabled pref. This prevents us from testing
-  // pristine profile conditions and likely indicates there isn't test
-  // coverage of the Sync service's fxAccountsEnabled property. Check
-  // that pre-condition and hack around it.
-  let branch = new Preferences("services.sync.");
-  Assert.ok(branch.isSet("fxaccounts.enabled"), "Check precondition");
-  branch.reset("fxaccounts.enabled");
-
   run_next_test();
 }
 
 add_task(function test_constructor() {
   let provider = new SyncProvider();
 });
 
 // Provider can initialize and de-initialize properly.
--- a/services/sync/tests/unit/test_hmac_error.js
+++ b/services/sync/tests/unit/test_hmac_error.js
@@ -16,16 +16,17 @@ let hmacErrorCount = 0;
     return hHE.call(Service);
   };
 })();
 
 function shared_setup() {
   hmacErrorCount = 0;
 
   // Do not instantiate SyncTestingInfrastructure; we need real crypto.
+  ensureLegacyIdentityManager();
   setBasicCredentials("foo", "foo", "aabcdeabcdeabcdeabcdeabcde");
 
   // Make sure RotaryEngine is the only one we sync.
   Service.engineManager._engines = {};
   Service.engineManager.register(RotaryEngine);
   let engine = Service.engineManager.get("rotary");
   engine.enabled = true;
   engine.lastSync = 123; // Needs to be non-zero so that tracker is queried.
--- a/services/sync/tests/unit/test_jpakeclient.js
+++ b/services/sync/tests/unit/test_jpakeclient.js
@@ -181,16 +181,17 @@ function run_test() {
     Svc.Prefs.resetBranch("");
   });
 
   // Ensure PSM is initialized.
   Cc["@mozilla.org/psm;1"].getService(Ci.nsISupports);
 
   // Simulate Sync setup with credentials in place. We want to make
   // sure the J-PAKE requests don't include those data.
+  ensureLegacyIdentityManager();
   setBasicCredentials("johndoe", "ilovejane");
 
   initTestLogging("Trace");
   Log.repository.getLogger("Sync.JPAKEClient").level = Log.Level.Trace;
   Log.repository.getLogger("Common.RESTRequest").level =
     Log.Level.Trace;
   run_next_test();
 }
--- a/services/sync/tests/unit/test_password_mpenabled.js
+++ b/services/sync/tests/unit/test_password_mpenabled.js
@@ -9,17 +9,24 @@ Cu.import("resource://services-sync/serv
 Cu.import("resource://testing-common/services/sync/utils.js");
 
 function run_test() {
   initTestLogging("Trace");
   run_next_test();
 }
 
 add_test(function test_simple() {
-  Services.prefs.setBoolPref("services.sync.fxaccounts.enabled", true);
+  ensureLegacyIdentityManager();
+  // Stub fxAccountsEnabled
+  let xpcs = Cc["@mozilla.org/weave/service;1"]
+             .getService(Components.interfaces.nsISupports)
+             .wrappedJSObject;
+  let fxaEnabledGetter = xpcs.__lookupGetter__("fxAccountsEnabled");
+  xpcs.__defineGetter__("fxAccountsEnabled", () => true);
+
   // Stub mpEnabled.
   let mpEnabledF = Utils.mpEnabled;
   let mpEnabled = false;
   Utils.mpEnabled = function() mpEnabled;
 
   let manager = Service.engineManager;
 
   Service.engineManager.register(PasswordEngine);
@@ -117,14 +124,14 @@ add_test(function test_simple() {
     //engineSync._updateEnabledEngines();
     engineMeta = Service.recordManager.get(engine.metaURL);
     Assert.equal(engineMeta.payload.engines[engine.name].version, engine.version,
                  "The engine should re-appear in the metadata");
   } finally {
     // restore the damage we did above...
     engine.wipeServer = engineWipeServerF;
     engine._store.wipe();
-    // Un-stub mpEnabled.
+    // Un-stub mpEnabled and fxAccountsEnabled
     Utils.mpEnabled = mpEnabledF;
-    Services.prefs.clearUserPref("services.sync.fxaccounts.enabled");
+    xpcs.__defineGetter__("fxAccountsEnabled", fxaEnabledGetter);
     server.stop(run_next_test);
   }
 });
--- a/services/sync/tests/unit/test_records_crypto.js
+++ b/services/sync/tests/unit/test_records_crypto.js
@@ -3,16 +3,17 @@
 
 Cu.import("resource://gre/modules/Log.jsm");
 Cu.import("resource://services-sync/constants.js");
 Cu.import("resource://services-sync/keys.js");
 Cu.import("resource://services-sync/record.js");
 Cu.import("resource://services-sync/resource.js");
 Cu.import("resource://services-sync/service.js");
 Cu.import("resource://services-sync/util.js");
+Cu.import("resource://testing-common/services/sync/utils.js");
 
 let cryptoWrap;
 
 function crypted_resource_handler(metadata, response) {
   let obj = {id: "resource",
              modified: cryptoWrap.modified,
              payload: JSON.stringify(cryptoWrap.payload)};
   return httpd_basic_auth_handler(JSON.stringify(obj), metadata, response);
@@ -25,16 +26,17 @@ function prepareCryptoWrap(collection, i
   w.id = id;
   return w;
 }
 
 function run_test() {
   let server;
   do_test_pending();
 
+  ensureLegacyIdentityManager();
   Service.identity.username = "john@example.com";
   Service.identity.syncKey = "a-abcde-abcde-abcde-abcde-abcde";
   let keyBundle = Service.identity.syncKeyBundle;
 
   try {
     let log = Log.repository.getLogger("Test");
     Log.repository.rootLogger.addAppender(new Log.DumpAppender());
 
--- a/services/sync/tests/unit/test_records_wbo.js
+++ b/services/sync/tests/unit/test_records_wbo.js
@@ -1,16 +1,17 @@
 /* Any copyright is dedicated to the Public Domain.
    http://creativecommons.org/publicdomain/zero/1.0/ */
 
 Cu.import("resource://services-sync/record.js");
 Cu.import("resource://services-sync/identity.js");
 Cu.import("resource://services-sync/resource.js");
 Cu.import("resource://services-sync/service.js");
 Cu.import("resource://services-sync/util.js");
+Cu.import("resource://testing-common/services/sync/utils.js");
 
 
 function test_toJSON() {
   _("Create a record, for now without a TTL.");
   let wbo = new WBORecord("coll", "a_record");
   wbo.modified = 12345;
   wbo.sortindex = 42;
   wbo.payload = {};
@@ -73,12 +74,13 @@ function test_fetch() {
 
   } finally {
     server.stop(do_test_finished);
   }
 }
 
 function run_test() {
   initTestLogging("Trace");
+  ensureLegacyIdentityManager();
 
   test_toJSON();
   test_fetch();
 }
--- a/services/sync/tests/unit/test_resource_ua.js
+++ b/services/sync/tests/unit/test_resource_ua.js
@@ -26,16 +26,17 @@ function uaHandler(f) {
 function run_test() {
   Log.repository.rootLogger.addAppender(new Log.DumpAppender());
   meta_global = new ServerWBO('global');
   server = httpd_setup({
     "/1.1/johndoe/info/collections": uaHandler(collectionsHelper.handler),
     "/1.1/johndoe/storage/meta/global": uaHandler(meta_global.handler()),
   });
 
+  ensureLegacyIdentityManager();
   setBasicCredentials("johndoe", "ilovejane");
   Service.serverURL = server.baseURI + "/";
   Service.clusterURL = server.baseURI + "/";
   _("Server URL: " + server.baseURI);
 
   expectedUA = Services.appinfo.name + "/" + Services.appinfo.version +
                " FxSync/" + WEAVE_VERSION + "." +
                Services.appinfo.appBuildID;
--- a/services/sync/tests/unit/test_sendcredentials_controller.js
+++ b/services/sync/tests/unit/test_sendcredentials_controller.js
@@ -3,16 +3,17 @@
 
 Cu.import("resource://services-sync/constants.js");
 Cu.import("resource://services-sync/jpakeclient.js");
 Cu.import("resource://services-sync/service.js");
 Cu.import("resource://services-sync/util.js");
 Cu.import("resource://testing-common/services/sync/utils.js");
 
 function run_test() {
+  ensureLegacyIdentityManager();
   setBasicCredentials("johndoe", "ilovejane", Utils.generatePassphrase());
   Service.serverURL  = "http://weave.server/";
 
   initTestLogging("Trace");
   Log.repository.getLogger("Sync.SendCredentialsController").level = Log.Level.Trace;
   Log.repository.getLogger("Sync.SyncScheduler").level = Log.Level.Trace;
   run_next_test();
 }
--- a/services/sync/tests/unit/test_service_attributes.js
+++ b/services/sync/tests/unit/test_service_attributes.js
@@ -1,19 +1,21 @@
 /* Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/ */
 
 Cu.import("resource://services-sync/constants.js");
 Cu.import("resource://services-sync/service.js");
 Cu.import("resource://services-sync/util.js");
 Cu.import("resource://testing-common/services/sync/fakeservices.js");
+Cu.import("resource://testing-common/services/sync/utils.js");
 
 function test_urls() {
   _("URL related Service properties correspond to preference settings.");
   try {
+    ensureLegacyIdentityManager();
     do_check_true(!!Service.serverURL); // actual value may change
     do_check_eq(Service.clusterURL, "");
     do_check_eq(Service.userBaseURL, undefined);
     do_check_eq(Service.infoURL, undefined);
     do_check_eq(Service.storageURL, undefined);
     do_check_eq(Service.metaURL, undefined);
 
     _("The 'clusterURL' attribute updates preferences and cached URLs.");
--- a/services/sync/tests/unit/test_service_changePassword.js
+++ b/services/sync/tests/unit/test_service_changePassword.js
@@ -8,16 +8,18 @@ Cu.import("resource://services-sync/util
 Cu.import("resource://testing-common/services/sync/utils.js");
 
 function run_test() {
   initTestLogging("Trace");
   Log.repository.getLogger("Sync.AsyncResource").level = Log.Level.Trace;
   Log.repository.getLogger("Sync.Resource").level = Log.Level.Trace;
   Log.repository.getLogger("Sync.Service").level = Log.Level.Trace;
 
+  ensureLegacyIdentityManager();
+
   run_next_test();
 }
 
 add_test(function test_change_password() {
   let requestBody;
   let server;
 
   function send(statusCode, status, body) {
--- a/services/sync/tests/unit/test_service_checkAccount.js
+++ b/services/sync/tests/unit/test_service_checkAccount.js
@@ -2,16 +2,17 @@
  * http://creativecommons.org/publicdomain/zero/1.0/ */
 
 Cu.import("resource://services-sync/service.js");
 Cu.import("resource://services-sync/util.js");
 Cu.import("resource://testing-common/services/sync/utils.js");
 
 function run_test() {
   do_test_pending();
+  ensureLegacyIdentityManager();
   let server = httpd_setup({
     "/user/1.0/johndoe": httpd_handler(200, "OK", "1"),
     "/user/1.0/janedoe": httpd_handler(200, "OK", "0"),
     // john@doe.com
     "/user/1.0/7wohs32cngzuqt466q3ge7indszva4of": httpd_handler(200, "OK", "0"),
     // jane@doe.com
     "/user/1.0/vuuf3eqgloxpxmzph27f5a6ve7gzlrms": httpd_handler(200, "OK", "1")
   });
--- a/services/sync/tests/unit/test_service_cluster.js
+++ b/services/sync/tests/unit/test_service_cluster.js
@@ -13,21 +13,22 @@ function do_check_throws(func) {
     raised = true;
   }
   do_check_true(raised);
 }
 
 add_test(function test_findCluster() {
   _("Test Service._findCluster()");
   let server;
+  ensureLegacyIdentityManager();
   try {
     _("_findCluster() throws on network errors (e.g. connection refused).");
     do_check_throws(function() {
       Service.serverURL = "http://dummy:9000/";
-      Service.identify.account = "johndoe";
+      Service.identity.account = "johndoe";
       Service._clusterManager._findCluster();
     });
 
     server = httpd_setup({
       "/user/1.0/johndoe/node/weave": httpd_handler(200, "OK", "http://weave.user.node/"),
       "/user/1.0/jimdoe/node/weave": httpd_handler(200, "OK", "null"),
       "/user/1.0/janedoe/node/weave": httpd_handler(404, "Not Found", "Not Found"),
       "/user/1.0/juliadoe/node/weave": httpd_handler(400, "Bad Request", "Bad Request"),
--- a/services/sync/tests/unit/test_service_detect_upgrade.js
+++ b/services/sync/tests/unit/test_service_detect_upgrade.js
@@ -38,16 +38,18 @@ add_test(function v4_upgrade() {
     // Just so we don't get 404s in the logs.
     "/1.1/johndoe/storage/bookmarks": new ServerCollection().handler(),
     "/1.1/johndoe/storage/forms": new ServerCollection().handler(),
     "/1.1/johndoe/storage/history": new ServerCollection().handler(),
     "/1.1/johndoe/storage/passwords": new ServerCollection().handler(),
     "/1.1/johndoe/storage/prefs": new ServerCollection().handler()
   });
 
+  ensureLegacyIdentityManager();
+
   try {
 
     _("Set up some tabs.");
     let myTabs =
       {windows: [{tabs: [{index: 1,
                           entries: [{
                             url: "http://foo.com/",
                             title: "Title"
--- a/services/sync/tests/unit/test_service_getStorageInfo.js
+++ b/services/sync/tests/unit/test_service_getStorageInfo.js
@@ -11,16 +11,17 @@ let collections = {steam:  65.11328,
                    petrol: 82.488281,
                    diesel: 2.25488281};
 
 function run_test() {
   Log.repository.getLogger("Sync.Service").level = Log.Level.Trace;
   Log.repository.getLogger("Sync.StorageRequest").level = Log.Level.Trace;
   initTestLogging();
 
+  ensureLegacyIdentityManager();
   setBasicCredentials("johndoe", "ilovejane");
 
   run_next_test();
 }
 
 add_test(function test_success() {
   let handler = httpd_handler(200, "OK", JSON.stringify(collections));
   let server = httpd_setup({"/1.1/johndoe/info/collections": handler});
--- a/services/sync/tests/unit/test_service_login.js
+++ b/services/sync/tests/unit/test_service_login.js
@@ -67,16 +67,17 @@ function setup() {
   return server;
 }
 
 add_test(function test_login_logout() {
   let server = setup();
 
   try {
     _("Force the initial state.");
+    ensureLegacyIdentityManager();
     Service.status.service = STATUS_OK;
     do_check_eq(Service.status.service, STATUS_OK);
 
     _("Try logging in. It won't work because we're not configured yet.");
     Service.login();
     do_check_eq(Service.status.service, CLIENT_NOT_CONFIGURED);
     do_check_eq(Service.status.login, LOGIN_FAILED_NO_USERNAME);
     do_check_false(Service.isLoggedIn);
--- a/services/sync/tests/unit/test_service_passwordUTF8.js
+++ b/services/sync/tests/unit/test_service_passwordUTF8.js
@@ -53,16 +53,18 @@ function change_password(request, respon
 }
 
 function run_test() {
   initTestLogging("Trace");
   let collectionsHelper = track_collections_helper();
   let upd = collectionsHelper.with_updated_collection;
   let collections = collectionsHelper.collections;
 
+  ensureLegacyIdentityManager();
+
   do_test_pending();
   let server = httpd_setup({
     "/1.1/johndoe/info/collections":    login_handling(collectionsHelper.handler),
     "/1.1/johndoe/storage/meta/global": upd("meta",   new ServerWBO("global").handler()),
     "/1.1/johndoe/storage/crypto/keys": upd("crypto", new ServerWBO("keys").handler()),
     "/user/1.0/johndoe/password":       change_password
   });
 
--- a/services/sync/tests/unit/test_service_persistLogin.js
+++ b/services/sync/tests/unit/test_service_persistLogin.js
@@ -4,16 +4,17 @@
 Cu.import("resource://services-sync/constants.js");
 Cu.import("resource://services-sync/service.js");
 Cu.import("resource://services-sync/util.js");
 Cu.import("resource://testing-common/services/sync/utils.js");
 
 function run_test() {
   try {
     // Ensure we have a blank slate to start.
+    ensureLegacyIdentityManager();
     Services.logins.removeAllLogins();
 
     setBasicCredentials("johndoe", "ilovejane", "abbbbbcccccdddddeeeeefffff");
 
     _("Confirm initial environment is empty.");
     let logins = Services.logins.findLogins({}, PWDMGR_HOST, null,
                                         PWDMGR_PASSWORD_REALM);
     do_check_eq(logins.length, 0);
--- a/services/sync/tests/unit/test_service_sync_remoteSetup.js
+++ b/services/sync/tests/unit/test_service_sync_remoteSetup.js
@@ -60,16 +60,17 @@ function run_test() {
     "/1.1/johndoe/storage/clients": upd("clients", clients.handler()),
     "/1.1/johndoe/storage/meta/global": upd("meta", wasCalledHandler(meta_global)),
     "/1.1/johndoe/storage/meta": upd("meta", wasCalledHandler(metaColl)),
     "/1.1/johndoe/info/collections": collectionsHelper.handler
   });
 
   try {
     _("Log in.");
+    ensureLegacyIdentityManager();
     Service.serverURL = server.baseURI;
 
     _("Checking Status.sync with no credentials.");
     Service.verifyAndFetchSymmetricKeys();
     do_check_eq(Service.status.sync, CREDENTIALS_CHANGED);
     do_check_eq(Service.status.login, LOGIN_FAILED_NO_PASSPHRASE);
 
     _("Log in with an old secret phrase, is upgraded to Sync Key.");
--- a/services/sync/tests/unit/test_service_verifyLogin.js
+++ b/services/sync/tests/unit/test_service_verifyLogin.js
@@ -25,16 +25,17 @@ function service_unavailable(request, re
   response.setHeader("Retry-After", "42");
   response.bodyOutputStream.write(body, body.length);
 }
 
 function run_test() {
   let logger = Log.repository.rootLogger;
   Log.repository.rootLogger.addAppender(new Log.DumpAppender());
 
+  ensureLegacyIdentityManager();
   // This test expects a clean slate -- no saved passphrase.
   Services.logins.removeAllLogins();
   let johnHelper = track_collections_helper();
   let johnU      = johnHelper.with_updated_collection;
   let johnColls  = johnHelper.collections;
 
   do_test_pending();
 
--- a/services/sync/tests/unit/test_service_wipeClient.js
+++ b/services/sync/tests/unit/test_service_wipeClient.js
@@ -77,16 +77,17 @@ add_test(function test_startOver_clears_
 
   run_next_test();
 });
 
 add_test(function test_credentials_preserved() {
   _("Ensure that credentials are preserved if client is wiped.");
 
   // Required for wipeClient().
+  ensureLegacyIdentityManager();
   Service.identity.account = "testaccount";
   Service.identity.basicPassword = "testpassword";
   Service.clusterURL = "http://dummy:9000/";
   let key = Utils.generatePassphrase();
   Service.identity.syncKey = key;
   Service.identity.persistCredentials();
 
   // Simulate passwords engine wipe without all the overhead. To do this
--- a/services/sync/tests/unit/test_status_checkSetup.js
+++ b/services/sync/tests/unit/test_status_checkSetup.js
@@ -1,17 +1,19 @@
 /* Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/ */
 
 Cu.import("resource://services-sync/constants.js");
 Cu.import("resource://services-sync/status.js");
 Cu.import("resource://services-sync/util.js");
+Cu.import("resource://testing-common/services/sync/utils.js");
 
 function run_test() {
   initTestLogging("Trace");
+  ensureLegacyIdentityManager();
 
   try {
     _("Ensure fresh config.");
     Status._authManager.deleteSyncCredentials();
 
     _("Fresh setup, we're not configured.");
     do_check_eq(Status.checkSetup(), CLIENT_NOT_CONFIGURED);
     do_check_eq(Status.login, LOGIN_FAILED_NO_USERNAME);
--- a/services/sync/tests/unit/test_syncscheduler.js
+++ b/services/sync/tests/unit/test_syncscheduler.js
@@ -80,16 +80,23 @@ function cleanUpAndGo(server) {
 }
 
 function run_test() {
   initTestLogging("Trace");
 
   Log.repository.getLogger("Sync.Service").level = Log.Level.Trace;
   Log.repository.getLogger("Sync.scheduler").level = Log.Level.Trace;
 
+  // The scheduler checks Weave.fxaEnabled to determine whether to use
+  // FxA defaults or legacy defaults.  As .fxaEnabled checks the username, we
+  // set a username here then reset the default to ensure they are used.
+  ensureLegacyIdentityManager();
+  setBasicCredentials("johndoe");
+  scheduler.setDefaults();
+
   run_next_test();
 }
 
 add_test(function test_prefAttributes() {
   _("Test various attributes corresponding to preferences.");
 
   const INTERVAL = 42 * 60 * 1000;   // 42 minutes
   const THRESHOLD = 3142;
--- a/services/sync/tests/unit/test_syncstoragerequest.js
+++ b/services/sync/tests/unit/test_syncstoragerequest.js
@@ -7,16 +7,18 @@ Cu.import("resource://services-sync/rest
 Cu.import("resource://services-sync/service.js");
 Cu.import("resource://services-sync/util.js");
 Cu.import("resource://testing-common/services/sync/utils.js");
 
 function run_test() {
   Log.repository.getLogger("Sync.RESTRequest").level = Log.Level.Trace;
   initTestLogging();
 
+  ensureLegacyIdentityManager();
+
   run_next_test();
 }
 
 add_test(function test_user_agent_desktop() {
   let handler = httpd_handler(200, "OK");
   let server = httpd_setup({"/resource": handler});
 
   let expectedUA = Services.appinfo.name + "/" + Services.appinfo.version +
--- a/services/sync/tests/unit/test_upgrade_old_sync_key.js
+++ b/services/sync/tests/unit/test_upgrade_old_sync_key.js
@@ -1,19 +1,21 @@
 /* Any copyright is dedicated to the Public Domain.
  * http://creativecommons.org/publicdomain/zero/1.0/ */
 
 Cu.import("resource://services-sync/constants.js");
 Cu.import("resource://services-sync/service.js");
 Cu.import("resource://services-sync/util.js");
+Cu.import("resource://testing-common/services/sync/utils.js");
 
 // Test upgrade of a dashed old-style sync key.
 function run_test() {
   const PBKDF2_KEY_BYTES = 16;
   initTestLogging("Trace");
+  ensureLegacyIdentityManager();
 
   let passphrase = "abcde-abcde-abcde-abcde";
   do_check_false(Utils.isPassphrase(passphrase));
 
   let normalized = Utils.normalizePassphrase(passphrase);
   _("Normalized: " + normalized);
 
   // Still not a modern passphrase...
--- a/services/sync/tps/extensions/tps/resource/tps.jsm
+++ b/services/sync/tps/extensions/tps/resource/tps.jsm
@@ -90,21 +90,20 @@ let TPS = {
   _operations_pending: 0,
   _loggedIn: false,
   _enabledEngines: null,
 
   /**
    * Check if the Firefox Accounts feature is enabled
    */
   get fxaccounts_enabled() {
-    try {
-      return Services.prefs.getBoolPref("services.sync.fxaccounts.enabled");
-    } catch (e) {
-      return false;
-    }
+    let service = Cc["@mozilla.org/weave/service;1"]
+                  .getService(Components.interfaces.nsISupports)
+                  .wrappedJSObject;
+    return service.fxAccountsEnabled;
   },
 
   DumpError: function (msg) {
     this._errors++;
     Logger.logError("[phase" + this._currentPhase + "] " + msg);
     this.quit();
   },