mirror of
https://github.com/outline/outline.git
synced 2026-11-26 07:33:19 +03:00
* Set lock_timeout on request transactions Lock waits in API transactions now fail after 5s with a 503 instead of holding a pool connection until the statement timeout. * Map query timeouts to request_timeout in batch sub-requests
435 lines
13 KiB
TypeScript
435 lines
13 KiB
TypeScript
import { RateLimiterRes } from "rate-limiter-flexible";
|
|
import { DatabaseError } from "sequelize";
|
|
import env from "@server/env";
|
|
import { Collection, Document as DocumentModel } from "@server/models";
|
|
import type { Document, User } from "@server/models";
|
|
import {
|
|
buildAdmin,
|
|
buildApiKey,
|
|
buildCollection,
|
|
buildDocument,
|
|
buildUser,
|
|
} from "@server/test/factories";
|
|
import { getTestServer } from "@server/test/support";
|
|
import RateLimiter from "@server/utils/RateLimiter";
|
|
|
|
const server = getTestServer();
|
|
|
|
describe("#batch", () => {
|
|
let user: User;
|
|
let documentOne: Document;
|
|
let documentTwo: Document;
|
|
|
|
beforeEach(async () => {
|
|
user = await buildUser();
|
|
[documentOne, documentTwo] = await Promise.all([
|
|
buildDocument({ userId: user.id, teamId: user.teamId }),
|
|
buildDocument({ userId: user.id, teamId: user.teamId }),
|
|
]);
|
|
});
|
|
|
|
it("should require authentication", async () => {
|
|
const res = await server.post("/api/batch", {
|
|
body: {
|
|
requests: [{ method: "documents.info", body: { id: documentOne.id } }],
|
|
},
|
|
});
|
|
expect(res.status).toEqual(401);
|
|
});
|
|
|
|
it("should reject an empty batch", async () => {
|
|
const res = await server.post("/api/batch", user, {
|
|
body: { requests: [] },
|
|
});
|
|
expect(res.status).toEqual(400);
|
|
});
|
|
|
|
it("should reject a batch over the maximum size", async () => {
|
|
const res = await server.post("/api/batch", user, {
|
|
body: {
|
|
requests: Array.from({ length: 26 }, () => ({
|
|
method: "documents.info",
|
|
body: { id: documentOne.id },
|
|
})),
|
|
},
|
|
});
|
|
const body = await res.json();
|
|
expect(res.status).toEqual(400);
|
|
expect(body.message).toContain("at most 25");
|
|
});
|
|
|
|
it("should dispatch multiple requests and return a response for each", async () => {
|
|
const res = await server.post("/api/batch", user, {
|
|
body: {
|
|
requests: [
|
|
{
|
|
method: "documents.update",
|
|
body: { id: documentOne.id, title: "One" },
|
|
},
|
|
{
|
|
method: "documents.update",
|
|
body: { id: documentTwo.id, title: "Two" },
|
|
},
|
|
],
|
|
},
|
|
});
|
|
const body = await res.json();
|
|
expect(res.status).toEqual(200);
|
|
expect(body.data).toHaveLength(2);
|
|
|
|
expect(body.data[0].ok).toBe(true);
|
|
expect(body.data[0].status).toEqual(200);
|
|
expect(body.data[0].data.id).toEqual(documentOne.id);
|
|
expect(body.data[0].data.title).toEqual("One");
|
|
expect(body.data[0].policies).toBeTruthy();
|
|
|
|
expect(body.data[1].ok).toBe(true);
|
|
expect(body.data[1].data.title).toEqual("Two");
|
|
});
|
|
|
|
it("should dispatch across multiple resources in one batch", async () => {
|
|
const admin = await buildAdmin();
|
|
const collection = await buildCollection({
|
|
teamId: admin.teamId,
|
|
userId: admin.id,
|
|
});
|
|
const doc = await buildDocument({
|
|
teamId: admin.teamId,
|
|
userId: admin.id,
|
|
collectionId: collection.id,
|
|
});
|
|
|
|
const res = await server.post("/api/batch", admin, {
|
|
body: {
|
|
requests: [
|
|
{ method: "documents.update", body: { id: doc.id, title: "Doc" } },
|
|
{
|
|
method: "collections.update",
|
|
body: { id: collection.id, name: "Coll" },
|
|
},
|
|
],
|
|
},
|
|
});
|
|
const body = await res.json();
|
|
expect(res.status).toEqual(200);
|
|
expect(body.data[0].ok).toBe(true);
|
|
expect(body.data[0].data.title).toEqual("Doc");
|
|
expect(body.data[1].ok).toBe(true);
|
|
expect(body.data[1].data.name).toEqual("Coll");
|
|
});
|
|
|
|
it("should isolate failures so the batch succeeds partially", async () => {
|
|
const otherDocument = await buildDocument();
|
|
|
|
const res = await server.post("/api/batch", user, {
|
|
body: {
|
|
requests: [
|
|
{
|
|
method: "documents.update",
|
|
body: { id: documentOne.id, title: "Updated" },
|
|
},
|
|
{
|
|
method: "documents.update",
|
|
body: { id: otherDocument.id, title: "Denied" },
|
|
},
|
|
],
|
|
},
|
|
});
|
|
const body = await res.json();
|
|
expect(res.status).toEqual(200);
|
|
|
|
expect(body.data[0].ok).toBe(true);
|
|
expect(body.data[0].data.title).toEqual("Updated");
|
|
|
|
expect(body.data[1].ok).toBe(false);
|
|
expect([403, 404]).toContain(body.data[1].status);
|
|
expect(body.data[1].error).toBeTruthy();
|
|
});
|
|
|
|
it("should reject an unknown method", async () => {
|
|
const res = await server.post("/api/batch", user, {
|
|
body: {
|
|
requests: [
|
|
{ method: "documents.nonexistent", body: { id: documentOne.id } },
|
|
],
|
|
},
|
|
});
|
|
const body = await res.json();
|
|
expect(res.status).toEqual(200);
|
|
expect(body.data[0].ok).toBe(false);
|
|
expect(body.data[0].status).toEqual(400);
|
|
expect(body.data[0].error).toEqual("invalid_request");
|
|
});
|
|
|
|
it("should dispatch star requests across resources", async () => {
|
|
const res = await server.post("/api/batch", user, {
|
|
body: {
|
|
requests: [
|
|
{ method: "stars.create", body: { documentId: documentOne.id } },
|
|
{
|
|
method: "documents.update",
|
|
body: { id: documentOne.id, title: "Starred" },
|
|
},
|
|
],
|
|
},
|
|
});
|
|
const body = await res.json();
|
|
expect(res.status).toEqual(200);
|
|
expect(body.data[0].ok).toBe(true);
|
|
expect(body.data[0].data.documentId).toEqual(documentOne.id);
|
|
expect(body.data[1].ok).toBe(true);
|
|
expect(body.data[1].data.title).toEqual("Starred");
|
|
});
|
|
|
|
it("should dispatch pin requests in a batch", async () => {
|
|
const admin = await buildAdmin();
|
|
const doc = await buildDocument({
|
|
teamId: admin.teamId,
|
|
userId: admin.id,
|
|
});
|
|
|
|
const res = await server.post("/api/batch", admin, {
|
|
body: {
|
|
requests: [{ method: "pins.create", body: { documentId: doc.id } }],
|
|
},
|
|
});
|
|
const body = await res.json();
|
|
expect(res.status).toEqual(200);
|
|
expect(body.data[0].ok).toBe(true);
|
|
expect(body.data[0].data.documentId).toEqual(doc.id);
|
|
});
|
|
|
|
it("should apply document moves in request order", async () => {
|
|
const [source, destination] = await Promise.all([
|
|
buildCollection({ userId: user.id, teamId: user.teamId }),
|
|
buildCollection({ userId: user.id, teamId: user.teamId }),
|
|
]);
|
|
const documents = [];
|
|
for (let i = 0; i < 6; i++) {
|
|
documents.push(
|
|
await buildDocument({
|
|
userId: user.id,
|
|
teamId: user.teamId,
|
|
collectionId: source.id,
|
|
})
|
|
);
|
|
}
|
|
const ordered = documents.reverse();
|
|
|
|
const res = await server.post("/api/batch", user, {
|
|
body: {
|
|
requests: ordered.map((document) => ({
|
|
method: "documents.move",
|
|
body: { id: document.id, collectionId: destination.id },
|
|
})),
|
|
},
|
|
});
|
|
const body = await res.json();
|
|
expect(res.status).toEqual(200);
|
|
expect(body.data.every((result: { ok: boolean }) => result.ok)).toBe(true);
|
|
|
|
const reloaded = await Collection.findByPk(destination.id, {
|
|
includeDocumentStructure: true,
|
|
rejectOnEmpty: true,
|
|
});
|
|
expect(reloaded.documentStructure?.map((node) => node.id)).toEqual(
|
|
ordered.map((document) => document.id)
|
|
);
|
|
});
|
|
|
|
it("should reject a known endpoint that is not allowlisted", async () => {
|
|
// documents.list is a real route, but reads aren't permitted in a batch.
|
|
const res = await server.post("/api/batch", user, {
|
|
body: {
|
|
requests: [{ method: "documents.list", body: {} }],
|
|
},
|
|
});
|
|
const body = await res.json();
|
|
expect(res.status).toEqual(200);
|
|
expect(body.data[0].ok).toBe(false);
|
|
expect(body.data[0].status).toEqual(400);
|
|
expect(body.data[0].error).toEqual("invalid_request");
|
|
});
|
|
|
|
it("should transform errors with parity to top-level routes", async () => {
|
|
const res = await server.post("/api/batch", user, {
|
|
body: {
|
|
requests: [
|
|
{
|
|
method: "documents.archive",
|
|
body: { id: "550e8400-e29b-41d4-a716-446655440000" },
|
|
},
|
|
],
|
|
},
|
|
});
|
|
const body = await res.json();
|
|
expect(res.status).toEqual(200);
|
|
// A Sequelize EmptyResultError is transformed to a 404 not_found, matching
|
|
// what the same request would return when called directly.
|
|
expect(body.data[0].ok).toBe(false);
|
|
expect(body.data[0].status).toEqual(404);
|
|
expect(body.data[0].error).toEqual("not_found");
|
|
});
|
|
|
|
it("should return a request timeout when a sub-request waits too long for a lock", async () => {
|
|
const parent = Object.assign(
|
|
new Error("canceling statement due to lock timeout"),
|
|
{ code: "55P03", sql: "" }
|
|
);
|
|
vi.spyOn(DocumentModel, "findByPk").mockRejectedValueOnce(
|
|
new DatabaseError(parent)
|
|
);
|
|
|
|
const res = await server.post("/api/batch", user, {
|
|
body: {
|
|
requests: [
|
|
{
|
|
method: "documents.update",
|
|
body: { id: documentOne.id, title: "Updated" },
|
|
},
|
|
],
|
|
},
|
|
});
|
|
const body = await res.json();
|
|
vi.restoreAllMocks();
|
|
|
|
expect(res.status).toEqual(200);
|
|
expect(body.data[0].ok).toBe(false);
|
|
expect(body.data[0].status).toEqual(503);
|
|
expect(body.data[0].error).toEqual("request_timeout");
|
|
});
|
|
|
|
it("should surface per-request validation errors", async () => {
|
|
const res = await server.post("/api/batch", user, {
|
|
body: {
|
|
requests: [{ method: "documents.update", body: {} }],
|
|
},
|
|
});
|
|
const body = await res.json();
|
|
expect(res.status).toEqual(200);
|
|
expect(body.data[0].ok).toBe(false);
|
|
expect(body.data[0].status).toEqual(400);
|
|
});
|
|
|
|
describe("rate limiting", () => {
|
|
const originalEnabled = env.RATE_LIMITER_ENABLED;
|
|
|
|
afterEach(() => {
|
|
env.RATE_LIMITER_ENABLED = originalEnabled;
|
|
vi.restoreAllMocks();
|
|
});
|
|
|
|
it("should rate limit each sub-request against its own method", async () => {
|
|
env.RATE_LIMITER_ENABLED = true;
|
|
const consume = vi.fn().mockResolvedValue(undefined);
|
|
const getRateLimiter = vi
|
|
.spyOn(RateLimiter, "getRateLimiter")
|
|
.mockReturnValue({ consume, points: 100 } as unknown as ReturnType<
|
|
typeof RateLimiter.getRateLimiter
|
|
>);
|
|
|
|
const res = await server.post("/api/batch", user, {
|
|
body: {
|
|
requests: [
|
|
{
|
|
method: "documents.update",
|
|
body: { id: documentOne.id, title: "x" },
|
|
},
|
|
],
|
|
},
|
|
});
|
|
|
|
expect(res.status).toEqual(200);
|
|
// The dispatched method is rate limited on its own path, not /batch, so a
|
|
// batch can't be used to bypass per-endpoint limits.
|
|
expect(getRateLimiter).toHaveBeenCalledWith(
|
|
expect.stringContaining("documents.update")
|
|
);
|
|
expect(consume).toHaveBeenCalled();
|
|
});
|
|
|
|
it("should return a per-item 429 when a sub-request is rate limited", async () => {
|
|
env.RATE_LIMITER_ENABLED = true;
|
|
// A RateLimiterRes rejection signals the limit was hit (a plain Error
|
|
// would instead fail open inside the limiter middleware).
|
|
const consume = vi
|
|
.fn()
|
|
.mockRejectedValue(new RateLimiterRes(0, 60000, 1, false));
|
|
vi.spyOn(RateLimiter, "getRateLimiter").mockReturnValue({
|
|
consume,
|
|
points: 1,
|
|
} as unknown as ReturnType<typeof RateLimiter.getRateLimiter>);
|
|
|
|
const res = await server.post("/api/batch", user, {
|
|
body: {
|
|
requests: [
|
|
{
|
|
method: "documents.update",
|
|
body: { id: documentOne.id, title: "x" },
|
|
},
|
|
],
|
|
},
|
|
});
|
|
const body = await res.json();
|
|
|
|
expect(res.status).toEqual(200);
|
|
expect(body.data[0].ok).toBe(false);
|
|
expect(body.data[0].status).toEqual(429);
|
|
});
|
|
});
|
|
describe("credentials", () => {
|
|
it("should reject an API key, as dispatching requires a session", async () => {
|
|
const apiKey = await buildApiKey({ userId: user.id, scope: ["write"] });
|
|
|
|
const res = await server.post("/api/batch", {
|
|
headers: { authorization: `Bearer ${apiKey.value}` },
|
|
body: {
|
|
requests: [
|
|
{
|
|
method: "documents.update",
|
|
body: { id: documentOne.id, title: "x" },
|
|
},
|
|
],
|
|
},
|
|
});
|
|
|
|
expect(res.status).toEqual(403);
|
|
});
|
|
|
|
it("should ignore a token in a sub-request body", async () => {
|
|
// A credential for an unrelated workspace, which the parent request has
|
|
// no access to. The sub-request must run as the parent's credential.
|
|
const other = await buildUser();
|
|
const otherDocument = await buildDocument({
|
|
userId: other.id,
|
|
teamId: other.teamId,
|
|
});
|
|
const otherKey = await buildApiKey({ userId: other.id, scope: ["*"] });
|
|
const title = otherDocument.title;
|
|
|
|
const res = await server.post(`/api/batch`, user, {
|
|
body: {
|
|
requests: [
|
|
{
|
|
method: "documents.update",
|
|
body: {
|
|
id: otherDocument.id,
|
|
title: "smuggled",
|
|
token: otherKey.value,
|
|
},
|
|
},
|
|
],
|
|
},
|
|
});
|
|
const body = await res.json();
|
|
|
|
expect(res.status).toEqual(200);
|
|
expect(body.data[0].ok).toBe(false);
|
|
expect(body.data[0].status).toEqual(403);
|
|
|
|
await otherDocument.reload();
|
|
expect(otherDocument.title).toEqual(title);
|
|
});
|
|
});
|
|
});
|