|
1 | 1 | import { isReadReplicaClient } from "@internal/run-store"; |
2 | 2 | import type { RuntimeEnvironmentType } from "@trigger.dev/database"; |
3 | 3 | import { $replica } from "~/db.server"; |
| 4 | +import { authenticatedEnvironmentForAuthentication } from "~/services/apiAuth.server"; |
| 5 | +import { authorizePatEnvironmentAccess } from "~/services/environmentVariableApiAccess.server"; |
| 6 | +import { rbac } from "~/services/rbac.server"; |
4 | 7 | import { runStore } from "~/v3/runStore.server"; |
| 8 | +import { memberProjects } from "./projectsList.server"; |
5 | 9 |
|
6 | 10 | const replicaReadClient = <T>(client: T): T | undefined => |
7 | 11 | isReadReplicaClient(client) ? client : undefined; |
@@ -56,3 +60,53 @@ export async function findRunEnvironment( |
56 | 60 | branch: environment.parentEnvironmentId ? (environment.branchName ?? undefined) : undefined, |
57 | 61 | }; |
58 | 62 | } |
| 63 | + |
| 64 | +// Answers only where the env JWT route would mint for this user; a thrown Response means no. |
| 65 | +export async function locateRunForUser( |
| 66 | + runId: string, |
| 67 | + userId: string, |
| 68 | + request: Request, |
| 69 | + reads: RunReads = productionReads() |
| 70 | +) { |
| 71 | + const projects = await memberProjects(userId); |
| 72 | + const projectId = await findRunProjectId( |
| 73 | + runId, |
| 74 | + projects.map(({ id }) => id), |
| 75 | + reads |
| 76 | + ); |
| 77 | + const project = projects.find(({ id }) => id === projectId); |
| 78 | + if (!project) return null; |
| 79 | + |
| 80 | + const found = await findRunEnvironment(runId, project.id, reads); |
| 81 | + if (!found) return null; |
| 82 | + |
| 83 | + const environment = await authenticatedEnvironmentForAuthentication( |
| 84 | + { type: "personalAccessToken", result: { userId } }, |
| 85 | + project.externalRef, |
| 86 | + found.environment, |
| 87 | + found.branch, |
| 88 | + { organizationScoped: true } |
| 89 | + ); |
| 90 | + if (environment.id !== found.environmentId) return null; |
| 91 | + |
| 92 | + const scope = { organizationId: environment.organizationId, projectId: environment.project.id }; |
| 93 | + const denied = await authorizePatEnvironmentAccess({ |
| 94 | + request, |
| 95 | + authType: "personalAccessToken", |
| 96 | + ...scope, |
| 97 | + envType: environment.type, |
| 98 | + resource: "apiKeys", |
| 99 | + action: "read", |
| 100 | + }); |
| 101 | + if (denied) return null; |
| 102 | + const scoped = await rbac.authenticatePat(request, scope); |
| 103 | + if (!scoped.ok || !scoped.ability.can("read", { type: "runs", envType: environment.type })) { |
| 104 | + return null; |
| 105 | + } |
| 106 | + |
| 107 | + return { |
| 108 | + projectRef: project.externalRef, |
| 109 | + environment: found.environment, |
| 110 | + ...(found.branch === undefined ? {} : { branch: found.branch }), |
| 111 | + }; |
| 112 | +} |
0 commit comments