Skip to content

Commit 07e3389

Browse files
carderneTrigger.dev RepoOps
authored andcommitted
feat: versioned encryption for runtime and build environment variables
Add opt-in versioned per-environment encryption for runtime and build environment variables, including rotation and migration support. Self-hosted deployments can use their existing platform keyring without KMS. Mono-RevId: e06e364006c479c2854cce35b09cc6928a909f5f
1 parent 1414446 commit 07e3389

35 files changed

Lines changed: 2920 additions & 282 deletions

‎.env.schema‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,13 @@ MAGIC_LINK_SECRET=abcdef1234
88
ENCRYPTION_KEY=ae13021afef0819c3a307ad487071c06 # Must be a random 16 byte hex string. You can generate an encryption key by running `openssl rand -hex 16` in your terminal
99
# Optional JSON: {"activeKeyId":"legacy","keys":{"legacy":"<existing key>","v2":"<new key>"}}
1010
ENCRYPTION_KEYRING=
11+
# Master gate for automatic enrollment; also requires the org/global environmentEncryptionEnabled flag.
12+
# Enable only after every reader supports versioned environment encryption.
13+
# @sensitive=false
14+
ENVIRONMENT_ENCRYPTION_ENABLED=false
15+
# Optional resolved AWS KMS key ARN; unset uses the platform keyring for wrapping.
16+
# @sensitive=false
17+
ENVIRONMENT_ENCRYPTION_KMS_KEY_ARN=
1118
# Stable non-secret seed. Use the same value on every schedule engine/API/dashboard instance.
1219
# Changing it only affects missing/new phases; existing persisted phases are preserved.
1320
# @sensitive=false
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
area: webapp
3+
type: feature
4+
---
5+
Add opt-in per-environment encryption keys for runtime and build environment variables, with rotation and migration support.

‎apps/webapp/app/env.server.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,14 @@ const EnvironmentSchema = z
435435
)
436436
.refine(isNotInsecureSecret, INSECURE_SECRET_MESSAGE),
437437
ENCRYPTION_KEYRING: z.string().transform(parseEncryptionKeyring).optional(),
438+
ENVIRONMENT_ENCRYPTION_ENABLED: BoolEnv.default(false),
439+
ENVIRONMENT_ENCRYPTION_KMS_KEY_ARN: z.preprocess(
440+
(value) => (value === "" ? undefined : value),
441+
z
442+
.string()
443+
.regex(/^arn:(aws|aws-us-gov|aws-cn):kms:[a-z0-9-]+:[0-9]{12}:key\/[a-zA-Z0-9-]+$/)
444+
.optional()
445+
),
438446
PUBLIC_TOKEN_SEALED_SUBJECT_ENABLED: BoolEnv.default(false),
439447
PUBLIC_TOKEN_SUBJECT_SECRET: z
440448
.string()

‎apps/webapp/app/models/vercelIntegration.server.ts‎

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1450,22 +1450,24 @@ export class VercelIntegrationRepository {
14501450
});
14511451

14521452
if (existingVarValues.length > 0) {
1453-
const secretStore = getSecretStore("DATABASE", { prismaClient: prisma });
1454-
const SecretValue = z.object({ secret: z.string() });
1453+
const decrypted = await envVarRepository.getVariableValuesForKeys(
1454+
params.projectId,
1455+
existingVarValues.map((value) => ({
1456+
environmentId: mapping.runtimeEnvironmentId,
1457+
key: value.variable.key,
1458+
}))
1459+
);
14551460

14561461
for (const varValue of existingVarValues) {
14571462
if (varValue.isSecret) {
14581463
existingSecretKeys.add(varValue.variable.key);
14591464
}
14601465

14611466
if (varValue.valueReference?.key) {
1462-
const existingSecret = await ResultAsync.fromPromise(
1463-
secretStore.getSecret(SecretValue, varValue.valueReference.key),
1464-
() => null
1465-
).unwrapOr(null);
1466-
if (existingSecret) {
1467-
existingValues.set(varValue.variable.key, existingSecret.secret);
1468-
}
1467+
const value = decrypted.get(
1468+
`${mapping.runtimeEnvironmentId}:${varValue.variable.key}`
1469+
);
1470+
if (value !== undefined) existingValues.set(varValue.variable.key, value);
14691471
}
14701472
}
14711473
}

