Storage auth session path uses a role-blind access check, letting billing-role users escalate
Tier 2 hard typescript · cross-file · real merged PR from formbricks/formbricks #8044
Ground-truth defects
In the storage route authorizePrivateDownload, the session-authenticated path calls hasUserWorkspaceAccess, which treats the billing role identically to owner/manager and ignores per-action permission, while the API-key path on the same function correctly gates by action via hasPermission. The asymmetry lets billing-role users download private files and delete files they should be excluded from (privilege escalation).
This PR renames the private storage download/delete route from a single-segment [fileName] dynamic parameter to a catch-all [...filePath], specifically so it can also serve the newly introduced /storage/{workspaceId}/private/surveys/{surveyId}/elements/{elementId}/{file} scoped upload paths (per the PR's own description: "Scope new private upload URLs under .../surveys/{surveyId}/elements/{elementId}/..."). Both the nested route shape and the underlying storage key scheme for element-scoped uploads are new in this diff. Routing these newly introduced, more sensitive per-response upload files through the SAME entry point -- still gated only by the pre-existing, role-blind hasUserWorkspaceAccess (see d1) -- exposes them to billing-role users for the first time. This is a diff-attributable widening of exposure, distinct from d1's own (pre-existing, unchanged) check logic: unlike d1, this defect is genuinely introduced by the diff and should not be excluded from headline scoring.
`ZUploadPrivateFileRequest` gains `elementId` as a required string with no `.optional()` and no default, and its single consumer returns 400 on parse failure before destructuring the field into the signed-URL path. The published contract is not updated: the OpenAPI reference still documents the endpoint as requiring only surveyId, fileName and fileType, and the diff does not touch it.
`isScopedPrivateUploadUrl` rejects anything that is not exactly the new eight-segment shape (`if (segments?.length !== 8) return false`), and `validateClientFileUploads` fails on that. Legacy private upload URLs are four segments, so a response created before the deploy can never be updated afterwards. The same diff's `parseStorageFileUrl` is deliberately tolerant, so the delete path stays backward compatible while the validate path does not.
The change under review
diff (truncated — full diff)
@@ -11,7 +11,7 @@ const mocks = vi.hoisted(() => ({ loggerError: vi.fn(), sendToPipeline: vi.fn(), updateResponseWithQuotaEvaluation: vi.fn(), - validateFileUploads: vi.fn(), + validateClientFileUploads: vi.fn(), validateOtherOptionLengthForMultipleChoice: vi.fn(), validateResponseData: vi.fn(), })); @@ -44,7 +44,7 @@ vi.mock("@/modules/api/v2/lib/element", () => ({ })); vi.mock("@/modules/storage/utils", () => ({ - validateFileUploads: mocks.validateFileUploads, + validateClientFileUploads: mocks.validateClientFileUploads, })); vi.mock("./response", () => ({ @@ -124,7 +124,7 @@ describe("putResponseHandler", () => { mocks.getResponse.mockResolvedValue(getBaseExistingResponse()); mocks.getSurvey.mockResolvedValue(getBaseSurvey()); mocks.updateResponseWithQuotaEvaluation.mockResolvedValue(getBaseUpdatedResponse()); - mocks.validateFileUploads.mockReturnValue(true); + mocks.validateClientFileUploads.mockReturnValue(true); mocks.validateOtherOptionLengthForMultipleChoice.mockReturnValue(null); mocks.validateResponseData.mockReturnValue(null); }); @@ -278,7 +278,7 @@ describe("putResponseHandler", () => { }); test("rejects invalid file upload updates", async () => { - mocks.validateFileUploads.mockReturnValue(false); + mocks.validateClientFileUploads.mockReturnValue(false); const result = await putResponseHandler(createHandlerParams()); @@ -11,7 +11,7 @@ import { getSurvey } from "@/lib/survey/service"; import { formatValidationErrorsForV1Api, validateResponseData } from "@/modules/api/lib/validation"; import { validateOtherOptionLengthForMultipleChoice } from "@/modules/api/v2/lib/element"; import { createQuotaFullObject } from "@/modules/ee/quotas/lib/helpers"; -import { validateFileUploads } from "@/modules/storage/utils"; +import { validateClientFileUploads } from "@/modules/storage/utils"; import { updateResponseWithQuotaEvaluation } from "./response"; import { getValidatedResponseUpdateInput } from "./validated-response-update-input"; @@ -126,7 +126,8 @@ const getSurveyForResponse = async ( const validateUpdateRequest = ( existingResponse: TResponse, survey: TSurvey, - responseUpdateInput: TResponseUpdateInput + responseUpdateInput: TResponseUpdateInput, + workspaceId: string ): TRouteResult | undefined => { if (existingResponse.finished) { return { @@ -134,7 +135,15 @@ const validateUpdateRequest = ( }; } - if (!validateFileUploads(responseUpdateInput.data, survey.questions)) { + if ( + !validateClientFileUploads({ + data: responseUpdateInput.data, + workspaceId, + surveyId: survey.id, + blocks: survey.blocks, + questions: survey.questions, + }) + ) { return { response: responses.badRequestResponse("Invalid file upload response", undefined, true), }; @@ -241,7 +250,7 @@ export const putResponseHandler = async ({ }; } - const validationResult = validateUpdateRequest(existingResponse, survey, responseUpdateInput); + const validationResult = validateUpdateRequest(existingResponse, survey, responseUpdateInput, workspaceId); if (validationResult) { return validationResult; } @@ -17,7 +17,7 @@ import { resolveClientApiIds } from "@/lib/utils/resolve-client-id"; import { formatValidationErrorsForV1Api, validateResponseData } from "@/modules/api/lib/validation"; import { getIsContactsEnabled } from "@/modules/ee/license-check/lib/utils"; import { createQuotaFullObject } from "@/modules/ee/quotas/lib/helpers"; -import { validateFileUploads } from "@/modules/storage/utils"; +import { validateClientFileUploads } from "@/modules/storage/utils"; import { createResponseWithQuotaEvaluation } from "./lib/response"; export const OPTIONS = async (): Promise<Response> => { @@ -147,7 +147,15 @@ export const POST = withV1ApiWrapper({ responseInputData.singleUseId = singleUseValidationResult.singleUseId; } - if (!validateFileUploads(responseInputData.data, survey.questions)) { + if ( + !validateClientFileUploads({ + data: responseInputData.data, + workspaceId, + surveyId: survey.id, + blocks: survey.blocks, + questions: survey.questions, + }) + ) { return { response: responses.badRequestResponse("Invalid file upload response"), }; @@ -27,7 +27,7 @@ export const OPTIONS = async (): Promise<Response> => { // api endpoint for getting a s3 signed url for uploading private files // uploaded files will be private, only the user who has access to the environment can access the file // uploading private files requires no authentication -// use this to let users upload files to a file upload question response for example +// use this to let users upload files to a file upload element response for example export const POST = withV1ApiWrapper({ handler: async ({ req, props }: THandlerParams<{ params: Promise<{ workspaceId: string }> }>) => { @@ -66,7 +66,7 @@ export const POST = withV1ApiWrapper({ }; } - const { fileName, fileType, surveyId } = parsedInputResult.data; + const { fileName, fileType, surveyId, elementId } = parsedInputResult.data; const [survey, organizationId] = await Promise.all([ getSurvey(surveyId), @@ -109,18 +109,23 @@ export const POST = withV1ApiWrapper({ const fileUploadPermission = validateSurveyAllowsFileUpload({ fileName, + elementId, blocks: survey.blocks, questions: survey.questions, }); if (!fileUploadPermission.ok) { + let responseString: string = ""; + if (fileUploadPermission.reason === "no_file_upload_element") { + responseString = "Survey does not allow file uploads"; + } else if (fileUploadPermission.reason === "file_upload_element_not_found") { + responseString = "Element does not allow file uploads"; + } else { + responseString = "File extension is not allowed for this element"; + } + return { - response: responses.badRequestResponse( - fileUploadPermission.reason === "no_file_upload_question" - ? "Survey does not allow file uploads" - : "File extension is not allowed for this survey", - undefined - ), + response: responses.badRequestResponse(responseString, undefined), }; } @@ -134,7 +139,8 @@ export const POST = withV1ApiWrapper({ workspaceId, fileType, "private", - maxFileUploadSize + maxFileUploadSize, + ["surveys", surveyId, "elements", elementId] ); if (!signedUrlResponse.ok) { @@ -15,6 +15,7 @@ import { formatValidationErrorsForV1Api, validateResponseData } from "@/modules/ import { validateOtherOptionLengthForMultipleChoice } from "@/modules/api/v2/lib/element"; import { getIsContactsEnabled } from "@/modules/ee/license-check/lib/utils"; import { createQuotaFullObject } from "@/modules/ee/quotas/lib/helpers"; +import { validateClientFileUploads } from "@/modules/storage/utils"; import { createResponseWithQuotaEvaluation } from "./lib/response"; import { TResponseInputV2, ZResponseInputV2 } from "./types/response"; @@ -89,6 +90,18 @@ const validateResponseSubmission = async ( return surveyCheckResult; } + if ( + !validateClientFileUploads({ + data: responseInputData.data, + workspaceId, + surveyId: survey.id, + blocks: survey.blocks, + questions: survey.questions, + }) + ) { + return responses.badRequestResponse("Invalid file upload response", undefined, true); + } + const otherResponseInvalidQuestionId = validateOtherOptionLengthForMultipleChoice({ responseData: responseInputData.data, surveyQuestions: getElementsFromBlocks(survey.blocks), similarity index 100% rename from apps/web/app/storage/[workspaceId]/[accessType]/[fileName]/lib/audit-logs.test.ts rename to apps/web/app/storage/[workspaceId]/[accessType]/[...filePath]/lib/audit-logs.test.ts similarity index 100% rename from apps/web/app/storage/[workspaceId]/[accessType]/[fileName]/lib/audit-logs.ts rename to apps/web/app/storage/[workspaceId]/[accessType]/[...filePath]/lib/audit-logs.ts similarity index 100% rename from apps/web/app/storage/[workspaceId]/[accessType]/[fileName]/lib/auth.ts rename to apps/web/app/storage/[workspaceId]/[accessType]/[...filePath]/lib/auth.ts similarity index 85% rename from apps/web/app/storage/[workspaceId]/[accessType]/[fileName]/route.ts rename to apps/web/app/storage/[workspaceId]/[accessType]/[...filePath]/route.ts @@ -4,7 +4,7 @@ import { logger } from "@formbricks/logger"; import { ZDeleteFileRequest, ZDownloadFileRequest } from "@formbricks/types/storage"; import { responses } from "@/app/lib/api/response"; import { transformErrorToDetails } from "@/app/lib/api/validator"; -import { authorizePrivateDownload } from "@/app/storage/[workspaceId]/[accessType]/[fileName]/lib/auth"; +import { authorizePrivateDownload } from "@/app/storage/[workspaceId]/[accessType]/[...filePath]/lib/auth"; import { resolveClientApiIds } from "@/lib/utils/resolve-client-id"; import { authOptions } from "@/modules/auth/lib/authOptions"; import { applyRateLimit } from "@/modules/core/rate-limit/helpers"; @@ -15,10 +15,14 @@ import { logFileDeletion } from "./lib/audit-logs"; export const GET = async ( request: NextRequest, - props: { params: Promise<{ workspaceId: string; accessType: string; fileName: string }> } + props: { params: Promise<{ workspaceId: string; accessType: string; filePath: string[] }> } ): Promise<Response> => { const params = await props.params; - const paramValidation = ZDownloadFileRequest.safeParse(params); + const fileName = params.filePath.join("/"); + const paramValidation = ZDownloadFileRequest.safeParse({ + accessType: params.accessType, + fileName, + }); if (!paramValidation.success) { return responses.badRequestResponse( @@ -28,7 +32,7 @@ export const GET = async ( ); } - const { accessType, fileName } = paramValidation.data; + const { accessType } = paramValidation.data; const idParam = params.workspaceId; // Resolve: the URL param may be an environmentId (old uploads) or workspaceId (new uploads) @@ -72,10 +76,14 @@ export const GET = async ( export const DELETE = async ( request: NextRequest, - props: { params: Promise<{ workspaceId: string; accessType: string; fileName: string }> } + props: { params: Promise<{ workspaceId: string; accessType: string; filePath: string[] }> } ): Promise<Response> => { const params = await props.params; - const paramValidation = ZDeleteFileRequest.safeParse(params); + const fileName = params.filePath.join("/"); + const paramValidation = ZDeleteFileRequest.safeParse({ + accessType: params.accessType, + fileName, + }); if (!paramValidation.success) { const errorDetails = transformErrorToDetails(paramValidation.error); @@ -88,7 +96,7 @@ export const DELETE = async ( return responses.badRequestResponse("Fields are missing or incorrectly formatted", errorDetails, true); } - const { accessType, fileName } = paramValidation.data; + const { accessType } = paramValidation.data; const idParam = params.workspaceId; // Resolve: the URL param may be an environmentId (old uploads) or workspaceId (new uploads) @@ -140,6 +148,20 @@ export const DELETE = async ( ); if (!deleteResult.ok) { + if (!("error" in deleteResult)) { + logger.error({ deleteResult }, "Unknown delete failure result shape"); + + await logFileDeletion({ + failureReason: "unknown_delete_failure", + accessType, + userId: session?.user?.id, + workspaceId: resolved.workspaceId, + apiUrl: request.url, + }); + + return responses.internalServerErrorResponse("Failed to delete file", true); + } + const { error } = deleteResult; logger.error({ error }, "Error deleting file"); @@ -22,7 +22,7 @@ import { getElementsFromBlocks } from "@/lib/survey/utils"; import { getIsQuotasEnabled } from "@/modules/ee/license-check/lib/utils"; import { reduceQuotaLimits } from "@/modules/ee/quotas/lib/quotas"; import { deleteFile } from "@/modules/storage/service"; -import { resolveStorageUrlsInObject } from "@/modules/storage/utils"; +import { parseStorageFileUrl, resolveStorageUrlsInObject } from "@/modules/storage/utils"; import { getOrganizationIdFromWorkspaceId } from "@/modules/survey/lib/organization"; import { getOrganizationBilling } from "@/modules/survey/lib/survey"; import { ITEMS_PER_PAGE } from "../constants"; @@ -589,14 +589,18 @@ const findAndDeleteUploadedFilesInResponse = async (response: TResponse, survey: const deletionPromises = fileUrls.map(async (fileUrl) => { try { - const { pathname } = new URL(fileUrl); - const [, storageId, accessType, fileName] = pathname.split("/").filter(Boolean); + const storageFile = parseStorageFileUrl(fileUrl); - if (!storageId || !accessType || !fileName) { - throw new Error(`Invalid file path: ${pathname}`); + if (!storageFile) { + throw new Error(`Invalid storage file URL: ${fileUrl}`); } - return deleteFile(storageId, accessType as "private" | "public", fileName, survey.workspaceId); + return deleteFile( + storageFile.storageId, + storageFile.accessType, + storageFile.fileName, + survey.workspaceId + ); } catch (error) { logger.error(error, `Failed to delete file ${fileUrl}`); } @@ -26,7 +26,7 @@ export const fileUploadQuestion: Survey["questions"][number] = { export const responseData: Response["data"] = { [openTextQuestion.id]: "Open Text Answer", [fileUploadQuestion.id]: [ - `https://example.com/dummy/${workspaceId}/private/file1.png`, - `https://example.com/dummy/${workspaceId}/private/file2.pdf`, + `https://example.com/storage/${workspaceId}/private/file1.png`, + `https://example.com/storage/${workspaceId}/private/file2.pdf`, ], }; @@ -4,6 +4,7 @@ import { Result, okVoid } from "@formbricks/types/error-handlers"; import { TSurveyQuestionTypeEnum } from "@formbricks/types/surveys/types"; import { ApiErrorResponseV2 } from "@/modules/api/v2/types/api-error"; import { deleteFile } from "@/modules/storage/service"; +import { parseStorageFileUrl } from "@/modules/storage/utils"; export const findAndDeleteUploadedFilesInResponse = async ( responseData: Response["data"], @@ -24,13 +25,12 @@ export const findAndDeleteUploadedFilesInResponse = async ( const deletionPromises = fileUrls.map(async (fileUrl) => { try { - const { pathname } = new URL(fileUrl); - const [, storageId, accessType, fileName] = pathname.split("/").filter(Boolean); + const storageFile = parseStorageFileUrl(fileUrl); - if (!storageId || !accessType || !fileName) { - throw new Error(`Invalid file path: ${pathname}`); + if (!storageFile) { + throw new Error(`Invalid storage file URL: ${fileUrl}`); } - return deleteFile(storageId, accessType as "private" | "public", fileName, workspaceId); + return deleteFile(storageFile.storageId, storageFile.accessType, storageFile.fileName, workspaceId); } catch (error) { logger.error({ error, fileUrl }, "Failed to delete file"); } @@ -117,6 +117,61 @@ describe("storage service", () => { } }); + test("should generate scoped private upload URL when path segments are provided", async () => { + const mockSignedUrlResponse = { + ok: true, + data: { + signedUrl: "https://s3.example.com/upload", + presignedFields: { key: "value" }, + }, + } as MockedSignedUploadReturn; + + vi.mocked(getSignedUploadUrl).mockResolvedValue(mockSignedUrlResponse); + + const result = await getSignedUrlForUpload( + "test-doc.pdf", + "ws-123", + "application/pdf", + "private" as TAccessType, + 1024 * 1024 * 10, + ["surveys", "survey-123", "elements", "element-123"] + ); + + expect(result.ok).toBe(true); + if (result.ok) { + expect(result.data.fileUrl).toBe( + `/storage/ws-123/private/surveys/survey-123/elements/element-123/test-doc--fid--${mockUUID}.pdf` + ); + } + + expect(getSignedUploadUrl).toHaveBeenCalledWith( + `test-doc--fid--${mockUUID}.pdf`, + "application/pdf", + "ws-123/private/surveys/survey-123/elements/element-123", + 1024 * 1024 * 10 + ); + }); + + test.each(["", ".", "..", "bad segment", "bad/segment", "bad\\segment", "bad?segment", "bad#segment"])( + "should reject unsafe scoped private upload path segment %s", + async (unsafeSegment) => { + const result = await getSignedUrlForUpload( + "test-doc.pdf", + "ws-123", + "application/pdf", + "private" as TAccessType, + 1024 * 1024 * 10, + ["surveys", unsafeSegment] + ); + + expect(result.ok).toBe(false); + if (!result.ok) { + expect(result.error.code).toBe(StorageErrorCode.InvalidInput); + } + expect(getSignedUploadUrl).not.toHaveBeenCalled(); + } + ); + test("should properly sanitize filenames with special characters like # in URL", async () => { const mockSignedUrlResponse = { ok: true, @@ -10,15 +10,18 @@ import { getSignedUploadUrl, } from "@formbricks/storage"; import { Result, err, ok } from "@formbricks/types/error-handlers"; -import { TAccessType } from "@formbricks/types/storage"; +import { type TAccessType } from "@formbricks/types/storage"; import { sanitizeFileName } from "./utils"; +const SAFE_FILE_PATH_SEGMENT = /^[A-Za-z0-9_-]+$/; + export const getSignedUrlForUpload = async ( fileName: string, workspaceId: string, fileType: string, accessType: TAccessType, - maxFileUploadSize: number = 1024 * 1024 * 10 // 10MB + maxFileUploadSize: number = 1024 * 1024 * 10, // 10MB + filePathSegments: string[] = [] ): Promise< Result< { @@ -34,17 +37,19 @@ export const getSignedUrlForUpload = async ( if (!safeFileName) { return err({ code: StorageErrorCode.InvalidInput }); } + + if (filePathSegments.some((segment) => !SAFE_FILE_PATH_SEGMENT.test(segment))) { + return err({ code: StorageErrorCode.InvalidInput }); + } + + const encodedFilePathSegments = filePathSegments.map((segment) => encodeURIComponent(segment)); const fileNameWithoutExtension = safeFileName.split(".").slice(0, -1).join("."); const fileExtension = safeFileName.split(".").pop(); const updatedFileName = `${fileNameWithoutExtension}--fid--${randomUUID()}.${fileExtension}`; + const filePath = [workspaceId, accessType, ...filePathSegments].join("/");
Leaderboard for this case
hard · 0 of 9 bots fully caught it (0% solve rate) · 44% avg coverage.
| # | Bot | Result | Caught | Coverage | Findings | False alarms |
|---|---|---|---|---|---|---|
| 1 | Drape (Review) | partial | 2/3 | 50.0% | 2 | 0 |
| 2 | greptile | partial | 2/3 | 50.0% | 2 | 0 |
| 3 | Mjolnir (Opus 5.5) | partial | 2/3 | 50.0% | 3 | 0 |
| 4 | Claude Code (Opus 5.5) | partial | 2/3 | 50.0% | 3 | 1 |
| 5 | Drape (Deep Review) | partial | 2/3 | 50.0% | 3 | 1 |
| 6 | Cubic | partial | 2/3 | 50.0% | 5 | 2 |
| 7 | cursor | miss | 0/3 | 0.0% | 1 | 0 |
| 8 | Mjolnir (Sonnet 5.5) | miss | 0/3 | 0.0% | 0 | 0 |
| 9 | qodo | miss | 0/3 | 0.0% | 0 | 0 |
Bot results
Claude Code (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d2 | high | ✗ | — |
| d3 | medium | ✓ | exact |
| d4 | medium | ✓ | exact |
| d1 | high | ✗ | — |
The new catch-all route does join `filePath` segments into the storage key without validating each segment. But the backend here is S3, which treats keys literally and does not resolve `..`. Next.js/URL parsing normalizes literal `..` before routing. Encoded separators were already decoded by `getFileStreamForDownload`'s `decodeURIComponent` before this change, so that path is not new. The claimed traversal depends on a hypothetical backend that normalizes paths, and nothing shown triggers it today. I can neither confirm nor rule out a real failure. [invalid: self-contradiction] [consensus 3/3: invalid=3]
raw comments (3)
`elementId` is now required in `ZUploadPrivateFileRequest`. The public client storage endpoint `/api/v1/client/[workspaceId]/storage` will return 400 to any caller that doesn't send it. That includes cached or older builds of the surveys bundle or SDK still running in users' browsers or apps during and after a deploy, and any integration that calls this endpoint directly. Those file uploads will start failing with no fallback. Consider keeping `elementId` optional for a deprecation window, falling back to the old survey-wide extension check and unscoped path.
`validateClientFileUploads` rejects every file-upload value that isn't exactly `/storage/<workspaceId>/private/surveys/<surveyId>/elements/<elementId>/<file>`. Several valid cases now get a 400: (1) a partially completed response whose upload happened before this deploy (unscoped `/storage/<id>/private/<file>`), or whose URL uses the legacy environmentId prefix, which is still supported for downloads; (2) absolute URLs, e.g. `https://app/storage/...`, which `getOriginalFileNameFromUrl` and `parseStorageFileUrl` explicitly support; (3) client-API users who submit externally hosted file URLs. The v2 client responses route did no file validation before, so it is now newly strict too. This is a behavior-breaking regression for in-flight respondents and existing integrations.
The catch-all `filePath` segments are joined with `/` and passed into the storage key (`${id}/${accessType}/${fileName}`). Nothing rejects `..` or empty segments, or segments containing encoded separators (e.g. `%2F` or `%2E%2E`, which get decoded again by `decodeURIComponent` in `getFileStreamForDownload`). The workspace prefix is still applied and S3 doesn't normalize keys, so the impact is limited. Still, the route now accepts arbitrary multi-level keys under the workspace prefix with no validation, and any non-S3 or S3-compatible backend that normalizes paths could be exposed to traversal. Each segment should be validated, e.g. against the same `SAFE_FILE_PATH_SEGMENT` pattern, except the last one.
Cubic · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d2 | high | ✗ | — |
| d3 | medium | ✓ | off by one |
| d4 | medium | ✓ | exact |
| d1 | high | ✗ | — |
The old code also used the storageId taken from the URL as the S3 prefix, so the cross-workspace deletion risk existed before this change. The change actually narrows it, because client submissions are now required to use scoped URLs for their own workspace. [invalid: contradiction] [consensus 5/5: invalid=5]
The old deletion path took the raw `URL.pathname` and never decoded it either, so encoded filenames already produced the wrong S3 key. Relative URLs failed outright before this change. Deletion fails the same way with or without the change. [invalid: contradiction] [consensus 5/5: invalid=5]
Before the change, the handlers used the zod-trimmed `fileName` from `paramValidation.data`. Now they use the raw joined path, so input with leading or trailing whitespace resolves to a different S3 key than it did before. [grounded: diff] [consensus 5/5: valid=5]
raw comments (6)
<!-- cubic:v=6819a634-20be-47d7-9193-7f178aec8800 -->
<!-- cubic:review-run=46bcb7c7-ee7c-5690-ad0c-24fa752c5885 -->
<!-- metadata:{"confidence":8} -->
P1: Existing v1 clients that upload without the new `elementId` field now receive a validation error before the storage handler runs, breaking file uploads for older SDK deployments. Preserve the v1 contract with a compatibility path or version the endpoint before making element-scoped uploads mandatory.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At packages/types/storage.ts, line 128:
<comment>Existing v1 clients that upload without the new `elementId` field now receive a validation error before the storage handler runs, breaking file uploads for older SDK deployments. Preserve the v1 contract with a compatibility path or version the endpoint before making element-scoped uploads mandatory.</comment>
<file context>
@@ -124,6 +125,14 @@ export const ZUploadPrivateFileRequest = z
fileType: z.string().trim().min(1),
allowedFileExtensions: z.array(ZAllowedFileExtension).optional(),
surveyId: z.cuid2(),
+ elementId: z
+ .string()
+ .trim()
</file context>
```
</details>
<!-- cubic:v=21419f6d-b52e-4ddb-93dc-bcc5ace70b83 -->
<!-- cubic:review-run=46bcb7c7-ee7c-5690-ad0c-24fa752c5885 -->
<!-- metadata:{"confidence":9} -->
P1: When a response contains a storage URL from another workspace, `parseStorageFileUrl` preserves that URL's `storageId`, and response deletion uses it as the primary S3 key prefix. Validate the parsed storage ID against the response's workspace before calling `deleteFile`, including for absolute URLs.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/modules/storage/utils.ts, line 221:
<comment>When a response contains a storage URL from another workspace, `parseStorageFileUrl` preserves that URL's `storageId`, and response deletion uses it as the primary S3 key prefix. Validate the parsed storage ID against the response's workspace before calling `deleteFile`, including for absolute URLs.</comment>
<file context>
@@ -178,6 +201,127 @@ export const validateSurveyAllowsFileUpload = ({
+ let pathname: string;
+
+ try {
+ pathname = fileUrl.startsWith("/storage/") ? fileUrl : new URL(fileUrl).pathname;
+ } catch {
+ return null;
</file context>
```
</details>
<!-- cubic:v=b93477e9-36c2-48dd-b653-f5a42155d019 -->
<!-- cubic:review-run=46bcb7c7-ee7c-5690-ad0c-24fa752c5885 -->
<!-- metadata:{"confidence":9} -->
P2: When an uploaded filename requires URL encoding, response deletion uses the encoded filename as the S3 key and silently fails. Decode each pathname segment before returning `fileName` from `parseStorageFileUrl` (and return `null` for malformed encodings).
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/modules/storage/utils.ts, line 232:
<comment>When an uploaded filename requires URL encoding, response deletion uses the encoded filename as the S3 key and silently fails. Decode each pathname segment before returning `fileName` from `parseStorageFileUrl` (and return `null` for malformed encodings).</comment>
<file context>
@@ -178,6 +201,127 @@ export const validateSurveyAllowsFileUpload = ({
+ const [storageSegment, storageId, accessType, ...fileNameSegments] = pathWithoutSearch
+ .split("/")
+ .filter(Boolean);
+ const fileName = fileNameSegments.join("/");
+
+ if (
</file context>
```
</details>
```suggestion
let fileName: string;
try {
fileName = decodeURIComponent(fileNameSegments.join("/"));
} catch {
return null;
}
```
<!-- cubic:v=1eb617bf-9719-4667-a911-853dab1284de -->
<!-- cubic:review-run=46bcb7c7-ee7c-5690-ad0c-24fa752c5885 -->
<!-- metadata:{"confidence":8} -->
P2: When the final path segment has leading or trailing whitespace, validation trims it but GET and DELETE continue using the untrimmed joined path, so valid requests look up or delete the wrong S3 key. Use `paramValidation.data.fileName` (or trim the joined value) in both handlers.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/app/storage/[workspaceId]/[accessType]/[...filePath]/route.ts, line 21:
<comment>When the final path segment has leading or trailing whitespace, validation trims it but GET and DELETE continue using the untrimmed joined path, so valid requests look up or delete the wrong S3 key. Use `paramValidation.data.fileName` (or trim the joined value) in both handlers.</comment>
<file context>
@@ -15,10 +15,14 @@ import { logFileDeletion } from "./lib/audit-logs";
): Promise<Response> => {
const params = await props.params;
- const paramValidation = ZDownloadFileRequest.safeParse(params);
+ const fileName = params.filePath.join("/");
+ const paramValidation = ZDownloadFileRequest.safeParse({
+ accessType: params.accessType,
</file context>
```
</details>
```suggestion
const fileName = params.filePath.join("/").trim();
```
<!-- cubic:v=020524db-5b6c-4c18-bcdb-3e769264eb7f -->
<!-- cubic:review-run=46bcb7c7-ee7c-5690-ad0c-24fa752c5885 -->
<!-- metadata:{"confidence":8} -->
P2: When a client submits a file URL produced by the legacy unscoped upload flow, this endpoint rejects the response as an invalid file upload. Accept legacy private paths during a migration window, or migrate existing URLs before enforcing scoped paths.
<details>
<summary>Prompt for AI agents</summary>
```text
Check if this issue is valid — if so, understand the root cause and fix it. At apps/web/app/api/v1/client/[workspaceId]/responses/route.ts, line 151:
<comment>When a client submits a file URL produced by the legacy unscoped upload flow, this endpoint rejects the response as an invalid file upload. Accept legacy private paths during a migration window, or migrate existing URLs before enforcing scoped paths.</comment>
<file context>
@@ -147,7 +147,15 @@ export const POST = withV1ApiWrapper({
- if (!validateFileUploads(responseInputData.data, survey.questions)) {
+ if (
+ !validateClientFileUploads({
+ data: responseInputData.data,
+ workspaceId,
</file context>
```
</details>
<!-- cubic:review-summary:start -->
**5 issues found** across 22 files
<!-- cubic:review-summary:end -->
<details>
<summary>Prompt for AI agents (unresolved issues)</summary>
```text
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="packages/types/storage.ts">
<violation number="1" location="packages/types/storage.ts:128">
P1: Existing v1 clients that upload without the new `elementId` field now receive a validation error before the storage handler runs, breaking file uploads for older SDK deployments. Preserve the v1 contract with a compatibility path or version the endpoint before making element-scoped uploads mandatory.</violation>
</file>
<file name="apps/web/modules/storage/utils.ts">
<violation number="1" location="apps/web/modules/storage/utils.ts:221">
P1: When a response contains a storage URL from another workspace, `parseStorageFileUrl` preserves that URL's `storageId`, and response deletion uses it as the primary S3 key prefix. Validate the parsed storage ID against the response's workspace before calling `deleteFile`, including for absolute URLs.</violation>
<violation number="2" location="apps/web/modules/storage/utils.ts:232">
P2: When an uploaded filename requires URL encoding, response deletion uses the encoded filename as the S3 key and silently fails. Decode each pathname segment before returning `fileName` from `parseStorageFileUrl` (and return `null` for malformed encodings).</violation>
</file>
<file name="apps/web/app/storage/[workspaceId]/[accessType]/[...filePath]/route.ts">
<violation number="1" location="apps/web/app/storage/[workspaceId]/[accessType]/[...filePath]/route.ts:21">
P2: When the final path segment has leading or trailing whitespace, validation trims it but GET and DELETE continue using the untrimmed joined path, so valid requests look up or delete the wrong S3 key. Use `paramValidation.data.fileName` (or trim the joined value) in both handlers.</violation>
</file>
<file name="apps/web/app/api/v1/client/[workspaceId]/responses/route.ts">
<violation number="1" location="apps/web/app/api/v1/client/[workspaceId]/responses/route.ts:151">
P2: When a client submits a file URL produced by the legacy unscoped upload flow, this endpoint rejects the response as an invalid file upload. Accept legacy private paths during a migration window, or migrate existing URLs before enforcing scoped paths.</violation>
</file>
```
</details>
<sub>Reply with feedback, questions, or to request a fix.<br /><br />[Re-trigger cubic](https://www.cubic.dev/action/re-review/pr/drape-io/crbench-cubic-2026-09/37/ai_pr_review_github_delivery_dac357f971a1d6e9c4127f362637d880d7dff53643e06b8d2ba4d1072c62fc02?returnTo=https%3A%2F%2Fgithub.com%2Fdrape-io%2Fcrbench-cubic-2026-09%2Fpull%2F37)</sub>
<!-- cubic:review-post:ai_pr_review_github_delivery_dac357f971a1d6e9c4127f362637d880d7dff53643e06b8d2ba4d1072c62fc02:cc128105436d627efdf38e4446e75458044de8af:46bcb7c7-ee7c-5690-ad0c-24fa752c5885 -->
cursor · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d2 | high | ✗ | — |
| d3 | medium | ✗ | — |
| d4 | medium | ✗ | — |
| d1 | high | ✗ | — |
The new `parseStorageFileUrl` returns the file name with its percent-encoding intact. Upload builds `fileUrl` with `encodeURIComponent(updatedFileName)`, but the S3 key uses the raw name, so a name with spaces (which `sanitizeFileName` keeps) is stored with a space and the URL holds `%20`. `deleteFile` builds `${primaryId}/${accessType}/${fileName}` without decoding, so it looks up the wrong key and the file is left behind. The DELETE route and `getFileStreamForDownload` both call `decodeURIComponent` first, which shows decoding is expected. The old code also failed here: `new URL` threw on relative URLs, and absolute pathnames stayed encoded. I still count this as introduced because the bug is in the parser this change adds, which was written to handle these URLs. [grounded: diff] [consensus 5/5: valid=5]
raw comments (2)
### Relative storage URLs skip filename decoding
**Medium Severity**
<!-- DESCRIPTION START -->
`parseStorageFileUrl` keeps encoded path characters for relative `/storage/...` URLs instead of decoding them. Upload stores an encoded `fileUrl` while the S3 object key uses the raw filename, so response deletion looks up the wrong key and leaves private files behind when names contain spaces or other encoded characters.
<!-- DESCRIPTION END -->
<!-- BUGBOT_BUG_ID: c7206511-4015-4831-b471-8cd9b0a90831 -->
<!-- LOCATIONS START
apps/web/modules/storage/utils.ts#L216-L244
apps/web/lib/response/service.ts#L589-L603
apps/web/modules/api/v2/management/responses/[responseId]/lib/utils.ts#L25-L33
LOCATIONS END -->
<details>
<summary>Additional Locations (2)</summary>
- [`apps/web/lib/response/service.ts#L589-L603`](https://github.com/drape-io/crbench-cursor-2026-09/blob/8fff2887857e1389c12896b7c380c45a45c0fa7f/apps/web/lib/response/service.ts#L589-L603)
- [`apps/web/modules/api/v2/management/responses/[responseId]/lib/utils.ts#L25-L33`](https://github.com/drape-io/crbench-cursor-2026-09/blob/8fff2887857e1389c12896b7c380c45a45c0fa7f/apps/web/modules/api/v2/management/responses/[responseId]/lib/utils.ts#L25-L33)
</details>
<div><a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmZlMjUzNGRiLTVlYjQtNDg3YS1hZTY1LWI0YmZlMDM3OTFlYyIsImVuY3J5cHRpb25LZXkiOiJUdjBaRDM5REFsRWhuWXhTUlJ0bGxVenpmTS1BTHpBcFdwdGJ5R2s5OGdrIiwiYnJhbmNoIjoidDItZm9ybWJyaWNrcy04MDQ0IiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a> <a href="https://cursor.com/agents?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OmZlMjUzNGRiLTVlYjQtNDg3YS1hZTY1LWI0YmZlMDM3OTFlYyIsImVuY3J5cHRpb25LZXkiOiJUdjBaRDM5REFsRWhuWXhTUlJ0bGxVenpmTS1BTHpBcFdwdGJ5R2s5OGdrIiwiYnJhbmNoIjoidDItZm9ybWJyaWNrcy04MDQ0IiwicmVwb093bmVyIjoiZHJhcGUtaW8iLCJyZXBvTmFtZSI6ImNyYmVuY2gtY3Vyc29yLTIwMjYtMDkiLCJwck51bWJlciI6MzgsImNvbW1pdFNoYSI6IjhmZmYyODg3ODU3ZTEzODljMTI4OTZiN2MzODBjNDVhNDVjMGZhN2YiLCJwcm92aWRlciI6ImdpdGh1YiJ9fQ" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-web-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-web-light.png"><img alt="Fix in Web" width="99" height="28" src="https://cursor.com/assets/images/fix-in-web-dark.png"></picture></a></div>
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 8fff2887857e1389c12896b7c380c45a45c0fa7f. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- BUGBOT_REVIEW -->
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
<!-- BUGBOT_FIX_ALL -->
<a href="https://cursor.com/open?link=eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9BTExfSU5fQ1VSU09SIiwiZGF0YSI6eyJyZWRpc0tleSI6ImJ1Z2JvdC1tdWx0aToyMmMzODVlZC0zNGY4LTQ1NGMtYWI2NS00Y2Q5N2M2NWI0Y2IiLCJlbmNyeXB0aW9uS2V5IjoiOXlWSTk4aVNsMFllekdXaUE3anU5cUFSU2FsVlFzMU1qaWcwXzhMU09vRSIsImJyYW5jaCI6InQyLWZvcm1icmlja3MtODA0NCIsInJlcG9Pd25lciI6ImRyYXBlLWlvIiwicmVwb05hbWUiOiJjcmJlbmNoLWN1cnNvci0yMDI2LTA5IiwicHJvdmlkZXIiOiJnaXRodWIifX0" target="_blank" rel="noopener noreferrer"><picture><source media="(prefers-color-scheme: dark)" srcset="https://cursor.com/assets/images/fix-in-cursor-dark.png"><source media="(prefers-color-scheme: light)" srcset="https://cursor.com/assets/images/fix-in-cursor-light.png"><img alt="Fix All in Cursor" width="115" height="28" src="https://cursor.com/assets/images/fix-in-cursor-dark.png"></picture></a>
<!-- /BUGBOT_FIX_ALL -->
<!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_BEGIN -->
<sup>❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- BUGBOT_AUTOFIX_REVIEW_FOOTNOTE_END -->
<sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 8fff2887857e1389c12896b7c380c45a45c0fa7f. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup>
Drape (Deep Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d2 | high | ✗ | — |
| d3 | medium | ✓ | exact |
| d4 | medium | ✓ | exact |
| d1 | high | ✗ | — |
parseStorageFileUrl does not decode the file name, so a name containing %20 would not match the S3 key. The removed code passed the same encoded pathname segment to deleteFile, so this failure happened identically before the change. [invalid: contradiction] [consensus 3/4: invalid=3, valid=1]
raw comments (3)
**Uploaded files with spaces not deleted with response**
`parseStorageFileUrl` returns the file name still URL-encoded (`my%20report…`), but the S3 key holds the raw name. Response deletion then targets a key that doesn't exist and leaves the private file behind. `decodeURIComponent` the file-name segments in `parseStorageFileUrl`, as the download route does.
```
apps/web/modules/storage/utils.ts:217 export const parseStorageFileUrl = (fileUrl: string): TParsedStorageFileUrl | null => {
apps/web/modules/storage/utils.ts:218 let pathname: string;
apps/web/modules/storage/utils.ts:220 try {
apps/web/modules/storage/utils.ts:221 pathname = fileUrl.startsWith("/storage/") ? fileUrl : new URL(fileUrl).pathname;
apps/web/modules/storage/service.ts:49 const updatedFileName = `${fileNameWithoutExtension}--fid--${randomUUID()}.${fileExtension}`;
apps/web/modules/storage/service.ts:50 const filePath = [workspaceId, accessType, ...filePathSegments].join("/");
apps/web/modules/storage/service.ts:52 const signedUrlResult = await getSignedUploadUrl(updatedFileName, fileType, filePath, maxFileUploadSize);
apps/web/modules/storage/service.ts:54 if (!signedUrlResult.ok) {
apps/web/modules/storage/service.ts:55 return signedUrlResult;
apps/web/modules/storage/service.ts:56 }
```
**Responses with earlier flat file URLs are rejected**
isScopedPrivateUploadUrl accepts only 8-segment surveys/<id>/elements/<id> paths. A response that holds a file uploaded before deploy (`/storage/<ws>/private/<file>`) now gets 400 on POST/PUT, so the respondent's answers are lost. Accept the legacy flat private path for the same workspace during a transition period.
```
apps/web/modules/storage/utils.ts:204 const getStorageUrlPathSegments = (fileUrl: string): string[] | null => {
apps/web/modules/storage/utils.ts:205 if (!fileUrl.startsWith("/storage/")) return null;
apps/web/modules/storage/utils.ts:207 const pathWithoutSearch = fileUrl.split(/[?#]/)[0];
apps/web/modules/storage/utils.ts:208 return pathWithoutSearch.split("/").filter(Boolean);
apps/web/modules/storage/utils.ts:209 };
apps/web/modules/storage/utils.ts:103 (base) if (!question || question.type !== TSurveyQuestionTypeEnum.FileUpload) continue;
apps/web/modules/storage/utils.ts:105 (base) const fileUrls = data[key];
apps/web/modules/storage/utils.ts:107 (base) if (!Array.isArray(fileUrls) || !fileUrls.every((url) => typeof url === "string")) return false;
apps/web/modules/storage/utils.ts:109 (base) for (const fileUrl of fileUrls) {
apps/web/modules/storage/utils.ts:110 (base) if (!validateSingleFile(fileUrl, question.allowedFileExtensions)) return false;
```
**Uploads from older survey bundles fail with 400**
`elementId` is now required in `ZUploadPrivateFileRequest`. A client that doesn't send it, such as a page loaded before the deploy or a cached older build, can no longer upload files. Make `elementId` optional for a transition period, falling back to the old survey-wide check.
```
packages/types/storage.ts:128 elementId: z
packages/types/storage.ts:129 .string()
packages/types/storage.ts:130 .trim()
packages/types/storage.ts:131 .min(1)
packages/types/storage.ts:132 .regex(
packages/types/storage.ts:133 /^[a-zA-Z0-9_-]+$/,
packages/types/storage.ts:134 "Element id must contain only alphanumeric characters, hyphens, or underscores"
packages/types/storage.ts:135 ),
```
Drape (Review) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d2 | high | ✗ | — |
| d3 | medium | ✓ | exact |
| d4 | medium | ✓ | exact |
| d1 | high | ✗ | — |
raw comments (2)
**Pre-upgrade flat file URLs rejected on response update**
A PUT whose block data holds a file URL issued before this change gets a 400 instead of saving. `isScopedPrivateUploadUrl` only accepts the new 8-segment surveys/elements path. This happens when a respondent uploads before the deploy and submits that block after it. Accept legacy flat `/storage/<id>/private/<file>` URLs as well.
```
apps/web/modules/storage/utils.ts:290 }: {
apps/web/modules/storage/utils.ts:291 data?: TResponseData;
apps/web/modules/storage/utils.ts:292 workspaceId: string;
apps/web/modules/storage/utils.ts:293 surveyId: string;
packages/surveys/src/lib/survey-state.ts:99 data: { ...this.responseAcc.data, ...responseUpdate.data },
```
**Upload endpoint rejects clients that omit elementId**
`elementId` is now required in `ZUploadPrivateFileRequest`. Already-loaded survey bundles and older SDKs don't send it, so their file uploads now get a 400. Fall back to the old unscoped behaviour when `elementId` is absent.
```
packages/types/storage.ts:128 elementId: z
packages/types/storage.ts:129 .string()
packages/types/storage.ts:130 .trim()
packages/types/storage.ts:131 .min(1)
packages/types/storage.ts:122 export const ZUploadPrivateFileRequest = z
packages/types/storage.ts:123 .object({
packages/types/storage.ts:124 fileName: z.string().trim().min(1),
packages/types/storage.ts:125 fileType: z.string().trim().min(1),
packages/types/storage.ts:126 allowedFileExtensions: z.array(ZAllowedFileExtension).optional(),
packages/types/storage.ts:127 surveyId: z.cuid2(),
```
greptile · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d2 | high | ✗ | — |
| d3 | medium | ✓ | off by one |
| d4 | medium | ✓ | off by one |
| d1 | high | ✗ | — |
raw comments (3)
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Required field breaks clients**
Older SDK versions send `surveyId` but not `elementId` when requesting an upload URL. Making `elementId` required causes schema validation to reject those requests before the handler runs, so file uploads stop working until those clients are upgraded. Preserve the previous request shape during the rollout or provide a compatibility path.
<a href="#"><img alt="P1" src="https://greptile-static-assets.s3.amazonaws.com/badges/p1.svg?v=9" align="top"></a> **Legacy uploads block updates**
Pending or offline updates created before this rollout can contain unscoped URLs such as `/storage/{id}/private/{file}`. Replaying such an update now fails this exact eight-segment check, leaving the update unsent and potentially preventing an in-progress response from finishing. Accept legacy URLs already issued by the service or migrate them before applying the new check.
<h3>Greptile Summary</h3>
This PR binds client file uploads to individual survey elements, introduces survey/element-scoped storage keys, supports nested storage download and deletion paths, and strengthens response upload validation.
- Adds `elementId` to upload requests and validates extensions against the selected element.
- Stores new private uploads under `surveys/{surveyId}/elements/{elementId}`.
- Changes the storage route to a catch-all path for nested object keys.
- Updates response creation, updates, cleanup helpers, client code, mocks, and storage tests.
- The rollout currently breaks older upload clients and replay of pending updates containing legacy upload URLs.
<h3>Confidence Score: 3/5</h3>
This PR is not safe to merge until older upload clients and pending response updates containing legacy file URLs have a compatible rollout path.
The backend immediately requires a field unavailable to previously deployed clients, and response updates now reject legacy URLs that may still exist in persisted offline queues; both paths can prevent users from uploading files or completing responses.
**Files Needing Attention:** packages/types/storage.ts; apps/web/modules/storage/utils.ts; apps/web/app/api/v1/client/[workspaceId]/storage/route.ts; apps/web/app/api/v1/client/[workspaceId]/responses/[responseId]/lib/put-response-handler.ts
<details><summary><h3>Important Files Changed</h3></summary>
| Filename | Overview |
|----------|----------|
| packages/types/storage.ts | Adds the required element identifier to private-upload validation, creating an incompatible request contract for older clients. |
| apps/web/modules/storage/utils.ts | Adds element-specific permission and scoped-URL validation but rejects legacy URLs during response updates. |
| apps/web/app/api/v1/client/[workspaceId]/storage/route.ts | Validates uploads against a specific survey element and signs scoped private object keys. |
| apps/web/modules/storage/service.ts | Adds safe nested path segments to signed upload keys and returned storage URLs. |
| apps/web/app/storage/[workspaceId]/[accessType]/[...filePath]/route.ts | Converts the storage download/delete endpoint to a catch-all route for nested keys while retaining workspace authorization. |
| packages/surveys/src/components/elements/file-upload-element.tsx | Propagates the current file-upload element ID into upload-signing requests. |
| apps/web/app/api/v1/client/[workspaceId]/responses/[responseId]/lib/put-response-handler.ts | Applies scoped file-upload validation to response-update deltas, exposing legacy pending updates to rejection. |
| apps/web/lib/response/service.ts | Updates response cleanup to parse and retain nested storage object paths. |
</details>
<details open><summary><h3>Flowchart</h3></summary>
```mermaid
%%{init: {'theme': 'neutral'}}%%
flowchart LR
A[File-upload element] -->|surveyId + elementId| B[Client storage API]
B --> C{Element and extension valid?}
C -->|No| D[400 response]
C -->|Yes| E[Create scoped signed upload]
E --> F["/storage/workspace/private/surveys/survey/elements/element/file"]
F --> G[Response create or update]
G --> H{Scoped URL validation}
H -->|Valid new URL| I[Persist response]
H -->|Legacy URL| D
I --> J[Catch-all download and deletion route]
```
</details>
<!-- greptile_other_comments_section -->
<sub>Reviews (1): Last reviewed commit: ["Update apps/web/app/api/v1/client/\[works..."](https://github.com/drape-io/crbench-greptile-2026-09/commit/219321949f094f0ec44f3fd90f87c31ffb98ceae) | [Re-trigger Greptile](https://app.greptile.com/api/retrigger?id=64284437)</sub>
Mjolnir (Opus 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d2 | high | ✗ | — |
| d3 | medium | ✓ | exact |
| d4 | medium | ✓ | exact |
| d1 | high | ✗ | — |
`isScopedPrivateUploadUrl` relies on `getStorageUrlPathSegments`, which returns null for anything that doesn't start with `/storage/`. So an absolute URL with the correct scope (e.g. https://host/storage/ws/private/surveys/s/elements/e/f.pdf) now fails `validateClientFileUploads`, while `parseStorageFileUrl` in the same change accepts that form. The old `validateFileUploads` accepted these URLs. Impact is limited because the signing endpoint returns relative paths ("Return relative path"), so only clients that convert the URL to an absolute one before submitting would hit this. [grounded: diff] [consensus 3/3: valid=3]
raw comments (3)
[P2] `elementId` is now mandatory for client file uploads, which breaks the documented Client API
`ZUploadPrivateFileRequest` now requires `elementId`. The public v1/v2 `/client/{workspaceId}/storage` endpoint (v2 re-exports the v1 handler) is documented in `docs/api-v2-reference/openapi.yml:237-277` as needing only `surveyId`, `fileName` and `fileType`. Any request that follows that contract now gets a 400 "Fields are missing or incorrectly formatted". That includes headless integrations, custom SDK users and any surveys bundle that is still cached. `/js/*` is served with `s-maxage=2592000`, so a CDN can keep serving the old bundle, which doesn't send `elementId`, for up to 30 days. The new response validation would also reject unscoped URLs, so this needs either a compatibility path or at least updated docs and a deliberate breaking-change note. Right now, file upload for these clients just stops working.
[P2] Client response validation rejects absolute storage URLs
`isScopedPrivateUploadUrl` uses `getStorageUrlPathSegments`, which returns `null` unless the value starts with `/storage/`. As a result, `validateClientFileUploads` fails the whole response when a file-upload answer is an absolute URL such as `https://app.formbricks.com/storage/‹ws›/private/surveys/‹sid›/elements/‹eid›/f--fid--x.pdf`, even if its scope is correct. That's the format shown in the API docs (`fileUrl: https://app.formbricks.com/storage/...` in openapi.yml), and other helpers in this same change accept it: `parseStorageFileUrl` and `getOriginalFileNameFromUrl` both handle absolute URLs. API clients that resolve or store the absolute URL before submitting to the v1/v2 client responses endpoints will get "Invalid file upload response". The v2 endpoint did not validate file URLs at all before this change. The fix is to parse the pathname from absolute URLs the same way `parseStorageFileUrl` does (and ideally check the origin against the app URL).
[P2] Making `elementId` mandatory breaks the documented Client storage API and stale survey bundles
packages/types/storage.ts:128-135 `ZUploadPrivateFileRequest` now requires `elementId`. As a result, `POST /api/v1|v2/client/{id}/storage` returns 400 for any caller that sends only the fields the public contract still lists as required (`surveyId`, `fileName`, `fileType`; see `apps/web/scripts/openapi/merge-client-endpoints.ts:233-248` and `docs/api-v2-reference/openapi.yml`). Headless or custom integrations built on the documented Client API will stop being able to upload files. Even if they upload some other way, the response endpoints now run `validateClientFileUploads`, which rejects any file URL that is not under `/storage/‹ws›/private/surveys/‹sid›/elements/‹eid›/…`. Old copies of `surveys.umd.cjs` hit the same 400, and the old bundle can stay in circulation after a deploy because `/js/*` is served with `s-maxage=2592000` (`apps/web/next.config.mjs:260-265`). Until CDN caches expire or are purged, file-upload questions in app and website surveys would fail. Either add a backward-compatible path, such as accepting a missing `elementId` during a transition period, or treat this as an announced breaking API change and update the OpenAPI spec and docs in the same change.
Mjolnir (Sonnet 5.5) · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d2 | high | ✗ | — |
| d3 | medium | ✗ | — |
| d4 | medium | ✗ | — |
| d1 | high | ✗ | — |
qodo · cross-file engine perris 0.11.1+proven.tiered0.25.call.read.subclass.type
| Defect | Severity | Found | Grade |
|---|---|---|---|
| d2 | high | ✗ | — |
| d3 | medium | ✗ | — |
| d4 | medium | ✗ | — |
| d1 | high | ✗ | — |
raw comments (2)
<h3>Qodo is busy working</h3>
Check back in a few minutes. Qodo's code review agents are on it.
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<img src="https://www.qodo.ai/wp-content/uploads/2026/01/anteater-looking-at-ants-01-transparent-bg-croped-ezgif.com-optimize-1.gif" width="30%">
<h3>PR Summary by Qodo</h3>
Scope survey uploads to elements and support nested storage paths
<code>🐞 Bug fix</code> <code>✨ Enhancement</code> <code>🧪 Tests</code> <code>🕐 40+ Minutes</code>
<img src="https://www.qodo.ai/wp-content/uploads/2025/11/light-grey-line.svg" height="10%" alt="Grey Divider">
<details>
<summary>AI Description</summary>
<dl>
<dd>
<br/>
><pre>
>• Scope private survey uploads by workspace, survey, and element.
>• Validate client response file URLs against their owning upload element.
>• Support nested storage paths across download, deletion, cleanup, and tests.
></pre>
</dd>
</dl>
</details>
<details>
<summary>Diagram</summary>
<dl>
<dd>
<br/>
```mermaid
sequenceDiagram
actor Respondent
participant SurveyUI as Survey UI
participant StorageAPI as Storage API
participant Validator as Upload Validator
participant ObjectStore as Object Storage
participant ResponseAPI as Response API
participant FileRoute as File Route
Respondent->>SurveyUI: Select file
SurveyUI->>StorageAPI: Send survey and element
StorageAPI->>Validator: Check element permissions
StorageAPI->>ObjectStore: Request scoped upload
ObjectStore-->>StorageAPI: Return signed URL
StorageAPI-->>SurveyUI: Return scoped file URL
SurveyUI->>ResponseAPI: Submit response
ResponseAPI->>Validator: Validate URL scope
FileRoute->>ObjectStore: Access nested path
```
</dd>
</dl>
</details>
<details>
<summary>High-Level Assessment</summary>
<dl>
<dd>
<br/>
>The following are alternative approaches to this PR:
<details>
<summary><b>1. Database-backed upload ownership</b></summary>
<dl>
<dd>
- ➕ Provides explicit ownership records independent of URL structure
- ➕ Supports revocation and richer upload lifecycle tracking
- ➖ Requires schema changes and additional reads and writes
- ➖ Introduces migration and cleanup complexity for existing uploads
</dd>
</dl>
</details>
<details>
<summary><b>2. Signed upload claim token</b></summary>
<dl>
<dd>
- ➕ Cryptographically binds an upload to its survey and element
- ➕ Avoids relying solely on storage path conventions
- ➖ Requires token issuance, transport, verification, and expiry handling
- ➖ Complicates response payloads and backward compatibility
</dd>
</dl>
</details>
>**Recommendation:** Keep the PR's scoped-path approach. It provides stateless ownership validation, aligns object keys with survey structure, and extends existing routes and cleanup logic with limited operational overhead. Database records or signed claims would be preferable only if revocation, expiring ownership, or cross-storage portability becomes necessary.
</dd>
</dl>
</details>
<details>
<summary> Files changed (22) <code> +580 / -86 </code> </summary>
<dl>
<dd>
<br/>
<details>
<summary>Enhancement (7) <code> +77 / -29 </code></summary>
<dl>
<dd>
<details>
<summary>route.ts<code>Create element-scoped private upload paths</code> <code>+15/-9</code></summary>
<br/>
>Create element-scoped private upload paths
>
><pre>
>• Requires upload element context, validates permissions against that specific element, and stores files under survey and element path segments. It also returns more precise permission errors.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/37/files#diff-935af85264b64ed26c53eac65bbe0c18a30f7e171648047d82d71d3bcfe319a1'>apps/web/app/api/v1/client/[workspaceId]/storage/route.ts</a>
</details>
<details>
<summary>route.ts<code>Handle nested storage file paths</code> <code>+29/-7</code></summary>
<br/>
>Handle nested storage file paths
>
><pre>
>• Changes storage GET and DELETE routing to join catch-all path segments into a complete object key. It also safely handles unknown deletion failure shapes and records an audit failure.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/37/files#diff-3f393bd50a8dd228451b0f7235e82a27e446a397d79f2596e4aabef78c054814'>apps/web/app/storage/[workspaceId]/[accessType]/[...filePath]/route.ts</a>
</details>
<details>
<summary>service.ts<code>Generate safe nested storage object paths</code> <code>+17/-9</code></summary>
<br/>
>Generate safe nested storage object paths
>
><pre>
>• Extends signed upload generation with optional validated path segments. Generated object keys and returned file URLs now preserve scoped nested paths.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/37/files#diff-22270c5c1a5dbabce5fe9d53e7ac609a6c70c001ec1926fbce13475bf5637267'>apps/web/modules/storage/service.ts</a>
</details>
<details>
<summary>storage.ts<code>Expose upload element context in JS types</code> <code>+4/-3</code></summary>
<br/>
>Expose upload element context in JS types
>
><pre>
>• Adds 'elementId' to the upload configuration and simplifies redundant optional-property type declarations.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/37/files#diff-9b8412b9304c11a7d55e6abf67ca5cb0bbfaed58409c6849b93fe12eed268612'>packages/js-core/src/types/storage.ts</a>
</details>
<details>
<summary>file-upload-element.tsx<code>Pass element identity during uploads</code> <code>+1/-0</code></summary>
<br/>
>Pass element identity during uploads
>
><pre>
>• Includes the current file-upload element ID when requesting an upload URL.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/37/files#diff-12bd828a1f7d2cb32d7ba6fdfdce138714e349709c58eeaa07b624e77d148249'>packages/surveys/src/components/elements/file-upload-element.tsx</a>
</details>
<details>
<summary>api-client.ts<code>Send element context to storage API</code> <code>+2/-1</code></summary>
<br/>
>Send element context to storage API
>
><pre>
>• Accepts 'elementId' in upload configuration and includes it in private upload signing requests.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/37/files#diff-61260e002eb61dbd54d9bb9d73252434f2f9d616e11c46ccc30b99daa1fcedb4'>packages/surveys/src/lib/api-client.ts</a>
</details>
<details>
<summary>storage.ts<code>Require valid private upload element IDs</code> <code>+9/-0</code></summary>
<br/>
>Require valid private upload element IDs
>
><pre>
>• Adds element IDs to shared upload configuration. Private upload requests now require a non-empty, path-safe element identifier.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/37/files#diff-e5cfe4a44aa5cc778edc7b5e6bf03949d0de93a14dade9da0b17362dfa32379e'>packages/types/storage.ts</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Bug fix (6) <code> +208 / -30 </code></summary>
<dl>
<dd>
<details>
<summary>put-response-handler.ts<code>Validate scoped uploads during response updates</code> <code>+13/-4</code></summary>
<br/>
>Validate scoped uploads during response updates
>
><pre>
>• Passes workspace, survey, block, and question context into client file validation. Response updates now reject files outside the expected survey element scope.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/37/files#diff-7fc9209f3aa027d68e00ccab570c77cd18efcdc4e571e63b37e9f017abd0e93a'>apps/web/app/api/v1/client/[workspaceId]/responses/[responseId]/lib/put-response-handler.ts</a>
</details>
<details>
<summary>route.ts<code>Enforce scoped uploads on v1 response creation</code> <code>+10/-2</code></summary>
<br/>
>Enforce scoped uploads on v1 response creation
>
><pre>
>• Replaces generic file extension validation with workspace-, survey-, and element-aware URL validation for new v1 responses.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/37/files#diff-093d9e543c77df99136d44d5dca2d980e4111ee0ed84c1bf5ecdb80be013bfd7'>apps/web/app/api/v1/client/[workspaceId]/responses/route.ts</a>
</details>
<details>
<summary>route.ts<code>Validate file ownership in v2 submissions</code> <code>+13/-0</code></summary>
<br/>
>Validate file ownership in v2 submissions
>
><pre>
>• Adds scoped client upload validation to v2 response submissions before other response element checks.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/37/files#diff-d44b54f1d4554fe6b174319a27ffe412b8b47b14a19ca1ed59db3adfafaeab7b'>apps/web/app/api/v2/client/[workspaceId]/responses/route.ts</a>
</details>
<details>
<summary>service.ts<code>Delete files with nested object keys</code> <code>+10/-6</code></summary>
<br/>
>Delete files with nested object keys
>
><pre>
>• Uses the shared storage URL parser when cleaning up response files, preserving all nested path segments during deletion.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/37/files#diff-b33c80909f142882b6325741f318ff7ca5dbdc38b2bac054b7ccd68d87018031'>apps/web/lib/response/service.ts</a>
</details>
<details>
<summary>utils.ts<code>Parse nested files during management cleanup</code> <code>+5/-5</code></summary>
<br/>
>Parse nested files during management cleanup
>
><pre>
>• Replaces manual URL splitting with the shared parser so management response deletion supports nested storage object keys.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/37/files#diff-7a73fee8fb507b1b9d46af8691bc432d26dde9498bc695afc8499a6662f90911'>apps/web/modules/api/v2/management/responses/[responseId]/lib/utils.ts</a>
</details>
<details>
<summary>utils.ts<code>Add scoped upload validation and URL parsing</code> <code>+157/-13</code></summary>
<br/>
>Add scoped upload validation and URL parsing
>
><pre>
>• Validates extensions against the selected file-upload element instead of any survey upload element. Adds shared nested URL parsing and strict validation that client-submitted private URLs belong to the expected workspace, survey, and element.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/37/files#diff-8964d0b76d7fe4123fb7da8605c87121eae38c8a53ff0ec36924ecfd4758d8c7'>apps/web/modules/storage/utils.ts</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Refactor (2) <code> +0 / -0 </code></summary>
<dl>
<dd>
<details>
<summary>audit-logs.ts<code>Relocate storage deletion audit logging</code> <code>+0/-0</code></summary>
<br/>
>Relocate storage deletion audit logging
>
><pre>
>• Moves deletion audit logging alongside the new catch-all nested storage route.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/37/files#diff-ab94c33b9eb5eb465ed96fa2f7aa2042a05a3c008ab4b726ae4cb28fef016577'>apps/web/app/storage/[workspaceId]/[accessType]/[...filePath]/lib/audit-logs.ts</a>
</details>
<details>
<summary>auth.ts<code>Relocate private file authorization</code> <code>+0/-0</code></summary>
<br/>
>Relocate private file authorization
>
><pre>
>• Moves session and API-key authorization helpers under the catch-all storage route structure.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/37/files#diff-b831e34578e10b79b042fe7a4f0ffab603d4ed3c1f23676c3004cc0115d13b4a'>apps/web/app/storage/[workspaceId]/[accessType]/[...filePath]/lib/auth.ts</a>
</details>
</dd>
</dl>
</details>
<details>
<summary>Tests (7) <code> +295 / -27 </code></summary>
<dl>
<dd>
<details>
<summary>put-response-handler.test.ts<code>Mock scoped client upload validation</code> <code>+4/-4</code></summary>
<br/>
>Mock scoped client upload validation
>
><pre>
>• Updates response-update tests to mock 'validateClientFileUploads', preserving coverage for accepted and rejected file upload changes.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/37/files#diff-6ccfe4f5647533434f97e2f84dc6ae6b0d237f94df9cc3d5c777726a7e59f7ed'>apps/web/app/api/v1/client/[workspaceId]/responses/[responseId]/lib/put-response-handler.test.ts</a>
</details>
<details>
<summary>audit-logs.test.ts<code>Relocate storage audit-log tests</code> <code>+0/-0</code></summary>
<br/>
>Relocate storage audit-log tests
>
><pre>
>• Moves the audit-log test suite beneath the catch-all storage path route without changing its behavioral coverage.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/37/files#diff-45738fc2b78441ed61cd9f9323b077a212df25243afd6bb20a32ebd38370184a'>apps/web/app/storage/[workspaceId]/[accessType]/[...filePath]/lib/audit-logs.test.ts</a>
</details>
<details>
<summary>utils.mock.ts<code>Use canonical storage URLs in response mocks</code> <code>+2/-2</code></summary>
<br/>
>Use canonical storage URLs in response mocks
>
><pre>
>• Updates mocked uploaded file URLs to use the '/storage' route expected by shared parsing logic.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/37/files#diff-24b6b2a1fd189fd9f48dda4219ec7442637681ff93c6c5a4c8ab9122c98dae3b'>apps/web/modules/api/v2/management/responses/[responseId]/lib/tests/__mocks__/utils.mock.ts</a>
</details>
<details>
<summary>service.test.ts<code>Test scoped upload path generation</code> <code>+55/-0</code></summary>
<br/>
>Test scoped upload path generation
>
><pre>
>• Covers nested private upload URLs and object-store paths. Adds rejection cases for empty, traversal-like, spaced, separated, and URL-reserved path segments.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/37/files#diff-78eb33252add926ce9d9c917fffdd1f3791562028dec0baa5b8fb5d1ee3d7597'>apps/web/modules/storage/service.test.ts</a>
</details>
<details>
<summary>utils.test.ts<code>Cover element permissions and scoped URL validation</code> <code>+162/-9</code></summary>
<br/>
>Cover element permissions and scoped URL validation
>
><pre>
>• Updates permission tests to target a specific upload element and adds coverage for mismatched surveys, elements, external URLs, legacy URLs, extensions, and nested URL parsing.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/37/files#diff-68733bb8fdb0a076babab0d5735d784c5e4d548a8868fef2a4d6ed42a725f282'>apps/web/modules/storage/utils.test.ts</a>
</details>
<details>
<summary>helper.ts<code>Mock scoped nested storage URLs</code> <code>+33/-12</code></summary>
<br/>
>Mock scoped nested storage URLs
>
><pre>
>• Enhances Playwright upload mocks to include workspace, survey, and element path context. Storage request interception now supports all nested '/storage' URLs.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/37/files#diff-9d9f828bd3e7dafd70d56f88c83c4fc523986940d62c2ceb386eb97c968a45e5'>apps/web/playwright/utils/helper.ts</a>
</details>
<details>
<summary>api-client.test.ts<code>Test upload signing context payload</code> <code>+39/-0</code></summary>
<br/>
>Test upload signing context payload
>
><pre>
>• Verifies that upload signing requests include both survey and element identifiers alongside file metadata.
></pre>
>
><a href='https://github.com/drape-io/crbench-qodo-2026-09/pull/37/files#diff-068ea3a4c1e73d3599587626547477e18e1146dea1e6eaa39f763682109a055c'>packages/surveys/src/lib/api-client.test.ts</a>
</details>
</dd>
</dl>
</details>
</dd>
</dl>
</details>