Search in sources :

Example 31 with MXSession

use of org.matrix.androidsdk.MXSession in project matrix-android-sdk by matrix-org.

the class CryptoTest method test23_testFirstMessageSentWhileSessionWasPaused.

@Test
public void test23_testFirstMessageSentWhileSessionWasPaused() throws Exception {
    Log.e(LOG_TAG, "test23_testFirstMessageSentWhileSessionWasPaused");
    Context context = InstrumentationRegistry.getContext();
    final String messageFromAlice = "Hello I'm Alice!";
    final Map<String, Object> results = new HashMap<>();
    CryptoTestData cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true);
    final MXSession aliceSession = cryptoTestData.getFirstSession();
    final String aliceRoomId = cryptoTestData.getRoomId();
    final MXSession bobSession = cryptoTestData.getSecondSession();
    bobSession.getCrypto().setWarnOnUnknownDevices(false);
    aliceSession.getCrypto().setWarnOnUnknownDevices(false);
    final Room roomFromBobPOV = bobSession.getDataHandler().getRoom(aliceRoomId);
    final Room roomFromAlicePOV = aliceSession.getDataHandler().getRoom(aliceRoomId);
    Assert.assertTrue(roomFromBobPOV.isEncrypted());
    Assert.assertTrue(roomFromAlicePOV.isEncrypted());
    bobSession.pauseEventStream();
    // wait that the bob session is really suspended
    SystemClock.sleep(30000);
    CountDownLatch lock0 = new CountDownLatch(1);
    roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), new TestApiCallback<Void>(lock0) {

        @Override
        public void onSuccess(Void info) {
            results.put("sendEvent", "sendEvent");
            super.onSuccess(info);
        }
    });
    mTestHelper.await(lock0);
    Assert.assertTrue(results.containsKey("sendEvent"));
    final CountDownLatch lock2 = new CountDownLatch(2);
    MXEventListener eventListener = new MXEventListener() {

        @Override
        public void onLiveEvent(Event event, RoomState roomState) {
            if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE)) {
                mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, messageFromAlice, aliceSession);
                results.put("onLiveEvent", "onLiveEvent");
                lock2.countDown();
            }
        }
    };
    roomFromBobPOV.addEventListener(eventListener);
    bobSession.getDataHandler().addListener(new MXEventListener() {

        @Override
        public void onToDeviceEvent(Event event) {
            results.put("onToDeviceEvent", event);
            lock2.countDown();
        }
    });
    bobSession.resumeEventStream();
    mTestHelper.await(lock2);
    Assert.assertTrue(results.containsKey("onToDeviceEvent"));
    Assert.assertTrue(results.containsKey("onLiveEvent"));
    cryptoTestData.clear(context);
}
Also used : Context(android.content.Context) HashMap(java.util.HashMap) CryptoTestData(org.matrix.androidsdk.common.CryptoTestData) CountDownLatch(java.util.concurrent.CountDownLatch) MXSession(org.matrix.androidsdk.MXSession) MXEventListener(org.matrix.androidsdk.listeners.MXEventListener) Event(org.matrix.androidsdk.rest.model.Event) JsonObject(com.google.gson.JsonObject) Room(org.matrix.androidsdk.data.Room) RoomState(org.matrix.androidsdk.data.RoomState) Test(org.junit.Test)

Example 32 with MXSession

use of org.matrix.androidsdk.MXSession in project matrix-android-sdk by matrix-org.

the class CryptoTest method test17_testLateRoomKey.

