Skip to content

Commit 04d4114

Browse files
fix(cli): os datasource introspect --out jail judges the realpath, not the spelling (#33994)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbTGhxJSYAmQXU7efVdNqrpw)_ Fixes #33841 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:`os datasource introspect --out` 写文件前按解析符号链接后的真实位置判断是否在当前目录内;`--out` 本身是符号链接也拒绝。 - 为什么改:原检查只看路径字面,项目里一个指向外部目录的符号链接就能让服务端生成的草稿写到项目外,且退出码 0。 - 风险与回滚:只动这一个命令的 `--out` 分支;拒绝文案与退出码 2 不变;回滚即 revert 本 PR。 - 先看:`packages/cli/src/commands/datasource/introspect.ts` 的 `landsInside`(上溯到最近的已存在目录再 realpath),然后是同目录新测试。 - 两分钟验证:`pnpm --filter @objectstack/cli exec vitest run --project unit src/commands/datasource/introspect-out-jail.test.ts`,预期 8 个用例全绿。 - 需要你做的:无,席位落地。 ## What changes `packages/cli/src/commands/datasource/introspect.ts`: after the existing lexical check (absolute path, `../` escape; both unchanged), `--out` is judged again on the location the write would really land on: 1. an `--out` that is an existing symlink is refused (`writeFile` follows it, even when it dangles); 2. the realpath of the nearest existing ancestor directory of the target must sit under the realpath of the current directory. Both refusals reuse the existing message (`--out must be a relative path within the current directory: OUT`) and its exit code 2. A plain relative in-tree path writes as before, also from a current directory reached through a symlink. No directory is created: a missing intermediate directory still fails in `writeFile` with `ENOENT`, as before. New test beside it, `introspect-out-jail.test.ts` (unit tier: no spawn, no driver), each case in its own temp tree removed in `afterEach`: - in-tree directory symlink to an outside dir: refused, exit 2, outside dir stays empty; - target that is an existing (dangling) symlink: refused, exit 2, nothing written outside; - plain nested in-tree path: writes the server's source; - cwd reached through a symlink: still writes; - missing subdirectory: `ENOENT` as before, not the jail refusal, nothing created; - `../x.object.ts`, `objects/../../x.object.ts` and an absolute path: refused exactly as before. Changeset: `@objectstack/cli` patch. ## Tests <details><summary>Ablation 1: realpath of the ancestor replaced by the lexical path (on-disk proof, red quoted)</summary> ``` ablation-replace: anchor "const real = await realpath(dir);" x1 (before) ablation-replace: ok mutation landed: anchor 1 -> 0, blob 1337969 -> 579c69b33151 FAIL ... > refuses an in-tree directory symlink that points outside, and writes nothing there AssertionError: expected undefined to deeply equal { …(2) } FAIL ... > still writes when the cwd itself is reached through a symlink Tests 2 failed | 6 passed (8) ablation-replace: ok restored: blob == HEAD (1337969) and `git diff HEAD` is empty ``` </details> <details><summary>Ablation 2: the symlink-target leg removed</summary> ``` ablation-replace: ok mutation landed: anchor 1 -> 0, blob 1337969 -> 6665d1768957 FAIL ... > refuses a target that is itself an existing symlink, even a dangling one Tests 1 failed | 7 passed (8) ablation-replace: ok restored: blob == HEAD (1337969) and `git diff HEAD` is empty ``` </details> <details><summary>Suites on head 7229d62</summary> ``` pnpm --filter @objectstack/cli exec vitest run --project unit --maxWorkers=2 src/commands/datasource/ Test Files 2 passed (2) Tests 20 passed (20) (8 new + 12 in envelope-unwrap.test.ts; run on fff6074, before the main merge, which touched no datasource file) NODE_OPTIONS=--max-old-space-size=8192 pnpm --filter @objectstack/cli typecheck -> TYPECHECK-EXIT=0 pnpm --filter @objectstack/cli exec vitest run --project unit --maxWorkers=2 (whole unit tier) Test Files 2 failed | 421 passed (423) Tests 5981 passed | 29 skipped (6010) the two failures: test/published-subpath-console.pin.test.ts, test/published-subpath-hook-body.pin.test.ts, both "packages/cli is not built (./dist/index.js is absent)" (a prerequisite, the closure build excluded cli itself); after pnpm --filter @objectstack/cli build: Test Files 2 passed (2) Tests 29 passed (29) ``` The `integration` tier is left to CI: the diff touches no integration-tier file, no spawn entry and no driver boot path. </details> ## Acceptance notes - The check and the write are two steps, so a symlink swapped in between them is not caught (time-of-check to time-of-use). The card's threat is a symlink already present in the tree; closing the race would need an `O_NOFOLLOW` open on every path component, which is not what the card asked for. - The existing lexical prefix check still spells the separator as `/`, so on Windows it reads as refusing every `--out` (read from the code, not run). Unchanged here, noted only; the new check uses `path.sep`. - The pre-existing `envelope-unwrap.test.ts` also drives this command; these pins went into a new file as the claim's file surface names, not into that one. ## Verification <details><summary>Derived gate families (dispatch-gates --commands, head 7229d62)</summary> ``` Run reconciliation: 65 derived, 61 run, 1 NOT-MEASURED, 3 UNRUN. 61 run: exit 0 each (pnpm check:i18n-walk-parity first exited 3, CLI not built; exit 0 after the cli build). NOT MEASURED: pnpm check:i18n-coverage, exit 3: examples/app-showcase needs @objectstack/connector-slack built (example closure, unrelated to this diff); CI runs it. UNRUN, left to CI: pnpm check:type-check-debt (verify-lock gate, rebuilds spec dist), pnpm check:dual-build-cjs-loads, pnpm check:i18n. dispatch-gates --tier: no path-derived mandate; Clause-② no (narrows a CLI flag's accepted paths to what its own refusal already declared; no spec, schema or published export moves). eslint --no-inline-config on the two touched .ts files: exit 0. ``` </details> Session: `session_01QsR2jTEivi2wogPpeo3xd5` (https://claude.ai/code/session_01QsR2jTEivi2wogPpeo3xd5) 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent c3c0c30 commit 04d4114

3 files changed

Lines changed: 207 additions & 3 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/cli': patch
3+
---
4+
5+
fix(cli): `os datasource introspect --out` judges where the write really lands, so an in-tree symlink no longer lets the server-generated draft leave the current directory
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The `--out` check compared the spelled path with the current directory and then wrote through `writeFile`, which follows symlinks. A path such as `objects/lnk/x.object.ts`, with `objects/lnk` a symlink to a directory outside the project, passed the check and wrote the draft outside the tree with exit 0. The same held for an `--out` that was itself a symlink, even one pointing at a file that did not exist yet.
11+
12+
The command now also refuses an `--out` that is an existing symlink, and resolves symlinks in both the current directory and the nearest existing directory above the target, refusing when the second is not under the first. Both refusals print the message absolute and `../` paths already get (`--out must be a relative path within the current directory`) and exit 2. Plain relative paths inside the tree write as before, including from a current directory reached through a symlink. A missing intermediate directory is still not created; the write fails as it did.
Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* `os datasource introspect --out` keeps the server-generated draft inside the
5+
* current directory once symlinks are resolved.
6+
*
7+
* The jail used to be lexical only: `resolve(cwd, out)` prefix-checked against
8+
* `cwd`, then handed to `writeFile`, which follows symlinks. An in-tree
9+
* directory symlink (`objects/lnk` -> a directory outside the project) or a
10+
* target that is itself a symlink therefore let the draft land outside the
11+
* tree with exit 0. These pins hold the declared refusal for both shapes, and
12+
* keep the absolute / `../` refusals and the plain in-tree write unchanged.
13+
*
14+
* Every case runs in its own temp tree (a `project/` directory standing in for
15+
* the cwd, and an `outside/` sibling it must never write into), removed after.
16+
* `Config.load` is paid at module scope for the reason the sibling
17+
* `envelope-unwrap.test.ts` records in its header.
18+
*/
19+
20+
import { afterEach, describe, expect, it, vi } from 'vitest';
21+
import { Config } from '@oclif/core';
22+
import { sendOk } from '@objectstack/types';
23+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync } from 'node:fs';
24+
import { tmpdir } from 'node:os';
25+
import { dirname, join, resolve } from 'node:path';
26+
import { fileURLToPath } from 'node:url';
27+
import { serverBody } from '../../utils/__tests__/server-body.js';
28+
import DatasourceIntrospect from './introspect.js';
29+
30+
const HERE = dirname(fileURLToPath(import.meta.url));
31+
/** This package's own root — `packages/cli`, never outside it. */
32+
const CLI_ROOT = resolve(HERE, '../../..');
33+
34+
const config = await Config.load({ root: CLI_ROOT });
35+
36+
const DRAFT_SOURCE = '/* draft source, verbatim from the server */';
37+
const target = ['showcase_external', '--url', 'http://127.0.0.1:39999', '--token', 'tok', '--table', 'orders'];
38+
39+
let root: string | undefined;
40+
41+
afterEach(() => {
42+
vi.restoreAllMocks();
43+
vi.unstubAllGlobals();
44+
if (root) rmSync(root, { recursive: true, force: true });
45+
root = undefined;
46+
});
47+
48+
/** A fresh `project/` (the cwd) beside an `outside/` directory. */
49+
function tree(): { project: string; outside: string } {
50+
root = mkdtempSync(join(tmpdir(), 'os-introspect-jail-'));
51+
const project = join(root, 'project');
52+
const outside = join(root, 'outside');
53+
mkdirSync(join(project, 'objects'), { recursive: true });
54+
mkdirSync(outside);
55+
return { project, outside };
56+
}
57+
58+
/** Run the command with `cwd` as the current directory and a draft-serving server. */
59+
async function introspect(cwd: string, out: string) {
60+
vi.spyOn(process, 'cwd').mockReturnValue(cwd);
61+
const body = serverBody((res) =>
62+
sendOk(res, {
63+
draft: { name: 'orders', datasource: 'showcase_external', definition: {}, source: DRAFT_SOURCE },
64+
}),
65+
);
66+
vi.stubGlobal('fetch', async () => ({ status: 200, ok: true, json: async () => body }));
67+
68+
const logs: string[] = [];
69+
const cmd = new DatasourceIntrospect([...target, '--out', out], config);
70+
Object.assign(cmd, { log: (m?: string) => logs.push(String(m ?? '')) });
71+
try {
72+
await cmd.run();
73+
return { logs };
74+
} catch (err) {
75+
const exit = (err as { oclif?: { exit?: number } }).oclif?.exit;
76+
return { logs, failure: { message: (err as Error).message, exit } };
77+
}
78+
}
79+
80+
const refusal = (out: string) => `--out must be a relative path within the current directory: ${out}`;
81+
82+
describe('os datasource introspect --out — the jail holds after symlinks resolve', () => {
83+
it('refuses an in-tree directory symlink that points outside, and writes nothing there', async () => {
84+
const { project, outside } = tree();
85+
symlinkSync(outside, join(project, 'objects', 'lnk'));
86+
87+
const run = await introspect(project, 'objects/lnk/qa_sym.object.ts');
88+
89+
expect(run.failure).toEqual({ message: refusal('objects/lnk/qa_sym.object.ts'), exit: 2 });
90+
expect(readdirSync(outside)).toEqual([]);
91+
});
92+
93+
it('refuses a target that is itself an existing symlink, even a dangling one', async () => {
94+
const { project, outside } = tree();
95+
symlinkSync(join(outside, 'x.object.ts'), join(project, 'objects', 'x.object.ts'));
96+
97+
const run = await introspect(project, 'objects/x.object.ts');
98+
99+
expect(run.failure).toEqual({ message: refusal('objects/x.object.ts'), exit: 2 });
100+
expect(readdirSync(outside)).toEqual([]);
101+
});
102+
103+
it('still writes a plain nested in-tree path', async () => {
104+
const { project } = tree();
105+
106+
const run = await introspect(project, 'objects/wh_order.object.ts');
107+
108+
expect(run.failure).toBeUndefined();
109+
expect(run.logs).toContain('Wrote objects/wh_order.object.ts');
110+
expect(readFileSync(join(project, 'objects', 'wh_order.object.ts'), 'utf8')).toBe(DRAFT_SOURCE);
111+
});
112+
113+
it('still writes when the cwd itself is reached through a symlink', async () => {
114+
const { project } = tree();
115+
const alias = join(root!, 'alias');
116+
symlinkSync(project, alias);
117+
118+
const run = await introspect(alias, 'objects/wh_order.object.ts');
119+
120+
expect(run.failure).toBeUndefined();
121+
expect(readFileSync(join(project, 'objects', 'wh_order.object.ts'), 'utf8')).toBe(DRAFT_SOURCE);
122+
});
123+
124+
it('creates no missing directory, and does not report one as outside the tree', async () => {
125+
const { project } = tree();
126+
127+
const run = await introspect(project, 'objects/new_dir/wh_order.object.ts');
128+
129+
// No `mkdir`: the write fails exactly as it did before the jail resolved
130+
// symlinks, and the failure is not the jail's refusal.
131+
expect(run.failure?.message).toContain('ENOENT');
132+
expect(run.failure?.message).not.toContain('--out must be');
133+
expect(existsSync(join(project, 'objects', 'new_dir'))).toBe(false);
134+
});
135+
136+
it.each(['../x.object.ts', 'objects/../../x.object.ts'])('refuses the traversing path %s, unchanged', async (out) => {
137+
const { project, outside } = tree();
138+
139+
const run = await introspect(project, out);
140+
141+
expect(run.failure).toEqual({ message: refusal(out), exit: 2 });
142+
expect(existsSync(join(dirname(project), 'x.object.ts'))).toBe(false);
143+
expect(readdirSync(outside)).toEqual([]);
144+
});
145+
146+
it('refuses an absolute path, unchanged', async () => {
147+
const { project, outside } = tree();
148+
const out = join(outside, 'x.object.ts');
149+
150+
const run = await introspect(project, out);
151+
152+
expect(run.failure).toEqual({ message: refusal(out), exit: 2 });
153+
expect(readdirSync(outside)).toEqual([]);
154+
});
155+
});

