Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

test(e2e): reject unsafe launch profiles and environment overrides (#9457)

James Dam44af0c93ae25
diff --git a/.github/workflows/e2e-check.yml b/.github/workflows/e2e-check.yml
index 307a8f348..512e2d268 100644
--- a/.github/workflows/e2e-check.yml
+++ b/.github/workflows/e2e-check.yml
@@ -2,7 +2,7 @@
# workflow installs it or looks at it. rust-check.yml does run on every PR, but
# it never touches e2e/ -- so without this, an e2e-only change would go through
# CI entirely unvalidated.
-# This validates the harness type-checks and its lockfile is current. It does
+# This runs focused launch-guard unit tests, typechecks, and checks the lockfile. It does
# NOT run the suite: that needs a full Tauri app build, 6-11 min cold on the
# hosted images, which is why running it is nightly work. See e2e-suite.yml, which does launch the app
# on all four platforms and can be dispatched by hand against any branch.
@@ -18,7 +18,10 @@ on:
jobs:
typecheck:
name: typecheck
- runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ os: [ubuntu-latest, macos-latest, windows-latest]
+ runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
@@ -35,6 +38,10 @@ jobs:
corepack enable
yarn install --immutable
+ - name: Launch guard unit tests
+ working-directory: e2e
+ run: yarn test:unit
+
- name: Typecheck
working-directory: e2e
run: yarn typecheck
diff --git a/.github/workflows/e2e-suite.yml b/.github/workflows/e2e-suite.yml
index eac245a21..d09c15121 100644
--- a/.github/workflows/e2e-suite.yml
+++ b/.github/workflows/e2e-suite.yml
@@ -83,19 +83,23 @@ jobs:
steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6
- # wdio.conf.ts creates a throwaway profile per run and deletes it, but an
- # inherited JAN_E2E_HOME is used and never removed (`ownsTestHome`) -- so
- # naming one is what leaves the profile behind for the artifact step.
- # Exported from a step rather than set in the job's `env`, because the
- # `runner` context does not exist yet at job level.
- - name: Pin the test profile inside the runner temp dir
- shell: bash
- run: echo "JAN_E2E_HOME=${{ runner.temp }}/jan-e2e-home" >> "$GITHUB_ENV"
-
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
with:
node-version: 20
+ # Use Node's temp root, which need not equal runner.temp. An inherited
+ # profile is validated but never deleted, so artifacts can retain it.
+ - name: Allocate the test profile inside the OS temp dir
+ shell: bash
+ run: |
+ node --input-type=module <<'NODE'
+ import { appendFileSync, mkdtempSync, realpathSync } from 'node:fs'
+ import { tmpdir } from 'node:os'
+ import { join } from 'node:path'
+ const home = mkdtempSync(join(realpathSync(tmpdir()), 'jan-e2e-'))
+ appendFileSync(process.env.GITHUB_ENV, `JAN_E2E_HOME=${home}\n`)
+ NODE
+
- uses: dtolnay/rust-toolchain@stable
# No cargo cache on purpose. rust-check.yml's policy of restoring on
@@ -179,7 +183,7 @@ jobs:
name: e2e-logs-${{ matrix.name }}
path: |
e2e/logs
- ${{ runner.temp }}/jan-e2e-home
- !${{ runner.temp }}/jan-e2e-home/AppData/Local/*/EBWebView
+ ${{ env.JAN_E2E_HOME }}
+ !${{ env.JAN_E2E_HOME }}/AppData/Local/*/EBWebView
retention-days: 7
if-no-files-found: warn
diff --git a/e2e/README.md b/e2e/README.md
index 1dca61d4a..6927e3535 100644
--- a/e2e/README.md
+++ b/e2e/README.md
@@ -109,7 +109,7 @@ cd e2e && yarn test
| Variable | Effect |
| --- | --- |
| `JAN_E2E_KEEP=1` | Keep the throwaway profile after the run instead of deleting it. |
-| `JAN_E2E_HOME=<dir>` | Use `<dir>` as the profile instead of a fresh temp dir. A directory supplied this way is never deleted — only a profile the harness created is cleaned up. Primarily how the launcher hands the path to its workers. |
+| `JAN_E2E_HOME=<dir>` | Use a validated `<dir>` strictly inside the OS temp root as the profile instead of a fresh temp dir. A directory supplied this way is never deleted — only a profile the harness created is cleaned up. Primarily how the launcher hands the path to its workers. |
This package is **not** a yarn workspace of the root project. It has its own
lockfile, because it shares no code with `core`/`web-app` and adding it to the
@@ -121,7 +121,8 @@ the release-build jobs that never run this suite.
Two workflows, deliberately split by cost:
- `.github/workflows/e2e-check.yml` runs on every PR that touches `e2e/**`. It
- type-checks this package and enforces `--immutable` against its lockfile. It
+ runs focused launch-guard unit tests and type-checks this package on Linux,
+ macOS and Windows, and enforces `--immutable` against its lockfile. It
does not build the app, so it cannot run the suite.
- `.github/workflows/e2e-suite.yml` builds the app and runs the suite on
ubuntu-latest, macos-latest, windows-latest and windows-11-arm. Nightly on
@@ -190,6 +191,46 @@ override depends on the platform.
| Linux | `$XDG_DATA_HOME`, else `$HOME/.local/share` | `HOME` **and** `XDG_DATA_HOME` |
| Windows | `FOLDERID_RoamingAppData` | nothing the OS provides — see below |
+### Launch guard (limited guarantee)
+
+Before profile seeding, recursive cleanup registration, or launch,
+`launch-guard.ts` validates `JAN_E2E_HOME`. Inherited paths are checked before
+mkdir; generated profiles require an initial `mkdtemp` allocation, preceded by
+the environment check. It must be strictly inside the OS temp root; CI and local launches
+allocate profiles with `mkdtemp` under Node’s `os.tmpdir()` (which may differ
+from GitHub’s `runner.temp`). Real homes and
+ancestors/descendants of known user Jan paths are rejected, including inherited
+XDG/AppData locations. Existing prefixes are canonicalized (also for not-yet-created
+paths) so symlink aliases cannot disguise overlap; sibling names are accepted.
+Redirected seed/scratch roots, desktop configuration paths, and their
+`data_folder` values outside the profile are rejected. This includes legacy
+migration sources: Rust checks canonical `Jan/settings.json` first, then (only
+if absent) copies and removes the first file found among bundle-id
+`settings.json` and then, on Linux, `.config/Jan/settings.json`. The guard conservatively
+validates all these sources even when shadowed by a higher-priority config,
+including known nightly/beta bundle IDs (Rust's current migration constant is
+`jan.ai.app`), and checks their directory/file symlinks before reading them.
+Inherited profiles are never recursively deleted.
+
+Unset nonempty `JAN_DATA_ROOT` on Unix: the WDIO service merges
+`{ ...process.env, ...options.env }`, so omitting it from the Unix overrides
+would otherwise preserve it and bypass native HOME/XDG lookup. Even a relative
+value is rejected rather than relying on fallback behavior. Windows explicitly
+overrides it. Nonempty `JAN_DATA_FOLDER`, `CI=e2e`, and `APP_NAME` values other
+than `Jan` (including empty) are rejected too.
+
+This is an accidental-launch guard, **not a filesystem sandbox** or a proof of
+complete confinement. It does not prevent concurrent symlink changes, hard-link
+aliases, every possible legacy/plugin/config escape, Windows registry folder
+redirection, or the Windows CLI/updater gaps below. Use a disposable OS account
+or VM if stronger separation is needed. Existing profiles should be disposable;
+the harness merges a bootstrap seed into their backend settings.
+
+Run `cd e2e && yarn test:unit && yarn typecheck` without an app build. The focused
+`node:test` tests run via the existing `tsx`, use only temporary fixture homes,
+and check rejection without writes, containment siblings, environment bypasses,
+and symlink aliases (Windows skips only if privilege is unavailable).
+
On Linux the harness pins **every** XDG base directory
(`XDG_DATA_HOME`, `XDG_CONFIG_HOME`, `XDG_STATE_HOME`, `XDG_CACHE_HOME`) rather
than relying on them being unset. Each outranks its `$HOME`-relative default, so
@@ -262,7 +303,9 @@ in `isolation.ts` next to `XDG_RUNTIME_DIR`:
base with Tauri's own resolver rather than `core/app/paths.rs`, landing it in
the real `%APPDATA%\jan.ai.app\`. Created only when absent.
-Both are residue or reads. The one Windows escape that was destructive —
+These are known desktop-suite residue or reads, not a full isolation guarantee.
+Windows CLI/global-config callers and explicit saves are not covered; this
+harness does not fix their known-folder escapes. The one Windows escape that was destructive —
deep-link registration, which rewrites the `HKCU` `jan://` handler to point at
whichever binary is running — is compiled out under the `e2e` feature instead of
being documented, since no environment variable reaches the registry.
@@ -273,12 +316,13 @@ Two things that look like they'd work but don't:
`JAN_DATA_ROOT` above: it names the data folder itself rather than the OS root
it sits under, and only `resolve_jan_data_folder()` reads it, which is the CLI
path. The desktop build ignores it.
-- `CI=e2e` short-circuits `get_app_configurations()` to a hardcoded `"./data"`,
+- `CI=e2e` (now rejected by the launch guard) short-circuits `get_app_configurations()` to a hardcoded `"./data"`,
which would skip the config resolution these tests exist to cover.
-Because the profile is always fresh, **every run is a first launch** — no
+With the default generated fresh profile, **every run is a first launch** — no
providers are configured, so `/` renders `SetupScreen`. The suite asserts that
-rather than working around it.
+rather than working around it. Reusing an inherited profile can retain providers
+and other state, so it may not satisfy these first-launch assertions.
A first launch used to **download**: Jan fetches its embedding model
`sentence-transformer-mini` (~45MB) on a profile it has not bootstrapped before,
diff --git a/e2e/isolation.ts b/e2e/isolation.ts
index 27ed3c31e..c899e5534 100644
--- a/e2e/isolation.ts
+++ b/e2e/isolation.ts
@@ -1,7 +1,9 @@
import { join } from 'node:path'
/**
- * Environment that confines the app's on-disk state to `home`.
+ * Environment redirects for the desktop e2e profile, NOT a sandbox.
+ * The launch guard must validate inherited overrides before this is merged with
+ * process.env. In particular Unix JAN_DATA_ROOT must be unset or empty.
*
* Its own module, with no side effects, so specs can assert on it without
* re-evaluating wdio.conf.ts (which creates the temp profile at import time).
@@ -93,6 +95,7 @@ import { join } from 'node:path'
* reads: the write at global_config.rs:469 is an explicit save no spec
* triggers, and user_subagents_dir's is gated behind prompt_subagent_create,
* which no spec reaches. So this is a read leak, not a destructive one.
+ * CLI callers/writes are not covered by this desktop smoke-suite guarantee.
* Strictly weaker than the other two platforms, and an accepted gap rather
* than an oversight.
*
diff --git a/e2e/launch-guard.ts b/e2e/launch-guard.ts
new file mode 100644
index 000000000..a75364cbf
--- /dev/null
+++ b/e2e/launch-guard.ts
@@ -0,0 +1,163 @@
+import { lstatSync, readFileSync, realpathSync } from 'node:fs'
+import { homedir, tmpdir, userInfo } from 'node:os'
+import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
+
+export interface LaunchContext {
+ env: NodeJS.ProcessEnv
+ platform: NodeJS.Platform
+ // Explicit homes make unit tests independent of the developer's filesystem.
+ realHomes: string[]
+ tempRoot: string
+}
+
+export function launchContext(accountHome: () => string = () => userInfo().homedir): LaunchContext {
+ let realAccountHome: string
+ try {
+ realAccountHome = accountHome()
+ } catch (error) {
+ // Fail closed: HOME alone may have been redirected and is not evidence of
+ // the account's real home (e.g. an arbitrary container UID without passwd).
+ throw new Error('Cannot validate e2e isolation: unable to resolve the account home via os.userInfo()', { cause: error })
+ }
+ return {
+ env: process.env,
+ platform: process.platform,
+ // HOME may itself have been overridden; protect the account home as well.
+ realHomes: [realAccountHome, homedir()],
+ tempRoot: tmpdir(),
+ }
+}
+
+/** Read-only: resolve symlinks in the longest existing prefix, even for a new target. */
+export function canonicalPath(target: string): string {
+ let prefix = resolve(target)
+ const tail: string[] = []
+ for (;;) {
+ try {
+ return join(realpathSync(prefix), ...tail)
+ } catch (error) {
+ // Broken links and permission failures must not silently become safe paths.
+ // realpath reports ENOENT for dangling links too; lstat below distinguishes them.
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
+ if (isSymlink(prefix)) throw new Error(`Unsafe dangling symlink: ${prefix}`)
+ const parent = dirname(prefix)
+ if (parent === prefix) throw error
+ tail.unshift(basename(prefix))
+ prefix = parent
+ }
+ }
+}
+
+function isSymlink(path: string): boolean {
+ try {
+ return lstatSync(path).isSymbolicLink()
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
+ return false
+ }
+}
+
+/** Includes equality. Unlike a string prefix, /profile-other is not in /profile. */
+export function containsPath(parent: string, child: string): boolean {
+ const delta = relative(parent, child)
+ return delta === '' || (!isAbsolute(delta) && delta !== '..' && !delta.startsWith(`..${sep}`))
+}
+
+/** Must run even before mkdtemp: these overrides bypass the native desktop lookup. */
+export function assertSafeLaunchEnvironment({ env, platform }: LaunchContext): void {
+ if (env.APP_NAME !== undefined && env.APP_NAME !== 'Jan') {
+ throw new Error('Unset APP_NAME (or use Jan) for e2e: it redirects Jan paths')
+ }
+ if (env.CI === 'e2e') {
+ throw new Error('Unsafe CI=e2e: bypasses native Jan configuration with ./data')
+ }
+ if (env.JAN_DATA_FOLDER) {
+ throw new Error('Unset JAN_DATA_FOLDER for e2e: it bypasses the test profile')
+ }
+ if (platform !== 'win32' && env.JAN_DATA_ROOT) {
+ throw new Error('Unset JAN_DATA_ROOT for e2e on Unix: it overrides native HOME/XDG resolution')
+ }
+}
+
+/** No writes, environment mutations, or cleanup listeners. Call before all seeding. */
+export function assertSafeE2eHome(home: string, context: LaunchContext): string {
+ assertSafeLaunchEnvironment(context)
+ const { env, realHomes } = context
+ const candidate = canonicalPath(home)
+ const tempRoot = canonicalPath(context.tempRoot)
+ if (candidate === tempRoot || !containsPath(tempRoot, candidate)) {
+ throw new Error(`Unsafe JAN_E2E_HOME ${home}: must be strictly inside temp root ${tempRoot}`)
+ }
+ const protectedPaths: string[] = []
+ const bundleIds = ['jan.ai.app', 'jan-nightly.ai.app', 'jan-beta.ai.app']
+ const addRoot = (root: string) => {
+ for (const name of ['Jan', ...bundleIds]) protectedPaths.push(join(root, name))
+ }
+ for (const realHome of realHomes) {
+ const canonicalHome = canonicalPath(realHome)
+ if (candidate === canonicalHome) throw new Error(`Unsafe JAN_E2E_HOME: real home ${home}`)
+ protectedPaths.push(join(realHome, '.jan'))
+ for (const root of [
+ '.local/share', '.local/state', '.config', '.cache',
+ 'Library/Application Support', 'Library/Caches', 'Library/Logs',
+ 'AppData/Roaming', 'AppData/Local',
+ ]) addRoot(join(realHome, root))
+ }
+ for (const key of [
+ 'XDG_DATA_HOME', 'XDG_CONFIG_HOME', 'XDG_STATE_HOME', 'XDG_CACHE_HOME',
+ 'APPDATA', 'LOCALAPPDATA', 'JAN_DATA_ROOT',
+ ]) {
+ if (env[key] && isAbsolute(env[key]!)) addRoot(env[key]!)
+ }
+ for (const path of protectedPaths) {
+ const protectedPath = canonicalPath(path)
+ if (containsPath(candidate, protectedPath) || containsPath(protectedPath, candidate)) {
+ throw new Error(`Unsafe JAN_E2E_HOME ${home}: overlaps real Jan path ${path}`)
+ }
+ }
+
+ // Existing subdirectories (or the settings file itself) may be symlinks too.
+ // Check all redirected roots and seed destinations before mkdir/writeFile.
+ for (const suffix of [
+ 'tmp', '.jan', '.local/share', '.local/state', '.config', '.cache',
+ 'Library/Application Support', 'Library/Caches', 'Library/Logs',
+ 'AppData/Roaming', 'AppData/Local',
+ '.local/share/Jan/data/settings.json',
+ 'Library/Application Support/Jan/data/settings.json',
+ 'AppData/Roaming/Jan/data/settings.json',
+ ]) {
+ if (!containsPath(candidate, canonicalPath(join(candidate, suffix)))) {
+ throw new Error(`Unsafe JAN_E2E_HOME ${home}: ${suffix} escapes profile`)
+ }
+ }
+ const dataRoot = context.platform === 'win32'
+ ? 'AppData/Roaming/Jan'
+ : context.platform === 'darwin' ? 'Library/Application Support/Jan' : '.local/share/Jan'
+ // Rust commands.rs checks canonical Jan/settings.json first; only if absent
+ // does it migrate the first file from bundle-id settings, then (Linux only)
+ // .config/Jan/settings.json. Migration copies AND removes its source. Validate
+ // every candidate, even those shadowed by an existing/higher-priority file,
+ // rather than depending on files remaining unchanged until the app starts.
+ // The Rust constant is currently jan.ai.app; include known channel IDs too
+ // conservatively, although a build may never consult those candidates.
+ const configFiles = [
+ join(candidate, dataRoot, 'settings.json'),
+ ...bundleIds.map(id => join(candidate, dirname(dataRoot), id, 'settings.json')),
+ ...(context.platform === 'linux' ? [join(candidate, '.config/Jan/settings.json')] : []),
+ ]
+ for (const configFile of configFiles) {
+ if (!containsPath(candidate, canonicalPath(configFile))) {
+ throw new Error(`Unsafe settings path: ${configFile}`)
+ }
+ try {
+ const config = JSON.parse(readFileSync(configFile, 'utf8'))
+ if (config.data_folder !== undefined && (
+ typeof config.data_folder !== 'string' || !isAbsolute(config.data_folder) ||
+ !containsPath(candidate, canonicalPath(config.data_folder))
+ )) throw new Error(`Unsafe data_folder in ${configFile}`)
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
+ }
+ }
+ return candidate
+}
diff --git a/e2e/package.json b/e2e/package.json
index 1e1867591..e7ccc3539 100644
--- a/e2e/package.json
+++ b/e2e/package.json
@@ -5,6 +5,7 @@
"type": "module",
"scripts": {
"test": "wdio run ./wdio.conf.ts",
+ "test:unit": "tsx --test tests/*.test.ts",
"typecheck": "tsc --noEmit"
},
"devDependencies": {
diff --git a/e2e/tests/launch-guard.test.ts b/e2e/tests/launch-guard.test.ts
new file mode 100644
index 000000000..153579a06
--- /dev/null
+++ b/e2e/tests/launch-guard.test.ts
@@ -0,0 +1,204 @@
+import assert from 'node:assert/strict'
+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { test } from 'node:test'
+import { assertSafeE2eHome, assertSafeLaunchEnvironment, canonicalPath, launchContext, type LaunchContext } from '../launch-guard.js'
+import { isolationEnv } from '../isolation.js'
+
+test('account lookup failure reports the isolation requirement and preserves its cause', () => {
+ const cause = new Error('no passwd entry')
+ assert.throws(() => launchContext(() => { throw cause }), (error: unknown) => {
+ assert.ok(error instanceof Error)
+ assert.match(error.message, /Cannot validate e2e isolation.*account home/)
+ assert.equal(error.cause, cause)
+ return true
+ })
+})
+
+function fixture(t: { after: (fn: () => void) => void }) {
+ const root = canonicalPath(mkdtempSync(join(tmpdir(), 'jan-guard-test-')))
+ t.after(() => rmSync(root, { recursive: true, force: true }))
+ const realHome = join(root, 'user')
+ mkdirSync(realHome)
+ const context: LaunchContext = { env: {}, platform: process.platform, realHomes: [realHome], tempRoot: root }
+ return { root, realHome, context }
+}
+
+test('rejects real home and Jan ancestors/descendants without writes', (t) => {
+ const { root, realHome, context } = fixture(t)
+ const jan = join(realHome, '.local/share/Jan')
+ mkdirSync(jan, { recursive: true })
+ const sentinel = join(jan, 'settings.json')
+ writeFileSync(sentinel, 'untouched')
+ const before = readdirSync(root, { recursive: true })
+ for (const home of [realHome, root, join(realHome, '.local'), jan, join(jan, 'new/profile'), join(realHome, '.jan/new')]) {
+ assert.throws(() => assertSafeE2eHome(home, context), /Unsafe/)
+ }
+ assert.deepEqual(readdirSync(root, { recursive: true }), before)
+ assert.equal(readFileSync(sentinel, 'utf8'), 'untouched')
+})
+
+test('accepts CI temp profile, mkdtemp, and prefix siblings, without creating targets', (t) => {
+ const { root, realHome, context } = fixture(t)
+ for (const home of [join(root, 'jan-e2e-home'), join(realHome, '.local/share/Jan-other')]) {
+ const before = readdirSync(root, { recursive: true })
+ assert.equal(assertSafeE2eHome(home, context), canonicalPath(home))
+ assert.deepEqual(readdirSync(root, { recursive: true }), before)
+ }
+ const generated = mkdtempSync(join(root, 'jan-e2e-'))
+ assert.equal(assertSafeE2eHome(generated, context), generated)
+ assert.throws(() => assertSafeE2eHome(join(root, '..', 'outside'), context), /temp root/)
+})
+
+test('protects inherited custom XDG and Windows app-data locations', (t) => {
+ const { root, context } = fixture(t)
+ for (const key of ['XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_STATE_HOME', 'XDG_CACHE_HOME', 'APPDATA', 'LOCALAPPDATA']) {
+ const base = join(root, `custom-${key}`)
+ const overridden = { ...context, env: { [key]: base } }
+ assert.throws(() => assertSafeE2eHome(join(base, 'Jan/new'), overridden), /overlaps/)
+ assert.throws(() => assertSafeE2eHome(base, overridden), /overlaps/)
+ assertSafeE2eHome(`${base}-sibling`, overridden)
+ }
+})
+
+test('environment bypasses fail before any profile creation', (t) => {
+ const { root, context } = fixture(t)
+ const before = readdirSync(root, { recursive: true })
+ for (const platform of ['linux', 'darwin', 'win32'] as const) {
+ for (const env of [{ CI: 'e2e' }, { JAN_DATA_FOLDER: join(root, 'outside') }, { APP_NAME: '../elsewhere' }, { APP_NAME: '' }]) {
+ assert.throws(() => assertSafeLaunchEnvironment({ ...context, platform, env }))
+ }
+ for (const value of ['', undefined]) {
+ assertSafeLaunchEnvironment({ ...context, platform, env: { JAN_DATA_ROOT: value, CI: 'true' } })
+ }
+ }
+ for (const platform of ['linux', 'darwin'] as const) {
+ for (const value of ['relative', ' ', join(root, 'override')]) {
+ assert.throws(() => assertSafeE2eHome(join(root, 'new'), { ...context, platform, env: { JAN_DATA_ROOT: value } }), /JAN_DATA_ROOT/)
+ }
+ }
+ assertSafeLaunchEnvironment({ ...context, platform: 'win32', env: { JAN_DATA_ROOT: 'inherited-is-overridden' } })
+ assert.deepEqual(readdirSync(root, { recursive: true }), before)
+})
+
+test('canonicalizes symlink prefixes and rejects redirected seed paths', (t) => {
+ const { root, realHome, context } = fixture(t)
+ const alias = join(root, 'alias')
+ try {
+ symlinkSync(realHome, alias, process.platform === 'win32' ? 'junction' : 'dir')
+ } catch (error) {
+ if (process.platform === 'win32' && ['EPERM', 'EACCES'].includes((error as NodeJS.ErrnoException).code!)) {
+ t.skip('Windows symlink privilege unavailable')
+ return
+ }
+ throw error
+ }
+ assert.throws(() => assertSafeE2eHome(alias, context), /Unsafe/)
+ assert.throws(() => assertSafeE2eHome(join(alias, '.jan/not-created'), context), /Unsafe/)
+ const profile = join(root, 'profile')
+ mkdirSync(profile)
+ symlinkSync(realHome, join(profile, '.local'), process.platform === 'win32' ? 'junction' : 'dir')
+ const before = readdirSync(root, { recursive: true })
+ assert.throws(() => assertSafeE2eHome(profile, context), /escapes/)
+ assert.deepEqual(readdirSync(root, { recursive: true }), before)
+})
+
+test('rejects existing desktop data_folder escape before changing settings', (t) => {
+ const { root, realHome, context } = fixture(t)
+ const profile = join(root, 'profile')
+ const dir = join(profile, '.local/share/Jan')
+ mkdirSync(dir, { recursive: true })
+ const file = join(dir, 'settings.json')
+ const unsafe = JSON.stringify({ data_folder: realHome })
+ writeFileSync(file, unsafe)
+ assert.throws(() => assertSafeE2eHome(profile, { ...context, platform: 'linux' }), /data_folder/)
+ assert.equal(readFileSync(file, 'utf8'), unsafe)
+ writeFileSync(file, JSON.stringify({ data_folder: join(profile, 'data') }))
+ assertSafeE2eHome(profile, { ...context, platform: 'linux' })
+})
+
+// Platform resolution is simulated, but all filesystem paths are native paths
+// under the fixture's temp root -- never a developer's real Jan directories.
+const migrationCases = (['linux', 'darwin', 'win32'] as const).flatMap(platform => {
+ const dataRoot = platform === 'win32' ? 'AppData/Roaming'
+ : platform === 'darwin' ? 'Library/Application Support' : '.local/share'
+ return [
+ ...['jan.ai.app', 'jan-nightly.ai.app', 'jan-beta.ai.app'].map(id => join(dataRoot, id, 'settings.json')),
+ ...(platform === 'linux' ? [join('.config/Jan/settings.json')] : []),
+ ].map(suffix => ({ platform, suffix, dataRoot }))
+})
+
+for (const { platform, suffix, dataRoot } of migrationCases) {
+ test(`validates migration data_folder read-only: ${platform}/${suffix}`, (t) => {
+ const { root, realHome, context } = fixture(t)
+ const profile = join(root, 'profile')
+ const file = join(profile, suffix)
+ mkdirSync(join(file, '..'), { recursive: true })
+ const launch = () => assertSafeE2eHome(profile, { ...context, platform })
+ for (const value of [realHome, 'relative', '', null, 123]) {
+ const unsafe = JSON.stringify({ data_folder: value })
+ writeFileSync(file, unsafe)
+ const before = readdirSync(root, { recursive: true })
+ assert.throws(launch, /data_folder/)
+ assert.deepEqual(readdirSync(root, { recursive: true }), before)
+ assert.equal(readFileSync(file, 'utf8'), unsafe)
+ }
+ // Deliberately conservative: canonical config shadows this source in Rust,
+ // but must not hide unsafe legacy settings from the launch guard.
+ const canonicalDir = join(profile, dataRoot, 'Jan')
+ mkdirSync(canonicalDir, { recursive: true })
+ writeFileSync(join(canonicalDir, 'settings.json'), '{}')
+ assert.throws(launch, /data_folder/)
+ for (const config of [{}, { data_folder: join(profile, 'data') }]) {
+ writeFileSync(file, JSON.stringify(config))
+ assert.equal(launch(), profile)
+ }
+ })
+
+ for (const kind of ['directory', 'file', 'dangling file', 'data_folder'] as const) {
+ test(`rejects migration ${kind} symlink: ${platform}/${suffix}`, (t) => {
+ const { root, realHome, context } = fixture(t)
+ const profile = join(root, 'profile')
+ const file = join(profile, suffix)
+ const outside = join(realHome, 'settings.json')
+ writeFileSync(outside, '{}')
+ mkdirSync(join(file, '..'), { recursive: true })
+ const link = kind === 'directory' ? join(file, '..')
+ : kind === 'data_folder' ? join(profile, 'data') : file
+ if (kind === 'directory') rmSync(link, { recursive: true })
+ const target = kind === 'directory' || kind === 'data_folder' ? realHome
+ : kind === 'dangling file' ? join(realHome, 'missing.json') : outside
+ try {
+ symlinkSync(target, link, kind === 'directory' || kind === 'data_folder'
+ ? process.platform === 'win32' ? 'junction' : 'dir' : 'file')
+ } catch (error) {
+ if (process.platform === 'win32' && ['EPERM', 'EACCES'].includes((error as NodeJS.ErrnoException).code!)) {
+ t.skip('Windows symlink privilege unavailable')
+ return
+ }
+ throw error
+ }
+ if (kind === 'data_folder') writeFileSync(file, JSON.stringify({ data_folder: link }))
+ const before = readdirSync(root, { recursive: true })
+ assert.throws(() => assertSafeE2eHome(profile, { ...context, platform }), /Unsafe/)
+ assert.deepEqual(readdirSync(root, { recursive: true }), before)
+ assert.equal(readFileSync(outside, 'utf8'), '{}')
+ })
+ }
+}
+
+test('isolation env overrides inherited path variables; Unix retains native resolution', (t) => {
+ const { root } = fixture(t)
+ const home = join(root, 'profile')
+ const overrides = isolationEnv(home)
+ const merged = { HOME: 'real-home', TMPDIR: 'real-temp', XDG_CONFIG_HOME: 'real-config', JAN_DATA_ROOT: '', ...overrides }
+ assert.equal(merged.HOME, home)
+ if (process.platform === 'win32') {
+ assert.equal(merged.JAN_DATA_ROOT, join(home, 'AppData/Roaming'))
+ } else {
+ assert.equal(merged.JAN_DATA_ROOT, '')
+ assert.equal(merged.TMPDIR, join(home, 'tmp'))
+ if (process.platform === 'linux') assert.equal(merged.XDG_CONFIG_HOME, join(home, '.config'))
+ }
+})
diff --git a/e2e/wdio.conf.ts b/e2e/wdio.conf.ts
index 21eb75384..7323e517c 100644
--- a/e2e/wdio.conf.ts
+++ b/e2e/wdio.conf.ts
@@ -14,6 +14,7 @@ import type { TauriCapabilities, TauriServiceOptions } from '@wdio/tauri-service
import { SevereServiceError } from 'webdriverio'
import { janUserDataDir } from './helpers/paths.js'
import { isolationEnv } from './isolation.js'
+import { assertSafeE2eHome, assertSafeLaunchEnvironment, canonicalPath, containsPath, launchContext } from './launch-guard.js'
// The app resolves its data folder through `core::app::paths::data_dir()`, and
// isolation is only sound where that call can be redirected by environment:
@@ -70,14 +71,17 @@ if (!existsSync(appBinary)) {
// `ownsTestHome` is load-bearing for safety, not just tidiness: cleanup deletes
// recursively, so it must only ever delete a directory this process created. A
// JAN_E2E_HOME inherited from the environment (a stray export, a CI variable)
-// is used but never removed.
+// is validated before any writes and never removed.
+const context = launchContext()
+assertSafeLaunchEnvironment(context)
const inheritedHome = process.env.JAN_E2E_HOME
const ownsTestHome = !inheritedHome
-// resolve() because `dirs` silently ignores a relative XDG value and falls back
-// to its $HOME-relative default -- which, with a relative HOME, is also relative.
-const testHome = inheritedHome
- ? resolve(inheritedHome)
- : mkdtempSync(join(realpathSync(tmpdir()), 'jan-e2e-'))
+// assertSafeE2eHome canonicalizes relative paths before they become HOME/XDG
+// values: `dirs` ignores relative XDG values and falls back to HOME defaults.
+const testHome = assertSafeE2eHome(
+ inheritedHome || mkdtempSync(join(realpathSync(tmpdir()), 'jan-e2e-')),
+ context
+)
process.env.JAN_E2E_HOME = testHome
if (ownsTestHome) {
@@ -102,7 +106,9 @@ if (ownsTestHome) {
return
}
// Belt and braces: never recurse outside the temp root.
- if (!testHome.startsWith(realpathSync(tmpdir()))) return
+ const currentHome = canonicalPath(testHome)
+ const tempRoot = canonicalPath(context.tempRoot)
+ if (currentHome !== testHome || currentHome === tempRoot || !containsPath(tempRoot, currentHome)) return
rmSync(testHome, {
recursive: true,
force: true,
@@ -172,7 +178,8 @@ if (process.platform === 'win32') {
// variable, someone reusing a profile -- quietly take the download and the
// toast back, with nothing in the log saying so, which is precisely the
// nondeterminism this block exists to remove. Writing one key into a profile
-// we did not create is acceptable: it is the same key the product writes
+// we did not create is limited to a validated disposable temp profile; it is
+// the same key the product writes
// itself after a successful bootstrap, it only adds to the file, and a caller
// who wants the real download has the env var above.
//