@Test
public void test17_testLateRoomKey() throws Exception {
    Log.e(LOG_TAG, "test17_testLateRoomKey");
    Context context = InstrumentationRegistry.getContext();
    final Map<String, Object> results = new HashMap<>();
    CryptoTestData cryptoTestData = mCryptoTestHelper.doE2ETestWithAliceAndBobInARoom(true);
    final MXSession aliceSession = cryptoTestData.getFirstSession();
    final String aliceRoomId = cryptoTestData.getRoomId();
    final MXSession bobSession = cryptoTestData.getSecondSession();
    bobSession.getCrypto().setWarnOnUnknownDevices(false);
    aliceSession.getCrypto().setWarnOnUnknownDevices(false);
    String messageFromAlice = "Hello I'm Alice!";
    final Room roomFromBobPOV = bobSession.getDataHandler().getRoom(aliceRoomId);
    final Room roomFromAlicePOV = aliceSession.getDataHandler().getRoom(aliceRoomId);
    Assert.assertTrue(roomFromBobPOV.isEncrypted());
    Assert.assertTrue(roomFromAlicePOV.isEncrypted());
    final CountDownLatch lock1 = new CountDownLatch(2);
    MXEventListener bobEventListener = new MXEventListener() {

        @Override
        public void onToDeviceEvent(Event event) {
            if (!results.containsKey("onToDeviceEvent")) {
                results.put("onToDeviceEvent", event);
                lock1.countDown();
            }
        }
    };
    bobSession.getDataHandler().addListener(bobEventListener);
    final List<Event> receivedEvents = new ArrayList<>();
    EventTimeline.Listener eventTimelineListener = new EventTimeline.Listener() {

        public void onEvent(Event event, EventTimeline.Direction direction, RoomState roomState) {
            if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE)) {
                receivedEvents.add(event);
                lock1.countDown();
            }
        }
    };
    roomFromBobPOV.getTimeline().addEventTimelineListener(eventTimelineListener);
    roomFromAlicePOV.sendEvent(mCryptoTestHelper.buildTextEvent(messageFromAlice, aliceSession, aliceRoomId), new SimpleApiCallback<Void>() {

        @Override
        public void onSuccess(Void info) {
        // Ignore
        }
    });
    mTestHelper.await(lock1);
    Assert.assertTrue(results.containsKey("onToDeviceEvent"));
    Assert.assertEquals(1, receivedEvents.size());
    Event event = receivedEvents.get(0);
    mCryptoTestHelper.checkEncryptedEvent(event, aliceRoomId, messageFromAlice, aliceSession);
    // Reinject a modified version of the received room_key event from Alice.
    // From Bob pov, that mimics Alice resharing her keys but with an advanced outbound group session.
    Event toDeviceEvent = (Event) results.get("onToDeviceEvent");
    String sessionId = toDeviceEvent.getContentAsJsonObject().get("session_id").getAsString();
    String senderKey = toDeviceEvent.getSenderKey();
    // remove the session
    bobSession.getCrypto().getOlmDevice().removeInboundGroupSession(sessionId, senderKey);
    event.setClearData(null);
    // check that the message cannot be decrypted
    Assert.assertFalse(bobSession.getDataHandler().decryptEvent(event, null));
    // check the error code
    Assert.assertEquals(MXCryptoError.UNKNOWN_INBOUND_SESSION_ID_ERROR_CODE, event.getCryptoError().errcode);
    final String[] decryptedRoomId = new String[1];
    final String[] decryptedEventId = new String[1];
    final CountDownLatch lock2 = new CountDownLatch(1);
    roomFromBobPOV.addEventListener(new MXEventListener() {

        @Override
        public void onEventDecrypted(String roomId, String eventId) {
            results.put("onEventDecrypted", "onEventDecrypted");
            decryptedRoomId[0] = roomId;
            decryptedEventId[0] = eventId;
            lock2.countDown();
        }
    });
    event.setClearData(null);
    // reinject the session key
    bobSession.getDataHandler().onToDeviceEvent(toDeviceEvent);
    // the message should be decrypted later
    mTestHelper.await(lock2);
    Assert.assertTrue(results.containsKey("onEventDecrypted"));
    Assert.assertEquals(event.roomId, decryptedRoomId[0]);
    Assert.assertEquals(event.eventId, decryptedEventId[0]);
    /*
            // We do not have a proper way to get the event for now
            Event decryptedEvent = bobSession.getDataHandler().getStore().getEvent(decryptedRoomId[0], decryptedEventId[0]);

            Assert.assertNotNull(decryptedEvent);

            mCryptoTestHelper.checkEncryptedEvent(decryptedEvent, aliceRoomId, messageFromAlice, aliceSession);
            Assert.assertNull(decryptedEvent.getCryptoError());
         */
    cryptoTestData.clear(context);
}
Also used : Context(android.content.Context) MXEventListener(org.matrix.androidsdk.listeners.MXEventListener) MXStoreListener(org.matrix.androidsdk.data.store.MXStoreListener) HashMap(java.util.HashMap) CryptoTestData(org.matrix.androidsdk.common.CryptoTestData) ArrayList(java.util.ArrayList) EventTimeline(org.matrix.androidsdk.data.timeline.EventTimeline) CountDownLatch(java.util.concurrent.CountDownLatch) MXSession(org.matrix.androidsdk.MXSession) MXEventListener(org.matrix.androidsdk.listeners.MXEventListener) Event(org.matrix.androidsdk.rest.model.Event) JsonObject(com.google.gson.JsonObject) Room(org.matrix.androidsdk.data.Room) RoomState(org.matrix.androidsdk.data.RoomState) Test(org.junit.Test)

