Skip to content

Commit 94699d9

Browse files
carderneTrigger.dev RepoOps
authored andcommitted
feat: add experimental proxy-only policy and resolver
Add disabled-by-default experimental proxy-only variable policies, run-bound placeholders and an internal resolver using existing encryption and run tokens. Keep protected values out of ordinary delivery and reject unsupported paths. Mono-RevId: 7db4377156f87e6bdac3b6b5af6f6759563995f9
1 parent 57d056e commit 94699d9

40 files changed

Lines changed: 2506 additions & 143 deletions

‎.env.schema‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,19 @@ 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+
# Lab only. Proxy-only values stay protected even when this gate is disabled.
12+
# @sensitive=false
13+
SECRET_PROXY_ENABLED=false
14+
# Serves /engine/v1/secret-proxy/resolve. Enable only on the private engine service.
15+
# @sensitive=false
16+
SECRET_PROXY_RESOLVER_ENABLED=false
17+
# Owner-only interceptor control socket. Unset keeps automatic registration disabled.
18+
# @sensitive=false
19+
SECRET_PROXY_INTERCEPTOR_SOCKET=
20+
# Dedicated HMAC keys: {"activeKeyId":"k1","keys":{"k1":"<32-byte lowercase hex>"}}
21+
SECRET_PROXY_PLACEHOLDER_KEYS=
22+
# Dedicated resolver service bearer, unrelated to run tokens and encryption keys (at least 32 chars).
23+
SECRET_PROXY_SERVICE_TOKEN=
1124
# Master gate for automatic enrollment; also requires the org/global environmentEncryptionEnabled flag.
1225
# Enable only after every reader supports versioned environment encryption.
1326
# @sensitive=false

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -432,6 +432,16 @@ const EnvironmentSchema = z
432432
)
433433
.refine(isNotInsecureSecret, INSECURE_SECRET_MESSAGE),
434434
ENCRYPTION_KEYRING: z.string().transform(parseEncryptionKeyring).optional(),
435+
SECRET_PROXY_ENABLED: BoolEnv.default(false),
436+
SECRET_PROXY_RESOLVER_ENABLED: BoolEnv.default(false),
437+
SECRET_PROXY_PLACEHOLDER_KEYS: z.preprocess(
438+
(value) => (value === "" ? undefined : value),
439+
z.string().optional()
440+
),
441+
SECRET_PROXY_SERVICE_TOKEN: z.preprocess(
442+
(value) => (value === "" ? undefined : value),
443+
z.string().min(32).optional()
444+
),
435445
ENVIRONMENT_ENCRYPTION_ENABLED: BoolEnv.default(false),
436446
ENVIRONMENT_ENCRYPTION_KMS_KEY_ARN: z.preprocess(
437447
(value) => (value === "" ? undefined : value),

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@ import { $transaction, prisma } from "~/db.server";
2020
import { env } from "~/env.server";
2121
import { logger } from "~/services/logger.server";
2222
import { getSecretStore } from "~/services/secrets/secretStore.server";
23+
import {
24+
environmentSecretPrefix,
25+
protectedSecretKeys,
26+
} from "~/services/environmentEncryption/secretStore.server";
2327
import { generateFriendlyId } from "~/v3/friendlyIdentifiers";
2428
import type {
2529
SyncEnvVarsMapping,
@@ -1398,7 +1402,15 @@ export class VercelIntegrationRepository {
13981402
return;
13991403
}
14001404

1405+
const protectedKeys = await protectedSecretKeys(prisma, params.projectId, [
1406+
mapping.runtimeEnvironmentId,
1407+
]);
1408+
const secretPrefix = environmentSecretPrefix(
1409+
params.projectId,
1410+
mapping.runtimeEnvironmentId
1411+
);
14011412
const varsToSync = mergedEnvVars.filter((envVar) => {
1413+
if (protectedKeys.has(`${secretPrefix}${envVar.key}`)) return false;
14021414
// Keep the flag-off path unchanged. When enabled, discard blanks
14031415
// after merging so a blank project override cannot select a shared fallback.
14041416
if (allowEmptyValues && envVar.value.trim() === "") {

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ const { action } = createActionApiRoute(
5151
}
5252

5353
// Resolved before the attempt exists, so an unavailable key leaves the run startable.
54-
const variables = await resolveAttemptVariables(authentication.environment);
54+
const { variables } = await resolveAttemptVariables(authentication.environment);
5555

5656
const engineResult = await engine.startRunAttempt({
5757
runId: RunId.toId(runFriendlyId),
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { json, type ActionFunctionArgs } from "@remix-run/server-runtime";
2+
import { env } from "~/env.server";
3+
import { secretProxy } from "~/services/secretProxy/instance.server";
4+
import { resolveSecretProxyRequest } from "~/services/secretProxy/resolveAction.server";
5+
6+
const headers = { "Cache-Control": "no-store", Pragma: "no-cache" };
7+
const RESOLVE_PATH = "/engine/v1/secret-proxy/resolve";
8+
9+
// Served only by the private engine service; every other service answers as if the route did not exist.
10+
function notFound() {
11+
return json({ error: "Not found" }, { status: 404, headers });
12+
}
13+
14+
// The public load balancer blocks this path by its raw spelling, but the router matches after
15+
// percent-decoding and case-folding. Only the exact spelling the relay sends is served.
16+
function served(request: Request) {
17+
return env.SECRET_PROXY_RESOLVER_ENABLED && new URL(request.url).pathname === RESOLVE_PATH;
18+
}
19+
20+
export function action({ request }: ActionFunctionArgs) {
21+
if (!served(request)) return notFound();
22+
return resolveSecretProxyRequest(secretProxy(), request);
23+
}
24+
25+
export function loader({ request }: ActionFunctionArgs) {
26+
if (!served(request)) return notFound();
27+
return json({ error: "Method not allowed" }, { status: 405, headers });
28+
}

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ export const action = createActionWorkerApiRoute(
2929
workerCell: body.workerCell,
3030
workerLane: body.workerLane,
3131
supportsRunTokenRefresh: body.supportsRunTokenRefresh,
32+
supportsSecretProxy: body.supportsSecretProxy,
3233
runnerId,
3334
environmentId,
3435
});

‎apps/webapp/app/services/deploymentBuildEnvVars.server.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import type { EnvironmentEncryptionService } from "~/services/environmentEncrypt
88
import { environmentEncryptionTelemetry } from "~/services/environmentEncryption/telemetry.server";
99
import { EnvironmentKeyUnavailableError } from "~/services/environmentEncryption/wrapping.server";
1010
import { FINAL_DEPLOYMENT_STATUSES } from "~/v3/services/failDeployment.server";
11+
import { effectiveEnvironmentVariables } from "./secretProxy/variables.server";
1112

1213
export async function deploymentBuildEnvVarsResponse(options: {
1314
db: PrismaClientOrTransaction;
@@ -35,6 +36,13 @@ export async function deploymentBuildEnvVarsResponse(options: {
3536
return json({ variables: {} } satisfies GetDeploymentBuildEnvVarsResponseBody);
3637
}
3738

39+
const metadata = await effectiveEnvironmentVariables(db, environment.projectId, environment.id);
40+
if (metadata.some((value) => value.isProxyOnly)) {
41+
return json(
42+
{ error: "Stored build environment exports are disabled for proxy-only environments" },
43+
{ status: 403 }
44+
);
45+
}
3846
const envelope = StoredEnvironmentValueSchema.safeParse(deployment.buildEnvVars);
3947
if (!envelope.success) {
4048
logger.error("Stored build env vars are not a valid encrypted envelope", {

‎apps/webapp/app/services/engineRateLimit.server.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@ export const engineRateLimiter = authorizationRateLimitMiddleware({
2424
maxItems: 1000,
2525
},
2626
pathMatchers: [/^\/engine(?:\/|$)/],
27-
pathWhiteList: [/^\/engine\/v1\/worker-actions(?:\/|$)/],
27+
// The resolver's bearer is a run token; the relay bounds its own resolver concurrency.
28+
pathWhiteList: [/^\/engine\/v1\/(?:worker-actions|secret-proxy)(?:\/|$)/],
2829
log: {
2930
rejections: env.RUN_ENGINE_RATE_LIMIT_REJECTION_LOGS_ENABLED === "1",
3031
requests: env.RUN_ENGINE_RATE_LIMIT_REQUEST_LOGS_ENABLED === "1",

‎apps/webapp/app/services/environmentEncryption/attemptVariables.server.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { json } from "@remix-run/server-runtime";
22
import {
3-
resolveVariablesForEnvironment,
3+
prepareVariablesForEnvironment,
44
type RuntimeEnvironmentForEnvRepo,
55
} from "~/v3/environmentVariables/environmentVariablesRepository.server";
66
import { EnvironmentKeyUnavailableError } from "./wrapping.server";
@@ -9,10 +9,11 @@ import { environmentEncryptionTelemetry } from "./telemetry.server";
99
// Called before the attempt starts, so an unavailable key consumes no attempt and the start can be retried.
1010
export async function resolveAttemptVariables(
1111
environment: RuntimeEnvironmentForEnvRepo,
12-
parentEnvironment?: RuntimeEnvironmentForEnvRepo
12+
parentEnvironment?: RuntimeEnvironmentForEnvRepo,
13+
options?: { proxyEnabled?: boolean }
1314
) {
1415
try {
15-
return await resolveVariablesForEnvironment(environment, parentEnvironment);
16+
return await prepareVariablesForEnvironment(environment, parentEnvironment, options);
1617
} catch (error) {
1718
if (!(error instanceof EnvironmentKeyUnavailableError)) throw error;
1819
environmentEncryptionTelemetry().failures.add(1, { reason: "attempt_start_unavailable" });

‎apps/webapp/app/services/environmentEncryption/secretStore.server.ts‎

Lines changed: 52 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { boundedIn, type PrismaClientOrTransaction } from "@trigger.dev/database";
1+
import { boundedIn, Prisma, type PrismaClientOrTransaction } from "@trigger.dev/database";
22
import type { z } from "zod";
33
import { logger } from "~/services/logger.server";
44
import { safeJsonParse } from "~/utils/json";
@@ -15,14 +15,46 @@ export function environmentSecretPrefixEnd(projectId: string, environmentId: str
1515
return `${environmentSecretPrefix(projectId, environmentId).slice(0, -1)};`;
1616
}
1717

18+
export async function protectedSecretKeys(
19+
db: PrismaClientOrTransaction,
20+
projectId: string,
21+
environmentIds: string[]
22+
): Promise<Set<string>> {
23+
if (!environmentIds.length) return new Set();
24+
const policies = await db.$queryRaw<Array<{ environmentId: string; key: string }>>(Prisma.sql`
25+
WITH environments AS (
26+
SELECT id, "parentEnvironmentId"
27+
FROM "RuntimeEnvironment"
28+
WHERE id = ANY(${[...new Set(environmentIds)]}::text[]) AND "projectId" = ${projectId}
29+
)
30+
SELECT e.id AS "environmentId", v.key
31+
FROM environments e
32+
JOIN "EnvironmentVariableValue" value ON value."environmentId" = e.id
33+
JOIN "EnvironmentVariable" v ON v.id = value."variableId"
34+
WHERE value."isProxyOnly" = true AND v."projectId" = ${projectId}
35+
UNION ALL
36+
SELECT e.id AS "environmentId", v.key
37+
FROM environments e
38+
JOIN "EnvironmentVariableValue" value ON value."environmentId" = e."parentEnvironmentId"
39+
JOIN "EnvironmentVariable" v ON v.id = value."variableId"
40+
WHERE value."isProxyOnly" = true AND v."projectId" = ${projectId}
41+
`);
42+
return new Set(
43+
policies.map(
44+
(policy) => `${environmentSecretPrefix(projectId, policy.environmentId)}${policy.key}`
45+
)
46+
);
47+
}
48+
1849
export class EnvironmentSecretStore {
1950
readonly #prefixes: Array<{ environmentId: string; prefix: string }>;
2051
constructor(
2152
private readonly db: PrismaClientOrTransaction,
2253
private readonly encryption: EnvironmentEncryptionService,
2354
private readonly projectId: string,
2455
environmentIds: string[],
25-
private readonly prepared = new Map<string, PreparedEnvironmentWrite>()
56+
private readonly prepared = new Map<string, PreparedEnvironmentWrite>(),
57+
private readonly protectedKeys?: ReadonlySet<string>
2658
) {
2759
this.#prefixes = [...new Set(environmentIds)].map((environmentId) => ({
2860
environmentId,
@@ -44,6 +76,15 @@ export class EnvironmentSecretStore {
4476
schema: z.Schema<T>,
4577
rows: Array<{ key: string; value: unknown; version: string }>
4678
) {
79+
if (!rows.length) return [];
80+
const protectedKeys =
81+
this.protectedKeys ??
82+
(await protectedSecretKeys(
83+
this.db,
84+
this.projectId,
85+
this.#prefixes.map((owner) => owner.environmentId)
86+
));
87+
rows = rows.filter((row) => !protectedKeys.has(row.key));
4788
const values = await this.encryption.decryptMany(
4889
rows.map((row) => ({
4990
projectId: this.projectId,
@@ -86,6 +127,10 @@ export class EnvironmentSecretStore {
86127

87128
async setSecret<T extends object>(key: string, value: T) {
88129
const context = this.#context(key);
130+
const protectedKeys =
131+
this.protectedKeys ??
132+
(await protectedSecretKeys(this.db, this.projectId, [context.environmentId]));
133+
if (protectedKeys.has(key)) throw new Error("Proxy-only variables require operator changes");
89134
const prepared = this.prepared.get(context.environmentId);
90135
if (!prepared)
91136
throw new Error("Environment encryption must be prepared before starting a transaction");
@@ -99,7 +144,11 @@ export class EnvironmentSecretStore {
99144
}
100145

101146
async deleteSecret(key: string) {
102-
this.#context(key);
147+
const context = this.#context(key);
148+
const protectedKeys =
149+
this.protectedKeys ??
150+
(await protectedSecretKeys(this.db, this.projectId, [context.environmentId]));
151+
if (protectedKeys.has(key)) throw new Error("Proxy-only variables require operator changes");
103152
await this.db.secretStore.delete({ where: { key } });
104153
}
105154
}

0 commit comments

Comments
 (0)