Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adds support for google drive backups on android #22

Merged
merged 3 commits into from Jan 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
31 changes: 31 additions & 0 deletions __tests__/setup.js
Expand Up @@ -31,3 +31,34 @@ jest.mock('frisbee', () => {
};
});
});

jest.mock('react-native-google-drive-api-wrapper', () => {
return {
setAccessToken: jest.fn(),
init: jest.fn(),
isInitialized: jest.fn(),
files: {
safeCreateFolder: jest.fn(),
createFileMultipart: jest.fn(),
get: jest.fn(),
getId: jest.fn(),
delete: jest.fn(),
list: jest.fn(() =>
Promise.resolve({
json: jest.fn(() => ({
files: jest.fn(),
})),
}),
),
},
};
});

jest.mock('@react-native-community/google-signin', () => {
return {
GoogleSignin: {
configure: jest.fn(),
getTokens: jest.fn(() => ({ accessToken: 'accessToken' })),
},
};
});
99 changes: 99 additions & 0 deletions __tests__/unit/cloudstore.android.test.js
@@ -0,0 +1,99 @@
import * as CloudStore from '../../src/cloudstore';
import * as GDriveCloudStorage from '../../src/GDriveCloudStorage';

describe('CloudStore android unit test', () => {
const keyId = '8abe1a93-6a9c-490c-bbd5-d7f11a4a9c8f';
const ciphertext = Buffer.from('encrypted stuff');

describe('putKey', () => {
it('fail on invalid args', async () => {
const setItemSpy = jest.spyOn(GDriveCloudStorage, 'setItem');

await expect(CloudStore.putKey({ keyId })).rejects.toThrow(/Invalid/);
expect(setItemSpy.mock.calls.length).toBe(0);
});

it('store item', async () => {
const getItemSpy = jest.spyOn(GDriveCloudStorage, 'getItem').mockImplementation();
const setItemSpy = jest.spyOn(GDriveCloudStorage, 'setItem');

await CloudStore.putKey({ keyId, ciphertext });
expect(setItemSpy.mock.calls[0][0]).toBe('1_photon_key_id');
expect(setItemSpy.mock.calls[0][1]).toBe(keyId);
expect(setItemSpy.mock.calls[1][0]).toBe('1_8abe1a93');
expect(setItemSpy.mock.calls[1][1]).toMatch(/^{"keyId":.*"}$/);
expect(setItemSpy.mock.calls.length).toBe(2);

getItemSpy.mockRestore();
setItemSpy.mockRestore();
});

it('should not backup twice', async () => {
const getItemSpy = jest.spyOn(GDriveCloudStorage, 'getItem').mockResolvedValue('resolved value');
const setItemSpy = jest.spyOn(GDriveCloudStorage, 'setItem');

await expect(CloudStore.putKey({ keyId, ciphertext })).rejects.toThrow(/already present/);
getItemSpy.mockRestore();

await CloudStore.putKey({ keyId, ciphertext });
expect(setItemSpy.mock.calls.length).toBe(2);

setItemSpy.mockRestore();
});
});

describe('getKey', () => {
it('should not find item', async () => {
const getItemSpy = jest.spyOn(GDriveCloudStorage, 'getItem').mockResolvedValue(null);

const stored = await CloudStore.getKey();
expect(stored).toBe(null);

getItemSpy.mockRestore();
});

it('should get stored item by key Id', async () => {
const result = {
keyId: keyId,
ciphertext: ciphertext,
time: new Date(),
};

const getItemSpy = jest
.spyOn(GDriveCloudStorage, 'getItem')
.mockImplementation()
.mockResolvedValueOnce(keyId)
.mockResolvedValueOnce(JSON.stringify(result));

const stored = await CloudStore.getKey();
expect(stored).toEqual({
keyId,
ciphertext,
time: expect.objectContaining(new Date()),
});

getItemSpy.mockRestore();
});

describe('removeKeyId', () => {
it('fail on invalid args', async () => {
const result = {
keyId: keyId,
ciphertext: ciphertext,
time: new Date(),
};

const removeItemSpy = jest.spyOn(GDriveCloudStorage, 'removeItem');
const getItemSpy = jest.spyOn(GDriveCloudStorage, 'getItem').mockResolvedValueOnce(keyId).mockResolvedValue(JSON.stringify(result));
const getKeySpy = jest.spyOn(CloudStore, 'getKey').mockResolvedValue(result);

await expect(CloudStore.removeKeyId({ keyId: 'invalid' })).rejects.toThrow(/not found/);
expect(getItemSpy.mock.calls.length).toBe(2);

getItemSpy.mockRestore();
removeItemSpy.mockRestore();
getKeySpy.mockRestore();
});
});
});
});
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice 👍 Does jest emulate an Android environment if the file is called *.android.test.js or how does it work?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No unfortunately not, the naming convention just makes it a bit easier to run in isolation here it's not ideal to have a setup file for running in the android environment but changing the Platform directly in the tests doesn't seem to work so this is a workaround using Haste.

14 changes: 14 additions & 0 deletions jest.android.json
@@ -0,0 +1,14 @@
{
"preset": "react-native",
"transform": {
"^.+\\.js$": "<rootDir>/node_modules/react-native/jest/preprocessor.js"
},
"haste": {
"defaultPlatform": "android",
"platforms": ["android"]
},
"watchPathIgnorePatterns": [
"<rootDir>/node_modules"
],
"setupFiles": ["./__tests__/setup.js"]
}
9 changes: 8 additions & 1 deletion package.json
Expand Up @@ -10,13 +10,15 @@
"type": "module",
"main": "src/index.js",
"scripts": {
"test": "npm run test:lint && npm run test:unit && npm run test:integration",
"test": "npm run test:lint && npm run test:unit && npm run test:unit:android && npm run test:integration",
"test:lint": "eslint .",
"test:unit": "jest __tests__/unit/*",
"test:unit:android": "jest --config jest.android.json __tests__/unit/.*\\.android\\..*",
"test:integration": "jest __tests__/integration/*"
},
"dependencies": {
"@photon-sdk/rn-electrum-client": "^4.0.0",
"@react-native-community/google-signin": "^5.0.0",
"base-x": "^3.0.8",
"bc-ur": "^0.1.6",
"bech32": "^1.1.4",
Expand All @@ -31,6 +33,7 @@
"create-hash": "^1.2.0",
"electrum-mnemonic": "^2.0.0",
"frisbee": "^3.1.2",
"react-native-google-drive-api-wrapper": "^1.3.0",
"util": "^0.12.3"
},
"peerDependencies": {
Expand Down Expand Up @@ -79,6 +82,10 @@
],
"watchPathIgnorePatterns": [
"<rootDir>/node_modules"
],
"testPathIgnorePatterns": [
"node_modules",
".*\\.android\\..*"
]
}
}
66 changes: 66 additions & 0 deletions src/GDriveCloudStorage.js
@@ -0,0 +1,66 @@
import GDrive from 'react-native-google-drive-api-wrapper';
import { GoogleSignin, statusCodes } from '@react-native-community/google-signin';