Example 33 with MXSession

use of org.matrix.androidsdk.MXSession in project matrix-android-sdk by matrix-org.

the class CryptoTest method test05_testRoomIsEncrypted.

@Test
public void test05_testRoomIsEncrypted() throws Exception {
    Log.e(LOG_TAG, "test05_testRoomIsEncrypted");
    Context context = InstrumentationRegistry.getContext();
    final Map<String, Object> results = new HashMap<>();
    MXSession bobSession = mTestHelper.createAccount(TestConstants.USER_BOB, mCryptoTestHelper.getDefaultSessionParams());
    CountDownLatch lock0 = new CountDownLatch(1);
    bobSession.enableCrypto(true, new TestApiCallback<Void>(lock0) {

        @Override
        public void onSuccess(Void info) {
            results.put("enableCrypto", "enableCrypto");
            super.onSuccess(info);
        }
    });
    mTestHelper.await(lock0);
    Assert.assertTrue(results.containsKey("enableCrypto"));
    final String[] roomId = { null };
    CountDownLatch lock1 = new CountDownLatch(1);
    bobSession.createRoom(new TestApiCallback<String>(lock1) {

        @Override
        public void onSuccess(String info) {
            roomId[0] = info;
            super.onSuccess(info);
        }
    });
    mTestHelper.await(lock1);
    Assert.assertNotNull(roomId[0]);
    Room room = bobSession.getDataHandler().getRoom(roomId[0]);
    Assert.assertFalse(room.isEncrypted());
    // Check algo in store
    Assert.assertNull(bobSession.getCrypto().getCryptoStore().getRoomAlgorithm(room.getRoomId()));
    // Wait for the room encryption event
    final CountDownLatch lock3 = new CountDownLatch(1);
    bobSession.getDataHandler().addListener(new MXEventListener() {

        @Override
        public void onLiveEvent(Event event, RoomState roomState) {
            if (TextUtils.equals(event.getType(), Event.EVENT_TYPE_MESSAGE_ENCRYPTION)) {
                lock3.countDown();
            }
        }
    });
    CountDownLatch lock2 = new CountDownLatch(1);
    room.enableEncryptionWithAlgorithm(CryptoConstantsKt.MXCRYPTO_ALGORITHM_MEGOLM, new TestApiCallback<Void>(lock2) {

        @Override
        public void onSuccess(Void info) {
            results.put("enableEncryptionWithAlgorithm", "enableEncryptionWithAlgorithm");
            super.onSuccess(info);
        }
    });
    mTestHelper.await(lock2);
    Assert.assertTrue(results.containsKey("enableEncryptionWithAlgorithm"));
    Assert.assertTrue(room.isEncrypted());
    mTestHelper.await(lock3);
    // Wait again for other onLiveEvent callback to have effect in the store
    Thread.sleep(1000);
    // Check algo in store
    Assert.assertEquals(CryptoConstantsKt.MXCRYPTO_ALGORITHM_MEGOLM, bobSession.getCrypto().getCryptoStore().getRoomAlgorithm(room.getRoomId()));
    bobSession.clear(context);
}
Also used : Context(android.content.Context) HashMap(java.util.HashMap) CountDownLatch(java.util.concurrent.CountDownLatch) MXSession(org.matrix.androidsdk.MXSession) MXEventListener(org.matrix.androidsdk.listeners.MXEventListener) Event(org.matrix.androidsdk.rest.model.Event) JsonObject(com.google.gson.JsonObject) Room(org.matrix.androidsdk.data.Room) RoomState(org.matrix.androidsdk.data.RoomState) Test(org.junit.Test)