‎apps/webapp/app/presenters/v3/EnvironmentVariablesPresenter.server.ts‎

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import type { EnvironmentVariableUpdater } from "~/v3/environmentVariables/repos
1212
import type { SyncEnvVarsMapping, EnvSlug } from "~/v3/vercel/vercelProjectIntegrationSchema";
1313
import { VercelIntegrationService } from "~/services/vercelIntegration.server";
1414
import { loadEnvironmentVariablesEnvironments } from "./environmentVariablesEnvironments.server";
15+
import { EnvironmentKeyUnavailableError } from "~/services/environmentEncryption/wrapping.server";
1516

1617
import { boundedIn, type Prisma } from "@trigger.dev/database";
1718
type Result = Awaited<ReturnType<EnvironmentVariablesPresenter["call"]>>;
@@ -209,10 +210,33 @@ export class EnvironmentVariablesPresenter {
209210
}
210211
}
211212

212-
const variableValuesByEnvAndKey = await repository.getVariableValuesForKeys(
213-
project.id,
214-
nonSecretItems
215-
);
213+
let variableValuesByEnvAndKey: Map<string, string>;
214+
const unavailableEnvironments = new Set<string>();
215+
try {
216+
variableValuesByEnvAndKey = await repository.getVariableValuesForKeys(
217+
project.id,
218+
nonSecretItems
219+
);
220+
} catch (error) {
221+
if (!(error instanceof EnvironmentKeyUnavailableError)) throw error;
222+
variableValuesByEnvAndKey = new Map();
223+
const environmentIds = [...new Set(nonSecretItems.map((item) => item.environmentId))];
224+
const results = await Promise.allSettled(
225+
environmentIds.map((environmentId) =>
226+
repository.getVariableValuesForKeys(
227+
project.id,
228+
nonSecretItems.filter((item) => item.environmentId === environmentId)
229+
)
230+
)
231+
);
232+
for (const [i, result] of results.entries()) {
233+
if (result.status === "fulfilled") {
234+
for (const [key, value] of result.value) variableValuesByEnvAndKey.set(key, value);
235+
} else if (result.reason instanceof EnvironmentKeyUnavailableError) {
236+
unavailableEnvironments.add(environmentIds[i]!);
237+
} else throw result.reason;
238+
}
239+
}
216240

