Skip to content

Commit cf49de1

Browse files
carderneTrigger.dev RepoOps
authored andcommitted
fix(auth): restricted key follow-ups to scoped run tokens
Restore offloaded payload, output, and stream-wait result downloads for API keys with packet read access. Keep shared waitpoint idempotency keys limited to callers with environment-wide waitpoint read and write access, and make the organization-only sandbox tasks flag read-only in global settings. Mono-RevId: 39daf34b427bc9870c7f7803d48beaab328c744a
1 parent 22f0b75 commit cf49de1

8 files changed

Lines changed: 164 additions & 30 deletions
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
area: webapp
3+
type: fix
4+
---
5+
6+
Restore offloaded payload, output, and stream-wait result downloads for API keys with packet read access.
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
area: webapp
3+
type: fix
4+
---
5+
6+
Keep waitpoint idempotency keys scoped to a run unless the API key can both read and write all waitpoints.

‎apps/webapp/app/routes/api.v1.runs.$runId.packets.$field.ts‎

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { json } from "@remix-run/server-runtime";
2+
import type { RbacResource } from "@trigger.dev/plugins";
23
import { z } from "zod";
34
import { $replica } from "~/db.server";
5+
import { assertPacketNamespaceAccess } from "~/services/packetApi.server";
46
import { anyResource, createLoaderApiRoute } from "~/services/routeBuilders/apiBuilder.server";
57
import { generatePresignedUrl, jsonPacketPresignFailure } from "~/v3/objectStore.server";
68
import { runStore } from "~/v3/runStore.server";
@@ -50,20 +52,28 @@ export const loader = createLoaderApiRoute(
5052
if (!run) return null;
5153

5254
const packetPath = storedPacketPath(run, params.field);
53-
return packetPath ? { ...run, packetPath } : null;
55+
return packetPath
56+
? {
57+
...run,
58+
packetPath,
59+
readResources: [
60+
{ type: "runs", id: run.friendlyId },
61+
{ type: "tasks", id: run.taskIdentifier },
62+
...run.runTags.map((tag) => ({ type: "tags", id: tag })),
63+
...(run.batch ? [{ type: "batch", id: run.batch.friendlyId }] : []),
64+
] satisfies RbacResource[],
65+
}
66+
: null;
5467
},
5568
authorization: {
5669
action: "read",
57-
resource: (run) =>
58-
anyResource([
59-
{ type: "runs", id: run.friendlyId },
60-
{ type: "tasks", id: run.taskIdentifier },
61-
...run.runTags.map((tag) => ({ type: "tags", id: tag })),
62-
...(run.batch ? [{ type: "batch", id: run.batch.friendlyId }] : []),
63-
]),
70+
resource: (run) => anyResource([...run.readResources, { type: "packets" }]),
6471
},
6572
},
66-
async ({ authentication, resource }) => {
73+
async ({ authentication, resource, ability }) => {
74+
if (!ability.can("read", resource.readResources)) {
75+
assertPacketNamespaceAccess(authentication);
76+
}
6777
const signed = await generatePresignedUrl(
6878
authentication.environment.project.externalRef,
6979
authentication.environment.slug,

‎apps/webapp/app/routes/api.v1.runs.$runId.waitpoints.$waitpointId.output.ts‎

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { json } from "@remix-run/server-runtime";
2+
import type { RbacResource } from "@trigger.dev/plugins";
23
import { z } from "zod";
34
import { $replica } from "~/db.server";
5+
import { assertPacketNamespaceAccess } from "~/services/packetApi.server";
46
import { anyResource, createLoaderApiRoute } from "~/services/routeBuilders/apiBuilder.server";
57
import { generatePresignedUrl, jsonPacketPresignFailure } from "~/v3/objectStore.server";
68
import { engine } from "~/v3/runEngine.server";
@@ -40,18 +42,24 @@ export const loader = createLoaderApiRoute(
4042
);
4143
if (!waitpoint?.output || waitpoint.outputType !== "application/store") return null;
4244

43-
return { ...run, packetPath: waitpoint.output };
45+
return {
46+
...run,
47+
packetPath: waitpoint.output,
48+
readResources: [
49+
{ type: "runs", id: run.friendlyId },
50+
{ type: "tasks", id: run.taskIdentifier },
51+
] satisfies RbacResource[],
52+
};
4453
},
4554
authorization: {
4655
action: "read",
47-
resource: (run) =>
48-
anyResource([
49-
{ type: "runs", id: run.friendlyId },
50-
{ type: "tasks", id: run.taskIdentifier },
51-
]),
56+
resource: (run) => anyResource([...run.readResources, { type: "packets" }]),
5257
},
5358
},
54-
async ({ authentication, resource }) => {
59+
async ({ authentication, resource, ability }) => {
60+
if (!ability.can("read", resource.readResources)) {
61+
assertPacketNamespaceAccess(authentication);
62+
}
5563
const signed = await generatePresignedUrl(
5664
authentication.environment.project.externalRef,
5765
authentication.environment.slug,

‎apps/webapp/app/utils/idempotencyKeys.server.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,12 @@ export function resolveRunWaitpointIdempotencyKey(
66
runId: string,
77
ability: RbacAbility
88
): string | undefined {
9-
if (!key || ability.can("write", { type: "waitpoints" })) return key;
9+
if (
10+
!key ||
11+
(ability.can("write", { type: "waitpoints" }) && ability.can("read", { type: "waitpoints" }))
12+
) {
13+
return key;
14+
}
1015
// Environment-wide keys could otherwise attach a scoped run to another run's waitpoint.
1116
return `run:${createHash("sha256")
1217
.update(JSON.stringify([runId, key]))

‎apps/webapp/app/v3/featureFlags.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,6 +278,7 @@ export const GLOBAL_LOCKED_FLAGS: FeatureFlagKey[] = [
278278
FEATURE_FLAG.runOpsMintShardSetPrev,
279279
FEATURE_FLAG.runOpsMintShardSetFlippedAt,
280280
FEATURE_FLAG.secretProxy,
281+
FEATURE_FLAG.sandboxTasks,
281282
];
282283

283284
// Flags that are read-only on the org-level dialog.

‎apps/webapp/test/runTokenApiAuthorization.test.ts‎

Lines changed: 80 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,22 @@ async function seedDeployedEnvironment() {
177177
return { ...seed, environment };
178178
}
179179

180+
async function packetReaderFor(environmentId: string) {
181+
const user = await seedTestUser(database.prisma);
182+
const key = `tr_prod_sk_${randomBytes(12).toString("hex")}`;
183+
await database.prisma.apiKey.create({
184+
data: {
185+
name: "Restricted packet reader",
186+
keyHash: createHash("sha256").update(key).digest("hex"),
187+
lastFour: key.slice(-4),
188+
runtimeEnvironmentId: environmentId,
189+
createdByUserId: user.id,
190+
scopes: ["read:packets"],
191+
},
192+
});
193+
return key;
194+
}
195+
180196
describe("run-token API authorization", () => {
181197
it("creates usable preview and production waitpoint callbacks and public JWTs", async () => {
182198
await assertRunTokenWaitpoints(database.prisma, tokenFor);
@@ -1159,7 +1175,7 @@ describe("run-token API authorization", () => {
11591175
unscopedInitialization.mockRestore();
11601176
});
11611177

1162-
// Catches: offloaded wait results needing environment-wide packet access, or leaking other waitpoints.
1178+
// Catches: packet-only keys losing offloaded wait results, or run grants leaking other waitpoints.
11631179
it("serves offloaded output only for waitpoints the run resumed from", async () => {
11641180
const { environment, project, organization } = await seedDeployedEnvironment();
11651181
const { run } = await seedTestRun(database.prisma, {
@@ -1199,21 +1215,72 @@ describe("run-token API authorization", () => {
11991215
});
12001216
const token = await tokenFor(environment, [`read:runs:${run.friendlyId}`]);
12011217
const { loader } = await import("~/routes/api.v1.runs.$runId.waitpoints.$waitpointId.output");
1202-
const load = (waitpointId: string) =>
1203-
loader({
1204-
request: new Request("https://api.example.com/test", {
1205-
headers: { Authorization: `Bearer ${token}` },
1206-
}),
1207-
params: { runId: run.friendlyId, waitpointId },
1208-
context: {},
1209-
});
1218+
for (const bearer of [token, await packetReaderFor(environment.id)]) {
1219+
const load = (waitpointId: string) =>
1220+
loader({
1221+
request: new Request("https://api.example.com/test", {
1222+
headers: { Authorization: `Bearer ${bearer}` },
1223+
}),
1224+
params: { runId: run.friendlyId, waitpointId },
1225+
context: {},
1226+
});
12101227

1211-
const response = await load(resumed.friendlyId);
1212-
expect(response.status).toBe(200);
1213-
expect((await response.json()).presignedUrl).toContain("waitpoint_resumed/stream/record.json");
1214-
expect((await load(other.friendlyId)).status).toBe(404);
1228+
const response = await load(resumed.friendlyId);
1229+
expect(response.status).toBe(200);
1230+
expect((await response.json()).presignedUrl).toContain(
1231+
"waitpoint_resumed/stream/record.json"
1232+
);
1233+
expect((await load(other.friendlyId)).status).toBe(404);
1234+
}
12151235
});
12161236

1237+
// Catches: packet-only keys losing run packets, or bypassing shared development namespace isolation.
1238+
it.each(["PRODUCTION", "DEVELOPMENT"] as const)(
1239+
"preserves run packet access and namespace isolation in %s",
1240+
async (environmentType) => {
1241+
const { environment, project } =
1242+
environmentType === "PRODUCTION"
1243+
? await seedDeployedEnvironment()
1244+
: await seedTestEnvironment(database.prisma);
1245+
const { run } = await seedTestRun(database.prisma, {
1246+
environmentId: environment.id,
1247+
projectId: project.id,
1248+
});
1249+
await database.prisma.taskRun.update({
1250+
where: { id: run.id },
1251+
data: {
1252+
payload: "stored/payload.json",
1253+
payloadType: "application/store",
1254+
output: "stored/output.json",
1255+
outputType: "application/store",
1256+
},
1257+
});
1258+
const key = await packetReaderFor(environment.id);
1259+
const runToken = await tokenFor(environment, [`read:runs:${run.friendlyId}`, "read:packets"]);
1260+
const foreign = await seedDeployedEnvironment();
1261+
const foreignKey = await packetReaderFor(foreign.environment.id);
1262+
const { loader } = await import("~/routes/api.v1.runs.$runId.packets.$field");
1263+
const load = (field: "payload" | "output", bearer: string) =>
1264+
loader({
1265+
request: new Request("https://api.example.com/test", {
1266+
headers: { Authorization: `Bearer ${bearer}` },
1267+
}),
1268+
params: { runId: run.friendlyId, field },
1269+
context: {},
1270+
});
1271+
1272+
for (const field of ["payload", "output"] as const) {
1273+
const response = await load(field, key);
1274+
expect(response.status).toBe(environmentType === "PRODUCTION" ? 200 : 403);
1275+
if (response.status === 200) {
1276+
expect((await response.json()).presignedUrl).toContain(`stored/${field}.json`);
1277+
}
1278+
expect((await load(field, runToken)).status).toBe(200);
1279+
expect((await load(field, foreignKey)).status).toBe(404);
1280+
}
1281+
}
1282+
);
1283+
12171284
// Catches: session output setup ignoring direction-scoped session grants, or a `.out` grant opening `.in`.
12181285
it("lets a direction-scoped run token initialize only that session direction", async () => {
12191286
const { environment } = await seedDeployedEnvironment();
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { buildJwtAbility } from "@trigger.dev/plugins";
2+
import { describe, expect, it } from "vitest";
3+
import { resolveRunWaitpointIdempotencyKey } from "~/utils/idempotencyKeys.server";
4+
5+
describe("resolveRunWaitpointIdempotencyKey", () => {
6+
// Catches: write-only waitpoint grants reusing another run's waitpoint and receiving its output.
7+
it.each([
8+
["write:waitpoints"],
9+
["write:waitpoints", "read:waitpoints:waitpoint_other"],
10+
["read:waitpoints"],
11+
])("isolates keys by run for scopes %j", (...scopes) => {
12+
const ability = buildJwtAbility(scopes);
13+
const key = resolveRunWaitpointIdempotencyKey("shared-key", "run_first", ability);
14+
15+
expect(key).not.toBe("shared-key");
16+
expect(key).toBe(resolveRunWaitpointIdempotencyKey("shared-key", "run_first", ability));
17+
expect(key).not.toBe(resolveRunWaitpointIdempotencyKey("shared-key", "run_second", ability));
18+
});
19+
20+
// Catches: callers with environment-wide waitpoint read and write grants losing shared keys.
21+
it("preserves environment-wide keys with both read and write grants", () => {
22+
const ability = buildJwtAbility(["write:waitpoints", "read:waitpoints"]);
23+
24+
expect(resolveRunWaitpointIdempotencyKey("shared-key", "run_first", ability)).toBe(
25+
"shared-key"
26+
);
27+
expect(resolveRunWaitpointIdempotencyKey("shared-key", "run_second", ability)).toBe(
28+
"shared-key"
29+
);
30+
});
31+
});

0 commit comments

Comments
 (0)