Example 34 with MXSession

use of org.matrix.androidsdk.MXSession in project matrix-android-sdk by matrix-org.

the class CommonTestHelper method createNewSession.

/**
 * Clone a session.
 * It simulate that the user launches again the application with the same Credentials, contrary to login which will create a new DeviceId
 *
 * @param from the session to clone
 * @return the duplicated session
 */
@NonNull
public MXSession createNewSession(@NonNull MXSession from, SessionTestParams sessionTestParams) throws InterruptedException {
    final Context context = InstrumentationRegistry.getContext();
    Credentials credentials = from.getCredentials();
    HomeServerConnectionConfig hs = createHomeServerConfig(credentials);
    MXFileStore store = new MXFileStore(hs, false, context);
    MXDataHandler dataHandler = new MXDataHandler(store, credentials);
    dataHandler.setLazyLoadingEnabled(sessionTestParams.getWithLazyLoading());
    store.setDataHandler(dataHandler);
    MXSession session2 = new MXSession.Builder(hs, dataHandler, context).withLegacyCryptoStore(sessionTestParams.getWithLegacyCryptoStore()).build();
    final Map<String, Object> results = new HashMap<>();
    final CountDownLatch lock = new CountDownLatch(1);
    MXStoreListener listener = new MXStoreListener() {

        @Override
        public void postProcess(String accountId) {
            results.put("postProcess", "postProcess " + accountId);
        }

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

        @Override
        public void onStoreCorrupted(String accountId, String description) {
            results.put("onStoreCorrupted", description);
            lock.countDown();
        }

        @Override
        public void onStoreOOM(String accountId, String description) {
            results.put("onStoreOOM", "onStoreOOM");
            lock.countDown();
        }
    };
    store.addMXStoreListener(listener);
    store.open();
    await(lock);
    Assert.assertTrue(results.toString(), results.containsKey("onStoreReady"));
    return session2;
}
Also used : Context(android.content.Context) MXStoreListener(org.matrix.androidsdk.data.store.MXStoreListener) HashMap(java.util.HashMap) MXFileStore(org.matrix.androidsdk.data.store.MXFileStore) CountDownLatch(java.util.concurrent.CountDownLatch) HomeServerConnectionConfig(org.matrix.androidsdk.HomeServerConnectionConfig) MXSession(org.matrix.androidsdk.MXSession) MXDataHandler(org.matrix.androidsdk.MXDataHandler) Credentials(org.matrix.androidsdk.rest.model.login.Credentials) NonNull(androidx.annotation.NonNull)

Example 35 with MXSession

use of org.matrix.androidsdk.MXSession in project matrix-android-sdk by matrix-org.

the class CommonTestHelper method createAccountAndSync.

/**
 * Create an account and a dedicated session
 *
 * @param context           the context
 * @param userName          the account username
 * @param password          the password
 * @param sessionTestParams parameters for the test
 */
