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
2 changes: 1 addition & 1 deletion packages/vite/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@
"fresh-import": "^0.2.1",
"host-validation-middleware": "^0.1.4",
"http-proxy-3": "^1.23.3",
"launch-editor-middleware": "^2.14.1",
"launch-editor-middleware": "^2.14.2",
"magic-string": "^1.2.0",
"mlly": "^1.8.2",
"mrmime": "^2.0.1",
Expand Down
29 changes: 29 additions & 0 deletions packages/vite/src/node/__tests__/dev.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,35 @@ describe('the dev server', () => {
expect(server.config.safeModulePaths).not.toContain(externalEntry)
})

test('does not mark unresolved SSR imports as safe', async () => {
const root = path.join(import.meta.dirname, 'fixtures', 'input-option')
const entry = normalizePath(path.join(root, 'unresolved-entry.js'))
const unresolvedImport = '/safe-module-path-unresolved'

server = await createServer({
configFile: false,
root,
optimizeDeps: { noDiscovery: true },
server: { middlewareMode: true, ws: false },
plugins: [
{
name: 'unresolved-ssr-import',
resolveId(id) {
if (id === '/unresolved-entry.js') return entry
},
load(id) {
if (id === entry)
return `import ${JSON.stringify(unresolvedImport)}`
},
},
],
})

await server.environments.ssr.transformRequest('/unresolved-entry.js')

expect(server.config.safeModulePaths).not.toContain(unresolvedImport)
})

