Merge pull request #165 from Bitcoin-com/wallet/task/369

Secure Storage on mobile devices
This commit is contained in:
Sebastiaan Pasma 2018-06-11 14:14:10 +02:00 committed by GitHub
commit 5da9f7c835
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
14 changed files with 1887 additions and 28 deletions

View file

@ -152,11 +152,22 @@ module.exports = function(grunt) {
src: [
'src/js/app.js',
'src/js/routes.js',
'src/js/directives/*.js',
'!src/js/directives/*.spec.js',
'src/js/filters/*.js',
'!src/js/filters/*.spec.js',
'src/js/models/*.js',
'!src/js/models/*.spec.js',
'src/js/services/*.js',
'!src/js/services/*.spec.js',
'src/js/controllers/**/*.js',
'!src/js/controllers/**/*.spec.js',
'src/js/translations.js',
'src/js/appConfig.js',
'src/js/externalServices.js',

View file

@ -72,6 +72,8 @@
<plugin name="cordova-plugin-queries-schemes" spec="~0.1.5" />
<plugin name="cordova-plugin-firebase" spec="https://github.com/arnesson/cordova-plugin-firebase.git" />
<plugin name="cordova-plugin-wkwebview-inputfocusfix" spec="https://github.com/onderceylan/cordova-plugin-wkwebview-inputfocusfix.git" />
<!-- Changes in error descriptions may break the use of cordova-plugin-secure-storage -->
<plugin name="cordova-plugin-secure-storage" spec="2.6.8" />
<!-- Supported Platforms -->
<engine name="ios" spec="~4.5.3" />
<engine name="android" spec="~6.3.0" />

View file

@ -113,8 +113,8 @@
"sign:android": "rm -f platforms/android/build/outputs/apk/android-release-signed-aligned.apk; jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore ../bitcoin-com-release-key.jks -signedjar platforms/android/build/outputs/apk/android-release-signed.apk platforms/android/build/outputs/apk/android-release-unsigned.apk bitcoin-com && $ANDROID_HOME/build-tools/27.0.1/zipalign -v 4 platforms/android/build/outputs/apk/android-release-signed.apk platforms/android/build/outputs/apk/android-release-signed-aligned.apk",
"apply:copay": "npm i fs-extra && cd app-template && node apply.js copay && npm i && cordova prepare",
"apply:bitpay": "npm i fs-extra && cd app-template && node apply.js bitpay && npm i && cordova prepare",
"apply:bitcoincom": "npm i fs-extra && cd app-template && node apply.js bitcoincom && npm i && cordova prepare",
"test": "echo \"no package tests configured\"",
"apply:bitcoincom": "npm i fs-extra && cd app-template && node apply.js bitcoincom && npm i && cordova prepare",
"test": "karma start test/karma.conf.js --single-run",
"clean": "trash platforms && trash plugins && cordova prepare",
"unstage-package": "git reset package.json",
"clean-all": "git clean -dfx"
@ -123,6 +123,10 @@
"cordova": "^6.3.1",
"grunt": "^1.0.1",
"ionic": "^3.6.0",
"jasmine-core": "^3.1.0",
"karma": "^2.0.2",
"karma-chrome-launcher": "^2.2.0",
"karma-jasmine": "^1.1.2",
"trash-cli": "^1.4.0",
"lodash": "^4.17.4",
"pre-commit": "^1.1.3"

View file

@ -9,12 +9,12 @@ function Profile() {
this.version = '1.0.0';
};
Profile.create = function(opts) {
opts = opts || {};
Profile.create = function(appVersion) {
var x = new Profile();
x.appVersion = appVersion;
x.createdOn = Date.now();
x.credentials = opts.credentials || [];
x.credentials = [];
x.disclaimerAccepted = true;
x.checked = {};
return x;
@ -23,6 +23,7 @@ Profile.create = function(opts) {
Profile.fromObj = function(obj) {
var x = new Profile();
x.appVersion = obj.appVersion;
x.createdOn = obj.createdOn;
x.credentials = obj.credentials;
x.disclaimerAccepted = obj.disclaimerAccepted;
@ -62,6 +63,39 @@ Profile.prototype.isDeviceChecked = function(ua) {
return this.checkedUA == ua;
};
/**
*
* @param {Profile} other
*/
Profile.prototype.merge = function(other) {
var newCredentials = [];
var otherCredentialsLength = other.credentials.length;
var thisProfile = this;
other.credentials.forEach(function(otherCredential) {
var credentialExists = false;
thisProfile.credentials.forEach(function(thisCredential) {
if (otherCredential.walletId === thisCredential.walletId) {
credentialExists = true;
}
});
if (!credentialExists) {
newCredentials.push(otherCredential);
}
});
Array.prototype.push.apply(this.credentials, newCredentials);
};
/**
* It's a simple operation, but it means that all the profile logic stays
* in this file.
* @param {string} appVersion - ie "4.11.0"
*/
Profile.prototype.setAppVersion = function(appVersion) {
this.appVersion = appVersion;
}
Profile.prototype.setChecked = function(ua, walletId) {
if (this.checkedUA != ua) {

View file

@ -0,0 +1,6 @@
'use strict';
angular.module('copayApp.services').factory('desktopSecureStorageService', function($log) {
// Placeholder
return {};
});

View file

@ -20,8 +20,7 @@ angular.module('copayApp.services')
if (isChromeApp || isNW) {
chrome.storage.local.get(k,
function(data) {
//TODO check for errors
return cb(null, data[k]);
return cb(chrome.runtime.lastError, data[k]);
});
} else {
return cb(null, ls.getItem(k));
@ -56,16 +55,24 @@ angular.module('copayApp.services')
obj[k] = v;
chrome.storage.local.set(obj, cb);
chrome.storage.local.set(obj, function(){
cb(chrome.runtime.lastError);
});
} else {
ls.setItem(k, v);
try {
ls.setItem(k, v);
} catch (e) {
return cb(e);
}
return cb();
}
};
root.remove = function(k, cb) {
if (isChromeApp || isNW) {
chrome.storage.local.remove(k, cb);
chrome.storage.local.remove(k, function(){
cb(chrome.runtime.lastError);
});
} else {
ls.removeItem(k);
return cb();

View file

@ -0,0 +1,88 @@
'use strict';
angular.module('copayApp.services').factory('mobileSecureStorageService', function($log, appConfigService, platformInfo) {
var root = {};
var isReady = false;
var initialisationFailed = false;
var pending = [];
var storage = null;
if (platformInfo.isCordova) {
storage = new cordova.plugins.SecureStorage(
function () {
isReady = true;
for (var i = 0; i < pending.length; i++) {
pending[i]();
}
pending = [];
},
function (error) {
initialisationFailed = true;
},
appConfigService.packageNameId);
}
root.get = function(key, cb) {
if (!platformInfo.isMobile) {
cb(new Error('mobileSecureStorageService is only available on mobile.'));
return;
}
if (!isReady) {
if (initialisationFailed) {
cb(new Error('mobileSecureStorageService initialisation failed.'));
} else {
pending.push(function(){ root.get(key, cb); });
}
return;
}
storage.get(
function (value) {
cb(null, value);
},
function (error) {
$log.debug('mss get failed. ' + error);
if (error.message === 'Failure in SecureStorage.get() - The specified item could not be found in the keychain' || // iOS
error.message === 'Key [_SS_profile] not found.') { // Android
// The callback expects no error, but also no value, if it cannot be found.
cb(null, null);
} else {
cb(new Error(error));
}
},
key);
};
root.set = function(key, value, cb) {
if (!platformInfo.isMobile) {
cb(new Error('mobileSecureStorageService is only available on mobile.'));
}
if (!isReady) {
if (initialisationFailed) {
cb(new Error('mobileSecureStorageService initialisation failed.'));
} else {
pending.push(function(){ root.set(key, value, cb); });
}
return;
}
storage.set(
function (value) {
cb();
},
function (error) {
cb(new Error(error));
},
key, value);
};
return root;
});

View file

@ -706,7 +706,7 @@ angular.module('copayApp.services')
configService.get(function(err) {
if (err) $log.debug(err);
var p = Profile.create();
var p = Profile.create(appConfigService.version);
storageService.storeNewProfile(p, function(err) {
if (err) return cb(err);
root.bindProfile(p, function(err) {

View file

@ -0,0 +1,53 @@
describe('rateService', function() {
var $httpBackend, rateService, requestHandler;
beforeEach(function() {
module('ngLodash');
module('copayApp.services');
inject(function($injector){
$httpBackend = $injector.get('$httpBackend');
requestHandler = $httpBackend.when('GET', 'https://www.bitcoin.com/special/rates.json')
.respond([
{
"code": "BTC",
"name": "Bitcoin",
"rate": 1
},
{
"code": "BCH_BTC",
"name": "Bitcoin Cash",
"rate": 6.739397
},
{
"code": "USD",
"name": "US Dollar",
"rate": 7602.04
}
]);
rateService = $injector.get('rateService');
$httpBackend.flush();
});
});
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('get rates', function() {
$httpBackend.expectGET('https://www.bitcoin.com/special/rates.json');
rateService.updateRates();
$httpBackend.flush();
var usdRate = rateService.getRate('USD');
expect(usdRate).toEqual(7602.04);
});
});

View file

@ -0,0 +1,32 @@
'use strict';
angular.module('copayApp.services').factory('secureStorageService', function(desktopSecureStorageService, localStorageService, $log, mobileSecureStorageService, platformInfo) {
var root = {};
// To make wrong code look wrong
function alteredKeyIndicatingDesireForSecureStorage(key) {
return key + ":desiredSecure";
}
root.get = function(k, cb) {
if (platformInfo.isMobile) {
mobileSecureStorageService.get(k, cb);
} else if (platformInfo.isNW) {
desktopSecureStorageService.get(k, cb);
} else { // Browser
localStorageService.get(alteredKeyIndicatingDesireForSecureStorage(k), cb);
}
}
root.set = function(k, v, cb) {
if (platformInfo.isMobile) {
mobileSecureStorageService.set(k, v, cb);
} else if (platformInfo.isNW) {
desktopSecureStorageService.set(k, v, cb);
} else { // Browser
localStorageService.set(alteredKeyIndicatingDesireForSecureStorage(k), v, cb);
}
}
return root;
});

View file

@ -0,0 +1,308 @@
describe('secureStorageService in browser', function(){
var localStorage,
sss;
beforeEach(function(){
module('ngLodash');
module('copayApp.services');
localStorage = {
get: jasmine.createSpy(),
set: jasmine.createSpy()
};
platformInfoStub = {
};
module(function($provide) {
$provide.value('localStorageService', localStorage);
$provide.value('platformInfo', platformInfoStub);
});
inject(function($injector){
sss = $injector.get('secureStorageService');
});
});
it('get fails', function() {
var error, key, result;
localStorage.get.and.callFake(function(k, cb){
key = k;
cb(new Error('Get error.'), null);
});
sss.get('a1234', function(e, res) {
error = e;
result = res;
});
expect(error.message).toBe('Get error.');
expect(result).toBeFalsy();
expect(key).toBe('a1234:desiredSecure');
});
it('get succeeds', function() {
var error, key, result;
localStorage.get.and.callFake(function(k, cb){
key = k;
cb(null, 'The result 1.');
});
sss.get('a123', function(e, res) {
error = e;
result = res;
});
expect(error).toBeFalsy();
expect(result).toBe('The result 1.');
expect(key).toBe('a123:desiredSecure');
});
it('set fails', function() {
var error, key, value;
localStorage.set.and.callFake(function(k, v, cb){
key = k;
value = v;
cb(new Error('Set error.'));
});
sss.set('a12345', 'The value 1.', function(e) {
error = e;
});
expect(error.message).toBe('Set error.');
expect(key).toBe('a12345:desiredSecure');
expect(value).toBe('The value 1.');
});
it('set succeeds', function() {
var error, key, value;
localStorage.set.and.callFake(function(k, v, cb){
key = k;
value = v;
cb(null);
});
sss.set('ab123', 'The value 2.', function(e) {
error = e;
});
expect(error).toBeFalsy();
expect(key).toBe('ab123:desiredSecure');
expect(value).toBe('The value 2.')
});
});
describe('secureStorageService on desktop', function(){
var desktopSss,
sss;
beforeEach(function(){
module('ngLodash');
module('copayApp.services');
desktopSss = {
get: jasmine.createSpy(),
set: jasmine.createSpy()
};
platformInfoStub = {
isNW: true
};
module(function($provide) {
$provide.value('desktopSecureStorageService', desktopSss);
$provide.value('platformInfo', platformInfoStub);
});
inject(function($injector){
sss = $injector.get('secureStorageService');
});
});
it('get fails', function() {
var error, key, result;
desktopSss.get.and.callFake(function(k, cb){
key = k;
cb(new Error('Get error.'), null);
});
sss.get('a1234', function(e, res) {
error = e;
result = res;
});
expect(error.message).toBe('Get error.');
expect(result).toBeFalsy();
expect(key).toBe('a1234');
});
it('get succeeds', function() {
var error, key, result;
desktopSss.get.and.callFake(function(k, cb){
key = k;
cb(null, 'The result 1.');
});
sss.get('a123', function(e, res) {
error = e;
result = res;
});
expect(error).toBeFalsy();
expect(result).toBe('The result 1.');
expect(key).toBe('a123');
});
it('set fails', function() {
var error, key, value;
desktopSss.set.and.callFake(function(k, v, cb){
key = k;
value = v;
cb(new Error('Set error.'));
});
sss.set('a12345', 'The value 1.', function(e) {
error = e;
});
expect(error.message).toBe('Set error.');
expect(key).toBe('a12345');
expect(value).toBe('The value 1.');
});
it('set succeeds', function() {
var error, key, value;
desktopSss.set.and.callFake(function(k, v, cb){
key = k;
value = v;
cb(null);
});
sss.set('ab123', 'The value 2.', function(e) {
error = e;
});
expect(error).toBeFalsy();
expect(key).toBe('ab123');
expect(value).toBe('The value 2.')
});
});
describe('secureStorageService on mobile', function(){
var mobileSss,
sss;
beforeEach(function(){
module('ngLodash');
module('copayApp.services');
mobileSss = {
get: jasmine.createSpy(),
set: jasmine.createSpy()
};
platformInfoStub = {
isMobile: true
};
module(function($provide) {
$provide.value('mobileSecureStorageService', mobileSss);
$provide.value('platformInfo', platformInfoStub);
});
inject(function($injector){
sss = $injector.get('secureStorageService');
});
});
it('get fails', function() {
var error, key, result;
mobileSss.get.and.callFake(function(k, cb){
key = k;
cb(new Error('Get error.'), null);
});
sss.get('a1234', function(e, res) {
error = e;
result = res;
});
expect(error.message).toBe('Get error.');
expect(result).toBeFalsy();
expect(key).toBe('a1234');
});
it('get succeeds', function() {
var error, key, result;
mobileSss.get.and.callFake(function(k, cb){
key = k;
cb(null, 'The result 1.');
});
sss.get('a123', function(e, res) {
error = e;
result = res;
});
expect(error).toBeFalsy();
expect(result).toBe('The result 1.');
expect(key).toBe('a123');
});
it('set fails', function() {
var error, key, value;
mobileSss.set.and.callFake(function(k, v, cb){
key = k;
value = v;
cb(new Error('Set error.'));
});
sss.set('a12345', 'The value 1.', function(e) {
error = e;
});
expect(error.message).toBe('Set error.');
expect(key).toBe('a12345');
expect(value).toBe('The value 1.');
});
it('set succeeds', function() {
var error, key, value;
mobileSss.set.and.callFake(function(k, v, cb){
key = k;
value = v;
cb(null);
});
sss.set('ab123', 'The value 2.', function(e) {
error = e;
});
expect(error).toBeFalsy();
expect(key).toBe('ab123');
expect(value).toBe('The value 2.')
});
});

View file

@ -1,6 +1,6 @@
'use strict';
angular.module('copayApp.services')
.factory('storageService', function(logHeader, fileStorageService, localStorageService, sjcl, $log, lodash, platformInfo, $timeout) {
.factory('storageService', function(appConfigService, logHeader, fileStorageService, localStorageService, sjcl, $log, lodash, platformInfo, secureStorageService, $timeout) {
var root = {};
var storage;
@ -116,34 +116,138 @@ angular.module('copayApp.services')
};
root.storeNewProfile = function(profile, cb) {
storage.create('profile', profile.toObj(), cb);
root.storeProfile(profile, cb);
};
root.storeProfile = function(profile, cb) {
storage.set('profile', profile.toObj(), cb);
var profileString = profile.toObj();
if (platformInfo.isNW) {
storage.set('profile', profileString, cb);
} else {
secureStorageService.set('profile', profileString, cb);
}
};
root.getProfile = function(cb) {
storage.get('profile', function(err, str) {
if (err || !str)
return cb(err);
/**
* @callback getProfileCallback
* @param {Error} error - falsy if profile not found.
* @param {Profile} profile - falsy if error or profile not found.
*/
decryptOnMobile(str, function(err, str) {
if (err) return cb(err);
var p, err;
try {
p = Profile.fromString(str);
} catch (e) {
$log.debug('Could not read profile:', e);
err = new Error('Could not read profile:' + p);
/**
* @param {Error} error
* @param {String} profileStr - containing the profile
* @param {getProfileCallback} cb
*/
function _onOldProfileRetrieved(error, profileStr, cb) {
if (error) {
return cb(error, null);
}
if (!profileStr) {
// No profiles found. No errors either.
return cb(null, null);
}
decryptOnMobile(profileStr, function(decryptErr, decryptedStr) {
if (decryptErr) return cb(decryptErr, null);
var profile;
try {
profile = Profile.fromString(decryptedStr);
} catch (e) {
$log.debug('Could not read profile:', e);
return(new Error('Could not read profile.'), null);
}
cb(null, profile)
});
}
/**
*
* @param {Profile} oldProfile
* @param {Profile} secureProfile - may be falsy if no secure profile found.
* @param {getProfileCallback} cb
*/
function _migrateProfiles(oldProfile, secureProfile, cb) {
var newProfile;
if (secureProfile) {
secureProfile.merge(oldProfile);
newProfile = secureProfile;
} else {
newProfile = oldProfile;
newProfile.setAppVersion(appConfigService.version);
}
root.storeNewProfile(newProfile, function(storeErr) {
if (storeErr) {
cb(storeErr, null);
return;
}
storage.remove('profile', function(removeErr){
if (removeErr) {
cb(removeErr, null);
return;
}
return cb(err, p);
cb(null, newProfile);
});
});
};
root.deleteProfile = function(cb) {
storage.remove('profile', cb);
/**
*
* @param {getProfileCallback} cb
*/
root.getProfile = function(cb) {
if (platformInfo.isNW) {
storage.get('profile', function(getErr, getStr) {
_onOldProfileRetrieved(getErr, getStr, cb);
});
return
}
secureStorageService.get('profile', function(secureErr, secureStr) {
var secureProfile;
var oldProfile;
if (secureErr) {
return cb(secureErr, null);
}
if (secureStr) {
try {
secureProfile = Profile.fromString(secureStr);
$log.debug('profile: ' + JSON.stringify(secureProfile));
} catch (e) {
$log.error(e);
return cb(e, null);
}
}
storage.get('profile', function(getErr, getStr) {
_onOldProfileRetrieved(getErr, getStr, function(oldErr, oldProfile){
if (oldErr) {
return cb(oldErr, null);
}
if (!oldProfile) {
if (secureProfile) {
return cb(null, secureProfile);
} else {
// No profiles found. No errors either.
return cb(null, null);
}
}
_migrateProfiles(oldProfile, secureProfile, cb);
});
});
});
};
root.setFeedbackInfo = function(feedbackValues, cb) {

File diff suppressed because one or more lines are too long

91
test/karma.conf.js Normal file
View file

@ -0,0 +1,91 @@
// Karma configuration
// Generated on Tue Jun 05 2018 16:39:51 GMT+1200 (NZST)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '..',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'node_modules/angular/angular.js',
// From Gruntfile.js
'bower_components/qrcode-generator/js/qrcode.js',
'bower_components/qrcode-generator/js/qrcode_UTF8.js',
'bower_components/moment/min/moment-with-locales.js',
'bower_components/angular-moment/angular-moment.js',
'bower_components/ng-lodash/build/ng-lodash.js',
'bower_components/angular-qrcode/angular-qrcode.js',
'bower_components/angular-gettext/dist/angular-gettext.js',
'bower_components/ng-csv/build/ng-csv.js',
'bower_components/ionic-toast/dist/ionic-toast.bundle.min.js',
'bower_components/angular-clipboard/angular-clipboard.js',
'bower_components/angular-md5/angular-md5.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/ngtouch/src/ngTouch.js',
'angular-bitauth/angular-bitauth.js',
'angular-bitcore-wallet-client/angular-bitcore-wallet-client.js',
'bower_components/ionic/release/js/ionic.bundle.min.js',
'bitcoin-cash-js/bitcoin-cash-js.js',
'src/js/**/*.js'
],
// list of files / patterns to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}