Where agent teams gather. Cross-platform team chat where AI agents are first-class teammates — with cloud or bring-your-own (Claude Code / Codex) brains.
TypeScript
fix(agents): prevent local attachment symlink escapes (#73)
OKNOTOKaf650ca4900c
diff --git a/server/src/__tests__/local-attachment-files.test.ts b/server/src/__tests__/local-attachment-files.test.tsnew file mode 100644index 0000000..e2347ba--- /dev/null+++ b/server/src/__tests__/local-attachment-files.test.ts@@ -0,0 +1,78 @@+/**+ * Regression tests for local attachment path containment.+ *+ * Run: node --import tsx --test server/src/__tests__/local-attachment-files.test.ts+ */+import assert from 'node:assert/strict'+import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, test } from 'node:test'+import { readLocalMessageAttachment } from '../local-attachment-files.js'++const tempRoots = new Set<string>()++async function fixture(): Promise<{ root: string; uploads: string }> {+ const root = await mkdtemp(join(tmpdir(), 'cumora-local-attachment-'))+ tempRoots.add(root)+ const uploads = join(root, 'uploads')+ await mkdir(join(uploads, 'attachments'), { recursive: true })+ return { root, uploads }+}++afterEach(async () => {+ await Promise.all([...tempRoots].map((root) => rm(root, { recursive: true, force: true })))+ tempRoots.clear()+})++test('reads a regular attachment inside the upload root', async () => {+ const { uploads } = await fixture()+ await writeFile(join(uploads, 'attachments', 'note.txt'), 'safe content')++ const data = await readLocalMessageAttachment(uploads, 'attachments/note.txt')++ assert.equal(data?.toString('utf8'), 'safe content')+})++test('rejects a final symlink whose target escapes the upload root', {+ // Creating file symlinks requires Developer Mode or elevation on Windows;+ // the directory-junction case below still exercises physical containment.+ skip: process.platform === 'win32',+}, async () => {+ const { root, uploads } = await fixture()+ const secret = join(root, 'secret.txt')+ await writeFile(secret, 'outside content')+ await symlink(secret, join(uploads, 'attachments', 'linked.txt'))++ const data = await readLocalMessageAttachment(uploads, 'attachments/linked.txt')++ assert.equal(data, null)+})++test('rejects an attachment reached through a directory symlink that escapes', async () => {+ const { root, uploads } = await fixture()+ const outside = join(root, 'outside')+ await mkdir(outside)+ await writeFile(join(outside, 'secret.txt'), 'outside content')+ await symlink(+ outside,+ join(uploads, 'attachments', 'linked-dir'),+ process.platform === 'win32' ? 'junction' : 'dir',+ )++ const data = await readLocalMessageAttachment(+ uploads,+ 'attachments/linked-dir/secret.txt',+ )++ assert.equal(data, null)+})++test('rejects non-attachment keys, missing files, and directories', async () => {+ const { uploads } = await fixture()+ await mkdir(join(uploads, 'attachments', 'folder'))++ assert.equal(await readLocalMessageAttachment(uploads, 'avatars/person.txt'), null)+ assert.equal(await readLocalMessageAttachment(uploads, 'attachments/missing.txt'), null)+ assert.equal(await readLocalMessageAttachment(uploads, 'attachments/folder'), null)+})diff --git a/server/src/agents/turn.ts b/server/src/agents/turn.tsindex f62df3f..31541b5 100644--- a/server/src/agents/turn.ts+++ b/server/src/agents/turn.ts@@ -20,6 +20,7 @@import type { ResponseInputItem, ResponseStreamEvent } from 'openai/resources/responses/responses'import { env } from '../env.js'import { redis } from '../redis.js'+import { readLocalMessageAttachment } from '../local-attachment-files.js'import { messageAttachmentStorageKey } from '../storage-keys.js'import { classifyInboxTriage, gateSyntheticWake } from './inbox-triage.js'import { GLANCE_YIELD_RULES } from './glance-protocol.js'@@ -718,18 +719,9 @@ async function readTextAttachment(att: InboxAttachment): Promise<TextExcerpt | nlet buf: Buffer | null = nullif (source.mode === 'local') {// Local-mode file — read straight from disk to avoid a needless HTTP hop.- try {- const { readFile } = await import('node:fs/promises')- const { resolve, sep } = await import('node:path')- const { UPLOAD_DIR } = await import('../storage.js')- const root = resolve(UPLOAD_DIR)- const path = resolve(root, source.key)- if (!path.startsWith(`${root}${sep}`)) return null- const data = await readFile(path)- buf = Buffer.from(data)- } catch {- return null- }+ // The helper resolves physical paths so an in-root symlink cannot escape.+ const { UPLOAD_DIR } = await import('../storage.js')+ buf = await readLocalMessageAttachment(UPLOAD_DIR, source.key)} else {// R2 URL was minted from the validated key above. Reject redirects so a// compromised/misconfigured storage edge cannot pivot to a private host.diff --git a/server/src/local-attachment-files.ts b/server/src/local-attachment-files.tsnew file mode 100644index 0000000..bc79a47--- /dev/null+++ b/server/src/local-attachment-files.ts@@ -0,0 +1,47 @@+import { constants } from 'node:fs'+import { open, realpath } from 'node:fs/promises'+import { isAbsolute, relative, resolve, sep } from 'node:path'+import { normalizeStorageKey } from './storage-keys.js'++function isWithin(root: string, candidate: string): boolean {+ const rel = relative(root, candidate)+ return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)+}++/** Read a server-managed local attachment without following a path outside+ * the upload root. Lexical containment alone is insufficient because a path+ * component inside the root may be a symbolic link. Resolve both paths to+ * their physical locations, then open the verified canonical path so the+ * original link is never used for the read. */+export async function readLocalMessageAttachment(+ uploadDir: string,+ rawKey: string,+): Promise<Buffer | null> {+ const key = normalizeStorageKey(rawKey)+ if (!key?.startsWith('attachments/')) return null++ const lexicalRoot = resolve(uploadDir)+ const lexicalCandidate = resolve(lexicalRoot, key)+ if (!isWithin(lexicalRoot, lexicalCandidate)) return null++ let handle: Awaited<ReturnType<typeof open>> | null = null+ try {+ const [physicalRoot, physicalCandidate] = await Promise.all([+ realpath(lexicalRoot),+ realpath(lexicalCandidate),+ ])+ if (!isWithin(physicalRoot, physicalCandidate)) return null++ // O_NOFOLLOW fails closed on platforms that expose it if the final+ // component is replaced with a link between realpath() and open().+ const noFollow = typeof constants.O_NOFOLLOW === 'number' ? constants.O_NOFOLLOW : 0+ handle = await open(physicalCandidate, constants.O_RDONLY | noFollow)+ const metadata = await handle.stat()+ if (!metadata.isFile()) return null+ return await handle.readFile()+ } catch {+ return null+ } finally {+ await handle?.close().catch(() => undefined)+ }+}