Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .maestro/tests/assorted/display-perf.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,9 @@ tags:
label: 'Should have group by favorites'
- extendedWaitUntil:
visible:
id: 'display-pref-view-types'
id: 'display-pref-view-categories'
timeout: 60000
label: 'Should have group by types'
label: 'Should have categories'

# should appear the last message in RoomList when is Expanded
- extendedWaitUntil:
Expand Down
2 changes: 1 addition & 1 deletion android/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ android {
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode VERSIONCODE as Integer
versionName "4.77.0"
versionName "4.77.1"
vectorDrawables.useSupportLibrary = true
manifestPlaceholders = [BugsnagAPIKey: BugsnagAPIKey as String]
}
Expand Down
4 changes: 2 additions & 2 deletions app/containers/message/components/Attachments/Reply.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,8 @@ const UrlImage = ({ image }: { image?: string }) => {
return null;
}

image = image.includes('http') ? image : `${baseUrl}/${image}?rc_uid=${user?.id ?? ''}&rc_token=${user?.token ?? ''}`;
return <Image source={{ uri: image }} style={styles.image} contentFit='cover' />;
const uri = formatAttachmentUrl(image, user?.id ?? '', user?.token ?? '', baseUrl ?? '');
return <Image source={{ uri }} style={styles.image} contentFit='cover' />;
};

