Files

361 lines
10 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import Router from "@koa/router";
import type { Transaction, WhereOptions } from "sequelize";
import { randomUUID } from "node:crypto";
import { AttachmentPreset } from "@shared/types";
import { bytesToHumanReadable, getFileNameFromUrl } from "@shared/utils/files";
import env from "@server/env";
import { AttachmentValidation } from "@shared/validations";
import { withTransaction } from "@server/context";
import {
AuthorizationError,
InvalidRequestError,
ValidationError,
} from "@server/errors";
import auth from "@server/middlewares/authentication";
import { rateLimiter } from "@server/middlewares/rateLimiter";
import { transaction } from "@server/middlewares/transaction";
import validate from "@server/middlewares/validate";
import type { User } from "@server/models";
import { Attachment, Document, Template } from "@server/models";
import AttachmentHelper from "@server/models/helpers/AttachmentHelper";
import { authorize } from "@server/policies";
import { presentAttachment, presentPolicies } from "@server/presenters";
import UploadAttachmentFromUrlTask from "@server/queues/tasks/UploadAttachmentFromUrlTask";
import pagination from "@server/routes/api/middlewares/pagination";
import { sequelize } from "@server/storage/database";
import FileStorage from "@server/storage/files";
import BaseStorage from "@server/storage/files/BaseStorage";
import type { Context } from "@server/types";
import { RateLimiterStrategy } from "@server/utils/RateLimiter";
import { assertIn } from "@server/validation";
import * as T from "./schema";
const router = new Router();
/**
* Authorizes an action on the document or template that an attachment belongs to.
*
* @param user The user to authorize.
* @param action The action to authorize.
* @param documentId The ID of the document or template.
* @param transaction An optional transaction to load the model in.
* @throws AuthorizationError if the user cannot perform the action.
*/
async function authorizeParent(
user: User,
action: "read" | "update",
documentId: string,
transaction?: Transaction
) {
const document = await Document.findByPk(documentId, {
userId: user.id,
transaction,
});
if (document) {
authorize(user, action, document);
return;
}
const template = await Template.findByPk(documentId, {
userId: user.id,
transaction,
});
authorize(user, action, template);
}
router.post(
"attachments.list",
auth(),
pagination(),
validate(T.AttachmentsListSchema),
async (ctx: Context<T.AttachmentsListReq>) => {
const { documentId, userId } = ctx.input.body;
const { user } = ctx.auth;
const where: WhereOptions<Attachment> = {
teamId: user.teamId,
};
// If a specific user is passed then add to filters
if (userId && user.isAdmin) {
where.userId = userId;
} else {
where.userId = user.id;
}
// If a specific document is passed then add to filters
if (documentId) {
await authorizeParent(user, "read", documentId);
where.documentId = documentId;
}
const [attachments, total] = await Promise.all([
Attachment.findAll({
where,
order: [["createdAt", "DESC"]],
offset: ctx.state.pagination.offset,
limit: ctx.state.pagination.limit,
}),
Attachment.count({
where,
}),
]);
ctx.body = {
pagination: { ...ctx.state.pagination, total },
data: attachments.map(presentAttachment),
policies: presentPolicies(user, attachments),
};
}
);
router.post(
"attachments.create",
rateLimiter(RateLimiterStrategy.TwentyFivePerMinute),
auth(),
validate(T.AttachmentsCreateSchema),
transaction(),
async (ctx: Context<T.AttachmentCreateReq>) => {
const { id, name, documentId, contentType, size, preset } = ctx.input.body;
const { auth, transaction } = ctx;
const { user } = auth;
if (documentId) {
await authorizeParent(user, "update", documentId, transaction);
}
// 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.WorkspaceImport) {
authorize(user, "createImport", user.team);
}
if (preset === AttachmentPreset.Emoji) {
assertIn(contentType, AttachmentValidation.emojiContentTypes);
}
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 = id ?? randomUUID();
const acl = AttachmentHelper.presetToAcl(preset);
const key = AttachmentHelper.getKey({
id: modelId,
name,
userId: user.id,
});
const attachment = await Attachment.createWithCtx(ctx, {
id: modelId,
key,
acl,
size,
expiresAt: AttachmentHelper.presetToExpiry(preset),
contentType,
documentId,
teamId: user.teamId,
userId: user.id,
});
const usePut = env.AWS_S3_UPLOAD_METHOD === "put";
if (usePut) {
const presignedPut = await FileStorage.getPresignedPut(
key,
acl,
size,
contentType
);
if (!presignedPut) {
throw InvalidRequestError(
`The current storage backend does not support PUT uploads. Set AWS_S3_UPLOAD_METHOD to "post" or use an S3-compatible storage provider.`
);
}
ctx.body = {
data: {
mode: "put",
url: presignedPut.url,
headers: presignedPut.headers,
attachment: {
...presentAttachment(attachment),
url: attachment.redirectUrl,
},
},
};
} else {
const presignedPost = await FileStorage.getPresignedPost(
ctx,
key,
acl,
maxUploadSize,
contentType
);
ctx.body = {
data: {
mode: "post",
uploadUrl: FileStorage.getUploadUrl(),
form: {
"Cache-Control": "max-age=31557600",
"Content-Type": contentType,
...presignedPost.fields,
},
attachment: {
...presentAttachment(attachment),
url: attachment.redirectUrl,
},
},
};
}
}
);
router.post(
"attachments.createFromUrl",
rateLimiter(RateLimiterStrategy.TwentyFivePerMinute),
auth(),
validate(T.AttachmentsCreateFromUrlSchema),
async (ctx: Context<T.AttachmentCreateFromUrlReq>) => {
const { id, url, documentId, preset } = ctx.input.body;
const { user } = ctx.auth;
if (preset !== AttachmentPreset.DocumentAttachment || !documentId) {
throw ValidationError(
"Only document attachments can be created from a URL"
);
}
await authorizeParent(user, "update", documentId);
const name = getFileNameFromUrl(url) ?? "file";
const modelId = id ?? randomUUID();
const acl = AttachmentHelper.presetToAcl(preset);
const key = AttachmentHelper.getKey({
id: modelId,
name,
userId: user.id,
});
// Does not use transaction middleware, as attachment must be persisted
// before the job is scheduled.
const attachment = await sequelize.transaction(async (transaction) =>
Attachment.createWithCtx(withTransaction(ctx, transaction), {
id: modelId,
key,
acl,
size: 0,
expiresAt: AttachmentHelper.presetToExpiry(preset),
contentType: "application/octet-stream",
documentId,
teamId: user.teamId,
userId: user.id,
})
);
const job = await new UploadAttachmentFromUrlTask().schedule({
attachmentId: attachment.id,
url,
});
const response = await job.finished();
if ("error" in response) {
await sequelize.transaction(async (transaction) =>
attachment.destroyWithCtx(withTransaction(ctx, transaction))
);
throw InvalidRequestError(response.error);
}
await attachment.reload();
ctx.body = {
data: presentAttachment(attachment),
};
}
);
router.post(
"attachments.delete",
auth(),
validate(T.AttachmentDeleteSchema),
transaction(),
async (ctx: Context<T.AttachmentDeleteReq>) => {
const { id } = ctx.input.body;
const { user } = ctx.auth;
const { transaction } = ctx;
const attachment = await Attachment.findByPk(id, {
rejectOnEmpty: true,
lock: transaction.LOCK.UPDATE,
transaction,
});
if (attachment.documentId) {
await authorizeParent(user, "update", attachment.documentId, transaction);
}
authorize(user, "delete", attachment);
await attachment.destroyWithCtx(ctx);
ctx.body = {
success: true,
};
}
);
const handleAttachmentsRedirect = async (
ctx: Context<T.AttachmentsRedirectReq>
) => {
const id = (ctx.input.body.id ?? ctx.input.query.id) as string;
const user = ctx.auth?.user;
const attachment = await Attachment.findByPk(id, {
rejectOnEmpty: true,
});
// Private attachments are accessible to any member of the workspace they
// belong to. This is intentional and not a permission bypass – attachments
// are owned by the workspace (team), not by individual documents. Checking
// document-level permissions here would be insufficient anyway as attachments
// can exist independently of documents.
if (attachment.isPrivate && attachment.teamId !== user?.teamId) {
throw AuthorizationError();
}
await attachment.updateAccessedAt();
if (attachment.isStoredInPublicBucket) {
ctx.set("Cache-Control", `max-age=604800, immutable`);
ctx.redirect(attachment.canonicalUrl);
} else {
ctx.set(
"Cache-Control",
`max-age=${BaseStorage.getSignedUrlMinimumLifetime()}, immutable`
);
ctx.redirect(await attachment.signedUrl);
}
};
router.register(
"attachments.redirect",
["get", "post"],
[
auth({ optional: true }),
validate(T.AttachmentsRedirectSchema),
handleAttachmentsRedirect,
]
);
export default router;