Skip to content

Commit 0bc5715

Browse files
authored
Return client errors for invalid image paths (#17942)
1 parent e294953 commit 0bc5715

5 files changed

Lines changed: 84 additions & 31 deletions

File tree

‎.changeset/breezy-bobcats-run.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'astro': patch
3+
---
4+
5+
Returns appropriate 400 and 404 responses from the image endpoint for invalid and missing local image paths

‎packages/astro/src/assets/endpoint/dev.ts‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,13 @@ import { readFile } from 'node:fs/promises';
44
import os from 'node:os';
55
import { type AnymatchFn, isFileLoadingAllowed, type ResolvedConfig } from 'vite';
66
import type { APIRoute } from '../../types/public/common.js';
7-
import { handleImageRequest, loadRemoteImage } from './shared.js';
7+
import { handleImageRequest, type LocalImageLoadResult, loadRemoteImage } from './shared.js';
88

99
function replaceFileSystemReferences(src: string) {
1010
return os.platform().includes('win32') ? src.replace(/^\/@fs\//, '') : src.replace(/^\/@fs/, '');
1111
}
1212

13-
async function loadLocalImage(src: string, url: URL) {
13+
async function loadLocalImage(src: string, url: URL): Promise<LocalImageLoadResult> {
1414
let returnValue: Buffer | undefined;
1515
let fsPath: string | undefined;
1616

@@ -55,12 +55,13 @@ async function loadLocalImage(src: string, url: URL) {
5555
const sourceUrl = new URL(src, url.origin);
5656
// This is only allowed if this is the same origin
5757
if (sourceUrl.origin !== url.origin) {
58-
return undefined;
58+
return { kind: 'invalid-path' };
5959
}
60-
return loadRemoteImage(sourceUrl);
60+
const buffer = await loadRemoteImage(sourceUrl);
61+
return buffer ? { kind: 'loaded', buffer } : { kind: 'failed' };
6162
}
6263

63-
return returnValue;
64+
return returnValue ? { kind: 'loaded', buffer: returnValue } : { kind: 'failed' };
6465
}
6566

6667
/**

‎packages/astro/src/assets/endpoint/node.ts‎

Lines changed: 27 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,31 +5,44 @@ import path from 'node:path';
55
import { fileURLToPath } from 'node:url';
66
import { isParentDirectory } from '@astrojs/internal-helpers/path';
77
import type { APIRoute } from '../../types/public/common.js';
8-
import { handleImageRequest } from './shared.js';
8+
import { handleImageRequest, type LocalImageLoadResult } from './shared.js';
99

10-
async function loadLocalImage(src: string, url: URL) {
10+
async function loadLocalImage(src: string, url: URL): Promise<LocalImageLoadResult> {
1111
const outDirURL = resolveOutDir();
1212
// If the _image segment isn't at the start of the path, we have a base
1313
const idx = url.pathname.indexOf('/_image');
1414
if (idx > 0) {
1515
// Remove the base path
1616
src = src.slice(idx);
1717
}
18-
if (!URL.canParse('.' + src, outDirURL)) {
19-
return undefined;
20-
}
21-
const fileUrl = new URL('.' + src, outDirURL);
22-
if (fileUrl.protocol !== 'file:') {
23-
return undefined;
24-
}
25-
if (!isParentDirectory(fileURLToPath(outDirURL), fileURLToPath(fileUrl))) {
26-
return undefined;
27-
}
2818

19+
let fileUrl: URL;
2920
try {
30-
return await readFile(fileUrl);
21+
if (!URL.canParse('.' + src, outDirURL)) {
22+
return { kind: 'invalid-path' };
23+
}
24+
fileUrl = new URL('.' + src, outDirURL);
25+
if (
26+
fileUrl.protocol !== 'file:' ||
27+
!isParentDirectory(fileURLToPath(outDirURL), fileURLToPath(fileUrl))
28+
) {
29+
return { kind: 'invalid-path' };
30+
}
3131
} catch {
32-
return undefined;
32+
return { kind: 'invalid-path' };
33+
}
34+
35+
try {
36+
return { kind: 'loaded', buffer: await readFile(fileUrl) };
37+
} catch (error) {
38+
if (
39+
error instanceof Error &&
40+
'code' in error &&
41+
(error.code === 'ENOENT' || error.code === 'ENOTDIR' || error.code === 'EISDIR')
42+
) {
43+
return { kind: 'not-found' };
44+
}
45+
return { kind: 'failed' };
3346
}
3447
}
3548

‎packages/astro/src/assets/endpoint/shared.ts‎

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,13 +33,19 @@ export async function loadRemoteImage(src: URL): Promise<Buffer | undefined> {
3333
}
3434
}
3535

36+
export type LocalImageLoadResult =
37+
| { kind: 'loaded'; buffer: Buffer }
38+
| { kind: 'invalid-path' }
39+
| { kind: 'not-found' }
40+
| { kind: 'failed' };
41+
3642
export const handleImageRequest = async ({
3743
request,
3844
loadLocalImage,
3945
logger,
4046
}: {
4147
request: Request;
42-
loadLocalImage: (src: string, baseUrl: URL) => Promise<Buffer | undefined>;
48+
loadLocalImage: (src: string, baseUrl: URL) => Promise<LocalImageLoadResult>;
4349
logger: AstroRuntimeLogger;
4450
}) => {
4551
const imageService = await getConfiguredImageService();
@@ -73,7 +79,17 @@ export const handleImageRequest = async ({
7379

7480
inputBuffer = await loadRemoteImage(new URL(transform.src));
7581
} else {
76-
inputBuffer = await loadLocalImage(removeQueryString(transform.src), url);
82+
const result = await loadLocalImage(removeQueryString(transform.src), url);
83+
switch (result.kind) {
84+
case 'invalid-path':
85+
return new Response('Invalid request', { status: 400 });
86+
case 'not-found':
87+
return new Response('Not Found', { status: 404 });
88+
case 'failed':
89+
return new Response('Internal Server Error', { status: 500 });
90+
case 'loaded':
91+
inputBuffer = result.buffer;
92+
}
7793
}
7894

7995
if (!inputBuffer) {

‎packages/astro/test/core-image.test.ts‎

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1542,22 +1542,18 @@ describe('prod ssr', () => {
15421542
let response = await app.render(request);
15431543
const body = await response.text();
15441544

1545-
// Most paths are malformed local paths (500), but some backslash patterns
1546-
// are now correctly detected as remote and get 403
15471545
const { isRemotePath } = await import('@astrojs/internal-helpers/path');
1548-
const isDetectedAsRemote = isRemotePath(path);
1549-
const expectedStatus = isDetectedAsRemote ? 403 : 500;
1550-
const expectedBodyText = isDetectedAsRemote ? 'Forbidden' : 'Internal Server Error';
1546+
const expectedStatuses = isRemotePath(path) ? [403] : [400, 404, 500];
15511547

15521548
assert.equal(
1553-
response.status,
1554-
expectedStatus,
1555-
`Path "${path}" should return ${expectedStatus}`,
1549+
expectedStatuses.includes(response.status),
1550+
true,
1551+
`Path "${path}" should return ${expectedStatuses.join(' or ')}`,
15561552
);
15571553
assert.equal(
1558-
body.includes(expectedBodyText),
1554+
['Invalid request', 'Forbidden', 'Not Found', 'Internal Server Error'].includes(body),
15591555
true,
1560-
`Path "${path}" body should include "${expectedBodyText}"`,
1556+
`Path "${path}" should return an opaque error`,
15611557
);
15621558
}
15631559

@@ -1567,6 +1563,28 @@ describe('prod ssr', () => {
15671563
assert.equal(response.status, 200);
15681564
});
15691565

1566+
it('returns 400 for local paths with parent directory segments', async () => {
1567+
const app = await fixture.loadTestAdapterApp();
1568+
const paths = ['/../../../.env', '/foo/../../../.env', '/foo\\..\\..\\.env', '/%2e%2e/.env'];
1569+
1570+
for (const path of paths) {
1571+
const request = new Request('http://example.com/_image?href=' + encodeURIComponent(path));
1572+
const response = await app.render(request);
1573+
1574+
assert.equal(response.status, 400, `Path "${path}" should return 400`);
1575+
assert.equal(await response.text(), 'Invalid request');
1576+
}
1577+
});
1578+
1579+
it('returns 404 when a valid local image is not found', async () => {
1580+
const app = await fixture.loadTestAdapterApp();
1581+
const request = new Request('http://example.com/_image?href=/does-not-exist.png');
1582+
const response = await app.render(request);
1583+
1584+
assert.equal(response.status, 404);
1585+
assert.equal(await response.text(), 'Not Found');
1586+
});
1587+
15701588
it('prerendered routes images are built', async () => {
15711589
const html = await fixture.readFile('/client/prerender/index.html');
15721590
const $ = cheerio.load(html);

0 commit comments

Comments
 (0)