opencastle 1.12.8 → 1.12.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,9 +6,9 @@
6
6
  * not only the statuses it records.
7
7
  */
8
8
  import { execFileSync } from 'node:child_process'
9
- import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
9
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
10
10
  import { tmpdir, hostname } from 'node:os'
11
- import { join } from 'node:path'
11
+ import { dirname, join } from 'node:path'
12
12
  import { DatabaseSync } from 'node:sqlite'
13
13
  import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
14
14
  import { createConvoyEngine, defaultBranchName, type ConvoyEngineOptions } from './engine.js'
@@ -195,6 +195,61 @@ describe('the change is committed before anything checks it', () => {
195
195
  })
196
196
  })
197
197
 
198
+ describe('symlinks out of the repository', () => {
199
+ function taskRow(convoyId: string, id: string) {
200
+ const store = createConvoyStore(join(repo, '.opencastle', 'convoy.db'))
201
+ try {
202
+ return store.getTask(id, convoyId)!
203
+ } finally {
204
+ store.close()
205
+ }
206
+ }
207
+
208
+ it('fail a task that adds one inside its declared directory, and none of its work merges', async () => {
209
+ // The scan looked at the declared paths only, so a link inside a declared
210
+ // directory went unchecked and merged.
211
+ const adapter = stubAdapter((_task, options) => {
212
+ mkdirSync(join(options.cwd!, 'src', 'auth'), { recursive: true })
213
+ writeFileSync(join(options.cwd!, 'src', 'auth', 'service.ts'), 'export {}\n')
214
+ symlinkSync(dirname(repo), join(options.cwd!, 'src', 'auth', 'keys'))
215
+ return { success: true, output: 'done', exitCode: 0 }
216
+ })
217
+ const result = await engine({ spec: spec([{ id: 'linker', files: ['src/auth/'] }]), adapter }).run()
218
+
219
+ expect(result.status).toBe('failed')
220
+ const task = taskRow(result.convoyId, 'linker')
221
+ expect(task.status).toBe('failed')
222
+ expect(task.output).toContain('symlink_escape_post_task: "src/auth/keys"')
223
+ expect(filesOn(result.branch!)).toEqual(['.gitignore', 'README.md'])
224
+ })
225
+
226
+ it('fail a task that declares no files and adds one', async () => {
227
+ const adapter = stubAdapter((_task, options) => {
228
+ symlinkSync(dirname(repo), join(options.cwd!, 'leak'))
229
+ return { success: true, output: 'done', exitCode: 0 }
230
+ })
231
+ const result = await engine({ spec: spec([{ id: 'linker' }]), adapter }).run()
232
+
233
+ expect(result.status).toBe('failed')
234
+ expect(taskRow(result.convoyId, 'linker').output).toContain('symlink_escape_post_task: "leak"')
235
+ expect(filesOn(result.branch!)).not.toContain('leak')
236
+ })
237
+
238
+ it('stop a task before its agent runs when its declared directory already holds one', async () => {
239
+ mkdirSync(join(repo, 'src'))
240
+ symlinkSync(dirname(repo), join(repo, 'src', 'vendor'))
241
+ git('add', '-A')
242
+ git('commit', '-qm', 'vendor link')
243
+ const adapter = stubAdapter(writesOwnFile)
244
+ const result = await engine({ spec: spec([{ id: 'edits-src', files: ['src/'] }]), adapter }).run()
245
+
246
+ expect(adapter.execute).not.toHaveBeenCalled()
247
+ const task = taskRow(result.convoyId, 'edits-src')
248
+ expect(task.status).toBe('failed')
249
+ expect(task.output).toContain('symlink_escape: "src/vendor"')
250
+ })
251
+ })
252
+
198
253
  describe('merge conflicts', () => {
199
254
  it('re-runs the conflicting task once, from the tip that now holds the other change', async () => {
200
255
  const prompts: Record<string, string[]> = {}
@@ -1269,7 +1269,9 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
1269
1269
 
1270
1270
  if (files.length > 0) {
1271
1271
  try {
1272
- scanSymlinks(files, wt)
1272
+ // The links git tracks inside a declared directory, too: one there
1273
+ // sends the agent's writes wherever it points.
1274
+ scanSymlinks(files, wt, wtManager.symlinks ? await wtManager.symlinks(wt, files.map(normalizePath)) : [])
1273
1275
  } catch (err) {
1274
1276
  return fail('failed', `Symlink security check failed: ${(err as Error).message}`, { kind: 'symlink-escape' })
1275
1277
  }
@@ -1587,9 +1589,12 @@ async function runConvoy(ctx: RunContext): Promise<ConvoyResult> {
1587
1589
  return fail('hook-failed', `post_task hook "${label}" failed: ${post.error ?? ''}`, { kind: 'hook-failed', hook: label })
1588
1590
  }
1589
1591
  }
1590
- if (files.length > 0) {
1592
+ // Every path the commit changed, not only the declared ones: a link added
1593
+ // inside a declared directory, or outside the task's paths (a partition
1594
+ // violation only warns), merges all the same.
1595
+ if (files.length > 0 || changedFiles.length > 0) {
1591
1596
  try {
1592
- scanNewSymlinks(wt, files)
1597
+ scanNewSymlinks(wt, files, changedFiles)
1593
1598
  } catch (err) {
1594
1599
  return fail('failed', `Post-execution symlink security check failed: ${(err as Error).message}`, { kind: 'symlink-escape-post' })
1595
1600
  }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * The symlink scans against real links on disk. partition.test.ts mocks
3
+ * node:fs, so it cannot follow a link through another one.
4
+ */
5
+ import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
6
+ import { tmpdir } from 'node:os'
7
+ import { join } from 'node:path'
8
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest'
9
+ import { scanSymlinks, scanNewSymlinks } from './partition.js'
10
+
11
+ let root: string
12
+ /** The worktree the scans guard. */
13
+ let base: string
14
+ /** A directory beside it, outside. */
15
+ let outside: string
16
+
17
+ beforeEach(() => {
18
+ root = realpathSync(mkdtempSync(join(tmpdir(), 'convoy-symlinks-')))
19
+ base = join(root, 'worktree')
20
+ outside = join(root, 'outside')
21
+ mkdirSync(join(base, 'src', 'auth'), { recursive: true })
22
+ mkdirSync(outside)
23
+ writeFileSync(join(outside, 'secret'), 'x\n')
24
+ })
25
+
26
+ afterEach(() => {
27
+ rmSync(root, { recursive: true, force: true })
28
+ })
29
+
30
+ describe('scanSymlinks, before the task', () => {
31
+ it('refuses a tracked link inside a declared directory that leads out', () => {
32
+ symlinkSync(outside, join(base, 'src/auth/keys'))
33
+ expect(() => scanSymlinks(['src/auth/'], base, ['src/auth/keys'])).toThrow('symlink_escape: "src/auth/keys"')
34
+ })
35
+
36
+ it('refuses a link above a declared file', () => {
37
+ symlinkSync(outside, join(base, 'src/vendor'))
38
+ expect(() => scanSymlinks(['src/vendor/lib.ts'], base)).toThrow('symlink_escape: "src/vendor"')
39
+ })
40
+
41
+ it('leaves alone a tracked link outside the declared paths', () => {
42
+ symlinkSync(outside, join(base, 'docs-link'))
43
+ expect(() => scanSymlinks(['src/auth/'], base, ['docs-link'])).not.toThrow()
44
+ })
45
+
46
+ it('passes a link to something inside that is not there yet, such as a build output', () => {
47
+ symlinkSync('../../dist/index.js', join(base, 'src/auth/built.js'))
48
+ expect(() => scanSymlinks(['src/auth/'], base, ['src/auth/built.js'])).not.toThrow()
49
+ })
50
+
51
+ it('refuses a link to something outside that is not there yet', () => {
52
+ symlinkSync(join(outside, 'new', 'authorized_keys'), join(base, 'src/auth/keys'))
53
+ expect(() => scanSymlinks(['src/auth/'], base, ['src/auth/keys'])).toThrow('resolves outside the partition')
54
+ })
55
+
56
+ it('follows the links on the way to a target that is not there yet', () => {
57
+ // src/auth/keys → src/vendor/keys, and src/vendor leads out.
58
+ symlinkSync(outside, join(base, 'src/vendor'))
59
+ symlinkSync('../vendor/keys', join(base, 'src/auth/keys'))
60
+ expect(() => scanSymlinks(['src/auth/'], base, ['src/auth/keys'])).toThrow('symlink_escape: "src/auth/keys"')
61
+ })
62
+ })
63
+
64
+ describe('scanNewSymlinks, after the task', () => {
65
+ it('refuses a new link inside a declared directory that leads out', () => {
66
+ symlinkSync(outside, join(base, 'src/auth/keys'))
67
+ expect(() => scanNewSymlinks(base, ['src/auth/'], ['src/auth/service.ts', 'src/auth/keys']))
68
+ .toThrow('symlink_escape_post_task: "src/auth/keys"')
69
+ })
70
+
71
+ it('refuses a new link outside the declared paths, and from a task that declares none', () => {
72
+ symlinkSync(join(outside, 'secret'), join(base, 'leak'))
73
+ expect(() => scanNewSymlinks(base, ['src/auth/'], ['leak'])).toThrow('symlink_escape_post_task: "leak"')
74
+ expect(() => scanNewSymlinks(base, [], ['leak'])).toThrow('symlink_escape_post_task: "leak"')
75
+ })
76
+
77
+ it('passes a link that stays inside, and a path the change deleted', () => {
78
+ writeFileSync(join(base, 'src/auth/service.ts'), 'export {}\n')
79
+ symlinkSync('service.ts', join(base, 'src/auth/alias.ts'))
80
+ expect(() => scanNewSymlinks(base, ['src/auth/'], ['src/auth/alias.ts', 'src/auth/gone.ts'])).not.toThrow()
81
+ })
82
+ })
@@ -336,7 +336,8 @@ describe('scanSymlinks', () => {
336
336
  .mockReturnValueOnce(BASE as unknown as string) // resolve(basePath)
337
337
  .mockReturnValueOnce(`${BASE}/src/auth/target.ts` as unknown as string) // symlink target
338
338
 
339
- vi.mocked(fs.lstatSync).mockReturnValue(makeFakeStats(true))
339
+ // The link itself; the directories above it are not links.
340
+ vi.mocked(fs.lstatSync).mockImplementation((p) => makeFakeStats(String(p).endsWith('/link.ts')))
340
341
 
341
342
  expect(() => scanSymlinks(['src/auth/link.ts'], BASE)).not.toThrow()
342
343
  })
@@ -1,6 +1,6 @@
1
- import { statSync, realpathSync, lstatSync, writeFileSync, rmSync } from 'node:fs'
1
+ import { statSync, realpathSync, lstatSync, readlinkSync, writeFileSync, rmSync } from 'node:fs'
2
2
  import { tmpdir } from 'node:os'
3
- import { normalize, join, resolve } from 'node:path'
3
+ import { basename, dirname, normalize, join, resolve, sep } from 'node:path'
4
4
  import type { Task } from './spec-types.js'
5
5
 
6
6
  // ── Path normalization ────────────────────────────────────────────────────────
@@ -164,69 +164,82 @@ export function determineFsCaseSensitivity(): boolean {
164
164
  // ── Symlink security scan ─────────────────────────────────────────────────────
165
165
 
166
166
  /**
167
- * Before task execution: scan each file in the task's files[] partition.
168
- * If any resolved symlink target escapes the basePath directory, throw symlink_escape.
167
+ * Where a write through the link at `absLink` lands, every link on the way
168
+ * followed. A link to something not there yet (a build output, say) lands
169
+ * where its target would be created. Null when even that cannot be told.
169
170
  */
170
- export function scanSymlinks(files: string[], basePath: string): void {
171
- const realBase = realpathSync(resolve(basePath))
171
+ function linkTarget(absLink: string): string | null {
172
+ try {
173
+ return realpathSync(absLink)
174
+ } catch { /* a link to nothing yet */ }
175
+ let target: string
176
+ try {
177
+ target = resolve(dirname(absLink), readlinkSync(absLink))
178
+ } catch {
179
+ return null
180
+ }
181
+ const missing: string[] = []
182
+ for (let dir = target; ; dir = dirname(dir)) {
183
+ try {
184
+ return join(realpathSync(dir), ...missing)
185
+ } catch { /* not there either: try its parent */ }
186
+ if (dirname(dir) === dir) return null
187
+ missing.unshift(basename(dir))
188
+ }
189
+ }
172
190
 
173
- for (const file of files) {
174
- const absPath = join(realBase, normalizePath(file))
175
- let stat: ReturnType<typeof lstatSync>
191
+ /** The first of `paths` (relative to `realBase`) that is a symlink leading out of it. */
192
+ function escapingLink(realBase: string, paths: Iterable<string>): { path: string; resolved: boolean } | null {
193
+ for (const rel of paths) {
194
+ const abs = join(realBase, rel)
176
195
  try {
177
- stat = lstatSync(absPath)
196
+ if (!lstatSync(abs).isSymbolicLink()) continue
178
197
  } catch {
179
- continue // file doesn't exist yet — skip
198
+ continue // not there (yet)
180
199
  }
200
+ const target = linkTarget(abs)
201
+ if (target === null) return { path: rel, resolved: false }
202
+ if (target !== realBase && !target.startsWith(realBase + sep)) return { path: rel, resolved: true }
203
+ }
204
+ return null
205
+ }
181
206
 
182
- if (stat.isSymbolicLink()) {
183
- let realTarget: string
184
- try {
185
- realTarget = realpathSync(absPath)
186
- } catch {
187
- throw new Error(`symlink_escape: symlink at "${file}" could not be resolved`)
188
- }
207
+ /** The directories above a path: `a/b/c` → `a`, `a/b`. */
208
+ function parentsOf(rel: string): string[] {
209
+ const parts = rel.replace(/\/+$/, '').split('/')
210
+ return parts.slice(0, -1).map((_, i) => parts.slice(0, i + 1).join('/'))
211
+ }
189
212
 
190
- if (!realTarget.startsWith(realBase + '/') && realTarget !== realBase) {
191
- throw new Error(
192
- `symlink_escape: "${file}" is a symlink that resolves outside the partition`,
193
- )
194
- }
195
- }
196
- }
213
+ /**
214
+ * Before task execution: no declared path may lead out of `basePath` through a
215
+ * symlink. Checked are the declared paths, the directories above them, and
216
+ * each of `trackedLinks` (the links git tracks, from the worktree) inside a
217
+ * declared directory, since a write through any of them lands wherever the
218
+ * link points. Throws symlink_escape.
219
+ */
220
+ export function scanSymlinks(files: string[], basePath: string, trackedLinks: string[] = []): void {
221
+ const realBase = realpathSync(resolve(basePath))
222
+ const declared = files.map(normalizePath)
223
+ const links = trackedLinks.filter(link => declared.some(file => pathsOverlap(file, link)))
224
+ const bad = escapingLink(realBase, new Set([...declared, ...declared.flatMap(parentsOf), ...links]))
225
+ if (!bad) return
226
+ throw new Error(bad.resolved
227
+ ? `symlink_escape: "${bad.path}" is a symlink that resolves outside the partition`
228
+ : `symlink_escape: symlink at "${bad.path}" could not be resolved`)
197
229
  }
198
230
 
199
231
  /**
200
- * After task execution: scan files[] in the worktree for new symlinks that escape the partition.
201
- * Throws symlink_escape_post_task if any symlink target is outside worktreePath.
232
+ * After task execution: no new symlink may lead out of the worktree. Checked
233
+ * are the declared paths and every path in `changed` (what the task's commit
234
+ * changed, from git), so a link added inside a declared directory, or outside
235
+ * the task's paths altogether, is found too: all of it merges.
236
+ * Throws symlink_escape_post_task.
202
237
  */
203
- export function scanNewSymlinks(worktreePath: string, files: string[]): void {
238
+ export function scanNewSymlinks(worktreePath: string, files: string[], changed: string[] = []): void {
204
239
  const realBase = realpathSync(resolve(worktreePath))
205
-
206
- for (const file of files) {
207
- const absPath = join(realBase, normalizePath(file))
208
- let stat: ReturnType<typeof lstatSync>
209
- try {
210
- stat = lstatSync(absPath)
211
- } catch {
212
- continue
213
- }
214
-
215
- if (stat.isSymbolicLink()) {
216
- let realTarget: string
217
- try {
218
- realTarget = realpathSync(absPath)
219
- } catch {
220
- throw new Error(
221
- `symlink_escape_post_task: "${file}" is a new symlink that cannot be resolved`,
222
- )
223
- }
224
-
225
- if (!realTarget.startsWith(realBase + '/') && realTarget !== realBase) {
226
- throw new Error(
227
- `symlink_escape_post_task: "${file}" is a new symlink that escapes the partition`,
228
- )
229
- }
230
- }
231
- }
240
+ const bad = escapingLink(realBase, new Set([...files.map(normalizePath), ...changed]))
241
+ if (!bad) return
242
+ throw new Error(bad.resolved
243
+ ? `symlink_escape_post_task: "${bad.path}" is a new symlink that escapes the partition`
244
+ : `symlink_escape_post_task: "${bad.path}" is a new symlink that cannot be resolved`)
232
245
  }
@@ -1,4 +1,4 @@
1
- import { mkdtempSync, rmSync, realpathSync } from 'node:fs'
1
+ import { mkdirSync, mkdtempSync, rmSync, realpathSync, symlinkSync, writeFileSync } from 'node:fs'
2
2
  import { tmpdir } from 'node:os'
3
3
  import { join } from 'node:path'
4
4
  import { execFile as execFileCb } from 'node:child_process'
@@ -212,6 +212,29 @@ describe('commitAll and changes', () => {
212
212
  })
213
213
  })
214
214
 
215
+ describe('changes and symlinks, by name as it is', () => {
216
+ it('reports a file with a non-ASCII name as it is, not quoted', async () => {
217
+ const path = await manager.create('worker1', 'HEAD')
218
+ const start = await manager.head!(path)
219
+ writeFileSync(join(path, 'résumé.md'), 'x\n')
220
+ await manager.commitAll!(path, 'add résumé.md')
221
+ expect((await manager.changes!(path, start!))!.files).toEqual(['résumé.md'])
222
+ })
223
+
224
+ it('lists the symlinks git tracks under the paths it is given, and nothing else', async () => {
225
+ const path = await manager.create('worker1', 'HEAD')
226
+ mkdirSync(join(path, 'docs'))
227
+ writeFileSync(join(path, 'docs', 'file.txt'), 'x\n')
228
+ symlinkSync('file.txt', join(path, 'docs', 'alias.txt'))
229
+ symlinkSync(tmpDir, join(path, 'docs', 'café'))
230
+ symlinkSync(tmpDir, join(path, 'elsewhere'))
231
+ await manager.commitAll!(path, 'links')
232
+ symlinkSync('file.txt', join(path, 'docs', 'untracked-link'))
233
+ expect((await manager.symlinks!(path, ['docs/'])).sort()).toEqual(['docs/alias.txt', 'docs/café'])
234
+ expect(await manager.symlinks!(path, [])).toEqual([])
235
+ })
236
+ })
237
+
215
238
  describe('ensureRootWorktree', () => {
216
239
  it('creates the branch from the base and checks it out in its own worktree', async () => {
217
240
  const { ensureRootWorktree } = await import('./worktree.js')
@@ -48,6 +48,8 @@ export interface WorktreeManager {
48
48
  head?(worktreePath: string): Promise<string | null>
49
49
  /** Files and diff between `sinceRef` and the worktree's HEAD. */
50
50
  changes?(worktreePath: string, sinceRef: string): Promise<WorktreeChanges | null>
51
+ /** The symlinks git tracks in the worktree under `paths`, as repository-relative paths. */
52
+ symlinks?(worktreePath: string, paths: string[]): Promise<string[]>
51
53
  }
52
54
 
53
55
  /** The branch name a worker's worktree is created on. */
@@ -268,8 +270,10 @@ export function createWorktreeManager(repoRoot: string): WorktreeManager {
268
270
 
269
271
  async function changes(worktreePath: string, sinceRef: string): Promise<WorktreeChanges | null> {
270
272
  try {
271
- const files = (await git(['diff', '--name-only', `${sinceRef}..HEAD`], worktreePath))
272
- .split('\n').map((s) => s.trim()).filter(Boolean)
273
+ // `-z`: each path as it is. Without it git quotes a name with non-ASCII
274
+ // characters, and nothing that reads the list finds that file.
275
+ const files = (await git(['diff', '--name-only', '-z', `${sinceRef}..HEAD`], worktreePath))
276
+ .split('\0').filter(Boolean)
273
277
  const diff = await git(['diff', `${sinceRef}..HEAD`], worktreePath)
274
278
  return { files, diff }
275
279
  } catch {
@@ -277,7 +281,17 @@ export function createWorktreeManager(repoRoot: string): WorktreeManager {
277
281
  }
278
282
  }
279
283
 
280
- return { create, remove, list, removeAll, commitAll, head, changes }
284
+ async function symlinks(worktreePath: string, paths: string[]): Promise<string[]> {
285
+ // No paths would list the whole repository.
286
+ if (paths.length === 0) return []
287
+ // Each entry: `<mode> <object> <stage>\t<path>`; 120000 is a symlink.
288
+ return (await git(['--literal-pathspecs', 'ls-files', '-s', '-z', '--', ...paths], worktreePath))
289
+ .split('\0')
290
+ .filter((entry) => entry.startsWith('120000 '))
291
+ .map((entry) => entry.slice(entry.indexOf('\t') + 1))
292
+ }
293
+
294
+ return { create, remove, list, removeAll, commitAll, head, changes, symlinks }
281
295
  }
282
296
 
283
297
  // ── The convoy's integration checkout ───────────────────────────────────────