export async function authenticate(options = {}) {
GoogleSignin.configure({
scopes: ['https://www.googleapis.com/auth/drive.appdata'],
...options,
});
await GoogleSignin.hasPlayServices({
showPlayServicesUpdateDialog: true,
});
try {
await GoogleSignin.signInSilently();
} catch (error) {
if (error.code === statusCodes.SIGN_IN_REQUIRED) {
await GoogleSignin.signIn();
}
}
const { accessToken } = await GoogleSignin.getTokens();
GDrive.setAccessToken(accessToken);
GDrive.init();
if (!GDrive.isInitialized) {
throw new Error('Unable to use GDrive');
}
}

export async function setItem(keyId, value) {
const content = Buffer.from(value).toString('base64');
await GDrive.files.createFileMultipart(
content,
'text/plain',
{
parents: ['appDataFolder'],
name: keyId,
},
true,
);
}

export async function _getFileId(keyId) {
const response = await GDrive.files.list({ spaces: 'appDataFolder', fields: 'nextPageToken, files(id, name)' });
const json = await response.json();
if (json.files.length === 0) {
return null;
}
const file = json.files.find(file => file.name === keyId);
return file ? file.id : null;
}

export async function getItem(keyId) {
const fileId = await _getFileId(keyId);
if (!fileId) {
return null;
}
const response = await GDrive.files.get(fileId, { alt: 'media' });
const key = await response.text();
return key;
}

export async function removeItem(keyId) {
const fileId = await _getFileId(keyId);
if (!fileId) {
return null;
}
await GDrive.files.delete(fileId);
}
11 changes: 9 additions & 2 deletions src/cloudstore.js
Expand Up @@ -5,15 +5,22 @@

import { Platform } from 'react-native';
import RNiCloudStorage from '@photon-sdk/react-native-icloudstore';
import AsyncStorage from '@react-native-community/async-storage';
import * as GDriveCloudStorage from './GDriveCloudStorage';
import { isPhone, isEmail, isId, isBuffer } from './verify';
const Store = Platform.OS === 'ios' ? RNiCloudStorage : AsyncStorage;

const Store = Platform.OS === 'ios' ? RNiCloudStorage : GDriveCloudStorage;

const VERSION = '1';
const KEY_ID = `${VERSION}_photon_key_id`;
const PHONE = `${VERSION}_photon_phone`;
const EMAIL = `${VERSION}_photon_email`;

export async function authenticate(options) {
if (Store.authenticate) {
await Store.authenticate(options);
}
}

//
// Encrypted key storage
//
Expand Down