private MXSession createAccountAndSync(Context context, String userName, String password, SessionTestParams sessionTestParams) throws InterruptedException {
    final HomeServerConnectionConfig hs = createHomeServerConfig(null);
    final LoginRestClient loginRestClient = new LoginRestClient(hs);
    final Map<String, Object> params = new HashMap<>();
    final RegistrationParams registrationParams = new RegistrationParams();
    CountDownLatch lock = new CountDownLatch(1);
    // get the registration session id
    loginRestClient.register(registrationParams, new TestApiCallback<Credentials>(lock, false) {

        @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);
            }
            super.onMatrixError(e);
        }
    });
    await(lock);
    final String session = (String) params.get("session");
    Assert.assertNotNull(session);
    registrationParams.username = userName;
    registrationParams.password = password;
    AuthParams authParams = new AuthParams(LoginRestClient.LOGIN_FLOW_TYPE_DUMMY);
    authParams.session = session;
    registrationParams.auth = authParams;
    lock = new CountDownLatch(1);
    loginRestClient.register(registrationParams, new TestApiCallback<Credentials>(lock) {

        @Override
        public void onSuccess(Credentials credentials) {
            params.put("credentials", credentials);
            super.onSuccess(credentials);
        }
    });
    await(lock);
    Credentials credentials = (Credentials) params.get("credentials");
    Assert.assertNotNull(credentials);
    hs.setCredentials(credentials);
    IMXStore store = new MXFileStore(hs, false, context);
    MXDataHandler dataHandler = new MXDataHandler(store, credentials);
    dataHandler.setLazyLoadingEnabled(sessionTestParams.getWithLazyLoading());
    MXSession mxSession = new MXSession.Builder(hs, dataHandler, context).withLegacyCryptoStore(sessionTestParams.getWithLegacyCryptoStore()).build();
    if (sessionTestParams.getWithCryptoEnabled()) {
        mxSession.enableCryptoWhenStarting();
    }
    if (sessionTestParams.getWithInitialSync()) {
        syncSession(mxSession, sessionTestParams.getWithCryptoEnabled());
    }
    return mxSession;
}
Also used : AuthParams(org.matrix.androidsdk.rest.model.login.AuthParams) 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) HomeServerConnectionConfig(org.matrix.androidsdk.HomeServerConnectionConfig) MXSession(org.matrix.androidsdk.MXSession) MXDataHandler(org.matrix.androidsdk.MXDataHandler) RegistrationParams(org.matrix.androidsdk.rest.model.login.RegistrationParams) LoginRestClient(org.matrix.androidsdk.rest.client.LoginRestClient) MatrixError(org.matrix.androidsdk.core.model.MatrixError) Credentials(org.matrix.androidsdk.rest.model.login.Credentials)

Aggregations

MXSession (org.matrix.androidsdk.MXSession)39 CountDownLatch (java.util.concurrent.CountDownLatch)37 Context (android.content.Context)36 HashMap (java.util.HashMap)36 Test (org.junit.Test)32 JsonObject (com.google.gson.JsonObject)27 Room (org.matrix.androidsdk.data.Room)25 MXEventListener (org.matrix.androidsdk.listeners.MXEventListener)25 Event (org.matrix.androidsdk.rest.model.Event)23 CryptoTestData (org.matrix.androidsdk.common.CryptoTestData)22 RoomState (org.matrix.androidsdk.data.RoomState)20 MXStoreListener (org.matrix.androidsdk.data.store.MXStoreListener)16 ArrayList (java.util.ArrayList)14 MXDeviceInfo (org.matrix.androidsdk.crypto.data.MXDeviceInfo)9 EventTimeline (org.matrix.androidsdk.data.timeline.EventTimeline)9 Credentials (org.matrix.androidsdk.rest.model.login.Credentials)9 MXUsersDevicesMap (org.matrix.androidsdk.crypto.data.MXUsersDevicesMap)8 HomeServerConnectionConfig (org.matrix.androidsdk.HomeServerConnectionConfig)7 MXDataHandler (org.matrix.androidsdk.MXDataHandler)7 MXFileStore (org.matrix.androidsdk.data.store.MXFileStore)7