diff --git a/packages/sim-cli/src/commands/protocol/source-dir/dir-kind.ts b/packages/sim-cli/src/commands/protocol/source-dir/dir-kind.ts index c87eee28848..d460fa0360e 100644 --- a/packages/sim-cli/src/commands/protocol/source-dir/dir-kind.ts +++ b/packages/sim-cli/src/commands/protocol/source-dir/dir-kind.ts @@ -3,7 +3,7 @@ * workspace directory, and which workspace a command on it acts on. */ -import { basename, dirname, resolve } from 'node:path' +import { basename, dirname, resolve, sep } from 'node:path' import { toRecord } from '@sim/utils/object' import { SOURCE_BASE_FILE, SOURCE_ENTRY_FILE } from '@sim/workflow-code/limits' import { KIND_DIRS } from '@sim/workspace-code' @@ -130,14 +130,14 @@ export interface NamedWorkspace { * workspace directory it is a workflow folder of, else the one its starter's types were written * for (`null` when none). The one definition of the workspace a directory names, for a source * command's `--dir` ({@link recordedWorkspace}) and the directory any command runs in - * ({@link enclosingWorkspace}). + * ({@link enclosingWorkspace}). Given `within`, nothing outside it is read. */ -async function namedWorkspace(dir: string): Promise { +async function namedWorkspace(dir: string, within?: string): Promise { const base = toRecord(await readSourceJson(dir, SOURCE_BASE_FILE)) if (typeof base.workspaceId === 'string') { return { workspaceId: base.workspaceId, dir, starter: false } } - const folder = await workspaceFolderOf(dir) + const folder = await workspaceFolderOf(dir, within) if (folder) return { workspaceId: folder.workspaceId, dir: folder.root, starter: false } const starter = await readStarterWorkspace(dir) return starter === null ? null : { workspaceId: starter, dir, starter: true } @@ -160,18 +160,31 @@ export async function recordedWorkspace( /** * The workspace the nearest directory at or above `cwd` names ({@link namedWorkspace}), which a * command run in `cwd` acts on unless `--workspace` or `SIM_WORKSPACE` names one; `null` when none - * up to the root names one. + * up to the root names one. Given `top`, nothing outside it is read, and a `cwd` outside it is + * read alone: an embedded run's every read is a round trip to its caller's machine, where nothing + * above the caller's working directory is theirs. */ -export async function enclosingWorkspace(cwd: string): Promise { - for (let dir = resolve(cwd); ; dir = dirname(dir)) { +export async function enclosingWorkspace( + cwd: string, + top?: string +): Promise { + const start = resolve(cwd) + const bound = top === undefined ? undefined : resolve(top) + const ceiling = bound === undefined || isWithin(start, bound) ? bound : start + for (let dir = start; ; dir = dirname(dir)) { // One whose records cannot be read (a symbolic link, no permission) names none: a directory // above the one a command runs in, such as a linked `~/.sim`, must not stop the command. - const named = await namedWorkspace(dir).catch(() => null) + const named = await namedWorkspace(dir, ceiling).catch(() => null) if (named) return named - if (dirname(dir) === dir) return null + if (dir === ceiling || dirname(dir) === dir) return null } } +/** Whether `path` is `dir` or inside it (both absolute). */ +function isWithin(path: string, dir: string): boolean { + return path === dir || path.startsWith(dir.endsWith(sep) ? dir : `${dir}${sep}`) +} + /** * A `workflows/` folder of a workspace directory: `root` holds a workspace `.sim/base.json`. * 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 { key: string } -/** The workspace directory `dir` is a workflow folder of, or `null`. */ -export async function workspaceFolderOf(dir: string): Promise { +/** + * The workspace directory `dir` is a workflow folder of, or `null`. Given `within`, a workspace + * directory outside it is never read and names none. + */ +export async function workspaceFolderOf( + dir: string, + within?: string +): Promise { const folder = resolve(dir) if (basename(dirname(folder)) !== KIND_DIRS.workflow) return null const root = dirname(dirname(folder)) + if (within !== undefined && !isWithin(root, resolve(within))) return null const base = toRecord(await readSourceJson(root, SOURCE_BASE_FILE)) if (typeof base.workspaceId !== 'string' || base.workflowId !== undefined) return null return { root, workspaceId: base.workspaceId, key: basename(folder) } diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-reads.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-reads.test.ts new file mode 100644 index 00000000000..676c79d1fea --- /dev/null +++ b/packages/sim-cli/src/commands/protocol/workflow-source-reads.test.ts @@ -0,0 +1,140 @@ +import { jsonResponse } from '@sim/testing/helpers/http' +import { describe, expect, it } from 'vitest' +import { runEmbeddedCli } from '../../embed' + +const WORKSPACE_ID = 'a2e3ab27-2f9d-4b8a-a2f2-3c47a1b0c9d1' +const OTHER_WORKSPACE_ID = 'b7c1d2e3-4f5a-4b6c-8d7e-9f0a1b2c3d4e' +const WORKFLOW_ID = 'c3d4e5f6-a7b8-4c9d-8e0f-1a2b3c4d5e6f' +const HOME = '/home/user' + +/** + * Runs `argv` embedded with the caller's machine at `workingDirectory` holding `files`, recording every path + * the CLI asks that machine for and every URL it calls. + */ +async function embedded( + argv: string[], + files: Record = {}, + workingDirectory = HOME +) { + const reads: string[] = [] + const urls: URL[] = [] + const result = await runEmbeddedCli( + ['--output', 'json', ...argv], + { + endpoint: 'https://sim.internal.test', + apiKey: 'sk-embedded-test', + workspaceId: WORKSPACE_ID, + transport: async (input) => { + urls.push(new URL(String(input))) + return jsonResponse({ data: {} }) + }, + }, + { + workingDirectory, + readFile: async (path) => { + reads.push(path) + if (path in files) return JSON.stringify(files[path]) + throw new Error('missing') + }, + } + ) + return { result, reads, urls } +} + +describe('embedded workflows source resources|catalog --dir', () => { + it.each(['resources', 'catalog'])( + '%s reads nothing outside the caller working directory', + async (command) => { + const { result, reads } = await embedded(['workflows', 'source', command]) + + expect(result.exitCode).toBe(0) + expect(reads.length).toBeGreaterThan(0) + for (const path of reads) expect(path.startsWith(`${HOME}/`)).toBe(true) + } + ) + + it('resolves a relative --dir against the caller working directory, reading its workflow', async () => { + const { result, reads, urls } = await embedded( + ['workflows', 'source', 'catalog', '--dir', 'wf'], + { + [`${HOME}/wf/.sim/base.json`]: { workspaceId: WORKSPACE_ID, workflowId: WORKFLOW_ID }, + } + ) + + expect(result.exitCode).toBe(0) + expect(reads).toContain(`${HOME}/wf/.sim/base.json`) + for (const path of reads) expect(path.startsWith(`${HOME}/`)).toBe(true) + expect(urls.map((url) => url.searchParams.get('workflowId'))).toEqual([WORKFLOW_ID]) + }) + + it('refuses a --dir read from another workspace than the one the caller acts in', async () => { + const { result, urls } = await embedded(['workflows', 'source', 'resources', '--dir', 'wf'], { + [`${HOME}/wf/.sim/base.json`]: { workspaceId: OTHER_WORKSPACE_ID }, + }) + + expect(result.exitCode).not.toBe(0) + expect(result.stderr).toContain('SOURCE_OTHER_WORKSPACE') + expect(urls).toEqual([]) + }) + + it('reads a --dir outside the working directory alone, never the directories above it', async () => { + const { result, reads } = await embedded([ + 'workflows', + 'source', + 'resources', + '--dir', + '/srv/wf', + ]) + + expect(result.exitCode).toBe(0) + expect(reads.length).toBeGreaterThan(0) + for (const path of reads) expect(path.startsWith('/srv/wf/')).toBe(true) + }) + + it('never reads the workspace above an outside workflows/ --dir', async () => { + const { result, reads } = await embedded( + ['workflows', 'source', 'resources', '--dir', '/srv/workflows/key'], + { '/srv/.sim/base.json': { workspaceId: OTHER_WORKSPACE_ID } } + ) + + expect(result.exitCode).toBe(0) + expect(reads.length).toBeGreaterThan(0) + for (const path of reads) expect(path.startsWith('/srv/workflows/key/')).toBe(true) + }) + + it('never reads the workspace above a working directory that is its workflows/ folder', async () => { + const workingDirectory = `${HOME}/workflows/key` + const { result, reads } = await embedded( + ['workflows', 'source', 'resources'], + { [`${HOME}/.sim/base.json`]: { workspaceId: OTHER_WORKSPACE_ID } }, + workingDirectory + ) + + expect(result.exitCode).toBe(0) + expect(reads.length).toBeGreaterThan(0) + for (const path of reads) expect(path.startsWith(`${workingDirectory}/`)).toBe(true) + }) + + it('reads the workspace of a workflows/ --dir inside the working directory', async () => { + const { result, reads } = await embedded( + ['workflows', 'source', 'resources', '--dir', 'workflows/key'], + { [`${HOME}/.sim/base.json`]: { workspaceId: OTHER_WORKSPACE_ID } } + ) + + expect(reads).toContain(`${HOME}/.sim/base.json`) + expect(result.stderr).toContain('SOURCE_OTHER_WORKSPACE') + }) + + it('refuses a relative caller working directory before reading anything', async () => { + const { result, reads, urls } = await embedded( + ['workflows', 'source', 'resources', '--dir', 'wf'], + {}, + 'home/user' + ) + + expect(result.exitCode).not.toBe(0) + expect(result.stderr).toContain('The caller working directory must be absolute.') + expect(reads).toEqual([]) + expect(urls).toEqual([]) + }) +}) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-reads.ts b/packages/sim-cli/src/commands/protocol/workflow-source-reads.ts index ba4c566c40d..7e9e55bf954 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-reads.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-reads.ts @@ -1,5 +1,8 @@ +import { posix } from 'node:path' import type { Command } from 'commander' import { profileFrom, setWorkingDirectoryWorkspace } from '../../context' +import { embedStore } from '../../embed-context' +import { SimApiError } from '../../http/client' import { heldAction } from '../../runtime/build' import { callsOperations } from '../../runtime/called-operations' import { absoluteDirOption, directoryWorkspace, enclosingWorkspace } from './source-dir' @@ -29,11 +32,18 @@ function generatedLeafWithDir( * Makes `--dir` the directory the command acts in, as if run inside it: the workspace it (or a * directory above it) names is the one read, and none when it names none. A `--workspace` or * `SIM_WORKSPACE` naming another one than its record is refused, as the directory's other - * commands refuse it ({@link directoryWorkspace}). Returns the directory. + * commands refuse it ({@link directoryWorkspace}). An embedded run resolves it against its + * caller's working directory, never the host's, and looks no higher. Returns the directory. */ async function actInDirectory(command: Command): Promise { - const dir = String(command.getOptionValue(DIR_FLAG)) - const named = await enclosingWorkspace(dir) + const given = String(command.getOptionValue(DIR_FLAG)) + const embedded = embedStore.getStore() + const top = embedded ? (embedded.workingDirectory ?? '/') : undefined + if (top !== undefined && !posix.isAbsolute(top)) { + throw new SimApiError('The caller working directory must be absolute.', 0) + } + const dir = top === undefined ? given : posix.resolve(top, given) + const named = await enclosingWorkspace(dir, top) setWorkingDirectoryWorkspace(command, named) if (named && !named.starter) { directoryWorkspace(