|
1 | | -import type { RuntimeEnvironment } from "@trigger.dev/database"; |
2 | | -import { prisma } from "~/db.server"; |
| 1 | +import type { PrismaClient, RuntimeEnvironment } from "@trigger.dev/database"; |
| 2 | +import type { HostRbacController } from "@trigger.dev/rbac"; |
3 | 3 | import { customAlphabet } from "nanoid"; |
| 4 | +import { MAX_API_KEY_TASK_IDENTIFIERS } from "~/consts"; |
| 5 | +import { prisma } from "~/db.server"; |
4 | 6 | import { RuntimeEnvironmentType } from "~/database-types"; |
| 7 | +import { canIssueAdditionalApiKeys } from "~/services/additionalApiKeyIssuance.server"; |
| 8 | +import { apiKeyTelemetry, type ApiKeyTelemetry } from "~/services/apiKeyTelemetry.server"; |
| 9 | +import { rbac } from "~/services/rbac.server"; |
| 10 | +import { generateAdditionalApiKey, generateRootApiKey } from "~/utils/apiKeys"; |
5 | 11 | import { controlPlaneResolver } from "~/v3/runOpsMigration/controlPlaneResolver.server"; |
6 | 12 |
|
7 | 13 | const apiKeyId = customAlphabet( |
@@ -94,8 +100,168 @@ export async function regenerateApiKey({ userId, environmentId }: RegenerateAPIK |
94 | 100 | return updatedEnviroment; |
95 | 101 | } |
96 | 102 |
|
| 103 | +export async function createEnvironmentApiKey( |
| 104 | + { |
| 105 | + environmentId, |
| 106 | + taskEnvironmentId, |
| 107 | + userId, |
| 108 | + name, |
| 109 | + expiresAt, |
| 110 | + presetId, |
| 111 | + taskIdentifiers, |
| 112 | + }: { |
| 113 | + environmentId: string; |
| 114 | + taskEnvironmentId: string; |
| 115 | + userId: string; |
| 116 | + name: string; |
| 117 | + expiresAt?: Date; |
| 118 | + presetId: string; |
| 119 | + taskIdentifiers?: string[]; |
| 120 | + }, |
| 121 | + { |
| 122 | + prismaClient = prisma, |
| 123 | + rbacController = rbac, |
| 124 | + issuanceAllowed, |
| 125 | + telemetryRecorder = apiKeyTelemetry, |
| 126 | + }: { |
| 127 | + prismaClient?: Pick< |
| 128 | + PrismaClient, |
| 129 | + "apiKey" | "featureFlag" | "organization" | "runtimeEnvironment" | "taskIdentifier" |
| 130 | + >; |
| 131 | + rbacController?: Pick<HostRbacController, "prepareApiKeyPolicy">; |
| 132 | + issuanceAllowed?: (organizationId: string) => Promise<boolean>; |
| 133 | + telemetryRecorder?: ApiKeyTelemetry; |
| 134 | + } = {} |
| 135 | +) { |
| 136 | + const environment = await prismaClient.runtimeEnvironment.findFirst({ |
| 137 | + where: { |
| 138 | + id: environmentId, |
| 139 | + organization: { members: { some: { userId } } }, |
| 140 | + }, |
| 141 | + select: { id: true, type: true, organizationId: true }, |
| 142 | + }); |
| 143 | + |
| 144 | + if (!environment) { |
| 145 | + throw new Error("Environment not found"); |
| 146 | + } |
| 147 | + |
| 148 | + const canIssue = |
| 149 | + issuanceAllowed ?? |
| 150 | + ((organizationId) => canIssueAdditionalApiKeys(organizationId, prismaClient)); |
| 151 | + if (!(await canIssue(environment.organizationId))) { |
| 152 | + throw new Error("Creating additional API keys is not enabled."); |
| 153 | + } |
| 154 | + |
| 155 | + if (expiresAt && expiresAt.getTime() <= Date.now()) { |
| 156 | + throw new Error("Expiration must be in the future"); |
| 157 | + } |
| 158 | + |
| 159 | + const selectedTasks = [...new Set(taskIdentifiers?.map((task) => task.trim()).filter(Boolean))]; |
| 160 | + |
| 161 | + if (selectedTasks.length > MAX_API_KEY_TASK_IDENTIFIERS) { |
| 162 | + throw new Error(`You can select at most ${MAX_API_KEY_TASK_IDENTIFIERS} tasks for an API key`); |
| 163 | + } |
| 164 | + if (selectedTasks.length > 0) { |
| 165 | + const matchingTasks = await prismaClient.taskIdentifier.count({ |
| 166 | + where: { |
| 167 | + runtimeEnvironmentId: taskEnvironmentId, |
| 168 | + slug: { in: selectedTasks }, |
| 169 | + runtimeEnvironment: { |
| 170 | + OR: [{ id: environment.id }, { parentEnvironmentId: environment.id }], |
| 171 | + }, |
| 172 | + }, |
| 173 | + }); |
| 174 | + |
| 175 | + if (matchingTasks !== selectedTasks.length) { |
| 176 | + throw new Error("One or more selected tasks are not available in this environment"); |
| 177 | + } |
| 178 | + } |
| 179 | + |
| 180 | + let prepared: Awaited<ReturnType<typeof rbacController.prepareApiKeyPolicy>>; |
| 181 | + try { |
| 182 | + prepared = await rbacController.prepareApiKeyPolicy({ |
| 183 | + organizationId: environment.organizationId, |
| 184 | + presetId, |
| 185 | + taskIdentifiers: selectedTasks.length > 0 ? selectedTasks : undefined, |
| 186 | + }); |
| 187 | + } catch (error) { |
| 188 | + telemetryRecorder.recordOperation("prepare_policy", "error", "policy_error"); |
| 189 | + throw error; |
| 190 | + } |
| 191 | + |
| 192 | + if (!prepared.ok) { |
| 193 | + telemetryRecorder.recordOperation("prepare_policy", "rejected", "policy_rejected"); |
| 194 | + throw new Error(prepared.error); |
| 195 | + } |
| 196 | + telemetryRecorder.recordOperation("prepare_policy", "success"); |
| 197 | + |
| 198 | + const generated = generateAdditionalApiKey(environment.type); |
| 199 | + const apiKey = await (async () => { |
| 200 | + try { |
| 201 | + return await prismaClient.apiKey.create({ |
| 202 | + data: { |
| 203 | + name, |
| 204 | + keyHash: generated.keyHash, |
| 205 | + lastFour: generated.lastFour, |
| 206 | + runtimeEnvironmentId: environment.id, |
| 207 | + createdByUserId: userId, |
| 208 | + expiresAt, |
| 209 | + presetId: prepared.policy.presetId, |
| 210 | + scopes: prepared.policy.scopes, |
| 211 | + }, |
| 212 | + }); |
| 213 | + } catch (error) { |
| 214 | + telemetryRecorder.recordOperation("create", "error", "database_error"); |
| 215 | + throw error; |
| 216 | + } |
| 217 | + })(); |
| 218 | + telemetryRecorder.recordOperation("create", "success"); |
| 219 | + |
| 220 | + return { apiKey, plaintext: generated.apiKey }; |
| 221 | +} |
| 222 | + |
| 223 | +export async function revokeEnvironmentApiKey( |
| 224 | + { |
| 225 | + environmentId, |
| 226 | + apiKeyId, |
| 227 | + }: { |
| 228 | + environmentId: string; |
| 229 | + apiKeyId: string; |
| 230 | + }, |
| 231 | + { |
| 232 | + prismaClient = prisma, |
| 233 | + telemetryRecorder = apiKeyTelemetry, |
| 234 | + }: { |
| 235 | + prismaClient?: Pick<PrismaClient, "apiKey">; |
| 236 | + telemetryRecorder?: ApiKeyTelemetry; |
| 237 | + } = {} |
| 238 | +) { |
| 239 | + const result = await (async () => { |
| 240 | + try { |
| 241 | + return await prismaClient.apiKey.updateMany({ |
| 242 | + where: { |
| 243 | + id: apiKeyId, |
| 244 | + runtimeEnvironmentId: environmentId, |
| 245 | + revokedAt: null, |
| 246 | + }, |
| 247 | + data: { revokedAt: new Date() }, |
| 248 | + }); |
| 249 | + } catch (error) { |
| 250 | + telemetryRecorder.recordOperation("revoke", "error", "database_error"); |
| 251 | + throw error; |
| 252 | + } |
| 253 | + })(); |
| 254 | + |
| 255 | + if (result.count !== 1) { |
| 256 | + telemetryRecorder.recordOperation("revoke", "rejected", "not_found_or_revoked"); |
| 257 | + throw new Error("API key not found or already revoked"); |
| 258 | + } |
| 259 | + |
| 260 | + telemetryRecorder.recordOperation("revoke", "success"); |
| 261 | +} |
| 262 | + |
97 | 263 | export function createApiKeyForEnv(envType: RuntimeEnvironment["type"]) { |
98 | | - return `tr_${envSlug(envType)}_${apiKeyId(20)}`; |
| 264 | + return generateRootApiKey(envType).apiKey; |
99 | 265 | } |
100 | 266 |
|
101 | 267 | export function createPkApiKeyForEnv(envType: RuntimeEnvironment["type"]) { |
|
0 commit comments