‎packages/cli/src/commands/datasource/introspect.ts‎

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
import { Args, Command, Flags } from '@oclif/core';
44
import type { ObjectDraft } from '@objectstack/spec/contracts';
55
import { readEnvelopeFrom } from '../../utils/response-envelope.js';
6-
import { writeFile } from 'node:fs/promises';
7-
import { resolve, isAbsolute } from 'node:path';
6+
import { lstat, realpath, writeFile } from 'node:fs/promises';
7+
import { dirname, isAbsolute, resolve, sep } from 'node:path';
88

99
/** Resolve server URL + token from flags then env (mirrors createApiClient). */
1010
function resolveTarget(flags: { url?: string; token?: string }): { url: string; token?: string } {
@@ -13,6 +13,36 @@ function resolveTarget(flags: { url?: string; token?: string }): { url: string;
1313
return { url, token };
1414
}
1515

16+
/**
17+
* Whether a write to `target` really lands under `cwd` once symlinks are
18+
* resolved. A lexically in-tree path can still leave the tree through a
19+
* symlinked directory on the way (`objects/lnk/x.ts` with `objects/lnk` ->
20+
* `/elsewhere`), or through `target` itself being a symlink, which
21+
* `writeFile` follows even when it dangles. So: refuse an existing symlink
22+
* at `target`, then realpath both `cwd` and the nearest EXISTING ancestor
23+
* of `target` and require the second to sit under the first. A missing
24+
* intermediate directory is left to `writeFile`, which fails as it always has.
25+
*/
26+
async function landsInside(cwd: string, target: string): Promise<boolean> {
27+
try {
28+
if ((await lstat(target)).isSymbolicLink()) return false;
29+
} catch (err) {
30+
if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err;
31+
}
32+
const root = await realpath(cwd);
33+
let dir = dirname(target);
34+
for (;;) {
35+
try {
36+
const real = await realpath(dir);
37+
return real === root || real.startsWith(root + sep);
38+
} catch (err) {
39+
const parent = dirname(dir);
40+
if ((err as NodeJS.ErrnoException).code !== 'ENOENT' || parent === dir) throw err;
41+
dir = parent;
42+
}
43+
}
44+
}
45+
1646
/**
1747
* `os datasource introspect <name> --table <remote>` — generate an Object
1848
* draft (`*.object.ts`) from a remote table (ADR-0015).
@@ -73,8 +103,15 @@ export default class DatasourceIntrospect extends Command {
73103
// tree (defends against a malicious/compromised server supplying an
74104
// absolute or traversing `--out` via shell expansion).
75105
const target = resolve(process.cwd(), flags.out);
106+
const refusal = `--out must be a relative path within the current directory: ${flags.out}`;
76107
if (isAbsolute(flags.out) || !target.startsWith(process.cwd() + '/')) {
77-
this.error(`--out must be a relative path within the current directory: ${flags.out}`);
108+
this.error(refusal);
109+
return;
110+
}
111+
// The check above is lexical; `writeFile` follows symlinks. Re-judge
112+
// the location the write would really land on.
113+
if (!(await landsInside(process.cwd(), target))) {
114+
this.error(refusal);
78115
return;
79116
}
80117
await writeFile(target, draft.source, 'utf8');

0 commit comments

Comments
 (0)