Skip to content

Commit e783cdc

Browse files
ericallamTrigger.dev RepoOps
authored andcommitted
fix(webapp): authenticate token routes before parsing the request
Authenticate token routes before parsing the request. Mono-RevId: 9ccdd5ff01935ea2b9406d7e62c3637613d97f67
1 parent cc0c6e9 commit e783cdc

2 files changed

Lines changed: 186 additions & 31 deletions

File tree

‎apps/webapp/app/services/routeBuilders/apiBuilder.server.ts‎

Lines changed: 45 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -868,6 +868,7 @@ type PATActionRouteBuilderOptions<
868868
// A single verb, or a list for multi-method routes (e.g. ["PATCH", "DELETE"]).
869869
method?: PATActionMethod | PATActionMethod[];
870870
body?: TBodySchema;
871+
maxContentLength?: number;
871872
// `identityOnly` waives the contextless refusal for reads that mutate nothing. An action
872873
// never qualifies, so it cannot be declared here.
873874
identityOnly?: never;
@@ -923,6 +924,7 @@ export function createActionPATApiRoute<
923924
context: contextFn,
924925
authorization,
925926
method,
927+
maxContentLength,
926928
} = options;
927929

928930
return async function action({ request, params }: ActionFunctionArgs) {
@@ -993,37 +995,6 @@ export function createActionPATApiRoute<
993995
parsedHeaders = headers.data;
994996
}
995997

996-
let parsedBody: any = undefined;
997-
if (bodySchema) {
998-
const rawBody = await request.text();
999-
if (rawBody.length === 0) {
1000-
return await wrapResponse(
1001-
request,
1002-
json({ error: "Request body is empty" }, { status: 400 }),
1003-
corsStrategy !== "none"
1004-
);
1005-
}
1006-
1007-
const rawParsedJson = safeJsonParse(rawBody);
1008-
if (!rawParsedJson) {
1009-
return await wrapResponse(
1010-
request,
1011-
json({ error: "Invalid JSON" }, { status: 400 }),
1012-
corsStrategy !== "none"
1013-
);
1014-
}
1015-
1016-
const body = bodySchema.safeParse(rawParsedJson);
1017-
if (!body.success) {
1018-
return await wrapResponse(
1019-
request,
1020-
json({ error: fromZodError(body.error).toString() }, { status: 400 }),
1021-
corsStrategy !== "none"
1022-
);
1023-
}
1024-
parsedBody = body.data;
1025-
}
1026-
1027998
const apiVersion = getApiVersion(request);
1028999

10291000
// `context` resolves the target org/project so the plugin can compute the
@@ -1090,6 +1061,49 @@ export function createActionPATApiRoute<
10901061
}
10911062
}
10921063

