|
| 1 | +import type { RunStore } from "@internal/run-store"; |
| 2 | +import { getMeter } from "@internal/tracing"; |
| 3 | +import { |
| 4 | + fromFriendlyId, |
| 5 | + type TaskRunContext, |
| 6 | + type TaskRunExecutionStatus, |
| 7 | +} from "@trigger.dev/core/v3"; |
| 8 | +import { |
| 9 | + USAGE_JWT_REFRESH_BEFORE_EXPIRY_SECONDS, |
| 10 | + type WorkerApiRunHeartbeatRequestBody, |
| 11 | +} from "@trigger.dev/core/v3/workers"; |
| 12 | +import { singleton } from "~/utils/singleton"; |
| 13 | +import { meteringClaims } from "~/v3/utils/meteringClaims.server"; |
| 14 | + |
| 15 | +type EnvironmentIdentity = { id: string; organizationId: string; projectId: string }; |
| 16 | + |
| 17 | +const LIVE_ATTEMPT_STATUSES: ReadonlySet<TaskRunExecutionStatus> = new Set<TaskRunExecutionStatus>([ |
| 18 | + "PENDING_EXECUTING", |
| 19 | + "EXECUTING", |
| 20 | + "EXECUTING_WITH_WAITPOINTS", |
| 21 | + "QUEUED_EXECUTING", |
| 22 | +]); |
| 23 | + |
| 24 | +const REFUSAL_REASONS = ["missing_identity", "not_owner", "identity_changed"] as const; |
| 25 | +type RefusalReason = (typeof REFUSAL_REASONS)[number]; |
| 26 | + |
| 27 | +class UsageJwtRefusal extends Error { |
| 28 | + constructor(readonly reason: RefusalReason) { |
| 29 | + super(`Billing JWT refresh refused: ${reason}`); |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +// Names and label values are relied on by internal dashboards and monitors. Labels stay bounded. |
| 34 | +const telemetry = singleton("usageJwtRefreshTelemetry", () => { |
| 35 | + const issued = getMeter("usage-jwt-refresh").createCounter("usage_jwt.refresh.issued", { |
| 36 | + description: "Due billing JWT refresh requests handled by the webapp. Not delivery success", |
| 37 | + }); |
| 38 | + // Export the failure series from zero, so a rate query sees a process's first failure. |
| 39 | + for (const reason of REFUSAL_REASONS) issued.add(0, { result: "refused", reason }); |
| 40 | + issued.add(0, { result: "error", reason: "error" }); |
| 41 | + const initial = getMeter("usage-jwt-refresh").createCounter("usage_jwt.initial", { |
| 42 | + description: "Billing credential kind handed out at attempt start", |
| 43 | + }); |
| 44 | + initial.add(0, { kind: "legacy_unverified" }); |
| 45 | + return { issued, initial }; |
| 46 | +}); |
| 47 | + |
| 48 | +export type InitialUsageAuth = |
| 49 | + | "control_plane" |
| 50 | + | "legacy_runner" |
| 51 | + | "legacy_root_key" |
| 52 | + | "legacy_unverified"; |
| 53 | + |
| 54 | +/** |
| 55 | + * Which billing credential an attempt starts with. A run holding the root key keeps API-key |
| 56 | + * recovery; only a run without it needs the control plane to renew its credential. |
| 57 | + */ |
| 58 | +export function initialUsageAuth(opts: { |
| 59 | + supportsUsageJwtRefresh?: boolean; |
| 60 | + verifiedEnvironmentId?: string; |
| 61 | + environmentId: string; |
| 62 | + hasRootKey: boolean; |
| 63 | +}): InitialUsageAuth { |
| 64 | + if (!opts.supportsUsageJwtRefresh) return "legacy_runner"; |
| 65 | + if (opts.hasRootKey) return "legacy_root_key"; |
| 66 | + if (opts.verifiedEnvironmentId !== opts.environmentId) return "legacy_unverified"; |
| 67 | + return "control_plane"; |
| 68 | +} |
| 69 | + |
| 70 | +export function countInitialUsageAuth(kind: InitialUsageAuth) { |
| 71 | + telemetry.initial.add(1, { kind }); |
| 72 | +} |
| 73 | + |
| 74 | +type RefreshOptions = { |
| 75 | + report: WorkerApiRunHeartbeatRequestBody["usageJwt"]; |
| 76 | + runId: string; |
| 77 | + snapshotId: string; |
| 78 | + workerId: string; |
| 79 | + runnerId?: string; |
| 80 | + environmentId?: string; |
| 81 | + projectId?: string; |
| 82 | + store: Pick<RunStore, "findLatestExecutionSnapshot" | "findRun">; |
| 83 | + resolveContext: (runId: string) => Promise<TaskRunContext>; |
| 84 | + sign: (environment: EnvironmentIdentity, claims: Record<string, string>) => Promise<string>; |
| 85 | + now?: number; |
| 86 | +}; |
| 87 | + |
| 88 | +/** Mints a replacement only when the reported credential is due. Throws when refused or failed. */ |
| 89 | +export async function refreshUsageJwtOnHeartbeat( |
| 90 | + opts: RefreshOptions |
| 91 | +): Promise<string | undefined> { |
| 92 | + const { report } = opts; |
| 93 | + if (!report) return undefined; |
| 94 | + if ( |
| 95 | + report.expiresAt - (opts.now ?? Date.now()) / 1_000 > |
| 96 | + USAGE_JWT_REFRESH_BEFORE_EXPIRY_SECONDS |
| 97 | + ) { |
| 98 | + return undefined; |
| 99 | + } |
| 100 | + |
| 101 | + try { |
| 102 | + const token = await issue(opts, report); |
| 103 | + telemetry.issued.add(1, { result: "success", reason: "none" }); |
| 104 | + return token; |
| 105 | + } catch (error) { |
| 106 | + const refused = error instanceof UsageJwtRefusal; |
| 107 | + telemetry.issued.add(1, { |
| 108 | + result: refused ? "refused" : "error", |
| 109 | + reason: refused ? error.reason : "error", |
| 110 | + }); |
| 111 | + throw error; |
| 112 | + } |
| 113 | +} |
| 114 | + |
| 115 | +async function issue( |
| 116 | + opts: RefreshOptions, |
| 117 | + report: NonNullable<RefreshOptions["report"]> |
| 118 | +): Promise<string> { |
| 119 | + if (!opts.environmentId || !opts.runnerId) throw new UsageJwtRefusal("missing_identity"); |
| 120 | + |
| 121 | + const assertOwnership = async () => { |
| 122 | + const snapshot = await opts.store.findLatestExecutionSnapshot( |
| 123 | + opts.runId, |
| 124 | + undefined, |
| 125 | + opts.environmentId |
| 126 | + ); |
| 127 | + if ( |
| 128 | + !snapshot || |
| 129 | + !snapshot.isValid || |
| 130 | + snapshot.id !== opts.snapshotId || |
| 131 | + snapshot.runId !== opts.runId || |
| 132 | + snapshot.environmentId !== opts.environmentId || |
| 133 | + snapshot.workerId !== opts.workerId || |
| 134 | + snapshot.runnerId !== opts.runnerId || |
| 135 | + snapshot.attemptNumber !== report.attemptNumber || |
| 136 | + !LIVE_ATTEMPT_STATUSES.has(snapshot.executionStatus) || |
| 137 | + (opts.projectId !== undefined && snapshot.projectId !== opts.projectId) |
| 138 | + ) { |
| 139 | + throw new UsageJwtRefusal("not_owner"); |
| 140 | + } |
| 141 | + return snapshot; |
| 142 | + }; |
| 143 | + |
| 144 | + const snapshot = await assertOwnership(); |
| 145 | + const [context, run] = await Promise.all([ |
| 146 | + opts.resolveContext(opts.runId), |
| 147 | + opts.store.findRun( |
| 148 | + { id: opts.runId }, |
| 149 | + { |
| 150 | + select: { |
| 151 | + runtimeEnvironmentId: true, |
| 152 | + attemptNumber: true, |
| 153 | + region: true, |
| 154 | + workerQueue: true, |
| 155 | + }, |
| 156 | + } |
| 157 | + ), |
| 158 | + ]); |
| 159 | + if ( |
| 160 | + !run || |
| 161 | + run.runtimeEnvironmentId !== snapshot.environmentId || |
| 162 | + run.attemptNumber !== report.attemptNumber || |
| 163 | + fromFriendlyId(context.run.id) !== opts.runId || |
| 164 | + context.environment.id !== snapshot.environmentId || |
| 165 | + context.organization.id !== snapshot.organizationId || |
| 166 | + context.project.id !== snapshot.projectId || |
| 167 | + context.attempt.number !== report.attemptNumber |
| 168 | + ) { |
| 169 | + throw new UsageJwtRefusal("identity_changed"); |
| 170 | + } |
| 171 | + // Context resolution can cross stores. Do not sign if the attempt moved during those reads. |
| 172 | + await assertOwnership(); |
| 173 | + |
| 174 | + return opts.sign( |
| 175 | + { |
| 176 | + id: context.environment.id, |
| 177 | + organizationId: context.organization.id, |
| 178 | + projectId: context.project.id, |
| 179 | + }, |
| 180 | + { |
| 181 | + ...meteringClaims({ |
| 182 | + environmentType: context.environment.type, |
| 183 | + region: run.region, |
| 184 | + workerQueue: run.workerQueue, |
| 185 | + }), |
| 186 | + run_id: opts.runId, |
| 187 | + machine_preset: context.machine.name, |
| 188 | + usage_auth: "control-plane-v1", |
| 189 | + usage_attempt: String(report.attemptNumber), |
| 190 | + } |
| 191 | + ); |
| 192 | +} |
0 commit comments