Skip to content

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

refactor file

Matheus Nogueira62757885f823
diff --git a/backend/src/services/secret-sync/spacelift/spacelift-sync-fns.ts b/backend/src/services/secret-sync/spacelift/spacelift-sync-fns.ts
index ac60142a3f..74a53c077f 100644
--- a/backend/src/services/secret-sync/spacelift/spacelift-sync-fns.ts
+++ b/backend/src/services/secret-sync/spacelift/spacelift-sync-fns.ts
@@ -101,12 +101,49 @@ const deleteContextConfigElement = async (instanceUrl: string, jwt: string, cont
);
};
+const sanitizeEnvVarName = (name: string): string => {
+ let sanitized = name.replace(/[^a-zA-Z0-9_]/g, "");
+ if (sanitized.length > 0 && /^[0-9]/.test(sanitized)) {
+ sanitized = `_${sanitized}`;
+ }
+ return sanitized;
+};
+
+const sanitizeSecretMapForEnvVars = (secretMap: TSecretMap): TSecretMap => {
+ const sanitized: TSecretMap = {};
+ for (const [key, entry] of Object.entries(secretMap)) {
+ const sanitizedKey = sanitizeEnvVarName(key);
+ if (sanitizedKey.length > 0) {
+ sanitized[sanitizedKey] = entry;
+ }
+ }
+ return sanitized;
+};
+
const toDirectoryPrefix = (path: string): string => {
if (!path) return "";
if (path.endsWith("/")) return path;
return `${path}/`;
};
+const buildFileMountPrefix = (basePath: string): string => {
+ return `/mnt/workspace/${toDirectoryPrefix(basePath)}`;
+};
+
+const buildFileMountPath = (basePath: string): string => {
+ return `/mnt/workspace/${basePath}`;
+};
+
+const isDirectChild = (elementId: string, prefix: string): boolean => {
+ if (!elementId.startsWith(prefix)) return false;
+ const relativePath = elementId.slice(prefix.length);
+ return relativePath.length > 0 && !relativePath.includes("/");
+};
+
+const getRelativeKey = (elementId: string, prefix: string): string => {
+ return elementId.slice(prefix.length);
+};
+
const secretMapToEnvFileContent = (secretMap: TSecretMap): string => {
const flat: Record<string, string> = {};
for (const [key, { value }] of Object.entries(secretMap)) {
@@ -124,94 +161,177 @@ const envFileContentToSecretMap = (content: string): TSecretMap => {
return secretMap;
};
+type TSpaceliftConnection = {
+ instanceUrl: string;
+ jwt: string;
+ contextId: string;
+};
+
+const syncSecretPerFile = async (
+ { instanceUrl, jwt, contextId }: TSpaceliftConnection,
+ basePath: string,
+ secretMap: TSecretMap,
+ writeOnly: boolean,
+ disableSecretDeletion?: boolean
+) => {
+ const prefix = buildFileMountPrefix(basePath);
+
+ for (const [key, { value }] of Object.entries(secretMap)) {
+ const fileId = `${prefix}${key}`;
+ const encoded = Buffer.from(value).toString("base64");
+
+ try {
+ await addContextConfigElement(instanceUrl, jwt, contextId, fileId, encoded, writeOnly, "FILE_MOUNT");
+ } catch (error) {
+ throw new SecretSyncError({ error, secretKey: key });
+ }
+ }
+
+ if (!disableSecretDeletion) {
+ const existingElements = await getContextConfigElements(instanceUrl, jwt, contextId);
+
+ for (const element of existingElements) {
+ if (element.type !== "FILE_MOUNT" || !isDirectChild(element.id, prefix)) {
+ // eslint-disable-next-line no-continue
+ continue;
+ }
+
+ const key = getRelativeKey(element.id, prefix);
+ if (!(key in secretMap)) {
+ try {
+ await deleteContextConfigElement(instanceUrl, jwt, contextId, element.id);
+ } catch (error) {
+ throw new SecretSyncError({ error, secretKey: key });
+ }
+ }
+ }
+ }
+};
+
+const syncDotEnvFile = async (
+ { instanceUrl, jwt, contextId }: TSpaceliftConnection,
+ basePath: string,
+ secretMap: TSecretMap,
+ writeOnly: boolean,
+ disableSecretDeletion?: boolean
+) => {
+ const filePath = buildFileMountPath(basePath);
+ const hasSecrets = Object.keys(secretMap).length > 0;
+
+ if (hasSecrets) {
+ const envContent = secretMapToEnvFileContent(secretMap);
+ const encoded = Buffer.from(envContent).toString("base64");
+ await addContextConfigElement(instanceUrl, jwt, contextId, filePath, encoded, writeOnly, "FILE_MOUNT");
+ } else if (!disableSecretDeletion) {
+ await deleteContextConfigElement(instanceUrl, jwt, contextId, filePath);
+ }
+};
+
+const getSecretsPerFile = (existingElements: TSpaceliftConfigElement[], basePath: string): TSecretMap => {
+ const prefix = buildFileMountPrefix(basePath);
+ const secretMap: TSecretMap = {};
+
+ for (const element of existingElements) {
+ if (element.type === "FILE_MOUNT" && !element.writeOnly && isDirectChild(element.id, prefix)) {
+ const secretKey = getRelativeKey(element.id, prefix);
+ secretMap[secretKey] = { value: Buffer.from(element.value, "base64").toString("utf-8") };
+ }
+ }
+
+ return secretMap;
+};
+
+const getSecretsDotEnvFile = (existingElements: TSpaceliftConfigElement[], basePath: string): TSecretMap => {
+ const filePath = buildFileMountPath(basePath);
+ const fileElement = existingElements.find((e) => e.id === filePath && e.type === "FILE_MOUNT");
+
+ if (!fileElement || fileElement.writeOnly) return {};
+
+ const decoded = Buffer.from(fileElement.value, "base64").toString("utf-8");
+ return envFileContentToSecretMap(decoded);
+};
+
+const removeSecretsPerFile = async (
+ { instanceUrl, jwt, contextId }: TSpaceliftConnection,
+ existingElements: TSpaceliftConfigElement[],
+ basePath: string,
+ secretMap: TSecretMap
+) => {
+ const prefix = buildFileMountPrefix(basePath);
+
+ for (const element of existingElements) {
+ if (element.type === "FILE_MOUNT" && isDirectChild(element.id, prefix)) {
+ const secretKey = getRelativeKey(element.id, prefix);
+ if (secretKey in secretMap) {
+ try {
+ await deleteContextConfigElement(instanceUrl, jwt, contextId, element.id);
+ } catch (error) {
+ throw new SecretSyncError({ error, secretKey });
+ }
+ }
+ }
+ }
+};
+
+const removeDotEnvFile = async (
+ { instanceUrl, jwt, contextId }: TSpaceliftConnection,
+ existingElements: TSpaceliftConfigElement[],
+ basePath: string
+) => {
+ const filePath = buildFileMountPath(basePath);
+ const fileElement = existingElements.find((e) => e.id === filePath && e.type === "FILE_MOUNT");
+
+ if (fileElement) {
+ try {
+ await deleteContextConfigElement(instanceUrl, jwt, contextId, filePath);
+ } catch (error) {
+ throw new SecretSyncError({ error, secretKey: filePath });
+ }
+ }
+};
+
export const SpaceliftSyncFns = {
syncSecrets: async (secretSync: TSpaceliftSyncWithCredentials, secretMap: TSecretMap): Promise<void> => {
const instanceUrl = removeTrailingSlash(secretSync.connection.credentials.apiUrl);
const { apiKeyId, apiKeySecret } = secretSync.connection.credentials;
const { contextId, configType, mountPath, fileMountFormat } = secretSync.destinationConfig;
const writeOnly = secretSync.syncOptions?.writeOnly ?? false;
+ const disableSecretDeletion = secretSync.syncOptions.disableSecretDeletion;
const jwt = await authenticateSpacelift(instanceUrl, apiKeyId, apiKeySecret);
+ const connection: TSpaceliftConnection = { instanceUrl, jwt, contextId };
if (configType === SpaceliftConfigType.FileMount) {
const basePath = mountPath ?? "";
if (fileMountFormat === SpaceliftFileMountFormat.SecretPerFile) {
- const existingElements = await getContextConfigElements(instanceUrl, jwt, contextId);
- const prefix = toDirectoryPrefix(basePath);
- const existingFileMounts = existingElements.filter(
- (e) => e.type === "FILE_MOUNT" && (prefix ? e.id.startsWith(prefix) : !e.id.includes("/"))
- );
-
- for (const [key, { value }] of Object.entries(secretMap)) {
- const fileId = `${prefix}${key}`;
- const encoded = Buffer.from(value).toString("base64");
-
- try {
- await addContextConfigElement(instanceUrl, jwt, contextId, fileId, encoded, writeOnly, "FILE_MOUNT");
- } catch (error) {
- throw new SecretSyncError({ error, secretKey: key });
- }
- }
-
- if (!secretSync.syncOptions.disableSecretDeletion) {
- for (const element of existingFileMounts) {
- const secretKey = element.id.slice(prefix.length);
- if (
- matchesSchema(secretKey, secretSync.environment?.slug || "", secretSync.syncOptions.keySchema) &&
- !(secretKey in secretMap)
- ) {
- try {
- await deleteContextConfigElement(instanceUrl, jwt, contextId, element.id);
- } catch (error) {
- throw new SecretSyncError({ error, secretKey });
- }
- }
- }
- }
-
- return;
- }
-
- const filePath = basePath;
- const hasSecrets = Object.keys(secretMap).length > 0;
-
- if (hasSecrets) {
- const envContent = secretMapToEnvFileContent(secretMap);
- const encoded = Buffer.from(envContent).toString("base64");
- await addContextConfigElement(instanceUrl, jwt, contextId, filePath, encoded, writeOnly, "FILE_MOUNT");
- } else if (!secretSync.syncOptions.disableSecretDeletion) {
- await deleteContextConfigElement(instanceUrl, jwt, contextId, filePath);
+ await syncSecretPerFile(connection, basePath, secretMap, writeOnly, disableSecretDeletion);
+ } else {
+ await syncDotEnvFile(connection, basePath, secretMap, writeOnly, disableSecretDeletion);
}
return;
}
- const existingElements = await getContextConfigElements(instanceUrl, jwt, contextId);
- const existingSecrets = existingElements.filter((e) => e.type === "ENVIRONMENT_VARIABLE");
-
- const existingByKey = new Map(existingSecrets.map((e) => [e.id, e]));
-
- for (const key of Object.keys(secretMap)) {
- const existing = existingByKey.get(key);
- if (existing && !existing.writeOnly && existing?.value === secretMap[key].value) {
- // eslint-disable-next-line no-continue
- continue;
- }
+ const sanitizedSecretMap = sanitizeSecretMapForEnvVars(secretMap);
+ for (const key of Object.keys(sanitizedSecretMap)) {
try {
- await addContextConfigElement(instanceUrl, jwt, contextId, key, secretMap[key].value, writeOnly);
+ await addContextConfigElement(instanceUrl, jwt, contextId, key, sanitizedSecretMap[key].value, writeOnly);
} catch (error) {
throw new SecretSyncError({ error, secretKey: key });
}
}
- if (secretSync.syncOptions.disableSecretDeletion) return;
+ if (disableSecretDeletion) return;
+
+ const existingElements = await getContextConfigElements(instanceUrl, jwt, contextId);
+ const existingSecrets = existingElements.filter((e) => e.type === "ENVIRONMENT_VARIABLE");
for (const element of existingSecrets) {
if (
matchesSchema(element.id, secretSync.environment?.slug || "", secretSync.syncOptions.keySchema) &&
- !(element.id in secretMap)
+ !(element.id in sanitizedSecretMap)
) {
try {
await deleteContextConfigElement(instanceUrl, jwt, contextId, element.id);
@@ -234,28 +354,10 @@ export const SpaceliftSyncFns = {
const basePath = mountPath ?? "";
if (fileMountFormat === SpaceliftFileMountFormat.SecretPerFile) {
- const prefix = toDirectoryPrefix(basePath);
- const secretMap: TSecretMap = {};
-
- for (const element of existingElements) {
- if (element.type === "FILE_MOUNT" && !element.writeOnly) {
- const matches = prefix ? element.id.startsWith(prefix) : !element.id.includes("/");
- if (matches) {
- const secretKey = element.id.slice(prefix.length);
- secretMap[secretKey] = { value: Buffer.from(element.value, "base64").toString("utf-8") };
- }
- }
- }
-
- return secretMap;
+ return getSecretsPerFile(existingElements, basePath);
}
- const fileElement = existingElements.find((e) => e.id === basePath && e.type === "FILE_MOUNT");
-
- if (!fileElement || fileElement.writeOnly) return {};
-
- const decoded = Buffer.from(fileElement.value, "base64").toString("utf-8");
- return envFileContentToSecretMap(decoded);
+ return getSecretsDotEnvFile(existingElements, basePath);
}
const secretMap: TSecretMap = {};
@@ -276,38 +378,15 @@ export const SpaceliftSyncFns = {
const jwt = await authenticateSpacelift(instanceUrl, apiKeyId, apiKeySecret);
const existingElements = await getContextConfigElements(instanceUrl, jwt, contextId);
+ const connection: TSpaceliftConnection = { instanceUrl, jwt, contextId };
if (configType === SpaceliftConfigType.FileMount) {
const basePath = mountPath ?? "";
if (fileMountFormat === SpaceliftFileMountFormat.SecretPerFile) {
- const prefix = basePath.endsWith("/") ? basePath : `${basePath}/`;
-
- for (const element of existingElements) {
- const matches = prefix ? element.id.startsWith(prefix) : !element.id.includes("/");
- if (element.type === "FILE_MOUNT" && matches) {
- const secretKey = element.id.slice(prefix.length);
- if (secretKey in secretMap) {
- try {
- await deleteContextConfigElement(instanceUrl, jwt, contextId, element.id);
- } catch (error) {
- throw new SecretSyncError({ error, secretKey });
- }
- }
- }
- }
-
- return;
- }
-
- const fileElement = existingElements.find((e) => e.id === basePath && e.type === "FILE_MOUNT");
-
- if (fileElement) {
- try {
- await deleteContextConfigElement(instanceUrl, jwt, contextId, basePath);
- } catch (error) {
- throw new SecretSyncError({ error, secretKey: basePath });
- }
+ await removeSecretsPerFile(connection, existingElements, basePath, secretMap);
+ } else {
+ await removeDotEnvFile(connection, existingElements, basePath);
}
return;