Skip to content

Commit 0ebff2e

Browse files
authored
fix(cli): keep embedded source resources and catalog --dir inside the caller's working directory (#10606)
* fix(cli): keep embedded source resources and catalog --dir inside the caller's working directory An embedded run (Mothership's sim_cli) resolved a relative --dir against the Sim server's cwd and walked every directory up to /, each level a sandbox file read through the host's reader. Resolve --dir against the embed context's workingDirectory and stop the walk there; a --dir outside it is read alone. * fix(cli): bound embedded source workspace lookups to the caller's working directory Pass the read bound into the workflows/<key> parent lookup so a workspace directory outside it is never read, read an outside --dir alone, and refuse a relative caller working directory before reading anything.
1 parent d07e84f commit 0ebff2e

3 files changed

Lines changed: 184 additions & 14 deletions

File tree

‎packages/sim-cli/src/commands/protocol/source-dir/dir-kind.ts‎

Lines changed: 31 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
* workspace directory, and which workspace a command on it acts on.
44
*/
55

6-
import { basename, dirname, resolve } from 'node:path'
6+
import { basename, dirname, resolve, sep } from 'node:path'
77
import { toRecord } from '@sim/utils/object'
88
import { SOURCE_BASE_FILE, SOURCE_ENTRY_FILE } from '@sim/workflow-code/limits'
99
import { KIND_DIRS } from '@sim/workspace-code'
@@ -130,14 +130,14 @@ export interface NamedWorkspace {
130130
* workspace directory it is a workflow folder of, else the one its starter's types were written
131131
* for (`null` when none). The one definition of the workspace a directory names, for a source
132132
* command's `--dir` ({@link recordedWorkspace}) and the directory any command runs in
133-
* ({@link enclosingWorkspace}).
133+
* ({@link enclosingWorkspace}). Given `within`, nothing outside it is read.
134134
*/
135-
async function namedWorkspace(dir: string): Promise<NamedWorkspace | null> {
135+
async function namedWorkspace(dir: string, within?: string): Promise<NamedWorkspace | null> {
136136
const base = toRecord(await readSourceJson(dir, SOURCE_BASE_FILE))
137137
if (typeof base.workspaceId === 'string') {
138138
return { workspaceId: base.workspaceId, dir, starter: false }
139139
}
140-
const folder = await workspaceFolderOf(dir)
140+
const folder = await workspaceFolderOf(dir, within)
141141
if (folder) return { workspaceId: folder.workspaceId, dir: folder.root, starter: false }
142142
const starter = await readStarterWorkspace(dir)
143143
return starter === null ? null : { workspaceId: starter, dir, starter: true }
@@ -160,18 +160,31 @@ export async function recordedWorkspace(
160160
/**
161161
* The workspace the nearest directory at or above `cwd` names ({@link namedWorkspace}), which a
162162
* command run in `cwd` acts on unless `--workspace` or `SIM_WORKSPACE` names one; `null` when none
163-
* up to the root names one.
163+
* up to the root names one. Given `top`, nothing outside it is read, and a `cwd` outside it is
164+
* read alone: an embedded run's every read is a round trip to its caller's machine, where nothing
165+
* above the caller's working directory is theirs.
164166
*/
165-
export async function enclosingWorkspace(cwd: string): Promise<NamedWorkspace | null> {
166-
for (let dir = resolve(cwd); ; dir = dirname(dir)) {
167+
export async function enclosingWorkspace(
168+
cwd: string,
169+
top?: string
170+
): Promise<NamedWorkspace | null> {
171+
const start = resolve(cwd)
172+
const bound = top === undefined ? undefined : resolve(top)
173+
const ceiling = bound === undefined || isWithin(start, bound) ? bound : start
174+
for (let dir = start; ; dir = dirname(dir)) {
167175
// One whose records cannot be read (a symbolic link, no permission) names none: a directory
168176
// above the one a command runs in, such as a linked `~/.sim`, must not stop the command.
169-
const named = await namedWorkspace(dir).catch(() => null)
177+
const named = await namedWorkspace(dir, ceiling).catch(() => null)
170178
if (named) return named
171-
if (dirname(dir) === dir) return null
179+
if (dir === ceiling || dirname(dir) === dir) return null
172180
}
173181
}
174182

183+
/** Whether `path` is `dir` or inside it (both absolute). */
184+
function isWithin(path: string, dir: string): boolean {
185+
return path === dir || path.startsWith(dir.endsWith(sep) ? dir : `${dir}${sep}`)
186+
}
187+
175188
/**
176189
* A `workflows/<key>` folder of a workspace directory: `root` holds a workspace `.sim/base.json`.
177190
* The workspace's `.sim/written.json` and base are the folder's records too, so a single-workflow
@@ -184,11 +197,18 @@ export interface WorkspaceFolder {
184197
key: string
185198
}
186199

187-
/** The workspace directory `dir` is a workflow folder of, or `null`. */
188-
export async function workspaceFolderOf(dir: string): Promise<WorkspaceFolder | null> {
200+
/**
201+
* The workspace directory `dir` is a workflow folder of, or `null`. Given `within`, a workspace
202+
* directory outside it is never read and names none.
203+
*/
204+
export async function workspaceFolderOf(
205+
dir: string,
206+
within?: string
207+
): Promise<WorkspaceFolder | null> {
189208
const folder = resolve(dir)
190209
if (basename(dirname(folder)) !== KIND_DIRS.workflow) return null
191210
const root = dirname(dirname(folder))
211+
if (within !== undefined && !isWithin(root, resolve(within))) return null
192212
const base = toRecord(await readSourceJson(root, SOURCE_BASE_FILE))
193213
if (typeof base.workspaceId !== 'string' || base.workflowId !== undefined) return null
194214
return { root, workspaceId: base.workspaceId, key: basename(folder) }
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
import { jsonResponse } from '@sim/testing/helpers/http'
2+
import { describe, expect, it } from 'vitest'
3+
import { runEmbeddedCli } from '../../embed'
4+
5+
const WORKSPACE_ID = 'a2e3ab27-2f9d-4b8a-a2f2-3c47a1b0c9d1'
6+
const OTHER_WORKSPACE_ID = 'b7c1d2e3-4f5a-4b6c-8d7e-9f0a1b2c3d4e'
7+
const WORKFLOW_ID = 'c3d4e5f6-a7b8-4c9d-8e0f-1a2b3c4d5e6f'
8+
const HOME = '/home/user'
9+
10+
/**
11+
* Runs `argv` embedded with the caller's machine at `workingDirectory` holding `files`, recording every path
12+
* the CLI asks that machine for and every URL it calls.
13+
*/
14+
async function embedded(
15+
argv: string[],
16+
files: Record<string, unknown> = {},
17+
workingDirectory = HOME
18+
) {
19+
const reads: string[] = []
20+
const urls: URL[] = []
21+
const result = await runEmbeddedCli(
22+
['--output', 'json', ...argv],
23+
{
24+
endpoint: 'https://sim.internal.test',
25+
apiKey: 'sk-embedded-test',
26+
workspaceId: WORKSPACE_ID,
27+
transport: async (input) => {
28+
urls.push(new URL(String(input)))
29+
return jsonResponse({ data: {} })
30+
},
31+
},
32+
{
33+
workingDirectory,
34+
readFile: async (path) => {
35+
reads.push(path)
36+
if (path in files) return JSON.stringify(files[path])
37+
throw new Error('missing')
38+
},
39+
}
40+
)
41+
return { result, reads, urls }
42+
}
43+
44+
describe('embedded workflows source resources|catalog --dir', () => {
45+
it.each(['resources', 'catalog'])(
46+
'%s reads nothing outside the caller working directory',
47+
async (command) => {
48+
const { result, reads } = await embedded(['workflows', 'source', command])
49+
50+
expect(result.exitCode).toBe(0)
51+
expect(reads.length).toBeGreaterThan(0)
52+
for (const path of reads) expect(path.startsWith(`${HOME}/`)).toBe(true)
53+
}
54+
)
55+
56+
it('resolves a relative --dir against the caller working directory, reading its workflow', async () => {
57+
const { result, reads, urls } = await embedded(
58+
['workflows', 'source', 'catalog', '--dir', 'wf'],
59+
{
60+
[`${HOME}/wf/.sim/base.json`]: { workspaceId: WORKSPACE_ID, workflowId: WORKFLOW_ID },
61+
}
62+
)
63+
64+
expect(result.exitCode).toBe(0)
65+
expect(reads).toContain(`${HOME}/wf/.sim/base.json`)
66+
for (const path of reads) expect(path.startsWith(`${HOME}/`)).toBe(true)
67+
expect(urls.map((url) => url.searchParams.get('workflowId'))).toEqual([WORKFLOW_ID])
68+
})
69+
70+
it('refuses a --dir read from another workspace than the one the caller acts in', async () => {
71+
const { result, urls } = await embedded(['workflows', 'source', 'resources', '--dir', 'wf'], {
72+
[`${HOME}/wf/.sim/base.json`]: { workspaceId: OTHER_WORKSPACE_ID },
73+
})
74+
75+
expect(result.exitCode).not.toBe(0)
76+
expect(result.stderr).toContain('SOURCE_OTHER_WORKSPACE')
77+
expect(urls).toEqual([])
78+
})
79+
80+
it('reads a --dir outside the working directory alone, never the directories above it', async () => {
81+
const { result, reads } = await embedded([
82+
'workflows',
83+
'source',
84+
'resources',
85+
'--dir',
86+
'/srv/wf',
87+
])
88+
89+
expect(result.exitCode).toBe(0)
90+
expect(reads.length).toBeGreaterThan(0)
91+
for (const path of reads) expect(path.startsWith('/srv/wf/')).toBe(true)
92+
})
93+
94+
it('never reads the workspace above an outside workflows/<key> --dir', async () => {
95+
const { result, reads } = await embedded(
96+
['workflows', 'source', 'resources', '--dir', '/srv/workflows/key'],
97+
{ '/srv/.sim/base.json': { workspaceId: OTHER_WORKSPACE_ID } }
98+
)
99+
100+
expect(result.exitCode).toBe(0)
101+
expect(reads.length).toBeGreaterThan(0)
102+
for (const path of reads) expect(path.startsWith('/srv/workflows/key/')).toBe(true)
103+
})
104+
105+
it('never reads the workspace above a working directory that is its workflows/<key> folder', async () => {
106+
const workingDirectory = `${HOME}/workflows/key`
107+
const { result, reads } = await embedded(
108+
['workflows', 'source', 'resources'],
109+
{ [`${HOME}/.sim/base.json`]: { workspaceId: OTHER_WORKSPACE_ID } },
110+
workingDirectory
111+
)
112+
113+
expect(result.exitCode).toBe(0)
114+
expect(reads.length).toBeGreaterThan(0)
115+
for (const path of reads) expect(path.startsWith(`${workingDirectory}/`)).toBe(true)
116+
})
117+
118+
it('reads the workspace of a workflows/<key> --dir inside the working directory', async () => {
119+
const { result, reads } = await embedded(
120+
['workflows', 'source', 'resources', '--dir', 'workflows/key'],
121+
{ [`${HOME}/.sim/base.json`]: { workspaceId: OTHER_WORKSPACE_ID } }
122+
)
123+
124+
expect(reads).toContain(`${HOME}/.sim/base.json`)
125+
expect(result.stderr).toContain('SOURCE_OTHER_WORKSPACE')
126+
})
127+
128+
it('refuses a relative caller working directory before reading anything', async () => {
129+
const { result, reads, urls } = await embedded(
130+
['workflows', 'source', 'resources', '--dir', 'wf'],
131+
{},
132+
'home/user'
133+
)
134+
135+
expect(result.exitCode).not.toBe(0)
136+
expect(result.stderr).toContain('The caller working directory must be absolute.')
137+
expect(reads).toEqual([])
138+
expect(urls).toEqual([])
139+
})
140+
})

‎packages/sim-cli/src/commands/protocol/workflow-source-reads.ts‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
1+
import { posix } from 'node:path'
12
import type { Command } from 'commander'
23
import { profileFrom, setWorkingDirectoryWorkspace } from '../../context'
4+
import { embedStore } from '../../embed-context'
5+
import { SimApiError } from '../../http/client'
36
import { heldAction } from '../../runtime/build'
47
import { callsOperations } from '../../runtime/called-operations'
58
import { absoluteDirOption, directoryWorkspace, enclosingWorkspace } from './source-dir'
@@ -29,11 +32,18 @@ function generatedLeafWithDir(
2932
* Makes `--dir` the directory the command acts in, as if run inside it: the workspace it (or a
3033
* directory above it) names is the one read, and none when it names none. A `--workspace` or
3134
* `SIM_WORKSPACE` naming another one than its record is refused, as the directory's other
32-
* commands refuse it ({@link directoryWorkspace}). Returns the directory.
35+
* commands refuse it ({@link directoryWorkspace}). An embedded run resolves it against its
36+
* caller's working directory, never the host's, and looks no higher. Returns the directory.
3337
*/
3438
async function actInDirectory(command: Command): Promise<string> {
35-
const dir = String(command.getOptionValue(DIR_FLAG))
36-
const named = await enclosingWorkspace(dir)
39+
const given = String(command.getOptionValue(DIR_FLAG))
40+
const embedded = embedStore.getStore()
41+
const top = embedded ? (embedded.workingDirectory ?? '/') : undefined
42+
if (top !== undefined && !posix.isAbsolute(top)) {
43+
throw new SimApiError('The caller working directory must be absolute.', 0)
44+
}
45+
const dir = top === undefined ? given : posix.resolve(top, given)
46+
const named = await enclosingWorkspace(dir, top)
3747
setWorkingDirectoryWorkspace(command, named)
3848
if (named && !named.starter) {
3949
directoryWorkspace(

0 commit comments

Comments
 (0)