Search in sources :

Example 1 with MXFileStore

use of org.matrix.androidsdk.data.store.MXFileStore in project matrix-android-sdk by matrix-org.

the class CryptoTest method test10_testAliceDecryptOldMessageWithANewDeviceInACryptedRoom.

@Test
public void test10_testAliceDecryptOldMessageWithANewDeviceInACryptedRoom() throws Exception {
    Log.e(LOG_TAG, "test10_testAliceDecryptOldMessageWithANewDeviceInACryptedRoom");
    Context context = InstrumentationRegistry.getContext();
    final HashMap<String, Object> results = new HashMap<>();
    doE2ETestWithAliceInARoom();
    mAliceSession.getCrypto().setWarnOnUnknownDevices(false);
    String message = "Hello myself!";
    Room roomFromAlicePOV = mAliceSession.getDataHandler().getRoom(mRoomId);
    final CountDownLatch lock1 = new CountDownLatch(1);
    roomFromAlicePOV.sendEvent(buildTextEvent(message, mAliceSession), new ApiCallback<Void>() {

        @Override
        public void onSuccess(Void info) {
            results.put("sendEvent", "sendEvent");
            lock1.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
            lock1.countDown();
        }

        @Override
        public void onMatrixError(MatrixError e) {
            lock1.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            lock1.countDown();
        }
    });
    lock1.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("sendEvent"));
    Credentials aliceCredentials = mAliceSession.getCredentials();
    Credentials aliceCredentials2 = new Credentials();
    // close the session and clear the data
    mAliceSession.clear(context);
    aliceCredentials2.userId = aliceCredentials.userId;
    aliceCredentials2.homeServer = aliceCredentials.homeServer;
    aliceCredentials2.accessToken = aliceCredentials.accessToken;
    aliceCredentials2.refreshToken = aliceCredentials.refreshToken;
    aliceCredentials2.deviceId = "AliceNewDevice";
    Uri uri = Uri.parse(CryptoTestHelper.TESTS_HOME_SERVER_URL);
    HomeServerConnectionConfig hs = new HomeServerConnectionConfig(uri);
    hs.setCredentials(aliceCredentials2);
    IMXStore store = new MXFileStore(hs, context);
    MXSession aliceSession2 = new MXSession(hs, new MXDataHandler(store, aliceCredentials2), context);
    aliceSession2.enableCryptoWhenStarting();
    final CountDownLatch lock1b = new CountDownLatch(1);
    MXStoreListener listener = new MXStoreListener() {

        @Override
        public void postProcess(String accountId) {
        }

        @Override
        public void onStoreReady(String accountId) {
            results.put("onStoreReady", "onStoreReady");
            lock1b.countDown();
        }

        @Override
        public void onStoreCorrupted(String accountId, String description) {
            lock1b.countDown();
        }

        @Override
        public void onStoreOOM(String accountId, String description) {
            lock1b.countDown();
        }
    };
    aliceSession2.getDataHandler().getStore().addMXStoreListener(listener);
    aliceSession2.getDataHandler().getStore().open();
    lock1b.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("onStoreReady"));
    final CountDownLatch lock2 = new CountDownLatch(2);
    MXEventListener eventListener = new MXEventListener() {

        @Override
        public void onInitialSyncComplete(String toToken) {
            results.put("onInitialSyncComplete", "onInitialSyncComplete");
            lock2.countDown();
        }

        @Override
        public void onCryptoSyncComplete() {
            results.put("onCryptoSyncComplete", "onCryptoSyncComplete");
            lock2.countDown();
        }
    };
    aliceSession2.getDataHandler().addListener(eventListener);
    aliceSession2.startEventStream(null);
    lock2.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("onInitialSyncComplete"));
    assertTrue(results.containsKey("onCryptoSyncComplete"));
    Room roomFromAlicePOV2 = aliceSession2.getDataHandler().getRoom(mRoomId);
    assertTrue(null != roomFromAlicePOV2);
    assertTrue(roomFromAlicePOV2.getLiveState().isEncrypted());
    Event event = roomFromAlicePOV2.getDataHandler().getStore().getLatestEvent(mRoomId);
    assertTrue(null != event);
    assertTrue(event.isEncrypted());
    assertTrue(null == event.getClearEvent());
    assertTrue(null != event.getCryptoError());
    assertTrue(TextUtils.equals(event.getCryptoError().errcode, MXCryptoError.UNKNOWN_INBOUND_SESSION_ID_ERROR_CODE));
    aliceSession2.clear(context);
}
Also used : Context(android.content.Context) MXStoreListener(org.matrix.androidsdk.data.store.MXStoreListener) HashMap(java.util.HashMap) IMXStore(org.matrix.androidsdk.data.store.IMXStore) MXFileStore(org.matrix.androidsdk.data.store.MXFileStore) CountDownLatch(java.util.concurrent.CountDownLatch) Uri(android.net.Uri) MXEventListener(org.matrix.androidsdk.listeners.MXEventListener) Event(org.matrix.androidsdk.rest.model.Event) JsonObject(com.google.gson.JsonObject) MatrixError(org.matrix.androidsdk.rest.model.MatrixError) Room(org.matrix.androidsdk.data.Room) Credentials(org.matrix.androidsdk.rest.model.login.Credentials) Test(org.junit.Test)

