Skip to content

Commit 6ed4499

Browse files
carderneTrigger.dev RepoOps
authored andcommitted
feat(cli,webapp): set Secret Proxy values from trigger env set
Mono-RevId: 6069c172e6bacb841e3e83fd02b062c26dcad44f
1 parent 54236fd commit 6ed4499

12 files changed

Lines changed: 716 additions & 52 deletions

File tree

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"trigger.dev": patch
3+
"@trigger.dev/core": patch
4+
---
5+
6+
Add Secret Proxy support to `trigger env set`. Pass `--secret-proxy` with `--allowed-domain` to store a value that tasks only get as a placeholder, and `--allowed-header` to choose the request headers it can be sent in. Leave out the value to move an existing variable into Secret Proxy or change its policy.
Lines changed: 154 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,154 @@
1+
import type { ActionFunctionArgs } from "@remix-run/server-runtime";
2+
import { json } from "@remix-run/server-runtime";
3+
import { SetSecretProxyVariableRequestBody } from "@trigger.dev/core/v3";
4+
import { z } from "zod";
5+
import { prisma } from "~/db.server";
6+
import {
7+
authenticatedEnvironmentForAuthentication,
8+
branchNameFromRequest,
9+
} from "~/services/apiAuth.server";
10+
import {
11+
authenticateEnvVarApiRequest,
12+
authorizeEnvVarApiRequest,
13+
} from "~/services/environmentVariableApiAccess.server";
14+
import { logger } from "~/services/logger.server";
15+
import {
16+
checkProxyPolicy,
17+
DEFAULT_PROXY_ALLOWED_HEADERS,
18+
} from "~/services/secretProxy/placeholder.server";
19+
import { EnvironmentVariablesRepository } from "~/v3/environmentVariables/environmentVariablesRepository.server";
20+
21+
const ParamsSchema = z.object({
22+
projectRef: z.string(),
23+
slug: z.string(),
24+
name: z.string(),
25+
});
26+
27+
const BRANCH_HEADER = "x-trigger-branch";
28+
29+
/**
30+
* Creates or updates a Secret Proxy value, or moves an existing value into Secret Proxy. Never
31+
* returns a value.
32+
*/
33+
export async function action({ params, request }: ActionFunctionArgs) {
34+
if (request.method.toUpperCase() !== "PUT") {
35+
return json({ error: "Method not allowed" }, { status: 405 });
36+
}
37+
38+
const parsedParams = ParamsSchema.safeParse(params);
39+
if (!parsedParams.success) {
40+
return json({ error: "Invalid params" }, { status: 400 });
41+
}
42+
43+
// Elsewhere a branch on another environment's slug, or one that sanitizes away, resolves to a
44+
// different environment than the caller named. Refuse both rather than write there.
45+
const branchHeader = request.headers.get(BRANCH_HEADER);
46+
const branch = branchNameFromRequest(request);
47+
if (branchHeader !== null && (parsedParams.data.slug !== "preview" || !branch)) {
48+
return json(
49+
{ error: "A branch can only be given for the preview environment, as a branch name." },
50+
{ status: 400 }
51+
);
52+
}
53+
54+
try {
55+
const authResult = await authenticateEnvVarApiRequest(request, "write");
56+
if (!authResult.ok) {
57+
return json({ error: authResult.error }, { status: authResult.status });
58+
}
59+
const authentication = authResult.authentication;
60+
// Task code holds its environment's API key and a run token. Either could widen a policy to a
61+
// host it controls and receive the real value, so only a user may change Secret Proxy values.
62+
if (authentication.type !== "personalAccessToken") {
63+
return json(
64+
{ error: "Changing Secret Proxy values needs a personal login. Run `trigger login`." },
65+
{ status: 403 }
66+
);
67+
}
68+
69+
const environment = await authenticatedEnvironmentForAuthentication(
70+
authentication,
71+
parsedParams.data.projectRef,
72+
parsedParams.data.slug,
73+
branch
74+
);
75+
76+
// As in the dashboard, a user who can't read a tier's values can't use Secret Proxy there.
77+
for (const action of ["write", "read"] as const) {
78+
const denied = await authorizeEnvVarApiRequest({
79+
request,
80+
authType: authentication.type,
81+
organizationId: environment.organizationId,
82+
projectId: environment.project.id,
83+
envType: environment.type,
84+
action,
85+
});
86+
if (denied) return denied;
87+
}
88+
89+
// The body holds a credential, and a JSON syntax error can quote it, so the error itself is
90+
// neither returned nor logged.
91+
const rawBody: unknown = await request.json().catch(() => undefined);
92+
const body = SetSecretProxyVariableRequestBody.safeParse(rawBody);
93+
if (!body.success) {
94+
return json({ error: "Invalid request body" }, { status: 400 });
95+
}
96+
97+
const current = await prisma.environmentVariableValue.findFirst({
98+
where: {
99+
environmentId: environment.id,
100+
variable: { projectId: environment.project.id, key: parsedParams.data.name },
101+
},
102+
select: { variableId: true },
103+
});
104+
105+
const userId = authentication.result.userId;
106+
const repository = new EnvironmentVariablesRepository();
107+
let result;
108+
if (current) {
109+
// Fields left out are filled in by the repository, from the policy it reads under its lock.
110+
result = await repository.saveVaultValue(environment.project.id, {
111+
id: current.variableId,
112+
environmentId: environment.id,
113+
policy: {
114+
...(body.data.allowedHosts && { allowedHosts: body.data.allowedHosts }),
115+
...(body.data.allowedHeaders && { allowedHeaders: body.data.allowedHeaders }),
116+
},
117+
value: body.data.value,
118+
userId,
119+
});
120+
} else {
121+
if (body.data.value === undefined) {
122+
return json(
123+
{ error: "This variable has no value in this environment. Pass a value to create it." },
124+
{ status: 404 }
125+
);
126+
}
127+
const checked = checkProxyPolicy({
128+
allowedHosts: body.data.allowedHosts ?? [],
129+
allowedHeaders: body.data.allowedHeaders ?? DEFAULT_PROXY_ALLOWED_HEADERS,
130+
});
131+
if (!checked.policy) {
132+
return json({ error: checked.message }, { status: 400 });
133+
}
134+
result = await repository.create(environment.project.id, {
135+
override: true,
136+
isSecret: true,
137+
vaultPolicy: checked.policy,
138+
environmentIds: [environment.id],
139+
parentEnvironmentId: environment.parentEnvironmentId ?? undefined,
140+
variables: [{ key: parsedParams.data.name, value: body.data.value }],
141+
lastUpdatedBy: { type: "user", userId },
142+
});
143+
}
144+
145+
if (!result.success) {
146+
return json({ error: result.error }, { status: result.conflict ? 409 : 400 });
147+
}
148+
return json({ success: true });
149+
} catch (error) {
150+
if (error instanceof Response) throw error;
151+
logger.error("Failed to set Secret Proxy variable", { error, projectRef: params.projectRef });
152+
return json({ error: "Internal Server Error" }, { status: 500 });
153+
}
154+
}

