snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
import { expect } from 'chai';
|
||||
import { beforeEach, describe, it } from 'mocha';
|
||||
import p from 'proxyquire';
|
||||
import sinon from 'sinon';
|
||||
|
||||
const hasPermissionStub = sinon.stub();
|
||||
|
||||
const AccountsMock = {
|
||||
_generateStampedLoginToken: sinon.stub(),
|
||||
_insertLoginToken: sinon.stub(),
|
||||
};
|
||||
|
||||
const UserMock = {
|
||||
ensureLoginTokensLimit: sinon.stub(),
|
||||
};
|
||||
|
||||
const AuthorizationMock = {
|
||||
hasPermission: hasPermissionStub,
|
||||
};
|
||||
|
||||
class MeteorErrorMock extends Error {
|
||||
error: string;
|
||||
|
||||
constructor(error: string, reason: string) {
|
||||
super(reason);
|
||||
this.error = error;
|
||||
}
|
||||
}
|
||||
|
||||
process.env.CREATE_TOKENS_FOR_USERS_SECRET = 'V@9#mK2$pL8!nQ5^rT1&wX6*jY3%uZ7';
|
||||
|
||||
const { generateAccessToken } = p.noCallThru().load('../../../../../server/meteor-methods/auth/createToken.ts', {
|
||||
'@rocket.chat/core-services': { Authorization: AuthorizationMock, MeteorError: MeteorErrorMock, User: UserMock },
|
||||
'meteor/accounts-base': { Accounts: AccountsMock },
|
||||
});
|
||||
|
||||
describe('generateAccessToken', () => {
|
||||
beforeEach(() => {
|
||||
hasPermissionStub.reset();
|
||||
AccountsMock._generateStampedLoginToken.reset();
|
||||
AccountsMock._insertLoginToken.reset();
|
||||
UserMock.ensureLoginTokensLimit.reset();
|
||||
});
|
||||
|
||||
it('should throw if secret does not match', async () => {
|
||||
await expect(generateAccessToken('targetId', 'wrong-secret', { _id: 'callerId' })).to.be.rejectedWith('Not authorized');
|
||||
});
|
||||
|
||||
it('should throw if caller targets another user and lacks user-generate-access-token permission', async () => {
|
||||
hasPermissionStub.resolves(false);
|
||||
|
||||
await expect(generateAccessToken('targetId', 'V@9#mK2$pL8!nQ5^rT1&wX6*jY3%uZ7', { _id: 'callerId' })).to.be.rejectedWith(
|
||||
'Not authorized',
|
||||
);
|
||||
sinon.assert.calledOnceWithExactly(hasPermissionStub, { _id: 'callerId' }, 'user-generate-access-token');
|
||||
});
|
||||
|
||||
it('should succeed if caller targets another user and has user-generate-access-token permission', async () => {
|
||||
hasPermissionStub.resolves(true);
|
||||
AccountsMock._generateStampedLoginToken.returns({ token: 'abc123' });
|
||||
UserMock.ensureLoginTokensLimit.resolves();
|
||||
|
||||
const result = await generateAccessToken('targetId', 'V@9#mK2$pL8!nQ5^rT1&wX6*jY3%uZ7', { _id: 'callerId' });
|
||||
|
||||
expect(result).to.deep.equal({ userId: 'targetId', authToken: 'abc123' });
|
||||
sinon.assert.calledOnceWithExactly(hasPermissionStub, { _id: 'callerId' }, 'user-generate-access-token');
|
||||
});
|
||||
|
||||
it('should succeed without permission check when caller generates token for themselves', async () => {
|
||||
AccountsMock._generateStampedLoginToken.returns({ token: 'abc123' });
|
||||
UserMock.ensureLoginTokensLimit.resolves();
|
||||
|
||||
const result = await generateAccessToken('userId', 'V@9#mK2$pL8!nQ5^rT1&wX6*jY3%uZ7', { _id: 'userId' });
|
||||
|
||||
expect(result).to.deep.equal({ userId: 'userId', authToken: 'abc123' });
|
||||
sinon.assert.notCalled(hasPermissionStub);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,144 @@
|
||||
import { PassThrough } from 'node:stream';
|
||||
|
||||
import { expect } from 'chai';
|
||||
import { beforeEach, describe, it } from 'mocha';
|
||||
import proxyquire from 'proxyquire';
|
||||
import sinon from 'sinon';
|
||||
|
||||
const progressStep = {
|
||||
DOWNLOADING_FILE: 'importer_downloading_file',
|
||||
FILE_LOADED: 'importer_file_loaded',
|
||||
ERROR: 'importer_import_failed',
|
||||
};
|
||||
|
||||
const stubs = {
|
||||
newOperation: sinon.stub(),
|
||||
serverFetch: sinon.stub(),
|
||||
importersGet: sinon.stub(),
|
||||
createWriteStream: sinon.stub(),
|
||||
startFileUpload: sinon.stub(),
|
||||
updateProgress: sinon.stub(),
|
||||
updateRecord: sinon.stub(),
|
||||
systemLoggerError: sinon.stub(),
|
||||
};
|
||||
|
||||
class MockImporter {
|
||||
startFileUpload = stubs.startFileUpload;
|
||||
|
||||
updateProgress = stubs.updateProgress;
|
||||
|
||||
updateRecord = stubs.updateRecord;
|
||||
}
|
||||
|
||||
const { executeDownloadPublicImportFile } = proxyquire
|
||||
.noCallThru()
|
||||
.load('../../../../../server/meteor-methods/import/downloadPublicImportFile.ts', {
|
||||
'@rocket.chat/core-services': { Import: { newOperation: stubs.newOperation } },
|
||||
'@rocket.chat/server-fetch': { serverFetch: stubs.serverFetch },
|
||||
'meteor/meteor': { Meteor: { methods: sinon.stub() } },
|
||||
'../../lib/authorization/hasPermission': { hasPermissionAsync: sinon.stub() },
|
||||
'../../lib/deprecationWarningLogger': { methodDeprecationLogger: { method: sinon.stub() } },
|
||||
'../../lib/import': { Importers: { get: stubs.importersGet } },
|
||||
'../../lib/import/startup/store': { RocketChatImportFileInstance: { createWriteStream: stubs.createWriteStream } },
|
||||
'../../lib/logger/system': { SystemLogger: { error: stubs.systemLoggerError } },
|
||||
'../../settings': { settings: { get: sinon.stub().returns('') } },
|
||||
'../../../app/importer/lib/ImporterProgressStep': { ProgressStep: progressStep },
|
||||
});
|
||||
|
||||
describe('executeDownloadPublicImportFile', () => {
|
||||
let writeStream: PassThrough;
|
||||
|
||||
beforeEach(() => {
|
||||
Object.values(stubs).forEach((stub) => stub.reset());
|
||||
|
||||
writeStream = new PassThrough();
|
||||
stubs.newOperation.resolves({ _id: 'operation-id' });
|
||||
stubs.importersGet.returns({ key: 'csv', name: 'CSV', importer: MockImporter });
|
||||
stubs.createWriteStream.returns(writeStream);
|
||||
stubs.startFileUpload.resolves();
|
||||
stubs.updateProgress.resolves();
|
||||
stubs.updateRecord.resolves();
|
||||
});
|
||||
|
||||
it('rejects an unsuccessful HTTP response and drains its body', async () => {
|
||||
const responseBody = new PassThrough();
|
||||
const resume = sinon.spy(responseBody, 'resume');
|
||||
stubs.serverFetch.resolves({ ok: false, status: 404, body: responseBody });
|
||||
|
||||
await expect(executeDownloadPublicImportFile('user-id', 'https://example.com/import.zip', 'csv')).to.be.rejectedWith(
|
||||
'Unexpected response status 404',
|
||||
);
|
||||
|
||||
expect(resume.calledOnce).to.be.true;
|
||||
expect(writeStream.destroyed).to.be.true;
|
||||
expect(stubs.updateProgress.calledWith(progressStep.ERROR)).to.be.true;
|
||||
});
|
||||
|
||||
it('marks the import as failed and destroys the writable when the HTTP stream fails', async () => {
|
||||
const responseBody = new PassThrough();
|
||||
stubs.serverFetch.resolves({ ok: true, status: 200, body: responseBody });
|
||||
|
||||
await executeDownloadPublicImportFile('user-id', 'https://example.com/import.zip', 'csv');
|
||||
const writeStreamClosed = new Promise<void>((resolve) => writeStream.once('close', resolve));
|
||||
responseBody.destroy(new Error('stream failed'));
|
||||
await writeStreamClosed;
|
||||
|
||||
expect(writeStream.destroyed).to.be.true;
|
||||
expect(stubs.updateProgress.withArgs(progressStep.ERROR).calledOnce).to.be.true;
|
||||
expect(stubs.updateProgress.calledWith(progressStep.FILE_LOADED)).to.be.false;
|
||||
});
|
||||
|
||||
it('marks the import as failed and destroys the HTTP stream when the writable fails', async () => {
|
||||
const responseBody = new PassThrough();
|
||||
stubs.serverFetch.resolves({ ok: true, status: 200, body: responseBody });
|
||||
|
||||
await executeDownloadPublicImportFile('user-id', 'https://example.com/import.zip', 'csv');
|
||||
const responseBodyClosed = new Promise<void>((resolve) => responseBody.once('close', resolve));
|
||||
writeStream.destroy(new Error('stream failed'));
|
||||
await responseBodyClosed;
|
||||
|
||||
expect(responseBody.destroyed).to.be.true;
|
||||
expect(stubs.updateProgress.withArgs(progressStep.ERROR).calledOnce).to.be.true;
|
||||
expect(stubs.updateProgress.calledWith(progressStep.FILE_LOADED)).to.be.false;
|
||||
});
|
||||
|
||||
it('handles a rejected error progress update when the writable fails', async () => {
|
||||
const responseBody = new PassThrough();
|
||||
const unhandledRejection = sinon.spy();
|
||||
const progressUpdateError = new Error('progress update failed');
|
||||
stubs.serverFetch.resolves({ ok: true, status: 200, body: responseBody });
|
||||
stubs.updateProgress.withArgs(progressStep.ERROR).rejects(progressUpdateError);
|
||||
process.on('unhandledRejection', unhandledRejection);
|
||||
|
||||
try {
|
||||
await executeDownloadPublicImportFile('user-id', 'https://example.com/import.zip', 'csv');
|
||||
const responseBodyClosed = new Promise<void>((resolve) => responseBody.once('close', resolve));
|
||||
writeStream.destroy(new Error('stream failed'));
|
||||
await responseBodyClosed;
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
|
||||
expect(unhandledRejection.called).to.be.false;
|
||||
expect(stubs.updateProgress.withArgs(progressStep.ERROR).calledOnce).to.be.true;
|
||||
sinon.assert.calledOnceWithExactly(stubs.systemLoggerError, {
|
||||
msg: 'Failed to update import progress to ERROR',
|
||||
err: progressUpdateError,
|
||||
});
|
||||
} finally {
|
||||
process.off('unhandledRejection', unhandledRejection);
|
||||
}
|
||||
});
|
||||
|
||||
it('marks the file as loaded when the writable finishes', async () => {
|
||||
const responseBody = new PassThrough();
|
||||
stubs.serverFetch.resolves({ ok: true, status: 200, body: responseBody });
|
||||
|
||||
await executeDownloadPublicImportFile('user-id', 'https://example.com/import.zip', 'csv');
|
||||
expect(stubs.updateProgress.calledWith(progressStep.FILE_LOADED)).to.be.false;
|
||||
|
||||
const finished = new Promise<void>((resolve) => writeStream.once('finish', resolve));
|
||||
responseBody.end('file contents');
|
||||
await finished;
|
||||
|
||||
expect(stubs.updateProgress.calledWith(progressStep.FILE_LOADED)).to.be.true;
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
import { MeteorError } from '@rocket.chat/core-services';
|
||||
import { expect } from 'chai';
|
||||
import { beforeEach, describe, it } from 'mocha';
|
||||
import p from 'proxyquire';
|
||||
import sinon from 'sinon';
|
||||
|
||||
const checkMock = sinon.stub();
|
||||
const meteorUserIdMock = sinon.stub();
|
||||
const meteorMethodsMock = sinon.stub();
|
||||
const deleteMessageValidatingPermissionMock = sinon.stub();
|
||||
const canDeleteFileMock = sinon.stub();
|
||||
const deleteByIdMock = sinon.stub();
|
||||
const fileUploadGetStoreMock = sinon.stub().returns({ deleteById: deleteByIdMock });
|
||||
|
||||
const modelsMock = {
|
||||
Messages: {
|
||||
getMessageByFileId: sinon.stub(),
|
||||
},
|
||||
Users: {
|
||||
findOneById: sinon.stub(),
|
||||
},
|
||||
Uploads: {
|
||||
findOneById: sinon.stub(),
|
||||
},
|
||||
};
|
||||
|
||||
p.noCallThru().load('../../../../../server/meteor-methods/messages/deleteFileMessage', {
|
||||
'meteor/meteor': {
|
||||
Meteor: {
|
||||
userId: meteorUserIdMock,
|
||||
Error: MeteorError,
|
||||
methods: meteorMethodsMock,
|
||||
},
|
||||
},
|
||||
'meteor/check': {
|
||||
check: checkMock,
|
||||
},
|
||||
'@rocket.chat/models': modelsMock,
|
||||
'@rocket.chat/core-services': {
|
||||
Upload: { canDeleteFile: canDeleteFileMock },
|
||||
},
|
||||
'../../lib/media/file-upload': {
|
||||
FileUpload: { getStore: fileUploadGetStoreMock },
|
||||
},
|
||||
'../../lib/messages/deleteMessage': {
|
||||
deleteMessageValidatingPermission: deleteMessageValidatingPermissionMock,
|
||||
},
|
||||
});
|
||||
|
||||
const deleteFileMessageMethod = meteorMethodsMock.firstCall.args[0].deleteFileMessage;
|
||||
|
||||
describe('deleteFileMessage', () => {
|
||||
beforeEach(() => {
|
||||
checkMock.resetHistory();
|
||||
meteorUserIdMock.reset();
|
||||
deleteMessageValidatingPermissionMock.reset();
|
||||
canDeleteFileMock.reset();
|
||||
deleteByIdMock.reset();
|
||||
fileUploadGetStoreMock.resetHistory();
|
||||
modelsMock.Messages.getMessageByFileId.reset();
|
||||
modelsMock.Users.findOneById.reset();
|
||||
modelsMock.Uploads.findOneById.reset();
|
||||
});
|
||||
|
||||
it('should throw if user is not authenticated', async () => {
|
||||
meteorUserIdMock.returns(null);
|
||||
|
||||
await expect(deleteFileMessageMethod('file123')).to.be.rejectedWith('Invalid user');
|
||||
});
|
||||
|
||||
it('should delete message validating permission if file has an associated message', async () => {
|
||||
meteorUserIdMock.returns('user123');
|
||||
const mockMsg = { _id: 'msg123', file: { _id: 'file123' } };
|
||||
modelsMock.Messages.getMessageByFileId.resolves(mockMsg);
|
||||
deleteMessageValidatingPermissionMock.resolves();
|
||||
|
||||
await deleteFileMessageMethod('file123');
|
||||
|
||||
expect(checkMock.calledOnceWith('file123', String)).to.be.true;
|
||||
expect(deleteMessageValidatingPermissionMock.calledOnceWith(mockMsg, 'user123')).to.be.true;
|
||||
expect(modelsMock.Users.findOneById.called).to.be.false;
|
||||
});
|
||||
|
||||
it('should throw if it is an orphan file but user is not found in DB', async () => {
|
||||
meteorUserIdMock.returns('user123');
|
||||
modelsMock.Messages.getMessageByFileId.resolves(null);
|
||||
modelsMock.Users.findOneById.resolves(null);
|
||||
|
||||
await expect(deleteFileMessageMethod('file123')).to.be.rejectedWith('Invalid user');
|
||||
});
|
||||
|
||||
it('should throw if it is an orphan file but file is not found in DB', async () => {
|
||||
meteorUserIdMock.returns('user123');
|
||||
modelsMock.Messages.getMessageByFileId.resolves(null);
|
||||
modelsMock.Users.findOneById.resolves({ _id: 'user123', username: 'test' });
|
||||
modelsMock.Uploads.findOneById.resolves(null);
|
||||
|
||||
await expect(deleteFileMessageMethod('file123')).to.be.rejectedWith('Invalid file');
|
||||
});
|
||||
|
||||
it('should not delete orphan file if user does not have permissions', async () => {
|
||||
meteorUserIdMock.returns('user123');
|
||||
modelsMock.Messages.getMessageByFileId.resolves(null);
|
||||
modelsMock.Users.findOneById.resolves({ _id: 'user123', username: 'test' });
|
||||
modelsMock.Uploads.findOneById.resolves({ _id: 'file123', userId: 'user123' });
|
||||
canDeleteFileMock.resolves(false);
|
||||
|
||||
await expect(deleteFileMessageMethod('file123')).to.be.rejectedWith('Not authorized');
|
||||
});
|
||||
|
||||
it('should delete orphan file if user has permissions', async () => {
|
||||
meteorUserIdMock.returns('user123');
|
||||
modelsMock.Messages.getMessageByFileId.resolves(null);
|
||||
modelsMock.Users.findOneById.resolves({ _id: 'user123', username: 'test' });
|
||||
modelsMock.Uploads.findOneById.resolves({ _id: 'file123', userId: 'user123' });
|
||||
canDeleteFileMock.resolves(true);
|
||||
deleteByIdMock.resolves();
|
||||
|
||||
await deleteFileMessageMethod('file123');
|
||||
|
||||
expect(fileUploadGetStoreMock.calledOnceWith('Uploads')).to.be.true;
|
||||
expect(deleteByIdMock.calledOnceWith('file123')).to.be.true;
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
import { MeteorError } from '@rocket.chat/core-services';
|
||||
import { expect } from 'chai';
|
||||
import { beforeEach, describe, it } from 'mocha';
|
||||
import p from 'proxyquire';
|
||||
import sinon from 'sinon';
|
||||
|
||||
const checkMock = sinon.stub();
|
||||
const meteorUserIdMock = sinon.stub();
|
||||
const meteorMethodsMock = sinon.stub();
|
||||
const canAccessRoomIdMock = sinon.stub();
|
||||
const normalizeMessagesForUserMock = sinon.stub();
|
||||
const settingsGetMock = sinon.stub();
|
||||
|
||||
// the method pushes into the array it gets back, so each call needs a fresh one
|
||||
const emptyCursor = () => ({ toArray: async () => [] });
|
||||
|
||||
const modelsMock = {
|
||||
Messages: {
|
||||
findOneById: sinon.stub(),
|
||||
findVisibleByRoomIdBeforeTimestamp: sinon.stub().callsFake(emptyCursor),
|
||||
findVisibleByRoomIdAfterTimestamp: sinon.stub().callsFake(emptyCursor),
|
||||
},
|
||||
};
|
||||
|
||||
p.noCallThru().load('../../../../../server/meteor-methods/messages/loadSurroundingMessages', {
|
||||
'meteor/meteor': {
|
||||
Meteor: {
|
||||
userId: meteorUserIdMock,
|
||||
Error: MeteorError,
|
||||
methods: meteorMethodsMock,
|
||||
},
|
||||
},
|
||||
'meteor/check': {
|
||||
check: checkMock,
|
||||
},
|
||||
'@rocket.chat/models': modelsMock,
|
||||
'../../lib/authorization/canAccessRoom': {
|
||||
canAccessRoomIdAsync: canAccessRoomIdMock,
|
||||
},
|
||||
'../../lib/deprecationWarningLogger': {
|
||||
methodDeprecationLogger: { method: sinon.stub() },
|
||||
},
|
||||
'../../lib/utils/lib/normalizeMessagesForUser': {
|
||||
normalizeMessagesForUser: normalizeMessagesForUserMock,
|
||||
},
|
||||
'../../settings': {
|
||||
settings: { get: settingsGetMock },
|
||||
},
|
||||
});
|
||||
|
||||
const loadSurroundingMessagesMethod = meteorMethodsMock.firstCall.args[0].loadSurroundingMessages;
|
||||
|
||||
const mainMessage = { _id: 'msg123', rid: 'room123', ts: new Date('2024-01-01T00:00:00Z') };
|
||||
|
||||
describe('loadSurroundingMessages', () => {
|
||||
beforeEach(() => {
|
||||
checkMock.resetHistory();
|
||||
meteorUserIdMock.reset();
|
||||
canAccessRoomIdMock.reset();
|
||||
normalizeMessagesForUserMock.reset();
|
||||
settingsGetMock.reset();
|
||||
modelsMock.Messages.findOneById.reset();
|
||||
});
|
||||
|
||||
it('should throw for an anonymous user when anonymous read is disabled', async () => {
|
||||
meteorUserIdMock.returns(null);
|
||||
settingsGetMock.withArgs('Accounts_AllowAnonymousRead').returns(false);
|
||||
|
||||
await expect(loadSurroundingMessagesMethod({ _id: 'msg123', rid: 'room123' })).to.be.rejectedWith('Invalid user');
|
||||
});
|
||||
|
||||
it('should load the surrounding messages for an anonymous user when anonymous read is enabled', async () => {
|
||||
meteorUserIdMock.returns(null);
|
||||
settingsGetMock.withArgs('Accounts_AllowAnonymousRead').returns(true);
|
||||
modelsMock.Messages.findOneById.resolves(mainMessage);
|
||||
canAccessRoomIdMock.resolves(true);
|
||||
|
||||
const result = await loadSurroundingMessagesMethod({ _id: 'msg123', rid: 'room123' });
|
||||
|
||||
expect(result).to.not.be.false;
|
||||
expect(result.messages).to.deep.equal([mainMessage]);
|
||||
expect(canAccessRoomIdMock.calledOnceWith('room123', undefined)).to.be.true;
|
||||
expect(normalizeMessagesForUserMock.called).to.be.false;
|
||||
});
|
||||
|
||||
it('should not load the surrounding messages when the room is out of reach', async () => {
|
||||
meteorUserIdMock.returns(null);
|
||||
settingsGetMock.withArgs('Accounts_AllowAnonymousRead').returns(true);
|
||||
modelsMock.Messages.findOneById.resolves(mainMessage);
|
||||
canAccessRoomIdMock.resolves(false);
|
||||
|
||||
expect(await loadSurroundingMessagesMethod({ _id: 'msg123', rid: 'room123' })).to.be.false;
|
||||
});
|
||||
|
||||
it('should normalize the messages for a logged in user', async () => {
|
||||
meteorUserIdMock.returns('user123');
|
||||
modelsMock.Messages.findOneById.resolves(mainMessage);
|
||||
canAccessRoomIdMock.resolves(true);
|
||||
normalizeMessagesForUserMock.resolves([mainMessage]);
|
||||
|
||||
await loadSurroundingMessagesMethod({ _id: 'msg123', rid: 'room123' });
|
||||
|
||||
expect(settingsGetMock.called).to.be.false;
|
||||
expect(normalizeMessagesForUserMock.calledOnceWith([mainMessage], 'user123')).to.be.true;
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { expect } from 'chai';
|
||||
import { beforeEach, describe, it } from 'mocha';
|
||||
import proxyquire from 'proxyquire';
|
||||
import sinon from 'sinon';
|
||||
|
||||
const models = {
|
||||
Subscriptions: {
|
||||
findOneByRoomIdAndUserId: sinon.stub(),
|
||||
setGroupE2EKey: sinon.stub(),
|
||||
setGroupE2ESuggestedKey: sinon.stub(),
|
||||
},
|
||||
Rooms: {
|
||||
removeUsersFromE2EEQueueByRoomId: sinon.stub(),
|
||||
},
|
||||
};
|
||||
|
||||
const { updateGroupKey } = proxyquire.noCallThru().load('../../../../../server/meteor-methods/platform/updateGroupKey.ts', {
|
||||
'../../lib/notifyListener': {
|
||||
notifyOnSubscriptionChanged: sinon.stub(),
|
||||
notifyOnRoomChangedById: sinon.stub(),
|
||||
notifyOnSubscriptionChangedById: sinon.stub(),
|
||||
},
|
||||
'@rocket.chat/models': models,
|
||||
'meteor/meteor': { Meteor: { methods: sinon.stub() } },
|
||||
});
|
||||
|
||||
describe('updateGroupKey', () => {
|
||||
beforeEach(() => {
|
||||
models.Subscriptions.findOneByRoomIdAndUserId.reset();
|
||||
models.Subscriptions.setGroupE2EKey.reset();
|
||||
models.Subscriptions.setGroupE2ESuggestedKey.reset();
|
||||
});
|
||||
|
||||
it('should do nothing if user has no subscription', async () => {
|
||||
models.Subscriptions.findOneByRoomIdAndUserId.resolves(null);
|
||||
const res = await updateGroupKey('rid', 'uid', 'key', 'callerUserId');
|
||||
|
||||
expect(res).to.be.undefined;
|
||||
});
|
||||
it('should suggest the key to the user when uid is different from callerUserId', async () => {
|
||||
models.Subscriptions.findOneByRoomIdAndUserId.resolves({ _id: 'subscriptionId' });
|
||||
models.Subscriptions.setGroupE2ESuggestedKey.resolves({ value: {} });
|
||||
const res = await updateGroupKey('rid', 'uid', 'key', 'callerUserId');
|
||||
|
||||
expect(res).to.be.undefined;
|
||||
expect(models.Subscriptions.setGroupE2ESuggestedKey.calledOnce).to.be.true;
|
||||
});
|
||||
it('should set the group key when uid is the callerUserId', async () => {
|
||||
models.Subscriptions.findOneByRoomIdAndUserId.resolves({ _id: 'subscriptionId' });
|
||||
models.Subscriptions.setGroupE2EKey.resolves({ modifiedCount: 1 });
|
||||
models.Rooms.removeUsersFromE2EEQueueByRoomId.resolves({ modifiedCount: 1 });
|
||||
const res = await updateGroupKey('rid', 'uid', 'key', 'uid');
|
||||
|
||||
expect(res).to.be.undefined;
|
||||
expect(models.Subscriptions.setGroupE2EKey.calledOnce).to.be.true;
|
||||
expect(models.Rooms.removeUsersFromE2EEQueueByRoomId.calledOnce).to.be.true;
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user