217241
// Get Vercel integration data if it exists
218242
const vercelService = new VercelIntegrationService(this.#prismaClient);
@@ -245,7 +269,8 @@ export class EnvironmentVariablesPresenter {
245269
? undefined
246270
: variableValuesByEnvAndKey.get(`${env.id}:${environmentVariable.key}`);
247271

248-
if (!isSecret && val === undefined) {
272+
const valueUnavailable = unavailableEnvironments.has(env.id);
273+
if (!isSecret && !valueUnavailable && val === undefined) {
249274
return [];
250275
}
251276

@@ -270,7 +295,8 @@ export class EnvironmentVariablesPresenter {
270295
id: environmentVariable.id,
271296
key: environmentVariable.key,
272297
environment: { type: env.type, id: env.id, branchName: env.branchName },
273-
value: isSecret ? "" : val!,
298+
value: isSecret || valueUnavailable ? "" : val!,
299+
...(valueUnavailable ? { valueUnavailable: true } : {}),
274300
isSecret,
275301
version: valueRecord.version,
276302
lastUpdatedBy,

‎apps/webapp/app/presenters/v3/VercelSettingsPresenter.server.ts‎

Lines changed: 34 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { type PrismaClient } from "@trigger.dev/database";
1+
import { boundedIn, type PrismaClient } from "@trigger.dev/database";
22
import { type Result, fromPromise, ok, okAsync, ResultAsync } from "neverthrow";
33
import { env } from "~/env.server";
44
import { logger } from "~/services/logger.server";
@@ -9,7 +9,6 @@ import type {
99
} from "~/models/vercelIntegration.server";
1010
import { VercelIntegrationRepository } from "~/models/vercelIntegration.server";
1111
import { type GitHubAppInstallation } from "~/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.github";
12-
import { EnvironmentVariablesRepository } from "~/v3/environmentVariables/environmentVariablesRepository.server";
1312
import { isReservedForExternalSync } from "~/v3/environmentVariableRules.server";
1413
import type { VercelProjectIntegrationData } from "~/v3/vercel/vercelProjectIntegrationSchema";
1514
import { VercelProjectIntegrationDataSchema } from "~/v3/vercel/vercelProjectIntegrationSchema";
@@ -433,6 +432,37 @@ export class VercelSettingsPresenter extends BasePresenter {
433432
});
434433
}
435434

435+
public async getExistingVariables(
436+
projectId: string
437+
): Promise<VercelOnboardingData["existingVariables"]> {
438+
const environments = await this._replica.runtimeEnvironment.findMany({
439+
where: { projectId, archivedAt: null },
440+
select: { id: true, slug: true, type: true },
441+
});
442+
const envIdToSlug = new Map(
443+
environments.map((environment) => [
444+
environment.id,
445+
environment.slug || environment.type.toLowerCase(),
446+
])
447+
);
448+
if (!envIdToSlug.size) return {};
449+
const values = await this._replica.environmentVariableValue.findMany({
450+
where: {
451+
variable: { projectId },
452+
environmentId: { in: boundedIn([...envIdToSlug.keys()]) },
453+
},
454+
select: { variable: { select: { key: true } }, environmentId: true },
455+
});
456+
const existing = new Map<string, { environments: string[] }>();
457+
for (const value of values) {
458+
const slug = envIdToSlug.get(value.environmentId)!;
459+
const entry = existing.get(value.variable.key);
460+
if (entry) entry.environments.push(slug);
461+
else existing.set(value.variable.key, { environments: [slug] });
462+
}
463+
return Object.fromEntries(existing);
464+
}
465+
436466
/**
437467
* Get data needed for the onboarding modal (custom environments and env vars)
438468
*/
@@ -734,36 +764,7 @@ export class VercelSettingsPresenter extends BasePresenter {
734764

735765
const sortedEnvVars = [...mergedEnvVars].sort((a, b) => a.key.localeCompare(b.key));
736766

737-
const projectEnvs = await (this._replica as PrismaClient).runtimeEnvironment.findMany({
738-
where: {
739-
projectId,
740-
archivedAt: null, // Filter out archived environments
741-
},
742-
select: {
743-
id: true,
744-
slug: true,
745-
type: true,
746-
},
747-
});
748-
const envIdToSlug = new Map(projectEnvs.map((e) => [e.id, e.slug]));
749-
const activeEnvIds = new Set(projectEnvs.map((e) => e.id));
750-
751-
const envVarRepository = new EnvironmentVariablesRepository(this._replica as PrismaClient);
752-
const existingVariables = await envVarRepository.getProject(projectId);
753-
const existingVariablesRecord: Record<string, { environments: string[] }> = {};
754-
for (const v of existingVariables) {
755-
// Filter out archived environments and map to slugs
756-
const activeEnvSlugs = v.values
757-
.filter((val) => activeEnvIds.has(val.environment.id))
758-
.map(
759-
(val) => envIdToSlug.get(val.environment.id) || val.environment.type.toLowerCase()
760-
);
761-
if (activeEnvSlugs.length > 0) {
762-
existingVariablesRecord[v.key] = {
763-
environments: activeEnvSlugs,
764-
};
765-
}
766-
}
767+
const existingVariables = await this.getExistingVariables(projectId);
767768

768769
const parsedIntegrationData = VercelProjectIntegrationDataSchema.safeParse(
769770
projectIntegration.integrationData
@@ -774,7 +775,7 @@ export class VercelSettingsPresenter extends BasePresenter {
774775
environmentVariables: sortedEnvVars,
775776
availableProjects: availableProjectsResult.value,
776777
hasProjectSelected: true,
777-
existingVariables: existingVariablesRecord,
778+
existingVariables,
778779
gitHubAppInstallations,
779780
isGitHubConnected,
780781
isOnboardingComplete: parsedIntegrationData.success

‎apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.environment-variables/route.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -932,6 +932,8 @@ function EnvironmentVariableTableRow({
932932
}
933933
content="With your current role, you can't view this environment's variables."
934934
/>
935+
) : variable.valueUnavailable ? (
936+
<span className="text-xs text-text-dimmed">Encryption key unavailable</span>
935937
) : variable.isSecret ? (
936938
<SimpleTooltip
937939
button={

‎apps/webapp/app/routes/api.v1.deployments.$deploymentId.build-env-vars.ts‎

Lines changed: 9 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -1,95 +1,32 @@
11
import { type LoaderFunctionArgs, json } from "@remix-run/server-runtime";
2-
import { type GetDeploymentBuildEnvVarsResponseBody } from "@trigger.dev/core/v3";
32
import { z } from "zod";
43
import { prisma } from "~/db.server";
5-
import { env } from "~/env.server";
64
import { authenticateApiKeyWithScope } from "~/services/apiAuth.server";
5+
import { deploymentBuildEnvVarsResponse } from "~/services/deploymentBuildEnvVars.server";
6+
import { environmentEncryption } from "~/services/environmentEncryption/instance.server";
77
import { logger } from "~/services/logger.server";
8-
import { decryptSecret, EncryptedSecretValueSchema } from "~/services/secrets/secretStore.server";
9-
import { FINAL_DEPLOYMENT_STATUSES } from "~/v3/services/failDeployment.server";
108

11-
const ParamsSchema = z.object({
12-
deploymentId: z.string(),
13-
});
9+
const ParamsSchema = z.object({ deploymentId: z.string() });
1410

1511
// Secret material: needs write, like the build's own progress and finalize calls.
1612
export async function loader({ request, params }: LoaderFunctionArgs) {
1713
const parsedParams = ParamsSchema.safeParse(params);
18-
19-
if (!parsedParams.success) {
20-
return json({ error: "Invalid params" }, { status: 400 });
21-
}
22-
14+
if (!parsedParams.success) return json({ error: "Invalid params" }, { status: 400 });
2315
try {
2416
const authResult = await authenticateApiKeyWithScope(request, {
2517
action: "write",
2618
resource: { type: "deployments" },
2719
});
28-
2920
if (!authResult.ok) {
3021
logger.info("Invalid or missing api key", { url: request.url });
3122
return json({ error: authResult.error }, { status: authResult.status });
3223
}
33-
34-
const authenticatedEnv = authResult.authentication.environment;
35-
36-
const { deploymentId } = parsedParams.data;
37-
38-
const deployment = await prisma.workerDeployment.findFirst({
39-
where: {
40-
friendlyId: deploymentId,
41-
environmentId: authenticatedEnv.id,
42-
},
43-
select: {
44-
id: true,
45-
status: true,
46-
buildEnvVars: true,
47-
},
48-
});
49-
50-
if (!deployment) {
51-
return json({ error: "Deployment not found" }, { status: 404 });
52-
}
53-
54-
logger.info("Build env vars read", {
55-
deploymentId,
56-
environmentId: authenticatedEnv.id,
57-
projectId: authenticatedEnv.projectId,
58-
status: deployment.status,
59-
hasVars: deployment.buildEnvVars !== null,
24+
return deploymentBuildEnvVarsResponse({
25+
db: prisma,
26+
encryption: environmentEncryption(),
27+
environment: authResult.authentication.environment,
28+
deploymentId: parsedParams.data.deploymentId,
6029
});
61-
62-
// Final rows keep their envelope for redeploys; only the new in-flight copy is ever served
63-
if (FINAL_DEPLOYMENT_STATUSES.includes(deployment.status)) {
64-
return json({ variables: {} } satisfies GetDeploymentBuildEnvVarsResponseBody, {
65-
status: 200,
66-
});
67-
}
68-
69-
if (!deployment.buildEnvVars) {
70-
return json({ variables: {} } satisfies GetDeploymentBuildEnvVarsResponseBody, {
71-
status: 200,
72-
});
73-
}
74-
75-
// Present-but-unreadable must fail loud: an empty record would let the build run without its secrets
76-
const envelope = EncryptedSecretValueSchema.safeParse(deployment.buildEnvVars);
77-
78-
if (!envelope.success) {
79-
logger.error("Stored build env vars are not a valid encrypted envelope", {
80-
deploymentId,
81-
environmentId: authenticatedEnv.id,
82-
});
83-
return json(
84-
{ error: "The stored build environment variables could not be read. Retry the deploy." },
85-
{ status: 500 }
86-
);
87-
}
88-
89-
const decrypted = await decryptSecret(env.ENCRYPTION_KEYRING, envelope.data);
90-
const variables = z.record(z.string(), z.string()).parse(JSON.parse(decrypted));
91-
92-
return json({ variables } satisfies GetDeploymentBuildEnvVarsResponseBody, { status: 200 });
9330
} catch (error) {
9431
if (error instanceof Response) throw error;
9532
logger.error("Failed to load deployment build env vars", { error });

‎apps/webapp/app/routes/engine.v1.dev.runs.$runFriendlyId.snapshots.$snapshotFriendlyId.attempts.start.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,11 @@ import { z } from "zod";
1010
import { prisma } from "~/db.server";
1111
import { generateJWTTokenForEnvironment } from "~/services/apiAuth.server";
1212
import { logger } from "~/services/logger.server";
13+
import { resolveAttemptVariables } from "~/services/environmentEncryption/attemptVariables.server";
1314
import { defaultMachine } from "~/services/platform.v3.server";
1415
import { devWorkerAuthorization } from "~/services/devWorkerAuthorization.server";
1516
import { createActionApiRoute } from "~/services/routeBuilders/apiBuilder.server";
16-
import { resolveVariablesForEnvironment } from "~/v3/environmentVariables/environmentVariablesRepository.server";
17+
import type { EnvironmentVariable } from "~/v3/environmentVariables/repository";
1718
import { machinePresetFromName } from "~/v3/machinePresets.server";
1819
import { meteringClaims } from "~/v3/utils/meteringClaims.server";
1920
import { engine } from "~/v3/runEngine.server";
@@ -49,6 +50,9 @@ const { action } = createActionApiRoute(
4950
throw new Response("You don't have permissions for this run", { status: 401 });
5051
}
5152

53+
// Resolved before the attempt exists, so an unavailable key leaves the run startable.
54+
const variables = await resolveAttemptVariables(authentication.environment);
55+
5256
const engineResult = await engine.startRunAttempt({
5357
runId: RunId.toId(runFriendlyId),
5458
snapshotId: SnapshotId.toId(snapshotFriendlyId),
@@ -58,6 +62,7 @@ const { action } = createActionApiRoute(
5862
const defaultMachinePreset = machinePresetFromName(defaultMachine);
5963

6064
const envVars = await getEnvVars(
65+
variables,
6166
authentication.environment,
6267
engineResult.run.id,
6368
engineResult.execution.machine ?? defaultMachinePreset,
@@ -84,14 +89,13 @@ const { action } = createActionApiRoute(
8489
);
8590

8691
async function getEnvVars(
92+
variables: EnvironmentVariable[],
8793
environment: AuthenticatedEnvironment,
8894
runId: string,
8995
machinePreset: MachinePreset,
9096
metering: Record<string, string>,
9197
taskEventStore?: string
9298
): Promise<Record<string, string>> {
93-
const variables = await resolveVariablesForEnvironment(environment);
94-
9599
const jwt = await generateJWTTokenForEnvironment(environment, {
96100
...metering,
97101
run_id: runId,

0 commit comments

Comments
 (0)