‎apps/webapp/app/services/secretProxy/placeholder.server.ts‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -140,14 +140,14 @@ const PROXY_HEADERS_ERROR = `Enter 1 to ${MAX_PROXY_ALLOWED_HEADERS} header name
140140
* on its own so the form can say which one is wrong.
141141
*/
142142
export function parseProxyPolicyForm(domains: string, headers: string) {
143-
const list = (text: string) =>
144-
text
145-
.toLowerCase()
146-
.split(",")
147-
.map((item) => item.trim())
148-
.filter(Boolean);
149-
const allowedHosts = ProxyAllowedHosts.safeParse(list(domains));
150-
const allowedHeaders = ProxyAllowedHeaders.safeParse(list(headers));
143+
return checkProxyPolicy({ allowedHosts: domains.split(","), allowedHeaders: headers.split(",") });
144+
}
145+
146+
/** Checks a submitted policy, ignoring case and blank entries, and says which field is wrong. */
147+
export function checkProxyPolicy(submitted: { allowedHosts: string[]; allowedHeaders: string[] }) {
148+
const list = (items: string[]) => items.map((item) => item.trim().toLowerCase()).filter(Boolean);
149+
const allowedHosts = ProxyAllowedHosts.safeParse(list(submitted.allowedHosts));
150+
const allowedHeaders = ProxyAllowedHeaders.safeParse(list(submitted.allowedHeaders));
151151
if (!allowedHosts.success) return { error: "domains" as const, message: PROXY_DOMAINS_ERROR };
152152
if (!allowedHeaders.success) return { error: "headers" as const, message: PROXY_HEADERS_ERROR };
153153
return { policy: { allowedHosts: allowedHosts.data, allowedHeaders: allowedHeaders.data } };

‎apps/webapp/app/v3/environmentVariables/environmentVariablesRepository.server.ts‎

Lines changed: 92 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ import { env } from "~/env.server";
2626
import { auditLogs } from "~/services/auditLogs/auditLogs.server";
2727
import { logger } from "~/services/logger.server";
2828
import {
29+
checkProxyPolicy,
30+
DEFAULT_PROXY_ALLOWED_HEADERS,
2931
intersectProxyPolicy,
3032
parseProxyConfig,
3133
type ProxyPolicy,
@@ -198,6 +200,61 @@ type WrittenValue = {
198200
*/
199201
const POLICY_UPDATE_BATCH_SIZE = 1000;
200202

203+
/**
204+
* The policy `saveVaultValue` stores: the submitted fields over the value's current policy. Call
205+
* with the variable's lock held, so a concurrent save of another field isn't undone. `covered`
206+
* when the value was already in Vault, itself or through its parent.
207+
*/
208+
async function vaultPolicyToSave(
209+
tx: PrismaClientOrTransaction,
210+
variableId: string,
211+
environmentId: string,
212+
submitted: Partial<ProxyPolicy>
213+
): Promise<{ policy: ProxyPolicy | "inherited"; covered: boolean }> {
214+
const environment = await tx.runtimeEnvironment.findFirstOrThrow({
215+
where: { id: environmentId },
216+
select: { parentEnvironmentId: true },
217+
});
218+
const values = await tx.environmentVariableValue.findMany({
219+
where: {
220+
variableId,
221+
isProxyOnly: true,
222+
environmentId: {
223+
in: boundedIn(
224+
environment.parentEnvironmentId
225+
? [environmentId, environment.parentEnvironmentId]
226+
: [environmentId]
227+
),
228+
},
229+
},
230+
select: { environmentId: true, proxyConfig: true },
231+
});
232+
const configOf = (id: string | null) =>
233+
values.find((value) => value.environmentId === id)?.proxyConfig;
234+
const own = configOf(environmentId);
235+
const inherited = configOf(environment.parentEnvironmentId);
236+
const covered = own !== undefined || inherited !== undefined;
237+
// A branch override in Vault through its parent follows the parent's policy until it's given
238+
// its own, so a save that sets no policy leaves it that way.
239+
if (
240+
own === undefined &&
241+
inherited !== undefined &&
242+
submitted.allowedHosts === undefined &&
243+
submitted.allowedHeaders === undefined
244+
) {
245+
return { policy: "inherited", covered };
246+
}
247+
const currentConfig = own ?? inherited;
248+
const current = currentConfig === undefined ? undefined : parseProxyConfig(currentConfig);
249+
const checked = checkProxyPolicy({
250+
allowedHosts: submitted.allowedHosts ?? current?.allowedHosts ?? [],
251+
allowedHeaders:
252+
submitted.allowedHeaders ?? current?.allowedHeaders ?? DEFAULT_PROXY_ALLOWED_HEADERS,
253+
});
254+
if (!checked.policy) throw new Error(checked.message);
255+
return { policy: checked.policy, covered };
256+
}
257+
201258
/**
202259
* Before these values are deleted or removed from Vault: a Preview branch's own value under one
203260
* of them keeps the policy it had through it, so a parent leaving Vault never unseals a branch or
@@ -1218,13 +1275,15 @@ export class EnvironmentVariablesRepository implements Repository {
12181275
/**
12191276
* Stores a value in Agent Vault, sent only as its policy allows. Moves an ordinary value in, or
12201277
* changes a Vault value's policy and, when `value` is set, its value. Never takes a value out.
1278+
* Policy fields left out keep the value's current policy, read under the variable's lock: its
1279+
* own, else its Vault parent's, else the defaults. There is no default for hosts.
12211280
*/
12221281
async saveVaultValue(
12231282
projectId: string,
12241283
options: {
12251284
id: string;
12261285
environmentId: string;
1227-
policy: ProxyPolicy;
1286+
policy: Partial<ProxyPolicy>;
12281287
value?: string;
12291288
userId: string;
12301289
}
@@ -1259,6 +1318,12 @@ export class EnvironmentVariablesRepository implements Repository {
12591318
await $transaction(this.prismaClient, "save env var value in vault", async (tx) => {
12601319
await lockVariableKeys(tx, projectId, [variable.key]);
12611320
await assertProjectVaultEnabled(tx, projectId, [options.environmentId]);
1321+
const { policy, covered } = await vaultPolicyToSave(
1322+
tx,
1323+
variable.id,
1324+
options.environmentId,
1325+
options.policy
1326+
);
12621327
if (prepared && options.value !== undefined) {
12631328
assertVaultValueSize(options.value);
12641329
await this.encryption.assertWrite(tx, [...prepared.values()]);
@@ -1272,30 +1337,36 @@ export class EnvironmentVariablesRepository implements Repository {
12721337
secretKey(projectId, options.environmentId, variable.key),
12731338
{ secret: options.value }
12741339
);
1275-
} else {
1276-
// Moving a value in keeps the stored credential, and the proxy refuses large ones.
1277-
// Read only to measure it, inside the transaction, along with any branch overrides the
1278-
// move newly brings into Vault.
1279-
const covered = await tx.environmentVariableValue.findMany({
1280-
where: {
1281-
variableId: variable.id,
1282-
isProxyOnly: false,
1283-
OR: [
1284-
{ environmentId: options.environmentId },
1285-
{ environment: { parentEnvironmentId: options.environmentId, archivedAt: null } },
1286-
],
1287-
},
1288-
select: { environmentId: true },
1289-
});
1340+
}
1341+
// The proxy refuses large credentials. A move into Vault newly covers this value, unless
1342+
// it was just replaced, and the branch overrides under it. Those stored values are read
1343+
// only to measure them, inside the transaction. A value already in Vault covers them
1344+
// already, so they aren't read again.
1345+
const newlyCovered = covered
1346+
? []
1347+
: await tx.environmentVariableValue.findMany({
1348+
where: {
1349+
variableId: variable.id,
1350+
isProxyOnly: false,
1351+
OR: [
1352+
...(options.value === undefined
1353+
? [{ environmentId: options.environmentId }]
1354+
: []),
1355+
{ environment: { parentEnvironmentId: options.environmentId, archivedAt: null } },
1356+
],
1357+
},
1358+
select: { environmentId: true },
1359+
});
1360+
if (newlyCovered.length) {
12901361
const stored = await this.#secretStore(
12911362
tx,
12921363
projectId,
1293-
covered.map((value) => value.environmentId),
1364+
newlyCovered.map((value) => value.environmentId),
12941365
undefined,
12951366
new Set()
12961367
).getSecretsByKeys(
12971368
SecretValue,
1298-
covered.map((value) => secretKey(projectId, value.environmentId, variable.key))
1369+
newlyCovered.map((value) => secretKey(projectId, value.environmentId, variable.key))
12991370
);
13001371
stored.forEach((secret) => assertVaultValueSize(secret.value.secret));
13011372
}
@@ -1307,9 +1378,9 @@ export class EnvironmentVariablesRepository implements Repository {
13071378
},
13081379
},
13091380
data: {
1310-
isProxyOnly: true,
1311-
isSecret: true,
1312-
proxyConfig: options.policy,
1381+
...(policy === "inherited"
1382+
? {}
1383+
: { isProxyOnly: true, isSecret: true, proxyConfig: policy }),
13131384
version: { increment: 1 },
13141385
lastUpdatedBy: { type: "user", userId: options.userId },
13151386
},

0 commit comments

Comments
 (0)