session-desktop/ts/test/session/unit/sending/MessageSender_test.ts

285 lines
12 KiB
TypeScript
Raw Normal View History

2020-07-10 03:30:06 +02:00
import { expect } from 'chai';
import * as crypto from 'crypto';
import Sinon, * as sinon from 'sinon';
import { MessageSender } from '../../../../session/sending';
2020-08-03 03:45:02 +02:00
import { TestUtils } from '../../../test-utils';
import { MessageEncrypter } from '../../../../session/crypto';
import { SignalService } from '../../../../protobuf';
import { PubKey, RawMessage } from '../../../../session/types';
import { MessageUtils, UserUtils } from '../../../../session/utils';
import { SNodeAPI } from '../../../../session/apis/snode_api';
import _ from 'lodash';
import { OpenGroupPollingUtils } from '../../../../session/apis/open_group_api/opengroupV2/OpenGroupPollingUtils';
import { TEST_identityKeyPair } from '../crypto/MessageEncrypter_test';
import { stubCreateObjectUrl, stubData, stubUtilWorker } from '../../../test-utils/utils';
import { SogsBlinding } from '../../../../session/apis/open_group_api/sogsv3/sogsBlinding';
import { Onions } from '../../../../session/apis/snode_api/onions';
import { OnionV4 } from '../../../../session/onions/onionv4';
import { OnionSending } from '../../../../session/onions/onionSend';
import { OpenGroupMessageV2 } from '../../../../session/apis/open_group_api/opengroupV2/OpenGroupMessageV2';
2020-07-10 03:30:06 +02:00
describe('MessageSender', () => {
afterEach(() => {
sinon.restore();
2020-07-10 03:30:06 +02:00
});
beforeEach(() => {
TestUtils.stubWindowLog();
});
// tslint:disable-next-line: max-func-body-length
2020-07-10 03:30:06 +02:00
describe('send', () => {
2020-09-15 02:10:34 +02:00
const ourNumber = '0123456789abcdef';
2022-02-18 03:03:47 +01:00
let sessionMessageAPISendStub: sinon.SinonStub<any>;
let encryptStub: sinon.SinonStub<[PubKey, Uint8Array, SignalService.Envelope.Type]>;
2020-07-10 03:30:06 +02:00
beforeEach(() => {
sessionMessageAPISendStub = Sinon.stub(MessageSender, 'sendMessageToSnode').resolves();
stubData('getMessageById').resolves();
2020-07-10 03:30:06 +02:00
encryptStub = Sinon.stub(MessageEncrypter, 'encrypt').resolves({
2021-06-10 00:55:25 +02:00
envelopeType: SignalService.Envelope.Type.SESSION_MESSAGE,
2020-07-10 03:30:06 +02:00
cipherText: crypto.randomBytes(10),
});
Sinon.stub(UserUtils, 'getOurPubKeyStrFromCache').returns(ourNumber);
2020-07-10 03:30:06 +02:00
});
describe('retry', () => {
let rawMessage: RawMessage;
beforeEach(async () => {
rawMessage = await MessageUtils.toRawMessage(
TestUtils.generateFakePubKey(),
TestUtils.generateVisibleMessage()
);
});
2020-07-10 03:30:06 +02:00
it('should not retry if an error occurred during encryption', async () => {
encryptStub.throws(new Error('Failed to encrypt.'));
const promise = MessageSender.send(rawMessage, 3, 10);
2020-07-10 03:30:06 +02:00
await expect(promise).is.rejectedWith('Failed to encrypt.');
2022-02-18 03:03:47 +01:00
expect(sessionMessageAPISendStub.callCount).to.equal(0);
2020-07-10 03:30:06 +02:00
});
it('should only call lokiMessageAPI once if no errors occured', async () => {
await MessageSender.send(rawMessage, 3, 10);
2022-02-18 03:03:47 +01:00
expect(sessionMessageAPISendStub.callCount).to.equal(1);
2020-07-10 03:30:06 +02:00
});
it('should only retry the specified amount of times before throwing', async () => {
2021-03-03 23:55:44 +01:00
// const clock = sinon.useFakeTimers();
2022-02-18 03:03:47 +01:00
sessionMessageAPISendStub.throws(new Error('API error'));
2020-07-10 03:30:06 +02:00
const attempts = 2;
2021-03-03 23:55:44 +01:00
const promise = MessageSender.send(rawMessage, attempts, 10);
2020-07-10 03:30:06 +02:00
await expect(promise).is.rejectedWith('API error');
2021-03-03 23:55:44 +01:00
// clock.restore();
2022-02-18 03:03:47 +01:00
expect(sessionMessageAPISendStub.callCount).to.equal(attempts);
2020-07-10 03:30:06 +02:00
});
it('should not throw error if successful send occurs within the retry limit', async () => {
2022-02-18 03:03:47 +01:00
sessionMessageAPISendStub.onFirstCall().throws(new Error('API error'));
2021-03-03 23:55:44 +01:00
await MessageSender.send(rawMessage, 3, 10);
2022-02-18 03:03:47 +01:00
expect(sessionMessageAPISendStub.callCount).to.equal(2);
2020-07-10 03:30:06 +02:00
});
});
describe('logic', () => {
2021-06-10 00:55:25 +02:00
let messageEncyrptReturnEnvelopeType = SignalService.Envelope.Type.SESSION_MESSAGE;
2020-07-10 03:30:06 +02:00
beforeEach(() => {
encryptStub.callsFake(async (_device, plainTextBuffer, _type) => ({
envelopeType: messageEncyrptReturnEnvelopeType,
cipherText: plainTextBuffer,
}));
});
it('should pass the correct values to lokiMessageAPI', async () => {
const device = TestUtils.generateFakePubKey();
const visibleMessage = TestUtils.generateVisibleMessage();
const rawMessage = await MessageUtils.toRawMessage(device, visibleMessage);
await MessageSender.send(rawMessage, 3, 10);
2020-07-10 03:30:06 +02:00
2022-02-18 03:03:47 +01:00
const args = sessionMessageAPISendStub.getCall(0).args;
expect(args[0]).to.equal(device.key);
// expect(args[3]).to.equal(visibleMessage.timestamp); the timestamp is overwritten on sending by the network clock offset
expect(args[2]).to.equal(visibleMessage.ttl());
2020-07-10 03:30:06 +02:00
});
it('should correctly build the envelope and override the timestamp', async () => {
2021-06-10 00:55:25 +02:00
messageEncyrptReturnEnvelopeType = SignalService.Envelope.Type.SESSION_MESSAGE;
2020-07-10 03:30:06 +02:00
// This test assumes the encryption stub returns the plainText passed into it.
const device = TestUtils.generateFakePubKey();
const visibleMessage = TestUtils.generateVisibleMessage();
const rawMessage = await MessageUtils.toRawMessage(device, visibleMessage);
const offset = 200000;
Sinon.stub(SNodeAPI, 'getLatestTimestampOffset').returns(offset);
await MessageSender.send(rawMessage, 3, 10);
2020-07-10 03:30:06 +02:00
2022-02-18 03:03:47 +01:00
const data = sessionMessageAPISendStub.getCall(0).args[1];
2020-07-10 03:30:06 +02:00
const webSocketMessage = SignalService.WebSocketMessage.decode(data);
expect(webSocketMessage.request?.body).to.not.equal(
undefined,
'Request body should not be undefined'
);
expect(webSocketMessage.request?.body).to.not.equal(
null,
'Request body should not be null'
);
const envelope = SignalService.Envelope.decode(
webSocketMessage.request?.body as Uint8Array
);
2021-06-10 00:55:25 +02:00
expect(envelope.type).to.equal(SignalService.Envelope.Type.SESSION_MESSAGE);
expect(envelope.source).to.equal('');
// the timestamp is overridden on sending with the network offset
const expectedTimestamp = Date.now() - offset;
const decodedTimestampFromSending = _.toNumber(envelope.timestamp);
expect(decodedTimestampFromSending).to.be.above(expectedTimestamp - 10);
expect(decodedTimestampFromSending).to.be.below(expectedTimestamp + 10);
2023-02-16 01:02:45 +01:00
// then make sure the plaintextBuffer was overridden too
const visibleMessageExpected = TestUtils.generateVisibleMessage({
timestamp: decodedTimestampFromSending,
});
const rawMessageExpected = await MessageUtils.toRawMessage(device, visibleMessageExpected);
expect(envelope.content).to.deep.equal(rawMessageExpected.plainTextBuffer);
2020-07-10 03:30:06 +02:00
});
2021-06-10 00:55:25 +02:00
describe('SESSION_MESSAGE', () => {
2020-07-10 03:30:06 +02:00
it('should set the envelope source to be empty', async () => {
2021-06-10 00:55:25 +02:00
messageEncyrptReturnEnvelopeType = SignalService.Envelope.Type.SESSION_MESSAGE;
2020-07-10 03:30:06 +02:00
// This test assumes the encryption stub returns the plainText passed into it.
const device = TestUtils.generateFakePubKey();
const visibleMessage = TestUtils.generateVisibleMessage();
const rawMessage = await MessageUtils.toRawMessage(device, visibleMessage);
await MessageSender.send(rawMessage, 3, 10);
2020-07-10 03:30:06 +02:00
2022-02-18 03:03:47 +01:00
const data = sessionMessageAPISendStub.getCall(0).args[1];
2020-07-10 03:30:06 +02:00
const webSocketMessage = SignalService.WebSocketMessage.decode(data);
expect(webSocketMessage.request?.body).to.not.equal(
undefined,
'Request body should not be undefined'
);
expect(webSocketMessage.request?.body).to.not.equal(
null,
'Request body should not be null'
);
const envelope = SignalService.Envelope.decode(
webSocketMessage.request?.body as Uint8Array
);
2021-06-10 00:55:25 +02:00
expect(envelope.type).to.equal(SignalService.Envelope.Type.SESSION_MESSAGE);
2020-07-10 03:30:06 +02:00
expect(envelope.source).to.equal(
'',
2021-06-10 00:55:25 +02:00
'envelope source should be empty in SESSION_MESSAGE'
2020-07-10 03:30:06 +02:00
);
});
});
});
});
describe('sendToOpenGroupV2', () => {
beforeEach(() => {
Sinon.stub(UserUtils, 'getOurPubKeyStrFromCache').resolves(
TestUtils.generateFakePubKey().key
);
Sinon.stub(UserUtils, 'getIdentityKeyPair').resolves(TEST_identityKeyPair);
2020-07-10 03:30:06 +02:00
Sinon.stub(SogsBlinding, 'getSogsSignature').resolves(new Uint8Array());
stubUtilWorker('arrayBufferToStringBase64', 'ba64');
Sinon.stub(OnionSending, 'getOnionPathForSending').resolves([{}] as any);
Sinon.stub(OnionSending, 'endpointRequiresDecoding').returnsArg(0);
stubData('getGuardNodes').resolves([]);
Sinon.stub(OpenGroupPollingUtils, 'getAllValidRoomInfos').returns([
{ roomId: 'room', serverPublicKey: 'whatever', serverUrl: 'serverUrl' },
]);
Sinon.stub(OpenGroupPollingUtils, 'getOurOpenGroupHeaders').resolves({
'X-SOGS-Pubkey': '00bac6e71efd7dfa4a83c98ed24f254ab2c267f9ccdb172a5280a0444ad24e89cc',
'X-SOGS-Timestamp': '1642472103',
'X-SOGS-Nonce': 'CdB5nyKVmQGCw6s0Bvv8Ww==',
'X-SOGS-Signature':
'gYqpWZX6fnF4Gb2xQM3xaXs0WIYEI49+B8q4mUUEg8Rw0ObaHUWfoWjMHMArAtP9QlORfiydsKWz1o6zdPVeCQ==',
});
stubCreateObjectUrl();
Sinon.stub(OpenGroupMessageV2, 'fromJson').resolves();
});
2020-07-10 03:30:06 +02:00
afterEach(() => {
Sinon.restore();
});
2020-07-10 03:30:06 +02:00
it('should call sendOnionRequestHandlingSnodeEjectStub', async () => {
const sendOnionRequestHandlingSnodeEjectStub = Sinon.stub(
Onions,
'sendOnionRequestHandlingSnodeEject'
).resolves({} as any);
Sinon.stub(OnionV4, 'decodeV4Response').returns({
metadata: { code: 200 },
body: {},
bodyBinary: new Uint8Array(),
bodyContentType: 'a',
});
const message = TestUtils.generateOpenGroupVisibleMessage();
const roomInfos = TestUtils.generateOpenGroupV2RoomInfos();
await MessageSender.sendToOpenGroupV2(message, roomInfos, false, []);
expect(sendOnionRequestHandlingSnodeEjectStub.callCount).to.eq(1);
});
2020-07-10 03:30:06 +02:00
it('should retry sendOnionRequestHandlingSnodeEjectStub ', async () => {
const message = TestUtils.generateOpenGroupVisibleMessage();
const roomInfos = TestUtils.generateOpenGroupV2RoomInfos();
Sinon.stub(Onions, 'sendOnionRequestHandlingSnodeEject').resolves({} as any);
const decodev4responseStub = Sinon.stub(OnionV4, 'decodeV4Response');
decodev4responseStub.throws('whate');
decodev4responseStub.onThirdCall().returns({
metadata: { code: 200 },
body: {},
bodyBinary: new Uint8Array(),
bodyContentType: 'a',
});
await MessageSender.sendToOpenGroupV2(message, roomInfos, false, []);
expect(decodev4responseStub.callCount).to.eq(3);
});
2020-07-10 03:30:06 +02:00
it('should not retry more than 3 sendOnionRequestHandlingSnodeEjectStub ', async () => {
const message = TestUtils.generateOpenGroupVisibleMessage();
const roomInfos = TestUtils.generateOpenGroupV2RoomInfos();
Sinon.stub(Onions, 'sendOnionRequestHandlingSnodeEject').resolves({} as any);
const decodev4responseStub = Sinon.stub(OnionV4, 'decodeV4Response');
decodev4responseStub.throws('whate');
decodev4responseStub.onCall(4).returns({
metadata: { code: 200 },
body: {},
bodyBinary: new Uint8Array(),
bodyContentType: 'a',
});
try {
await MessageSender.sendToOpenGroupV2(message, roomInfos, false, []);
// tslint:disable-next-line: no-empty
} catch (e) {}
// we made the fourth call success, but we should not get there. We should stop at 3 the retries (1+2)
expect(decodev4responseStub.calledThrice);
2020-07-10 03:30:06 +02:00
});
});
});