Example 2 with MXFileStore

use of org.matrix.androidsdk.data.store.MXFileStore in project matrix-android-sdk by matrix-org.

the class CryptoTest method test03_testKeysUploadAndDownload.

@Test
public void test03_testKeysUploadAndDownload() throws Exception {
    Log.e(LOG_TAG, "test03_testKeysUploadAndDownload");
    Context context = InstrumentationRegistry.getContext();
    final HashMap<String, Object> results = new HashMap<>();
    createAliceAccount();
    mAliceSession.getCredentials().deviceId = "AliceDevice";
    final CountDownLatch lock0 = new CountDownLatch(1);
    mAliceSession.enableCrypto(true, new ApiCallback<Void>() {

        @Override
        public void onSuccess(Void info) {
            results.put("enableCrypto", "enableCrypto");
            lock0.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
            lock0.countDown();
        }

        @Override
        public void onMatrixError(MatrixError e) {
            lock0.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            lock0.countDown();
        }
    });
    lock0.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("enableCrypto"));
    createBobAccount();
    final CountDownLatch lock2 = new CountDownLatch(1);
    mBobSession.getCredentials().deviceId = "BobDevice";
    mBobSession.enableCrypto(true, new ApiCallback<Void>() {

        @Override
        public void onSuccess(Void info) {
            results.put("enableCrypto2", "enableCrypto2");
            lock2.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
            lock2.countDown();
        }

        @Override
        public void onMatrixError(MatrixError e) {
            lock2.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            lock2.countDown();
        }
    });
    lock2.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("enableCrypto2"));
    final CountDownLatch lock3 = new CountDownLatch(1);
    mBobSession.getCrypto().getDeviceList().downloadKeys(Arrays.asList(mBobSession.getMyUserId(), mAliceSession.getMyUserId()), false, new ApiCallback<MXUsersDevicesMap<MXDeviceInfo>>() {

        @Override
        public void onSuccess(MXUsersDevicesMap<MXDeviceInfo> info) {
            results.put("downloadKeys", info);
            lock3.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
            lock3.countDown();
        }

        @Override
        public void onMatrixError(MatrixError e) {
            lock3.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            lock3.countDown();
        }
    });
    lock3.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("downloadKeys"));
    MXUsersDevicesMap<MXDeviceInfo> usersDevicesInfoMap = (MXUsersDevicesMap<MXDeviceInfo>) results.get("downloadKeys");
    assertTrue(2 == usersDevicesInfoMap.getUserIds().size());
    assertTrue(1 == usersDevicesInfoMap.getUserDeviceIds(mAliceSession.getMyUserId()).size());
    MXDeviceInfo aliceDeviceFromBobPOV = usersDevicesInfoMap.getObject("AliceDevice", mAliceSession.getMyUserId());
    assertTrue(null != aliceDeviceFromBobPOV);
    assertTrue(TextUtils.equals(aliceDeviceFromBobPOV.fingerprint(), mAliceSession.getCrypto().getOlmDevice().getDeviceEd25519Key()));
    // Continue testing other methods
    assertTrue(null != mBobSession.getCrypto().deviceWithIdentityKey(mAliceSession.getCrypto().getOlmDevice().getDeviceCurve25519Key(), mAliceSession.getMyUserId(), MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_OLM));
    assertTrue(aliceDeviceFromBobPOV.isUnknown());
    final CountDownLatch lock3a = new CountDownLatch(1);
    mBobSession.getCrypto().setDevicesKnown(Arrays.asList(aliceDeviceFromBobPOV), new ApiCallback<Void>() {

        @Override
        public void onSuccess(Void info) {
            results.put("setDevicesKnown", info);
            lock3a.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
            lock3a.countDown();
        }

        @Override
        public void onMatrixError(MatrixError e) {
            lock3a.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            lock3a.countDown();
        }
    });
    lock3a.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("setDevicesKnown"));
    assertTrue(aliceDeviceFromBobPOV.isUnverified());
    final CountDownLatch lock3b = new CountDownLatch(1);
    mBobSession.getCrypto().setDeviceVerification(MXDeviceInfo.DEVICE_VERIFICATION_BLOCKED, aliceDeviceFromBobPOV.deviceId, mAliceSession.getMyUserId(), new ApiCallback<Void>() {

        @Override
        public void onSuccess(Void info) {
            results.put("setDeviceVerification1", info);
            lock3b.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
            lock3b.countDown();
        }

        @Override
        public void onMatrixError(MatrixError e) {
            lock3b.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            lock3b.countDown();
        }
    });
    lock3b.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("setDeviceVerification1"));
    assertTrue(aliceDeviceFromBobPOV.isBlocked());
    Credentials bobCredentials = mBobSession.getCredentials();
    Uri uri = Uri.parse(CryptoTestHelper.TESTS_HOME_SERVER_URL);
    HomeServerConnectionConfig hs = new HomeServerConnectionConfig(uri);
    hs.setCredentials(bobCredentials);
    IMXStore store = new MXFileStore(hs, context);
    MXSession bobSession2 = new MXSession(hs, new MXDataHandler(store, bobCredentials), context);
    final CountDownLatch lock4 = new CountDownLatch(1);
    MXStoreListener listener = new MXStoreListener() {

        @Override
        public void postProcess(String accountId) {
        }

        @Override
        public void onStoreReady(String accountId) {
            results.put("onStoreReady", "onStoreReady");
            lock4.countDown();
        }

        @Override
        public void onStoreCorrupted(String accountId, String description) {
            lock4.countDown();
        }

        @Override
        public void onStoreOOM(String accountId, String description) {
            lock4.countDown();
        }
    };
    bobSession2.getDataHandler().getStore().addMXStoreListener(listener);
    bobSession2.getDataHandler().getStore().open();
    lock4.await(2000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("onStoreReady"));
    final CountDownLatch lock4b = new CountDownLatch(2);
    MXEventListener eventListener = new MXEventListener() {

        @Override
        public void onInitialSyncComplete(String toToken) {
            results.put("onInitialSyncComplete", "onInitialSyncComplete");
            lock4b.countDown();
        }

        @Override
        public void onCryptoSyncComplete() {
            results.put("onCryptoSyncComplete", "onCryptoSyncComplete");
            lock4b.countDown();
        }
    };
    bobSession2.getDataHandler().addListener(eventListener);
    bobSession2.startEventStream(null);
    lock4b.await(2000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("onInitialSyncComplete"));
    assertTrue(results.containsKey("onCryptoSyncComplete"));
    MXDeviceInfo aliceDeviceFromBobPOV2 = bobSession2.getCrypto().deviceWithIdentityKey(mAliceSession.getCrypto().getOlmDevice().getDeviceCurve25519Key(), mAliceSession.getMyUserId(), MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_OLM);
    assertTrue(null != aliceDeviceFromBobPOV2);
    assertTrue(TextUtils.equals(aliceDeviceFromBobPOV2.fingerprint(), mAliceSession.getCrypto().getOlmDevice().getDeviceEd25519Key()));
    assertTrue(aliceDeviceFromBobPOV2.mVerified + " instead of " + MXDeviceInfo.DEVICE_VERIFICATION_BLOCKED, aliceDeviceFromBobPOV2.mVerified == MXDeviceInfo.DEVICE_VERIFICATION_BLOCKED);
    // Download again alice device
    final CountDownLatch lock5 = new CountDownLatch(1);
    bobSession2.getCrypto().getDeviceList().downloadKeys(Arrays.asList(mAliceSession.getMyUserId()), true, new ApiCallback<MXUsersDevicesMap<MXDeviceInfo>>() {

        @Override
        public void onSuccess(MXUsersDevicesMap<MXDeviceInfo> info) {
            results.put("downloadKeys2", info);
            lock5.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
            lock5.countDown();
        }

        @Override
        public void onMatrixError(MatrixError e) {
            lock5.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            lock5.countDown();
        }
    });
    lock5.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("downloadKeys2"));
    MXDeviceInfo aliceDeviceFromBobPOV3 = bobSession2.getCrypto().deviceWithIdentityKey(mAliceSession.getCrypto().getOlmDevice().getDeviceCurve25519Key(), mAliceSession.getMyUserId(), MXCryptoAlgorithms.MXCRYPTO_ALGORITHM_OLM);
    assertTrue(null != aliceDeviceFromBobPOV3);
    assertTrue(TextUtils.equals(aliceDeviceFromBobPOV3.fingerprint(), mAliceSession.getCrypto().getOlmDevice().getDeviceEd25519Key()));
    assertTrue(aliceDeviceFromBobPOV3.isBlocked());
    mAliceSession.clear(context);
    mBobSession.clear(context);
    bobSession2.clear(context);
}
Also used : Context(android.content.Context) MXStoreListener(org.matrix.androidsdk.data.store.MXStoreListener) HashMap(java.util.HashMap) IMXStore(org.matrix.androidsdk.data.store.IMXStore) MXFileStore(org.matrix.androidsdk.data.store.MXFileStore) MXDeviceInfo(org.matrix.androidsdk.crypto.data.MXDeviceInfo) CountDownLatch(java.util.concurrent.CountDownLatch) MXUsersDevicesMap(org.matrix.androidsdk.crypto.data.MXUsersDevicesMap) Uri(android.net.Uri) MXEventListener(org.matrix.androidsdk.listeners.MXEventListener) JsonObject(com.google.gson.JsonObject) MatrixError(org.matrix.androidsdk.rest.model.MatrixError) Credentials(org.matrix.androidsdk.rest.model.login.Credentials) Test(org.junit.Test)

