Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions backend/src/routes/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ export function createFileRoutes() {
headers: {
'Content-Type': result.mimeType || 'application/octet-stream',
'Content-Length': result.size.toString(),
'Content-Security-Policy': 'sandbox allow-scripts',
}
})
}
Expand Down
22 changes: 15 additions & 7 deletions backend/src/services/files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ export async function getRawFileContent(userPath: string): Promise<Buffer> {

export async function getFile(userPath: string): Promise<FileInfo> {
const validatedPath = validatePath(userPath)
const responsePath = path.isAbsolute(userPath.trim()) ? path.relative(SHARED_WORKSPACE_BASE, validatedPath) : userPath
logger.info(`Getting file for path: ${userPath} -> ${validatedPath}`)

try {
Expand All @@ -84,7 +85,7 @@ export async function getFile(userPath: string): Promise<FileInfo> {
for (const entry of entries) {
children.push({
name: entry.name,
path: path.join(userPath, entry.name),
path: path.join(responsePath, entry.name),
isDirectory: entry.isDirectory,
size: entry.size,
lastModified: entry.lastModified,
Expand All @@ -93,7 +94,7 @@ export async function getFile(userPath: string): Promise<FileInfo> {

return {
name: path.basename(validatedPath),
path: userPath,
path: responsePath,
isDirectory: true,
size: 0,
children: children.sort((a, b) => {
Expand Down Expand Up @@ -127,7 +128,7 @@ export async function getFile(userPath: string): Promise<FileInfo> {

return {
name: path.basename(validatedPath),
path: userPath,
path: responsePath,
isDirectory: false,
size: stats.size,
mimeType,
Expand Down Expand Up @@ -234,14 +235,21 @@ export async function renameOrMoveFile(userPath: string, body: { newPath: string
}
}

function isWithinBase(resolved: string, basePath: string): boolean {
return resolved === basePath || resolved.startsWith(`${basePath}${path.sep}`)
}

function validatePath(userPath: string): string {
const trimmed = userPath.trim()
const normalized = path.normalize(trimmed || '.')
const fullPath = path.join(SHARED_WORKSPACE_BASE, normalized)
const resolved = path.resolve(fullPath)

const basePath = path.resolve(WORKSPACE_BASE)
if (resolved !== basePath && !resolved.startsWith(`${basePath}${path.sep}`)) {

if (path.isAbsolute(normalized) && isWithinBase(path.resolve(normalized), basePath)) {
return path.resolve(normalized)
}

const resolved = path.resolve(path.join(SHARED_WORKSPACE_BASE, normalized))
if (!isWithinBase(resolved, basePath)) {
throw { message: 'Path traversal detected', statusCode: 403 }
}

Expand Down
11 changes: 11 additions & 0 deletions backend/test/routes/files.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,17 @@ describe('File Routes', () => {
expect(getFile).toHaveBeenCalledWith('test-repo/test.txt')
})

it('should serve raw content inside a CSP sandbox', async () => {
getFile.mockResolvedValue({ ...mockFileInfo, name: 'report.html', mimeType: 'text/html', size: 13 })
vi.mocked(fileService.getRawFileContent).mockResolvedValue(Buffer.from('<h1>hi</h1>\n\n'))

const response = await app.request('/api/files?path=test-repo/report.html&raw=true')

expect(response.status).toBe(200)
expect(response.headers.get('Content-Type')).toBe('text/html')
expect(response.headers.get('Content-Security-Policy')).toBe('sandbox allow-scripts')
})

it('should return 404 when path does not exist', async () => {
getFile.mockRejectedValue({ message: 'File or directory not found', statusCode: 404 })

Expand Down
24 changes: 24 additions & 0 deletions backend/test/services/files.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -386,6 +386,30 @@ describe('files service', () => {
})

describe('path traversal protection', () => {
it('reads an absolute path that lies inside the workspace', async () => {
const absolutePath = await writeLines(`${relativeRoot}/report.html`, '<h1>hi</h1>')

const buffer = await getRawFileContent(absolutePath)

expect(buffer.toString('utf8')).toBe('<h1>hi</h1>')
})

it('returns repos-relative paths for directories requested by absolute path', async () => {
await writeLines(`${relativeRoot}/sub/a.txt`, 'a')

const result = await getFile(path.join(reposPath, relativeRoot, 'sub'))

expect(result.path).toBe(`${relativeRoot}/sub`)
expect(result.children?.map((child) => child.path)).toEqual([`${relativeRoot}/sub/a.txt`])
})

it('treats an absolute path outside the workspace as repos-relative', async () => {
await expect(getRawFileContent('/etc/passwd')).rejects.toEqual({
message: 'File not found or cannot be read',
statusCode: 404,
})
})

it('rejects traversal in getFile', async () => {
await expect(getFile('../../etc/passwd')).rejects.toEqual({
message: 'Path traversal detected',
Expand Down
33 changes: 22 additions & 11 deletions frontend/src/components/file-browser/FileBrowser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -144,27 +144,19 @@ export const FileBrowser = forwardRef<FileBrowserHandle, FileBrowserProps>(funct

const dropZoneRef = useRef<HTMLDivElement>(null)
const uploadCancelledRef = useRef(false)
const loadRequestRef = useRef(0)
const isMobile = useMobile()

const { data: initialFileData, error: initialFileError } = useFile(initialSelectedFile)

useEffect(() => {
if (initialFileData) {
setSelectedFile(initialFileData)
if (isMobile) {
setIsPreviewModalOpen(true)
onPreviewStateChange?.(true)
}
}
}, [initialFileData, isMobile, onPreviewStateChange])

useEffect(() => {
if (initialFileError) {
setError(initialFileError.message)
}
}, [initialFileError])

const loadFiles = useCallback(async (path: string) => {
const request = ++loadRequestRef.current
setLoading(true)
setError(null)

Expand All @@ -175,13 +167,15 @@ useEffect(() => {
}

const data = await response.json()
if (request !== loadRequestRef.current) return
setFiles(data)
setCurrentPath(path)
onDirectoryLoad?.({ workspaceRoot: data.workspaceRoot, currentPath: path })
} catch (err) {
if (request !== loadRequestRef.current) return
setError(err instanceof Error ? err.message : 'Failed to load files')
} finally {
setLoading(false)
if (request === loadRequestRef.current) setLoading(false)
}
}, [onDirectoryLoad])

Expand Down Expand Up @@ -448,6 +442,23 @@ useEffect(() => {
loadFiles(basePath)
}, [basePath, loadFiles])

useEffect(() => {
if (!initialFileData) return
setError(null)
if (initialFileData.isDirectory) {
setSelectedFile(null)
void loadFiles(initialFileData.path)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
return
}
setSelectedFile(initialFileData)
}, [initialFileData, loadFiles])

useEffect(() => {
if (!initialFileData || initialFileData.isDirectory || !isMobile) return
setIsPreviewModalOpen(true)
onPreviewStateChange?.(true)
}, [initialFileData, isMobile, onPreviewStateChange])

useEffect(() => {
const handleFileSaved = (event: CustomEvent<{ path: string; content?: string }>) => {
if (selectedFile && selectedFile.path === event.detail.path) {
Expand Down
82 changes: 82 additions & 0 deletions frontend/src/components/file-browser/FileBrowserSheet.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,88 @@ describe('FileBrowserSheet', () => {
})
})

describe('FileBrowser initial selection', () => {
it('navigates into an initially selected directory even when the base listing resolves later', async () => {
const directory = (path: string, children: string[]) => ({
name: path.split('/').pop(),
path,
isDirectory: true,
size: 0,
lastModified: new Date().toISOString(),
children: children.map((name) => ({ name, path: `${path}/${name}`, isDirectory: true, size: 0, lastModified: new Date().toISOString() })),
})
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
const path = new URL(String(input), 'http://localhost').searchParams.get('path')
if (path === 'repo') {
await new Promise((resolve) => setTimeout(resolve, 50))
return new Response(JSON.stringify(directory('repo', ['frontend'])), { status: 200, headers: { 'Content-Type': 'application/json' } })
}
return new Response(JSON.stringify(directory('repo/frontend', ['src'])), { status: 200, headers: { 'Content-Type': 'application/json' } })
})
vi.stubGlobal('fetch', fetchMock)
const ref = { current: null as unknown as FileBrowserHandle }

try {
render(
<FileBrowser ref={ref as never} basePath="repo" embedded={true} initialSelectedFile="repo/frontend" />,
{ wrapper: createWrapper() }
)

expect(await screen.findByText('src')).toBeInTheDocument()
await new Promise((resolve) => setTimeout(resolve, 100))
expect(ref.current.getCurrentPath()).toBe('repo/frontend')
expect(screen.queryByText('frontend')).not.toBeInTheDocument()
} finally {
vi.unstubAllGlobals()
}
})

it('does not reload the initial directory when the viewport changes', async () => {
const directory = (path: string, children: string[]) => ({
name: path.split('/').pop(),
path,
isDirectory: true,
size: 0,
lastModified: new Date().toISOString(),
children: children.map((name) => ({ name, path: `${path}/${name}`, isDirectory: true, size: 0, lastModified: new Date().toISOString() })),
})
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
const path = new URL(String(input), 'http://localhost').searchParams.get('path')
if (path === 'repo') {
await new Promise((resolve) => setTimeout(resolve, 50))
return new Response(JSON.stringify(directory('repo', ['frontend'])), { status: 200, headers: { 'Content-Type': 'application/json' } })
}
return new Response(JSON.stringify(directory('repo/frontend', ['src'])), { status: 200, headers: { 'Content-Type': 'application/json' } })
})
vi.stubGlobal('fetch', fetchMock)
const mobileSpy = vi.spyOn(useMobile, 'useMobile').mockReturnValue(false)
const ref = { current: null as unknown as FileBrowserHandle }

try {
const { rerender } = render(
<FileBrowser ref={ref as never} basePath="repo" embedded={true} initialSelectedFile="repo/frontend" />,
{ wrapper: createWrapper() }
)

expect(await screen.findByText('src')).toBeInTheDocument()
await new Promise((resolve) => setTimeout(resolve, 100))
const callsBefore = fetchMock.mock.calls.length

mobileSpy.mockReturnValue(true)
rerender(
<FileBrowser ref={ref as never} basePath="repo" embedded={true} initialSelectedFile="repo/frontend" />
)

await new Promise((resolve) => setTimeout(resolve, 100))
expect(fetchMock.mock.calls.length).toBe(callsBefore)
expect(ref.current.getCurrentPath()).toBe('repo/frontend')
} finally {
mobileSpy.mockRestore()
vi.unstubAllGlobals()
}
})
})

describe('FileBrowser navigation', () => {
it('exposes imperative handle with goBack, canGoBack, and getCurrentPath', () => {
const ref = { current: null as unknown as FileBrowserHandle }
Expand Down
15 changes: 15 additions & 0 deletions frontend/src/components/file-browser/FilePreview.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,21 @@ describe('FilePreview header buttons', () => {
expect(active.className).not.toMatch(OUTLINE_DARK_OVERRIDE)
})

it('renders HTML files in a sandboxed iframe with a raw toggle', () => {
render(<FilePreview file={textFile('report.html', 'text/html')} />)

const frame = screen.getByTitle('report.html')
expect(frame.tagName).toBe('IFRAME')
expect(frame).toHaveAttribute('sandbox', 'allow-scripts')
expect(frame.getAttribute('src')).toContain('raw=true')
expect(screen.getByTitle('Open HTML in new tab')).toHaveAttribute('target', '_blank')

fireEvent.click(screen.getByTitle('Show raw HTML'))

expect(screen.queryByTitle('report.html')).not.toBeInTheDocument()
expect(screen.getByText('# heading')).toBeInTheDocument()
})

it('keeps the success and destructive tints on the edit actions in dark mode', () => {
render(<FilePreview file={textFile('Dockerfile', 'text/plain')} />)

Expand Down
Loading