Bug 1296767 part 4 - Update tests to work with the BrowserID identity manager. r=markh

MozReview-Commit-ID: AFRyZFW6xZU
This commit is contained in:
Edouard Oger 2017-01-13 15:59:32 -05:00
parent bf4dae4e25
commit df80e282e9
38 changed files with 190 additions and 1023 deletions

View File

@ -7,9 +7,6 @@
this.EXPORTED_SYMBOLS = [ this.EXPORTED_SYMBOLS = [
"btoa", // It comes from a module import. "btoa", // It comes from a module import.
"encryptPayload", "encryptPayload",
"isConfiguredWithLegacyIdentity",
"ensureLegacyIdentityManager",
"setBasicCredentials",
"makeIdentityConfig", "makeIdentityConfig",
"makeFxAccountsInternalMock", "makeFxAccountsInternalMock",
"configureFxAccountIdentity", "configureFxAccountIdentity",
@ -107,40 +104,6 @@ this.promiseNamedTimer = function(wait, thisObj, name) {
}); });
} }
/**
* Return true if Sync is configured with the "legacy" identity provider.
*/
this.isConfiguredWithLegacyIdentity = function() {
let ns = {};
Cu.import("resource://services-sync/service.js", ns);
// We can't use instanceof as BrowserIDManager (the "other" identity) inherits
// from IdentityManager so that would return true - so check the prototype.
return Object.getPrototypeOf(ns.Service.identity) === IdentityManager.prototype;
}
/**
* 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;
auth.syncKey = syncKey;
}
// Return an identity configuration suitable for testing with our identity // Return an identity configuration suitable for testing with our identity
// providers. |overrides| can specify overrides for any default values. // providers. |overrides| can specify overrides for any default values.
// |server| is optional, but if specified, will be used to form the cluster // |server| is optional, but if specified, will be used to form the cluster

View File

@ -23,6 +23,11 @@ function return_timestamp(request, response, timestamp) {
return timestamp; return timestamp;
} }
function has_hawk_header(req) {
return req.hasHeader("Authorization") &&
req.getHeader("Authorization").startsWith("Hawk");
}
function basic_auth_header(user, password) { function basic_auth_header(user, password) {
return "Basic " + btoa(user + ":" + Utils.encodeUTF8(password)); return "Basic " + btoa(user + ":" + Utils.encodeUTF8(password));
} }

View File

@ -83,7 +83,6 @@ add_task(async function test_initialializeWithCurrentIdentity() {
await browseridManager.whenReadyToAuthenticate.promise; await browseridManager.whenReadyToAuthenticate.promise;
do_check_true(!!browseridManager._token); do_check_true(!!browseridManager._token);
do_check_true(browseridManager.hasValidToken()); do_check_true(browseridManager.hasValidToken());
do_check_eq(browseridManager.account, identityConfig.fxaccount.user.email);
} }
); );
@ -131,10 +130,8 @@ add_task(async function test_initialializeWithAuthErrorAndDeletedAccount() {
do_check_true(signCertificateCalled); do_check_true(signCertificateCalled);
do_check_true(accountStatusCalled); do_check_true(accountStatusCalled);
do_check_false(browseridManager.account);
do_check_false(browseridManager._token); do_check_false(browseridManager._token);
do_check_false(browseridManager.hasValidToken()); do_check_false(browseridManager.hasValidToken());
do_check_false(browseridManager.account);
}); });
add_task(async function test_initialializeWithNoKeys() { add_task(async function test_initialializeWithNoKeys() {
@ -496,10 +493,8 @@ add_task(async function test_refreshCertificateOn401() {
do_check_eq(getCertCount, 2); do_check_eq(getCertCount, 2);
do_check_true(didReturn401); do_check_true(didReturn401);
do_check_true(didReturn200); do_check_true(didReturn200);
do_check_true(browseridManager.account);
do_check_true(browseridManager._token); do_check_true(browseridManager._token);
do_check_true(browseridManager.hasValidToken()); do_check_true(browseridManager.hasValidToken());
do_check_true(browseridManager.account);
}); });

View File

@ -102,7 +102,7 @@ add_task(async function test_bad_hmac() {
try { try {
await configureIdentity({username: "foo"}, server); await configureIdentity({username: "foo"}, server);
Service.login("foo"); Service.login();
generateNewKeys(Service.collectionKeys); generateNewKeys(Service.collectionKeys);

View File

@ -80,7 +80,7 @@ add_task(async function test_locally_changed_keys() {
do_check_true(serverKeys.upload(Service.resource(Service.cryptoKeysURL)).success); do_check_true(serverKeys.upload(Service.resource(Service.cryptoKeysURL)).success);
// Check that login works. // Check that login works.
do_check_true(Service.login("johndoe")); do_check_true(Service.login());
do_check_true(Service.isLoggedIn); do_check_true(Service.isLoggedIn);
// Sync should upload records. // Sync should upload records.

View File

@ -83,10 +83,7 @@ add_identity_test(this, async function test_401_logout() {
_("Got weave:service:login:error in second sync."); _("Got weave:service:login:error in second sync.");
Svc.Obs.remove("weave:service:login:error", onLoginError); Svc.Obs.remove("weave:service:login:error", onLoginError);
let expected = isConfiguredWithLegacyIdentity() ? do_check_eq(Status.login, LOGIN_FAILED_NETWORK_ERROR);
LOGIN_FAILED_LOGIN_REJECTED : LOGIN_FAILED_NETWORK_ERROR;
do_check_eq(Status.login, expected);
do_check_false(Service.isLoggedIn); do_check_false(Service.isLoggedIn);
// Clean up. // Clean up.
@ -159,13 +156,6 @@ add_identity_test(this, function test_shouldReportError() {
Service.serverURL = fakeServerUrl; Service.serverURL = fakeServerUrl;
Service.clusterURL = fakeServerUrl; Service.clusterURL = fakeServerUrl;
// Test dontIgnoreErrors, non-network, non-prolonged, login error reported
Status.resetSync();
setLastSync(NON_PROLONGED_ERROR_DURATION);
errorHandler.dontIgnoreErrors = true;
Status.login = LOGIN_FAILED_NO_PASSWORD;
do_check_true(errorHandler.shouldReportError());
// Test dontIgnoreErrors, non-network, non-prolonged, sync error reported // Test dontIgnoreErrors, non-network, non-prolonged, sync error reported
Status.resetSync(); Status.resetSync();
setLastSync(NON_PROLONGED_ERROR_DURATION); setLastSync(NON_PROLONGED_ERROR_DURATION);
@ -173,13 +163,6 @@ add_identity_test(this, function test_shouldReportError() {
Status.sync = CREDENTIALS_CHANGED; Status.sync = CREDENTIALS_CHANGED;
do_check_true(errorHandler.shouldReportError()); do_check_true(errorHandler.shouldReportError());
// Test dontIgnoreErrors, non-network, prolonged, login error reported
Status.resetSync();
setLastSync(PROLONGED_ERROR_DURATION);
errorHandler.dontIgnoreErrors = true;
Status.login = LOGIN_FAILED_NO_PASSWORD;
do_check_true(errorHandler.shouldReportError());
// Test dontIgnoreErrors, non-network, prolonged, sync error reported // Test dontIgnoreErrors, non-network, prolonged, sync error reported
Status.resetSync(); Status.resetSync();
setLastSync(PROLONGED_ERROR_DURATION); setLastSync(PROLONGED_ERROR_DURATION);
@ -215,24 +198,6 @@ add_identity_test(this, function test_shouldReportError() {
Status.sync = LOGIN_FAILED_NETWORK_ERROR; Status.sync = LOGIN_FAILED_NETWORK_ERROR;
do_check_true(errorHandler.shouldReportError()); do_check_true(errorHandler.shouldReportError());
// Test non-network, prolonged, login error reported
do_check_false(errorHandler.didReportProlongedError);
Status.resetSync();
setLastSync(PROLONGED_ERROR_DURATION);
errorHandler.dontIgnoreErrors = false;
Status.login = LOGIN_FAILED_NO_PASSWORD;
do_check_true(errorHandler.shouldReportError());
do_check_true(errorHandler.didReportProlongedError);
// Second time with prolonged error and without resetting
// didReportProlongedError, sync error should not be reported.
Status.resetSync();
setLastSync(PROLONGED_ERROR_DURATION);
errorHandler.dontIgnoreErrors = false;
Status.login = LOGIN_FAILED_NO_PASSWORD;
do_check_false(errorHandler.shouldReportError());
do_check_true(errorHandler.didReportProlongedError);
// Test non-network, prolonged, sync error reported // Test non-network, prolonged, sync error reported
Status.resetSync(); Status.resetSync();
setLastSync(PROLONGED_ERROR_DURATION); setLastSync(PROLONGED_ERROR_DURATION);
@ -261,14 +226,6 @@ add_identity_test(this, function test_shouldReportError() {
do_check_true(errorHandler.didReportProlongedError); do_check_true(errorHandler.didReportProlongedError);
errorHandler.didReportProlongedError = false; errorHandler.didReportProlongedError = false;
// Test non-network, non-prolonged, login error reported
Status.resetSync();
setLastSync(NON_PROLONGED_ERROR_DURATION);
errorHandler.dontIgnoreErrors = false;
Status.login = LOGIN_FAILED_NO_PASSWORD;
do_check_true(errorHandler.shouldReportError());
do_check_false(errorHandler.didReportProlongedError);
// Test non-network, non-prolonged, sync error reported // Test non-network, non-prolonged, sync error reported
Status.resetSync(); Status.resetSync();
setLastSync(NON_PROLONGED_ERROR_DURATION); setLastSync(NON_PROLONGED_ERROR_DURATION);
@ -409,7 +366,7 @@ add_task(async function test_login_syncAndReportErrors_non_network_error() {
// when calling syncAndReportErrors // when calling syncAndReportErrors
let server = EHTestsCommon.sync_httpd_setup(); let server = EHTestsCommon.sync_httpd_setup();
await EHTestsCommon.setUp(server); await EHTestsCommon.setUp(server);
Service.identity.resetSyncKey(); Service.identity.resetSyncKeyBundle();
let promiseObserved = promiseOneObserver("weave:ui:login:error"); let promiseObserved = promiseOneObserver("weave:ui:login:error");
@ -458,7 +415,7 @@ add_task(async function test_login_syncAndReportErrors_prolonged_non_network_err
// reported when calling syncAndReportErrors. // reported when calling syncAndReportErrors.
let server = EHTestsCommon.sync_httpd_setup(); let server = EHTestsCommon.sync_httpd_setup();
await EHTestsCommon.setUp(server); await EHTestsCommon.setUp(server);
Service.identity.resetSyncKey(); Service.identity.resetSyncKeyBundle();
let promiseObserved = promiseOneObserver("weave:ui:login:error"); let promiseObserved = promiseOneObserver("weave:ui:login:error");
@ -577,7 +534,7 @@ add_task(async function test_login_prolonged_non_network_error() {
// Test prolonged, non-network errors are reported // Test prolonged, non-network errors are reported
let server = EHTestsCommon.sync_httpd_setup(); let server = EHTestsCommon.sync_httpd_setup();
await EHTestsCommon.setUp(server); await EHTestsCommon.setUp(server);
Service.identity.resetSyncKey(); Service.identity.resetSyncKeyBundle();
let promiseObserved = promiseOneObserver("weave:ui:login:error"); let promiseObserved = promiseOneObserver("weave:ui:login:error");
@ -659,7 +616,7 @@ add_task(async function test_login_non_network_error() {
// Test non-network errors are reported // Test non-network errors are reported
let server = EHTestsCommon.sync_httpd_setup(); let server = EHTestsCommon.sync_httpd_setup();
await EHTestsCommon.setUp(server); await EHTestsCommon.setUp(server);
Service.identity.resetSyncKey(); Service.identity.resetSyncKeyBundle();
let promiseObserved = promiseOneObserver("weave:ui:login:error"); let promiseObserved = promiseOneObserver("weave:ui:login:error");

View File

@ -1,98 +0,0 @@
// We change this pref before anything else initializes
Services.prefs.setCharPref("identity.fxaccounts.auth.uri", "http://localhost");
// Test the FxAMigration module
Cu.import("resource://services-sync/FxaMigrator.jsm");
// Set our username pref early so sync initializes with the legacy provider.
Services.prefs.setCharPref("services.sync.username", "foo");
// And ensure all debug messages end up being printed.
Services.prefs.setCharPref("services.sync.log.appender.dump", "Debug");
// Now import sync
Cu.import("resource://services-sync/service.js");
Cu.import("resource://services-sync/record.js");
Cu.import("resource://services-sync/util.js");
// And reset the username.
Services.prefs.clearUserPref("services.sync.username");
Cu.import("resource://testing-common/services/sync/utils.js");
Cu.import("resource://testing-common/services/common/logging.js");
Cu.import("resource://testing-common/services/sync/rotaryengine.js");
const FXA_USERNAME = "someone@somewhere";
// Helpers
function configureLegacySync() {
let engine = new RotaryEngine(Service);
engine.enabled = true;
Svc.Prefs.set("registerEngines", engine.name);
Svc.Prefs.set("log.logger.engine.rotary", "Trace");
let contents = {
meta: {global: {engines: {rotary: {version: engine.version,
syncID: engine.syncID}}}},
crypto: {},
rotary: {}
};
const USER = "foo";
const PASSPHRASE = "abcdeabcdeabcdeabcdeabcdea";
setBasicCredentials(USER, "password", PASSPHRASE);
let onRequest = function(request, response) {
// ideally we'd only do this while a legacy user is configured, but WTH.
response.setHeader("x-weave-alert", JSON.stringify({code: "soft-eol"}));
}
let server = new SyncServer({onRequest});
server.registerUser(USER, "password");
server.createContents(USER, contents);
server.start();
Service.serverURL = server.baseURI;
Service.clusterURL = server.baseURI;
Service.identity.username = USER;
Service._updateCachedURLs();
Service.engineManager._engines[engine.name] = engine;
return [engine, server];
}
add_task(async function testMigrationUnlinks() {
// when we do a .startOver we want the new provider.
let oldValue = Services.prefs.getBoolPref("services.sync-testing.startOverKeepIdentity");
Services.prefs.setBoolPref("services.sync-testing.startOverKeepIdentity", false);
do_register_cleanup(() => {
Services.prefs.setBoolPref("services.sync-testing.startOverKeepIdentity", oldValue)
});
// Arrange for a legacy sync user.
configureLegacySync();
// Start a sync - this will cause an EOL notification which the migrator's
// observer will notice.
let promiseMigration = promiseOneObserver("fxa-migration:state-changed");
let promiseStartOver = promiseOneObserver("weave:service:start-over:finish");
_("Starting sync");
Service.sync();
_("Finished sync");
await promiseStartOver;
await promiseMigration;
// We should have seen the observer and Sync should no longer be configured.
Assert.ok(!Services.prefs.prefHasUserValue("services.sync.username"));
});
function run_test() {
initTestLogging();
do_register_cleanup(() => {
fxaMigrator.finalize();
Svc.Prefs.resetBranch("");
});
run_next_test();
}

View File

@ -1,64 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
Cu.import("resource://testing-common/services/sync/utils.js");
Cu.import("resource://services-sync/identity.js");
Cu.import("resource://services-sync/browserid_identity.js");
Cu.import("resource://services-sync/service.js");
function run_test() {
initTestLogging("Trace");
run_next_test();
}
add_task(async function test_startover() {
let oldValue = Services.prefs.getBoolPref("services.sync-testing.startOverKeepIdentity");
Services.prefs.setBoolPref("services.sync-testing.startOverKeepIdentity", false);
ensureLegacyIdentityManager();
await configureIdentity({username: "johndoe"});
// 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);
Service.serverURL = "https://localhost/";
Service.clusterURL = Service.serverURL;
Service.login();
// We should have a cluster URL
do_check_true(Service.clusterURL.length > 0);
// remember some stuff so we can reset it after.
let oldIdentity = Service.identity;
let oldClusterManager = Service._clusterManager;
let promiseStartOver = new Promise(resolve => {
Services.obs.addObserver(function observeStartOverFinished() {
Services.obs.removeObserver(observeStartOverFinished, "weave:service:start-over:finish");
resolve();
}, "weave:service:start-over:finish", false);
});
Service.startOver();
await promiseStartOver; // wait for the observer to fire.
// 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-testing.startOverKeepIdentity", oldValue);
});

View File

@ -4,7 +4,6 @@
Cu.import("resource://services-sync/constants.js"); Cu.import("resource://services-sync/constants.js");
Cu.import("resource://services-sync/engines/history.js"); Cu.import("resource://services-sync/engines/history.js");
Cu.import("resource://services-sync/engines.js"); Cu.import("resource://services-sync/engines.js");
Cu.import("resource://services-sync/identity.js");
Cu.import("resource://services-sync/record.js"); Cu.import("resource://services-sync/record.js");
Cu.import("resource://services-sync/service.js"); Cu.import("resource://services-sync/service.js");
Cu.import("resource://services-sync/util.js"); Cu.import("resource://services-sync/util.js");

View File

@ -135,16 +135,7 @@ add_task(async function hmac_error_during_node_reassignment() {
}; };
} }
function sameNodeHandler(request, response) {
// Set this so that _setCluster will think we've really changed.
let url = Service.serverURL.replace("localhost", "LOCALHOST");
_("Client requesting reassignment; pointing them to " + url);
response.setStatusLine(request.httpVersion, 200, "OK");
response.bodyOutputStream.write(url, url.length);
}
let handlers = { let handlers = {
"/user/1.0/foo/node/weave": sameNodeHandler,
"/1.1/foo/info/collections": collectionsHelper.handler, "/1.1/foo/info/collections": collectionsHelper.handler,
"/1.1/foo/storage/meta/global": upd("meta", global.handler()), "/1.1/foo/storage/meta/global": upd("meta", global.handler()),
"/1.1/foo/storage/crypto/keys": upd("crypto", keysWBO.handler()), "/1.1/foo/storage/crypto/keys": upd("crypto", keysWBO.handler()),

View File

@ -2,10 +2,11 @@
* http://creativecommons.org/publicdomain/zero/1.0/ */ * http://creativecommons.org/publicdomain/zero/1.0/ */
Cu.import("resource://services-sync/constants.js"); Cu.import("resource://services-sync/constants.js");
Cu.import("resource://services-sync/identity.js");
Cu.import("resource://services-sync/keys.js"); Cu.import("resource://services-sync/keys.js");
Cu.import("resource://services-sync/record.js"); Cu.import("resource://services-sync/record.js");
Cu.import("resource://services-sync/util.js"); Cu.import("resource://services-sync/util.js");
Cu.import("resource://services-sync/browserid_identity.js");
Cu.import("resource://testing-common/services/sync/utils.js");
var collectionKeys = new CollectionKeyManager(); var collectionKeys = new CollectionKeyManager();
@ -163,16 +164,16 @@ add_test(function test_keymanager() {
run_next_test(); run_next_test();
}); });
add_test(function test_collections_manager() { add_task(async function test_ensureLoggedIn() {
let log = Log.repository.getLogger("Test"); let log = Log.repository.getLogger("Test");
Log.repository.rootLogger.addAppender(new Log.DumpAppender()); Log.repository.rootLogger.addAppender(new Log.DumpAppender());
let identity = new IdentityManager(); let identityConfig = makeIdentityConfig();
let browseridManager = new BrowserIDManager();
configureFxAccountIdentity(browseridManager, identityConfig);
await browseridManager.ensureLoggedIn();
identity.account = "john@example.com"; let keyBundle = browseridManager.syncKeyBundle;
identity.syncKey = "a-bbbbb-ccccc-ddddd-eeeee-fffff";
let keyBundle = identity.syncKeyBundle;
/* /*
* Build a test version of storage/crypto/keys. * Build a test version of storage/crypto/keys.
@ -313,8 +314,6 @@ add_test(function test_collections_manager() {
do_check_array_eq(d4.changed, ["bar", "foo"]); do_check_array_eq(d4.changed, ["bar", "foo"]);
do_check_array_eq(d5.changed, ["baz", "foo"]); do_check_array_eq(d5.changed, ["baz", "foo"]);
do_check_array_eq(d6.changed, ["bar", "foo"]); do_check_array_eq(d6.changed, ["bar", "foo"]);
run_next_test();
}); });
function run_test() { function run_test() {

View File

@ -25,7 +25,6 @@ function run_test() {
Log.repository.getLogger("Sync.SyncScheduler").level = Log.Level.Trace; Log.repository.getLogger("Sync.SyncScheduler").level = Log.Level.Trace;
initTestLogging(); initTestLogging();
validate_all_future_pings(); validate_all_future_pings();
ensureLegacyIdentityManager();
Service.engineManager.register(RotaryEngine); Service.engineManager.register(RotaryEngine);
@ -59,35 +58,12 @@ function handleReassign(handler, req, resp) {
resp.bodyOutputStream.write(reassignBody, reassignBody.length); resp.bodyOutputStream.write(reassignBody, reassignBody.length);
} }
/** async function prepareServer() {
* A node assignment handler. let server = new SyncServer();
*/ server.registerUser("johndoe");
function installNodeHandler(server, next) { server.start();
let newNodeBody = server.baseURI; await configureIdentity({username: "johndoe"}, server);
function handleNodeRequest(req, resp) { return server;
_("Client made a request for a node reassignment.");
resp.setStatusLine(req.httpVersion, 200, "OK");
resp.setHeader("Content-Type", "text/plain");
resp.bodyOutputStream.write(newNodeBody, newNodeBody.length);
Utils.nextTick(next);
}
let nodePath = "/user/1.0/johndoe/node/weave";
server.server.registerPathHandler(nodePath, handleNodeRequest);
_("Registered node handler at " + nodePath);
}
function prepareServer() {
let deferred = PromiseUtils.defer();
configureIdentity({username: "johndoe"}).then(() => {
let server = new SyncServer();
server.registerUser("johndoe");
server.start();
Service.serverURL = server.baseURI;
Service.clusterURL = server.baseURI;
do_check_eq(Service.userAPIURI, server.baseURI + "user/1.0/");
deferred.resolve(server);
});
return deferred.promise;
} }
function getReassigned() { function getReassigned() {
@ -111,8 +87,19 @@ function getReassigned() {
async function syncAndExpectNodeReassignment(server, firstNotification, between, async function syncAndExpectNodeReassignment(server, firstNotification, between,
secondNotification, url) { secondNotification, url) {
let deferred = PromiseUtils.defer(); let deferred = PromiseUtils.defer();
let getTokenCount = 0;
let mockTSC = { // TokenServerClient
getTokenFromBrowserIDAssertion(uri, assertion, cb) {
getTokenCount++;
cb(null, {
endpoint: server.baseURI + "1.1/johndoe/"
});
},
};
Service.identity._tokenServerClient = mockTSC;
function onwards() { function onwards() {
let nodeFetched = false;
function onFirstSync() { function onFirstSync() {
_("First sync completed."); _("First sync completed.");
Svc.Obs.remove(firstNotification, onFirstSync); Svc.Obs.remove(firstNotification, onFirstSync);
@ -120,17 +107,6 @@ async function syncAndExpectNodeReassignment(server, firstNotification, between,
do_check_eq(Service.clusterURL, ""); do_check_eq(Service.clusterURL, "");
// Track whether we fetched node/weave. We want to wait for the second
// sync to finish so that we're cleaned up for the next test, so don't
// run_next_test in the node handler.
nodeFetched = false;
// Verify that the client requests a node reassignment.
// Install a node handler to watch for these requests.
installNodeHandler(server, function() {
nodeFetched = true;
});
// Allow for tests to clean up error conditions. // Allow for tests to clean up error conditions.
between(); between();
} }
@ -143,7 +119,7 @@ async function syncAndExpectNodeReassignment(server, firstNotification, between,
// before we proceed. // before we proceed.
waitForZeroTimer(function() { waitForZeroTimer(function() {
_("Second sync nextTick."); _("Second sync nextTick.");
do_check_true(nodeFetched); do_check_eq(getTokenCount, 1);
Service.startOver(); Service.startOver();
server.stop(deferred.resolve); server.stop(deferred.resolve);
}); });
@ -298,9 +274,19 @@ add_task(async function test_loop_avoidance_storage() {
let secondNotification = "weave:service:login:error"; let secondNotification = "weave:service:login:error";
let thirdNotification = "weave:service:sync:finish"; let thirdNotification = "weave:service:sync:finish";
let nodeFetched = false;
let deferred = PromiseUtils.defer(); let deferred = PromiseUtils.defer();
let getTokenCount = 0;
let mockTSC = { // TokenServerClient
getTokenFromBrowserIDAssertion(uri, assertion, cb) {
getTokenCount++;
cb(null, {
endpoint: server.baseURI + "1.1/johndoe/"
});
},
};
Service.identity._tokenServerClient = mockTSC;
// Track the time. We want to make sure the duration between the first and // Track the time. We want to make sure the duration between the first and
// second sync is small, and then that the duration between second and third // second sync is small, and then that the duration between second and third
// is set to be large. // is set to be large.
@ -316,17 +302,6 @@ add_task(async function test_loop_avoidance_storage() {
// We got a 401 mid-sync, and set the pref accordingly. // We got a 401 mid-sync, and set the pref accordingly.
do_check_true(Services.prefs.getBoolPref("services.sync.lastSyncReassigned")); do_check_true(Services.prefs.getBoolPref("services.sync.lastSyncReassigned"));
// Track whether we fetched node/weave. We want to wait for the second
// sync to finish so that we're cleaned up for the next test, so don't
// run_next_test in the node handler.
nodeFetched = false;
// Verify that the client requests a node reassignment.
// Install a node handler to watch for these requests.
installNodeHandler(server, function() {
nodeFetched = true;
});
// Update the timestamp. // Update the timestamp.
now = Date.now(); now = Date.now();
} }
@ -371,7 +346,7 @@ add_task(async function test_loop_avoidance_storage() {
waitForZeroTimer(function() { waitForZeroTimer(function() {
_("Third sync nextTick."); _("Third sync nextTick.");
do_check_false(getReassigned()); do_check_false(getReassigned());
do_check_true(nodeFetched); do_check_eq(getTokenCount, 2);
Service.startOver(); Service.startOver();
server.stop(deferred.resolve); server.stop(deferred.resolve);
}); });
@ -395,6 +370,17 @@ add_task(async function test_loop_avoidance_engine() {
engine.enabled = true; engine.enabled = true;
let deferred = PromiseUtils.defer(); let deferred = PromiseUtils.defer();
let getTokenCount = 0;
let mockTSC = { // TokenServerClient
getTokenFromBrowserIDAssertion(uri, assertion, cb) {
getTokenCount++;
cb(null, {
endpoint: server.baseURI + "1.1/johndoe/"
});
},
};
Service.identity._tokenServerClient = mockTSC;
// We need the server to be correctly set up prior to experimenting. Do this // We need the server to be correctly set up prior to experimenting. Do this
// through a sync. // through a sync.
let global = {syncID: Service.syncID, let global = {syncID: Service.syncID,
@ -435,8 +421,6 @@ add_task(async function test_loop_avoidance_engine() {
let secondNotification = "weave:service:sync:finish"; let secondNotification = "weave:service:sync:finish";
let thirdNotification = "weave:service:sync:finish"; let thirdNotification = "weave:service:sync:finish";
let nodeFetched = false;
// Track the time. We want to make sure the duration between the first and // Track the time. We want to make sure the duration between the first and
// second sync is small, and then that the duration between second and third // second sync is small, and then that the duration between second and third
// is set to be large. // is set to be large.
@ -455,17 +439,6 @@ add_task(async function test_loop_avoidance_engine() {
// We got a 401 mid-sync, and set the pref accordingly. // We got a 401 mid-sync, and set the pref accordingly.
do_check_true(Services.prefs.getBoolPref("services.sync.lastSyncReassigned")); do_check_true(Services.prefs.getBoolPref("services.sync.lastSyncReassigned"));
// Track whether we fetched node/weave. We want to wait for the second
// sync to finish so that we're cleaned up for the next test, so don't
// run_next_test in the node handler.
nodeFetched = false;
// Verify that the client requests a node reassignment.
// Install a node handler to watch for these requests.
installNodeHandler(server, function() {
nodeFetched = true;
});
// Update the timestamp. // Update the timestamp.
now = Date.now(); now = Date.now();
} }
@ -511,7 +484,7 @@ add_task(async function test_loop_avoidance_engine() {
waitForZeroTimer(function() { waitForZeroTimer(function() {
_("Third sync nextTick."); _("Third sync nextTick.");
do_check_false(getReassigned()); do_check_false(getReassigned());
do_check_true(nodeFetched); do_check_eq(getTokenCount, 2);
afterSuccessfulSync(); afterSuccessfulSync();
}); });
} }

View File

@ -2,7 +2,6 @@
http://creativecommons.org/publicdomain/zero/1.0/ */ http://creativecommons.org/publicdomain/zero/1.0/ */
Cu.import("resource://services-sync/record.js"); 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/resource.js");
Cu.import("resource://services-sync/service.js"); Cu.import("resource://services-sync/service.js");
Cu.import("resource://services-sync/util.js"); Cu.import("resource://services-sync/util.js");

View File

@ -3,9 +3,11 @@
Cu.import("resource://gre/modules/Log.jsm"); Cu.import("resource://gre/modules/Log.jsm");
Cu.import("resource://services-common/observers.js"); Cu.import("resource://services-common/observers.js");
Cu.import("resource://services-sync/identity.js");
Cu.import("resource://services-sync/resource.js"); Cu.import("resource://services-sync/resource.js");
Cu.import("resource://services-sync/status.js");
Cu.import("resource://services-sync/util.js"); Cu.import("resource://services-sync/util.js");
Cu.import("resource://services-sync/browserid_identity.js");
Cu.import("resource://testing-common/services/sync/utils.js");
var logger; var logger;
@ -26,7 +28,7 @@ function server_open(metadata, response) {
function server_protected(metadata, response) { function server_protected(metadata, response) {
let body; let body;
if (basic_auth_matches(metadata, "guest", "guest")) { if (has_hawk_header(metadata)) {
body = "This path exists and is protected"; body = "This path exists and is protected";
response.setStatusLine(metadata.httpVersion, 200, "OK, authorized"); response.setStatusLine(metadata.httpVersion, 200, "OK, authorized");
response.setHeader("WWW-Authenticate", 'Basic realm="secret"', false); response.setHeader("WWW-Authenticate", 'Basic realm="secret"', false);
@ -229,11 +231,6 @@ function run_test() {
"Parse fail: Response body starts: \"\"This path exists\"\"."); "Parse fail: Response body starts: \"\"This path exists\"\".");
logger.debug = dbg; logger.debug = dbg;
_("Test that the BasicAuthenticator doesn't screw up header case.");
let res1 = new Resource(server.baseURI + "/foo");
res1.setHeader("Authorization", "Basic foobar");
do_check_eq(res1.headers["authorization"], "Basic foobar");
_("GET a password protected resource (test that it'll fail w/o pass, no throw)"); _("GET a password protected resource (test that it'll fail w/o pass, no throw)");
let res2 = new Resource(server.baseURI + "/protected"); let res2 = new Resource(server.baseURI + "/protected");
content = res2.get(); content = res2.get();
@ -243,8 +240,10 @@ function run_test() {
_("GET a password protected resource"); _("GET a password protected resource");
let res3 = new Resource(server.baseURI + "/protected"); let res3 = new Resource(server.baseURI + "/protected");
let identity = new IdentityManager(); let identityConfig = makeIdentityConfig();
let auth = identity.getBasicResourceAuthenticator("guest", "guest"); let browseridManager = Status._authManager;
configureFxAccountIdentity(browseridManager, identityConfig);
let auth = browseridManager.getResourceAuthenticator();
res3.authenticator = auth; res3.authenticator = auth;
do_check_eq(res3.authenticator, auth); do_check_eq(res3.authenticator, auth);
content = res3.get(); content = res3.get();

View File

@ -3,9 +3,10 @@
Cu.import("resource://gre/modules/Log.jsm"); Cu.import("resource://gre/modules/Log.jsm");
Cu.import("resource://services-common/observers.js"); Cu.import("resource://services-common/observers.js");
Cu.import("resource://services-sync/identity.js");
Cu.import("resource://services-sync/resource.js"); Cu.import("resource://services-sync/resource.js");
Cu.import("resource://services-sync/util.js"); Cu.import("resource://services-sync/util.js");
Cu.import("resource://services-sync/browserid_identity.js");
Cu.import("resource://testing-common/services/sync/utils.js");
var logger; var logger;
@ -26,7 +27,7 @@ function server_open(metadata, response) {
function server_protected(metadata, response) { function server_protected(metadata, response) {
let body; let body;
if (basic_auth_matches(metadata, "guest", "guest")) { if (has_hawk_header(metadata, "guest", "guest")) {
body = "This path exists and is protected"; body = "This path exists and is protected";
response.setStatusLine(metadata.httpVersion, 200, "OK, authorized"); response.setStatusLine(metadata.httpVersion, 200, "OK, authorized");
response.setHeader("WWW-Authenticate", 'Basic realm="secret"', false); response.setHeader("WWW-Authenticate", 'Basic realm="secret"', false);
@ -320,8 +321,10 @@ add_test(function test_get_protected_fail() {
add_test(function test_get_protected_success() { add_test(function test_get_protected_success() {
_("GET a password protected resource"); _("GET a password protected resource");
let identity = new IdentityManager(); let identityConfig = makeIdentityConfig();
let auth = identity.getBasicResourceAuthenticator("guest", "guest"); let browseridManager = new BrowserIDManager();
configureFxAccountIdentity(browseridManager, identityConfig);
let auth = browseridManager.getResourceAuthenticator();
let res3 = new AsyncResource(server.baseURI + "/protected"); let res3 = new AsyncResource(server.baseURI + "/protected");
res3.authenticator = auth; res3.authenticator = auth;
do_check_eq(res3.authenticator, auth); do_check_eq(res3.authenticator, auth);

View File

@ -18,7 +18,6 @@ add_task(async function test_urls() {
do_check_eq(Service.metaURL, undefined); do_check_eq(Service.metaURL, undefined);
_("The 'clusterURL' attribute updates preferences and cached URLs."); _("The 'clusterURL' attribute updates preferences and cached URLs.");
Service.identity.username = "johndoe";
// Since we don't have a cluster URL yet, these will still not be defined. // Since we don't have a cluster URL yet, these will still not be defined.
do_check_eq(Service.infoURL, undefined); do_check_eq(Service.infoURL, undefined);
@ -48,11 +47,6 @@ add_task(async function test_urls() {
do_check_eq(Service.pwResetURL, do_check_eq(Service.pwResetURL,
"http://weave.server/weave-password-reset"); "http://weave.server/weave-password-reset");
_("Empty/false value for 'username' resets preference.");
Service.identity.username = "";
do_check_eq(Svc.Prefs.get("username"), undefined);
do_check_eq(Service.identity.username, null);
_("The 'serverURL' attributes updates/resets preferences."); _("The 'serverURL' attributes updates/resets preferences.");
Service.serverURL = "http://different.auth.node/"; Service.serverURL = "http://different.auth.node/";

View File

@ -1,80 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
Cu.import("resource://gre/modules/Log.jsm");
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() {
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) {
return function(request, response) {
requestBody = readBytesFromInputStream(request.bodyInputStream);
response.setStatusLine(request.httpVersion, statusCode, status);
response.bodyOutputStream.write(body, body.length);
};
}
try {
Service.baseURI = "http://localhost:9999/";
Service.serverURL = "http://localhost:9999/";
setBasicCredentials("johndoe", "ilovejane");
_("changePassword() returns false for a network error, the password won't change.");
let res = Service.changePassword("ILoveJane83");
do_check_false(res);
do_check_eq(Service.identity.basicPassword, "ilovejane");
_("Let's fire up the server and actually change the password.");
server = httpd_setup({
"/user/1.0/johndoe/password": send(200, "OK", ""),
"/user/1.0/janedoe/password": send(401, "Unauthorized", "Forbidden!")
});
Service.serverURL = server.baseURI;
res = Service.changePassword("ILoveJane83");
do_check_true(res);
do_check_eq(Service.identity.basicPassword, "ILoveJane83");
do_check_eq(requestBody, "ILoveJane83");
_("Make sure the password has been persisted in the login manager.");
let logins = Services.logins.findLogins({}, PWDMGR_HOST, null,
PWDMGR_PASSWORD_REALM);
do_check_eq(logins.length, 1);
do_check_eq(logins[0].password, "ILoveJane83");
_("A non-ASCII password is UTF-8 encoded.");
const moneyPassword = "moneyislike$£¥";
res = Service.changePassword(moneyPassword);
do_check_true(res);
do_check_eq(Service.identity.basicPassword, Utils.encodeUTF8(moneyPassword));
do_check_eq(requestBody, Utils.encodeUTF8(moneyPassword));
_("changePassword() returns false for a server error, the password won't change.");
Services.logins.removeAllLogins();
setBasicCredentials("janedoe", "ilovejohn");
res = Service.changePassword("ILoveJohn86");
do_check_false(res);
do_check_eq(Service.identity.basicPassword, "ilovejohn");
} finally {
Svc.Prefs.resetBranch("");
Services.logins.removeAllLogins();
server.stop(run_next_test);
}
});

View File

@ -1,41 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* 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")
});
try {
Service.serverURL = server.baseURI;
_("A 404 will be recorded as 'generic-server-error'");
do_check_eq(Service.checkAccount("jimdoe"), "generic-server-error");
_("Account that's available.");
do_check_eq(Service.checkAccount("john@doe.com"), "available");
_("Account that's not available.");
do_check_eq(Service.checkAccount("jane@doe.com"), "notAvailable");
_("Username fallback: Account that's not available.");
do_check_eq(Service.checkAccount("johndoe"), "notAvailable");
_("Username fallback: Account that's available.");
do_check_eq(Service.checkAccount("janedoe"), "available");
} finally {
Svc.Prefs.resetBranch("");
server.stop(do_test_finished);
}
}

View File

@ -1,6 +1,7 @@
/* Any copyright is dedicated to the Public Domain. /* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */ http://creativecommons.org/publicdomain/zero/1.0/ */
Cu.import("resource://gre/modules/PromiseUtils.jsm");
Cu.import("resource://services-sync/service.js"); Cu.import("resource://services-sync/service.js");
Cu.import("resource://services-sync/util.js"); Cu.import("resource://services-sync/util.js");
Cu.import("resource://testing-common/services/sync/utils.js"); Cu.import("resource://testing-common/services/sync/utils.js");
@ -17,9 +18,14 @@ function do_check_throws(func) {
add_test(function test_findCluster() { add_test(function test_findCluster() {
_("Test Service._findCluster()"); _("Test Service._findCluster()");
let server;
ensureLegacyIdentityManager();
try { try {
let whenReadyToAuthenticate = PromiseUtils.defer();
Service.identity.whenReadyToAuthenticate = whenReadyToAuthenticate;
whenReadyToAuthenticate.resolve(true);
Service.identity._ensureValidToken = () => Promise.reject(new Error("Connection refused"));
_("_findCluster() throws on network errors (e.g. connection refused)."); _("_findCluster() throws on network errors (e.g. connection refused).");
do_check_throws(function() { do_check_throws(function() {
Service.serverURL = "http://dummy:9000/"; Service.serverURL = "http://dummy:9000/";
@ -27,64 +33,27 @@ add_test(function test_findCluster() {
Service._clusterManager._findCluster(); Service._clusterManager._findCluster();
}); });
server = httpd_setup({ Service.identity._ensureValidToken = () => Promise.resolve(true);
"/user/1.0/johndoe/node/weave": httpd_handler(200, "OK", "http://weave.user.node/"), Service.identity._token = { endpoint: "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"),
"/user/1.0/joedoe/node/weave": httpd_handler(500, "Server Error", "Server Error")
});
Service.serverURL = server.baseURI;
Service.identity.account = "johndoe";
_("_findCluster() returns the user's cluster node"); _("_findCluster() returns the user's cluster node");
let cluster = Service._clusterManager._findCluster(); let cluster = Service._clusterManager._findCluster();
do_check_eq(cluster, "http://weave.user.node/"); do_check_eq(cluster, "http://weave.user.node/");
_("A 'null' response is converted to null.");
Service.identity.account = "jimdoe";
cluster = Service._clusterManager._findCluster();
do_check_eq(cluster, null);
_("If a 404 is encountered, the server URL is taken as the cluster URL");
Service.identity.account = "janedoe";
cluster = Service._clusterManager._findCluster();
do_check_eq(cluster, Service.serverURL);
_("A 400 response will throw an error.");
Service.identity.account = "juliadoe";
do_check_throws(function() {
Service._clusterManager._findCluster();
});
_("Any other server response (e.g. 500) will throw an error.");
Service.identity.account = "joedoe";
do_check_throws(function() {
Service._clusterManager._findCluster();
});
} finally { } finally {
Svc.Prefs.resetBranch(""); Svc.Prefs.resetBranch("");
if (server) { run_next_test();
server.stop(run_next_test);
}
} }
}); });
add_test(function test_setCluster() { add_test(function test_setCluster() {
_("Test Service._setCluster()"); _("Test Service._setCluster()");
let 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")
});
try { try {
Service.serverURL = server.baseURI;
Service.identity.account = "johndoe";
_("Check initial state."); _("Check initial state.");
do_check_eq(Service.clusterURL, ""); do_check_eq(Service.clusterURL, "");
Service._clusterManager._findCluster = () => "http://weave.user.node/";
_("Set the cluster URL."); _("Set the cluster URL.");
do_check_true(Service._clusterManager.setCluster()); do_check_true(Service._clusterManager.setCluster());
do_check_eq(Service.clusterURL, "http://weave.user.node/"); do_check_eq(Service.clusterURL, "http://weave.user.node/");
@ -94,13 +63,13 @@ add_test(function test_setCluster() {
do_check_eq(Service.clusterURL, "http://weave.user.node/"); do_check_eq(Service.clusterURL, "http://weave.user.node/");
_("A 'null' response won't make a difference either."); _("A 'null' response won't make a difference either.");
Service.identity.account = "jimdoe"; Service._clusterManager._findCluster = () => null;
do_check_false(Service._clusterManager.setCluster()); do_check_false(Service._clusterManager.setCluster());
do_check_eq(Service.clusterURL, "http://weave.user.node/"); do_check_eq(Service.clusterURL, "http://weave.user.node/");
} finally { } finally {
Svc.Prefs.resetBranch(""); Svc.Prefs.resetBranch("");
server.stop(run_next_test); run_next_test();
} }
}); });

View File

@ -13,9 +13,7 @@ Cu.import("resource://testing-common/services/sync/utils.js");
Service.engineManager.register(TabEngine); Service.engineManager.register(TabEngine);
add_test(function v4_upgrade() { add_task(async function v4_upgrade() {
let passphrase = "abcdeabcdeabcdeabcdeabcdea";
let clients = new ServerCollection(); let clients = new ServerCollection();
let meta_global = new ServerWBO("global"); let meta_global = new ServerWBO("global");
@ -43,8 +41,6 @@ add_test(function v4_upgrade() {
"/1.1/johndoe/storage/prefs": new ServerCollection().handler() "/1.1/johndoe/storage/prefs": new ServerCollection().handler()
}); });
ensureLegacyIdentityManager();
try { try {
_("Set up some tabs."); _("Set up some tabs.");
@ -68,7 +64,9 @@ add_test(function v4_upgrade() {
_("Logging in."); _("Logging in.");
Service.serverURL = server.baseURI; Service.serverURL = server.baseURI;
Service.login("johndoe", "ilovejane", passphrase); await configureIdentity({ "username": "johndoe" }, server);
Service.login();
do_check_true(Service.isLoggedIn); do_check_true(Service.isLoggedIn);
Service.verifyAndFetchSymmetricKeys(); Service.verifyAndFetchSymmetricKeys();
do_check_true(Service._remoteSetup()); do_check_true(Service._remoteSetup());
@ -105,7 +103,7 @@ add_test(function v4_upgrade() {
"storageVersion": STORAGE_VERSION}); "storageVersion": STORAGE_VERSION});
collections.meta = Date.now() / 1000; collections.meta = Date.now() / 1000;
Service.recordManager.set(Service.metaURL, meta_global); Service.recordManager.set(Service.metaURL, meta_global);
Service.login("johndoe", "ilovejane", passphrase); Service.login();
do_check_true(Service.isLoggedIn); do_check_true(Service.isLoggedIn);
Service.sync(); Service.sync();
do_check_true(Service.isLoggedIn); do_check_true(Service.isLoggedIn);
@ -168,7 +166,7 @@ add_test(function v4_upgrade() {
let oldClientsModified = collections.clients; let oldClientsModified = collections.clients;
let oldTabsModified = collections.tabs; let oldTabsModified = collections.tabs;
Service.login("johndoe", "ilovejane", passphrase); Service.login();
Service.sync(); Service.sync();
_("New key should have forced upload of data."); _("New key should have forced upload of data.");
_("Tabs: " + oldTabsModified + " < " + collections.tabs); _("Tabs: " + oldTabsModified + " < " + collections.tabs);
@ -184,13 +182,11 @@ add_test(function v4_upgrade() {
} finally { } finally {
Svc.Prefs.resetBranch(""); Svc.Prefs.resetBranch("");
server.stop(run_next_test); await promiseStopServer(server);
} }
}); });
add_test(function v5_upgrade() { add_task(async function v5_upgrade() {
let passphrase = "abcdeabcdeabcdeabcdeabcdea";
// Tracking info/collections. // Tracking info/collections.
let collectionsHelper = track_collections_helper(); let collectionsHelper = track_collections_helper();
let upd = collectionsHelper.with_updated_collection; let upd = collectionsHelper.with_updated_collection;
@ -232,16 +228,17 @@ add_test(function v5_upgrade() {
Service.status.resetSync(); Service.status.resetSync();
setBasicCredentials("johndoe", "ilovejane", passphrase);
Service.serverURL = server.baseURI + "/"; Service.serverURL = server.baseURI + "/";
Service.clusterURL = server.baseURI + "/"; Service.clusterURL = server.baseURI + "/";
await configureIdentity({ "username": "johndoe" }, server);
// Test an upgrade where the contents of the server would cause us to error // Test an upgrade where the contents of the server would cause us to error
// -- keys decrypted with a different sync key, for example. // -- keys decrypted with a different sync key, for example.
_("Testing v4 -> v5 (or similar) upgrade."); _("Testing v4 -> v5 (or similar) upgrade.");
function update_server_keys(syncKeyBundle, wboName, collWBO) { function update_server_keys(syncKeyBundle, wboName, collWBO) {
generateNewKeys(Service.collectionKeys); generateNewKeys(Service.collectionKeys);
serverKeys = Service.collectionKeys.asWBO("crypto", wboName); let serverKeys = Service.collectionKeys.asWBO("crypto", wboName);
serverKeys.encrypt(syncKeyBundle); serverKeys.encrypt(syncKeyBundle);
let res = Service.resource(Service.storageURL + collWBO); let res = Service.resource(Service.storageURL + collWBO);
do_check_true(serverKeys.upload(res).success); do_check_true(serverKeys.upload(res).success);
@ -269,7 +266,7 @@ add_test(function v5_upgrade() {
_("Logging in."); _("Logging in.");
try { try {
Service.login("johndoe", "ilovejane", passphrase); Service.login();
} catch (e) { } catch (e) {
_("Exception: " + e); _("Exception: " + e);
} }
@ -282,7 +279,7 @@ add_test(function v5_upgrade() {
} finally { } finally {
Svc.Prefs.resetBranch(""); Svc.Prefs.resetBranch("");
server.stop(run_next_test); await promiseStopServer(server);
} }
}); });

View File

@ -10,8 +10,7 @@ Cu.import("resource://testing-common/services/sync/utils.js");
function login_handling(handler) { function login_handling(handler) {
return function(request, response) { return function(request, response) {
if (basic_auth_matches(request, "johndoe", "ilovejane") || if (has_hawk_header(request)) {
basic_auth_matches(request, "janedoe", "ilovejohn")) {
handler(request, response); handler(request, response);
} else { } else {
let body = "Unauthorized"; let body = "Unauthorized";
@ -64,12 +63,11 @@ function setup() {
return server; return server;
} }
add_test(function test_login_logout() { add_task(async function test_login_logout() {
let server = setup(); let server = setup();
try { try {
_("Force the initial state."); _("Force the initial state.");
ensureLegacyIdentityManager();
Service.status.service = STATUS_OK; Service.status.service = STATUS_OK;
do_check_eq(Service.status.service, STATUS_OK); do_check_eq(Service.status.service, STATUS_OK);
@ -79,42 +77,9 @@ add_test(function test_login_logout() {
do_check_eq(Service.status.login, LOGIN_FAILED_NO_USERNAME); do_check_eq(Service.status.login, LOGIN_FAILED_NO_USERNAME);
do_check_false(Service.isLoggedIn); do_check_false(Service.isLoggedIn);
_("Try again with username and password set."); _("Try again with a configured account");
Service.identity.account = "johndoe"; await configureIdentity({ username: "johndoe" }, server);
Service.identity.basicPassword = "ilovejane";
Service.login(); Service.login();
do_check_eq(Service.status.service, CLIENT_NOT_CONFIGURED);
do_check_eq(Service.status.login, LOGIN_FAILED_NO_PASSPHRASE);
do_check_false(Service.isLoggedIn);
_("Success if passphrase is set.");
Service.identity.syncKey = "foo";
Service.login();
do_check_eq(Service.status.service, STATUS_OK);
do_check_eq(Service.status.login, LOGIN_SUCCEEDED);
do_check_true(Service.isLoggedIn);
_("We can also pass username, password and passphrase to login().");
Service.login("janedoe", "incorrectpassword", "bar");
setBasicCredentials("janedoe", "incorrectpassword", "bar");
do_check_eq(Service.status.service, LOGIN_FAILED);
do_check_eq(Service.status.login, LOGIN_FAILED_LOGIN_REJECTED);
do_check_false(Service.isLoggedIn);
_("Try again with correct password.");
Service.login("janedoe", "ilovejohn");
do_check_eq(Service.status.service, STATUS_OK);
do_check_eq(Service.status.login, LOGIN_SUCCEEDED);
do_check_true(Service.isLoggedIn);
_("Calling login() with parameters when the client is unconfigured sends notification.");
let notified = false;
Svc.Obs.add("weave:service:setup-complete", function() {
notified = true;
});
setBasicCredentials(null, null, null);
Service.login("janedoe", "ilovejohn", "bar");
do_check_true(notified);
do_check_eq(Service.status.service, STATUS_OK); do_check_eq(Service.status.service, STATUS_OK);
do_check_eq(Service.status.login, LOGIN_SUCCEEDED); do_check_eq(Service.status.login, LOGIN_SUCCEEDED);
do_check_true(Service.isLoggedIn); do_check_true(Service.isLoggedIn);
@ -129,13 +94,13 @@ add_test(function test_login_logout() {
} finally { } finally {
Svc.Prefs.resetBranch(""); Svc.Prefs.resetBranch("");
server.stop(run_next_test); await promiseStopServer(server);
} }
}); });
add_test(function test_login_on_sync() { add_task(async function test_login_on_sync() {
let server = setup(); let server = setup();
setBasicCredentials("johndoe", "ilovejane", "bar"); await configureIdentity({ username: "johndoe" }, server);
try { try {
_("Sync calls login."); _("Sync calls login.");
@ -197,13 +162,7 @@ add_test(function test_login_on_sync() {
// Testing exception handling if master password dialog is canceled. // Testing exception handling if master password dialog is canceled.
// Do this by monkeypatching. // Do this by monkeypatching.
let oldGetter = Service.identity.__lookupGetter__("syncKey"); Service.identity.unlockAndVerifyAuthState = () => Promise.resolve(MASTER_PASSWORD_LOCKED);
let oldSetter = Service.identity.__lookupSetter__("syncKey");
_("Old passphrase function is " + oldGetter);
Service.identity.__defineGetter__("syncKey",
function() {
throw "User canceled Master Password entry";
});
let cSTCalled = false; let cSTCalled = false;
let lockedSyncCalled = false; let lockedSyncCalled = false;
@ -225,14 +184,11 @@ add_test(function test_login_on_sync() {
do_check_true(cSTCalled); do_check_true(cSTCalled);
do_check_false(lockedSyncCalled); do_check_false(lockedSyncCalled);
Service.identity.__defineGetter__("syncKey", oldGetter);
Service.identity.__defineSetter__("syncKey", oldSetter);
// N.B., a bunch of methods are stubbed at this point. Be careful putting // N.B., a bunch of methods are stubbed at this point. Be careful putting
// new tests after this point! // new tests after this point!
} finally { } finally {
Svc.Prefs.resetBranch(""); Svc.Prefs.resetBranch("");
server.stop(run_next_test); await promiseStopServer(server);
} }
}); });

View File

@ -1,94 +0,0 @@
/* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */
Cu.import("resource://services-sync/resource.js");
Cu.import("resource://services-sync/util.js");
Cu.import("resource://services-sync/service.js");
Cu.import("resource://testing-common/services/sync/utils.js");
const JAPANESE = "\u34ff\u35ff\u36ff\u37ff";
const APPLES = "\uf8ff\uf8ff\uf8ff\uf8ff";
const LOWBYTES = "\xff\xff\xff\xff";
// Poor man's /etc/passwd. Static since there's no btoa()/atob() in xpcshell.
var basicauth = {};
basicauth[LOWBYTES] = "Basic am9obmRvZTr/////";
basicauth[Utils.encodeUTF8(JAPANESE)] = "Basic am9obmRvZTrjk7/jl7/jm7/jn78=";
// Global var for the server password, read by info_collections(),
// modified by change_password().
var server_password;
function login_handling(handler) {
return function(request, response) {
let basic = basicauth[server_password];
if (basic && (request.getHeader("Authorization") == basic)) {
handler(request, response);
} else {
let body = "Unauthorized";
response.setStatusLine(request.httpVersion, 401, "Unauthorized");
response.setHeader("WWW-Authenticate", 'Basic realm="secret"', false);
response.bodyOutputStream.write(body, body.length);
}
};
}
function change_password(request, response) {
let body, statusCode, status;
let basic = basicauth[server_password];
if (basic && (request.getHeader("Authorization") == basic)) {
server_password = readBytesFromInputStream(request.bodyInputStream);
body = "";
statusCode = 200;
status = "OK";
} else {
statusCode = 401;
body = status = "Unauthorized";
}
response.setStatusLine(request.httpVersion, statusCode, status);
response.setHeader("WWW-Authenticate", 'Basic realm="secret"', false);
response.bodyOutputStream.write(body, body.length);
}
function run_test() {
initTestLogging("Trace");
let collectionsHelper = track_collections_helper();
let upd = collectionsHelper.with_updated_collection;
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
});
setBasicCredentials("johndoe", JAPANESE, "irrelevant");
Service.serverURL = server.baseURI;
try {
_("Try to log in with the password.");
server_password = "foobar";
do_check_false(Service.verifyLogin());
do_check_eq(server_password, "foobar");
_("Make the server password the low byte version of our password.");
server_password = LOWBYTES;
do_check_false(Service.verifyLogin());
do_check_eq(server_password, LOWBYTES);
_("Can't use a password that has the same low bytes as ours.");
server_password = Utils.encodeUTF8(JAPANESE);
Service.identity.basicPassword = APPLES;
do_check_false(Service.verifyLogin());
do_check_eq(server_password, Utils.encodeUTF8(JAPANESE));
} finally {
server.stop(do_test_finished);
Svc.Prefs.resetBranch("");
}
}

View File

@ -1,46 +0,0 @@
/* 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");
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);
logins = Services.logins.findLogins({}, PWDMGR_HOST, null,
PWDMGR_PASSPHRASE_REALM);
do_check_eq(logins.length, 0);
_("Persist logins to the login service");
Service.persistLogin();
_("The password has been persisted in the login service.");
logins = Services.logins.findLogins({}, PWDMGR_HOST, null,
PWDMGR_PASSWORD_REALM);
do_check_eq(logins.length, 1);
do_check_eq(logins[0].username, "johndoe");
do_check_eq(logins[0].password, "ilovejane");
_("The passphrase has been persisted in the login service.");
logins = Services.logins.findLogins({}, PWDMGR_HOST, null,
PWDMGR_PASSPHRASE_REALM);
do_check_eq(logins.length, 1);
do_check_eq(logins[0].username, "johndoe");
do_check_eq(logins[0].password, "abbbbbcccccdddddeeeeefffff");
} finally {
Svc.Prefs.resetBranch("");
Services.logins.removeAllLogins();
}
}

View File

@ -33,7 +33,6 @@ add_identity_test(this, async function test_resetLocalData() {
Service.status.enforceBackoff = true; Service.status.enforceBackoff = true;
Service.status.backoffInterval = 42; Service.status.backoffInterval = 42;
Service.status.minimumNextSync = 23; Service.status.minimumNextSync = 23;
Service.persistLogin();
// Verify set up. // Verify set up.
do_check_eq(Service.status.checkSetup(), STATUS_OK); do_check_eq(Service.status.checkSetup(), STATUS_OK);
@ -52,8 +51,6 @@ add_identity_test(this, async function test_resetLocalData() {
// Verify the site was nuked from orbit. // Verify the site was nuked from orbit.
do_check_eq(Svc.Prefs.get("username"), undefined); do_check_eq(Svc.Prefs.get("username"), undefined);
do_check_eq(Service.identity.basicPassword, null);
do_check_eq(Service.identity.syncKey, null);
do_check_eq(Service.status.service, CLIENT_NOT_CONFIGURED); do_check_eq(Service.status.service, CLIENT_NOT_CONFIGURED);
do_check_false(Service.status.enforceBackoff); do_check_false(Service.status.enforceBackoff);

View File

@ -9,7 +9,7 @@ Cu.import("resource://services-sync/util.js");
Cu.import("resource://testing-common/services/sync/fakeservices.js"); Cu.import("resource://testing-common/services/sync/fakeservices.js");
Cu.import("resource://testing-common/services/sync/utils.js"); Cu.import("resource://testing-common/services/sync/utils.js");
function run_test() { add_task(async function run_test() {
validate_all_future_pings(); validate_all_future_pings();
Log.repository.rootLogger.addAppender(new Log.DumpAppender()); Log.repository.rootLogger.addAppender(new Log.DumpAppender());
@ -75,7 +75,6 @@ function run_test() {
try { try {
_("Log in."); _("Log in.");
ensureLegacyIdentityManager();
Service.serverURL = server.baseURI; Service.serverURL = server.baseURI;
_("Checking Status.sync with no credentials."); _("Checking Status.sync with no credentials.");
@ -83,18 +82,9 @@ function run_test() {
do_check_eq(Service.status.sync, CREDENTIALS_CHANGED); do_check_eq(Service.status.sync, CREDENTIALS_CHANGED);
do_check_eq(Service.status.login, LOGIN_FAILED_NO_PASSPHRASE); do_check_eq(Service.status.login, LOGIN_FAILED_NO_PASSPHRASE);
_("Log in with an old secret phrase, is upgraded to Sync Key."); await configureIdentity({ username: "johndoe" }, server);
Service.login("johndoe", "ilovejane", "my old secret phrase!!1!");
_("End of login");
do_check_true(Service.isLoggedIn);
do_check_true(Utils.isPassphrase(Service.identity.syncKey));
let syncKey = Service.identity.syncKey;
Service.startOver();
Service.serverURL = server.baseURI;
Service.login("johndoe", "ilovejane", syncKey);
do_check_true(Service.isLoggedIn);
Service.login();
_("Checking that remoteSetup returns true when credentials have changed."); _("Checking that remoteSetup returns true when credentials have changed.");
Service.recordManager.get(Service.metaURL).payload.syncID = "foobar"; Service.recordManager.get(Service.metaURL).payload.syncID = "foobar";
do_check_true(Service._remoteSetup()); do_check_true(Service._remoteSetup());
@ -113,7 +103,7 @@ function run_test() {
do_check_false(Service._remoteSetup()); do_check_false(Service._remoteSetup());
mock.restore(); mock.restore();
Service.login("johndoe", "ilovejane", syncKey); Service.login();
mock = mockHandler(GLOBAL_PATH, returnStatusCode("GET", 503)); mock = mockHandler(GLOBAL_PATH, returnStatusCode("GET", 503));
Service.recordManager.del(Service.metaURL); Service.recordManager.del(Service.metaURL);
_("Checking that remoteSetup returns false on 503 on first get /meta/global."); _("Checking that remoteSetup returns false on 503 on first get /meta/global.");
@ -121,6 +111,7 @@ function run_test() {
do_check_eq(Service.status.sync, METARECORD_DOWNLOAD_FAIL); do_check_eq(Service.status.sync, METARECORD_DOWNLOAD_FAIL);
mock.restore(); mock.restore();
Service.login();
mock = mockHandler(GLOBAL_PATH, returnStatusCode("GET", 404)); mock = mockHandler(GLOBAL_PATH, returnStatusCode("GET", 404));
Service.recordManager.del(Service.metaURL); Service.recordManager.del(Service.metaURL);
_("Checking that remoteSetup recovers on 404 on first get /meta/global."); _("Checking that remoteSetup recovers on 404 on first get /meta/global.");
@ -188,31 +179,6 @@ function run_test() {
do_check_true(meta_global.wasCalled); do_check_true(meta_global.wasCalled);
do_check_eq(metaModified, meta_global.modified); do_check_eq(metaModified, meta_global.modified);
_("Checking bad passphrases.");
let pp = Service.identity.syncKey;
Service.identity.syncKey = "notvalid";
do_check_false(Service.verifyAndFetchSymmetricKeys());
do_check_eq(Service.status.sync, CREDENTIALS_CHANGED);
do_check_eq(Service.status.login, LOGIN_FAILED_INVALID_PASSPHRASE);
Service.identity.syncKey = pp;
do_check_true(Service.verifyAndFetchSymmetricKeys());
// changePassphrase wipes our keys, and they're regenerated on next sync.
_("Checking changed passphrase.");
let existingDefault = Service.collectionKeys.keyForCollection();
let existingKeysPayload = keysWBO.payload;
let newPassphrase = "bbbbbabcdeabcdeabcdeabcdea";
Service.changePassphrase(newPassphrase);
_("Local key cache is full, but different.");
do_check_true(!!Service.collectionKeys._default);
do_check_false(Service.collectionKeys._default.equals(existingDefault));
_("Server has new keys.");
do_check_true(!!keysWBO.payload);
do_check_true(!!keysWBO.modified);
do_check_neq(keysWBO.payload, existingKeysPayload);
// Try to screw up HMAC calculation. // Try to screw up HMAC calculation.
// Re-encrypt keys with a new random keybundle, and upload them to the // Re-encrypt keys with a new random keybundle, and upload them to the
// server, just as might happen with a second client. // server, just as might happen with a second client.
@ -230,4 +196,4 @@ function run_test() {
Svc.Prefs.resetBranch(""); Svc.Prefs.resetBranch("");
server.stop(do_test_finished); server.stop(do_test_finished);
} }
} });

View File

@ -9,7 +9,7 @@ Cu.import("resource://testing-common/services/sync/utils.js");
function login_handling(handler) { function login_handling(handler) {
return function(request, response) { return function(request, response) {
if (basic_auth_matches(request, "johndoe", "ilovejane")) { if (has_hawk_header(request)) {
handler(request, response); handler(request, response);
} else { } else {
let body = "Unauthorized"; let body = "Unauthorized";
@ -29,7 +29,10 @@ function service_unavailable(request, response) {
function run_test() { function run_test() {
Log.repository.rootLogger.addAppender(new Log.DumpAppender()); Log.repository.rootLogger.addAppender(new Log.DumpAppender());
ensureLegacyIdentityManager(); run_next_test();
}
add_task(async function test_verifyLogin() {
// This test expects a clean slate -- no saved passphrase. // This test expects a clean slate -- no saved passphrase.
Services.logins.removeAllLogins(); Services.logins.removeAllLogins();
let johnHelper = track_collections_helper(); let johnHelper = track_collections_helper();
@ -37,20 +40,12 @@ function run_test() {
do_test_pending(); do_test_pending();
let server; let server = httpd_setup({
function weaveHandler(request, response) { "/1.1/johndoe/info/collections": login_handling(johnHelper.handler),
response.setStatusLine(request.httpVersion, 200, "OK"); "/1.1/janedoe/info/collections": service_unavailable,
let body = server.baseURI + "/api/";
response.bodyOutputStream.write(body, body.length);
}
server = httpd_setup({ "/1.1/johndoe/storage/crypto/keys": johnU("crypto", new ServerWBO("keys").handler()),
"/api/1.1/johndoe/info/collections": login_handling(johnHelper.handler), "/1.1/johndoe/storage/meta/global": johnU("meta", new ServerWBO("global").handler())
"/api/1.1/janedoe/info/collections": service_unavailable,
"/api/1.1/johndoe/storage/crypto/keys": johnU("crypto", new ServerWBO("keys").handler()),
"/api/1.1/johndoe/storage/meta/global": johnU("meta", new ServerWBO("global").handler()),
"/user/1.0/johndoe/node/weave": weaveHandler,
}); });
try { try {
@ -66,26 +61,16 @@ function run_test() {
do_check_eq(Service.status.service, CLIENT_NOT_CONFIGURED); do_check_eq(Service.status.service, CLIENT_NOT_CONFIGURED);
do_check_eq(Service.status.login, LOGIN_FAILED_NO_USERNAME); do_check_eq(Service.status.login, LOGIN_FAILED_NO_USERNAME);
_("Try again with username and password set."); _("Success if syncBundleKey is set.");
Service.status.resetSync(); Service.status.resetSync();
setBasicCredentials("johndoe", "ilovejane", null); await configureIdentity({ username: "johndoe" }, server);
do_check_false(Service.verifyLogin());
do_check_eq(Service.status.service, CLIENT_NOT_CONFIGURED);
do_check_eq(Service.status.login, LOGIN_FAILED_NO_PASSPHRASE);
_("verifyLogin() has found out the user's cluster URL, though.");
do_check_eq(Service.clusterURL, server.baseURI + "/api/");
_("Success if passphrase is set.");
Service.status.resetSync();
Service.identity.syncKey = "foo";
do_check_true(Service.verifyLogin()); do_check_true(Service.verifyLogin());
do_check_eq(Service.status.service, STATUS_OK); do_check_eq(Service.status.service, STATUS_OK);
do_check_eq(Service.status.login, LOGIN_SUCCEEDED); do_check_eq(Service.status.login, LOGIN_SUCCEEDED);
_("If verifyLogin() encounters a server error, it flips on the backoff flag and notifies observers on a 503 with Retry-After."); _("If verifyLogin() encounters a server error, it flips on the backoff flag and notifies observers on a 503 with Retry-After.");
Service.status.resetSync(); Service.status.resetSync();
Service.identity.account = "janedoe"; await configureIdentity({ username: "janedoe" }, server);
Service._updateCachedURLs(); Service._updateCachedURLs();
do_check_false(Service.status.enforceBackoff); do_check_false(Service.status.enforceBackoff);
let backoffInterval; let backoffInterval;
@ -102,6 +87,7 @@ function run_test() {
_("Ensure a network error when finding the cluster sets the right Status bits."); _("Ensure a network error when finding the cluster sets the right Status bits.");
Service.status.resetSync(); Service.status.resetSync();
Service.serverURL = "http://localhost:12345/"; Service.serverURL = "http://localhost:12345/";
Service._clusterManager._findCluster = () => "http://localhost:12345/";
do_check_false(Service.verifyLogin()); do_check_false(Service.verifyLogin());
do_check_eq(Service.status.service, LOGIN_FAILED); do_check_eq(Service.status.service, LOGIN_FAILED);
do_check_eq(Service.status.login, LOGIN_FAILED_NETWORK_ERROR); do_check_eq(Service.status.login, LOGIN_FAILED_NETWORK_ERROR);
@ -117,4 +103,4 @@ function run_test() {
Svc.Prefs.resetBranch(""); Svc.Prefs.resetBranch("");
server.stop(do_test_finished); server.stop(do_test_finished);
} }
} });

View File

@ -1,7 +1,7 @@
/* Any copyright is dedicated to the Public Domain. /* Any copyright is dedicated to the Public Domain.
* http://creativecommons.org/publicdomain/zero/1.0/ */ * http://creativecommons.org/publicdomain/zero/1.0/ */
Cu.import("resource://services-sync/identity.js"); Cu.import("resource://services-sync/browserid_identity.js");
Cu.import("resource://services-sync/engines.js"); Cu.import("resource://services-sync/engines.js");
Cu.import("resource://services-sync/record.js"); Cu.import("resource://services-sync/record.js");
Cu.import("resource://services-sync/service.js"); Cu.import("resource://services-sync/service.js");
@ -78,33 +78,6 @@ add_test(function test_startOver_clears_keys() {
run_next_test(); 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
// properly would require extra test infrastructure.
Services.logins.removeAllLogins();
Service.wipeClient();
let id = new IdentityManager();
do_check_eq(id.account, "testaccount");
do_check_eq(id.basicPassword, "testpassword");
do_check_eq(id.syncKey, key);
Service.startOver();
run_next_test();
});
function run_test() { function run_test() {
initTestLogging(); initTestLogging();

View File

@ -19,7 +19,6 @@ function run_test() {
// Check login status // Check login status
for (let code of [LOGIN_FAILED_NO_USERNAME, for (let code of [LOGIN_FAILED_NO_USERNAME,
LOGIN_FAILED_NO_PASSWORD,
LOGIN_FAILED_NO_PASSPHRASE]) { LOGIN_FAILED_NO_PASSPHRASE]) {
Status.login = code; Status.login = code;
do_check_eq(Status.login, code); do_check_eq(Status.login, code);

View File

@ -6,9 +6,8 @@ Cu.import("resource://services-sync/status.js");
Cu.import("resource://services-sync/util.js"); Cu.import("resource://services-sync/util.js");
Cu.import("resource://testing-common/services/sync/utils.js"); Cu.import("resource://testing-common/services/sync/utils.js");
function run_test() { add_task(async function test_status_checkSetup() {
initTestLogging("Trace"); initTestLogging("Trace");
ensureLegacyIdentityManager();
try { try {
_("Ensure fresh config."); _("Ensure fresh config.");
@ -19,22 +18,9 @@ function run_test() {
do_check_eq(Status.login, LOGIN_FAILED_NO_USERNAME); do_check_eq(Status.login, LOGIN_FAILED_NO_USERNAME);
Status.resetSync(); Status.resetSync();
_("Let's provide a username."); _("Let's provide the syncKeyBundle");
Status._authManager.username = "johndoe"; await configureIdentity();
do_check_eq(Status.checkSetup(), CLIENT_NOT_CONFIGURED);
do_check_eq(Status.login, LOGIN_FAILED_NO_PASSWORD);
Status.resetSync();
do_check_neq(Status._authManager.username, null);
_("Let's provide a password.");
Status._authManager.basicPassword = "carotsalad";
do_check_eq(Status.checkSetup(), CLIENT_NOT_CONFIGURED);
do_check_eq(Status.login, LOGIN_FAILED_NO_PASSPHRASE);
Status.resetSync();
_("Let's provide a passphrase");
Status._authManager.syncKey = "a-bcdef-abcde-acbde-acbde-acbde";
_("checkSetup()"); _("checkSetup()");
do_check_eq(Status.checkSetup(), STATUS_OK); do_check_eq(Status.checkSetup(), STATUS_OK);
Status.resetSync(); Status.resetSync();
@ -42,4 +28,4 @@ function run_test() {
} finally { } finally {
Svc.Prefs.resetBranch(""); Svc.Prefs.resetBranch("");
} }
} });

View File

@ -54,8 +54,6 @@ let MockClientsEngine = {
} }
// Configure Sync with our mock tabs engine and force it to become initialized. // Configure Sync with our mock tabs engine and force it to become initialized.
Services.prefs.setCharPref("services.sync.username", "someone@somewhere.com");
Weave.Service.engineManager.unregister("tabs"); Weave.Service.engineManager.unregister("tabs");
Weave.Service.engineManager.register(MockTabsEngine); Weave.Service.engineManager.register(MockTabsEngine);
Weave.Service.clientsEngine = MockClientsEngine; Weave.Service.clientsEngine = MockClientsEngine;

View File

@ -32,13 +32,6 @@ async function promiseClean(engine, server) {
await promiseStopServer(server); await promiseStopServer(server);
} }
function configureService(server, username, password) {
Service.clusterURL = server.baseURI;
Service.identity.account = username || "foo";
Service.identity.basicPassword = password || "password";
}
async function createServerAndConfigureClient() { async function createServerAndConfigureClient() {
let engine = new RotaryEngine(Service); let engine = new RotaryEngine(Service);
@ -98,7 +91,6 @@ add_task(async function test_syncStartup_emptyOrOutdatedGlobalsResetsSync() {
}); });
await SyncTestingInfrastructure(server); await SyncTestingInfrastructure(server);
Service.identity.username = "foo";
let engine = makeRotaryEngine(); let engine = makeRotaryEngine();
engine._store.items = {rekolok: "Rekonstruktionslokomotive"}; engine._store.items = {rekolok: "Rekonstruktionslokomotive"};
@ -142,7 +134,6 @@ add_task(async function test_syncStartup_serverHasNewerVersion() {
}); });
await SyncTestingInfrastructure(server); await SyncTestingInfrastructure(server);
Service.identity.username = "foo";
let engine = makeRotaryEngine(); let engine = makeRotaryEngine();
try { try {
@ -167,8 +158,8 @@ add_task(async function test_syncStartup_syncIDMismatchResetsClient() {
_("SyncEngine._syncStartup resets sync if syncIDs don't match"); _("SyncEngine._syncStartup resets sync if syncIDs don't match");
let server = sync_httpd_setup({}); let server = sync_httpd_setup({});
await SyncTestingInfrastructure(server); await SyncTestingInfrastructure(server);
Service.identity.username = "foo";
// global record with a different syncID than our engine has // global record with a different syncID than our engine has
let engine = makeRotaryEngine(); let engine = makeRotaryEngine();
@ -208,7 +199,6 @@ add_task(async function test_processIncoming_emptyServer() {
}); });
await SyncTestingInfrastructure(server); await SyncTestingInfrastructure(server);
Service.identity.username = "foo";
let engine = makeRotaryEngine(); let engine = makeRotaryEngine();
try { try {
@ -247,7 +237,6 @@ add_task(async function test_processIncoming_createFromServer() {
}); });
await SyncTestingInfrastructure(server); await SyncTestingInfrastructure(server);
Service.identity.username = "foo";
generateNewKeys(Service.collectionKeys); generateNewKeys(Service.collectionKeys);
@ -332,7 +321,6 @@ add_task(async function test_processIncoming_reconcile() {
}); });
await SyncTestingInfrastructure(server); await SyncTestingInfrastructure(server);
Service.identity.username = "foo";
let engine = makeRotaryEngine(); let engine = makeRotaryEngine();
engine._store.items = {newerserver: "New data, but not as new as server!", engine._store.items = {newerserver: "New data, but not as new as server!",
@ -608,7 +596,6 @@ add_task(async function test_processIncoming_mobile_batchSize() {
_("SyncEngine._processIncoming doesn't fetch everything at once on mobile clients"); _("SyncEngine._processIncoming doesn't fetch everything at once on mobile clients");
Svc.Prefs.set("client.type", "mobile"); Svc.Prefs.set("client.type", "mobile");
Service.identity.username = "foo";
// A collection that logs each GET // A collection that logs each GET
let collection = new ServerCollection(); let collection = new ServerCollection();
@ -677,7 +664,6 @@ add_task(async function test_processIncoming_mobile_batchSize() {
add_task(async function test_processIncoming_store_toFetch() { add_task(async function test_processIncoming_store_toFetch() {
_("If processIncoming fails in the middle of a batch on mobile, state is saved in toFetch and lastSync."); _("If processIncoming fails in the middle of a batch on mobile, state is saved in toFetch and lastSync.");
Service.identity.username = "foo";
Svc.Prefs.set("client.type", "mobile"); Svc.Prefs.set("client.type", "mobile");
// A collection that throws at the fourth get. // A collection that throws at the fourth get.
@ -742,7 +728,6 @@ add_task(async function test_processIncoming_store_toFetch() {
add_task(async function test_processIncoming_resume_toFetch() { add_task(async function test_processIncoming_resume_toFetch() {
_("toFetch and previousFailed items left over from previous syncs are fetched on the next sync, along with new items."); _("toFetch and previousFailed items left over from previous syncs are fetched on the next sync, along with new items.");
Service.identity.username = "foo";
const LASTSYNC = Date.now() / 1000; const LASTSYNC = Date.now() / 1000;
@ -811,7 +796,6 @@ add_task(async function test_processIncoming_resume_toFetch() {
add_task(async function test_processIncoming_applyIncomingBatchSize_smaller() { add_task(async function test_processIncoming_applyIncomingBatchSize_smaller() {
_("Ensure that a number of incoming items less than applyIncomingBatchSize is still applied."); _("Ensure that a number of incoming items less than applyIncomingBatchSize is still applied.");
Service.identity.username = "foo";
// Engine that doesn't like the first and last record it's given. // Engine that doesn't like the first and last record it's given.
const APPLY_BATCH_SIZE = 10; const APPLY_BATCH_SIZE = 10;
@ -866,7 +850,6 @@ add_task(async function test_processIncoming_applyIncomingBatchSize_smaller() {
add_task(async function test_processIncoming_applyIncomingBatchSize_multiple() { add_task(async function test_processIncoming_applyIncomingBatchSize_multiple() {
_("Ensure that incoming items are applied according to applyIncomingBatchSize."); _("Ensure that incoming items are applied according to applyIncomingBatchSize.");
Service.identity.username = "foo";
const APPLY_BATCH_SIZE = 10; const APPLY_BATCH_SIZE = 10;
@ -919,7 +902,6 @@ add_task(async function test_processIncoming_applyIncomingBatchSize_multiple() {
add_task(async function test_processIncoming_notify_count() { add_task(async function test_processIncoming_notify_count() {
_("Ensure that failed records are reported only once."); _("Ensure that failed records are reported only once.");
Service.identity.username = "foo";
const APPLY_BATCH_SIZE = 5; const APPLY_BATCH_SIZE = 5;
const NUMBER_OF_RECORDS = 15; const NUMBER_OF_RECORDS = 15;
@ -1008,7 +990,6 @@ add_task(async function test_processIncoming_notify_count() {
add_task(async function test_processIncoming_previousFailed() { add_task(async function test_processIncoming_previousFailed() {
_("Ensure that failed records are retried."); _("Ensure that failed records are retried.");
Service.identity.username = "foo";
Svc.Prefs.set("client.type", "mobile"); Svc.Prefs.set("client.type", "mobile");
const APPLY_BATCH_SIZE = 4; const APPLY_BATCH_SIZE = 4;
@ -1094,7 +1075,6 @@ add_task(async function test_processIncoming_previousFailed() {
add_task(async function test_processIncoming_failed_records() { add_task(async function test_processIncoming_failed_records() {
_("Ensure that failed records from _reconcile and applyIncomingBatch are refetched."); _("Ensure that failed records from _reconcile and applyIncomingBatch are refetched.");
Service.identity.username = "foo";
// Let's create three and a bit batches worth of server side records. // Let's create three and a bit batches worth of server side records.
let collection = new ServerCollection(); let collection = new ServerCollection();
@ -1229,8 +1209,6 @@ add_task(async function test_processIncoming_failed_records() {
add_task(async function test_processIncoming_decrypt_failed() { add_task(async function test_processIncoming_decrypt_failed() {
_("Ensure that records failing to decrypt are either replaced or refetched."); _("Ensure that records failing to decrypt are either replaced or refetched.");
Service.identity.username = "foo";
// Some good and some bogus records. One doesn't contain valid JSON, // Some good and some bogus records. One doesn't contain valid JSON,
// the other will throw during decrypt. // the other will throw during decrypt.
let collection = new ServerCollection(); let collection = new ServerCollection();
@ -1310,7 +1288,6 @@ add_task(async function test_processIncoming_decrypt_failed() {
add_task(async function test_uploadOutgoing_toEmptyServer() { add_task(async function test_uploadOutgoing_toEmptyServer() {
_("SyncEngine._uploadOutgoing uploads new records to server"); _("SyncEngine._uploadOutgoing uploads new records to server");
Service.identity.username = "foo";
let collection = new ServerCollection(); let collection = new ServerCollection();
collection._wbos.flying = new ServerWBO("flying"); collection._wbos.flying = new ServerWBO("flying");
collection._wbos.scotsman = new ServerWBO("scotsman"); collection._wbos.scotsman = new ServerWBO("scotsman");
@ -1367,7 +1344,6 @@ add_task(async function test_uploadOutgoing_toEmptyServer() {
add_task(async function test_uploadOutgoing_huge() { add_task(async function test_uploadOutgoing_huge() {
Service.identity.username = "foo";
let collection = new ServerCollection(); let collection = new ServerCollection();
collection._wbos.flying = new ServerWBO("flying"); collection._wbos.flying = new ServerWBO("flying");
collection._wbos.scotsman = new ServerWBO("scotsman"); collection._wbos.scotsman = new ServerWBO("scotsman");
@ -1416,7 +1392,6 @@ add_task(async function test_uploadOutgoing_huge() {
add_task(async function test_uploadOutgoing_failed() { add_task(async function test_uploadOutgoing_failed() {
_("SyncEngine._uploadOutgoing doesn't clear the tracker of objects that failed to upload."); _("SyncEngine._uploadOutgoing doesn't clear the tracker of objects that failed to upload.");
Service.identity.username = "foo";
let collection = new ServerCollection(); let collection = new ServerCollection();
// We only define the "flying" WBO on the server, not the "scotsman" // We only define the "flying" WBO on the server, not the "scotsman"
// and "peppercorn" ones. // and "peppercorn" ones.
@ -1482,7 +1457,6 @@ add_task(async function test_uploadOutgoing_failed() {
add_task(async function test_uploadOutgoing_MAX_UPLOAD_RECORDS() { add_task(async function test_uploadOutgoing_MAX_UPLOAD_RECORDS() {
_("SyncEngine._uploadOutgoing uploads in batches of MAX_UPLOAD_RECORDS"); _("SyncEngine._uploadOutgoing uploads in batches of MAX_UPLOAD_RECORDS");
Service.identity.username = "foo";
let collection = new ServerCollection(); let collection = new ServerCollection();
// Let's count how many times the client posts to the server // Let's count how many times the client posts to the server
@ -1546,7 +1520,6 @@ add_task(async function test_uploadOutgoing_MAX_UPLOAD_RECORDS() {
add_task(async function test_uploadOutgoing_largeRecords() { add_task(async function test_uploadOutgoing_largeRecords() {
_("SyncEngine._uploadOutgoing throws on records larger than MAX_UPLOAD_BYTES"); _("SyncEngine._uploadOutgoing throws on records larger than MAX_UPLOAD_BYTES");
Service.identity.username = "foo";
let collection = new ServerCollection(); let collection = new ServerCollection();
let engine = makeRotaryEngine(); let engine = makeRotaryEngine();
@ -1602,7 +1575,6 @@ add_task(async function test_syncFinish_noDelete() {
add_task(async function test_syncFinish_deleteByIds() { add_task(async function test_syncFinish_deleteByIds() {
_("SyncEngine._syncFinish deletes server records slated for deletion (list of record IDs)."); _("SyncEngine._syncFinish deletes server records slated for deletion (list of record IDs).");
Service.identity.username = "foo";
let collection = new ServerCollection(); let collection = new ServerCollection();
collection._wbos.flying = new ServerWBO( collection._wbos.flying = new ServerWBO(
"flying", encryptPayload({id: "flying", "flying", encryptPayload({id: "flying",
@ -1642,7 +1614,6 @@ add_task(async function test_syncFinish_deleteByIds() {
add_task(async function test_syncFinish_deleteLotsInBatches() { add_task(async function test_syncFinish_deleteLotsInBatches() {
_("SyncEngine._syncFinish deletes server records in batches of 100 (list of record IDs)."); _("SyncEngine._syncFinish deletes server records in batches of 100 (list of record IDs).");
Service.identity.username = "foo";
let collection = new ServerCollection(); let collection = new ServerCollection();
// Let's count how many times the client does a DELETE request to the server // Let's count how many times the client does a DELETE request to the server
@ -1713,8 +1684,6 @@ add_task(async function test_syncFinish_deleteLotsInBatches() {
add_task(async function test_sync_partialUpload() { add_task(async function test_sync_partialUpload() {
_("SyncEngine.sync() keeps changedIDs that couldn't be uploaded."); _("SyncEngine.sync() keeps changedIDs that couldn't be uploaded.");
Service.identity.username = "foo";
let collection = new ServerCollection(); let collection = new ServerCollection();
let server = sync_httpd_setup({ let server = sync_httpd_setup({
"/1.1/foo/storage/rotary": collection.handler() "/1.1/foo/storage/rotary": collection.handler()
@ -1787,7 +1756,6 @@ add_task(async function test_sync_partialUpload() {
add_task(async function test_canDecrypt_noCryptoKeys() { add_task(async function test_canDecrypt_noCryptoKeys() {
_("SyncEngine.canDecrypt returns false if the engine fails to decrypt items on the server, e.g. due to a missing crypto key collection."); _("SyncEngine.canDecrypt returns false if the engine fails to decrypt items on the server, e.g. due to a missing crypto key collection.");
Service.identity.username = "foo";
// Wipe collection keys so we can test the desired scenario. // Wipe collection keys so we can test the desired scenario.
Service.collectionKeys.clear(); Service.collectionKeys.clear();
@ -1814,7 +1782,6 @@ add_task(async function test_canDecrypt_noCryptoKeys() {
add_task(async function test_canDecrypt_true() { add_task(async function test_canDecrypt_true() {
_("SyncEngine.canDecrypt returns true if the engine can decrypt the items on the server."); _("SyncEngine.canDecrypt returns true if the engine can decrypt the items on the server.");
Service.identity.username = "foo";
generateNewKeys(Service.collectionKeys); generateNewKeys(Service.collectionKeys);
@ -1840,8 +1807,6 @@ add_task(async function test_canDecrypt_true() {
}); });
add_task(async function test_syncapplied_observer() { add_task(async function test_syncapplied_observer() {
Service.identity.username = "foo";
const NUMBER_OF_RECORDS = 10; const NUMBER_OF_RECORDS = 10;
let engine = makeRotaryEngine(); let engine = makeRotaryEngine();

View File

@ -48,17 +48,16 @@ function sync_httpd_setup() {
let upd = collectionsHelper.with_updated_collection; let upd = collectionsHelper.with_updated_collection;
return httpd_setup({ return httpd_setup({
"/1.1/johndoe/storage/meta/global": upd("meta", global.handler()), "/1.1/johndoe@mozilla.com/storage/meta/global": upd("meta", global.handler()),
"/1.1/johndoe/info/collections": collectionsHelper.handler, "/1.1/johndoe@mozilla.com/info/collections": collectionsHelper.handler,
"/1.1/johndoe/storage/crypto/keys": "/1.1/johndoe@mozilla.com/storage/crypto/keys":
upd("crypto", (new ServerWBO("keys")).handler()), upd("crypto", (new ServerWBO("keys")).handler()),
"/1.1/johndoe/storage/clients": upd("clients", clientsColl.handler()), "/1.1/johndoe@mozilla.com/storage/clients": upd("clients", clientsColl.handler())
"/user/1.0/johndoe/node/weave": httpd_handler(200, "OK", "null")
}); });
} }
async function setUp(server) { async function setUp(server) {
await configureIdentity({username: "johndoe"}, server); await configureIdentity({username: "johndoe@mozilla.com"}, server);
generateNewKeys(Service.collectionKeys); generateNewKeys(Service.collectionKeys);
let serverKeys = Service.collectionKeys.asWBO("crypto", "keys"); let serverKeys = Service.collectionKeys.asWBO("crypto", "keys");
@ -83,11 +82,6 @@ function run_test() {
Log.repository.getLogger("Sync.scheduler").level = Log.Level.Trace; Log.repository.getLogger("Sync.scheduler").level = Log.Level.Trace;
validate_all_future_pings(); validate_all_future_pings();
// 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(); scheduler.setDefaults();
run_next_test(); run_next_test();
@ -130,7 +124,7 @@ add_test(function test_prefAttributes() {
_("Intervals correspond to default preferences."); _("Intervals correspond to default preferences.");
do_check_eq(scheduler.singleDeviceInterval, do_check_eq(scheduler.singleDeviceInterval,
Svc.Prefs.get("scheduler.sync11.singleDeviceInterval") * 1000); Svc.Prefs.get("scheduler.fxa.singleDeviceInterval") * 1000);
do_check_eq(scheduler.idleInterval, do_check_eq(scheduler.idleInterval,
Svc.Prefs.get("scheduler.idleInterval") * 1000); Svc.Prefs.get("scheduler.idleInterval") * 1000);
do_check_eq(scheduler.activeInterval, do_check_eq(scheduler.activeInterval,
@ -139,7 +133,7 @@ add_test(function test_prefAttributes() {
Svc.Prefs.get("scheduler.immediateInterval") * 1000); Svc.Prefs.get("scheduler.immediateInterval") * 1000);
_("Custom values for prefs will take effect after a restart."); _("Custom values for prefs will take effect after a restart.");
Svc.Prefs.set("scheduler.sync11.singleDeviceInterval", 420); Svc.Prefs.set("scheduler.fxa.singleDeviceInterval", 420);
Svc.Prefs.set("scheduler.idleInterval", 230); Svc.Prefs.set("scheduler.idleInterval", 230);
Svc.Prefs.set("scheduler.activeInterval", 180); Svc.Prefs.set("scheduler.activeInterval", 180);
Svc.Prefs.set("scheduler.immediateInterval", 31415); Svc.Prefs.set("scheduler.immediateInterval", 31415);
@ -150,7 +144,7 @@ add_test(function test_prefAttributes() {
do_check_eq(scheduler.immediateInterval, 31415000); do_check_eq(scheduler.immediateInterval, 31415000);
_("Custom values for interval prefs can't be less than 60 seconds."); _("Custom values for interval prefs can't be less than 60 seconds.");
Svc.Prefs.set("scheduler.sync11.singleDeviceInterval", 42); Svc.Prefs.set("scheduler.fxa.singleDeviceInterval", 42);
Svc.Prefs.set("scheduler.idleInterval", 50); Svc.Prefs.set("scheduler.idleInterval", 50);
Svc.Prefs.set("scheduler.activeInterval", 50); Svc.Prefs.set("scheduler.activeInterval", 50);
Svc.Prefs.set("scheduler.immediateInterval", 10); Svc.Prefs.set("scheduler.immediateInterval", 10);
@ -494,7 +488,7 @@ add_identity_test(this, async function test_autoconnect_nextSync_future() {
} }
Svc.Obs.add("weave:service:login:start", onLoginStart); Svc.Obs.add("weave:service:login:start", onLoginStart);
await configureIdentity({username: "johndoe"}); await configureIdentity({username: "johndoe@mozilla.com"});
scheduler.delayedAutoConnect(0); scheduler.delayedAutoConnect(0);
await promiseZeroTimer(); await promiseZeroTimer();
@ -505,8 +499,6 @@ add_identity_test(this, async function test_autoconnect_nextSync_future() {
await cleanUpAndGo(); await cleanUpAndGo();
}); });
// XXX - this test can't be run with the browserid identity as it relies
// on the syncKey getter behaving in a certain way...
add_task(async function test_autoconnect_mp_locked() { add_task(async function test_autoconnect_mp_locked() {
let server = sync_httpd_setup(); let server = sync_httpd_setup();
await setUp(server); await setUp(server);
@ -515,13 +507,14 @@ add_task(async function test_autoconnect_mp_locked() {
let origLocked = Utils.mpLocked; let origLocked = Utils.mpLocked;
Utils.mpLocked = () => true; Utils.mpLocked = () => true;
let origGetter = Service.identity.__lookupGetter__("syncKey");
let origSetter = Service.identity.__lookupSetter__("syncKey"); let origEnsureMPUnlocked = Utils.ensureMPUnlocked;
delete Service.identity.syncKey; Utils.ensureMPUnlocked = () => {
Service.identity.__defineGetter__("syncKey", function() {
_("Faking Master Password entry cancelation."); _("Faking Master Password entry cancelation.");
throw "User canceled Master Password entry"; return false;
}); }
let origCanFetchKeys = Service.identity._canFetchKeys;
Service.identity._canFetchKeys = () => false;
// A locked master password will still trigger a sync, but then we'll hit // A locked master password will still trigger a sync, but then we'll hit
// MASTER_PASSWORD_LOCKED and hence MASTER_PASSWORD_LOCKED_RETRY_INTERVAL. // MASTER_PASSWORD_LOCKED and hence MASTER_PASSWORD_LOCKED_RETRY_INTERVAL.
@ -535,9 +528,8 @@ add_task(async function test_autoconnect_mp_locked() {
do_check_eq(Status.login, MASTER_PASSWORD_LOCKED); do_check_eq(Status.login, MASTER_PASSWORD_LOCKED);
Utils.mpLocked = origLocked; Utils.mpLocked = origLocked;
delete Service.identity.syncKey; Utils.ensureMPUnlocked = origEnsureMPUnlocked;
Service.identity.__defineGetter__("syncKey", origGetter); Service.identity._canFetchKeys = origCanFetchKeys;
Service.identity.__defineSetter__("syncKey", origSetter);
await cleanUpAndGo(server); await cleanUpAndGo(server);
}); });
@ -781,7 +773,7 @@ add_identity_test(this, async function test_sync_X_Weave_Backoff() {
const BACKOFF = 7337; const BACKOFF = 7337;
// Extend info/collections so that we can put it into server maintenance mode. // Extend info/collections so that we can put it into server maintenance mode.
const INFO_COLLECTIONS = "/1.1/johndoe/info/collections"; const INFO_COLLECTIONS = "/1.1/johndoe@mozilla.com/info/collections";
let infoColl = server._handler._overridePaths[INFO_COLLECTIONS]; let infoColl = server._handler._overridePaths[INFO_COLLECTIONS];
let serverBackoff = false; let serverBackoff = false;
function infoCollWithBackoff(request, response) { function infoCollWithBackoff(request, response) {
@ -838,7 +830,7 @@ add_identity_test(this, async function test_sync_503_Retry_After() {
const BACKOFF = 7337; const BACKOFF = 7337;
// Extend info/collections so that we can put it into server maintenance mode. // Extend info/collections so that we can put it into server maintenance mode.
const INFO_COLLECTIONS = "/1.1/johndoe/info/collections"; const INFO_COLLECTIONS = "/1.1/johndoe@mozilla.com/info/collections";
let infoColl = server._handler._overridePaths[INFO_COLLECTIONS]; let infoColl = server._handler._overridePaths[INFO_COLLECTIONS];
let serverMaintenance = false; let serverMaintenance = false;
function infoCollWithMaintenance(request, response) { function infoCollWithMaintenance(request, response) {
@ -892,10 +884,9 @@ add_identity_test(this, async function test_sync_503_Retry_After() {
add_identity_test(this, async function test_loginError_recoverable_reschedules() { add_identity_test(this, async function test_loginError_recoverable_reschedules() {
_("Verify that a recoverable login error schedules a new sync."); _("Verify that a recoverable login error schedules a new sync.");
await configureIdentity({username: "johndoe"}); await configureIdentity({username: "johndoe@mozilla.com"});
Service.serverURL = "http://localhost:1234/"; Service.serverURL = "http://localhost:1234/";
Service.clusterURL = Service.serverURL; Service.clusterURL = Service.serverURL;
Service.persistLogin();
Status.resetSync(); // reset Status.login Status.resetSync(); // reset Status.login
let promiseObserved = promiseOneObserver("weave:service:login:error"); let promiseObserved = promiseOneObserver("weave:service:login:error");
@ -933,15 +924,14 @@ add_identity_test(this, async function test_loginError_recoverable_reschedules()
add_identity_test(this, async function test_loginError_fatal_clearsTriggers() { add_identity_test(this, async function test_loginError_fatal_clearsTriggers() {
_("Verify that a fatal login error clears sync triggers."); _("Verify that a fatal login error clears sync triggers.");
await configureIdentity({username: "johndoe"}); await configureIdentity({username: "johndoe@mozilla.com"});
let server = httpd_setup({ let server = httpd_setup({
"/1.1/johndoe/info/collections": httpd_handler(401, "Unauthorized") "/1.1/johndoe@mozilla.com/info/collections": httpd_handler(401, "Unauthorized")
}); });
Service.serverURL = server.baseURI + "/"; Service.serverURL = server.baseURI + "/";
Service.clusterURL = Service.serverURL; Service.clusterURL = Service.serverURL;
Service.persistLogin();
Status.resetSync(); // reset Status.login Status.resetSync(); // reset Status.login
let promiseObserved = promiseOneObserver("weave:service:login:error"); let promiseObserved = promiseOneObserver("weave:service:login:error");
@ -956,21 +946,13 @@ add_identity_test(this, async function test_loginError_fatal_clearsTriggers() {
await promiseObserved; await promiseObserved;
await promiseNextTick(); await promiseNextTick();
if (isConfiguredWithLegacyIdentity()) { // For the FxA identity, a 401 on info/collections means a transient
// for the "legacy" identity, a 401 on info/collections means the // error, probably due to an inability to fetch a token.
// password is wrong, so we enter a "login rejected" state. do_check_eq(Status.login, LOGIN_FAILED_NETWORK_ERROR);
do_check_eq(Status.login, LOGIN_FAILED_LOGIN_REJECTED); // syncs should still be scheduled.
do_check_true(scheduler.nextSync > Date.now());
do_check_true(scheduler.syncTimer.delay > 0);
do_check_eq(scheduler.nextSync, 0);
do_check_eq(scheduler.syncTimer, null);
} else {
// For the FxA identity, a 401 on info/collections means a transient
// error, probably due to an inability to fetch a token.
do_check_eq(Status.login, LOGIN_FAILED_NETWORK_ERROR);
// syncs should still be scheduled.
do_check_true(scheduler.nextSync > Date.now());
do_check_true(scheduler.syncTimer.delay > 0);
}
await cleanUpAndGo(server); await cleanUpAndGo(server);
}); });

View File

@ -15,8 +15,6 @@ function run_test() {
Log.repository.getLogger("Sync.RESTRequest").level = Log.Level.Trace; Log.repository.getLogger("Sync.RESTRequest").level = Log.Level.Trace;
initTestLogging(); initTestLogging();
ensureLegacyIdentityManager();
run_next_test(); run_next_test();
} }
@ -59,23 +57,24 @@ add_test(function test_user_agent_mobile() {
}); });
}); });
add_test(function test_auth() { // XXX - DISABLED BECAUSE getStorageRequest broken with browserid_manager
let handler = httpd_handler(200, "OK"); // add_test(function test_auth() {
let server = httpd_setup({"/resource": handler}); // let handler = httpd_handler(200, "OK");
// let server = httpd_setup({"/resource": handler});
setBasicCredentials("johndoe", "ilovejane", "XXXXXXXXX"); // configureIdentity();
let request = Service.getStorageRequest(server.baseURI + "/resource"); // let request = Service.getStorageRequest(server.baseURI + "/resource");
request.get(function(error) { // request.get(function(error) {
do_check_eq(error, null); // do_check_eq(error, null);
do_check_eq(this.response.status, 200); // do_check_eq(this.response.status, 200);
do_check_true(basic_auth_matches(handler.request, "johndoe", "ilovejane")); // do_check_true(has_hawk_header(handler.request));
Svc.Prefs.reset(""); // Svc.Prefs.reset("");
server.stop(run_next_test); // server.stop(run_next_test);
}); // });
}); // });
/** /**
* The X-Weave-Timestamp header updates SyncStorageRequest.serverTime. * The X-Weave-Timestamp header updates SyncStorageRequest.serverTime.

View File

@ -79,7 +79,6 @@ add_task(async function test_tab_engine_skips_incoming_local_record() {
}); });
await SyncTestingInfrastructure(server); await SyncTestingInfrastructure(server);
Service.identity.username = "foo";
let meta_global = Service.recordManager.set(engine.metaURL, let meta_global = Service.recordManager.set(engine.metaURL,
new WBORecord(engine.metaURL)); new WBORecord(engine.metaURL));

View File

@ -73,7 +73,6 @@ add_identity_test(this, async function test_basic() {
let helper = track_collections_helper(); let helper = track_collections_helper();
let upd = helper.with_updated_collection; let upd = helper.with_updated_collection;
await configureIdentity({ username: "johndoe" });
let handlers = { let handlers = {
"/1.1/johndoe/info/collections": helper.handler, "/1.1/johndoe/info/collections": helper.handler,
"/1.1/johndoe/storage/crypto/keys": upd("crypto", new ServerWBO("keys").handler()), "/1.1/johndoe/storage/crypto/keys": upd("crypto", new ServerWBO("keys").handler()),
@ -87,6 +86,7 @@ add_identity_test(this, async function test_basic() {
} }
let server = httpd_setup(handlers); let server = httpd_setup(handlers);
await configureIdentity({ username: "johndoe" }, server);
Service.serverURL = server.baseURI; Service.serverURL = server.baseURI;
await sync_and_validate_telem(true); await sync_and_validate_telem(true);
@ -192,7 +192,6 @@ add_task(async function test_uploading() {
}); });
add_task(async function test_upload_failed() { add_task(async function test_upload_failed() {
Service.identity.username = "foo";
let collection = new ServerCollection(); let collection = new ServerCollection();
collection._wbos.flying = new ServerWBO("flying"); collection._wbos.flying = new ServerWBO("flying");
@ -201,6 +200,7 @@ add_task(async function test_upload_failed() {
}); });
await SyncTestingInfrastructure(server); await SyncTestingInfrastructure(server);
await configureIdentity({ username: "foo" }, server);
let engine = new RotaryEngine(Service); let engine = new RotaryEngine(Service);
engine.lastSync = 123; // needs to be non-zero so that tracker is queried engine.lastSync = 123; // needs to be non-zero so that tracker is queried
@ -246,8 +246,6 @@ add_task(async function test_upload_failed() {
}); });
add_task(async function test_sync_partialUpload() { add_task(async function test_sync_partialUpload() {
Service.identity.username = "foo";
let collection = new ServerCollection(); let collection = new ServerCollection();
let server = sync_httpd_setup({ let server = sync_httpd_setup({
"/1.1/foo/storage/rotary": collection.handler() "/1.1/foo/storage/rotary": collection.handler()

View File

@ -1,49 +0,0 @@
/* 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...
do_check_false(Utils.isPassphrase(normalized));
// ... but different.
do_check_neq(normalized, passphrase);
do_check_eq(normalized, "abcdeabcdeabcdeabcde");
// Now run through the upgrade.
Service.identity.account = "johndoe";
Service.syncID = "1234567890";
Service.identity.syncKey = normalized; // UI normalizes.
do_check_false(Utils.isPassphrase(Service.identity.syncKey));
Service.upgradeSyncKey(Service.syncID);
let upgraded = Service.identity.syncKey;
_("Upgraded: " + upgraded);
do_check_true(Utils.isPassphrase(upgraded));
// Now let's verify that it's been derived correctly, from the normalized
// version, and the encoded sync ID.
_("Sync ID: " + Service.syncID);
let derivedKeyStr =
Utils.derivePresentableKeyFromPassphrase(normalized,
btoa(Service.syncID),
PBKDF2_KEY_BYTES, true);
_("Derived: " + derivedKeyStr);
// Success!
do_check_eq(derivedKeyStr, upgraded);
}

View File

@ -70,17 +70,14 @@ skip-if = os == "android"
# Service semantics. # Service semantics.
[test_service_attributes.js] [test_service_attributes.js]
[test_service_changePassword.js]
# Bug 752243: Profile cleanup frequently fails # Bug 752243: Profile cleanup frequently fails
skip-if = os == "mac" || os == "linux" skip-if = os == "mac" || os == "linux"
[test_service_checkAccount.js]
[test_service_cluster.js] [test_service_cluster.js]
[test_service_detect_upgrade.js] [test_service_detect_upgrade.js]
[test_service_getStorageInfo.js] # XXX - Disabled because getStorageInfo is broken
# [test_service_getStorageInfo.js]
[test_service_login.js] [test_service_login.js]
[test_service_migratePrefs.js] [test_service_migratePrefs.js]
[test_service_passwordUTF8.js]
[test_service_persistLogin.js]
[test_service_set_serverURL.js] [test_service_set_serverURL.js]
[test_service_startOver.js] [test_service_startOver.js]
[test_service_startup.js] [test_service_startup.js]
@ -117,10 +114,8 @@ skip-if = os == "android"
[test_status.js] [test_status.js]
[test_status_checkSetup.js] [test_status_checkSetup.js]
[test_syncscheduler.js] [test_syncscheduler.js]
[test_upgrade_old_sync_key.js]
# Firefox Accounts specific tests # Firefox Accounts specific tests
[test_fxa_startOver.js]
[test_fxa_service_cluster.js] [test_fxa_service_cluster.js]
[test_fxa_node_reassignment.js] [test_fxa_node_reassignment.js]
@ -181,9 +176,6 @@ support-files = prefs_test_prefs_store.js
[test_warn_on_truncated_response.js] [test_warn_on_truncated_response.js]
[test_postqueue.js] [test_postqueue.js]
# FxA migration
[test_fxa_migration.js]
# Synced tabs. # Synced tabs.
[test_syncedtabs.js] [test_syncedtabs.js]

View File

@ -221,7 +221,7 @@
"Traversal.jsm": ["TraversalRules", "TraversalHelper"], "Traversal.jsm": ["TraversalRules", "TraversalHelper"],
"UpdateTelemetry.jsm": ["AUSTLMY"], "UpdateTelemetry.jsm": ["AUSTLMY"],
"util.js": ["getChromeWindow", "XPCOMUtils", "Services", "Utils", "Async", "Svc", "Str"], "util.js": ["getChromeWindow", "XPCOMUtils", "Services", "Utils", "Async", "Svc", "Str"],
"utils.js": ["applicationName", "assert", "Copy", "getBrowserObject", "getChromeWindow", "getWindows", "getWindowByTitle", "getWindowByType", "getWindowId", "getMethodInWindows", "getPreference", "saveDataURL", "setPreference", "sleep", "startTimer", "stopTimer", "takeScreenshot", "unwrapNode", "waitFor", "btoa", "encryptPayload", "isConfiguredWithLegacyIdentity", "ensureLegacyIdentityManager", "setBasicCredentials", "makeIdentityConfig", "makeFxAccountsInternalMock", "configureFxAccountIdentity", "configureIdentity", "SyncTestingInfrastructure", "waitForZeroTimer", "Promise", "add_identity_test", "MockFxaStorageManager", "AccountState", "sumHistogram", "CommonUtils", "CryptoUtils", "TestingUtils"], "utils.js": ["applicationName", "assert", "Copy", "getBrowserObject", "getChromeWindow", "getWindows", "getWindowByTitle", "getWindowByType", "getWindowId", "getMethodInWindows", "getPreference", "saveDataURL", "setPreference", "sleep", "startTimer", "stopTimer", "takeScreenshot", "unwrapNode", "waitFor", "btoa", "encryptPayload", "makeIdentityConfig", "makeFxAccountsInternalMock", "configureFxAccountIdentity", "configureIdentity", "SyncTestingInfrastructure", "waitForZeroTimer", "Promise", "add_identity_test", "MockFxaStorageManager", "AccountState", "sumHistogram", "CommonUtils", "CryptoUtils", "TestingUtils"],
"Utils.jsm": ["Utils", "Logger", "PivotContext", "PrefCache"], "Utils.jsm": ["Utils", "Logger", "PivotContext", "PrefCache"],
"VariablesView.jsm": ["VariablesView", "escapeHTML"], "VariablesView.jsm": ["VariablesView", "escapeHTML"],
"VariablesViewController.jsm": ["VariablesViewController", "StackFrameUtils"], "VariablesViewController.jsm": ["VariablesViewController", "StackFrameUtils"],