Example 3 with MXFileStore

use of org.matrix.androidsdk.data.store.MXFileStore in project matrix-android-sdk by matrix-org.

the class CryptoTest method test09_testAliceInACryptedRoomAfterInitialSync.

@Test
public void test09_testAliceInACryptedRoomAfterInitialSync() throws Exception {
    Log.e(LOG_TAG, "test09_testAliceInACryptedRoomAfterInitialSync");
    Context context = InstrumentationRegistry.getContext();
    final HashMap<String, Object> results = new HashMap<>();
    doE2ETestWithAliceInARoom();
    mAliceSession.getCrypto().setWarnOnUnknownDevices(false);
    final String message = "Hello myself!";
    Credentials aliceCredentials = mAliceSession.getCredentials();
    mAliceSession.clear(context);
    Uri uri = Uri.parse(CryptoTestHelper.TESTS_HOME_SERVER_URL);
    HomeServerConnectionConfig hs = new HomeServerConnectionConfig(uri);
    hs.setCredentials(aliceCredentials);
    IMXStore store = new MXFileStore(hs, context);
    final CountDownLatch lock1 = new CountDownLatch(1);
    final MXSession aliceSession2 = new MXSession(hs, new MXDataHandler(store, aliceCredentials), context);
    MXStoreListener listener = new MXStoreListener() {

        @Override
        public void postProcess(String accountId) {
        }

        @Override
        public void onStoreReady(String accountId) {
            results.put("onStoreReady", "onStoreReady");
            lock1.countDown();
        }

        @Override
        public void onStoreCorrupted(String accountId, String description) {
            lock1.countDown();
        }

        @Override
        public void onStoreOOM(String accountId, String description) {
            lock1.countDown();
        }
    };
    aliceSession2.getDataHandler().getStore().addMXStoreListener(listener);
    aliceSession2.getDataHandler().getStore().open();
    lock1.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("onStoreReady"));
    final CountDownLatch lock1b = new CountDownLatch(2);
    MXEventListener eventListener = new MXEventListener() {

        @Override
        public void onInitialSyncComplete(String toToken) {
            results.put("onInitialSyncComplete", "onInitialSyncComplete");
            lock1b.countDown();
        }

        @Override
        public void onCryptoSyncComplete() {
            results.put("onCryptoSyncComplete", "onCryptoSyncComplete");
            lock1b.countDown();
        }
    };
    aliceSession2.getDataHandler().addListener(eventListener);
    aliceSession2.startEventStream(null);
    lock1b.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("onInitialSyncComplete"));
    assertTrue(results.containsKey("onCryptoSyncComplete"));
    Room roomFromAlicePOV2 = aliceSession2.getDataHandler().getRoom(mRoomId);
    assertTrue(roomFromAlicePOV2.isEncrypted());
    final CountDownLatch lock2 = new CountDownLatch(1);
    if (false) {
        // The android client does not echo its own message
        MXEventListener aliceEventListener = new MXEventListener() {

            @Override
            public void onLiveEvent(Event event, RoomState roomState) {
                if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE)) {
                    try {
                        if (checkEncryptedEvent(event, mRoomId, message, aliceSession2)) {
                            lock2.countDown();
                        }
                    } catch (Exception e) {
                    }
                }
            }
        };
        roomFromAlicePOV2.addEventListener(aliceEventListener);
    }
    // the IOS client echoes the message
    // the android client does not
    roomFromAlicePOV2.sendEvent(buildTextEvent(message, aliceSession2), new ApiCallback<Void>() {

        @Override
        public void onSuccess(Void info) {
            results.put("sendEvent", "sendEvent");
            lock2.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
            lock2.countDown();
        }

        @Override
        public void onMatrixError(MatrixError e) {
            lock2.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            lock2.countDown();
        }
    });
    lock2.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("sendEvent"));
    aliceSession2.clear(context);
}
Also used : Context(android.content.Context) MXStoreListener(org.matrix.androidsdk.data.store.MXStoreListener) HashMap(java.util.HashMap) IMXStore(org.matrix.androidsdk.data.store.IMXStore) MXFileStore(org.matrix.androidsdk.data.store.MXFileStore) CountDownLatch(java.util.concurrent.CountDownLatch) Uri(android.net.Uri) MXEventListener(org.matrix.androidsdk.listeners.MXEventListener) Event(org.matrix.androidsdk.rest.model.Event) JsonObject(com.google.gson.JsonObject) MatrixError(org.matrix.androidsdk.rest.model.MatrixError) Room(org.matrix.androidsdk.data.Room) Credentials(org.matrix.androidsdk.rest.model.login.Credentials) RoomState(org.matrix.androidsdk.data.RoomState) Test(org.junit.Test)