1064+
if (maxContentLength) {
1065+
const contentLength = request.headers.get("content-length");
1066+
1067+
if (!contentLength || parseInt(contentLength) > maxContentLength) {
1068+
return await wrapResponse(
1069+
request,
1070+
json({ error: "Request body too large" }, { status: 413 }),
1071+
corsStrategy !== "none"
1072+
);
1073+
}
1074+
}
1075+
1076+
let parsedBody: any = undefined;
1077+
if (bodySchema) {
1078+
const rawBody = await request.text();
1079+
if (rawBody.length === 0) {
1080+
return await wrapResponse(
1081+
request,
1082+
json({ error: "Request body is empty" }, { status: 400 }),
1083+
corsStrategy !== "none"
1084+
);
1085+
}
1086+
1087+
const rawParsedJson = safeJsonParse(rawBody);
1088+
if (!rawParsedJson) {
1089+
return await wrapResponse(
1090+
request,
1091+
json({ error: "Invalid JSON" }, { status: 400 }),
1092+
corsStrategy !== "none"
1093+
);
1094+
}
1095+
1096+
const body = bodySchema.safeParse(rawParsedJson);
1097+
if (!body.success) {
1098+
return await wrapResponse(
1099+
request,
1100+
json({ error: fromZodError(body.error).toString() }, { status: 400 }),
1101+
corsStrategy !== "none"
1102+
);
1103+
}
1104+
parsedBody = body.data;
1105+
}
1106+
10931107
// PAT auth carries `userId` but no environment — enrich the scope the
10941108
// Express middleware established so Sentry events get user attribution.
10951109
tenantContext.enrich({ userId: authenticationResult.userId });
Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
import { buildJwtAbility } from "@trigger.dev/rbac";
2+
import { json } from "@remix-run/server-runtime";
3+
import { beforeEach, describe, expect, it, vi } from "vitest";
4+
import { z } from "zod";
5+
import * as webappRouteMocks from "./helpers/webappRouteMocks";
6+
7+
const mocks = vi.hoisted(() => ({
8+
authenticateUserActor: vi.fn(),
9+
authenticatePat: vi.fn(),
10+
}));
11+
12+
vi.mock("~/services/rbac.server", () => ({
13+
rbac: {
14+
authenticateUserActor: mocks.authenticateUserActor,
15+
authenticatePat: mocks.authenticatePat,
16+
},
17+
}));
18+
vi.mock("~/db.server", () => ({ prisma: {}, $replica: {} }));
19+
vi.mock("~/env.server", () => ({ env: { SESSION_SECRET: "test-session-secret" } }));
20+
vi.mock("~/services/personalAccessToken.server", () => ({
21+
...webappRouteMocks.personalAccessTokenMock(),
22+
personalAccessTokenAuthFailureBody: (result: { error: string }) => ({ error: result.error }),
23+
}));
24+
vi.mock("~/services/authTelemetry.server", () => webappRouteMocks.authTelemetryMock());
25+
vi.mock("~/services/logger.server", () => webappRouteMocks.loggerMock());
26+
vi.mock("~/services/tenantContext.server", () => webappRouteMocks.tenantContextMock());
27+
vi.mock("~/v3/services/worker/workerGroupTokenService.server", () =>
28+
webappRouteMocks.workerGroupTokenServiceMock()
29+
);
30+
vi.mock("~/v3/services/common.server", () => webappRouteMocks.serviceValidationErrorMock());
31+
vi.mock("@internal/run-engine", () => webappRouteMocks.engineServiceValidationErrorMock());
32+
33+
import { createActionPATApiRoute } from "~/services/routeBuilders/apiBuilder.server";
34+
35+
const handler = vi.fn(async ({ body }: { body: unknown }) => json({ received: body }));
36+
37+
function route(options: { maxContentLength?: number } = {}) {
38+
return createActionPATApiRoute(
39+
{
40+
method: "POST",
41+
body: z.object({ name: z.string() }),
42+
...options,
43+
},
44+
handler as any
45+
);
46+
}
47+
48+
/** A request whose body records whether anything pulled from it. */
49+
function trackedRequest(body: string, headers: Record<string, string> = {}) {
50+
const read = { started: false };
51+
const bytes = new TextEncoder().encode(body);
52+
const stream = new ReadableStream<Uint8Array>(
53+
{
54+
pull(controller) {
55+
read.started = true;
56+
controller.enqueue(bytes);
57+
controller.close();
58+
},
59+
},
60+
// Pull only when something reads, not to pre-fill the queue.
61+
{ highWaterMark: 0 }
62+
);
63+
const request = new Request("https://api.trigger.dev/api/v1/orgs", {
64+
method: "POST",
65+
headers: { Authorization: "Bearer tr_pat_test", ...headers },
66+
body: stream,
67+
// @ts-expect-error duplex is required by undici for stream bodies
68+
duplex: "half",
69+
});
70+
return { request, read };
71+
}
72+
73+
async function call(action: ReturnType<typeof route>, request: Request) {
74+
const response = await action({ request, params: {}, context: {} } as any);
75+
return { status: response.status, body: await response.json() };
76+
}
77+
78+
beforeEach(() => {
79+
vi.clearAllMocks();
80+
mocks.authenticatePat.mockResolvedValue({
81+
ok: true,
82+
userId: "usr_1",
83+
tokenId: "pat_1",
84+
lastAccessedAt: new Date(),
85+
ability: buildJwtAbility(["admin"]),
86+
});
87+
});
88+
89+
describe("PAT action route builder", () => {
90+
it("parses the body for an accepted token", async () => {
91+
// Catches: an accepted token no longer reaching the handler with its parsed body.
92+
const { request } = trackedRequest(JSON.stringify({ name: "acme" }));
93+
94+
const result = await call(route(), request);
95+
96+
expect(result).toEqual({ status: 200, body: { received: { name: "acme" } } });
97+
});
98+
99+
it("returns the auth failure without reading the body", async () => {
100+
// Catches: the request body being read before the token is checked.
101+
mocks.authenticatePat.mockResolvedValue({ ok: false, status: 401, error: "Invalid token" });
102+
const { request, read } = trackedRequest(JSON.stringify({ name: "acme" }));
103+
104+
const result = await call(route(), request);
105+
106+
expect(result.status).toBe(401);
107+
expect(read.started).toBe(false);
108+
expect(handler).not.toHaveBeenCalled();
109+
});
110+
111+
it("reports the auth failure before body validation errors", async () => {
112+
// Catches: a body error answering in place of the auth failure.
113+
mocks.authenticatePat.mockResolvedValue({ ok: false, status: 401, error: "Invalid token" });
114+
const { request } = trackedRequest("not json");
115+
116+
const result = await call(route(), request);
117+
118+
expect(result.status).toBe(401);
119+
});
120+
121+
it("rejects a body over maxContentLength with 413", async () => {
122+
// Catches: maxContentLength being ignored by PAT action routes.
123+
const body = JSON.stringify({ name: "a".repeat(100) });
124+
const { request, read } = trackedRequest(body, { "content-length": String(body.length) });
125+
126+
const result = await call(route({ maxContentLength: 50 }), request);
127+
128+
expect(result.status).toBe(413);
129+
expect(read.started).toBe(false);
130+
});
131+
132+
it("accepts a body within maxContentLength", async () => {
133+
// Catches: maxContentLength rejecting a body under the limit.
134+
const body = JSON.stringify({ name: "acme" });
135+
const { request } = trackedRequest(body, { "content-length": String(body.length) });
136+
137+
const result = await call(route({ maxContentLength: 1024 }), request);
138+
139+
expect(result.status).toBe(200);
140+
});
141+
});

0 commit comments

Comments
 (0)