Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

fix(uploads): authorize and claim only referenced staged assets

Tin7468accd48b4
diff --cc apps/api/src/task/controllers/create-task.ts
index 78b89eab8,dd08fa955..eb6395213
--- a/apps/api/src/task/controllers/create-task.ts
+++ b/apps/api/src/task/controllers/create-task.ts
@@@ -1,4 -1,4 +1,5 @@@
-import { and, eq } from "drizzle-orm";
++import { extractAssetIds } from "../../storage/cleanup-assets";
+import { and, eq, inArray, isNull } from "drizzle-orm";
import { HTTPException } from "hono/http-exception";
import db from "../../database";
import {
@@@ -155,28 -152,6 +156,33 @@@ async function createTask(
})
.returning();
+ if (task && draftAssetIds?.length) {
- const ids = [...new Set(draftAssetIds)];
- const claimed = await tx
- .update(assetTable)
- .set({ taskId: task.id, surface: "description" })
- .where(
- and(
- inArray(assetTable.id, ids),
- eq(assetTable.projectId, projectId),
- eq(assetTable.createdBy, currentUserId),
- eq(assetTable.surface, "draft"),
- isNull(assetTable.taskId),
- ),
- )
- .returning({ id: assetTable.id });
- if (claimed.length !== ids.length)
- throw new HTTPException(400, {
- message:
- "Some staged uploads are unavailable or belong to another owner/project",
- });
++ const referenced = extractAssetIds(description);
++ const ids = [...new Set(draftAssetIds)].filter((id) =>
++ referenced.has(id),
++ );
++ if (ids.length) {
++ const claimed = await tx
++ .update(assetTable)
++ .set({ taskId: task.id, surface: "description" })
++ .where(
++ and(
++ inArray(assetTable.id, ids),
++ eq(assetTable.projectId, projectId),
++ eq(assetTable.createdBy, currentUserId),
++ eq(assetTable.surface, "draft"),
++ isNull(assetTable.taskId),
++ ),
++ )
++ .returning({ id: assetTable.id });
++ if (claimed.length !== ids.length)
++ throw new HTTPException(400, {
++ message:
++ "Some staged uploads are unavailable or belong to another owner/project",
++ });
++ }
+ }
+
if (task && mergedCustomFields.length) {
await tx.insert(customFieldValueTable).values(
mergedCustomFields.map(({ fieldId, value }) => ({
diff --cc apps/api/src/task/controllers/stage-task-asset.ts
index c2d98894d,000000000..689f2a31c
mode 100644,000000..100644
--- a/apps/api/src/task/controllers/stage-task-asset.ts
+++ b/apps/api/src/task/controllers/stage-task-asset.ts
@@@ -1,120 -1,0 +1,119 @@@
+import { and, eq, inArray, isNull } from "drizzle-orm";
+import { HTTPException } from "hono/http-exception";
+import db from "../../database";
+import { assetTable, projectTable } from "../../database/schema";
+import {
- assertTaskImageKeyMatchesContext,
+ createTaskImageUploadUrl,
+ InvalidUploadedAssetError,
+ isImageContentType,
+ validateTaskAssetUploadInput,
+ verifyTaskAssetUpload,
+} from "../../storage/s3";
+
+type Upload = { filename: string; contentType: string; size: number };
+async function uploadContext(projectId: string, userId: string) {
+ const project = await db.query.projectTable.findFirst({
+ where: eq(projectTable.id, projectId),
+ });
+ if (!project) throw new HTTPException(404, { message: "Project not found" });
+ return {
+ workspaceId: project.workspaceId,
+ projectId,
+ taskId: `draft-${userId}`,
+ surface: "description" as const,
+ };
+}
+function validate(input: Upload) {
+ try {
+ validateTaskAssetUploadInput(input.contentType, input.size);
+ } catch (error) {
+ throw new HTTPException(400, {
+ message: error instanceof Error ? error.message : "Invalid upload",
+ });
+ }
+}
+export async function stageTaskAssetUpload(
+ projectId: string,
+ userId: string,
+ input: Upload,
+) {
+ validate(input);
+ const context = await uploadContext(projectId, userId);
++ let upload: Awaited<ReturnType<typeof createTaskImageUploadUrl>>;
+ try {
- const upload = await createTaskImageUploadUrl({ ...context, ...input });
- await db.insert(assetTable).values({
- workspaceId: context.workspaceId,
- projectId,
- taskId: null,
- objectKey: upload.key,
- filename: input.filename,
- mimeType: input.contentType,
- size: input.size,
- kind: isImageContentType(input.contentType) ? "image" : "attachment",
- surface: "draft-pending",
- createdBy: userId,
- });
- return upload;
++ upload = await createTaskImageUploadUrl({ ...context, ...input });
+ } catch {
+ throw new HTTPException(503, {
+ message: "Image uploads are not configured",
+ });
+ }
++ await db.insert(assetTable).values({
++ workspaceId: context.workspaceId,
++ projectId,
++ taskId: null,
++ objectKey: upload.key,
++ filename: input.filename,
++ mimeType: input.contentType,
++ size: input.size,
++ kind: isImageContentType(input.contentType) ? "image" : "attachment",
++ surface: "draft-pending",
++ createdBy: userId,
++ });
++
++ return upload;
+}
+export async function finalizeStagedTaskAsset(
+ projectId: string,
+ userId: string,
+ input: Upload & { key: string },
+) {
+ validate(input);
- const context = await uploadContext(projectId, userId);
++ await uploadContext(projectId, userId);
+ const key = input.key.trim();
- if (!assertTaskImageKeyMatchesContext(key, context))
- throw new HTTPException(400, {
- message: "Upload key does not match the draft owner and project",
- });
- let uploaded: Awaited<ReturnType<typeof verifyTaskAssetUpload>>;
- try {
- uploaded = await verifyTaskAssetUpload(key, input);
- } catch (error) {
- throw new HTTPException(
- error instanceof InvalidUploadedAssetError ? 400 : 503,
- {
- message:
- error instanceof Error ? error.message : "Unable to verify upload",
- },
- );
- }
++ // The persisted key is the issuance record. Project moves update authorization
++ // metadata, but the object remains at its originally issued storage key.
+ const existing = await db.query.assetTable.findFirst({
+ where: eq(assetTable.objectKey, key),
+ });
+ if (
+ !existing ||
+ !["draft", "draft-pending"].includes(existing.surface) ||
+ existing.createdBy !== userId ||
+ existing.projectId !== projectId ||
+ existing.taskId !== null
+ )
+ throw new HTTPException(409, {
+ message: "Upload is unavailable or already attached",
+ });
++ let uploaded: Awaited<ReturnType<typeof verifyTaskAssetUpload>>;
++ try {
++ uploaded = await verifyTaskAssetUpload(key, input);
++ } catch (error) {
++ throw new HTTPException(
++ error instanceof InvalidUploadedAssetError ? 400 : 503,
++ {
++ message:
++ error instanceof Error ? error.message : "Unable to verify upload",
++ },
++ );
++ }
+ const [asset] = await db
+ .update(assetTable)
+ .set({
+ mimeType: uploaded.contentType,
+ size: uploaded.size,
+ kind: isImageContentType(uploaded.contentType) ? "image" : "attachment",
+ surface: "draft",
+ })
+ .where(
+ and(
+ eq(assetTable.id, existing.id),
+ isNull(assetTable.taskId),
+ inArray(assetTable.surface, ["draft", "draft-pending"]),
+ ),
+ )
+ .returning({ id: assetTable.id });
+ if (!asset)
+ throw new HTTPException(409, { message: "Upload is already attached" });
+ return asset;
+}
diff --cc apps/api/src/task/index.ts
index 6545614bd,a9b1ce15c..4e4a77eb0
--- a/apps/api/src/task/index.ts
+++ b/apps/api/src/task/index.ts
@@@ -84,6 -81,6 +85,8 @@@ import
duplicateTaskBody,
finalizeImageUploadBody,
imageUploadBody,
++ stagedImageUploadBody,
++ finalizeStagedImageUploadBody,
importTasksBody,
listTasksQuery,
moveTaskBody,
@@@ -151,62 -148,6 +154,64 @@@ const bulkUpdateTasksRoute = createRout
},
});
+const stagedUploadRoute = createRoute({
+ method: "post",
+ operationId: "stageTaskAssetUpload",
+ path: "/draft-upload/{projectId}",
+ tags: ["Tasks"],
+ summary: "Stage a task attachment",
+ description:
+ "Upload an attachment before submitting a task. Staged assets are private to the uploader and expire after 24 hours.",
+ middleware: [
+ workspaceAccess.fromProject("projectId"),
+ requireWorkspacePermission({ task: ["create"] }),
+ requireEntitlement,
+ ] as const,
+ request: {
+ params: projectIdParam,
+ body: {
+ required: true,
- content: { "application/json": { schema: imageUploadBody } },
++ content: { "application/json": { schema: stagedImageUploadBody } },
+ },
+ },
+ responses: {
+ 200: jsonResponse("Presigned upload", imageUploadSchema),
+ 400: errorResponse("Invalid upload"),
+ 403: errorResponse("Missing task:create permission"),
+ 404: errorResponse("Project not found"),
+ 503: errorResponse("Storage unavailable"),
+ },
+});
+const finalizeStagedUploadRoute = createRoute({
+ method: "post",
+ operationId: "finalizeStagedTaskAsset",
+ path: "/draft-upload/{projectId}/finalize",
+ tags: ["Tasks"],
+ summary: "Finalize a staged task attachment",
+ middleware: [
+ workspaceAccess.fromProject("projectId"),
+ requireWorkspacePermission({ task: ["create"] }),
+ requireEntitlement,
+ ] as const,
+ request: {
+ params: projectIdParam,
+ body: {
+ required: true,
- content: { "application/json": { schema: finalizeImageUploadBody } },
++ content: {
++ "application/json": { schema: finalizeStagedImageUploadBody },
++ },
+ },
+ },
+ responses: {
+ 200: jsonResponse("Staged attachment", finalizedAssetSchema),
+ 400: errorResponse("Invalid upload"),
+ 403: errorResponse("Missing task:create permission"),
+ 404: errorResponse("Project not found"),
+ 409: errorResponse("Upload already attached"),
+ 503: errorResponse("Storage unavailable"),
+ },
+});
+
const createTaskRoute = createRoute({
method: "post",
operationId: "createTask",
diff --cc apps/api/src/task/schema.ts
index 40f56b451,ab85f70ee..569397440
--- a/apps/api/src/task/schema.ts
+++ b/apps/api/src/task/schema.ts
@@@ -158,3 -157,3 +158,10 @@@ export const descriptionMatchesQuery =
});
export const duplicateTaskBody = z.object({ title: z.string().optional() });
++
++export const stagedImageUploadBody = imageUploadBody.extend({
++ surface: z.literal("description"),
++});
++export const finalizeStagedImageUploadBody = finalizeImageUploadBody.extend({
++ surface: z.literal("description"),
++});
diff --cc apps/docs/openapi.json
index 507fefd55,b263bb917..acec71643
--- a/apps/docs/openapi.json
+++ b/apps/docs/openapi.json
@@@ -8550,240 -8550,6 +8550,236 @@@
}
}
},
+ "/task/draft-upload/{projectId}": {
+ "post": {
+ "operationId": "stageTaskAssetUpload",
+ "tags": [
+ "Tasks"
+ ],
+ "summary": "Stage a task attachment",
+ "description": "Upload an attachment before submitting a task. Staged assets are private to the uploader and expire after 24 hours.",
+ "parameters": [
+ {
+ "schema": {
+ "type": "string"
+ },
+ "required": true,
+ "name": "projectId",
+ "in": "path"
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "filename": {
+ "type": "string"
+ },
+ "contentType": {
+ "type": "string"
+ },
+ "size": {
+ "type": "number"
+ },
+ "surface": {
+ "type": "string",
+ "enum": [
- "description",
- "comment"
- ],
- "description": "Where the image is used, which decides how it is scoped."
++ "description"
++ ]
+ }
+ },
+ "required": [
+ "filename",
+ "contentType",
+ "size",
+ "surface"
+ ]
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Presigned upload",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TaskImageUpload"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid upload",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Missing or invalid credentials"
+ },
+ "403": {
+ "description": "Missing task:create permission",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Project not found",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "503": {
+ "description": "Storage unavailable",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/task/draft-upload/{projectId}/finalize": {
+ "post": {
+ "operationId": "finalizeStagedTaskAsset",
+ "tags": [
+ "Tasks"
+ ],
+ "summary": "Finalize a staged task attachment",
+ "parameters": [
+ {
+ "schema": {
+ "type": "string"
+ },
+ "required": true,
+ "name": "projectId",
+ "in": "path"
+ }
+ ],
+ "requestBody": {
+ "required": true,
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "key": {
+ "type": "string",
+ "description": "The key returned when the URL was issued."
+ },
+ "filename": {
+ "type": "string"
+ },
+ "contentType": {
+ "type": "string"
+ },
+ "size": {
+ "type": "number"
+ },
+ "surface": {
+ "type": "string",
+ "enum": [
- "description",
- "comment"
- ],
- "description": "Where the image is used, which decides how it is scoped."
++ "description"
++ ]
+ }
+ },
+ "required": [
+ "key",
+ "filename",
+ "contentType",
+ "size",
+ "surface"
+ ]
+ }
+ }
+ }
+ },
+ "responses": {
+ "200": {
+ "description": "Staged attachment",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/TaskImageAsset"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid upload",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Missing or invalid credentials"
+ },
+ "403": {
+ "description": "Missing task:create permission",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Project not found",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "Upload already attached",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "503": {
+ "description": "Storage unavailable",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/task/{projectId}": {
"post": {
"operationId": "createTask",
diff --cc apps/web/src/components/shared/modals/create-task-modal.test.tsx
index 8a8d59113,999a39046..d14493825
--- a/apps/web/src/components/shared/modals/create-task-modal.test.tsx
+++ b/apps/web/src/components/shared/modals/create-task-modal.test.tsx
@@@ -89,10 -85,10 +89,17 @@@ vi.mock("@tanstack/react-router", () =
vi.mock("@/components/task/task-description-editor", () => ({
default: (props: {
taskId?: string;
- ensureTaskId: () => Promise<string | null>;
+ uploadAsset: (file: File) => Promise<unknown>;
++ onChange: (value: string) => void;
}) => {
- ensureTaskId = props.ensureTaskId;
- return <div data-testid="description-editor" data-task-id={props.taskId} />;
+ uploadAsset = props.uploadAsset;
- return <div data-testid="description-editor" data-task-id={props.taskId} />;
++ return (
++ <textarea
++ data-testid="description-editor"
++ data-task-id={props.taskId}
++ onChange={(event) => props.onChange(event.target.value)}
++ />
++ );
},
}));
@@@ -397,30 -407,30 +404,33 @@@ describe("CreateTaskModal context isola
wrapper: createWrapper(),
});
await chooseBeta();
- let pending!: Promise<string | null>;
- act(() => {
- pending = ensureTaskId?.() as Promise<string | null>;
- });
- workspaceId = "workspace-2";
- useLocation.mockReturnValue({
- pathname: "/dashboard/workspace/workspace-2",
- });
- view.rerender(<CreateTaskModal open onClose={vi.fn()} />);
+ enterTitle();
await act(async () => {
- finish();
- await pending;
+ await uploadAsset?.(new File(["x"], "x.png"));
});
- await expect(pending).resolves.toBeNull();
- expect(deleteTask).toHaveBeenCalledExactlyOnceWith("old-draft");
- expect(screen.getByTestId("description-editor")).not.toHaveAttribute(
- "data-task-id",
- );
+ expect(createTask).not.toHaveBeenCalled();
expect(updateTask).not.toHaveBeenCalled();
- expect(setProject).not.toHaveBeenCalled();
++ fireEvent.change(screen.getByTestId("description-editor"), {
++ target: { value: "![image](/asset/staged-1)" },
++ });
+ submit();
+ await vi.waitFor(() => expect(createTask).toHaveBeenCalledOnce());
+ expect(createTask).toHaveBeenCalledWith(
+ expect.objectContaining({
+ draftAssetIds: ["staged-1"],
+ projectId: "project-2",
+ }),
+ );
});
- it("waits for the upload draft on submit and saves that task only once", async () => {
- const finish = pendingCreate();
+ it("does not submit while attachments are uploading", async () => {
+ let finish!: (value: unknown) => void;
+ stageUpload.mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ finish = resolve;
+ }),
+ );
render(<CreateTaskModal open onClose={vi.fn()} />, {
wrapper: createWrapper(),
});
diff --cc apps/web/src/components/shared/modals/create-task-modal.tsx
index c28952098,e7382e3f8..5e04a5e96
--- a/apps/web/src/components/shared/modals/create-task-modal.tsx
+++ b/apps/web/src/components/shared/modals/create-task-modal.tsx
@@@ -484,27 -555,50 +484,29 @@@ function CreateTaskModalContent(
submittingRef.current = true;
setIsSubmitting(true);
try {
- // Submitting while a file prepares its draft must update that same task.
- const pendingDraft = draftCreationPromiseRef.current;
- if (pendingDraft) await pendingDraft;
- if (!activeRef.current) return;
- const currentDraft = draftTaskRef.current;
- if (currentDraft && currentDraft.projectId !== resolvedProjectId) return;
const taskStatus = status ?? "to-do";
didSubmitRef.current = true;
-
- const savedTask = currentDraft
- ? normalizeTask(
- await updateTask({
- ...currentDraft,
- title: title.trim(),
- description: description.trim() || "",
- userId: assigneeId || null,
- status: taskStatus,
- priority,
- startDate: startDate ? startDate.toISOString() : null,
- dueDate: dueDate ? dueDate.toISOString() : null,
- projectId: resolvedProjectId,
- customFieldValues: Object.entries(customFieldValues)
- .filter(([_, value]) => value.trim() !== "")
- .map(([fieldId, value]) => ({ fieldId, value })),
- }),
- )
- : normalizeTask(
- await createTask({
- title: title.trim(),
- description: description.trim() || "",
- userId: assigneeId,
- priority,
- projectId: resolvedProjectId,
- startDate: startDate ? startDate.toISOString() : undefined,
- dueDate: dueDate ? dueDate.toISOString() : undefined,
- status: taskStatus,
- customFields: Object.entries(customFieldValues)
- .filter(([_, value]) => value.trim() !== "")
- .map(([fieldId, value]) => ({
- fieldId,
- value,
- })),
- }),
- );
+ const savedTask = normalizeTask(
+ await createTask({
+ title: title.trim(),
+ description: description.trim() || "",
+ userId: assigneeId,
+ priority,
+ projectId: resolvedProjectId,
+ startDate: startDate ? startDate.toISOString() : undefined,
+ dueDate: dueDate ? dueDate.toISOString() : undefined,
+ status: taskStatus,
- draftAssetIds: stagedAssetsRef.current,
++ draftAssetIds: stagedAssetsRef.current.filter((id) =>
++ description.includes(`/asset/${id}`),
++ ),
+ customFields: Object.entries(customFieldValues)
+ .filter(([_, value]) => value.trim() !== "")
+ .map(([fieldId, value]) => ({
+ fieldId,
+ value,
+ })),
+ }),
+ );
for (const label of labels) {
try {
diff --cc apps/web/src/lib/upload-draft-asset.ts
index 79a5458c9,000000000..e3d2aae96
mode 100644,000000..100644
--- a/apps/web/src/lib/upload-draft-asset.ts
+++ b/apps/web/src/lib/upload-draft-asset.ts
@@@ -1,44 -1,0 +1,46 @@@
++import { i18n } from "@/lib/i18n";
+import { client } from "@kaneo/libs";
+import { HttpError } from "@/lib/http-error";
+import { getImageAltText, isSupportedImageFile } from "@/lib/upload-task-image";
+
+export async function uploadDraftAsset(projectId: string, file: File) {
+ const json = {
+ filename: file.name || "file",
+ contentType: file.type || "application/octet-stream",
+ size: file.size,
+ surface: "description" as const,
+ };
+ const response = await client.task["draft-upload"][":projectId"].$post({
+ param: { projectId },
+ json,
+ });
+ if (!response.ok) throw new HttpError(response.status, await response.text());
+ const upload = await response.json();
+ const stored = await fetch(upload.uploadUrl, {
+ method: "PUT",
+ headers: upload.headers,
+ body: file,
+ });
- if (!stored.ok) throw new Error("Failed to upload file to storage.");
++ if (!stored.ok)
++ throw new Error(i18n.t("activity:comment.editor.failedToUploadFile"));
+ const finalized = await client.task["draft-upload"][
+ ":projectId"
+ ].finalize.$post({
+ param: { projectId },
+ json: { ...json, key: upload.key },
+ });
+ if (!finalized.ok)
+ throw new HttpError(finalized.status, await finalized.text());
+ const asset = await finalized.json();
+ return {
+ id: asset.id,
+ url: asset.url,
+ alt: getImageAltText(file.name),
+ filename: json.filename,
+ kind: isSupportedImageFile(file)
+ ? ("image" as const)
+ : ("attachment" as const),
+ mimeType: json.contentType,
+ size: file.size,
+ };
+}
diff --cc tests/api-integration/staged-task-attachments.test.ts
index 248997db6,000000000..fdace9807
mode 100644,000000..100644
--- a/tests/api-integration/staged-task-attachments.test.ts
+++ b/tests/api-integration/staged-task-attachments.test.ts
@@@ -1,160 -1,0 +1,219 @@@
+import { eq } from "drizzle-orm";
+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
+import db, { schema } from "../../apps/api/src/database";
+import createTask from "../../apps/api/src/task/controllers/create-task";
+import {
+ stageTaskAssetUpload,
+ finalizeStagedTaskAsset,
+} from "../../apps/api/src/task/controllers/stage-task-asset";
+import { resetTestDatabase } from "./helpers/database";
+import {
+ createProjectFixture,
+ createWorkspaceMember,
+} from "./helpers/fixtures";
+const publish = vi.hoisted(() => vi.fn(async () => undefined));
+vi.mock("../../apps/api/src/events", () => ({ publishEvent: publish }));
+vi.mock("../../apps/api/src/storage/s3", () => ({
+ validateTaskAssetUploadInput: vi.fn(),
+ createTaskImageUploadUrl: vi.fn(async (context: { taskId: string }) => ({
+ key: `${context.taskId}/test.png`,
+ uploadUrl: "https://example.test/upload",
+ headers: {},
+ })),
+ assertTaskImageKeyMatchesContext: vi.fn(
+ (key: string, context: { taskId: string }) =>
+ key.startsWith(`${context.taskId}/`),
+ ),
+ verifyTaskAssetUpload: vi.fn(async () => ({
+ size: 12,
+ contentType: "image/png",
+ })),
+ isImageContentType: () => true,
+ InvalidUploadedAssetError: class extends Error {},
+}));
+beforeEach(async () => {
+ await resetTestDatabase();
+ vi.clearAllMocks();
+});
+describe("staged task attachments", () => {
+ it("creates no task or integration event until explicit submission", async () => {
+ const { user, workspace } = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+ const input = { filename: "image.png", contentType: "image/png", size: 12 };
+ const upload = await stageTaskAssetUpload(project.id, user.id, input);
+ expect(await db.query.taskTable.findMany()).toHaveLength(0);
+ expect(await db.query.assetTable.findMany()).toEqual([
+ expect.objectContaining({
+ taskId: null,
+ surface: "draft-pending",
+ objectKey: upload.key,
+ }),
+ ]);
+ const asset = await finalizeStagedTaskAsset(project.id, user.id, {
+ ...input,
+ key: upload.key,
+ });
+ expect(publish).not.toHaveBeenCalled();
+ const task = await createTask({
+ projectId: project.id,
+ currentUserId: user.id,
+ title: "submitted",
+ status: "to-do",
+ description: `/api/asset/${asset.id}`,
+ draftAssetIds: [asset.id],
+ });
+ expect(
+ await db.query.assetTable.findFirst({
+ where: eq(schema.assetTable.id, asset.id),
+ }),
+ ).toMatchObject({ taskId: task.id, surface: "description" });
+ expect(publish).toHaveBeenCalledTimes(1);
+ expect(publish).toHaveBeenCalledWith(
+ "task.created",
+ expect.objectContaining({ taskId: task.id }),
+ );
+ });
+ it("cannot claim an upload belonging to another creator or project", async () => {
+ const { user, workspace } = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+ const outsider = await createWorkspaceMember();
+ const [asset] = await db
+ .insert(schema.assetTable)
+ .values({
+ workspaceId: workspace.id,
+ projectId: project.id,
+ objectKey: "other-owner",
+ filename: "x",
+ mimeType: "image/png",
+ size: 12,
+ surface: "draft",
+ createdBy: outsider.user.id,
+ })
+ .returning();
+ await expect(
+ createTask({
+ projectId: project.id,
+ currentUserId: user.id,
+ title: "bad",
+ status: "to-do",
++ description: `/api/asset/${asset.id}`,
+ draftAssetIds: [asset.id],
+ }),
+ ).rejects.toThrow("staged uploads");
+ expect(await db.query.taskTable.findMany()).toHaveLength(0);
+ expect(publish).not.toHaveBeenCalled();
+ });
+ it("cannot submit an upload before finalization", async () => {
+ const { user, workspace } = await createWorkspaceMember();
+ const { project } = await createProjectFixture({
+ workspaceId: workspace.id,
+ });
+ await stageTaskAssetUpload(project.id, user.id, {
+ filename: "image.png",
+ contentType: "image/png",
+ size: 12,
+ });
+ const [asset] = await db.query.assetTable.findMany();
+ await expect(
+ createTask({
+ projectId: project.id,
+ currentUserId: user.id,
+ title: "bad",
+ status: "to-do",
++ description: `/api/asset/${asset.id}`,
+ draftAssetIds: [asset.id],
+ }),
+ ).rejects.toThrow("staged uploads");
+ expect(await db.query.taskTable.findMany()).toHaveLength(0);
+ });
+});
+
+it("expires abandoned pending and finalized uploads without deleting published assets", async () => {
+ const { cleanupDraftUploads } =
+ await import("../../apps/api/src/scheduler/draft-upload-cleanup");
+ const { workspace, user } = await createWorkspaceMember({ role: "owner" });
+ const { project } = await createProjectFixture({ workspaceId: workspace.id });
+ await db.insert(schema.assetTable).values(
+ ["draft", "draft-pending", "description"].map((surface) => ({
+ workspaceId: workspace.id,
+ projectId: project.id,
+ surface,
+ objectKey: `synthetic-expiry-${surface}`,
+ filename: "test.png",
+ mimeType: "image/png",
+ size: 1,
+ createdBy: user.id,
+ createdAt: new Date(Date.now() - 25 * 60 * 60 * 1000),
+ })),
+ );
+ await cleanupDraftUploads();
+ expect(
+ (await db.select().from(schema.assetTable)).map((asset) => asset.surface),
+ ).toEqual(["description"]);
+ expect(
+ (await db.select().from(schema.storageCleanupTable))
+ .map((item) => item.objectKey)
+ .sort(),
+ ).toEqual(["synthetic-expiry-draft", "synthetic-expiry-draft-pending"]);
+});
++
++it("leaves removed draft attachments private and eligible for expiry", async () => {
++ const { user, workspace } = await createWorkspaceMember();
++ const { project } = await createProjectFixture({ workspaceId: workspace.id });
++ const upload = await stageTaskAssetUpload(project.id, user.id, {
++ filename: "removed.png",
++ contentType: "image/png",
++ size: 12,
++ });
++ const asset = await finalizeStagedTaskAsset(project.id, user.id, {
++ key: upload.key,
++ filename: "removed.png",
++ contentType: "image/png",
++ size: 12,
++ });
++ await createTask({
++ projectId: project.id,
++ currentUserId: user.id,
++ title: "without attachment",
++ status: "to-do",
++ description: "removed",
++ draftAssetIds: [asset.id],
++ });
++ expect(
++ await db.query.assetTable.findFirst({
++ where: eq(schema.assetTable.id, asset.id),
++ }),
++ ).toMatchObject({ taskId: null, surface: "draft" });
++});
++it("finalizes the issued object after its project moves to another workspace", async () => {
++ const { user, workspace } = await createWorkspaceMember();
++ const { project } = await createProjectFixture({ workspaceId: workspace.id });
++ const destination = await createWorkspaceMember();
++ const input = { filename: "moved.png", contentType: "image/png", size: 12 };
++ const upload = await stageTaskAssetUpload(project.id, user.id, input);
++ await db
++ .update(schema.projectTable)
++ .set({ workspaceId: destination.workspace.id })
++ .where(eq(schema.projectTable.id, project.id));
++ await db
++ .update(schema.assetTable)
++ .set({ workspaceId: destination.workspace.id })
++ .where(eq(schema.assetTable.projectId, project.id));
++ const asset = await finalizeStagedTaskAsset(project.id, user.id, {
++ ...input,
++ key: upload.key,
++ });
++ expect(
++ await db.query.assetTable.findFirst({
++ where: eq(schema.assetTable.id, asset.id),
++ }),
++ ).toMatchObject({
++ workspaceId: destination.workspace.id,
++ surface: "draft",
++ objectKey: upload.key,
++ });
++});
diff --cc tests/api-integration/staged-upload-permissions.test.ts
index 000000000,000000000..eda42ebad
new file mode 100644
--- /dev/null
+++ b/tests/api-integration/staged-upload-permissions.test.ts
@@@ -1,0 -1,0 +1,82 @@@
++import { beforeEach, expect, it, vi } from "vite-plus/test";
++import db, { schema } from "../../apps/api/src/database";
++import { createApp } from "../../apps/api/src/index";
++import { mockAuthenticatedSession } from "./helpers/auth";
++import { resetTestDatabase } from "./helpers/database";
++import {
++ createProjectFixture,
++ createWorkspaceMember,
++} from "./helpers/fixtures";
++const storage = vi.hoisted(() => ({ presign: vi.fn(), verify: vi.fn() }));
++vi.mock("../../apps/api/src/storage/s3", async (original) => ({
++ ...(await original<typeof import("../../apps/api/src/storage/s3")>()),
++ createTaskImageUploadUrl: storage.presign,
++ verifyTaskAssetUpload: storage.verify,
++}));
++beforeEach(async () => {
++ await resetTestDatabase();
++ vi.clearAllMocks();
++});
++it.each(["", "/finalize"])(
++ "rejects staged upload%s without task creation permission",
++ async (suffix) => {
++ const { user, workspace } = await createWorkspaceMember({
++ role: "draft-reader",
++ });
++ await db.insert(schema.workspaceRoleTable).values({
++ workspaceId: workspace.id,
++ role: "draft-reader",
++ permission: JSON.stringify({ task: ["read"] }),
++ });
++ const { project } = await createProjectFixture({
++ workspaceId: workspace.id,
++ });
++ mockAuthenticatedSession(user);
++ const { app } = createApp();
++ const response = await app.request(
++ `/api/task/draft-upload/${project.id}${suffix}`,
++ {
++ method: "POST",
++ headers: { "Content-Type": "application/json" },
++ body: JSON.stringify({
++ filename: "private.png",
++ contentType: "image/png",
++ size: 12,
++ surface: "description",
++ ...(suffix ? { key: "unclaimed-key" } : {}),
++ }),
++ },
++ );
++ expect(response.status).toBe(403);
++ expect(storage.presign).not.toHaveBeenCalled();
++ expect(storage.verify).not.toHaveBeenCalled();
++ },
++);
++it.each(["", "/finalize"])(
++ "rejects comment scope on staged upload%s",
++ async (suffix) => {
++ const { user, workspace } = await createWorkspaceMember({ role: "owner" });
++ const { project } = await createProjectFixture({
++ workspaceId: workspace.id,
++ });
++ mockAuthenticatedSession(user);
++ const { app } = createApp();
++ const response = await app.request(
++ `/api/task/draft-upload/${project.id}${suffix}`,
++ {
++ method: "POST",
++ headers: { "Content-Type": "application/json" },
++ body: JSON.stringify({
++ filename: "private.png",
++ contentType: "image/png",
++ size: 12,
++ surface: "comment",
++ ...(suffix ? { key: "unclaimed-key" } : {}),
++ }),
++ },
++ );
++ expect(response.status).toBe(400);
++ expect(storage.presign).not.toHaveBeenCalled();
++ expect(storage.verify).not.toHaveBeenCalled();
++ },
++);