const Fields = ({ attachment }: { attachment: IAttachment }) => {
Expand Down
5 changes: 2 additions & 3 deletions app/containers/message/components/Urls.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import axios from 'axios';

import MessageActionTouchable from './Touchable/MessageActionTouchable';
import openLink from '~/lib/methods/helpers/openLink';
import { formatAttachmentUrl } from '~/lib/methods/helpers/formatAttachmentUrl';
import sharedStyles from '~/views/Styles';
import { useTheme } from '~/theme';
import { LISTENER } from '~/containers/Toast';
Expand Down Expand Up @@ -128,9 +129,7 @@ const Url = ({ url }: { url: IUrl }) => {
const rawImageUrl = url.image || url.url;
if (!rawImageUrl || !API_Embed) return;

const _imageUrl = rawImageUrl.startsWith('http')
? rawImageUrl
: `${baseUrl}/${rawImageUrl}?rc_uid=${user?.id ?? ''}&rc_token=${user?.token ?? ''}`;
const _imageUrl = formatAttachmentUrl(rawImageUrl, user?.id ?? '', user?.token ?? '', baseUrl ?? '');

const response = await axios.head(_imageUrl);
const contentType = response.headers['content-type'];
Expand Down
38 changes: 30 additions & 8 deletions app/containers/message/components/__tests__/Reply.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { type IAttachment, type TAnyMessageModel } from '~/definitions';
import { E2E_MESSAGE_TYPE, E2E_STATUS } from '~/lib/constants/keys';
import { fileDownloadAndPreview } from '~/lib/methods/helpers/fileDownload';
import openLink from '~/lib/methods/helpers/openLink';
import { formatAttachmentUrl } from '~/lib/methods/helpers/formatAttachmentUrl';
import { store } from '~/lib/store/auxStore';

jest.mock('~/containers/markdown', () => {
const React = require('react');
Expand All @@ -32,20 +32,20 @@ jest.mock('~/lib/methods/helpers/openLink', () => ({
default: jest.fn()
}));

jest.mock('~/lib/methods/helpers/formatAttachmentUrl', () => ({
formatAttachmentUrl: jest.fn((url: string) => `formatted:${url}`)
jest.mock('~/lib/store/auxStore', () => ({
store: { getState: jest.fn() }
}));

jest.mock('expo-image', () => {
const { View } = require('react-native');
const Image = () => <View testID='reply-url-image' />;
const Image = ({ source }: { source?: { uri?: string } }) => <View testID='reply-url-image' source={source} />;
Image.loadAsync = jest.fn();
return { Image };
});

const mockFileDownloadAndPreview = fileDownloadAndPreview as jest.Mock;
const mockOpenLink = openLink as jest.Mock;
const mockFormatAttachmentUrl = formatAttachmentUrl as jest.Mock;
const mockGetState = store.getState as jest.Mock;

const buildItem = (isEncrypted?: boolean) =>
({
Expand Down Expand Up @@ -84,7 +84,7 @@ mockedStore.dispatch(selectServerSuccess({ server: 'https://open.rocket.chat', v
describe('Reply', () => {
beforeEach(() => {
jest.clearAllMocks();
mockFormatAttachmentUrl.mockImplementation((url: string) => `formatted:${url}`);
mockGetState.mockReturnValue({ settings: { FileUpload_ProtectFiles: true } });
});

describe('null gate', () => {
Expand Down Expand Up @@ -118,8 +118,11 @@ describe('Reply', () => {
fireEvent.press(getByTestId('reply-Alice-doc'));

await waitFor(() => expect(mockFileDownloadAndPreview).toHaveBeenCalled());
expect(mockFormatAttachmentUrl).toHaveBeenCalledWith('/file-upload/doc', 'user-1', 'token', 'https://open.rocket.chat');
expect(mockFileDownloadAndPreview).toHaveBeenCalledWith('formatted:/file-upload/doc', attachment, 'msg-1');
expect(mockFileDownloadAndPreview).toHaveBeenCalledWith(
'https://open.rocket.chat/file-upload/doc?rc_token=token&rc_uid=user-1',
attachment,
'msg-1'
);
expect(mockOpenLink).not.toHaveBeenCalled();
});

Expand Down Expand Up @@ -190,6 +193,25 @@ describe('Reply', () => {
const { queryByTestId } = renderReply({ attachment: { author_name: 'Alice', text: 'Hi' } });
expect(queryByTestId('reply-url-image')).toBeNull();
});

it('adds credentials to a relative thumb_url on the workspace', () => {
const { getByTestId } = renderReply({
attachment: { thumb_url: 'file-upload/1/thumb.png', author_name: 'Alice', text: 'Hi' }
});
const uri = getByTestId('reply-url-image').props.source.uri as string;
expect(uri.startsWith('https://open.rocket.chat/file-upload/1/thumb.png')).toBe(true);
expect(uri).toContain('rc_token=token');
expect(uri).toContain('rc_uid=user-1');
});

it('requests an absolute third-party thumb_url without credentials', () => {
const { getByTestId } = renderReply({
attachment: { thumb_url: 'https://evil.example/thumb.png', author_name: 'Alice', text: 'Hi' }
});
const uri = getByTestId('reply-url-image').props.source.uri as string;
expect(uri).toBe('https://evil.example/thumb.png');
expect(uri).not.toContain('rc_token');
});
});

describe('Fields', () => {
Expand Down
69 changes: 69 additions & 0 deletions app/containers/message/components/__tests__/Urls.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { Provider } from 'react-redux';
import { render, waitFor } from '@testing-library/react-native';
import axios from 'axios';

import Urls from '../Urls';
import { MessageProvider } from '~/containers/message/stores/MessageStore';
import { MessageRoomProvider } from '~/containers/message/stores/MessageRoomStore';
import { mockedStore } from '~/reducers/mockedStore';
import { setUser } from '~/actions/login';
import { selectServerSuccess } from '~/actions/server';
import { addSettings } from '~/actions/settings';
import { type TAnyMessageModel } from '~/definitions';
import { store } from '~/lib/store/auxStore';

jest.mock('~/lib/store/auxStore', () => ({
store: { getState: jest.fn() }
}));

jest.mock('axios', () => ({
__esModule: true,
default: { head: jest.fn() }
}));

jest.mock('expo-image', () => {
const { View } = require('react-native');
const Image = () => <View />;
Image.loadAsync = jest.fn();
return { Image };
});

const SERVER = 'https://mobile.qa.rocket.chat';
const mockHead = axios.head as jest.Mock;

mockedStore.dispatch(setUser({ id: 'user-1', username: 'john', token: 'secret-token' }));
mockedStore.dispatch(selectServerSuccess({ server: SERVER, version: '', name: '' }));
mockedStore.dispatch(addSettings({ API_Embed: true }));

const renderUrls = (urlImage: string) => {
const item = { id: 'msg-1', urls: [{ url: 'https://example.com/page', image: urlImage }] } as unknown as TAnyMessageModel;
return render(
<Provider store={mockedStore}>
<MessageRoomProvider>
<MessageProvider item={item}>
<Urls />
</MessageProvider>
</MessageRoomProvider>
</Provider>
);
};

describe('Urls image preview credentials', () => {
beforeEach(() => {
jest.clearAllMocks();
(store.getState as jest.Mock).mockReturnValue({ settings: { FileUpload_ProtectFiles: true } });
mockHead.mockResolvedValue({ headers: { 'content-type': 'image/png' } });
});

it('adds credentials to a relative preview image on the workspace', async () => {
renderUrls('file-upload/1/preview.png');
await waitFor(() => expect(mockHead).toHaveBeenCalled());
expect(mockHead).toHaveBeenCalledWith(`${SERVER}/file-upload/1/preview.png?rc_token=secret-token&rc_uid=user-1`);
});

it('requests an absolute third-party preview image without credentials', async () => {
renderUrls('https://evil.example/x.png');
await waitFor(() => expect(mockHead).toHaveBeenCalled());
expect(mockHead).toHaveBeenCalledWith('https://evil.example/x.png');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,13 @@ import { selectServerSuccess } from '~/actions/server';
import { type IAttachment, type IUserMessage, type TAnyMessageModel } from '~/definitions';
import { cancelDownload, downloadMediaFile, getMediaCache, isDownloadActive } from '~/lib/methods/handleMediaDownload';
import { fetchAutoDownloadEnabled } from '~/lib/methods/autoDownloadPreference';
import { formatAttachmentUrl } from '~/lib/methods/helpers/formatAttachmentUrl';
import { isImageBase64 } from '~/lib/methods/isImageBase64';
import { emitter } from '~/lib/methods/helpers/emitter';
import { store } from '~/lib/store/auxStore';

jest.mock('~/lib/store/auxStore', () => ({
store: { getState: jest.fn() }
}));

jest.mock('~/lib/methods/handleMediaDownload', () => ({
downloadMediaFile: jest.fn(),
Expand All @@ -26,10 +30,6 @@ jest.mock('~/lib/methods/autoDownloadPreference', () => ({
fetchAutoDownloadEnabled: jest.fn()
}));

jest.mock('~/lib/methods/helpers/formatAttachmentUrl', () => ({
formatAttachmentUrl: jest.fn()
}));

jest.mock('~/lib/methods/isImageBase64', () => ({
isImageBase64: jest.fn()
}));
Expand All @@ -54,9 +54,9 @@ const mockGetMediaCache = getMediaCache as jest.Mock;
const mockIsDownloadActive = isDownloadActive as jest.Mock;
const mockCancelDownload = cancelDownload as jest.Mock;
const mockFetchAutoDownloadEnabled = fetchAutoDownloadEnabled as jest.Mock;
const mockFormatAttachmentUrl = formatAttachmentUrl as jest.Mock;
const mockIsImageBase64 = isImageBase64 as jest.Mock;
const mockEmitterOn = emitter.on as jest.Mock;
const mockGetState = store.getState as jest.Mock;

const URL = 'https://open.rocket.chat/file.png';
const USER = { id: 'user-1', username: 'john', token: 'token' };
Expand Down Expand Up @@ -106,7 +106,7 @@ const renderMediaHook = ({
describe('useMediaAutoDownload', () => {
beforeEach(() => {
jest.clearAllMocks();
mockFormatAttachmentUrl.mockReturnValue(URL);
mockGetState.mockReturnValue({ settings: { FileUpload_ProtectFiles: false } });
mockIsImageBase64.mockReturnValue(false);
mockGetMediaCache.mockResolvedValue({ exists: false });
mockIsDownloadActive.mockReturnValue(false);
Expand Down Expand Up @@ -134,10 +134,11 @@ describe('useMediaAutoDownload', () => {
expect(mockFetchAutoDownloadEnabled).toHaveBeenCalledWith('audioPreferenceDownload');
});

it('defaults to the image preference when the file has no media url', async () => {
it('does not try to auto-download when the file has no media url', async () => {
renderMediaHook({ file: {} });
await flushMount();
expect(mockFetchAutoDownloadEnabled).toHaveBeenCalledWith('imagePreferenceDownload');
expect(mockFetchAutoDownloadEnabled).not.toHaveBeenCalled();
expect(mockDownloadMediaFile).not.toHaveBeenCalled();
});
});

Expand Down Expand Up @@ -184,7 +185,7 @@ describe('useMediaAutoDownload', () => {

it('resumes an active download by registering the download listener and showing loading', async () => {
mockIsDownloadActive.mockReturnValue(true);
const { result } = renderMediaHook({ file: { image_url: '/img' } });
const { result } = renderMediaHook({ file: { image_url: '/file.png' } });
await waitFor(() => expect(result.current.status).toBe('loading'));
expect(mockEmitterOn).toHaveBeenCalledWith(`downloadMedia${URL}`, expect.any(Function));
});
Expand Down Expand Up @@ -236,7 +237,7 @@ describe('useMediaAutoDownload', () => {
describe('onPress', () => {
it('cancels the download and returns to to-download while loading', async () => {
mockIsDownloadActive.mockReturnValue(true);
const { result } = renderMediaHook({ file: { image_url: '/img' } });
const { result } = renderMediaHook({ file: { image_url: '/file.png' } });
await waitFor(() => expect(result.current.status).toBe('loading'));

act(() => result.current.onPress());
Expand Down Expand Up @@ -276,7 +277,7 @@ describe('useMediaAutoDownload', () => {
it('does not open the attachment while it is still encrypted', async () => {
mockIsDownloadActive.mockReturnValue(true);
const showAttachment = jest.fn();
const { result } = renderMediaHook({ file: { image_url: '/img', e2e: 'pending' }, showAttachment });
const { result } = renderMediaHook({ file: { image_url: '/file.png', e2e: 'pending' }, showAttachment });
await waitFor(() => expect(result.current.status).toBe('loading'));

act(() => emitter.emit(`downloadMedia${URL}`, 'file://encrypted'));
Expand All @@ -287,4 +288,42 @@ describe('useMediaAutoDownload', () => {
expect(showAttachment).not.toHaveBeenCalled();
});
});

describe('attachment credentials', () => {
beforeEach(() => {
mockGetState.mockReturnValue({ settings: { FileUpload_ProtectFiles: true } });
});

const getUrl = (file: IAttachment) => renderMediaHook({ file }).result.current.url as string;

it('adds credentials to a file hosted on the workspace', () => {
expect(getUrl({ title_link: '/file.png', image_url: URL })).toBe(`${URL}?rc_token=${USER.token}&rc_uid=${USER.id}`);
});

it('does not rewrite the credentials already on an untrusted url', () => {
const attackerUrl = 'https://evil.example/x.png?rc_token=attacker&rc_uid=attacker';
expect(getUrl({ image_url: attackerUrl })).toBe(attackerUrl);
expect(getUrl({ title_link: attackerUrl, image_url: URL })).toBe(attackerUrl);
});

it.each([
['plain image_url on attacker host', { image_url: 'https://evil.example/pixel.jpg' }],
['title_link on attacker host, image_url on the real server', { title_link: 'https://evil.example/x.jpg', image_url: URL }],
[
'title_link on attacker host, image_url on a look-alike host',
{ title_link: 'https://evil.example/x.jpg', image_url: 'https://open.rocket.chat.evil.example/x.png' }
],
[
'title_link on attacker host, image_url with userinfo',
{ title_link: 'https://evil.example/x.jpg', image_url: 'https://open.rocket.chat@evil.example/x.png' }
],
['title_link on attacker host, no image_url', { title_link: 'https://evil.example/x.jpg', image_type: 'image/png' }],
['video title_link on attacker host', { title_link: 'https://evil.example/v.mp4', video_url: URL }],
['audio title_link on attacker host', { title_link: 'https://evil.example/a.mp3', audio_url: URL }]
] as [string, IAttachment][])('does not send credentials for %s', (_name, file) => {
const url = getUrl(file);
expect(url).not.toContain('rc_token');
expect(url).not.toContain('rc_uid');
});
});
});
4 changes: 4 additions & 0 deletions app/i18n/locales/ar.json
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@
"Connect": "اتصال",
"Connect_to_server_as_user": "اتصل بـ {{serverUrl}} كـ {{user}}",
"Connecting": "جار الاتصال...",
"Connection_timed_out": "انتهت مهلة الاتصال. تحقق من عنوان URL لمساحة العمل وحاول مرة أخرى.",
"Contact_us": "تواصل معنا",
"Contact_your_server_admin": "اتصل بمسؤول الخادم",
"Continue_with": "متابعة بـ",
Expand All @@ -150,6 +151,9 @@
"Dark_level": "مستوى السمة الداكنة",
"Deep_link_login_description": "يوجد رابط يطلب تسجيل دخولك إلى {{server}}. تابع فقط إذا كنت قد فتحت هذا الرابط بنفسك وتثق به.",
"Deep_link_login_title": "تسجيل الدخول إلى مساحة العمل هذه؟",
"Deep_link_open_declined": "تم تجاهل رابط مساحة العمل.",
"Deep_link_open_description": "يوجد رابط يطلب فتح {{server}}. تابع فقط إذا كنت قد فتحت هذا الرابط بنفسك وتثق به.",
"Deep_link_open_title": "فتح مساحة العمل هذه؟",
"Default": "افتراضي",
"Default_browser": "المتصفح الأساسي",
"DELETE": "حذف",
Expand Down
6 changes: 5 additions & 1 deletion app/i18n/locales/bn-IN.json
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@
"Cannot_delete": "মুছতে সম্ভব নয়",
"Cannot_leave": "ছেড়ে যাওয়া সম্ভব নয়",
"Cannot_remove": "সরাতে সম্ভব নয়",
"Categories": "বিভাগসমূহ",
"Certificate_password": "সার্টিফিকেট পাসওয়ার্ড",
"Change_Language": "ভাষা পরিবর্তন",
"Change_language_loading": "ভাষা পরিবর্তন করা হচ্ছে।",
Expand Down Expand Up @@ -175,6 +176,7 @@
"Connect": "সংযোগ করুন",
"Connect_to_server_as_user": "{{user}} হিসেবে {{serverUrl}} এ সংযোগ করুন",
"Connecting": "সংযোগ হচ্ছে...",
"Connection_timed_out": "সংযোগের সময় শেষ হয়ে গেছে। ওয়ার্কস্পেস URL পরীক্ষা করে আবার চেষ্টা করুন।",
"Contact_us": "আমাদের সাথে যোগাযোগ করুন",
"Contact_your_server_admin": "আপনার কাজকর্ম অ্যাডমিনের সাথে যোগাযোগ করুন।",
"Content": "কন্টেন্ট",
Expand Down Expand Up @@ -215,6 +217,9 @@
"decline": "অস্বীকার করুন",
"Deep_link_login_description": "একটি লিঙ্ক আপনাকে {{server}}-এ সাইন ইন করাতে চাইছে। আপনি নিজে এই লিঙ্কটি খুলে থাকেন এবং এটিকে বিশ্বাস করেন তবেই এগিয়ে যান।",
"Deep_link_login_title": "এই ওয়ার্কস্পেসে সাইন ইন করবেন?",
"Deep_link_open_declined": "ওয়ার্কস্পেস লিংক খারিজ করা হয়েছে।",
"Deep_link_open_description": "একটি লিঙ্ক {{server}} খুলতে চাইছে। আপনি নিজে এই লিঙ্কটি খুলে থাকেন এবং এটিকে বিশ্বাস করেন তবেই এগিয়ে যান।",
"Deep_link_open_title": "এই ওয়ার্কস্পেস খুলবেন?",
"Default": "ডিফল্ট",
"Default_browser": "ডিফল্ট ব্রাউজার",
"Defined_user_as_role": "{{user}} একটি {{role}} হিসেবে নির্ধারণ করেছে",
Expand Down Expand Up @@ -873,7 +878,6 @@
"Two_Factor_Authentication": "দুটি ধারণামূলক প্রমাণীকরণ",
"Two_Factor_Success_message": "দুই-স্তরের প্রমাণীকরণ কোড পাঠানো হয়েছে! অনুগ্রহ করে আপনার ইমেইল চেক করুন।",
"Type_message": "বার্তা লিখুন",
"Types": "ধরণ",
"UNARCHIVE": "আনআরকাইভ",
"unarchive": "আনআরকাইভ",
"unauthorized": "অননুমোদিত",
Expand Down
Loading
Loading