Files
apes-sidebar/tests/fs-operations.spec.ts
T
unsc9 832ff586b1 fix(fs): 恢复「指向根的链接可删」——根守卫改用 lstat,只看条目自己
上一提交的守卫用 stat,会跟随符号链接,于是「指向根的链接」被解析成根本身而被拒绝:
用户再也删不掉自己建的那个快捷方式。原代码比的是字符串,链接路径 ≠ 根路径,放行后
走 lstat 的 unlink 分支,只删链接本身、不递归 —— 这是个可用的行为,不该被顺手关掉。

改成 lstat:问的是「这一行条目本身是不是根」,链接就是它自己,不是它指向的东西。
于是链接恢复可删,而真正造成过事故的那些拼写 —— 大小写变体、\?\ 前缀、8.3 短名、
映射盘 —— 仍然全部被拒。

顺带消掉了「验身份用 stat、做动作用 lstat」的不一致:现在两次调用是同一个。

测试:fs-operations 那条 symlink→根 的用例由「拒绝」翻转为「删掉链接、项目完好」。
注意本机无创建软链接权限,该用例走 runIf(canSymlink) 被跳过,未能在本机实跑。
2026-10-05 11:31:54 +08:00

412 lines
17 KiB
TypeScript

import { afterAll, describe, expect, it } from 'vitest'
import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
import { renameWorkspaceEntry, removeWorkspaceEntry, mkdirWorkspaceEntry, writeWorkspaceUpload } from '../src/fs-operations.ts'
/** The test workspace root (each suite gets its own temp tree). */
const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-upload-'))
/** Symlink creation needs privileges on Windows; the link cases skip there. */
const canSymlink = (() => {
const dir = mkdtempSync(join(tmpdir(), 'dsh-sidebar-upload-probe-'))
try {
symlinkSync(dir, join(dir, 'probe-link'))
return true
} catch {
return false
} finally {
rmSync(dir, { recursive: true, force: true })
}
})()
afterAll(() => {
rmSync(root, { recursive: true, force: true })
})
/** Names of leftover temp files under `dir` (must be empty after every run). */
function tmpLeftovers(dir: string): string[] {
return readdirSync(dir).filter(name => name.includes('.dsh-upload-'))
}
/** Turn a string into the async-iterable chunk shape the route receives. */
function chunksOf(text: string): AsyncIterable<string | Uint8Array> {
return {
async *[Symbol.asyncIterator]() {
// Split on two-byte boundaries so UTF-8 multi-byte sequences cross
// chunk edges (streaming must reassemble them as raw bytes, not text).
for (let i = 0; i < text.length; i += 2) yield text.slice(i, i + 2)
},
}
}
/**
* A temp project whose root directory carries letters, so a lowercase variant
* of its path is a real spelling of the SAME directory (the win32 cases) and a
* link to it stands for the project itself.
*/
function makeProject(): { ws: string; inner: string } {
const ws = mkdtempSync(join(tmpdir(), 'dsh-sidebar-root-'))
const inner = join(ws, 'ProjDir')
mkdirSync(join(inner, 'src'), { recursive: true })
writeFileSync(join(inner, 'src', 'keep.ts'), 'x')
return { ws, inner }
}
describe('writeWorkspaceUpload', () => {
it('writes a file under the upload directory and returns its size', async () => {
const { path, size } = await writeWorkspaceUpload({
cwd: root,
dir: root,
relativePath: 'a.txt',
chunks: chunksOf('hello 世界'),
limit: 1024,
})
expect(path).toBe(join(root, 'a.txt'))
expect(size).toBe(Buffer.byteLength('hello 世界'))
expect(readFileSync(path, 'utf8')).toBe('hello 世界')
})
it('creates nested directories on demand (folder uploads)', async () => {
const { path } = await writeWorkspaceUpload({
cwd: root,
dir: root,
relativePath: 'docs/nested/deep.txt',
chunks: chunksOf('x'),
limit: 1024,
})
expect(existsSync(path)).toBe(true)
})
it('resolves relativePaths against the chosen directory', async () => {
const { path } = await writeWorkspaceUpload({
cwd: root,
dir: join(root, 'docs'),
relativePath: 'b.txt',
chunks: chunksOf('y'),
limit: 1024,
})
expect(path).toBe(join(root, 'docs', 'b.txt'))
})
it('refuses traversal, empty segments, and absolute relativePaths', async () => {
await expect(writeWorkspaceUpload({
cwd: root, dir: root, relativePath: '../evil.txt', chunks: chunksOf('x'), limit: 1024,
})).rejects.toMatchObject({ code: 'bad-request' })
await expect(writeWorkspaceUpload({
cwd: root, dir: root, relativePath: './a.txt', chunks: chunksOf('x'), limit: 1024,
})).rejects.toMatchObject({ code: 'bad-request' })
await expect(writeWorkspaceUpload({
cwd: root, dir: root, relativePath: 'a/../b.txt', chunks: chunksOf('x'), limit: 1024,
})).rejects.toMatchObject({ code: 'bad-request' })
await expect(writeWorkspaceUpload({
cwd: root, dir: root, relativePath: '//', chunks: chunksOf('x'), limit: 1024,
})).rejects.toMatchObject({ code: 'bad-request' })
// Empty segments are refused, not silently collapsed.
await expect(writeWorkspaceUpload({
cwd: root, dir: root, relativePath: 'a//b.txt', chunks: chunksOf('x'), limit: 1024,
})).rejects.toMatchObject({ code: 'bad-request' })
await expect(writeWorkspaceUpload({
cwd: root, dir: root, relativePath: 'a/b/', chunks: chunksOf('x'), limit: 1024,
})).rejects.toMatchObject({ code: 'bad-request' })
// Absolute paths (POSIX and Windows separators) are refused, not re-anchored.
await expect(writeWorkspaceUpload({
cwd: root, dir: root, relativePath: '/x.txt', chunks: chunksOf('x'), limit: 1024,
})).rejects.toMatchObject({ code: 'bad-request' })
await expect(writeWorkspaceUpload({
cwd: root, dir: root, relativePath: '\\x.txt', chunks: chunksOf('x'), limit: 1024,
})).rejects.toMatchObject({ code: 'bad-request' })
})
it('uploads into a directory outside the workspace (containment was removed)', async () => {
const outside = mkdtempSync(join(tmpdir(), 'dsh-sidebar-upload-outside-'))
try {
// ⚠️ PERMISSION CHANGE: the workspace fence is gone, so an absolute
// directory the host user can write is a valid upload target.
const result = await writeWorkspaceUpload({
cwd: root, dir: outside, relativePath: 'x.txt', chunks: chunksOf('x'), limit: 1024,
})
expect(result).toEqual({ path: join(outside, 'x.txt'), size: 1 })
expect(readFileSync(join(outside, 'x.txt'), 'utf8')).toBe('x')
} finally {
rmSync(outside, { recursive: true, force: true })
}
})
it('follows an upload directory symlink outside the workspace (no realpath guard)', async () => {
if (!canSymlink) return
const outside = mkdtempSync(join(tmpdir(), 'dsh-sidebar-upload-symlink-outside-'))
const link = join(root, 'upload-link')
try {
symlinkSync(outside, link)
const viaLink = await writeWorkspaceUpload({
cwd: root, dir: link, relativePath: 'a.txt', chunks: chunksOf('a'), limit: 1024,
})
expect(viaLink.path).toBe(join(link, 'a.txt'))
// …and a relative path that walks through the link lands there too.
const viaRelative = await writeWorkspaceUpload({
cwd: root, dir: root, relativePath: 'upload-link/b.txt', chunks: chunksOf('b'), limit: 1024,
})
expect(viaRelative.path).toBe(join(root, 'upload-link', 'b.txt'))
expect(readFileSync(join(outside, 'a.txt'), 'utf8')).toBe('a')
expect(readFileSync(join(outside, 'b.txt'), 'utf8')).toBe('b')
} finally {
rmSync(link, { force: true })
rmSync(outside, { recursive: true, force: true })
}
})
it('refuses oversized uploads without leaving a target or temp file', async () => {
const target = join(root, 'big.bin')
await expect(writeWorkspaceUpload({
cwd: root, dir: root, relativePath: 'big.bin', chunks: chunksOf('1234567890'), limit: 4,
})).rejects.toMatchObject({ code: 'too-large' })
expect(existsSync(target)).toBe(false)
expect(tmpLeftovers(root)).toEqual([])
})
it('keeps concurrent uploads to the same target independent', async () => {
const target = join(root, 'race.txt')
await Promise.all([
writeWorkspaceUpload({ cwd: root, dir: root, relativePath: 'race.txt', chunks: chunksOf('first'), limit: 1024 }),
writeWorkspaceUpload({ cwd: root, dir: root, relativePath: 'race.txt', chunks: chunksOf('second'), limit: 1024 }),
])
// Both renames succeed (unique temp names, no EEXIST cross-talk); the last
// rename wins and the losers leave nothing behind.
expect(['first', 'second']).toContain(readFileSync(target, 'utf8'))
expect(tmpLeftovers(root)).toEqual([])
})
it('does not overwrite an existing file on a failed (oversized) retry', async () => {
const target = join(root, 'keep.txt')
await writeWorkspaceUpload({ cwd: root, dir: root, relativePath: 'keep.txt', chunks: chunksOf('original'), limit: 1024 })
await expect(writeWorkspaceUpload({
cwd: root, dir: root, relativePath: 'keep.txt', chunks: chunksOf('0123456789'), limit: 2,
})).rejects.toMatchObject({ code: 'too-large' })
expect(readFileSync(target, 'utf8')).toBe('original')
})
})
describe('renameWorkspaceEntry', () => {
it('renames a file within its directory', async () => {
writeFileSync(join(root, 'old-name.txt'), 'x')
const { path } = await renameWorkspaceEntry({ cwd: root, path: join(root, 'old-name.txt'), name: 'new-name.txt' })
// The returned path is CANONICAL (realpath-resolved ancestors — on macOS
// the tmpdir's /var becomes /private/var), so assert the shape, not the
// lexical spelling.
expect(path.endsWith('new-name.txt')).toBe(true)
expect(existsSync(join(root, 'old-name.txt'))).toBe(false)
expect(existsSync(join(root, 'new-name.txt'))).toBe(true)
})
it('renames a directory (recursive content moves with it)', async () => {
mkdirSync(join(root, 'olddir/nested'), { recursive: true })
writeFileSync(join(root, 'olddir/nested/deep.txt'), 'x')
await renameWorkspaceEntry({ cwd: root, path: join(root, 'olddir'), name: 'newdir' })
expect(readFileSync(join(root, 'newdir/nested/deep.txt'), 'utf8')).toBe('x')
})
it('is a no-op for the same name (destination-exists refusal must not bite)', async () => {
writeFileSync(join(root, 'same.txt'), 'x')
await renameWorkspaceEntry({ cwd: root, path: join(root, 'same.txt'), name: 'same.txt' })
expect(existsSync(join(root, 'same.txt'))).toBe(true)
})
it('refuses single-segment violations (empty, dot, traversal, separators)', async () => {
writeFileSync(join(root, 'r.txt'), 'x')
for (const name of ['', '.', '..', 'a/b', 'a\\b']) {
await expect(renameWorkspaceEntry({ cwd: root, path: join(root, 'r.txt'), name }))
.rejects.toMatchObject({ code: 'bad-request' })
}
})
it('refuses an existing destination instead of clobbering it', async () => {
writeFileSync(join(root, 'src.txt'), 'src')
writeFileSync(join(root, 'dst.txt'), 'dst')
await expect(renameWorkspaceEntry({ cwd: root, path: join(root, 'src.txt'), name: 'dst.txt' }))
.rejects.toMatchObject({ code: 'fs-error', status: 409 })
expect(readFileSync(join(root, 'dst.txt'), 'utf8')).toBe('dst')
})
it('refuses the workspace root and missing sources', async () => {
await expect(renameWorkspaceEntry({ cwd: root, path: root, name: 'nope' }))
.rejects.toMatchObject({ code: 'fs-error' })
await expect(renameWorkspaceEntry({ cwd: root, path: join(root, 'missing.txt'), name: 'x' }))
.rejects.toMatchObject({ code: 'fs-error' })
})
it('renames a symlink ROW, not its target', async () => {
writeFileSync(join(root, 'target.txt'), 't')
symlinkSync(join(root, 'target.txt'), join(root, 'alias.txt'))
await renameWorkspaceEntry({ cwd: root, path: join(root, 'alias.txt'), name: 'alias2.txt' })
expect(existsSync(join(root, 'alias.txt'))).toBe(false)
expect(existsSync(join(root, 'alias2.txt'))).toBe(true)
expect(readFileSync(join(root, 'target.txt'), 'utf8')).toBe('t')
})
})
describe('removeWorkspaceEntry', () => {
it('unlinks a file', async () => {
writeFileSync(join(root, 'gone.txt'), 'x')
await removeWorkspaceEntry({ cwd: root, path: join(root, 'gone.txt') })
expect(existsSync(join(root, 'gone.txt'))).toBe(false)
})
it('removes a directory recursively', async () => {
mkdirSync(join(root, 'tree/sub'), { recursive: true })
writeFileSync(join(root, 'tree/sub/leaf.txt'), 'x')
await removeWorkspaceEntry({ cwd: root, path: join(root, 'tree') })
expect(existsSync(join(root, 'tree'))).toBe(false)
})
it('unlinks a symlink row without touching (or recursing into) its target', async () => {
mkdirSync(join(root, 'realdir'), { recursive: true })
writeFileSync(join(root, 'realdir/keep.txt'), 'x')
symlinkSync(join(root, 'realdir'), join(root, 'linkdir'))
await removeWorkspaceEntry({ cwd: root, path: join(root, 'linkdir') })
expect(existsSync(join(root, 'linkdir'))).toBe(false)
expect(readFileSync(join(root, 'realdir/keep.txt'), 'utf8')).toBe('x')
})
it('refuses the workspace root and missing paths', async () => {
await expect(removeWorkspaceEntry({ cwd: root, path: root }))
.rejects.toMatchObject({ code: 'fs-error' })
await expect(removeWorkspaceEntry({ cwd: root, path: join(root, 'no-such.txt') }))
.rejects.toMatchObject({ code: 'fs-error' })
})
it.runIf(canSymlink)('unlinks a symlink aimed AT the root, leaving the project intact', async () => {
// The guard compares the ENTRY's own identity (the same `lstat` the
// removal below uses), never what the link resolves to: the link goes and
// the project behind it stays — the behaviour the string compare had.
const { ws, inner } = makeProject()
symlinkSync(inner, join(ws, 'link-to-proj'))
try {
await removeWorkspaceEntry({ cwd: inner, path: join(ws, 'link-to-proj') })
expect(existsSync(join(ws, 'link-to-proj'))).toBe(false)
expect(existsSync(join(inner, 'src', 'keep.ts'))).toBe(true)
} finally {
rmSync(ws, { recursive: true, force: true })
}
})
})
describe('session-relative targets (the shared resolution contract, #646)', () => {
it('uploads into a session-relative directory', async () => {
const ws = mkdtempSync(join(tmpdir(), 'dsh-sidebar-relupload-'))
try {
const { path, size } = await writeWorkspaceUpload({
cwd: ws,
dir: '.',
relativePath: 'up/rel.txt',
chunks: chunksOf('rel'),
limit: 64,
})
expect(path).toBe(join(ws, 'up', 'rel.txt'))
expect(size).toBe(3)
expect(readFileSync(path, 'utf8')).toBe('rel')
expect(tmpLeftovers(ws)).toEqual([])
} finally {
rmSync(ws, { recursive: true, force: true })
}
})
it('renames a session-relative row', async () => {
const ws = mkdtempSync(join(tmpdir(), 'dsh-sidebar-relrename-'))
try {
writeFileSync(join(ws, 'a.txt'), 'x')
const renamed = await renameWorkspaceEntry({ cwd: ws, path: 'a.txt', name: 'b.txt' })
expect(renamed.path).toBe(join(ws, 'b.txt'))
expect(existsSync(join(ws, 'b.txt'))).toBe(true)
} finally {
rmSync(ws, { recursive: true, force: true })
}
})
it('removes a session-relative row', async () => {
const ws = mkdtempSync(join(tmpdir(), 'dsh-sidebar-relremove-'))
try {
writeFileSync(join(ws, 'gone.txt'), 'x')
const removed = await removeWorkspaceEntry({ cwd: ws, path: 'gone.txt' })
expect(removed.path).toBe(join(ws, 'gone.txt'))
expect(existsSync(join(ws, 'gone.txt'))).toBe(false)
} finally {
rmSync(ws, { recursive: true, force: true })
}
})
it('mkdirs under a session-relative parent', async () => {
const ws = mkdtempSync(join(tmpdir(), 'dsh-sidebar-relmkdir-'))
try {
const made = await mkdirWorkspaceEntry({ cwd: ws, path: '.', name: 'sub' })
expect(made.path).toBe(join(ws, 'sub'))
expect(existsSync(join(ws, 'sub'))).toBe(true)
} finally {
rmSync(ws, { recursive: true, force: true })
}
})
})
/**
* One directory has many SPELLINGS — a case variant, a `\\?\` prefix, an 8.3
* short name, a mapped drive. The root guard compared the two strings, so any
* of them walked past it and "delete this row" became a recursive delete of
* the whole project. The guard compares what the filesystem itself compares
* (`dev`+`ino`), which does not care how a path is spelled.
*
* Windows-only: on Linux the variant is a different directory, not a spelling
* of this one, and a case variant of a real path does not exist.
*/
describe.runIf(process.platform === 'win32')('workspace-root guard across path spellings', () => {
it('refuses a case variant of the root', async () => {
const { ws, inner } = makeProject()
try {
const variant = inner.toLowerCase()
// `ProjDir` carries capitals, so the lowercase spelling always differs —
// this does not depend on how the temp directory itself is spelled.
expect(variant).not.toBe(inner)
await expect(removeWorkspaceEntry({ cwd: inner, path: variant }))
.rejects.toMatchObject({ code: 'fs-error' })
expect(existsSync(join(inner, 'src', 'keep.ts'))).toBe(true)
} finally {
rmSync(ws, { recursive: true, force: true })
}
})
it('refuses the extended-length spelling of the root', async () => {
const { ws, inner } = makeProject()
try {
await expect(removeWorkspaceEntry({ cwd: inner, path: `\\\\?\\${inner}` }))
.rejects.toMatchObject({ code: 'fs-error' })
expect(existsSync(join(inner, 'src', 'keep.ts'))).toBe(true)
} finally {
rmSync(ws, { recursive: true, force: true })
}
})
it('refuses a case variant for rename too', async () => {
const { ws, inner } = makeProject()
try {
await expect(renameWorkspaceEntry({ cwd: inner, path: inner.toLowerCase(), name: 'moved' }))
.rejects.toMatchObject({ code: 'fs-error' })
expect(existsSync(join(inner, 'src', 'keep.ts'))).toBe(true)
} finally {
rmSync(ws, { recursive: true, force: true })
}
})
it('still removes a SUBdirectory reached through a spelled-out path', async () => {
const { ws, inner } = makeProject()
try {
mkdirSync(join(inner, 'Sub'))
// A spelled-out path that is NOT the root passes the guard — and unlike a
// case variant this holds on a case-SENSITIVE volume too.
await removeWorkspaceEntry({ cwd: inner, path: `\\\\?\\${join(inner, 'Sub')}` })
expect(existsSync(join(inner, 'Sub'))).toBe(false)
expect(existsSync(inner)).toBe(true)
} finally {
rmSync(ws, { recursive: true, force: true })
}
})
})