Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(desktop): harden folder-zip walk guards and sanitization (BUG-175 review)

M3117c5df99df
diff --git a/desktop-app/ui/src/lib/__tests__/gfsFolderZip.test.ts b/desktop-app/ui/src/lib/__tests__/gfsFolderZip.test.ts
index 23c827011..02277cb53 100644
--- a/desktop-app/ui/src/lib/__tests__/gfsFolderZip.test.ts
+++ b/desktop-app/ui/src/lib/__tests__/gfsFolderZip.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from 'vitest'
import {
GFS_ZIP_MAX_ENTRIES,
type GfsFolderZipDeps,
+ GfsFolderZipEmptyError,
GfsFolderZipLimitError,
type GfsFolderZipProgress,
type GfsZipChildItem,
@@ -200,10 +201,14 @@ describe('createGfsFolderZip', () => {
const result = await createGfsFolderZip(
{ resourceId: 'root', drive: 'main', name: 'Root' },
{ deps }
- )
+ ).catch(error => error)
- expect(result.fileCount).toBe(0)
- expect(result.skipped).toEqual([{ path: 'Root/locked', reason: 'Permission denied' }])
+ // Nothing archivable: the walk short-circuits as empty (L8), carrying the
+ // skip so the caller can still explain why.
+ expect(result).toBeInstanceOf(GfsFolderZipEmptyError)
+ expect((result as GfsFolderZipEmptyError).skipped).toEqual([
+ { path: 'Root/locked', reason: 'Permission denied' },
+ ])
})
it('refuses over the declared byte ceiling with a clear message', async () => {
@@ -291,12 +296,11 @@ describe('createGfsFolderZip', () => {
sleep: async () => undefined,
}
- const result = await createGfsFolderZip(
- { resourceId: 'root', drive: 'main', name: 'Throttled' },
- { deps }
- )
+ // The retry succeeds but finds nothing archivable → empty short-circuit.
+ await expect(
+ createGfsFolderZip({ resourceId: 'root', drive: 'main', name: 'Throttled' }, { deps })
+ ).rejects.toThrow(/no downloadable files/)
expect(attempts).toBe(2)
- expect(result.fileCount).toBe(0)
})
it('aborts on a non-permission download failure instead of a holey archive', async () => {
@@ -322,21 +326,136 @@ describe('createGfsFolderZip', () => {
root: [
{
items: [
+ // Traversal needs separators — only exact `.`/`..` segments drop,
+ // so a leading-dot filename keeps its name (L5).
folder({ resourceId: 'n1', name: '../escape.txt' }),
folder({ resourceId: 'n2', name: 'a/b.txt' }),
folder({ resourceId: 'n3', name: '' }),
+ folder({ resourceId: 'n4', name: '.env' }),
+ // Windows-forbidden characters and trailing dots map away (L6).
+ folder({ resourceId: 'n5', name: 're:port*?"<>|.txt' }),
+ folder({ resourceId: 'n6', name: 'ends...' }),
+ folder({ resourceId: 'n7', name: '.' }),
+ folder({ resourceId: 'n8', name: '..' }),
],
nextCursor: null,
},
],
})
const result = await createGfsFolderZip(
- { resourceId: 'root', drive: 'main', name: 'Weird/Name' },
+ { resourceId: 'root', drive: 'main', name: 'Weird/Name:' },
{ deps }
)
expect(zipEntryNames(result.bytes).sort()).toEqual(
- ['Weird_Name/_escape.txt', 'Weird_Name/a_b.txt', 'Weird_Name/unnamed'].sort()
+ [
+ 'Weird_Name_/.._escape.txt',
+ 'Weird_Name_/a_b.txt',
+ 'Weird_Name_/unnamed',
+ 'Weird_Name_/.env',
+ 'Weird_Name_/re_port______.txt',
+ 'Weird_Name_/ends',
+ 'Weird_Name_/unnamed (2)',
+ 'Weird_Name_/unnamed (3)',
+ ].sort()
+ )
+ expect(result.fileName).toBe('Weird_Name_.zip')
+ })
+
+ it('treats a missing byte count as zero instead of NaN-poisoning the size guard (M1)', async () => {
+ const deps = depsFor({
+ root: [
+ {
+ items: [
+ folder({
+ resourceId: 'unknown',
+ name: 'unknown.bin',
+ bytes: undefined as unknown as number,
+ }),
+ folder({ resourceId: 'small', name: 'small.bin', bytes: 512 }),
+ ],
+ nextCursor: null,
+ },
+ ],
+ })
+ const result = await createGfsFolderZip(
+ { resourceId: 'root', drive: 'main', name: 'Legacy' },
+ // 1 KiB ceiling: NaN accumulation would disable the guard; 0 + 512 must
+ // still leave room, and a real overage must still refuse.
+ { deps, limits: { maxTotalBytes: 1024 } }
)
+ expect(result.fileCount).toBe(2)
+
+ const overDeps = depsFor({
+ root: [
+ {
+ items: [
+ folder({
+ resourceId: 'unknown',
+ name: 'unknown.bin',
+ bytes: undefined as unknown as number,
+ }),
+ folder({ resourceId: 'big', name: 'big.bin', bytes: 2048 }),
+ ],
+ nextCursor: null,
+ },
+ ],
+ })
+ await expect(
+ createGfsFolderZip(
+ { resourceId: 'root', drive: 'main', name: 'Legacy' },
+ { deps: overDeps, limits: { maxTotalBytes: 1024 } }
+ )
+ ).rejects.toThrow(/exceeds the 1 KiB folder-zip limit/)
+ })
+
+ it('re-enters the throttle budget after a 429 backoff before retrying (L1)', async () => {
+ let attempts = 0
+ const acquire = vi.fn(async () => undefined)
+ const deps: GfsFolderZipDeps = {
+ listChildren: vi.fn(async () => {
+ attempts += 1
+ if (attempts === 1) throw new Error('429 httpStatus=429 retryAfterSeconds=0')
+ return { items: [], nextCursor: null }
+ }),
+ download: async () => ({ bytes: new ArrayBuffer(0) }),
+ throttle: { acquire },
+ sleep: async () => undefined,
+ }
+
+ // An empty retry answer short-circuits as "no downloadable files"; the
+ // witness here is the budget: initial acquire + one post-backoff acquire.
+ await expect(
+ createGfsFolderZip({ resourceId: 'root', drive: 'main', name: 'Throttled' }, { deps })
+ ).rejects.toThrow(/no downloadable files/)
+ expect(attempts).toBe(2)
+ expect(acquire).toHaveBeenCalledTimes(2)
+ })
+
+ it('refuses to save an empty archive and reports skips (L8)', async () => {
+ const emptyDeps = depsFor({ root: [{ items: [], nextCursor: null }] })
+ await expect(
+ createGfsFolderZip({ resourceId: 'root', drive: 'main', name: 'Empty' }, { deps: emptyDeps })
+ ).rejects.toMatchObject({
+ name: 'GfsFolderZipEmptyError',
+ message: '"Empty" has no downloadable files.',
+ })
+
+ const allSkipped = depsFor({
+ root: [
+ {
+ items: [folder({ resourceId: 'hidden', name: 'hidden.txt', readable: false })],
+ nextCursor: null,
+ },
+ ],
+ })
+ const failure = await createGfsFolderZip(
+ { resourceId: 'root', drive: 'main', name: 'Mixed' },
+ { deps: allSkipped }
+ ).catch(error => error)
+ expect(failure).toBeInstanceOf(GfsFolderZipEmptyError)
+ expect((failure as GfsFolderZipEmptyError).skipped).toEqual([
+ { path: 'Mixed/hidden.txt', reason: 'No access' },
+ ])
})
})
diff --git a/desktop-app/ui/src/lib/gfsFolderZip.ts b/desktop-app/ui/src/lib/gfsFolderZip.ts
index db6a24df7..196818330 100644
--- a/desktop-app/ui/src/lib/gfsFolderZip.ts
+++ b/desktop-app/ui/src/lib/gfsFolderZip.ts
@@ -46,6 +46,16 @@ export interface GfsFolderZipResult {
/** The walk exceeded a configured ceiling — a refusal, not a failure. */
export class GfsFolderZipLimitError extends Error {}
+/** Nothing was archivable (an empty folder, or every entry was skipped). */
+export class GfsFolderZipEmptyError extends Error {
+ readonly skipped: GfsZipSkippedEntry[]
+ constructor(folderName: string, skipped: GfsZipSkippedEntry[]) {
+ super(`"${folderName}" has no downloadable files.`)
+ this.name = 'GfsFolderZipEmptyError'
+ this.skipped = skipped
+ }
+}
+
export interface GfsReadThrottle {
acquire(): Promise<void>
}
@@ -83,7 +93,8 @@ export interface GfsZipChildItem {
gfsUri: string
name: string
kind: 'file' | 'directory'
- bytes: number
+ /** Absent on older servers — treated as 0 by the size guard, never as NaN. */
+ bytes?: number
drive?: string
readable?: boolean
}
@@ -121,17 +132,28 @@ function isAccessDenied(message: string): boolean {
return parseHttpStatus(message) === 403 || message.toLowerCase().includes('forbidden')
}
-/** Zip-safe path segment: no separators, no NUL, no traversal prefix. */
+/**
+ * Zip-safe path segment. Separators, NUL and the characters Windows forbids
+ * (`: * ? " < > |`) map to `_`; trailing dots/spaces (also invalid on Windows)
+ * are stripped; only the EXACT `.`/`..` segments are dropped, so dotfiles like
+ * `.env` keep their name. Traversal is impossible regardless: separators are
+ * gone before the segment is used.
+ */
function sanitizeZipSegment(name: string): string {
const cleaned = name
- .replace(/[/\\\u0000]/g, '_')
- .replace(/^\.+/, '')
+ .replace(/[/\\:*?"<>|\u0000]/g, '_')
+ .replace(/[\s.]+$/, '')
.trim()
- return cleaned || 'unnamed'
+ if (!cleaned || cleaned === '.' || cleaned === '..') return 'unnamed'
+ return cleaned
}
function sanitizeFileName(name: string): string {
- return name.replace(/[/\\\u0000]/g, '_').trim() || 'folder'
+ const cleaned = name
+ .replace(/[/\\:*?"<>|\u0000]/g, '_')
+ .replace(/[\s.]+$/, '')
+ .trim()
+ return cleaned || 'folder'
}
export async function createGfsFolderZip(
@@ -151,7 +173,13 @@ export async function createGfsFolderZip(
const report = (progress: GfsFolderZipProgress) => options.onProgress?.(progress)
- /** One 429 backs off by the server-provided hint and retries exactly once. */
+ /**
+ * One 429 backs off by the server-provided hint and retries exactly once.
+ * The backoff window is NOT a throttle slot: after it elapses the retry
+ * re-enters the budget through `throttle.acquire()`, so a
+ * `retryAfterSeconds=0` answer cannot fire the retry with zero spacing
+ * against the same per-minute budget that just refused the first attempt.
+ */
const withRateLimitRetry = async <T>(operation: () => Promise<T>): Promise<T> => {
try {
return await operation()
@@ -159,6 +187,7 @@ export async function createGfsFolderZip(
const message = toMessage(error)
if (!isRateLimited(message)) throw error
await sleep(Math.min((parseRetryAfterSeconds(message) ?? 15) * 1000, 120_000))
+ await throttle.acquire()
return operation()
}
}
@@ -212,7 +241,10 @@ export async function createGfsFolderZip(
`"${folder.name}" holds more than ${maxEntries} files, which exceeds the folder-zip limit. Download smaller subfolders individually.`
)
}
- plannedBytes += child.bytes
+ // Older servers omit `bytes`; a missing value must read as 0, not
+ // NaN — NaN would poison `plannedBytes` and silently disable the
+ // size guard for the rest of the walk (M1).
+ plannedBytes += Number.isFinite(child.bytes) ? child.bytes : 0
if (plannedBytes > maxTotalBytes) {
throw new GfsFolderZipLimitError(
`"${folder.name}" exceeds the ${formatZipBytes(maxTotalBytes)} folder-zip limit. Download smaller subfolders individually.`
@@ -230,6 +262,11 @@ export async function createGfsFolderZip(
} while (cursor)
}
+ // An archive with zero entries is never useful: short-circuit instead of
+ // saving an empty zip (L8). Any skips are carried on the error so the caller
+ // can still explain why nothing was archivable.
+ if (files.length === 0) throw new GfsFolderZipEmptyError(folder.name, skipped)
+
// ── Phase 2: throttled downloads, skipping per-resource denials. ──
let addedBytes = 0
for (const [index, file] of files.entries()) {
diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsx
index e0e1b62b7..088b3e273 100644
--- a/desktop-app/ui/src/pages/FilesPage.tsx
+++ b/desktop-app/ui/src/pages/FilesPage.tsx
@@ -43,6 +43,7 @@ import { isEventFromNestedInteractive } from '@lib/clickableRowProps'
import { saveBytesToDisk, saveGfsFileToDisk } from '@lib/gfsDownload'
import { assertGfsFileUploadSize } from '@lib/gfsFileUpload'
import {
+ GfsFolderZipEmptyError,
GfsFolderZipLimitError,
type GfsFolderZipProgress,
createGfsFolderZip,
@@ -841,7 +842,12 @@ export function FilesPage({
pushToast?.(describeZipSkips(result.skipped), 'warn', { durationMs: 10_000 })
}
} catch (zipError) {
- if (!failClosedOnAuthorizationError(zipError)) {
+ if (zipError instanceof GfsFolderZipEmptyError) {
+ pushToast?.(zipError.message, 'info')
+ if (zipError.skipped.length) {
+ pushToast?.(describeZipSkips(zipError.skipped), 'warn', { durationMs: 10_000 })
+ }
+ } else if (!failClosedOnAuthorizationError(zipError)) {
const message =
zipError instanceof GfsFolderZipLimitError
? zipError.message
diff --git a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
index 2341347fc..d06966f51 100644
--- a/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/FilesPage.test.tsx
@@ -3446,6 +3446,56 @@ describe('FilesPage', () => {
)
})
+ it('tells the user an empty folder has nothing to zip instead of saving an empty archive', async () => {
+ vi.useFakeTimers()
+ const listChildren = vi.fn(async () => ({ items: [], nextCursor: null }))
+ const download = vi.fn(async () => ({ bytes: new ArrayBuffer(0) }))
+ const pushToast = vi.fn()
+ const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: { gfs: { listChildren, download } },
+ })
+ hookMock.useGfsBrowserController.mockReturnValue({
+ ...baseController(),
+ accessibleResources: [
+ {
+ resourceId: 'folder-1',
+ rid: 'folder-1',
+ gfsUri: 'gfs://main/folder-1',
+ drive: 'main',
+ parentResourceId: null,
+ name: 'Empty',
+ kind: 'directory',
+ path: '/Empty',
+ version: 0,
+ bytes: 0,
+ sources: ['grant'],
+ permissions: ['read'],
+ coversDescendants: false,
+ },
+ ],
+ })
+
+ renderFilesPage(pushToast)
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: 'Options for Empty' }))
+ })
+ await act(async () => {
+ fireEvent.click(screen.getByRole('menuitem', { name: 'Download as zip' }))
+ await vi.advanceTimersByTimeAsync(5_000)
+ })
+ await act(async () => {
+ await Promise.resolve()
+ })
+ expect(screen.queryByTestId('gfs-zip-progress')).toBeNull()
+
+ expect(listChildren).toHaveBeenCalledWith('folder-1', 'main', undefined)
+ expect(download).not.toHaveBeenCalled()
+ expect(click).not.toHaveBeenCalled()
+ expect(pushToast).toHaveBeenCalledWith('"Empty" has no downloadable files.', 'info')
+ })
+
it('omits Download as zip for a folder the session cannot read', async () => {
hookMock.useGfsBrowserController.mockReturnValue({
...baseController(),