fix: harden media sanitization

This commit is contained in:
7w1 committed 2026-06-26 00:33:06 -05:00
1 parent ca2cf3fe47
commit be9a7c70d2
4 files changed
+255 -29

No files matched your search

@@ -0,0 +1,115 @@
import { render } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { MAudio, MFile, MImage, MSticker, MVideo } from './MsgTypeRenderers';
vi.mock('$utils/platform', () => ({
hasServiceWorker: () => false,
hasControllingServiceWorker: () => false,
}));
vi.mock('$utils/fetch', () => ({
fetch: globalThis.fetch,
}));
describe('incoming media renderers', () => {
it('rejects arbitrary image URLs', () => {
const renderImageContent = vi.fn(() => <img alt="rendered" />);
render(
<MImage
content={{ body: 'remote image', url: 'https://attacker.example/image.png' } as any}
renderImageContent={renderImageContent}
/>
);
expect(renderImageContent).not.toHaveBeenCalled();
expect(document.body).toHaveTextContent('Broken message: remote image');
});
it('renders mxc image URLs', () => {
const renderImageContent = vi.fn(() => <img alt="rendered" />);
render(
<MImage
content={{ body: 'matrix image', url: 'mxc://example.org/image' } as any}
renderImageContent={renderImageContent}
/>
);
expect(renderImageContent).toHaveBeenCalledWith(
expect.objectContaining({ url: 'mxc://example.org/image' })
);
});
it('does not pass arbitrary video URLs to the video renderer', () => {
const renderAsFile = vi.fn(() => <span>file fallback</span>);
const renderVideoContent = vi.fn(() => <video />);
render(
<MVideo
content={
{
body: 'remote video',
url: 'https://attacker.example/video.mp4',
info: { mimetype: 'video/mp4' },
} as any
}
renderAsFile={renderAsFile}
renderVideoContent={renderVideoContent}
/>
);
expect(renderVideoContent).not.toHaveBeenCalled();
expect(renderAsFile).toHaveBeenCalledTimes(1);
});
it('does not pass arbitrary audio URLs to the audio renderer', () => {
const renderAsFile = vi.fn(() => <span>file fallback</span>);
const renderAudioContent = vi.fn(() => <audio />);
render(
<MAudio
content={
{
body: 'remote audio',
url: 'https://attacker.example/audio.mp3',
info: { mimetype: 'audio/mpeg' },
} as any
}
renderAsFile={renderAsFile}
renderAudioContent={renderAudioContent}
/>
);
expect(renderAudioContent).not.toHaveBeenCalled();
expect(renderAsFile).toHaveBeenCalledTimes(1);
});
it('rejects arbitrary file URLs', () => {
const renderFileContent = vi.fn(() => <span>rendered file</span>);
render(
<MFile
content={{ body: 'remote file', url: 'https://attacker.example/file.txt' } as any}
renderFileContent={renderFileContent}
/>
);
expect(renderFileContent).not.toHaveBeenCalled();
expect(document.body).toHaveTextContent('Broken message: remote file');
});
it('rejects arbitrary sticker URLs', () => {
const renderImageContent = vi.fn(() => <img alt="rendered sticker" />);
render(
<MSticker
content={{ body: 'remote sticker', url: 'https://attacker.example/sticker.png' } as any}
renderImageContent={renderImageContent}
/>
);
expect(renderImageContent).not.toHaveBeenCalled();
expect(document.body).toHaveTextContent('Broken message: remote sticker');
});
});
+18 -12
View File
@@ -73,6 +73,10 @@ export function BrokenContent({ body }: BrokenContentProps) {
);
}
function getIncomingMediaMxcUrl(url: unknown): string | undefined {
return typeof url === 'string' && url.startsWith('mxc://') ? url : undefined;
}
type RenderBodyProps = {
body: string;
customBody?: string;
@@ -324,8 +328,8 @@ type MImageProps = {
};
export function MImage({ content, renderImageContent, outlined }: MImageProps) {
const imgInfo = content?.info;
const mxcUrl = content.file?.url ?? content.url;
if (typeof mxcUrl !== 'string') {
const mxcUrl = getIncomingMediaMxcUrl(content.file?.url ?? content.url);
if (!mxcUrl) {
return <BrokenContent body={content.body ?? content.filename} />;
}
const MAX_SIZE = 400;
@@ -381,11 +385,12 @@ type MVideoProps = {
};
export function MVideo({ content, renderAsFile, renderVideoContent, outlined }: MVideoProps) {
const videoInfo = content?.info;
const mxcUrl = content.file?.url ?? content.url;
const rawUrl = content.file?.url ?? content.url;
const mxcUrl = getIncomingMediaMxcUrl(rawUrl);
const safeMimeType = getBlobSafeMimeType(videoInfo?.mimetype ?? '');
if (!videoInfo || !safeMimeType.startsWith('video') || typeof mxcUrl !== 'string') {
if (mxcUrl) {
if (!videoInfo || !safeMimeType.startsWith('video') || !mxcUrl) {
if (mxcUrl || typeof rawUrl === 'string') {
return renderAsFile();
}
return <BrokenContent body={content.body ?? content.filename} />;
@@ -450,11 +455,12 @@ type MAudioProps = {
};
export function MAudio({ content, renderAsFile, renderAudioContent, outlined }: MAudioProps) {
const audioInfo = content?.info;
const mxcUrl = content.file?.url ?? content.url;
const rawUrl = content.file?.url ?? content.url;
const mxcUrl = getIncomingMediaMxcUrl(rawUrl);
const safeMimeType = getBlobSafeMimeType(audioInfo?.mimetype ?? '');
if (!audioInfo || !safeMimeType.startsWith('audio') || typeof mxcUrl !== 'string') {
if (mxcUrl) {
if (!audioInfo || !safeMimeType.startsWith('audio') || !mxcUrl) {
if (mxcUrl || typeof rawUrl === 'string') {
return renderAsFile();
}
return <BrokenContent body={content.body ?? content.filename} />;
@@ -505,9 +511,9 @@ type MFileProps = {
};
export function MFile({ content, renderFileContent, outlined }: MFileProps) {
const fileInfo = content?.info;
const mxcUrl = content.file?.url ?? content.url;
const mxcUrl = getIncomingMediaMxcUrl(content.file?.url ?? content.url);
if (typeof mxcUrl !== 'string') {
if (!mxcUrl) {
return <BrokenContent body={content.body ?? content.filename} />;
}
@@ -570,8 +576,8 @@ type MStickerProps = {
};
export function MSticker({ content, renderImageContent }: MStickerProps) {
const imgInfo = content?.info;
const mxcUrl = content.file?.url ?? content.url;
if (typeof mxcUrl !== 'string') {
const mxcUrl = getIncomingMediaMxcUrl(content.file?.url ?? content.url);
if (!mxcUrl) {
return <MessageBrokenContent body={content.body} />;
}
const height = scaleYDimension(imgInfo?.w || 152, 152, imgInfo?.h || 152);
+68 -2
View File
@@ -15,7 +15,12 @@ const mediaCache = vi.hoisted(() => {
};
});
const appFetch = vi.hoisted(() => ({
fetch: vi.fn((input: RequestInfo | URL, init?: RequestInit) => globalThis.fetch(input, init)),
}));
vi.mock('$utils/platform', () => platform);
vi.mock('$utils/fetch', () => appFetch);
vi.mock('./mediaCache', () => mediaCache);
describe('fetchMediaBlob', () => {
@@ -25,6 +30,7 @@ describe('fetchMediaBlob', () => {
vi.resetModules();
platform.hasControllingServiceWorker.mockReset();
platform.hasControllingServiceWorker.mockReturnValue(false);
appFetch.fetch.mockClear();
mediaCache.cache.clear();
mediaCache.getFromMediaCache.mockClear();
mediaCache.putInMediaCache.mockClear();
@@ -226,7 +232,7 @@ describe('fetchMediaBlob', () => {
it('re-resolves auth once after a 401 in direct-fetch mode', async () => {
const { fetchMediaBlob } = await import('./mediaTransport');
const url = 'https://example.org/auth-media.png';
const url = 'https://matrix.example.org/_matrix/client/v1/media/download/example.org/media-id';
localStorage.setItem(
'matrixSessions',
JSON.stringify([
@@ -269,6 +275,66 @@ describe('fetchMediaBlob', () => {
expect(mediaCache.putInMediaCache).toHaveBeenCalledTimes(1);
});
it('does not send stored auth to untrusted origins', async () => {
const { fetchMediaBlob } = await import('./mediaTransport');
const url = 'https://attacker.example/media.png';
const headersSeen: Array<string | null> = [];
localStorage.setItem(
'matrixSessions',
JSON.stringify([
{
baseUrl: 'https://matrix.example.org',
userId: '@alice:example.org',
deviceId: 'DEVICE',
accessToken: 'token-1',
},
])
);
localStorage.setItem('matrixActiveSession', '@alice:example.org');
vi.mocked(fetch).mockImplementation(async (_input, init) => {
const headers = new Headers(init?.headers);
headersSeen.push(headers.get('authorization'));
return new Response('ok', { status: 200 });
});
const blob = await fetchMediaBlob(url);
expect(await blob.text()).toBe('ok');
expect(headersSeen).toEqual([null]);
});
it('does not send stored auth to non-media paths on the homeserver origin', async () => {
const { fetchMediaBlob } = await import('./mediaTransport');
const url = 'https://matrix.example.org/not-media.png';
const headersSeen: Array<string | null> = [];
localStorage.setItem(
'matrixSessions',
JSON.stringify([
{
baseUrl: 'https://matrix.example.org',
userId: '@alice:example.org',
deviceId: 'DEVICE',
accessToken: 'token-1',
},
])
);
localStorage.setItem('matrixActiveSession', '@alice:example.org');
vi.mocked(fetch).mockImplementation(async (_input, init) => {
const headers = new Headers(init?.headers);
headersSeen.push(headers.get('authorization'));
return new Response('ok', { status: 200 });
});
const blob = await fetchMediaBlob(url);
expect(await blob.text()).toBe('ok');
expect(headersSeen).toEqual([null]);
});
it('retries once on the service worker path without direct auth headers', async () => {
platform.hasControllingServiceWorker.mockReturnValue(true);
const { fetchMediaBlob } = await import('./mediaTransport');
@@ -317,7 +383,7 @@ describe('fetchMediaBlob', () => {
it('uses direct auth fetches when service workers are supported but not controlling', async () => {
platform.hasControllingServiceWorker.mockReturnValue(false);
const { fetchMediaBlob } = await import('./mediaTransport');
const url = 'https://example.org/auth-media.png';
const url = 'https://matrix.example.org/_matrix/client/v1/media/download/example.org/media-id';
const headersSeen: Array<string | null> = [];
localStorage.setItem(
+54 -15
View File
@@ -3,6 +3,7 @@ import { fetch } from '$utils/fetch';
import { getFromMediaCache, putInMediaCache } from './mediaCache';
type StoredSession = {
baseUrl?: string;
userId: string;
accessToken: string;
};
@@ -23,6 +24,7 @@ const ACTIVE_SESSION_KEY = 'matrixActiveSession';
const FALLBACK_ACCESS_TOKEN_KEY = 'cinny_access_token';
const FALLBACK_USER_ID_KEY = 'cinny_user_id';
const FALLBACK_BASE_URL_KEY = 'cinny_hs_base_url';
const MATRIX_MEDIA_PATH_PREFIXES = ['/_matrix/media/', '/_matrix/client/v1/media/'];
function parseStoredSessions(): StoredSession[] {
if (typeof localStorage === 'undefined') return [];
@@ -46,6 +48,10 @@ function parseStoredSessions(): StoredSession[] {
return [
{
baseUrl:
typeof (session as { baseUrl?: unknown }).baseUrl === 'string'
? (session as { baseUrl: string }).baseUrl
: undefined,
userId: (session as StoredSession).userId,
accessToken: (session as StoredSession).accessToken,
},
@@ -56,23 +62,61 @@ function parseStoredSessions(): StoredSession[] {
}
}
function getStoredAccessToken(): string | undefined {
function getActiveStoredSession(): StoredSession | undefined {
if (typeof localStorage === 'undefined') return undefined;
const sessions = parseStoredSessions();
const activeSessionId = localStorage.getItem(ACTIVE_SESSION_KEY);
const activeSession =
return (
(activeSessionId
? sessions.find((session) => session.userId === activeSessionId)
: undefined) ?? sessions[0];
: undefined) ?? sessions[0]
);
}
if (activeSession?.accessToken) return activeSession.accessToken;
function getUrlOrigin(url: string): string | undefined {
try {
return new URL(url).origin;
} catch {
return undefined;
}
}
function isMatrixMediaPath(pathname: string): boolean {
return MATRIX_MEDIA_PATH_PREFIXES.some((prefix) => pathname.startsWith(prefix));
}
function isTrustedMatrixMediaUrl(url: string, baseUrl: string | undefined): boolean {
if (!baseUrl) return false;
try {
const parsedUrl = new URL(url);
if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') return false;
return parsedUrl.origin === getUrlOrigin(baseUrl) && isMatrixMediaPath(parsedUrl.pathname);
} catch {
return false;
}
}
function getStoredAccessToken(url: string): string | undefined {
if (typeof localStorage === 'undefined') return undefined;
const activeSession = getActiveStoredSession();
if (activeSession?.accessToken && isTrustedMatrixMediaUrl(url, activeSession.baseUrl)) {
return activeSession.accessToken;
}
const fallbackBaseUrl = localStorage.getItem(FALLBACK_BASE_URL_KEY);
const fallbackUserId = localStorage.getItem(FALLBACK_USER_ID_KEY);
const fallbackAccessToken = localStorage.getItem(FALLBACK_ACCESS_TOKEN_KEY);
if (fallbackBaseUrl && fallbackUserId && fallbackAccessToken) {
if (
fallbackBaseUrl &&
fallbackUserId &&
fallbackAccessToken &&
isTrustedMatrixMediaUrl(url, fallbackBaseUrl)
) {
return fallbackAccessToken;
}
@@ -82,12 +126,7 @@ function getStoredAccessToken(): string | undefined {
export function getCurrentMediaSessionScope(): string {
if (typeof localStorage === 'undefined') return 'anonymous';
const sessions = parseStoredSessions();
const activeSessionId = localStorage.getItem(ACTIVE_SESSION_KEY);
const activeSession =
(activeSessionId
? sessions.find((session) => session.userId === activeSessionId)
: undefined) ?? sessions[0];
const activeSession = getActiveStoredSession();
if (activeSession) {
return activeSession.userId;
@@ -117,7 +156,7 @@ function getScopedMediaCacheKey(url: string, sessionScope?: string): string {
return `${sessionScope ?? getCurrentMediaSessionScope()}:${url}`;
}
function resolveAccessToken(options?: MediaTransportOptions): string | undefined {
function resolveAccessToken(url: string, options?: MediaTransportOptions): string | undefined {
if (options && Object.hasOwn(options, 'getAccessToken')) {
return typeof options.getAccessToken === 'function'
? (options.getAccessToken() ?? undefined)
@@ -128,7 +167,7 @@ function resolveAccessToken(options?: MediaTransportOptions): string | undefined
return options.accessToken ?? undefined;
}
return getStoredAccessToken();
return getStoredAccessToken(url);
}
function resolveSessionScope(options?: MediaTransportOptions): string {
@@ -203,7 +242,7 @@ async function fetchMediaBlobInternal(url: string, options?: MediaTransportOptio
return fetchAndCache(await fetchMediaResponse(url, undefined, cacheMode));
}
const initialAccessToken = resolveAccessToken(options);
const initialAccessToken = resolveAccessToken(url, options);
const initialResponse = await fetchMediaResponse(url, initialAccessToken, cacheMode);
if (initialResponse.ok) {
return fetchAndCache(initialResponse);
@@ -215,7 +254,7 @@ async function fetchMediaBlobInternal(url: string, options?: MediaTransportOptio
);
}
const retryAccessToken = resolveAccessToken(options);
const retryAccessToken = resolveAccessToken(url, options);
return fetchAndCache(await fetchMediaResponse(url, retryAccessToken, cacheMode));
}