审查 AI 生成的 Node.js 路径检查:目录包含、符号链接与九组反例
让 AI 写一个只能在指定目录下读写文件的 Node.js 函数,很容易得到一段看似合理的 startsWith 检查。真正需要审查的,是它判断了字符串,还是判断了应用想约束的目录关系;即使后者成立,也还没有获得执行文件操作的授权。本文用九组可以单独运行的实验,把词法计算、输入政策、实际文件位置和操作权限分开检验。
每段示例都保存为独立的 .cjs 文件后用 Node 运行,成功时打印固定的 passed 消息。代码只使用内置模块;全部文件系统副作用局限于 mkdtemp 创建的临时测试目录,并在 finally 中清理。平台语法示例中的虚拟盘符只参与字符串计算。不要把临时目录变量替换成个人资料、项目根目录或服务器数据目录后执行实验。同步 API 是为了让断言顺序清楚,正式服务还需另行考虑阻塞与错误处理。

一、先让错误的 startsWith 判断露出破绽
审查 AI 生成的文件处理函数,我会先找它有没有把字符串前缀当成目录关系。名称为 allowed 的目录和 allowed-copy 是同级目录;后者的完整路径却可能以前者开头。这样的代码看起来简洁,普通子文件测试也会通过,因此很容易在审查中被放过。第一组实验专门构造同级前缀碰撞,不读取任何真实业务文件。反例的价值在于证明判断条件不足,而不是收集更多看起来正常的输入。
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const fixture = fs.mkdtempSync(path.join(os.tmpdir(), 'path-review-'));
try {
const root = path.join(fixture, 'allowed');
const sibling = path.join(fixture, 'allowed-copy');
fs.mkdirSync(root);
fs.mkdirSync(sibling);
const candidate = path.join(sibling, 'note.txt');
assert.equal(candidate.startsWith(root), true);
assert.equal(path.relative(root, candidate),
path.join('..', 'allowed-copy', 'note.txt'));
assert.equal(fs.existsSync(candidate), false);
console.log('example 01 passed');
} finally {
fs.rmSync(fixture, { recursive: true, force: true });
}注意,实验中 candidate 只是待判断的字符串,并没有被写入。真实评审也应把路径计算与文件副作用分开:先运行纯判断测试,再考虑允许哪些操作。给前缀补一个分隔符能够修复这一种反例,但还必须处理根目录自身、规范化和不同平台语义。把这些条件散落在业务逻辑里,比集中表达目录关系更难审核。
二、把判断改成 resolve 加 relative,但准确命名能力
我更愿意把基础函数叫作词法上的严格后代检查。先用 resolve 计算规范化后的绝对路径,再用 relative 询问:从授权根目录走到候选路径,需要先离开根目录吗?相对结果等于两个点,或者以两个点加当前平台分隔符开头,就意味着向上离开;结果仍是绝对路径,也不能视为根目录下的后代。空字符串表示同一路径,本例明确不把根目录自身当成目标文件。
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const fixture = fs.mkdtempSync(path.join(os.tmpdir(), 'path-review-'));
try {
function isDescendant(root, candidate) {
const rel = path.relative(path.resolve(root), path.resolve(candidate));
return rel !== '' && rel !== '..' &&
!rel.startsWith('..' + path.sep) && !path.isAbsolute(rel);
}
const root = path.join(fixture, 'allowed');
fs.mkdirSync(root);
const good = path.resolve(root, 'drafts', '..', 'note.txt');
const bad = path.resolve(root, '..', 'elsewhere', 'note.txt');
assert.equal(isDescendant(root, good), true);
assert.equal(isDescendant(root, bad), false);
assert.equal(isDescendant(root, root), false);
assert.equal(good, path.join(root, 'note.txt'));
console.log('example 02 passed');
} finally {
fs.rmSync(fixture, { recursive: true, force: true });
}这是由 Node 路径 API 语义推导出来的词法策略,不是 Node 提供的目录授权接口。resolve 不会检查目录是否存在,也不会沿符号链接找到真实目标。函数返回 true,只说明当前选择的路径语法把字符串解释成后代路径,不能推出访问已获授权、对象一定是普通文件,或者操作不会受到并发修改影响。
三、绝对路径要有业务政策,不能靠 resolve 猜意图
resolve 从右向左处理路径片段,后面的绝对路径可以使前面的根目录失去约束作用。因此,先拼一个根目录,并不等于输入就被关在里面。另一方面,位于根目录内的绝对路径在词法上确实可以通过后代检查。业务究竟允许它,必须单独写清楚。若表单约定只接收相对路径,我会在计算候选路径之前拒绝绝对路径和带 Windows 根信息的输入;这还能排除盘符相对形式,而不仅是普通的盘符绝对路径。
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const fixture = fs.mkdtempSync(path.join(os.tmpdir(), 'path-review-'));
try {
function relativeCandidate(root, input) {
if (typeof input !== 'string' || input.length === 0 || input.includes('\0')) {
throw new Error('invalid input');
}
if (path.posix.isAbsolute(input) || path.win32.parse(input).root !== '') {
throw new Error('relative path required');
}
const candidate = path.resolve(root, input);
const rel = path.relative(root, candidate);
if (rel === '' || rel === '..' || rel.startsWith('..' + path.sep) ||
path.isAbsolute(rel)) throw new Error('outside root');
return candidate;
}
const root = path.join(fixture, 'allowed');
const outside = path.join(fixture, 'elsewhere', 'note.txt');
fs.mkdirSync(root);
assert.equal(path.resolve(root, outside), outside);
assert.throws(() => relativeCandidate(root, outside), /relative/);
assert.throws(() => relativeCandidate(root, path.join(root, 'note.txt')), /relative/);
assert.throws(() => relativeCandidate(root, 'C:note.txt'), /relative/);
assert.throws(() => relativeCandidate(root, '../note.txt'), /outside/);
assert.equal(relativeCandidate(root, 'note.txt'), path.join(root, 'note.txt'));
console.log('example 03 passed');
} finally {
fs.rmSync(fixture, { recursive: true, force: true });
}这里接受的仍然是宿主平台的相对路径语法,额外拒绝另一种平台的根信息只是保守的接口限制。它不是完整的跨平台文件名校验器。冒号、设备名、尾部空格等规则另有平台差异;如果应用只需要生成几个类型的文件,限制为一个经过白名单校验的文件名,通常比接受任意路径更容易解释和维护。
四、给边界条件写断言,别让示例只测试快乐路径
AI 常常能给出一个有效子路径,却漏掉等于根目录、父目录、同级目录和看似特殊的合法名字。我会把这些情况放到一张输入与预期结果清单里。尤其不要简单地拒绝所有以两个点开头的字符串:名字为 ..draft.txt 的文件不是父目录跳转。判断必须看完整路径片段,而非把字符出现与目录语义混为一谈。空输入和空字符也应在调用路径 API 前被明确拒绝。
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const fixture = fs.mkdtempSync(path.join(os.tmpdir(), 'path-review-'));
try {
function accepts(root, input) {
if (typeof input !== 'string' || input.length === 0 || input.includes('\0')) {
return false;
}
if (path.posix.isAbsolute(input) || path.win32.parse(input).root !== '') return false;
const rel = path.relative(root, path.resolve(root, input));
return rel !== '' && rel !== '..' &&
!rel.startsWith('..' + path.sep) && !path.isAbsolute(rel);
}
const root = path.join(fixture, 'allowed');
fs.mkdirSync(root);
const cases = [
['note.txt', true], ['nested/note.txt', true],
['./nested/../note.txt', true], ['..draft.txt', true],
['', false], ['.', false], ['nested/..', false],
['..', false], ['../note.txt', false],
['../allowed-copy/note.txt', false], ['../../note.txt', false],
['bad\0name', false], [null, false]
];
for (const [input, expected] of cases) {
assert.equal(accepts(root, input), expected, String(input));
}
console.log('example 04 passed');
} finally {
fs.rmSync(fixture, { recursive: true, force: true });
}这些断言只计算候选名称,不会创建父目录中的文件。测试的预期值应由接口约定决定,不应把被测函数的结果复制一遍当作答案。还要保留错误输入的测试,确保以后有人调整需求时,清楚知道自己改变的是根目录政策、输入语法,还是后代判断本身。
五、Windows 和 POSIX 语法需要显式选择
Node 默认的 path 方法跟随运行平台。Linux 上的反斜杠通常只是文件名字符,Windows 的路径方法则把它当成分隔符;Windows 的盘符和跨盘相对结果也有额外含义。下面只构造虚拟路径字符串,不访问示例中的盘符。虚拟目录名取自本次临时目录,目的是让语法测试可以在 Linux 上执行,同时仍然覆盖 Windows 规则。
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const fixture = fs.mkdtempSync(path.join(os.tmpdir(), 'path-review-'));
try {
const id = path.basename(fixture);
const winRoot = path.win32.join('C:\\', id, 'allowed');
const posixRoot = path.posix.join('/', id, 'allowed');
const input = '..\\outside.txt';
const winCandidate = path.win32.resolve(winRoot, input);
const posixCandidate = path.posix.resolve(posixRoot, input);
assert.equal(path.win32.relative(winRoot, winCandidate), '..\\outside.txt');
assert.equal(path.posix.relative(posixRoot, posixCandidate), input);
assert.equal(path.posix.isAbsolute(winRoot), false);
assert.equal(path.win32.isAbsolute(winRoot), true);
const otherDrive = path.win32.join('D:\\', id, 'note.txt');
assert.equal(path.win32.isAbsolute(path.win32.relative(winRoot, otherDrive)), true);
assert.equal(path.win32.isAbsolute('C:note.txt'), false);
assert.equal(path.win32.parse('C:note.txt').root, 'C:');
console.log('example 05 passed');
} finally {
fs.rmSync(fixture, { recursive: true, force: true });
}这也解释了后代检查里为什么要保留 isAbsolute 对相对结果的判断。导入、归档或远端协议里的路径应先声明采用哪种语法;实际访问本机文件时,还必须按本机规则重新验证最终候选路径。不要用字符串替换斜杠后便宣称跨平台安全,也不要用统一转小写模拟所有文件系统的大小写行为。解析库的规则和实际文件系统的行为是两个层次。
六、符号链接会让词法包含与实际位置分离
第六组实验在临时目录内部创建两个兄弟目录,再从授权目录放置一个指向另一个目录的链接。链接本身的路径位于授权根目录下,但沿链接访问到的文件实际位于其外。这里的外部文件也是本次实验刚创建的测试数据,不涉及系统目录。对于已存在的对象,realpath 可以把链接解析为规范路径,然后再比较真实根目录与真实目标;这种补充检查可以揭示当前链接状态。
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const fixture = fs.mkdtempSync(path.join(os.tmpdir(), 'path-review-'));
try {
function inside(root, target) {
const rel = path.relative(root, target);
return rel !== '' && rel !== '..' &&
!rel.startsWith('..' + path.sep) && !path.isAbsolute(rel);
}
const root = path.join(fixture, 'allowed');
const other = path.join(fixture, 'other');
fs.mkdirSync(root);
fs.mkdirSync(other);
fs.writeFileSync(path.join(other, 'note.txt'), 'fixture only');
const link = path.join(root, 'shortcut');
fs.symlinkSync(other, link, process.platform === 'win32' ? 'junction' : 'dir');
const candidate = path.join(link, 'note.txt');
assert.equal(inside(root, candidate), true);
const realRoot = fs.realpathSync(root);
const realTarget = fs.realpathSync(candidate);
assert.equal(inside(realRoot, realTarget), false);
assert.equal(realTarget, path.join(fs.realpathSync(other), 'note.txt'));
console.log('example 06 passed');
} finally {
fs.rmSync(fixture, { recursive: true, force: true });
}不要因为 realpath 检查通过,就把函数命名成安全沙箱。它并不说明以后访问时的路径仍然指向同一对象,也不能证明没有硬链接等其他别名。链接实验需要环境允许创建目录链接;Windows 分支使用 junction。若运行环境禁止该能力,应报告相关测试未执行,不能把跳过记为通过。
七、用可控顺序展示检查与使用之间的时间窗口
时间检查与时间使用问题,常被缩写为 TOCTOU。为了避免依赖调度时机,我们不使用两个进程竞争,而是在同一个脚本里主动安排顺序:先检查链接的真实目标,随后替换链接,最后读取同一个字符串路径。这个实验是对可能发生的交错顺序的确定性展示,不是对现实竞争概率的测量。即使每个单独的文件系统调用都成功,组合起来也不自动具备原子性。
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const fixture = fs.mkdtempSync(path.join(os.tmpdir(), 'path-review-'));
try {
function inside(root, target) {
const rel = path.relative(root, target);
return rel !== '' && rel !== '..' &&
!rel.startsWith('..' + path.sep) && !path.isAbsolute(rel);
}
const root = path.join(fixture, 'allowed');
const first = path.join(root, 'first');
const second = path.join(fixture, 'other');
fs.mkdirSync(first, { recursive: true });
fs.mkdirSync(second);
fs.writeFileSync(path.join(first, 'note.txt'), 'before');
fs.writeFileSync(path.join(second, 'note.txt'), 'after');
const link = path.join(root, 'alias');
const type = process.platform === 'win32' ? 'junction' : 'dir';
fs.symlinkSync(first, link, type);
const candidate = path.join(link, 'note.txt');
const checked = fs.realpathSync(candidate);
assert.equal(inside(fs.realpathSync(root), checked), true);
fs.unlinkSync(link);
fs.symlinkSync(second, link, type);
assert.notEqual(fs.realpathSync(candidate), checked);
assert.equal(fs.readFileSync(candidate, 'utf8'), 'after');
assert.equal(inside(fs.realpathSync(root), fs.realpathSync(candidate)), false);
console.log('example 07 passed');
} finally {
fs.rmSync(fixture, { recursive: true, force: true });
}Node 官方文档以先 access 再 open 为例提醒了类似的竞争窗口;此处把同一原理应用到路径检查。改成同步函数不会阻止其他进程修改目录。对手若能改写路径祖先、链接或挂载关系,就不能只依赖这套字符串与 realpath 检查。需要另行设计操作系统权限、不可被对手修改的目录结构,以及适合目标平台的隔离机制。
八、新文件没有 realpath,父目录检查也有前提
创建文件时,目标还不存在,直接解析目标会失败。对于受应用控制、不会被不可信进程替换的目录,可以检查已存在的父目录,限制末级文件名,再以排他创建模式写入。这是一种减少误写和覆盖的工作流,不是解决所有目录竞争的技巧。下面只允许在已经存在的授权根目录中创建一个简单文本文件,不支持动态创建用户指定的多级目录。
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const fixture = fs.mkdtempSync(path.join(os.tmpdir(), 'path-review-'));
try {
const root = path.join(fixture, 'allowed');
fs.mkdirSync(root);
const name = 'report.txt';
assert.match(name, /^[a-z0-9][a-z0-9_-]{0,31}\.txt$/);
const candidate = path.join(root, name);
assert.throws(() => fs.realpathSync(candidate), { code: 'ENOENT' });
const realRoot = fs.realpathSync(root);
assert.equal(fs.realpathSync(path.dirname(candidate)), realRoot);
const fd = fs.openSync(candidate, 'wx');
try {
fs.writeFileSync(fd, 'new fixture file', 'utf8');
} finally {
fs.closeSync(fd);
}
assert.equal(fs.readFileSync(candidate, 'utf8'), 'new fixture file');
assert.throws(() => fs.openSync(candidate, 'wx'), { code: 'EEXIST' });
console.log('example 08 passed');
} finally {
fs.rmSync(fixture, { recursive: true, force: true });
}排他创建的作用是让已存在目标导致失败,避免把已有文件直接截断;不同文件系统仍可能有行为限制,应查阅部署环境。它不保证祖先目录没有被替换。若业务需要覆盖、删除、移动或者递归处理,必须重新定义相应授权与失败策略,不能从允许新建一个文件推导出更大的权限。
九、把明确授权写进工作流,而不是藏在路径函数里
最后一组把路径逻辑放回实际任务:授权对象来自可信调用方的配置,输入只提供一个文件名;未授权创建时,在任何业务写入前就失败。临时目录代表用户已经明确同意使用的工作目录,布尔值只模拟授权状态,生产系统不能让请求者自己提交一个 true 就获得权限。真正的确认还应说明目录、操作类型、文件范围,以及是否允许覆盖。
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const fixture = fs.mkdtempSync(path.join(os.tmpdir(), 'path-review-'));
try {
function createApprovedNote(grant, name, text) {
if (grant.allowCreate !== true) throw new Error('creation not approved');
if (typeof name !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,31}\.txt$/.test(name)) {
throw new Error('invalid filename');
}
const root = fs.realpathSync(grant.directory);
const candidate = path.resolve(root, name);
const rel = path.relative(root, candidate);
if (rel === '' || rel === '..' || rel.startsWith('..' + path.sep) ||
path.isAbsolute(rel)) throw new Error('outside root');
fs.writeFileSync(candidate, text, { encoding: 'utf8', flag: 'wx' });
return candidate;
}
const directory = path.join(fixture, 'approved-notes');
fs.mkdirSync(directory);
const denied = Object.freeze({ directory, allowCreate: false });
assert.throws(() => createApprovedNote(denied, 'note.txt', 'demo'), /not approved/);
assert.deepEqual(fs.readdirSync(directory), []);
const approved = Object.freeze({ directory, allowCreate: true });
assert.throws(() => createApprovedNote(approved, '../note.txt', 'demo'), /filename/);
const saved = createApprovedNote(approved, 'note.txt', 'approved demo');
assert.equal(fs.readFileSync(saved, 'utf8'), 'approved demo');
assert.throws(() => createApprovedNote(approved, 'note.txt', 'replace'), { code: 'EEXIST' });
console.log('example 09 passed');
} finally {
fs.rmSync(fixture, { recursive: true, force: true });
}这段代码的前提仍然是授权目录由应用管理,而且不存在能够替换其路径组件的不可信参与者。授权、输入限制、目录关系、对象类型、覆盖政策与系统权限,各自回答不同问题。AI 可以帮助写出候选实现和测试清单,但没有任何一个布尔返回值,能够替代这些边界的逐项确认。
审查结论:把保证说小,把测试做实
我会拒绝把 resolve 加 relative 描述成完整沙箱,但会把它保留为清晰、可测试的词法包含判断。最值得交给 AI 辅助的部分,是生成反例、整理接口约定和补齐回归测试;最需要人工负责的部分,是确认授权来自哪里、哪些进程能修改目录、部署平台是什么,以及失败时是否还会发生副作用。一次测试通过只能证明测试覆盖的行为,不能证明任意环境下都不存在越界。
实践中先把允许的任务缩小:固定一个明确授权的目录,只接受所需的文件名格式,默认不覆盖,拒绝不支持的输入,再按威胁模型评估链接和并发问题。若需求从个人脚本升级到处理不可信上传、多人共享目录或自动化代理,不应仅扩展几条字符串规则就继续沿用原来的安全结论。
参考依据与复现说明
Node.js path.resolve 与 path.relative:绝对路径生成、规范化与相对结果的官方语义。
Node.js Windows 与 POSIX 路径差异,以及 path.isAbsolute:平台选择及字面绝对路径判断的边界。
Node.js fs.realpath 与 fs.access 的竞争条件说明:实际路径解析及检查与使用之间的风险。
Node.js 文件系统打开标志:排他创建模式及其限制。
核验日期为 2026 年 10 月 18 日。九段代码在 Node.js v24.19.0、Linux 环境实际独立执行并通过断言;Windows 路径语法通过 path.win32 进行计算测试,未据此声称完成 Windows 文件系统实测。文中的目录授权和威胁模型判断是基于这些 API 语义形成的工程分析,示例均为本文独立构造。