Example 4 with MXFileStore

use of org.matrix.androidsdk.data.store.MXFileStore in project matrix-android-sdk by matrix-org.

the class CryptoTestHelper method createAccountAndSync.

/**
 * Create an account and a dedicated session
 * @param context the context
 * @param userName the account username
 * @param password the password
 * @param startSession true to perform an initial sync
 * @throws Exception an exception if the account creation failed
 */
public static MXSession createAccountAndSync(Context context, String userName, String password, boolean startSession) throws Exception {
    Uri uri = Uri.parse(TESTS_HOME_SERVER_URL);
    HomeServerConnectionConfig hs = new HomeServerConnectionConfig(uri);
    LoginRestClient loginRestClient = new LoginRestClient(hs);
    final HashMap<String, Object> params = new HashMap<>();
    RegistrationParams registrationParams = new RegistrationParams();
    mLock = new CountDownLatch(1);
    // get the registration session id
    loginRestClient.register(registrationParams, new ApiCallback<Credentials>() {

        @Override
        public void onSuccess(Credentials credentials) {
            mLock.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
            mLock.countDown();
        }

        @Override
        public void onMatrixError(MatrixError e) {
            // detect if a parameter is expected
            RegistrationFlowResponse registrationFlowResponse = null;
            // when a response is not completed the server returns an error message
            if ((null != e.mStatus) && (e.mStatus == 401)) {
                try {
                    registrationFlowResponse = JsonUtils.toRegistrationFlowResponse(e.mErrorBodyAsString);
                } catch (Exception castExcept) {
                }
            }
            // check if the server response can be casted
            if (null != registrationFlowResponse) {
                params.put("session", registrationFlowResponse.session);
            }
            mLock.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            mLock.countDown();
        }
    });
    mLock.await(10000, TimeUnit.MILLISECONDS);
    String session = (String) params.get("session");
    assertTrue(null != session);
    registrationParams.username = userName;
    registrationParams.password = password;
    HashMap<String, Object> authParams = new HashMap<>();
    authParams.put("session", session);
    authParams.put("type", LoginRestClient.LOGIN_FLOW_TYPE_DUMMY);
    registrationParams.auth = authParams;
    mLock = new CountDownLatch(1);
    loginRestClient.register(registrationParams, new ApiCallback<Credentials>() {

        @Override
        public void onSuccess(Credentials credentials) {
            params.put("credentials", credentials);
            mLock.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
            mLock.countDown();
        }

        @Override
        public void onMatrixError(MatrixError e) {
            mLock.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            mLock.countDown();
        }
    });
    mLock.await(10000, TimeUnit.MILLISECONDS);
    Credentials credentials = (Credentials) params.get("credentials");
    assertTrue(null != credentials);
    hs.setCredentials(credentials);
    IMXStore store = new MXFileStore(hs, context);
    MXSession mxSession = new MXSession(hs, new MXDataHandler(store, credentials), context);
    if (!startSession) {
        return mxSession;
    }
    mxSession.getDataHandler().getStore().open();
    mxSession.startEventStream(null);
    mLock = new CountDownLatch(1);
    mxSession.getDataHandler().addListener(new MXEventListener() {

        @Override
        public void onInitialSyncComplete(String toToken) {
            params.put("isInit", true);
            mLock.countDown();
        }
    });
    mLock.await(100000, TimeUnit.MILLISECONDS);
    assertTrue(params.containsKey("isInit"));
    return mxSession;
}
Also used : HashMap(java.util.HashMap) RegistrationFlowResponse(org.matrix.androidsdk.rest.model.login.RegistrationFlowResponse) IMXStore(org.matrix.androidsdk.data.store.IMXStore) MXFileStore(org.matrix.androidsdk.data.store.MXFileStore) CountDownLatch(java.util.concurrent.CountDownLatch) Uri(android.net.Uri) MXEventListener(org.matrix.androidsdk.listeners.MXEventListener) RegistrationParams(org.matrix.androidsdk.rest.model.login.RegistrationParams) LoginRestClient(org.matrix.androidsdk.rest.client.LoginRestClient) MatrixError(org.matrix.androidsdk.rest.model.MatrixError) Credentials(org.matrix.androidsdk.rest.model.login.Credentials)

