Skip to content

feat: switch sandbox file upload from multipart to blob URLs - #361

Merged
sweetmantech merged 2 commits into
testfrom
feature/sandbox-upload-blob-urls
Mar 27, 2026
Merged

sweetmantech merged 2 commits into
testfrom
feature/sandbox-upload-blob-urls

Conversation

@sweetmantech

@sweetmantech sweetmantech commented Mar 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Replace multipart form data with JSON body accepting file URLs ({ url, name })
  • API downloads from each URL, commits to GitHub, then deletes the temporary blob via @vercel/blob
  • Bypasses Vercel's 4.5MB serverless function body size limit
  • Uses Zod schema validation for request body

Test plan

  • Verify file upload via blob URLs works end-to-end
  • Verify blob cleanup after successful commit
  • Verify partial failure handling (some files fail, others succeed)
  • All 17 unit tests passing

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • New Features

    • Added remote file download capability for sandbox operations.
  • Refactor

    • File upload API now accepts JSON-formatted requests with remote file URLs instead of multipart form uploads.
    • Temporary resources are automatically cleaned up after successful file processing.

- 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>
@vercel

vercel Bot commented Mar 27, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
recoup-api Ready Ready Preview Mar 27, 2026 6:34pm

Request Review

@coderabbitai

coderabbitai Bot commented Mar 27, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

The pull request refactors the sandbox file upload flow from multipart uploads to JSON-based requests with remote file downloads. A new downloadFile utility fetches remote content from URLs, while request validation switches to JSON parsing with Zod schema validation, and the handler executes downloads before storage with cleanup of temporary blob resources.

Changes

Cohort / File(s) Summary
Download Utility
lib/sandbox/downloadFile.ts
New exported async function that fetches URLs, validates HTTP responses, converts response data to Buffer, and returns structured error objects for HTTP failures or runtime exceptions.
Request Handling Refactor
lib/sandbox/validatePostSandboxesFilesRequest.ts, lib/sandbox/postSandboxesFilesHandler.ts
Switched from multipart/form-data to JSON request bodies. Validation now uses Zod schema to enforce files as array of { url, name } objects. Handler downloads remote content via downloadFile instead of extracting from request, tracks blob URLs for cleanup via Promise.allSettled, and adjusts error handling to skip GitHub commits on download failures.

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
Loading

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly Related PRs

Poem

JSON whispers where forms once flew,
Remote downloads, fresh and true,
Zod guards the gateway wide,
Blobs scrubbed with righteous pride—
Clean code blooms! 📥✨

🚥 Pre-merge checks | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Solid & Clean Code ⚠️ Warning PR violates SOLID principles: incomplete error handling in postSandboxesFilesHandler allows exceptions from resolveSubmodulePath() and createOrUpdateFileContent() to break partial-failure guarantees; function length (100 lines) and loop complexity (33 lines) exceed guidelines; downloadFile lacks SSRF validation and timeouts. Extract file processing into helper function with comprehensive try-catch blocks; add timeout and size limits to downloadFile; implement hostname validation for trusted blob services.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/sandbox-upload-blob-urls

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@sweetmantech

Copy link
Copy Markdown
Contributor Author

E2E Test Results (Blob URL Flow)

Tested against preview deployment with BLOB_READ_WRITE_TOKEN configured.

Validation Tests

Test Expected Actual Status
POST no auth 401 401 ✅
POST empty files array 400 400 ✅
POST missing name field 400 400 ✅
OPTIONS (CORS) 200 200 ✅

Upload Tests

Test Expected Actual Status
Single file via URL (httpbin) 200 200 ✅
Batch of 3 files via URLs 200 + 3 uploaded 200 ✅
Download failure (404 URL) 500 with error 500 ✅

Blob Cleanup Test (E2E)

Step Result
Upload file to Vercel Blob ✅ Blob created
Verify blob exists (list()) ✅ Present
POST blob URL to API ✅ 200, committed to GitHub
Verify blob deleted (list()) ✅ Gone from storage

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 }> {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SRP: new file for downloadFile function.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done — extracted to lib/sandbox/downloadFile.ts.

Comment on lines +83 to +85
path: result.data.path,
message: result.data.message,
files: result.data.files,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not simply return ...result.data?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 PostSandboxesFilesBody but 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.ts would match the repo convention.

As per coding guidelines, lib/**/validate*.ts files should "export both the schema and inferred TypeScript type" and follow validate<EndpointName>Body.ts / validate<EndpointName>Query.ts naming.

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between 583bef3 and b07a0de.

⛔ Files ignored due to path filters (3)
  • lib/sandbox/__tests__/postSandboxesFilesHandler.test.ts is excluded by !**/*.test.*, !**/__tests__/** and included by lib/**
  • package.json is excluded by none and included by none
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml and included by none
📒 Files selected for processing (3)
  • lib/sandbox/downloadFile.ts
  • lib/sandbox/postSandboxesFilesHandler.ts
  • lib/sandbox/validatePostSandboxesFilesRequest.ts

Comment on lines +7 to +14
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);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 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
fi

Repository: 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 tsx

Repository: 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 tsx

Repository: 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 1

Repository: 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 -20

Repository: 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.ts

Repository: 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.ts

Repository: 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/ -i

Repository: 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.

Comment on lines 57 to +83
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)));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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.

This branch was successfully deployed

1 active deployment
Preview — b07a0de6 Deployed Mar 27, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant