refactor: add server side validation schema for attachments (#4606)
* refactor: schema for attachments.create * refactor: schema for attachments.delete * refactor: remove deprecated "public" request param
This commit is contained in:
committed by
GitHub
parent
f3469d25fe
commit
318e1df13b
388
server/routes/api/attachments/attachments.test.ts
Normal file
388
server/routes/api/attachments/attachments.test.ts
Normal file
@@ -0,0 +1,388 @@
|
||||
import { AttachmentPreset, CollectionPermission } from "@shared/types";
|
||||
import { CollectionUser } from "@server/models";
|
||||
import Attachment from "@server/models/Attachment";
|
||||
import {
|
||||
buildUser,
|
||||
buildAdmin,
|
||||
buildCollection,
|
||||
buildAttachment,
|
||||
buildDocument,
|
||||
buildViewer,
|
||||
} from "@server/test/factories";
|
||||
import { getTestServer } from "@server/test/support";
|
||||
|
||||
jest.mock("@server/utils/s3");
|
||||
|
||||
const server = getTestServer();
|
||||
|
||||
describe("#attachments.create", () => {
|
||||
it("should require authentication", async () => {
|
||||
const res = await server.post("/api/attachments.create");
|
||||
expect(res.status).toEqual(401);
|
||||
});
|
||||
|
||||
describe("member", () => {
|
||||
it("should allow upload using avatar preset", async () => {
|
||||
const user = await buildUser();
|
||||
const res = await server.post("/api/attachments.create", {
|
||||
body: {
|
||||
name: "test.png",
|
||||
contentType: "image/png",
|
||||
size: 1000,
|
||||
preset: AttachmentPreset.Avatar,
|
||||
token: user.getJwtToken(),
|
||||
},
|
||||
});
|
||||
expect(res.status).toEqual(200);
|
||||
|
||||
const body = await res.json();
|
||||
const attachment = await Attachment.findByPk(body.data.attachment.id);
|
||||
expect(attachment!.expiresAt).toBeNull();
|
||||
});
|
||||
|
||||
it("should allow attachment creation for documents", async () => {
|
||||
const user = await buildUser();
|
||||
const document = await buildDocument({ teamId: user.teamId });
|
||||
|
||||
const res = await server.post("/api/attachments.create", {
|
||||
body: {
|
||||
name: "test.png",
|
||||
contentType: "image/png",
|
||||
size: 1000,
|
||||
documentId: document.id,
|
||||
preset: AttachmentPreset.DocumentAttachment,
|
||||
token: user.getJwtToken(),
|
||||
},
|
||||
});
|
||||
expect(res.status).toEqual(200);
|
||||
});
|
||||
|
||||
it("should create expiring attachment using import preset", async () => {
|
||||
const user = await buildUser();
|
||||
const res = await server.post("/api/attachments.create", {
|
||||
body: {
|
||||
name: "test.zip",
|
||||
contentType: "application/zip",
|
||||
size: 10000,
|
||||
preset: AttachmentPreset.Import,
|
||||
token: user.getJwtToken(),
|
||||
},
|
||||
});
|
||||
expect(res.status).toEqual(200);
|
||||
|
||||
const body = await res.json();
|
||||
const attachment = await Attachment.findByPk(body.data.attachment.id);
|
||||
expect(attachment!.expiresAt).toBeTruthy();
|
||||
});
|
||||
|
||||
it("should not allow attachment creation for other documents", async () => {
|
||||
const user = await buildUser();
|
||||
const document = await buildDocument();
|
||||
|
||||
const res = await server.post("/api/attachments.create", {
|
||||
body: {
|
||||
name: "test.png",
|
||||
contentType: "image/png",
|
||||
size: 1000,
|
||||
documentId: document.id,
|
||||
preset: AttachmentPreset.DocumentAttachment,
|
||||
token: user.getJwtToken(),
|
||||
},
|
||||
});
|
||||
expect(res.status).toEqual(403);
|
||||
});
|
||||
|
||||
it("should not allow file upload for avatar preset", async () => {
|
||||
const user = await buildUser();
|
||||
const res = await server.post("/api/attachments.create", {
|
||||
body: {
|
||||
name: "test.pdf",
|
||||
contentType: "application/pdf",
|
||||
size: 1000,
|
||||
preset: AttachmentPreset.Avatar,
|
||||
token: user.getJwtToken(),
|
||||
},
|
||||
});
|
||||
expect(res.status).toEqual(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe("viewer", () => {
|
||||
it("should allow attachment creation for documents in collections with edit access", async () => {
|
||||
const user = await buildViewer();
|
||||
const collection = await buildCollection({
|
||||
teamId: user.teamId,
|
||||
permission: null,
|
||||
});
|
||||
const document = await buildDocument({
|
||||
teamId: user.teamId,
|
||||
collectionId: collection.id,
|
||||
});
|
||||
|
||||
await CollectionUser.create({
|
||||
createdById: user.id,
|
||||
collectionId: collection.id,
|
||||
userId: user.id,
|
||||
permission: CollectionPermission.ReadWrite,
|
||||
});
|
||||
|
||||
const res = await server.post("/api/attachments.create", {
|
||||
body: {
|
||||
name: "test.png",
|
||||
contentType: "image/png",
|
||||
size: 1000,
|
||||
documentId: document.id,
|
||||
preset: AttachmentPreset.DocumentAttachment,
|
||||
token: user.getJwtToken(),
|
||||
},
|
||||
});
|
||||
expect(res.status).toEqual(200);
|
||||
});
|
||||
|
||||
it("should not allow attachment creation for documents", async () => {
|
||||
const user = await buildViewer();
|
||||
const document = await buildDocument({ teamId: user.teamId });
|
||||
|
||||
const res = await server.post("/api/attachments.create", {
|
||||
body: {
|
||||
name: "test.png",
|
||||
contentType: "image/png",
|
||||
size: 1000,
|
||||
documentId: document.id,
|
||||
preset: AttachmentPreset.DocumentAttachment,
|
||||
token: user.getJwtToken(),
|
||||
},
|
||||
});
|
||||
expect(res.status).toEqual(403);
|
||||
});
|
||||
|
||||
it("should allow upload using avatar preset", async () => {
|
||||
const user = await buildViewer();
|
||||
const res = await server.post("/api/attachments.create", {
|
||||
body: {
|
||||
name: "test.png",
|
||||
contentType: "image/png",
|
||||
size: 1000,
|
||||
preset: AttachmentPreset.Avatar,
|
||||
token: user.getJwtToken(),
|
||||
},
|
||||
});
|
||||
expect(res.status).toEqual(200);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("#attachments.delete", () => {
|
||||
it("should require authentication", async () => {
|
||||
const res = await server.post("/api/attachments.delete");
|
||||
expect(res.status).toEqual(401);
|
||||
});
|
||||
|
||||
it("should allow deleting an attachment belonging to a document user has access to", async () => {
|
||||
const user = await buildUser();
|
||||
const attachment = await buildAttachment({
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
});
|
||||
const res = await server.post("/api/attachments.delete", {
|
||||
body: {
|
||||
token: user.getJwtToken(),
|
||||
id: attachment.id,
|
||||
},
|
||||
});
|
||||
expect(res.status).toEqual(200);
|
||||
expect(await Attachment.count()).toEqual(0);
|
||||
});
|
||||
|
||||
it("should allow deleting an attachment without a document created by user", async () => {
|
||||
const user = await buildUser();
|
||||
const attachment = await buildAttachment({
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
});
|
||||
attachment.documentId = null;
|
||||
await attachment.save();
|
||||
const res = await server.post("/api/attachments.delete", {
|
||||
body: {
|
||||
token: user.getJwtToken(),
|
||||
id: attachment.id,
|
||||
},
|
||||
});
|
||||
expect(res.status).toEqual(200);
|
||||
expect(await Attachment.count()).toEqual(0);
|
||||
});
|
||||
|
||||
it("should allow deleting an attachment without a document if admin", async () => {
|
||||
const user = await buildAdmin();
|
||||
const attachment = await buildAttachment({
|
||||
teamId: user.teamId,
|
||||
});
|
||||
attachment.documentId = null;
|
||||
await attachment.save();
|
||||
const res = await server.post("/api/attachments.delete", {
|
||||
body: {
|
||||
token: user.getJwtToken(),
|
||||
id: attachment.id,
|
||||
},
|
||||
});
|
||||
expect(res.status).toEqual(200);
|
||||
expect(await Attachment.count()).toEqual(0);
|
||||
});
|
||||
|
||||
it("should not allow deleting an attachment in another team", async () => {
|
||||
const user = await buildAdmin();
|
||||
const attachment = await buildAttachment();
|
||||
attachment.documentId = null;
|
||||
await attachment.save();
|
||||
const res = await server.post("/api/attachments.delete", {
|
||||
body: {
|
||||
token: user.getJwtToken(),
|
||||
id: attachment.id,
|
||||
},
|
||||
});
|
||||
expect(res.status).toEqual(403);
|
||||
});
|
||||
|
||||
it("should not allow deleting an attachment without a document", async () => {
|
||||
const user = await buildUser();
|
||||
const attachment = await buildAttachment({
|
||||
teamId: user.teamId,
|
||||
});
|
||||
attachment.documentId = null;
|
||||
await attachment.save();
|
||||
const res = await server.post("/api/attachments.delete", {
|
||||
body: {
|
||||
token: user.getJwtToken(),
|
||||
id: attachment.id,
|
||||
},
|
||||
});
|
||||
expect(res.status).toEqual(403);
|
||||
});
|
||||
|
||||
it("should not allow deleting an attachment belonging to a document user does not have access to", async () => {
|
||||
const user = await buildUser();
|
||||
const collection = await buildCollection({
|
||||
permission: null,
|
||||
});
|
||||
const document = await buildDocument({
|
||||
teamId: collection.teamId,
|
||||
userId: collection.createdById,
|
||||
collectionId: collection.id,
|
||||
});
|
||||
const attachment = await buildAttachment({
|
||||
teamId: document.teamId,
|
||||
userId: document.createdById,
|
||||
documentId: document.id,
|
||||
acl: "private",
|
||||
});
|
||||
const res = await server.post("/api/attachments.delete", {
|
||||
body: {
|
||||
token: user.getJwtToken(),
|
||||
id: attachment.id,
|
||||
},
|
||||
});
|
||||
expect(res.status).toEqual(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe("#attachments.redirect", () => {
|
||||
it("should require authentication", async () => {
|
||||
const res = await server.post("/api/attachments.redirect");
|
||||
expect(res.status).toEqual(401);
|
||||
});
|
||||
|
||||
it("should return a redirect for an attachment belonging to a document user has access to", async () => {
|
||||
const user = await buildUser();
|
||||
const attachment = await buildAttachment({
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
});
|
||||
const res = await server.post("/api/attachments.redirect", {
|
||||
body: {
|
||||
token: user.getJwtToken(),
|
||||
id: attachment.id,
|
||||
},
|
||||
redirect: "manual",
|
||||
});
|
||||
expect(res.status).toEqual(302);
|
||||
});
|
||||
|
||||
it("should return a redirect for an attachment belonging to a trashed document user has access to", async () => {
|
||||
const user = await buildUser();
|
||||
const collection = await buildCollection({
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
});
|
||||
const document = await buildDocument({
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
collectionId: collection.id,
|
||||
deletedAt: new Date(),
|
||||
});
|
||||
const attachment = await buildAttachment({
|
||||
documentId: document.id,
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
});
|
||||
const res = await server.post("/api/attachments.redirect", {
|
||||
body: {
|
||||
token: user.getJwtToken(),
|
||||
id: attachment.id,
|
||||
},
|
||||
redirect: "manual",
|
||||
});
|
||||
expect(res.status).toEqual(302);
|
||||
});
|
||||
|
||||
it("should always return a redirect for a public attachment", async () => {
|
||||
const user = await buildUser();
|
||||
const collection = await buildCollection({
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
permission: null,
|
||||
});
|
||||
const document = await buildDocument({
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
collectionId: collection.id,
|
||||
});
|
||||
const attachment = await buildAttachment({
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
documentId: document.id,
|
||||
});
|
||||
const res = await server.post("/api/attachments.redirect", {
|
||||
body: {
|
||||
token: user.getJwtToken(),
|
||||
id: attachment.id,
|
||||
},
|
||||
redirect: "manual",
|
||||
});
|
||||
expect(res.status).toEqual(302);
|
||||
});
|
||||
|
||||
it("should not return a redirect for a private attachment belonging to a document user does not have access to", async () => {
|
||||
const user = await buildUser();
|
||||
const collection = await buildCollection({
|
||||
permission: null,
|
||||
});
|
||||
const document = await buildDocument({
|
||||
teamId: collection.teamId,
|
||||
userId: collection.createdById,
|
||||
collectionId: collection.id,
|
||||
});
|
||||
const attachment = await buildAttachment({
|
||||
teamId: document.teamId,
|
||||
userId: document.createdById,
|
||||
documentId: document.id,
|
||||
acl: "private",
|
||||
});
|
||||
const res = await server.post("/api/attachments.redirect", {
|
||||
body: {
|
||||
token: user.getJwtToken(),
|
||||
id: attachment.id,
|
||||
},
|
||||
});
|
||||
expect(res.status).toEqual(403);
|
||||
});
|
||||
});
|
||||
170
server/routes/api/attachments/attachments.ts
Normal file
170
server/routes/api/attachments/attachments.ts
Normal file
@@ -0,0 +1,170 @@
|
||||
import Router from "koa-router";
|
||||
import { v4 as uuidv4 } from "uuid";
|
||||
import { AttachmentPreset } from "@shared/types";
|
||||
import { bytesToHumanReadable } from "@shared/utils/files";
|
||||
import { AttachmentValidation } from "@shared/validations";
|
||||
import { AuthorizationError, ValidationError } from "@server/errors";
|
||||
import auth from "@server/middlewares/authentication";
|
||||
import { transaction } from "@server/middlewares/transaction";
|
||||
import validate from "@server/middlewares/validate";
|
||||
import { Attachment, Document, Event } from "@server/models";
|
||||
import AttachmentHelper from "@server/models/helpers/AttachmentHelper";
|
||||
import { authorize } from "@server/policies";
|
||||
import { presentAttachment } from "@server/presenters";
|
||||
import { APIContext, ContextWithState } from "@server/types";
|
||||
import { getPresignedPost, publicS3Endpoint } from "@server/utils/s3";
|
||||
import { assertIn, assertUuid } from "@server/validation";
|
||||
import * as T from "./schema";
|
||||
|
||||
const router = new Router();
|
||||
|
||||
router.post(
|
||||
"attachments.create",
|
||||
auth(),
|
||||
validate(T.AttachmentsCreateSchema),
|
||||
transaction(),
|
||||
async (ctx: APIContext<T.AttachmentCreateReq>) => {
|
||||
const { name, documentId, contentType, size, preset } = ctx.input;
|
||||
const { user, transaction } = ctx.state;
|
||||
|
||||
// All user types can upload an avatar so no additional authorization is needed.
|
||||
if (preset === AttachmentPreset.Avatar) {
|
||||
assertIn(contentType, AttachmentValidation.avatarContentTypes);
|
||||
} else if (preset === AttachmentPreset.DocumentAttachment && documentId) {
|
||||
const document = await Document.findByPk(documentId, {
|
||||
userId: user.id,
|
||||
});
|
||||
authorize(user, "update", document);
|
||||
} else {
|
||||
authorize(user, "createAttachment", user.team);
|
||||
}
|
||||
|
||||
const maxUploadSize = AttachmentHelper.presetToMaxUploadSize(preset);
|
||||
|
||||
if (size > maxUploadSize) {
|
||||
throw ValidationError(
|
||||
`Sorry, this file is too large – the maximum size is ${bytesToHumanReadable(
|
||||
maxUploadSize
|
||||
)}`
|
||||
);
|
||||
}
|
||||
|
||||
const modelId = uuidv4();
|
||||
const acl = AttachmentHelper.presetToAcl(preset);
|
||||
const key = AttachmentHelper.getKey({
|
||||
acl,
|
||||
id: modelId,
|
||||
name,
|
||||
userId: user.id,
|
||||
});
|
||||
|
||||
const attachment = await Attachment.create(
|
||||
{
|
||||
id: modelId,
|
||||
key,
|
||||
acl,
|
||||
size,
|
||||
expiresAt: AttachmentHelper.presetToExpiry(preset),
|
||||
contentType,
|
||||
documentId,
|
||||
teamId: user.teamId,
|
||||
userId: user.id,
|
||||
},
|
||||
{ transaction }
|
||||
);
|
||||
await Event.create(
|
||||
{
|
||||
name: "attachments.create",
|
||||
data: {
|
||||
name,
|
||||
},
|
||||
modelId,
|
||||
teamId: user.teamId,
|
||||
actorId: user.id,
|
||||
ip: ctx.request.ip,
|
||||
},
|
||||
{ transaction }
|
||||
);
|
||||
|
||||
const presignedPost = await getPresignedPost(
|
||||
key,
|
||||
acl,
|
||||
maxUploadSize,
|
||||
contentType
|
||||
);
|
||||
|
||||
ctx.body = {
|
||||
data: {
|
||||
uploadUrl: publicS3Endpoint(),
|
||||
form: {
|
||||
"Cache-Control": "max-age=31557600",
|
||||
"Content-Type": contentType,
|
||||
...presignedPost.fields,
|
||||
},
|
||||
attachment: presentAttachment(attachment),
|
||||
},
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
router.post(
|
||||
"attachments.delete",
|
||||
auth(),
|
||||
validate(T.AttachmentDeleteSchema),
|
||||
async (ctx: APIContext<T.AttachmentDeleteReq>) => {
|
||||
const { id } = ctx.input;
|
||||
const { user } = ctx.state;
|
||||
const attachment = await Attachment.findByPk(id, {
|
||||
rejectOnEmpty: true,
|
||||
});
|
||||
|
||||
if (attachment.documentId) {
|
||||
const document = await Document.findByPk(attachment.documentId, {
|
||||
userId: user.id,
|
||||
});
|
||||
authorize(user, "update", document);
|
||||
}
|
||||
|
||||
authorize(user, "delete", attachment);
|
||||
await attachment.destroy();
|
||||
await Event.create({
|
||||
name: "attachments.delete",
|
||||
teamId: user.teamId,
|
||||
actorId: user.id,
|
||||
ip: ctx.request.ip,
|
||||
});
|
||||
|
||||
ctx.body = {
|
||||
success: true,
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
const handleAttachmentsRedirect = async (ctx: ContextWithState) => {
|
||||
const id = ctx.request.body?.id ?? ctx.request.query?.id;
|
||||
assertUuid(id, "id is required");
|
||||
|
||||
const { user } = ctx.state;
|
||||
const attachment = await Attachment.findByPk(id, {
|
||||
rejectOnEmpty: true,
|
||||
});
|
||||
|
||||
if (attachment.isPrivate && attachment.teamId !== user.teamId) {
|
||||
throw AuthorizationError();
|
||||
}
|
||||
|
||||
await attachment.update({
|
||||
lastAccessedAt: new Date(),
|
||||
});
|
||||
|
||||
if (attachment.isPrivate) {
|
||||
ctx.redirect(await attachment.signedUrl);
|
||||
} else {
|
||||
ctx.redirect(attachment.canonicalUrl);
|
||||
}
|
||||
};
|
||||
|
||||
router.get("attachments.redirect", auth(), handleAttachmentsRedirect);
|
||||
router.post("attachments.redirect", auth(), handleAttachmentsRedirect);
|
||||
|
||||
export default router;
|
||||
1
server/routes/api/attachments/index.ts
Normal file
1
server/routes/api/attachments/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { default } from "./attachments";
|
||||
28
server/routes/api/attachments/schema.ts
Normal file
28
server/routes/api/attachments/schema.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { z } from "zod";
|
||||
import { AttachmentPreset } from "@shared/types";
|
||||
|
||||
export const AttachmentsCreateSchema = z.object({
|
||||
/** Attachment name */
|
||||
name: z.string(),
|
||||
|
||||
/** Id of the document to which the Attachment belongs */
|
||||
documentId: z.string().uuid().optional(),
|
||||
|
||||
/** File size of the Attachment */
|
||||
size: z.number(),
|
||||
|
||||
/** Content-Type of the Attachment */
|
||||
contentType: z.string().optional().default("application/octet-stream"),
|
||||
|
||||
/** Attachment type */
|
||||
preset: z.nativeEnum(AttachmentPreset),
|
||||
});
|
||||
|
||||
export type AttachmentCreateReq = z.infer<typeof AttachmentsCreateSchema>;
|
||||
|
||||
export const AttachmentDeleteSchema = z.object({
|
||||
/** Id of the attachment to be deleted */
|
||||
id: z.string().uuid(),
|
||||
});
|
||||
|
||||
export type AttachmentDeleteReq = z.infer<typeof AttachmentDeleteSchema>;
|
||||
Reference in New Issue
Block a user