Example 5 with MXFileStore

use of org.matrix.androidsdk.data.store.MXFileStore in project matrix-android-sdk by matrix-org.

the class CryptoTest method test24_testExportImport.

@Test
public void test24_testExportImport() throws Exception {
    Log.e(LOG_TAG, "test24_testExportImport");
    Context context = InstrumentationRegistry.getContext();
    final HashMap<String, Object> results = new HashMap<>();
    doE2ETestWithAliceInARoom();
    mAliceSession.getCrypto().setWarnOnUnknownDevices(false);
    String message = "Hello myself!";
    String password = "hello";
    Room roomFromAlicePOV = mAliceSession.getDataHandler().getRoom(mRoomId);
    final CountDownLatch lock1 = new CountDownLatch(1);
    roomFromAlicePOV.sendEvent(buildTextEvent(message, mAliceSession), new ApiCallback<Void>() {

        @Override
        public void onSuccess(Void info) {
            results.put("sendEvent", "sendEvent");
            lock1.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
            lock1.countDown();
        }

        @Override
        public void onMatrixError(MatrixError e) {
            lock1.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            lock1.countDown();
        }
    });
    lock1.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("sendEvent"));
    Credentials aliceCredentials = mAliceSession.getCredentials();
    Credentials aliceCredentials2 = new Credentials();
    final CountDownLatch lock1a = new CountDownLatch(1);
    mAliceSession.getCrypto().exportRoomKeys(password, new ApiCallback<byte[]>() {

        @Override
        public void onSuccess(byte[] info) {
            results.put("exportRoomKeys", info);
            lock1a.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
            lock1a.countDown();
        }

        @Override
        public void onMatrixError(MatrixError e) {
            lock1a.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            lock1a.countDown();
        }
    });
    lock1a.await(10000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("exportRoomKeys"));
    // close the session and clear the data
    mAliceSession.clear(context);
    aliceCredentials2.userId = aliceCredentials.userId;
    aliceCredentials2.homeServer = aliceCredentials.homeServer;
    aliceCredentials2.accessToken = aliceCredentials.accessToken;
    aliceCredentials2.refreshToken = aliceCredentials.refreshToken;
    aliceCredentials2.deviceId = "AliceNewDevice";
    Uri uri = Uri.parse(CryptoTestHelper.TESTS_HOME_SERVER_URL);
    HomeServerConnectionConfig hs = new HomeServerConnectionConfig(uri);
    hs.setCredentials(aliceCredentials2);
    IMXStore store = new MXFileStore(hs, context);
    MXSession aliceSession2 = new MXSession(hs, new MXDataHandler(store, aliceCredentials2), context);
    aliceSession2.enableCryptoWhenStarting();
    final CountDownLatch lock1b = new CountDownLatch(1);
    MXStoreListener listener = new MXStoreListener() {

        @Override
        public void postProcess(String accountId) {
        }

        @Override
        public void onStoreReady(String accountId) {
            results.put("onStoreReady", "onStoreReady");
            lock1b.countDown();
        }

        @Override
        public void onStoreCorrupted(String accountId, String description) {
            lock1b.countDown();
        }

        @Override
        public void onStoreOOM(String accountId, String description) {
            lock1b.countDown();
        }
    };
    aliceSession2.getDataHandler().getStore().addMXStoreListener(listener);
    aliceSession2.getDataHandler().getStore().open();
    lock1b.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("onStoreReady"));
    final CountDownLatch lock2 = new CountDownLatch(2);
    MXEventListener eventListener = new MXEventListener() {

        @Override
        public void onInitialSyncComplete(String toToken) {
            results.put("onInitialSyncComplete", "onInitialSyncComplete");
            lock2.countDown();
        }

        @Override
        public void onCryptoSyncComplete() {
            results.put("onCryptoSyncComplete", "onCryptoSyncComplete");
            lock2.countDown();
        }
    };
    aliceSession2.getDataHandler().addListener(eventListener);
    aliceSession2.startEventStream(null);
    lock2.await(1000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("onInitialSyncComplete"));
    assertTrue(results.containsKey("onCryptoSyncComplete"));
    Room roomFromAlicePOV2 = aliceSession2.getDataHandler().getRoom(mRoomId);
    assertTrue(null != roomFromAlicePOV2);
    assertTrue(roomFromAlicePOV2.getLiveState().isEncrypted());
    Event event = roomFromAlicePOV2.getDataHandler().getStore().getLatestEvent(mRoomId);
    assertTrue(null != event);
    assertTrue(event.isEncrypted());
    assertTrue(null == event.getClearEvent());
    assertTrue(null != event.getCryptoError());
    assertTrue(TextUtils.equals(event.getCryptoError().errcode, MXCryptoError.UNKNOWN_INBOUND_SESSION_ID_ERROR_CODE));
    // import the e2e keys
    // test with a wrong password
    final CountDownLatch lock3 = new CountDownLatch(1);
    aliceSession2.getCrypto().importRoomKeys((byte[]) results.get("exportRoomKeys"), "wrong password", new ApiCallback<Void>() {

        @Override
        public void onSuccess(Void info) {
            results.put("importRoomKeys", "importRoomKeys");
            lock3.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
            results.put("importRoomKeys_failed", "importRoomKeys_failed");
            lock3.countDown();
        }

        @Override
        public void onMatrixError(MatrixError e) {
            results.put("importRoomKeys_failed", "importRoomKeys_failed");
            lock3.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            results.put("importRoomKeys_failed", "importRoomKeys_failed");
            lock3.countDown();
        }
    });
    lock3.await(10000, TimeUnit.MILLISECONDS);
    assertTrue(!results.containsKey("importRoomKeys"));
    assertTrue(results.containsKey("importRoomKeys_failed"));
    // check that the message cannot be decrypted
    event = roomFromAlicePOV2.getDataHandler().getStore().getLatestEvent(mRoomId);
    assertTrue(null != event);
    assertTrue(event.isEncrypted());
    assertTrue(null == event.getClearEvent());
    assertTrue(null != event.getCryptoError());
    assertTrue(TextUtils.equals(event.getCryptoError().errcode, MXCryptoError.UNKNOWN_INBOUND_SESSION_ID_ERROR_CODE));
    final CountDownLatch lock4 = new CountDownLatch(1);
    aliceSession2.getCrypto().importRoomKeys((byte[]) results.get("exportRoomKeys"), password, new ApiCallback<Void>() {

        @Override
        public void onSuccess(Void info) {
            results.put("importRoomKeys", "importRoomKeys");
            lock4.countDown();
        }

        @Override
        public void onNetworkError(Exception e) {
            lock4.countDown();
        }

        @Override
        public void onMatrixError(MatrixError e) {
            lock4.countDown();
        }

        @Override
        public void onUnexpectedError(Exception e) {
            lock4.countDown();
        }
    });
    lock4.await(10000, TimeUnit.MILLISECONDS);
    assertTrue(results.containsKey("importRoomKeys"));
    // check that the message CAN be decrypted
    event = roomFromAlicePOV2.getDataHandler().getStore().getLatestEvent(mRoomId);
    assertTrue(null != event);
    assertTrue(event.isEncrypted());
    assertTrue(null != event.getClearEvent());
    assertTrue(null == event.getCryptoError());
    assertTrue(checkEncryptedEvent(event, mRoomId, message, mAliceSession));
    aliceSession2.clear(context);
}
Also used : Context(android.content.Context) MXStoreListener(org.matrix.androidsdk.data.store.MXStoreListener) HashMap(java.util.HashMap) IMXStore(org.matrix.androidsdk.data.store.IMXStore) MXFileStore(org.matrix.androidsdk.data.store.MXFileStore) CountDownLatch(java.util.concurrent.CountDownLatch) Uri(android.net.Uri) MXEventListener(org.matrix.androidsdk.listeners.MXEventListener) Event(org.matrix.androidsdk.rest.model.Event) JsonObject(com.google.gson.JsonObject) MatrixError(org.matrix.androidsdk.rest.model.MatrixError) Room(org.matrix.androidsdk.data.Room) Credentials(org.matrix.androidsdk.rest.model.login.Credentials) Test(org.junit.Test)