test('silently resolves index.html as the fallback for every environment', async () => {
const root = path.join(import.meta.dirname, 'fixtures', 'input-option')
const clientEntry = normalizePath(path.join(root, 'client-index.html'))
Expand Down
9 changes: 3 additions & 6 deletions packages/vite/src/node/plugins/importAnalysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ import {
} from '../server/hmr'
import {
createDebugger,
fsPathFromUrl,
generateCodeFrame,
getFileStartIndex,
getHash,
Expand Down Expand Up @@ -588,13 +587,11 @@ export function importAnalysisPlugin(config: ResolvedConfig): Plugin {

// normalize
let [url, resolvedId] = await normalizeUrl(specifier, start)
if (resolvedId) {
config.safeModulePaths.add(cleanUrl(resolvedId))
}
resolvedId = resolvedId || url

// record as safe modules
// safeModulesPath should not include the base prefix.
// See https://github.com/vitejs/vite/issues/9438#issuecomment-1465270409
config.safeModulePaths.add(fsPathFromUrl(stripBase(url, base)))

if (url !== specifier) {
let rewriteDone = false
// optimizer-emitted imports resolve to the sibling file they
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { FS_PREFIX } from '../../../constants'
const FIXTURE_DIR = path.resolve(import.meta.dirname, 'fixtures')
const HTML_PATH = path.resolve(FIXTURE_DIR, 'root/index.html')
const HTML_CONTENT = fs.readFileSync(HTML_PATH, 'utf-8')
const VITE_PACKAGE_DIR = path.resolve(import.meta.dirname, '../../../../..')

async function createTestServer(rootDir?: string) {
const root = path.resolve(import.meta.dirname, rootDir ?? 'fixtures/root')
Expand All @@ -29,7 +30,7 @@ async function createTestServer(rootDir?: string) {
return server
}

describe('indexHtml middleware — /@fs/ inline script proxy cache', () => {
describe('indexHtml middleware — inline script proxy cache', () => {
test('inline <script type="module"> in an /@fs/ HTML file is loadable via the html-proxy module', async () => {
const server = await createTestServer()
const fsUrl = path.posix.join(FS_PREFIX, HTML_PATH)
Expand Down Expand Up @@ -85,6 +86,25 @@ describe('indexHtml middleware — /@fs/ inline script proxy cache', () => {
expect(result, 'proxy module should resolve without error').not.toBeNull()
expect(result!.code).toContain('module loaded')
})

for (const prefix of ['//', '///']) {
test(`does not preserve a protocol-relative request URL (${prefix}) as the inline module proxy URL`, async () => {
const server = await createTestServer(VITE_PACKAGE_DIR)
const url = prefix + 'evil.example.com/payload.js?/../../package.json'

const transformed = await server.transformIndexHtml(url, HTML_CONTENT)
const proxyUrlMatch = transformed.match(/src="([^"]*html-proxy[^"]*)"/)

expect(
proxyUrlMatch,
'devHtmlHook should have rewritten the inline <script> to a ?html-proxy src',
).toBeTruthy()
expect(proxyUrlMatch![1]).toMatchInlineSnapshot(
`"/@id/__x00__/evil.example.com/payload.js?/../../package.json?html-proxy&index=0.js"`,
)
expect(proxyUrlMatch![1]).not.toMatch(/^\/\//)
})
}
})

describe('indexHtml middleware — HMR timestamp injection with non-root base', () => {
Expand Down
16 changes: 13 additions & 3 deletions packages/vite/src/node/server/middlewares/indexHtml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,11 +106,12 @@ export function createDevHtmlTransformFn(
}

function getHtmlFilename(url: string, server: ViteDevServer) {
if (url.startsWith(FS_PREFIX)) {
return decodeURIComponent(fsPathFromId(url))
const urlPath = cleanUrl(url)
if (urlPath.startsWith(FS_PREFIX)) {
return decodeURIComponent(fsPathFromId(urlPath))
} else {
return decodeURIComponent(
normalizePath(path.join(server.config.root, url.slice(1))),
normalizePath(path.join(server.config.root, urlPath.slice(1))),
)
}
}
Expand All @@ -131,6 +132,8 @@ function getHtmlDirnameForRelativeUrl(htmlPath: string): string {
return htmlPath.endsWith('/') ? htmlPath : path.posix.dirname(htmlPath)
}

const multipleLeadingSlashesRE = /^\/{2,}/g

const processNodeUrl = (
url: string,
useSrcSetReplacer: boolean,
Expand Down Expand Up @@ -205,6 +208,13 @@ const devHtmlHook: IndexHtmlTransformHook = async (
html,
{ path: htmlPath, filename, server, originalUrl },
) => {
// There's no way to express a relative URL that starts with `//`. URLs starting with `//` is relative to the scheme.
// The relative URL is needed to generate the URL in script tags and link tags.
// We replace `//` with `/` here for workaround, which is the best we can do.
if (htmlPath.startsWith('//')) {
htmlPath = htmlPath.replace(multipleLeadingSlashesRE, '/')
}

const { config, watcher } = server!
const base = config.base || '/'
const decodedBase = config.decodedBase || '/'
Expand Down
9 changes: 8 additions & 1 deletion packages/vite/src/node/server/middlewares/transform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,12 +56,19 @@ const urlRE = /[?&]url\b/
const rawRE = /[?&]raw\b/
const inlineRE = /[?&]inline\b/
const svgRE = /\.svg\b/
const wasmInstanceRE = /[?&]vite-wasm-instance(?:&|$)/

export function isServerAccessDeniedForTransform(
config: ResolvedConfig,
id: string,
): boolean {
if (rawRE.test(id) || urlRE.test(id) || inlineRE.test(id) || svgRE.test(id)) {
if (
rawRE.test(id) ||
urlRE.test(id) ||
inlineRE.test(id) ||
svgRE.test(id) ||
wasmInstanceRE.test(id)
) {
return (
checkLoadingAccess(config, cleanUrl(id)) !== 'allowed' ||
checkLoadingAccess(config, id) !== 'allowed'
Expand Down
13 changes: 13 additions & 0 deletions playground/fs-serve/__tests__/commonTests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,13 @@ describe.runIf(isServe)('matrix', () => {
content: /403 Restricted/,
status: '403',
},
{
name: 'unsafe fetch with vite wasm instance query',
testId: 'unsafe-vite-wasm-instance',
content: /403 Restricted/,
status: '403',
disableVariants: [''],
},
// It is 404 in `fs-serve/base` test, 403 in `fs-serve` test
{
name: 'unsafe fetch with relative path after query',
Expand Down Expand Up @@ -259,6 +266,12 @@ describe.runIf(isServe)('matrix', () => {
content: /403 Restricted/,
status: '403',
},
{
name: 'denied .env with vite wasm instance query',
testId: 'unsafe-dotenv-vite-wasm-instance',
content: /403 Restricted/,
status: '403',
},
// On NTFS, it exposes a file's default data stream through the `::$DATA` suffix,
// so `.env::$DATA` resolves to the same content as `.env`.
// It is 404 on non-NTFS.
Expand Down
10 changes: 9 additions & 1 deletion playground/fs-serve/__tests__/fs-serve.spec.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
import net from 'node:net'
import path from 'node:path'
import { describe, expect, test } from 'vitest'
import { isServe, isWindows, viteTestUrl } from '~utils'
import { isServe, isWindows, page, viteTestUrl } from '~utils'
import './commonTests'

describe.runIf(isServe)('safe module paths', () => {
test('keeps root-relative module URLs separate from absolute filesystem paths', async () => {
await expect
.poll(() => page.textContent('.safe-module-path-status'))
.toBe(isWindows ? '404' : '403')
})
})

describe.runIf(isServe)('invalid request', () => {
const sendRawRequest = async (baseUrl: string, requestTarget: string) => {
return new Promise<string>((resolve, reject) => {
Expand Down
2 changes: 2 additions & 0 deletions playground/fs-serve/root/matrixTestResultPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ const testIds = [
'unsafe-query-dot-svg-import',
'unsafe-svg',
'unsafe-import-inline-wasm-init',
'unsafe-vite-wasm-instance',
'unsafe-relative-path-after-query',
'unsafe-dotenv',
'unsafe-dotenv-casing',
Expand All @@ -32,6 +33,7 @@ const testIds = [
'unsafe-dotenv-inline',
'unsafe-dotenv-query-dot-svg-wasm-init',
'unsafe-dotenv-import-raw',
'unsafe-dotenv-vite-wasm-instance',
'unsafe-dotenv-ntfs-ads',
'unsafe-dotenv-83-short-name',
]
Expand Down
24 changes: 24 additions & 0 deletions playground/fs-serve/root/safeModulePathPlugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import path from 'node:path'
import type { Plugin } from 'vite'

const playgroundRoot = path.dirname(import.meta.dirname).replace(/\\/g, '/')
const targetRoot = playgroundRoot.replace(/^[A-Z]:/i, '')
const target = path.posix.join(targetRoot, 'root/unsafe.txt')
const decoyId = path.posix.join(import.meta.dirname.replace(/\\/g, '/'), target)

export default function safeModulePathPlugin(): Plugin {
return {
name: 'safe-module-path',
enforce: 'pre',
resolveId(id) {
if (id === 'virtual:safe-module-path-confusion') {
return decoyId
}
},
load(id) {
if (id === decoyId) {
return 'export {}'
}
},
}
}
23 changes: 23 additions & 0 deletions playground/fs-serve/root/src/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,17 @@ <h2>Normal Import</h2>
<pre class="virtual-svg"></pre>
</div>

<div>
<h2>Safe Module Path Access Isolation</h2>
<pre class="safe-module-path-status"></pre>
</div>

<!-- REPLACE WITH MATRIX TEST RESULT -->

<script type="module">
import '../../entry'
import json, { msg } from '../../safe.json'
import 'virtual:safe-module-path-confusion'
import './code.js'

// Check virtual svg module still works
Expand All @@ -23,6 +29,13 @@ <h2>Normal Import</h2>
text('.named', msg)
text('.virtual-svg', fooSvg)

if (import.meta.env.DEV) {
const base = typeof BASE !== 'undefined' ? BASE : '/'
const hostFileUrl = `${base}@fs${ROOT}/root/unsafe.txt`
const response = await fetch(hostFileUrl)
text('.safe-module-path-status', response.status)
}

function text(sel, text) {
document.querySelector(sel).textContent = text
}
Expand Down Expand Up @@ -124,6 +137,11 @@ <h2>Normal Import</h2>
testId: 'unsafe-import-inline-wasm-init',
path: '/root/unsafe.txt?import&?inline=1.wasm?init',
},
// outside of allowed dir, vite wasm instance query
{
testId: 'unsafe-vite-wasm-instance',
path: '/unsafe.json?import&vite-wasm-instance',
},
// outside of allowed dir, relative path after query
{
testId: 'unsafe-relative-path-after-query',
Expand Down Expand Up @@ -155,6 +173,11 @@ <h2>Normal Import</h2>
},
// .env with ?import&raw
{ testId: 'unsafe-dotenv-import-raw', path: '/root/src/.env?import&raw' },
// .env with ?vite-wasm-instance
{
testId: 'unsafe-dotenv-vite-wasm-instance',
path: '/root/src/.env?vite-wasm-instance',
},
// .env with NTFS ADS suffix
{ testId: 'unsafe-dotenv-ntfs-ads', path: '/root/src/.env::$DATA' },
// .env with 8.3 short name
Expand Down
7 changes: 6 additions & 1 deletion playground/fs-serve/root/vite.config-base.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import path from 'node:path'
import { defineConfig } from 'vite'
import safeModulePathPlugin from './safeModulePathPlugin.ts'
import svgVirtualModulePlugin from './svgVirtualModulePlugin.ts'
import matrixTestResultPlugin from './matrixTestResultPlugin.ts'
import { getWindows83ShortNameForDotEnv } from './windows83Filename.ts'
Expand Down Expand Up @@ -36,5 +37,9 @@ export default defineConfig({
BASE: JSON.stringify(BASE),
DOTENV83SHORTNAME: JSON.stringify(getWindows83ShortNameForDotEnv()),
},
plugins: [svgVirtualModulePlugin(), matrixTestResultPlugin()],
plugins: [
svgVirtualModulePlugin(),
safeModulePathPlugin(),
matrixTestResultPlugin(),
],
})
3 changes: 2 additions & 1 deletion playground/fs-serve/root/vite.config-deny.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import path from 'node:path'
import { defineConfig } from 'vite'
import safeModulePathPlugin from './safeModulePathPlugin.ts'
import svgVirtualModulePlugin from './svgVirtualModulePlugin.ts'

export default defineConfig({
Expand All @@ -19,5 +20,5 @@ export default defineConfig({
define: {
ROOT: JSON.stringify(path.dirname(import.meta.dirname).replace(/\\/g, '/')),
},
plugins: [svgVirtualModulePlugin()],
plugins: [svgVirtualModulePlugin(), safeModulePathPlugin()],
})
7 changes: 6 additions & 1 deletion playground/fs-serve/root/vite.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import path from 'node:path'
import { defineConfig } from 'vite'
import safeModulePathPlugin from './safeModulePathPlugin.ts'
import svgVirtualModulePlugin from './svgVirtualModulePlugin.ts'
import matrixTestResultPlugin from './matrixTestResultPlugin.ts'
import { getWindows83ShortNameForDotEnv } from './windows83Filename.ts'
Expand Down Expand Up @@ -32,5 +33,9 @@ export default defineConfig({
ROOT: JSON.stringify(path.dirname(import.meta.dirname).replace(/\\/g, '/')),
DOTENV83SHORTNAME: JSON.stringify(getWindows83ShortNameForDotEnv()),
},
plugins: [svgVirtualModulePlugin(), matrixTestResultPlugin()],
plugins: [
svgVirtualModulePlugin(),
safeModulePathPlugin(),
matrixTestResultPlugin(),
],
})
26 changes: 26 additions & 0 deletions playground/html/__tests__/html.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,32 @@ test('invalidate inline proxy module on reload', async () => {
expect(await page.textContent('.test')).toContain('ok')
})

test.runIf(!isBundled)(
'normalizes protocol-relative HTML proxy URLs',
async () => {
const response = await fetchHtml('//protocol-relative.html')
const html = await response.text()

expect(response.status).toBe(200)
expect(html).toContain('url(./protocol-relative.png)')
expect(html).toContain(
'src="/protocol-relative.html?html-proxy&index=0.js"',
)
expect(html).not.toContain('url(//protocol-relative.png)')
expect(html).not.toContain('src="//protocol-relative.html?html-proxy')
expect(
viteServer.environments.client.moduleGraph.urlToModuleMap.has(
'/protocol-relative.html?html-proxy&direct&index=0.css',
),
).toBe(true)
expect(
viteServer.environments.client.moduleGraph.urlToModuleMap.has(
'//protocol-relative.html?html-proxy&direct&index=0.css',
),
).toBe(false)
},
)

test.runIf(isServe)(
'malformed URLs in src attributes should show errors',
async () => {
Expand Down
Loading
Loading