Repository navigation
feat: POST /api/sandboxes/files - file upload endpoint - #357
Conversation
…ub repos Adds a new API endpoint that accepts multipart form data to upload files to the authenticated account's sandbox GitHub repository. Supports submodule path resolution so files targeting submodule directories are committed to the correct repository. Co-Authored-By: Paperclip <noreply@paperclip.ing>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
📝 WalkthroughWalkthroughA new file upload feature enables authenticated users to upload files to GitHub repositories through an API endpoint. The implementation includes request validation, multipart form data parsing, GitHub API integration for creating or updating file contents, and structured error handling with CORS support. Changes
Sequence DiagramsequenceDiagram
participant Client
participant APIRoute as API Route<br/>(/api/sandboxes/files)
participant Validator as Request Validator
participant Handler as Upload Handler
participant GitHub as GitHub API
Client->>APIRoute: POST /api/sandboxes/files<br/>(multipart/form-data)
APIRoute->>Validator: validatePostSandboxesFilesRequest()
activate Validator
Validator->>Validator: Authenticate user
Validator->>Validator: Parse multipart form data
Validator->>Validator: Extract path, message, files
Validator-->>APIRoute: ValidatedPostSandboxesFilesParams
deactivate Validator
APIRoute->>Handler: postSandboxesFilesHandler(request)
activate Handler
Handler->>Handler: Determine account/org context
Handler->>Handler: Fetch account snapshots
Handler->>Handler: Extract GitHub repository
loop For each uploaded file
Handler->>Handler: Resolve target file path
Handler->>GitHub: GET file (check if exists)
GitHub-->>Handler: File SHA (if exists)
Handler->>GitHub: PUT file (create or update)
GitHub-->>Handler: Upload result or error
Handler->>Handler: Partition into uploaded/errors
end
Handler-->>APIRoute: NextResponse (200/500)<br/>with results & CORS headers
deactivate Handler
APIRoute-->>Client: JSON response<br/>(uploaded files, errors)
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes 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 |
There was a problem hiding this comment.
Actionable comments posted: 5
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@app/api/sandboxes/files/route.ts`:
- Around line 18-45: Add comprehensive tests for the new upload flow driven by
POST -> postSandboxesFilesHandler: create unit/integration tests that cover (1)
single-file and multi-file successful uploads asserting returned uploaded paths
and SHAs, (2) auth rejection when x-api-key/Authorization is missing or invalid,
(3) handling of non-multipart requests returning proper error, (4) invalid path
input (e.g., traversal or bad characters) returning validation error, (5)
submodule resolution pathing by stubbing snapshot/submodule lookup to ensure
files are written to the correct repo, and (6) partial and full upload failures
by mocking GitHub write errors to verify correct error/status responses;
exercise both happy and error branches and use the same handler
(postSandboxesFilesHandler) to route requests so tests fail if behavior changes.
In `@lib/github/createOrUpdateFileContent.ts`:
- Line 41: The Contents API URL is built by interpolating path raw into url
(const url = `https://api.github.com/repos/${owner}/${repo}/contents/${path}`),
which breaks for names with characters like #, ?, %, or spaces; fix by splitting
the path into segments, apply encodeURIComponent to each segment, rejoin with
'/' and use that encodedPath when constructing url (leave owner/repo as-is
unless they can contain special chars), ensuring createOrUpdateFileContent uses
the encoded URL to target the correct repo resource.
- Around line 45-79: In createOrUpdateFileContent, wrap both fetch calls (the
initial GET that yields getResponse and the subsequent PUT that yields response)
in try/catch blocks and return the expected { error: string } on failures; for
the GET: if fetch throws return an error object, if getResponse.ok use
existing.sha, if getResponse.status === 404 treat as “not found” (no
existingSha) but for any other non-ok status read response.text() and return {
error: `GET failed: ${status} ${text}` }; for the PUT: catch fetch rejections
and if response is non-ok read response.text() and return { error: `PUT failed:
${status} ${text}` } so all network/auth/rate-limit/server failures preserve the
function’s error contract and surface details.
In `@lib/sandbox/postSandboxesFilesHandler.ts`:
- Around line 41-49: The current code treats any empty array from
selectAccountSnapshots as "no repo" causing false 404s; modify
selectAccountSnapshots to surface failures (throw or return an error result) and
update postSandboxesFilesHandler to distinguish a DB/error result from a
legitimately empty snapshots array: call selectAccountSnapshots and if it
returns an error/throws return a 5xx NextResponse.json with the error details,
but only treat an empty snapshots array (no error) as the 404 "No GitHub
repository found" branch when githubRepo is null; reference
selectAccountSnapshots, snapshots, githubRepo and the NextResponse.json calls
when making these changes.
In `@lib/sandbox/validatePostSandboxesFilesRequest.ts`:
- Around line 53-76: The handler in validatePostSandboxesFilesRequest.ts
unsafely casts FormData values (path, message) and filenames, allowing File
objects to be coerced and enabling path traversal; replace the manual checks
with a Zod schema (e.g., SandboxUploadSchema) that validates path and message as
strings, validates each filename against a safe filename regex (no "..", "/", or
"\"), and enforces at least one file; parse FormData entries with proper type
guards (ensure each entry is a File before reading arrayBuffer) and after
zod.parse export the inferred type (export type SandboxUploadBody =
z.infer<typeof SandboxUploadSchema>) so callers use the typed, validated
payload.
🪄 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: 8aa973fc-d43c-4223-8292-91bca61e234d
📒 Files selected for processing (4)
app/api/sandboxes/files/route.tslib/github/createOrUpdateFileContent.tslib/sandbox/postSandboxesFilesHandler.tslib/sandbox/validatePostSandboxesFilesRequest.ts
| /** | ||
| * POST /api/sandboxes/files | ||
| * | ||
| * Uploads one or more files to the authenticated account's sandbox GitHub | ||
| * repository. Accepts multipart form data with files and an optional target | ||
| * directory path. Resolves submodule paths so files in submodule directories | ||
| * are committed to the correct repository. | ||
| * | ||
| * Authentication: x-api-key header or Authorization Bearer token required. | ||
| * | ||
| * Form data: | ||
| * - files: File[] (required) - One or more files to upload | ||
| * - path: string (optional) - Target directory path within the repository | ||
| * - message: string (optional) - Commit message (defaults to "Upload files via API") | ||
| * | ||
| * Response (200): | ||
| * - status: "success" | ||
| * - uploaded: Array<{ path: string, sha: string }> | ||
| * | ||
| * Error (400/401/403/404/500): | ||
| * - status: "error" | ||
| * - error: string | ||
| * | ||
| * @param request - The request object | ||
| * @returns A NextResponse with uploaded file details or error | ||
| */ | ||
| export async function POST(request: NextRequest): Promise<Response> { | ||
| return postSandboxesFilesHandler(request); |
There was a problem hiding this comment.
Please add endpoint coverage for the new upload flow before merging.
This route now drives auth, multipart parsing, snapshot lookup, submodule resolution, and GitHub writes, but no tests are included for the success and failure branches in the checklist. Please cover at least single/multi-file success, auth rejection, non-multipart requests, invalid path input, submodule resolution, and partial/all-upload failures.
Based on learnings: Applies to app/api/**/route.ts : Write tests for new API endpoints covering all success and error paths
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@app/api/sandboxes/files/route.ts` around lines 18 - 45, Add comprehensive
tests for the new upload flow driven by POST -> postSandboxesFilesHandler:
create unit/integration tests that cover (1) single-file and multi-file
successful uploads asserting returned uploaded paths and SHAs, (2) auth
rejection when x-api-key/Authorization is missing or invalid, (3) handling of
non-multipart requests returning proper error, (4) invalid path input (e.g.,
traversal or bad characters) returning validation error, (5) submodule
resolution pathing by stubbing snapshot/submodule lookup to ensure files are
written to the correct repo, and (6) partial and full upload failures by mocking
GitHub write errors to verify correct error/status responses; exercise both
happy and error branches and use the same handler (postSandboxesFilesHandler) to
route requests so tests fail if behavior changes.
| return { error: "GitHub token not configured" }; | ||
| } | ||
|
|
||
| const url = `https://api.github.com/repos/${owner}/${repo}/contents/${path}`; |
There was a problem hiding this comment.
Encode each repo path segment before building the Contents API URL.
path is interpolated raw into the URL here. Valid names containing #, ?, %, or spaces will change the request URL instead of the repository path, so uploads can fail or hit the wrong resource.
💡 Proposed fix
- const url = `https://api.github.com/repos/${owner}/${repo}/contents/${path}`;
+ const encodedPath = path
+ .split("/")
+ .map(encodeURIComponent)
+ .join("/");
+ const url = `https://api.github.com/repos/${owner}/${repo}/contents/${encodedPath}`;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const url = `https://api.github.com/repos/${owner}/${repo}/contents/${path}`; | |
| const encodedPath = path | |
| .split("/") | |
| .map(encodeURIComponent) | |
| .join("/"); | |
| const url = `https://api.github.com/repos/${owner}/${repo}/contents/${encodedPath}`; |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@lib/github/createOrUpdateFileContent.ts` at line 41, The Contents API URL is
built by interpolating path raw into url (const url =
`https://api.github.com/repos/${owner}/${repo}/contents/${path}`), which breaks
for names with characters like #, ?, %, or spaces; fix by splitting the path
into segments, apply encodeURIComponent to each segment, rejoin with '/' and use
that encodedPath when constructing url (leave owner/repo as-is unless they can
contain special chars), ensuring createOrUpdateFileContent uses the encoded URL
to target the correct repo resource.
| const getResponse = await fetch(url, { | ||
| headers: { | ||
| Authorization: `Bearer ${token}`, | ||
| Accept: "application/vnd.github.v3+json", | ||
| }, | ||
| }); | ||
|
|
||
| if (getResponse.ok) { | ||
| const existing = await getResponse.json(); | ||
| existingSha = existing.sha; | ||
| } | ||
|
|
||
| const body: Record<string, string> = { | ||
| message, | ||
| content: content.toString("base64"), | ||
| branch: "main", | ||
| }; | ||
|
|
||
| if (existingSha) { | ||
| body.sha = existingSha; | ||
| } | ||
|
|
||
| const response = await fetch(url, { | ||
| method: "PUT", | ||
| headers: { | ||
| Authorization: `Bearer ${token}`, | ||
| Accept: "application/vnd.github.v3+json", | ||
| "Content-Type": "application/json", | ||
| }, | ||
| body: JSON.stringify(body), | ||
| }); | ||
|
|
||
| if (!response.ok) { | ||
| const errorText = await response.text(); | ||
| return { error: `Failed to upload file: ${response.status} ${errorText}` }; |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
cat -n lib/github/createOrUpdateFileContent.tsRepository: recoupable/api
Length of output: 2863
Wrap both fetch calls in error handling to preserve the error contract and surface auth/rate-limit/server failures.
The function promises { error: string } in its return type but violates this contract:
- The initial
GETat line 45 is unwrapped—network rejections throw out of the function instead of returning an error object. - Non-404 responses (403, 401, 429, 500, etc.) are silently treated as "file doesn't exist" because only
.okis checked. This masks authentication, rate-limit, and server failures, causing thePUTto fail for the wrong reason. - The
PUTat line 67 is also unprotected from fetch rejection.
This breaks error transparency for batch operations and violates the established error-handling pattern within the same function.
🛡️ Proposed fix
+ try {
const getResponse = await fetch(url, {
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/vnd.github.v3+json",
},
});
if (getResponse.ok) {
const existing = await getResponse.json();
existingSha = existing.sha;
- }
+ } else if (getResponse.status !== 404) {
+ return {
+ error: `Failed to inspect existing file: ${getResponse.status} ${await getResponse.text()}`,
+ };
+ }
+ } catch (error) {
+ return {
+ error: `Failed to inspect existing file: ${
+ error instanceof Error ? error.message : "Unknown error"
+ }`,
+ };
+ }
+ let response: Response;
+ try {
const response = await fetch(url, {
method: "PUT",
headers: {
Authorization: `Bearer ${token}`,
Accept: "application/vnd.github.v3+json",
"Content-Type": "application/json",
},
body: JSON.stringify(body),
});
+ } catch (error) {
+ return {
+ error: `Failed to upload file: ${
+ error instanceof Error ? error.message : "Unknown error"
+ }`,
+ };
+ }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@lib/github/createOrUpdateFileContent.ts` around lines 45 - 79, In
createOrUpdateFileContent, wrap both fetch calls (the initial GET that yields
getResponse and the subsequent PUT that yields response) in try/catch blocks and
return the expected { error: string } on failures; for the GET: if fetch throws
return an error object, if getResponse.ok use existing.sha, if
getResponse.status === 404 treat as “not found” (no existingSha) but for any
other non-ok status read response.text() and return { error: `GET failed:
${status} ${text}` }; for the PUT: catch fetch rejections and if response is
non-ok read response.text() and return { error: `PUT failed: ${status} ${text}`
} so all network/auth/rate-limit/server failures preserve the function’s error
contract and surface details.
| const snapshots = await selectAccountSnapshots(snapshotAccountId); | ||
| const githubRepo = snapshots[0]?.github_repo ?? null; | ||
|
|
||
| if (!githubRepo) { | ||
| return NextResponse.json( | ||
| { status: "error", error: "No GitHub repository found for this account" }, | ||
| { status: 404, headers: getCorsHeaders() }, | ||
| ); | ||
| } |
There was a problem hiding this comment.
Don’t report snapshot lookup failures as “repository not found.”
selectAccountSnapshots() returns an empty array both when the account has no snapshot and when the Supabase query fails, so this branch will emit a false 404 during database outages. Please surface the lookup failure separately so clients get a 5xx instead of a misleading configuration error.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@lib/sandbox/postSandboxesFilesHandler.ts` around lines 41 - 49, The current
code treats any empty array from selectAccountSnapshots as "no repo" causing
false 404s; modify selectAccountSnapshots to surface failures (throw or return
an error result) and update postSandboxesFilesHandler to distinguish a DB/error
result from a legitimately empty snapshots array: call selectAccountSnapshots
and if it returns an error/throws return a 5xx NextResponse.json with the error
details, but only treat an empty snapshots array (no error) as the 404 "No
GitHub repository found" branch when githubRepo is null; reference
selectAccountSnapshots, snapshots, githubRepo and the NextResponse.json calls
when making these changes.
| const path = (formData.get("path") as string) ?? ""; | ||
| const message = (formData.get("message") as string) ?? "Upload files via API"; | ||
|
|
||
| const fileEntries = formData.getAll("files"); | ||
| if (!fileEntries.length) { | ||
| return NextResponse.json( | ||
| { status: "error", missing_fields: ["files"], error: "At least one file is required" }, | ||
| { status: 400, headers: getCorsHeaders() }, | ||
| ); | ||
| } | ||
|
|
||
| const files: { name: string; content: Buffer }[] = []; | ||
| for (const entry of fileEntries) { | ||
| if (!(entry instanceof File)) { | ||
| return NextResponse.json( | ||
| { status: "error", error: "Invalid file entry" }, | ||
| { status: 400, headers: getCorsHeaders() }, | ||
| ); | ||
| } | ||
| const arrayBuffer = await entry.arrayBuffer(); | ||
| files.push({ | ||
| name: entry.name, | ||
| content: Buffer.from(arrayBuffer), | ||
| }); |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
# First, locate and check the file in question
find . -type f -name "validatePostSandboxesFilesRequest.ts" -o -name "*Sandbox*" -type f | head -20Repository: recoupable/api
Length of output: 968
🏁 Script executed:
# Also check the general structure of lib/sandbox directory
ls -la lib/sandbox/ 2>/dev/null || echo "Directory not found"Repository: recoupable/api
Length of output: 1974
🏁 Script executed:
# Check what validation files exist and how they're structured
fd -t f "validate.*\.(ts|tsx)$" lib/ | head -20Repository: recoupable/api
Length of output: 1033
🏁 Script executed:
# Check if Zod is used in the project
rg "from.*zod|import.*zod" lib/ --type ts --type tsx | head -10Repository: recoupable/api
Length of output: 85
🏁 Script executed:
# Read the actual validatePostSandboxesFilesRequest.ts file
cat -n lib/sandbox/validatePostSandboxesFilesRequest.tsRepository: recoupable/api
Length of output: 3135
🏁 Script executed:
# Also check a few existing validation files to see how they structure schemas and types
cat -n lib/accounts/validateCreateAccountBody.tsRepository: recoupable/api
Length of output: 1406
🏁 Script executed:
# Check how other validation files handle Zod
cat -n lib/accounts/validateAddArtistBody.tsRepository: recoupable/api
Length of output: 1375
🏁 Script executed:
# Verify FormData.get() return type in TypeScript definitions
rg "FormDataEntryValue|formData.get" --type ts -A 2 -B 2 | head -30Repository: recoupable/api
Length of output: 698
🏁 Script executed:
# Check if any other validation files handle multipart/FormData
fd -t f "validate.*\.ts$" lib/ -x grep -l "FormData\|formData" {} \;Repository: recoupable/api
Length of output: 106
Unsafe multipart field handling enables path traversal; use Zod-backed validation.
FormData.get() returns FormDataEntryValue (string | File | null), so casting directly to string accepts File objects and coerces them unsafely. Filenames are also accepted without validation—no checks for .., /, \, or path separators—allowing crafted multipart requests to target unintended repository paths.
Additionally, this validator violates the coding guideline by manually validating instead of using a Zod schema and exporting an inferred type (see validateCreateAccountBody.ts for the correct pattern).
Suggested approach
- const path = (formData.get("path") as string) ?? "";
- const message = (formData.get("message") as string) ?? "Upload files via API";
+ const rawPath = formData.get("path");
+ const rawMessage = formData.get("message");
+
+ if (rawPath != null && typeof rawPath !== "string") {
+ return NextResponse.json(
+ { status: "error", error: "path must be a string" },
+ { status: 400, headers: getCorsHeaders() },
+ );
+ }
+
+ if (rawMessage != null && typeof rawMessage !== "string") {
+ return NextResponse.json(
+ { status: "error", error: "message must be a string" },
+ { status: 400, headers: getCorsHeaders() },
+ );
+ }
+
+ const path = rawPath ?? "";
+ const message = rawMessage ?? "Upload files via API";Define a Zod schema to validate path, message, and filenames (reject traversal sequences), then export the inferred type.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@lib/sandbox/validatePostSandboxesFilesRequest.ts` around lines 53 - 76, The
handler in validatePostSandboxesFilesRequest.ts unsafely casts FormData values
(path, message) and filenames, allowing File objects to be coerced and enabling
path traversal; replace the manual checks with a Zod schema (e.g.,
SandboxUploadSchema) that validates path and message as strings, validates each
filename against a safe filename regex (no "..", "/", or "\"), and enforces at
least one file; parse FormData entries with proper type guards (ensure each
entry is a File before reading arrayBuffer) and after zod.parse export the
inferred type (export type SandboxUploadBody = z.infer<typeof
SandboxUploadSchema>) so callers use the typed, validated payload.
…-upload-api" This reverts commit 0284b55.
Summary
POST /api/sandboxes/filesendpoint for uploading files to GitHub org submodulesvalidateAuthContext, resolves sandbox repo from account snapshotRelated
Test plan
Summary by CodeRabbit