Aggregations

Uri (android.net.Uri)10 HashMap (java.util.HashMap)10 CountDownLatch (java.util.concurrent.CountDownLatch)10 IMXStore (org.matrix.androidsdk.data.store.IMXStore)10 MXFileStore (org.matrix.androidsdk.data.store.MXFileStore)10 MXEventListener (org.matrix.androidsdk.listeners.MXEventListener)10 MatrixError (org.matrix.androidsdk.rest.model.MatrixError)10 Credentials (org.matrix.androidsdk.rest.model.login.Credentials)10 Context (android.content.Context)7 JsonObject (com.google.gson.JsonObject)7 Test (org.junit.Test)7 MXStoreListener (org.matrix.androidsdk.data.store.MXStoreListener)6 Room (org.matrix.androidsdk.data.Room)4 Event (org.matrix.androidsdk.rest.model.Event)4 MXDeviceInfo (org.matrix.androidsdk.crypto.data.MXDeviceInfo)3 LoginRestClient (org.matrix.androidsdk.rest.client.LoginRestClient)3 MXUsersDevicesMap (org.matrix.androidsdk.crypto.data.MXUsersDevicesMap)2 RoomState (org.matrix.androidsdk.data.RoomState)2 RegistrationFlowResponse (org.matrix.androidsdk.rest.model.login.RegistrationFlowResponse)2 RegistrationParams (org.matrix.androidsdk.rest.model.login.RegistrationParams)2