Repository navigation
feat: switch sandbox file upload from multipart to blob URLs - #361
Conversation
- Accept JSON body with { url, name } file objects instead of multipart
- Download files from provided URLs, commit to GitHub, then delete blobs
- Add @vercel/blob for cleanup of temporary blob storage
- Use Zod schema validation for request body
- Update tests for new URL-based flow
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
📝 WalkthroughWalkthroughThe pull request refactors the sandbox file upload flow from multipart uploads to JSON-based requests with remote file downloads. A new Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Validator
participant Handler
participant DownloadFile
participant GitHub
participant BlobStorage
Client->>Validator: POST (JSON: files array with URLs)
Validator->>Validator: Parse JSON & validate with Zod
Validator-->>Handler: Return ValidatedParams (files: {url, name}[])
Handler->>Handler: Iterate files
loop For each file
Handler->>DownloadFile: downloadFile(url)
DownloadFile->>DownloadFile: Fetch & validate response
DownloadFile-->>Handler: Buffer or error object
alt Download success
Handler->>GitHub: createOrUpdateFileContent(content)
Handler->>Handler: Track blob URL for cleanup
else Download failed
Handler->>Handler: Record per-file error
end
end
Handler->>BlobStorage: del(blobUrlsToDelete)
BlobStorage-->>Handler: Cleanup complete
Handler-->>Client: Response with results
Estimated Code Review Effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly Related PRs
Poem
🚥 Pre-merge checks | ❌ 1❌ Failed checks (1 warning)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
E2E Test Results (Blob URL Flow)Tested against preview deployment with Validation Tests
Upload Tests
Blob Cleanup Test (E2E)
Full flow verified: Upload → Commit to GitHub → Blob cleanup all working correctly. |
| * @param url - The URL to download from | ||
| * @returns The file content as a Buffer, or an error string | ||
| */ | ||
| async function downloadFile(url: string): Promise<Buffer | { error: string }> { |
There was a problem hiding this comment.
SRP: new file for downloadFile function.
There was a problem hiding this comment.
Done — extracted to lib/sandbox/downloadFile.ts.
| path: result.data.path, | ||
| message: result.data.message, | ||
| files: result.data.files, |
There was a problem hiding this comment.
Why not simply return ...result.data?
There was a problem hiding this comment.
Good call — simplified to ...result.data.
- Move downloadFile to lib/sandbox/downloadFile.ts (SRP) - Spread result.data in validator return Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
lib/sandbox/validatePostSandboxesFilesRequest.ts (1)
8-21: Export the schema from this validate module.This file now exposes
PostSandboxesFilesBodybut keeps the actual Zod schema private, so the request contract can't be reused directly by callers or tests. Please export the schema too; if you're renaming in this area,validatePostSandboxesFilesBody.tswould match the repo convention.As per coding guidelines,
lib/**/validate*.tsfiles should "export both the schema and inferred TypeScript type" and followvalidate<EndpointName>Body.ts/validate<EndpointName>Query.tsnaming.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/sandbox/validatePostSandboxesFilesRequest.ts` around lines 8 - 21, The module defines postSandboxesFilesSchema but only exports the inferred type PostSandboxesFilesBody; export the Zod schema itself (postSandboxesFilesSchema) so callers/tests can reuse the contract, e.g., change its declaration to an exported constant and export it alongside PostSandboxesFilesBody; optionally rename the file to follow the validate<EndpointName>Body.ts convention (e.g., validatePostSandboxesFilesBody.ts) if renaming is needed to match repo guidelines.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@lib/sandbox/downloadFile.ts`:
- Around line 7-14: The downloadFile function currently accepts any URL which
enables SSRF/DoS; update downloadFile to validate the origin hostname (only
allow Vercel Blob hostnames like vercel-storage or the canonical domain you
permit) before fetching, use an AbortController to enforce a configurable fetch
timeout, and enforce a maximum download size by reading the response.body as a
stream and aborting/returning { error: 'too large' } if the cumulative bytes
exceed the limit (instead of blindly calling response.arrayBuffer()); keep
returning Buffer.from(bytes) on success and return descriptive { error: string }
objects for timeout, invalid origin, non-OK responses, or size exceeded.
In `@lib/sandbox/postSandboxesFilesHandler.ts`:
- Around line 57-83: The loop over files currently only handles explicit "{
error }" returns and lets exceptions from resolveSubmodulePath or
createOrUpdateFileContent abort processing and skip cleanup; wrap the per-file
processing (downloadFile, resolveSubmodulePath, createOrUpdateFileContent) in a
try/catch so any thrown error for a given file is caught and pushed into errors
(e.g., `${file.name}: ${err.message}`) and the loop continues, ensure
blobUrlsToDelete is still populated only for successfully uploaded files, and
change the cleanup to await Promise.allSettled on del(url) results and record
any rejections into errors (or a cleanupErrors array) instead of ignoring them;
optionally extract the entire loop plus cleanup into a helper function (e.g.,
processFilesForSandbox or handleSandboxFileUploads) to keep the parent function
small and easier to test.
---
Nitpick comments:
In `@lib/sandbox/validatePostSandboxesFilesRequest.ts`:
- Around line 8-21: The module defines postSandboxesFilesSchema but only exports
the inferred type PostSandboxesFilesBody; export the Zod schema itself
(postSandboxesFilesSchema) so callers/tests can reuse the contract, e.g., change
its declaration to an exported constant and export it alongside
PostSandboxesFilesBody; optionally rename the file to follow the
validate<EndpointName>Body.ts convention (e.g.,
validatePostSandboxesFilesBody.ts) if renaming is needed to match repo
guidelines.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 1c1ac776-c33e-4a4d-8a36-204cff2684cc
⛔ Files ignored due to path filters (3)
lib/sandbox/__tests__/postSandboxesFilesHandler.test.tsis excluded by!**/*.test.*,!**/__tests__/**and included bylib/**package.jsonis excluded by none and included by nonepnpm-lock.yamlis excluded by!**/pnpm-lock.yamland included by none
📒 Files selected for processing (3)
lib/sandbox/downloadFile.tslib/sandbox/postSandboxesFilesHandler.tslib/sandbox/validatePostSandboxesFilesRequest.ts
| export async function downloadFile(url: string): Promise<Buffer | { error: string }> { | ||
| try { | ||
| const response = await fetch(url); | ||
| if (!response.ok) { | ||
| return { error: `Failed to download: ${response.status}` }; | ||
| } | ||
| const arrayBuffer = await response.arrayBuffer(); | ||
| return Buffer.from(arrayBuffer); |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Locate the file and read its full content
echo "=== File: lib/sandbox/downloadFile.ts ==="
if [ -f "lib/sandbox/downloadFile.ts" ]; then
cat -n lib/sandbox/downloadFile.ts
else
echo "File not found, searching for it..."
fd -t f downloadFile.ts
fiRepository: recoupable/api
Length of output: 814
🏁 Script executed:
#!/bin/bash
# Find all places where downloadFile is imported/called
echo "=== Searching for downloadFile usage ==="
rg "downloadFile" -A 3 -B 1 --type ts --type tsxRepository: recoupable/api
Length of output: 143
🏁 Script executed:
#!/bin/bash
# Check if there's a sandbox configuration or any security policies
echo "=== Checking for sandbox-related config ==="
fd -t f -i config lib/sandbox/
fd -t f -i security lib/
rg "origin|allowlist|trusted|timeout|size.*limit" lib/sandbox/ -t ts --type tsxRepository: recoupable/api
Length of output: 146
🏁 Script executed:
#!/bin/bash
# Find all places where downloadFile is imported/called
echo "=== Searching for downloadFile usage ==="
rg "downloadFile" -A 3 -B 1Repository: recoupable/api
Length of output: 1148
🏁 Script executed:
#!/bin/bash
# Check if there's a sandbox configuration or any security policies
echo "=== Checking for sandbox-related files ==="
find lib/sandbox -type f 2>/dev/null
echo ""
echo "=== Searching for URL validation, origin checks, or size limits ==="
rg "origin|allowlist|trusted|timeout|maxSize|max_size|size.*limit" lib/sandbox/Repository: recoupable/api
Length of output: 5582
🏁 Script executed:
#!/bin/bash
# Check the broader sandbox directory structure and any index/exports
echo "=== Sandbox directory structure ==="
tree lib/sandbox/ -L 3 2>/dev/null || find lib/sandbox -type f
echo ""
echo "=== Check for exports from sandbox directory ==="
cat -n lib/sandbox/index.ts 2>/dev/null || echo "No index.ts"Repository: recoupable/api
Length of output: 1706
🏁 Script executed:
#!/bin/bash
# Look for callers of downloadFile in common patterns
echo "=== Searching all files for downloadFile imports ==="
rg "from.*sandbox|import.*downloadFile" | head -20Repository: recoupable/api
Length of output: 2374
🏁 Script executed:
#!/bin/bash
# Read the full postSandboxesFilesHandler.ts to see context
echo "=== postSandboxesFilesHandler.ts ==="
cat -n lib/sandbox/postSandboxesFilesHandler.tsRepository: recoupable/api
Length of output: 4160
🏁 Script executed:
#!/bin/bash
# Check the validation for POST files request
echo "=== validatePostSandboxesFilesRequest.ts ==="
cat -n lib/sandbox/validatePostSandboxesFilesRequest.tsRepository: recoupable/api
Length of output: 3072
🏁 Script executed:
#!/bin/bash
# Check if there's any URL validation or allowlist elsewhere
echo "=== Looking for GitHub or API origin patterns ==="
rg "github\.|github.com|api.github" lib/sandbox/ -iRepository: recoupable/api
Length of output: 4207
Add origin validation, timeout, and size limits to prevent authenticated SSRF and DoS via arbitrary downloads.
The function accepts any URL from an authenticated user without validating it originates from a trusted blob service. An authenticated attacker can exploit this to perform SSRF attacks against internal services or trigger DoS by downloading large files without size/timeout constraints. Add hostname validation to restrict downloads to Vercel Blob URLs, implement a fetch timeout, and enforce a maximum response size before calling arrayBuffer().
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@lib/sandbox/downloadFile.ts` around lines 7 - 14, The downloadFile function
currently accepts any URL which enables SSRF/DoS; update downloadFile to
validate the origin hostname (only allow Vercel Blob hostnames like
vercel-storage or the canonical domain you permit) before fetching, use an
AbortController to enforce a configurable fetch timeout, and enforce a maximum
download size by reading the response.body as a stream and aborting/returning {
error: 'too large' } if the cumulative bytes exceed the limit (instead of
blindly calling response.arrayBuffer()); keep returning Buffer.from(bytes) on
success and return descriptive { error: string } objects for timeout, invalid
origin, non-OK responses, or size exceeded.
| for (const file of files) { | ||
| const filePath = path ? `${path}/${file.name}` : file.name; | ||
| const content = await downloadFile(file.url); | ||
| if ("error" in content) { | ||
| errors.push(`${file.name}: ${content.error}`); | ||
| continue; | ||
| } | ||
|
|
||
| const filePath = path ? `${path}/${file.name}` : file.name; | ||
| const resolved = await resolveSubmodulePath({ githubRepo, path: filePath }); | ||
|
|
||
| const result = await createOrUpdateFileContent({ | ||
| githubRepo: resolved.githubRepo, | ||
| path: resolved.path, | ||
| content: file.content, | ||
| content, | ||
| message, | ||
| }); | ||
|
|
||
| if ("error" in result) { | ||
| errors.push(`${file.name}: ${result.error}`); | ||
| } else { | ||
| uploaded.push(result); | ||
| blobUrlsToDelete.push(file.url); | ||
| } | ||
| } | ||
|
|
||
| // Clean up temporary blobs after successful commits | ||
| await Promise.allSettled(blobUrlsToDelete.map(url => del(url))); |
There was a problem hiding this comment.
Unexpected exceptions still bypass partial-failure handling.
Only explicit { error } results are collected. If resolveSubmodulePath() or createOrUpdateFileContent() throws for one file, later files never run and the cleanup block at Line 83 is skipped. Wrap each file in try/catch, and record rejected cleanup results instead of ignoring them. Extracting Lines 57-84 into a helper would also make this policy much easier to test.
As per coding guidelines, domain functions should have single responsibility and "Keep functions under 50 lines".
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@lib/sandbox/postSandboxesFilesHandler.ts` around lines 57 - 83, The loop over
files currently only handles explicit "{ error }" returns and lets exceptions
from resolveSubmodulePath or createOrUpdateFileContent abort processing and skip
cleanup; wrap the per-file processing (downloadFile, resolveSubmodulePath,
createOrUpdateFileContent) in a try/catch so any thrown error for a given file
is caught and pushed into errors (e.g., `${file.name}: ${err.message}`) and the
loop continues, ensure blobUrlsToDelete is still populated only for successfully
uploaded files, and change the cleanup to await Promise.allSettled on del(url)
results and record any rejections into errors (or a cleanupErrors array) instead
of ignoring them; optionally extract the entire loop plus cleanup into a helper
function (e.g., processFilesForSandbox or handleSandboxFileUploads) to keep the
parent function small and easier to test.
Summary
{ url, name })@vercel/blobTest plan
🤖 Generated with Claude Code
Summary by CodeRabbit
Release Notes
New Features
Refactor