Skip to content

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): restrict attachment fetches to storage (#66)

OKNOTOKdaf41f611b95
diff --git a/server/src/__tests__/storage-keys.test.ts b/server/src/__tests__/storage-keys.test.ts
new file mode 100644
index 0000000..a24158f
--- /dev/null
+++ b/server/src/__tests__/storage-keys.test.ts
@@ -0,0 +1,87 @@
+/**
+ * Regression tests for message attachment storage references.
+ *
+ * Run: node --import tsx --test server/src/__tests__/storage-keys.test.ts
+ */
+import { test } from 'node:test'
+import assert from 'node:assert/strict'
+import {
+ messageAttachmentStorageKey,
+ normalizeStorageKey,
+ storageKeyFromPublicUrl,
+} from '../storage-keys.js'
+
+const PUBLIC_BASE = 'https://cdn.cumora.test/private-files'
+
+test('rejects arbitrary text-attachment URLs, including private network targets', () => {
+ for (const url of [
+ 'http://127.0.0.1:5181/admin',
+ 'http://169.254.169.254/latest/meta-data',
+ 'http://10.0.0.8/internal',
+ 'https://attacker.example/payload.txt',
+ ]) {
+ assert.equal(messageAttachmentStorageKey({ url }, PUBLIC_BASE), null)
+ }
+})
+
+test('accepts local and configured-public-base attachment URLs', () => {
+ assert.equal(
+ messageAttachmentStorageKey({ url: '/uploads/attachments/abc123.txt' }, PUBLIC_BASE),
+ 'attachments/abc123.txt',
+ )
+ assert.equal(
+ messageAttachmentStorageKey({ url: `${PUBLIC_BASE}/attachments/abc123.txt?exp=1&sig=x` }, PUBLIC_BASE),
+ 'attachments/abc123.txt',
+ )
+})
+
+test('accepts a valid explicit key while ignoring an unverifiable presigned URL', () => {
+ assert.equal(
+ messageAttachmentStorageKey({
+ key: 'attachments/abc123.txt',
+ url: 'https://bucket.example.invalid/presigned-object?signature=opaque',
+ }, PUBLIC_BASE),
+ 'attachments/abc123.txt',
+ )
+})
+
+test('rejects conflicting trusted key and URL references', () => {
+ assert.equal(
+ messageAttachmentStorageKey({
+ key: 'attachments/one.txt',
+ url: `${PUBLIC_BASE}/attachments/two.txt`,
+ }, PUBLIC_BASE),
+ null,
+ )
+})
+
+test('message attachments cannot reference other storage namespaces', () => {
+ assert.equal(messageAttachmentStorageKey({ key: 'avatars/person.png' }, PUBLIC_BASE), null)
+ assert.equal(messageAttachmentStorageKey({ key: 'email-attachments/mail.txt' }, PUBLIC_BASE), null)
+})
+
+test('rejects traversal, encoded traversal, backslashes, and empty keys', () => {
+ for (const key of [
+ 'attachments/../../etc/passwd',
+ 'attachments/%2e%2e/secret.txt',
+ 'attachments\\..\\secret.txt',
+ 'attachments/',
+ ]) {
+ assert.equal(normalizeStorageKey(key), null)
+ }
+})
+
+test('public URL parsing is pinned to the configured origin and base path', () => {
+ assert.equal(
+ storageKeyFromPublicUrl(`${PUBLIC_BASE}/attachments/report.md`, PUBLIC_BASE),
+ 'attachments/report.md',
+ )
+ assert.equal(
+ storageKeyFromPublicUrl('https://cdn.cumora.test/other/attachments/report.md', PUBLIC_BASE),
+ null,
+ )
+ assert.equal(
+ storageKeyFromPublicUrl('https://cdn.cumora.test.evil.example/private-files/attachments/report.md', PUBLIC_BASE),
+ null,
+ )
+})
diff --git a/server/src/agents/turn.ts b/server/src/agents/turn.ts
index baa8ab6..f62df3f 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 { messageAttachmentStorageKey } from '../storage-keys.js'
import { classifyInboxTriage, gateSyntheticWake } from './inbox-triage.js'
import { GLANCE_YIELD_RULES } from './glance-protocol.js'
import { TOOL_DEFS_RESPONSES, executePodTool } from './runtime/pod-tools.js'
@@ -388,17 +389,25 @@ function publicUrlFor(url: string): string {
return base.replace(/\/+$/, '') + url
}
-/** Re-sign an attachment URL just-in-time for the agent's wake — the URL
- * stored in messages.attachment.url could be hours/days old. With HMAC
- * signing on, an expired URL would 403 when the agent (or OpenAI vision)
- * tries to fetch. We resolve via the storage layer at the moment of use. */
-async function freshAttachmentUrl(att: InboxAttachment): Promise<string> {
- if (!att.key) return att.url
+interface TrustedAttachmentSource {
+ key: string
+ url: string
+ mode: 'local' | 'r2'
+}
+
+/** Resolve message content exclusively from Cumora storage. The persisted URL
+ * is presentation data and must never select a server-side fetch target;
+ * regenerate it from the validated key and fail closed for legacy/external
+ * references. External image links remain visible in text context, but are
+ * deliberately not downloaded by this process. */
+async function trustedAttachmentSource(att: InboxAttachment): Promise<TrustedAttachmentSource | null> {
+ const key = messageAttachmentStorageKey(att, env.R2_PUBLIC_BASE)
+ if (!key) return null
try {
const { storage } = await import('../storage.js')
- return await storage.publicUrl(att.key)
+ return { key, url: await storage.publicUrl(key), mode: storage.mode }
} catch {
- return att.url
+ return null
}
}
@@ -704,27 +713,32 @@ async function readTextAttachment(att: InboxAttachment): Promise<TextExcerpt | n
const looksTextual = mime.startsWith('text/') || TEXT_LIKE_MIMES.has(mime)
if (!looksTextual) return null
+ const source = await trustedAttachmentSource(att)
+ if (!source) return null
let buf: Buffer | null = null
- if (att.url.startsWith('/uploads/')) {
+ if (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 { join } = await import('node:path')
+ const { resolve, sep } = await import('node:path')
const { UPLOAD_DIR } = await import('../storage.js')
- const rel = att.url.replace(/^\/uploads\//, '')
- const data = await readFile(join(UPLOAD_DIR, rel))
+ 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
}
} else {
- // R2 / external URL — re-sign just-in-time so an old persisted URL
- // doesn't 403 at the Worker, then fetch with a short timeout so a
- // flaky bucket can't stall the wake.
- const fresh = await freshAttachmentUrl(att)
- if (!/^https?:\/\//.test(fresh)) return null
+ // R2 URL was minted from the validated key above. Reject redirects so a
+ // compromised/misconfigured storage edge cannot pivot to a private host.
+ if (!/^https?:\/\//.test(source.url)) return null
try {
- const r = await fetch(fresh, { signal: AbortSignal.timeout(5000) })
+ const r = await fetch(source.url, {
+ signal: AbortSignal.timeout(5000),
+ redirect: 'error',
+ })
if (!r.ok) return null
buf = Buffer.from(await r.arrayBuffer())
} catch {
@@ -765,8 +779,9 @@ async function collectImageAttachments(items: InboxRow[]): Promise<Array<{ messa
for (const m of items) {
const a = m.attachment
if (!a || a.kind !== 'img' || !a.url) continue
- const fresh = await freshAttachmentUrl(a)
- const url = publicUrlFor(fresh)
+ const source = await trustedAttachmentSource(a)
+ if (!source) continue
+ const url = publicUrlFor(source.url)
// Only ship images OpenAI can actually fetch. Local /uploads paths without
// a PUBLIC_HOST get textually mentioned but not vision-fed.
if (!/^https?:\/\//.test(url)) continue
diff --git a/server/src/api/router.ts b/server/src/api/router.ts
index 71a7865..e965f3c 100644
--- a/server/src/api/router.ts
+++ b/server/src/api/router.ts
@@ -1,5 +1,8 @@
import { Router, type Request, type Response, type NextFunction } from 'express'
-import { storage, UPLOAD_DIR, freshenAttachmentUrl, normalizeStorageKey, storageKeyFromPublicUrl } from '../storage.js'
+import {
+ storage, UPLOAD_DIR, freshenAttachmentUrl, normalizeStorageKey,
+ storageKeyFromPublicUrl, messageAttachmentStorageKey,
+} from '../storage.js'
import { pool } from '../db/pool.js'
import { CH_MESSAGE_NEW, CH_REACTIONS, CH_CONVO_UPDATED, CH_DOCS, CH_TYPING, CH_CALENDAR_EVENTS, publish } from '../redis.js'
import { createPoll, castVote, closePoll, PollError } from '../polls.js'
@@ -3295,16 +3298,28 @@ api.post('/conversations/:id/messages', async (req, res) => {
if (rawAttachment && typeof rawAttachment === 'object') {
const a = rawAttachment as Record<string, unknown>
if (typeof a.url === 'string' && typeof a.name === 'string') {
+ // URLs are display data and may be client-controlled or expired. Resolve
+ // the server-generated object key, then mint the URL ourselves so a chat
+ // attachment can never turn an agent wake into an arbitrary server fetch.
+ const key = messageAttachmentStorageKey(a)
+ if (!key) {
+ res.status(400).json({ error: 'attachment must reference Cumora storage' })
+ return
+ }
+ let url: string
+ try {
+ url = await storage.publicUrl(key)
+ } catch {
+ res.status(400).json({ error: 'attachment storage reference is invalid' })
+ return
+ }
attachment = {
- url: a.url,
- name: a.name,
+ url,
+ name: a.name.trim().slice(0, 200),
kind: (a.kind === 'pdf' || a.kind === 'file' || a.kind === 'fig' ? a.kind : 'img') as AttachmentPayload['kind'],
mime: typeof a.mime === 'string' ? a.mime : undefined,
size: typeof a.size === 'number' ? a.size : undefined,
- // Preserve the storage `key` so we can later re-sign the URL on
- // every read — without it, signed URLs would expire and break
- // historical message bubbles after their TTL window.
- key: typeof a.key === 'string' ? a.key : undefined,
+ key,
}
}
}
diff --git a/server/src/storage-keys.ts b/server/src/storage-keys.ts
new file mode 100644
index 0000000..12f3351
--- /dev/null
+++ b/server/src/storage-keys.ts
@@ -0,0 +1,78 @@
+/** Pure storage-reference policy shared by API persistence and agent reads.
+ *
+ * A message attachment URL is presentation data: signatures expire and the
+ * client can alter it. Only a server-generated `attachments/` key may choose
+ * what the server reads. Keeping this module free of env/storage imports makes
+ * the trust boundary directly unit-testable. */
+
+const STORAGE_KEY_PREFIXES = ['attachments/', 'email-attachments/', 'avatars/']
+
+function stripQueryAndHash(value: string): string {
+ return value.split('?')[0].split('#')[0]
+}
+
+export function normalizeStorageKey(raw: string): string | null {
+ try {
+ const key = decodeURIComponent(stripQueryAndHash(raw.trim()).replace(/^\/+/, ''))
+ if (!key || key.length > 1024) return null
+ if (/[\\\u0000-\u001f\u007f]/.test(key) || key.includes('?') || key.includes('#')) return null
+ const segments = key.split('/')
+ if (segments.some((segment) => !segment || segment === '.' || segment === '..')) return null
+ const prefix = STORAGE_KEY_PREFIXES.find((candidate) => key.startsWith(candidate))
+ if (!prefix || key.length === prefix.length) return null
+ return key
+ } catch {
+ return null
+ }
+}
+
+/** Derive a storage key only from a local upload URL or the configured R2
+ * public origin. Arbitrary absolute URLs are never storage references. */
+export function storageKeyFromPublicUrl(raw: string, r2PublicBase: string): string | null {
+ const value = raw.trim()
+ if (!value) return null
+
+ if (value.startsWith('/uploads/')) {
+ return normalizeStorageKey(value.slice('/uploads/'.length))
+ }
+
+ if (!r2PublicBase) return null
+ try {
+ const url = new URL(value)
+ const base = new URL(r2PublicBase)
+ const basePath = base.pathname.replace(/\/+$/, '')
+ if (url.origin !== base.origin) return null
+ if (basePath && !url.pathname.startsWith(`${basePath}/`)) return null
+ const rawKey = basePath
+ ? url.pathname.slice(basePath.length + 1)
+ : url.pathname.replace(/^\/+/, '')
+ return normalizeStorageKey(rawKey)
+ } catch {
+ return null
+ }
+}
+
+/** Select the authoritative object key for a chat message attachment.
+ *
+ * A valid explicit key wins even when its accompanying URL is a presigned S3
+ * URL that cannot be derived from R2_PUBLIC_BASE; consumers must regenerate
+ * the URL from that key. If both fields identify known storage objects they
+ * must agree, preventing a confused-reference mismatch. */
+export function messageAttachmentStorageKey(
+ input: { key?: unknown; url?: unknown },
+ r2PublicBase: string,
+): string | null {
+ const rawKey = typeof input.key === 'string' ? input.key.trim() : ''
+ const fromUrl = typeof input.url === 'string'
+ ? storageKeyFromPublicUrl(input.url, r2PublicBase)
+ : null
+
+ if (rawKey) {
+ const fromKey = normalizeStorageKey(rawKey)
+ if (!fromKey?.startsWith('attachments/')) return null
+ if (fromUrl && fromUrl !== fromKey) return null
+ return fromKey
+ }
+
+ return fromUrl?.startsWith('attachments/') ? fromUrl : null
+}
diff --git a/server/src/storage.ts b/server/src/storage.ts
index feda318..b93a183 100644
--- a/server/src/storage.ts
+++ b/server/src/storage.ts
@@ -28,6 +28,13 @@ import {
} from '@aws-sdk/client-s3'
import { getSignedUrl } from '@aws-sdk/s3-request-presigner'
import { env } from './env.js'
+import {
+ normalizeStorageKey,
+ storageKeyFromPublicUrl as storageKeyFromPublicUrlForBase,
+ messageAttachmentStorageKey as messageAttachmentStorageKeyForBase,
+} from './storage-keys.js'
+
+export { normalizeStorageKey }
/** Keys under these prefixes get HMAC-signed URLs when a signing secret is
* configured. Other prefixes (e.g. `avatars/`) are served unsigned — they
@@ -37,46 +44,12 @@ function needsSignature(key: string): boolean {
return SIGNED_PREFIXES.some((p) => key.startsWith(p))
}
-const STORAGE_KEY_PREFIXES = ['attachments/', 'email-attachments/', 'avatars/']
-function isStorageKey(key: string): boolean {
- return STORAGE_KEY_PREFIXES.some((p) => key.startsWith(p))
-}
-
-function stripQueryAndHash(path: string): string {
- return path.split('?')[0].split('#')[0]
-}
-
-export function normalizeStorageKey(raw: string): string | null {
- try {
- const key = decodeURIComponent(stripQueryAndHash(raw.trim()).replace(/^\/+/, ''))
- return isStorageKey(key) ? key : null
- } catch {
- return null
- }
-}
-
export function storageKeyFromPublicUrl(raw: string): string | null {
- const value = raw.trim()
- if (!value) return null
-
- if (value.startsWith('/uploads/')) {
- return normalizeStorageKey(value.slice('/uploads/'.length))
- }
+ return storageKeyFromPublicUrlForBase(raw, env.R2_PUBLIC_BASE)
+}
- if (!env.R2_PUBLIC_BASE) return null
- try {
- const url = new URL(value)
- const base = new URL(env.R2_PUBLIC_BASE)
- const basePath = base.pathname.replace(/\/+$/, '')
- if (url.origin !== base.origin) return null
- if (basePath && !url.pathname.startsWith(`${basePath}/`)) return null
- const rawKey = basePath
- ? url.pathname.slice(basePath.length + 1)
- : url.pathname.replace(/^\/+/, '')
- return normalizeStorageKey(rawKey)
- } catch {
- return null
- }
+export function messageAttachmentStorageKey(input: { key?: unknown; url?: unknown }): string | null {
+ return messageAttachmentStorageKeyForBase(input, env.R2_PUBLIC_BASE)
}
export function signedUrlExpiresSoon(raw: string, leewaySeconds = 300): boolean {