⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
fix(web): serve only avatar and attachment files from the media route (#633)
Croff9b039bda0fab
diff --git a/apps/web/src/app/media/[...path]/route.test.ts b/apps/web/src/app/media/[...path]/route.test.tsnew file mode 100644index 00000000..c9581185--- /dev/null+++ b/apps/web/src/app/media/[...path]/route.test.ts@@ -0,0 +1,62 @@+import assert from 'node:assert/strict';+import { afterEach, describe, it } from 'node:test';+import { GET } from './route';++const PUBLIC_ID = '123e4567-e89b-42d3-a456-426614174000';+const originalFetch = globalThis.fetch;+const originalOrigin = process.env.SERVICE_URL_API;++afterEach(() => {+ globalThis.fetch = originalFetch;+ if (originalOrigin === undefined) delete process.env.SERVICE_URL_API;+ else process.env.SERVICE_URL_API = originalOrigin;+});++function get(path: string[]) {+ return GET(new Request('https://plan.test/media/example'), { params: Promise.resolve({ path }) });+}++describe('public media proxy', () => {+ it('answers 404 without contacting the API for a path of another shape', async () => {+ let called = false;+ globalThis.fetch = (async () => {+ called = true;+ return new Response();+ }) as typeof fetch;+ for (const path of [+ ['docs', PUBLIC_ID, 'raw'],+ ['avatars', 'not-an-id', 'raw'],+ ['avatars', PUBLIC_ID],+ ['avatars', PUBLIC_ID, 'meta'],+ ['avatars', PUBLIC_ID, 'raw', 'extra'],+ ]) {+ const response = await get(path);+ assert.equal(response.status, 404, path.join('/'));+ }+ assert.equal(called, false);+ });++ it('streams the exact media endpoint with the query and the cache validator', async () => {+ process.env.SERVICE_URL_API = 'http://api:3000';+ let capturedInput = '';+ let capturedInit: RequestInit | undefined;+ globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {+ capturedInput = String(input);+ capturedInit = init;+ return new Response('image', {+ headers: { 'content-type': 'image/png', 'x-private': 'drop-me' },+ });+ }) as typeof fetch;+ const response = await GET(+ new Request('https://plan.test/media/example?download=1', {+ headers: { cookie: 'session=value', 'if-none-match': 'v0' },+ }),+ { params: Promise.resolve({ path: ['attachments', PUBLIC_ID, 'raw'] }) },+ );+ assert.equal(capturedInput, `http://api:3000/attachments/${PUBLIC_ID}/raw?download=1`);+ assert.deepEqual(capturedInit?.headers, { 'if-none-match': 'v0' });+ assert.equal(capturedInit?.redirect, 'error');+ assert.equal(response.headers.get('content-type'), 'image/png');+ assert.equal(response.headers.get('x-private'), null);+ });+});diff --git a/apps/web/src/app/media/[...path]/route.ts b/apps/web/src/app/media/[...path]/route.tsindex 22e1b5ca..ac381546 100644--- a/apps/web/src/app/media/[...path]/route.ts+++ b/apps/web/src/app/media/[...path]/route.ts@@ -9,6 +9,7 @@ import { serverRuntimeEnv } from '@/utils/runtimeEnv';// request header is forwarded — this must never become a way to reach the rest of the// api through the web server.const MEDIA_ROOTS = ['avatars', 'attachments', 'chat-attachments', 'initiative-attachments'];+const PUBLIC_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;// Copied from the api's response, including the headers that keep attacker-controlled// bytes inert (nosniff, the disposition that forces a download, the sandbox CSP).@@ -24,7 +25,13 @@ const PASSTHROUGH_HEADERS = [export async function GET(request: Request, { params }: { params: Promise<{ path: string[] }> }) {const { path } = await params;- if (!MEDIA_ROOTS.includes(path[0]) || path.some((segment) => segment === '..')) {+ const [root, publicId, raw] = path;+ if (+ path.length !== 3 ||+ !MEDIA_ROOTS.includes(root) ||+ !PUBLIC_ID.test(publicId) ||+ raw !== 'raw'+ ) {return new Response(null, { status: 404 });}@@ -32,10 +39,11 @@ export async function GET(request: Request, { params }: { params: Promise<{ path// reached by service name, which is what SERVICE_URL_API carries (as for the worker).const origin = process.env.SERVICE_URL_API || serverRuntimeEnv().apiUrl;const { search } = new URL(request.url);- const upstream = await fetch(`${origin}/${path.join('/')}${search}`, {+ const upstream = await fetch(`${origin}/${root}/${publicId}/raw${search}`, {// The api answers 304 to it, and passing it on keeps a cached avatar cached.headers: forwardedHeaders(request),cache: 'no-store',+ redirect: 'error',});const headers = new Headers();