Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat(secret-sync): implement detach functionality for project and team shared environment variables

Victor Hugo dos Santos4f75a568d3df
diff --git a/backend/src/services/secret-sync/vercel/vercel-sync-fns.ts b/backend/src/services/secret-sync/vercel/vercel-sync-fns.ts
index 1b292df521..59453c2120 100644
--- a/backend/src/services/secret-sync/vercel/vercel-sync-fns.ts
+++ b/backend/src/services/secret-sync/vercel/vercel-sync-fns.ts
@@ -318,6 +318,72 @@ const updateSecret = async (
}
};
+// A project-scope record is "merged" when it covers more than just the sync's env.
+const isProjectRecordMerged = (vercelSecret: VercelApiSecret) => {
+ const totalScope = vercelSecret.target.length + (vercelSecret.customEnvironmentIds?.length ?? 0);
+ return totalScope > 1;
+};
+
+// Remove the sync's env from an existing Vercel project record, preserving the original value
+// for the remaining environments. Falls back to a full delete if removing our env would leave
+// the record with no scope at all.
+const detachEnvFromProjectSecret = async (
+ secretSync: TVercelSyncWithCredentials,
+ vercelSecret: VercelApiSecret,
+ attempt = 0
+): Promise<void> => {
+ const {
+ destinationConfig,
+ connection: {
+ credentials: { apiToken }
+ }
+ } = secretSync;
+
+ if (destinationConfig.scope !== VercelSyncScope.Project) {
+ throw new SecretSyncError({
+ message: "Invalid scope for Vercel secret sync",
+ shouldRetry: false
+ });
+ }
+
+ const newTarget = vercelSecret.target.filter((t) => t !== destinationConfig.env);
+ const newCustomEnvironmentIds = (vercelSecret.customEnvironmentIds ?? []).filter(
+ (id) => id !== destinationConfig.env
+ );
+
+ if (newTarget.length === 0 && newCustomEnvironmentIds.length === 0) {
+ await deleteSecret(secretSync, vercelSecret);
+ return;
+ }
+
+ try {
+ await request.patch(
+ `${IntegrationUrls.VERCEL_API_URL}/v9/projects/${destinationConfig.app}/env/${vercelSecret.id}?teamId=${destinationConfig.teamId}`,
+ {
+ ...(vercelSecret.type !== "sensitive" && { key: vercelSecret.key }),
+ type: vercelSecret.type,
+ target: newTarget,
+ customEnvironmentIds: newCustomEnvironmentIds
+ },
+ {
+ headers: {
+ Authorization: `Bearer ${apiToken}`,
+ "Accept-Encoding": "application/json"
+ }
+ }
+ );
+ } catch (error) {
+ if ((error as { response: { status: number } }).response.status === 429 && attempt < MAX_RETRIES) {
+ await sleep();
+ return detachEnvFromProjectSecret(secretSync, vercelSecret, attempt + 1);
+ }
+ throw new SecretSyncError({
+ error,
+ secretKey: vercelSecret.key
+ });
+ }
+};
+
// ===== Team-scoped shared environment variable functions =====
type TeamDestinationConfig = Extract<TVercelSyncWithCredentials["destinationConfig"], { scope: VercelSyncScope.Team }>;
@@ -330,10 +396,18 @@ const setsEqual = (a: readonly string[] | undefined, b: readonly string[] | unde
return av.every((v) => bSet.has(v));
};
-const isTeamSharedEnvVarOwnedByThisSync = (envVar: VercelSharedEnvVar, destinationConfig: TeamDestinationConfig) => {
- const expectedType = destinationConfig.sensitive ? "sensitive" : "encrypted";
- if (envVar.type !== expectedType) return false;
+const isSubset = (a: readonly string[] | undefined, b: readonly string[] | undefined) => {
+ const bSet = new Set(b ?? []);
+ return (a ?? []).every((v) => bSet.has(v));
+};
+// Ownership is by exact (target, projectId) scope match. Type is intentionally NOT checked
+// here — if it were, a sensitivity flip on an existing sync's var would orphan the var (it
+// would be invisible to both the owned and merged-superset paths) and the next sync run would
+// hit Vercel's `existing_key_and_target` rejection on create. Letting same-scope-different-type
+// vars enter the owned map lets the existing `sensitivityChanged` branch in syncSecrets do
+// delete-and-recreate.
+const isTeamSharedEnvVarOwnedByThisSync = (envVar: VercelSharedEnvVar, destinationConfig: TeamDestinationConfig) => {
const effectiveTargets = destinationConfig.sensitive
? destinationConfig.targetEnvironments?.filter((env) => env !== VercelEnvironmentType.Development)
: destinationConfig.targetEnvironments;
@@ -341,6 +415,30 @@ const isTeamSharedEnvVarOwnedByThisSync = (envVar: VercelSharedEnvVar, destinati
return setsEqual(envVar.target, effectiveTargets) && setsEqual(envVar.projectId, destinationConfig.targetProjects);
};
+// True when an existing team shared env var's scope is a strict superset of the sync's scope
+const teamVarStrictlyCoversSyncScope = (envVar: VercelSharedEnvVar, destinationConfig: TeamDestinationConfig) => {
+ const effectiveTargets =
+ (destinationConfig.sensitive
+ ? destinationConfig.targetEnvironments?.filter((env) => env !== VercelEnvironmentType.Development)
+ : destinationConfig.targetEnvironments) ?? [];
+
+ if (!isSubset(effectiveTargets, envVar.target)) return false;
+
+ const ourProjects = destinationConfig.targetProjects ?? [];
+ const varProjects = envVar.projectId ?? [];
+
+ // var.projectId empty means "team-wide / all projects" in Vercel
+ if (varProjects.length > 0) {
+ if (ourProjects.length === 0) return false;
+ if (!isSubset(ourProjects, varProjects)) return false;
+ }
+
+ // Scopes must not be exactly equal. If they are, this is the "owned" path.
+ const targetEqual = setsEqual(envVar.target, effectiveTargets);
+ const projectEqual = setsEqual(varProjects, ourProjects);
+ return !(targetEqual && projectEqual);
+};
+
const listTeamSharedEnvVarsWithRetries = async (
secretSync: TVercelSyncWithCredentials
): Promise<VercelSharedEnvVar[]> => {
@@ -663,16 +761,154 @@ const deleteTeamSharedEnvVar = async (
}
};
+// Detach this sync's scope from a team shared env var that strictly covers it. PATCHes the
+// var to remove our targets and projects, preserving its original value/type for the remaining
+// scopes. If the detach would leave the var with no scope at all, falls back to a full delete.
+const detachTeamSharedEnvVar = async (
+ secretSync: TVercelSyncWithCredentials,
+ envVar: VercelSharedEnvVar,
+ attempt = 0
+): Promise<void> => {
+ const {
+ destinationConfig,
+ connection: {
+ credentials: { apiToken }
+ }
+ } = secretSync;
+
+ if (destinationConfig.scope !== VercelSyncScope.Team) {
+ throw new SecretSyncError({
+ message: "Invalid scope for team-level Vercel secret sync",
+ shouldRetry: false
+ });
+ }
+
+ const ourEffectiveTargets =
+ (destinationConfig.sensitive
+ ? destinationConfig.targetEnvironments?.filter((env) => env !== VercelEnvironmentType.Development)
+ : destinationConfig.targetEnvironments) ?? [];
+ const ourTargetsSet = new Set<string>(ourEffectiveTargets);
+
+ const existingProjects = envVar.projectId ?? [];
+ const ourProjects = destinationConfig.targetProjects ?? [];
+ const ourProjectsSet = new Set(ourProjects);
+
+ // Only narrow a dimension where the var's scope is strictly broader than ours. If the
+ // dimensions are equal, leave them alone — narrowing an equal dimension would zero it out
+ // (e.g. removing projectId=[A] when ours=[A] gives []), which would either delete the var
+ // or — worse — silently broaden it (Vercel treats empty projectId as "all projects").
+ const targetsAreEqual = setsEqual(envVar.target, ourEffectiveTargets);
+ const newTarget = targetsAreEqual ? envVar.target : envVar.target.filter((t) => !ourTargetsSet.has(t));
+
+ const bothHaveProjects = existingProjects.length > 0 && ourProjects.length > 0;
+ const projectsAreEqual = bothHaveProjects && setsEqual(existingProjects, ourProjects);
+ const newProjectId =
+ bothHaveProjects && !projectsAreEqual ? existingProjects.filter((p) => !ourProjectsSet.has(p)) : existingProjects;
+
+ if (newTarget.length === 0 && newProjectId.length === 0 && existingProjects.length > 0) {
+ // After detach, var would have no remaining scope. Fall back to full delete.
+ await deleteTeamSharedEnvVar(secretSync, envVar);
+ return;
+ }
+ if (newTarget.length === 0 && existingProjects.length === 0) {
+ // Var was team-wide (no projectId). With no targets left, it has no scope. Full delete.
+ await deleteTeamSharedEnvVar(secretSync, envVar);
+ return;
+ }
+
+ // If detach didn't actually narrow anything in either dimension, the var is broader than us
+ // in a way we can't represent in Vercel (e.g. team-wide projectId vs sync's specific project
+ // list). PATCHing with a no-op leaves the overlap intact and the create that follows will be
+ // rejected. Surface this loudly with context instead of letting the user see a confusing
+ // `existing_key_and_target` error.
+ if (newTarget === envVar.target && newProjectId === existingProjects) {
+ throw new SecretSyncError({
+ message:
+ `Cannot detach scope from existing shared env var "${envVar.key}": ` +
+ `the var's scope is broader than this sync's in a dimension that can't be narrowed ` +
+ `(e.g. team-wide projectId or merged across both target environments and projects). ` +
+ `Manually split or scope the existing var in Vercel.`,
+ secretKey: envVar.key,
+ shouldRetry: false
+ });
+ }
+
+ try {
+ const { data: updateResponse } = await request.patch<{
+ updated: VercelSharedEnvVar[];
+ failed: { error: { code: string; message: string } }[];
+ }>(
+ `${IntegrationUrls.VERCEL_API_URL}/v1/env?teamId=${destinationConfig.teamId}`,
+ {
+ updates: {
+ [envVar.id]: {
+ ...(newTarget.length ? { target: newTarget } : {}),
+ ...(existingProjects.length > 0 ? { projectId: newProjectId } : {})
+ }
+ }
+ },
+ {
+ headers: {
+ Authorization: `Bearer ${apiToken}`,
+ "Accept-Encoding": "application/json"
+ }
+ }
+ );
+
+ if (updateResponse.failed?.length > 0) {
+ throw new SecretSyncError({
+ message: `Failed to detach scope from shared env var: ${updateResponse.failed[0].error.message}`,
+ secretKey: envVar.key,
+ shouldRetry: false
+ });
+ }
+ } catch (error) {
+ if (error instanceof SecretSyncError) throw error;
+ if ((error as { response: { status: number } }).response.status === 429 && attempt < MAX_RETRIES) {
+ await sleep();
+ return detachTeamSharedEnvVar(secretSync, envVar, attempt + 1);
+ }
+ throw new SecretSyncError({ error, secretKey: envVar.key });
+ }
+};
+
+const getMergedTeamSharedEnvVars = async (secretSync: TVercelSyncWithCredentials): Promise<VercelSharedEnvVar[]> => {
+ if (secretSync.destinationConfig.scope !== VercelSyncScope.Team) {
+ throw new SecretSyncError({
+ message: "Invalid scope for team-level Vercel secret sync",
+ shouldRetry: false
+ });
+ }
+
+ const teamDestinationConfig = secretSync.destinationConfig;
+ const allSharedEnvVars = await getTeamSharedEnvVars(secretSync);
+ return allSharedEnvVars.filter((envVar) => teamVarStrictlyCoversSyncScope(envVar, teamDestinationConfig));
+};
+
export const VercelSyncFns = {
syncSecrets: async (secretSync: TVercelSyncWithCredentials, secretMap: TSecretMap) => {
if (secretSync.destinationConfig.scope === VercelSyncScope.Team) {
const sharedEnvVars = await getOwnedTeamSharedEnvVars(secretSync);
const sharedEnvVarsMap = new Map(sharedEnvVars.map((s) => [s.key, s]));
+ // Vars whose scope strictly covers ours — Vercel rejects creating an overlapping var,
+ // so we must split (detach our scope from the existing var, then create a dedicated
+ // record)
+ const mergedSharedEnvVars = await getMergedTeamSharedEnvVars(secretSync);
+ const mergedSharedEnvVarsMap = new Map(mergedSharedEnvVars.map((s) => [s.key, s]));
+
const { targetEnvironments, targetProjects, sensitive } = secretSync.destinationConfig;
for await (const key of Object.keys(secretMap)) {
const existingVar = sharedEnvVarsMap.get(key);
+ const mergedVar = mergedSharedEnvVarsMap.get(key);
+
+ if (mergedVar) {
+ await detachTeamSharedEnvVar(secretSync, mergedVar);
+ await createTeamSharedEnvVar(secretSync, key, secretMap[key].value);
+ // eslint-disable-next-line no-continue
+ continue;
+ }
if (!existingVar) {
await createTeamSharedEnvVar(secretSync, key, secretMap[key].value);
@@ -744,6 +980,15 @@ export const VercelSyncFns = {
continue;
}
+ // Merged record (covers other environments too): detach our env from it — preserving
+ // the original value for the remaining environments — then create a dedicated record.
+ if (isProjectRecordMerged(existingSecret)) {
+ await detachEnvFromProjectSecret(secretSync, existingSecret);
+ await createSecret(secretSync, secretMap, key);
+ // eslint-disable-next-line no-continue
+ continue;
+ }
+
// Vercel does not allow changing a secret's `type` between encrypted and sensitive
// via PATCH, so we delete and recreate when the desired sensitivity differs.
const existingIsSensitive = existingSecret.type === "sensitive";
@@ -765,6 +1010,12 @@ export const VercelSyncFns = {
// eslint-disable-next-line no-continue
continue;
+ // Skip merged rows: delete removes the whole multi-env record, not only this sync's scope.
+ if (isProjectRecordMerged(vercelSecret)) {
+ // eslint-disable-next-line no-continue
+ continue;
+ }
+
if (!secretMap[vercelSecret.key]) {
await deleteSecret(secretSync, vercelSecret);
}