Skip to content

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

add secret import

Matheus Nogueira9bd5a146a5b9
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 860ada0240..93d087b798 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -1422,6 +1422,7 @@ export const SECRET_IMPORTS = {
isReplication:
"When true, secrets from the source will be automatically sent to the destination. If approval policies exist at the destination, the secrets will be sent as approval requests instead of being applied immediately.",
import: {
+ projectId: "The ID of the project to import from.",
environment: "The slug of the environment to import from.",
path: "The path to import from."
}
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index ce665c557b..fca2383c44 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1978,6 +1978,7 @@ export const registerRoutes = async (
const secretImportService = secretImportServiceFactory({
licenseService,
projectBotService,
+ projectGrantDAL,
projectEnvDAL,
folderDAL,
permissionService,
diff --git a/backend/src/server/routes/v1/project-grant-router.ts b/backend/src/server/routes/v1/project-grant-router.ts
index d9a8187221..c89eabc690 100644
--- a/backend/src/server/routes/v1/project-grant-router.ts
+++ b/backend/src/server/routes/v1/project-grant-router.ts
@@ -40,6 +40,39 @@ export const registerProjectGrantRouter = async (server: FastifyZodProvider) =>
}
});
+ server.route({
+ method: "GET",
+ url: "/received",
+ config: { rateLimit: readLimit },
+ schema: {
+ querystring: z.object({
+ targetProjectId: z.string()
+ }),
+ response: {
+ 200: z.object({
+ grants: ProjectFolderGrantsSchema.extend({
+ folderName: z.string(),
+ environmentName: z.string(),
+ environmentSlug: z.string(),
+ sourceProjectName: z.string(),
+ secretCount: z.number()
+ }).array()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ const grants = await server.services.projectGrant.listGrantsForTargetProject({
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ targetProjectId: req.query.targetProjectId
+ });
+ return { grants };
+ }
+ });
+
server.route({
method: "POST",
url: "/",
diff --git a/backend/src/server/routes/v2/secret-import-router.ts b/backend/src/server/routes/v2/secret-import-router.ts
index 22a353bbc4..d956f0e0f5 100644
--- a/backend/src/server/routes/v2/secret-import-router.ts
+++ b/backend/src/server/routes/v2/secret-import-router.ts
@@ -34,6 +34,7 @@ export const registerSecretImportRouter = async (server: FastifyZodProvider) =>
environment: z.string().trim().describe(SECRET_IMPORTS.CREATE.environment),
path: z.string().trim().default("/").transform(removeTrailingSlash).describe(SECRET_IMPORTS.CREATE.path),
import: z.object({
+ sourceProjectId: z.string().trim().optional().describe(SECRET_IMPORTS.CREATE.import.projectId),
environment: z.string().trim().describe(SECRET_IMPORTS.CREATE.import.environment),
path: z.string().trim().transform(removeTrailingSlash).describe(SECRET_IMPORTS.CREATE.import.path)
}),
diff --git a/backend/src/services/project-grant/project-grant-dal.ts b/backend/src/services/project-grant/project-grant-dal.ts
index 89c3756753..b35bb276b5 100644
--- a/backend/src/services/project-grant/project-grant-dal.ts
+++ b/backend/src/services/project-grant/project-grant-dal.ts
@@ -39,5 +39,35 @@ export const projectGrantDALFactory = (db: TDbClient) => {
})[];
};
- return { ...orm, listBySourceProject };
+ const listByTargetProject = async (targetProjectId: string, tx?: Knex) => {
+ const rows = await (tx || db.replicaNode())(TableName.ProjectFolderGrant)
+ .where(`${TableName.ProjectFolderGrant}.targetProjectId`, targetProjectId)
+ .join(TableName.SecretFolder, `${TableName.ProjectFolderGrant}.sourceFolderId`, `${TableName.SecretFolder}.id`)
+ .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)
+ .join(
+ `${TableName.Project} as sourceProject`,
+ `${TableName.ProjectFolderGrant}.sourceProjectId`,
+ `sourceProject.id`
+ )
+ .select(
+ `${TableName.ProjectFolderGrant}.*`,
+ `${TableName.SecretFolder}.name as folderName`,
+ `${TableName.Environment}.name as environmentName`,
+ `${TableName.Environment}.slug as environmentSlug`,
+ `sourceProject.name as sourceProjectName`,
+ db.raw(
+ `(SELECT COUNT(*)::integer FROM "${TableName.SecretV2}" WHERE "folderId" = "${TableName.ProjectFolderGrant}"."sourceFolderId" AND "type" = 'shared') as "secretCount"`
+ )
+ );
+
+ return rows as unknown[] as (TProjectFolderGrants & {
+ folderName: string;
+ environmentName: string;
+ environmentSlug: string;
+ sourceProjectName: string;
+ secretCount: number;
+ })[];
+ };
+
+ return { ...orm, listBySourceProject, listByTargetProject };
};
diff --git a/backend/src/services/project-grant/project-grant-service.ts b/backend/src/services/project-grant/project-grant-service.ts
index faf6b759f6..69900c0958 100644
--- a/backend/src/services/project-grant/project-grant-service.ts
+++ b/backend/src/services/project-grant/project-grant-service.ts
@@ -11,7 +11,12 @@ import { TProjectDALFactory } from "@app/services/project/project-dal";
import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";
import { TProjectGrantDALFactory } from "./project-grant-dal";
-import { TCreateProjectGrantDTO, TDeleteProjectGrantDTO, TListProjectGrantsDTO } from "./project-grant-types";
+import {
+ TCreateProjectGrantDTO,
+ TDeleteProjectGrantDTO,
+ TListProjectGrantsDTO,
+ TListProjectGrantsForTargetDTO
+} from "./project-grant-types";
export type TProjectGrantServiceFactory = ReturnType<typeof projectGrantServiceFactory>;
@@ -130,5 +135,24 @@ export const projectGrantServiceFactory = ({
return projectGrantDAL.listBySourceProject(sourceProjectId);
};
- return { createGrant, deleteGrant, listGrantsByProject };
+ const listGrantsForTargetProject = async ({
+ actorId,
+ actor,
+ actorAuthMethod,
+ actorOrgId,
+ targetProjectId
+ }: TListProjectGrantsForTargetDTO) => {
+ await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId,
+ projectId: targetProjectId,
+ actionProjectType: ActionProjectType.SecretManager
+ });
+
+ return projectGrantDAL.listByTargetProject(targetProjectId);
+ };
+
+ return { createGrant, deleteGrant, listGrantsByProject, listGrantsForTargetProject };
};
diff --git a/backend/src/services/project-grant/project-grant-types.ts b/backend/src/services/project-grant/project-grant-types.ts
index 35be5f1d24..780092a831 100644
--- a/backend/src/services/project-grant/project-grant-types.ts
+++ b/backend/src/services/project-grant/project-grant-types.ts
@@ -22,3 +22,7 @@ export type TDeleteProjectGrantDTO = TBaseActor & {
export type TListProjectGrantsDTO = TBaseActor & {
sourceProjectId: string;
};
+
+export type TListProjectGrantsForTargetDTO = TBaseActor & {
+ targetProjectId: string;
+};
diff --git a/backend/src/services/secret-import/secret-import-dal.ts b/backend/src/services/secret-import/secret-import-dal.ts
index cec142bb7e..c58345e095 100644
--- a/backend/src/services/secret-import/secret-import-dal.ts
+++ b/backend/src/services/secret-import/secret-import-dal.ts
@@ -96,7 +96,8 @@ export const secretImportDALFactory = (db: TDbClient) => {
db.ref("*").withSchema(TableName.SecretImport) as unknown as keyof TSecretImports,
db.ref("slug").withSchema(TableName.Environment),
db.ref("name").withSchema(TableName.Environment),
- db.ref("id").withSchema(TableName.Environment).as("envId")
+ db.ref("id").withSchema(TableName.Environment).as("envId"),
+ db.ref("projectId").withSchema(TableName.Environment).as("envProjectId")
)
.orderBy("position", "asc");
@@ -106,9 +107,9 @@ export const secretImportDALFactory = (db: TDbClient) => {
const docs = await query;
- return docs.map(({ envId, slug, name, ...el }) => ({
+ return docs.map(({ envId, envProjectId, slug, name, ...el }) => ({
...el,
- importEnv: { id: envId, slug, name }
+ importEnv: { id: envId, slug, name, projectId: envProjectId }
}));
} catch (error) {
throw new DatabaseError({ error, name: "Find secret imports" });
@@ -125,7 +126,8 @@ export const secretImportDALFactory = (db: TDbClient) => {
db.ref("*").withSchema(TableName.SecretImport) as unknown as keyof TSecretImports,
db.ref("slug").withSchema(TableName.Environment),
db.ref("name").withSchema(TableName.Environment),
- db.ref("id").withSchema(TableName.Environment).as("envId")
+ db.ref("id").withSchema(TableName.Environment).as("envId"),
+ db.ref("projectId").withSchema(TableName.Environment).as("envProjectId")
)
.first();
@@ -133,11 +135,11 @@ export const secretImportDALFactory = (db: TDbClient) => {
return null;
}
- const { envId, slug, name, ...el } = doc;
+ const { envId, envProjectId, slug, name, ...el } = doc;
return {
...el,
- importEnv: { id: envId, slug, name }
+ importEnv: { id: envId, slug, name, projectId: envProjectId }
};
} catch (error) {
throw new DatabaseError({ error, name: "Find secret imports" });
@@ -154,12 +156,13 @@ export const secretImportDALFactory = (db: TDbClient) => {
db.ref("*").withSchema(TableName.SecretImport) as unknown as keyof TSecretImports,
db.ref("slug").withSchema(TableName.Environment),
db.ref("name").withSchema(TableName.Environment),
- db.ref("id").withSchema(TableName.Environment).as("envId")
+ db.ref("id").withSchema(TableName.Environment).as("envId"),
+ db.ref("projectId").withSchema(TableName.Environment).as("envProjectId")
);
- return docs.map(({ envId, slug, name, ...el }) => ({
+ return docs.map(({ envId, envProjectId, slug, name, ...el }) => ({
...el,
- importEnv: { id: envId, slug, name }
+ importEnv: { id: envId, slug, name, projectId: envProjectId }
}));
} catch (error) {
throw new DatabaseError({ error, name: "Find secret imports by ids" });
@@ -221,12 +224,13 @@ export const secretImportDALFactory = (db: TDbClient) => {
db.ref("*").withSchema(TableName.SecretImport) as unknown as keyof TSecretImports,
db.ref("slug").withSchema(TableName.Environment),
db.ref("name").withSchema(TableName.Environment),
- db.ref("id").withSchema(TableName.Environment).as("envId")
+ db.ref("id").withSchema(TableName.Environment).as("envId"),
+ db.ref("projectId").withSchema(TableName.Environment).as("envProjectId")
)
.orderBy("position", "asc");
- return docs.map(({ envId, slug, name, ...el }) => ({
+ return docs.map(({ envId, envProjectId, slug, name, ...el }) => ({
...el,
- importEnv: { id: envId, slug, name }
+ importEnv: { id: envId, slug, name, projectId: envProjectId }
}));
} catch (error) {
throw new DatabaseError({ error, name: "Find secret imports" });
diff --git a/backend/src/services/secret-import/secret-import-fns.ts b/backend/src/services/secret-import/secret-import-fns.ts
index e58e29682b..fe54cc0146 100644
--- a/backend/src/services/secret-import/secret-import-fns.ts
+++ b/backend/src/services/secret-import/secret-import-fns.ts
@@ -4,6 +4,7 @@ import { SecretType, TSecretImports, TSecrets, TSecretsV2 } from "@app/db/schema
import { groupBy, unique } from "@app/lib/fn";
import { ResourceMetadataWithEncryptionDTO } from "../resource-metadata/resource-metadata-schema";
+import { TProjectGrantDALFactory } from "../project-grant/project-grant-dal";
import { TSecretDALFactory } from "../secret/secret-dal";
import { INFISICAL_SECRET_VALUE_HIDDEN_MASK } from "../secret/secret-fns";
import { PersonalOverridesBehavior, SecretsOrderBy } from "../secret/secret-types";
@@ -35,6 +36,7 @@ type TSecretImportSecretsV2 = {
id: string;
folderId: string | undefined;
importFolderId: string;
+ crossProjectImport: boolean;
secrets: (TSecretsV2 & {
secretTags: {
slug: string;
@@ -241,10 +243,13 @@ export const fnSecretsV2FromImports = async ({
hasSecretAccess,
viewSecretValue,
userId,
- personalOverridesBehavior
+ personalOverridesBehavior,
+ projectId,
+ projectGrantDAL,
+ getProjectDecryptor
}: {
secretImports: (Omit<TSecretImports, "importEnv"> & {
- importEnv: { id: string; slug: string; name: string };
+ importEnv: { id: string; slug: string; name: string; projectId?: string };
})[];
folderDAL: Pick<TSecretFolderDALFactory, "findByManySecretPath">;
viewSecretValue: boolean;
@@ -261,8 +266,13 @@ export const fnSecretsV2FromImports = async ({
hasSecretAccess: (environment: string, secretPath: string, secretName: string, secretTagSlugs: string[]) => boolean;
userId?: string;
personalOverridesBehavior?: PersonalOverridesBehavior;
+ projectId?: string;
+ projectGrantDAL?: Pick<TProjectGrantDALFactory, "find">;
+ getProjectDecryptor?: (sourceProjectId: string) => Promise<(value?: Buffer | null) => string>;
}) => {
const cyclicDetector = new Set();
+ // Cache decryptors per source project to avoid redundant KMS calls across loop iterations
+ const projectDecryptors = new Map<string, (value?: Buffer | null) => string>();
const stack: {
secretImports: typeof rootSecretImports;
depth: number;
@@ -361,14 +371,64 @@ export const fnSecretsV2FromImports = async ({
processedBatchImports.forEach(({ importPath, importEnv }) => {
cyclicDetector.add(getImportUniqKey(importEnv.slug, importPath));
});
+
+ // Batch-check ProjectGrants for cross-project imports in this batch.
+ // Reserved (replication) imports are excluded: their secrets are already
+ // stored locally and encrypted with the target project's key.
+ const grantedFolderIds = new Set<string>();
+ if (projectId && projectGrantDAL) {
+ const crossProjectItems: { sourceFolderId: string; sourceProjectId: string }[] = [];
+ for (const { importPath, importEnv, isReserved } of processedBatchImports) {
+ if (!isReserved && importEnv.projectId && importEnv.projectId !== projectId) {
+ const sourceFolder = importedFolderGroupBySourceImport[`${importEnv.id}-${importPath}`]?.[0];
+ if (sourceFolder?.id) {
+ crossProjectItems.push({ sourceFolderId: sourceFolder.id, sourceProjectId: importEnv.projectId });
+ }
+ }
+ }
+
+ if (crossProjectItems.length > 0) {
+ const grants = await projectGrantDAL.find({
+ $in: { sourceFolderId: crossProjectItems.map((c) => c.sourceFolderId) },
+ targetProjectId: projectId
+ });
+ grants.forEach((g) => grantedFolderIds.add(g.sourceFolderId));
+
+ if (getProjectDecryptor) {
+ const projectIdsNeeded = new Set(
+ crossProjectItems.filter((c) => grantedFolderIds.has(c.sourceFolderId)).map((c) => c.sourceProjectId)
+ );
+ for (const sourceProjectId of projectIdsNeeded) {
+ if (!projectDecryptors.has(sourceProjectId)) {
+ projectDecryptors.set(sourceProjectId, await getProjectDecryptor(sourceProjectId));
+ }
+ }
+ }
+ }
+ }
+
// now we need to check recursively deeper imports made inside other imports
// we go level wise meaning we take all imports of a tree level and then go deeper ones level by level
const deeperImports = await secretImportDAL.findByFolderIds(importedFolderIds);
const deeperImportsGroupByFolderId = groupBy(deeperImports, (i) => i.folderId);
const isFirstIteration = !processedImports.length;
- processedBatchImports.forEach(({ importPath, importEnv, id, folderId }, i) => {
+ processedBatchImports.forEach(({ importPath, importEnv, id, folderId, isReserved }, i) => {
const sourceImportFolder = importedFolderGroupBySourceImport[`${importEnv.id}-${importPath}`]?.[0];
+
+ const isCrossProject = !isReserved && Boolean(projectId && importEnv.projectId && importEnv.projectId !== projectId);
+
+ // Skip cross-project imports that have no corresponding ProjectGrant
+ if (isCrossProject && !grantedFolderIds.has(sourceImportFolder?.id || "")) {
+ return;
+ }
+
+ // For cross-project imports, use the source project's decryptor when available
+ const activeDecryptor =
+ isCrossProject && importEnv.projectId && projectDecryptors.has(importEnv.projectId)
+ ? projectDecryptors.get(importEnv.projectId)!
+ : decryptor;
+
const secretsWithDuplicate = (importedSecretsGroupByFolderId?.[importedFolders?.[i]?.id as string] || [])
.filter((item) =>
hasSecretAccess(
@@ -383,13 +443,13 @@ export const fnSecretsV2FromImports = async ({
secretKey: item.key,
secretMetadata: item.secretMetadata.map((metadata) => ({
key: metadata.key,
- value: metadata.encryptedValue ? decryptor(metadata.encryptedValue) : metadata.value || "",
+ value: metadata.encryptedValue ? activeDecryptor(metadata.encryptedValue) : metadata.value || "",
isEncrypted: Boolean(metadata.encryptedValue)
})),
- secretValue: viewSecretValue ? decryptor(item.encryptedValue) : INFISICAL_SECRET_VALUE_HIDDEN_MASK,
+ secretValue: viewSecretValue ? activeDecryptor(item.encryptedValue) : INFISICAL_SECRET_VALUE_HIDDEN_MASK,
secretValueHidden: !viewSecretValue,
secretTags: item.tags,
- secretComment: decryptor(item.encryptedComment),
+ secretComment: activeDecryptor(item.encryptedComment),
environment: importEnv.slug,
workspace: "", // This field should not be used, it's only here to keep the older Python SDK versions backwards compatible with the new Postgres backend.
_id: item.id // The old Python SDK depends on the _id field being returned. We return this to keep the older Python SDK versions backwards compatible with the new Postgres backend.
@@ -411,7 +471,8 @@ export const fnSecretsV2FromImports = async ({
folderId: importedFolders?.[i]?.id,
id,
importFolderId: folderId,
- secrets: secretsWithDuplicate
+ secrets: secretsWithDuplicate,
+ crossProjectImport: isCrossProject
});
} else {
parentImportedSecrets.push(...secretsWithDuplicate);
diff --git a/backend/src/services/secret-import/secret-import-service.ts b/backend/src/services/secret-import/secret-import-service.ts
index 21cea2a7bc..28811faa20 100644
--- a/backend/src/services/secret-import/secret-import-service.ts
+++ b/backend/src/services/secret-import/secret-import-service.ts
@@ -16,7 +16,7 @@ import {
} from "@app/ee/services/permission/project-permission";
import { ProjectEvents } from "@app/ee/services/project-events/project-events-types";
import { getReplicationFolderName } from "@app/ee/services/secret-replication/secret-replication-service";
-import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { TKmsServiceFactory } from "../kms/kms-service";
import { KmsDataKey } from "../kms/kms-types";
@@ -29,6 +29,7 @@ import { TSecretQueueFactory } from "../secret/secret-queue";
import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";
import { TSecretV2BridgeDALFactory } from "../secret-v2-bridge/secret-v2-bridge-dal";
import { recursivelyGetSecretPaths } from "../secret-v2-bridge/secret-v2-bridge-fns";
+import { TProjectGrantDALFactory } from "../project-grant/project-grant-dal";
import { TSecretImportDALFactory } from "./secret-import-dal";
import { fnSecretsFromImports, fnSecretsV2FromImports } from "./secret-import-fns";
import {
@@ -49,6 +50,7 @@ type TSecretImportServiceFactoryDep = {
projectBotService: Pick<TProjectBotServiceFactory, "getBotKey">;
projectDAL: Pick<TProjectDALFactory, "checkProjectUpgradeStatus">;
projectEnvDAL: TProjectEnvDALFactory;
+ projectGrantDAL: Pick<TProjectGrantDALFactory, "findOne">;
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
secretQueueService: Pick<TSecretQueueFactory, "syncSecrets" | "replicateSecrets">;
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
@@ -62,6 +64,7 @@ export type TSecretImportServiceFactory = ReturnType<typeof secretImportServiceF
export const secretImportServiceFactory = ({
secretImportDAL,
projectEnvDAL,
+ projectGrantDAL,
permissionService,
folderDAL,
projectDAL,
@@ -98,11 +101,30 @@ export const secretImportServiceFactory = ({
subject(ProjectPermissionSub.SecretImports, { environment, secretPath })
);
- // check if user has permission to import from target path
- throwIfMissingSecretReadValueOrDescribePermission(permission, ProjectPermissionSecretActions.DescribeSecret, {
- environment: data.environment,
- secretPath: data.path
- });
+ const sourceProjectId = data.sourceProjectId ?? projectId;
+ const isCrossProjectImport = sourceProjectId !== projectId;
+
+ if (isCrossProjectImport) {
+ const importFolder = await folderDAL.findBySecretPath(sourceProjectId, data.environment, data.path);
+ if (!importFolder) {
+ throw new NotFoundError({
+ message: `Folder with path '${data.path}' in environment '${data.environment}' not found in source project`
+ });
+ }
+
+ const grant = await projectGrantDAL.findOne({ sourceFolderId: importFolder.id, targetProjectId: projectId });
+ if (!grant) {
+ throw new ForbiddenRequestError({
+ message: "No project grant found allowing this cross-project import"
+ });
+ }
+ } else {
+ // check if user has permission to import from target path
+ throwIfMissingSecretReadValueOrDescribePermission(permission, ProjectPermissionSecretActions.DescribeSecret, {
+ environment: data.environment,
+ secretPath: data.path
+ });
+ }
if (isReplication) {
const plan = await licenseService.getPlan(actorOrgId);
@@ -121,18 +143,18 @@ export const secretImportServiceFactory = ({
message: `Folder with path '${secretPath}' in environment with slug '${environment}' not found`
});
- const [importEnv] = await projectEnvDAL.findBySlugs(projectId, [data.environment]);
+ const [importEnv] = await projectEnvDAL.findBySlugs(sourceProjectId, [data.environment]);
if (!importEnv) {
throw new NotFoundError({
- error: `Imported environment with slug '${data.environment}' in project with ID '${projectId}' not found`
+ error: `Imported environment with slug '${data.environment}' in project with ID '${sourceProjectId}' not found`
});
}
- if (environment === data.environment && secretPath === data.path) {
+ if (!isCrossProjectImport && environment === data.environment && secretPath === data.path) {
throw new BadRequestError({ message: "Cyclic import not allowed" });
}
- const sourceFolder = await folderDAL.findBySecretPath(projectId, data.environment, data.path);
+ const sourceFolder = await folderDAL.findBySecretPath(sourceProjectId, data.environment, data.path);
if (sourceFolder) {
const existingImport = await secretImportDAL.findOne({
folderId: sourceFolder.id,
@@ -181,6 +203,7 @@ export const secretImportServiceFactory = ({
actor
});
} else {
+ // TODO: check if I need to change anything here.
await secretQueueService.syncSecrets({
secretPath,
orgId: actorOrgId,
@@ -791,7 +814,16 @@ export const secretImportServiceFactory = ({
secretPath: expandSecretPath,
secretName: expandSecretKey,
secretTags: expandSecretTags
- })
+ }),
+ projectId,
+ projectGrantDAL,
+ getProjectDecryptor: async (sourceProjectId: string) => {
+ const { decryptor: sourceDecryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId: sourceProjectId
+ });
+ return (value) => (value ? sourceDecryptor({ cipherTextBlob: value }).toString() : "");
+ }
});
return importedSecrets;
diff --git a/backend/src/services/secret-import/secret-import-types.ts b/backend/src/services/secret-import/secret-import-types.ts
index 41ddbc9e24..4280edabb4 100644
--- a/backend/src/services/secret-import/secret-import-types.ts
+++ b/backend/src/services/secret-import/secret-import-types.ts
@@ -6,6 +6,7 @@ export type TCreateSecretImportDTO = {
data: {
environment: string;
path: string;
+ sourceProjectId?: string
};
isReplication?: boolean;
} & TProjectPermission;
diff --git a/frontend/src/hooks/api/projectGrants/index.ts b/frontend/src/hooks/api/projectGrants/index.ts
index ba09afd469..d24ba35eac 100644
--- a/frontend/src/hooks/api/projectGrants/index.ts
+++ b/frontend/src/hooks/api/projectGrants/index.ts
@@ -1,3 +1,3 @@
export { useCreateProjectGrant, useDeleteProjectGrant } from "./mutations";
-export { useListProjectGrants } from "./queries";
-export type { TCreateProjectGrantDTO, TDeleteProjectGrantDTO, TProjectGrant } from "./types";
+export { useListProjectGrants, useListProjectGrantsReceived } from "./queries";
+export type { TCreateProjectGrantDTO, TDeleteProjectGrantDTO, TProjectGrant, TProjectGrantReceived } from "./types";
diff --git a/frontend/src/hooks/api/projectGrants/queries.tsx b/frontend/src/hooks/api/projectGrants/queries.tsx
index e8f3d8a93e..54a856cceb 100644
--- a/frontend/src/hooks/api/projectGrants/queries.tsx
+++ b/frontend/src/hooks/api/projectGrants/queries.tsx
@@ -2,10 +2,11 @@ import { useQuery } from "@tanstack/react-query";
import { apiRequest } from "@app/config/request";
-import { TProjectGrant } from "./types";
+import { TProjectGrant, TProjectGrantReceived } from "./types";
export const projectGrantKeys = {
- listByProject: (sourceProjectId: string) => [{ sourceProjectId }, "project-grants"] as const
+ listByProject: (sourceProjectId: string) => [{ sourceProjectId }, "project-grants"] as const,
+ listReceived: (targetProjectId: string) => [{ targetProjectId }, "project-grants-received"] as const
};
export const useListProjectGrants = (sourceProjectId: string) =>
@@ -19,3 +20,18 @@ export const useListProjectGrants = (sourceProjectId: string) =>
},
enabled: Boolean(sourceProjectId)
});
+
+export const useListProjectGrantsReceived = (targetProjectId: string) =>
+ useQuery({
+ queryKey: projectGrantKeys.listReceived(targetProjectId),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{ grants: TProjectGrantReceived[] }>(
+ "/api/v1/project-grants/received",
+ {
+ params: { targetProjectId }
+ }
+ );
+ return data.grants;
+ },
+ enabled: Boolean(targetProjectId)
+ });
diff --git a/frontend/src/hooks/api/projectGrants/types.ts b/frontend/src/hooks/api/projectGrants/types.ts
index c5196f4794..10f39cb692 100644
--- a/frontend/src/hooks/api/projectGrants/types.ts
+++ b/frontend/src/hooks/api/projectGrants/types.ts
@@ -12,6 +12,20 @@ export type TProjectGrant = {
secretCount: number;
};
+export type TProjectGrantReceived = {
+ id: string;
+ sourceProjectId: string;
+ sourceFolderId: string;
+ targetProjectId: string;
+ createdAt: string;
+ updatedAt: string;
+ folderName: string;
+ environmentName: string;
+ environmentSlug: string;
+ sourceProjectName: string;
+ secretCount: number;
+};
+
export type TCreateProjectGrantDTO = {
sourceProjectId: string;
environment: string;
diff --git a/frontend/src/hooks/api/secretImports/types.ts b/frontend/src/hooks/api/secretImports/types.ts
index d17641398b..8f3c33b385 100644
--- a/frontend/src/hooks/api/secretImports/types.ts
+++ b/frontend/src/hooks/api/secretImports/types.ts
@@ -60,6 +60,7 @@ export type TCreateSecretImportDTO = {
environment: string;
path?: string;
import: {
+ sourceProjectId?: string;
environment: string;
path: string;
};
diff --git a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateSecretImportForm.tsx b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateSecretImportForm.tsx
index 36bb6b2911..67d38fcaf5 100644
--- a/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateSecretImportForm.tsx
+++ b/frontend/src/pages/secret-manager/SecretDashboardPage/components/ActionBar/CreateSecretImportForm.tsx
@@ -1,21 +1,38 @@
+import { useMemo, useState } from "react";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { AxiosError } from "axios";
+import { FileInput, Key, Share2 } from "lucide-react";
import { z } from "zod";
import { createNotification } from "@app/components/notifications";
+import { SecretPathInput } from "@app/components/v3";
import {
Button,
+ Card,
+ CardDescription,
+ CardTitle,
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ Field,
+ FieldContent,
+ FieldDescription,
+ FieldError,
+ FieldLabel,
FilterableSelect,
- FormControl,
- Modal,
- ModalContent,
Select,
- SelectItem
-} from "@app/components/v2";
-import { SecretPathInput } from "@app/components/v2/SecretPathInput";
-import { useProject, useSubscription } from "@app/context";
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue
+} from "@app/components/v3";
+import { useOrganization, useProject, useSubscription } from "@app/context";
import { useCreateSecretImport } from "@app/hooks/api";
+import { useListProjectGrantsReceived } from "@app/hooks/api/projectGrants";
const typeSchema = z.object({
environment: z.object({ name: z.string(), slug: z.string() }),
@@ -30,11 +47,12 @@ const typeSchema = z.object({
type TFormSchema = z.infer<typeof typeSchema>;
+type ImportSource = "this-project" | "another-project";
+
type Props = {
environment: string;
projectId: string;
secretPath?: string;
- // modal props
isOpen?: boolean;
onClose: () => void;
onTogglePopUp: (isOpen: boolean) => void;
@@ -55,14 +73,90 @@ export const CreateSecretImportForm = ({
control,
reset,
watch,
- formState: { isSubmitting }
+ formState: { isSubmitting, errors }
} = useForm<TFormSchema>({ resolver: zodResolver(typeSchema) });
+
const { currentProject } = useProject();
+ const { currentOrg } = useOrganization();
const environments = currentProject?.environments || [];
const selectedEnvironment = watch("environment");
const { subscription } = useSubscription();
- const { mutateAsync: createSecretImport } = useCreateSecretImport();
+ const { mutateAsync: createSecretImport, isPending: isCreatingImport } = useCreateSecretImport();
+
+ const { data: receivedGrants = [] } = useListProjectGrantsReceived(
+ currentOrg?.allowCrossProjectSecretSharing ? projectId : ""
+ );
+
+ const showSourceStep = receivedGrants.length > 0;
+
+ const [step, setStep] = useState<1 | 2>(1);
+ const [importSource, setImportSource] = useState<ImportSource | null>(null);
+
+ const [selectedSourceProjectId, setSelectedSourceProjectId] = useState<string | null>(null);
+ const [selectedEnvironmentSlug, setSelectedEnvironmentSlug] = useState<string | null>(null);
+ const [selectedFolderName, setSelectedFolderName] = useState<string | null>(null);
+
+ const uniqueSourceProjects = useMemo(() => {
+ const seen = new Set<string>();
+ return receivedGrants.filter((g) => {
+ if (seen.has(g.sourceProjectId)) return false;
+ seen.add(g.sourceProjectId);
+ return true;
+ });
+ }, [receivedGrants]);
+
+ const grantsForSelectedProject = useMemo(
+ () => receivedGrants.filter((g) => g.sourceProjectId === selectedSourceProjectId),
+ [receivedGrants, selectedSourceProjectId]
+ );
+
+ const uniqueEnvironmentsForProject = useMemo(() => {
+ const seen = new Set<string>();
+ return grantsForSelectedProject.filter((g) => {
+ if (seen.has(g.environmentSlug)) return false;
+ seen.add(g.environmentSlug);
+ return true;
+ });
+ }, [grantsForSelectedProject]);
+
+ const grantsForSelectedEnv = useMemo(
+ () => grantsForSelectedProject.filter((g) => g.environmentSlug === selectedEnvironmentSlug),
+ [grantsForSelectedProject, selectedEnvironmentSlug]
+ );
+
+ const selectedGrant = useMemo(
+ () => grantsForSelectedEnv.find((g) => g.folderName === selectedFolderName) ?? null,
+ [grantsForSelectedEnv, selectedFolderName]
+ );
+
+ const handleClose = () => {
+ reset();
+ setStep(1);
+ setImportSource(null);
+ setSelectedSourceProjectId(null);
+ setSelectedEnvironmentSlug(null);
+ setSelectedFolderName(null);
+ onClose();
+ };
+
+ const handleToggle = (open: boolean) => {
+ if (!open) handleClose();
+ else onTogglePopUp(open);
+ };
+
+ const handleSourceSelect = (source: ImportSource) => {
+ setImportSource(source);
+ setStep(2);
+ };
+
+ const handleBack = () => {
+ setStep(1);
+ setImportSource(null);
+ setSelectedSourceProjectId(null);
+ setSelectedEnvironmentSlug(null);
+ setSelectedFolderName(null);
+ };
const handleFormSubmit = async ({
environment: importedEnv,
@@ -85,13 +179,10 @@ export const CreateSecretImportForm = ({
path: importedSecPath
}
});
- onClose();
- reset();
+ handleClose();
createNotification({
type: "success",
- text: `Successfully linked. ${
- isReplication ? "Please refresh the dashboard to view changes" : ""
- }`
+ text: `Successfully linked. ${isReplication ? "Please refresh the dashboard to view changes" : ""}`
});
} catch (err) {
console.error(err);
@@ -105,86 +196,303 @@ export const CreateSecretImportForm = ({
}
};
- return (
- <Modal isOpen={isOpen} onOpenChange={onTogglePopUp}>
- <ModalContent
- bodyClassName="overflow-visible"
- title="Add Secret Import"
- subTitle="To inherit secrets from another environment or folder"
- >
- <form onSubmit={handleSubmit(handleFormSubmit)}>
- <Controller
- control={control}
- name="environment"
- render={({ field: { onChange, value }, fieldState: { error } }) => (
- <FormControl label="Environment" errorText={error?.message} isError={Boolean(error)}>
+ const effectiveStep = showSourceStep ? step : 2;
+ const effectiveImportSource: ImportSource = showSourceStep
+ ? (importSource ?? "this-project")
+ : "this-project";
+
+ const renderStep1 = () => (
+ <>
+ <DialogDescription>
+ Choose where to bring secrets in from. Imports stay in sync with their source.
+ </DialogDescription>
+ <div className="grid grid-cols-2 gap-4">
+ <button
+ type="button"
+ onClick={() => handleSourceSelect("this-project")}
+ className="block w-full text-left"
+ >
+ <Card className="gap-3 transition-colors hover:bg-mineshaft-700">
+ <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-blue-900/40">
+ <FileInput className="size-5 text-blue-400" />
+ </div>
+ <div>
+ <CardTitle className="text-base">This Project</CardTitle>
+ <CardDescription className="mt-1">
+ Inherit secrets from another environment or folder within{" "}
+ {currentProject?.name ?? "this project"}.
+ </CardDescription>
+ </div>
+ </Card>
+ </button>
+
+ <button
+ type="button"
+ onClick={() => handleSourceSelect("another-project")}
+ className="block w-full text-left"
+ >
+ <Card className="gap-3 transition-colors hover:bg-mineshaft-700">
+ <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-yellow-900/40">
+ <Share2 className="size-5 text-yellow-400" />
+ </div>
+ <div>
+ <CardTitle className="text-base">Another Project</CardTitle>
+ <CardDescription className="mt-1">
+ Import secrets that a different project has shared with this one.
+ </CardDescription>
+ </div>
+ </Card>
+ </button>
+ </div>
+ </>
+ );
+
+ const renderThisProjectForm = () => (
+ <form onSubmit={handleSubmit(handleFormSubmit)} className="space-y-4">
+ <Controller
+ control={control}
+ name="environment"
+ render={({ field }) => {
+ const selectedItem = environments.find((e) => e.slug === field.value?.slug);
+ return (
+ <Field>
+ <FieldLabel>Environment</FieldLabel>
+ <FieldContent>
<FilterableSelect
options={environments}
getOptionLabel={(option) => option.name}
getOptionValue={(option) => option.slug}
placeholder="Select environment..."
- value={value}
- onChange={onChange}
+ value={selectedItem || null}
+ onChange={(newValue) => {
+ const single = Array.isArray(newValue) ? newValue[0] : newValue;
+ field.onChange(single || null);
+ }}
/>
- </FormControl>
- )}
- />
- <Controller
- control={control}
- name="secretPath"
- defaultValue="/"
- render={({ field, fieldState: { error } }) => (
- <FormControl label="Secret Path" isError={Boolean(error)} errorText={error?.message}>
- <SecretPathInput {...field} environment={selectedEnvironment?.slug} />
- </FormControl>
- )}
- />
- <Controller
- name="isReplication"
- control={control}
- defaultValue={false}
- render={({ field: { value, onChange }, fieldState: { error } }) => (
- <FormControl
- isError={Boolean(error?.message)}
- errorText={error?.message}
- helperText={
- value
- ? "Secrets from the source will be automatically sent to the destination. If approval policies exist at the destination, the secrets will be sent as approval requests instead of being applied immediately."
- : "Secrets from the source location will be imported to the selected destination immediately, ignoring any approval policies at the destination."
- }
+ </FieldContent>
+ <FieldError>{errors.environment?.message}</FieldError>
+ </Field>
+ );
+ }}
+ />
+ <Controller
+ control={control}
+ name="secretPath"
+ defaultValue="/"
+ render={({ field }) => (
+ <Field>
+ <FieldLabel>Secret Path</FieldLabel>
+ <FieldContent>
+ <SecretPathInput {...field} environment={selectedEnvironment?.slug} />
+ </FieldContent>
+ <FieldError>{errors.secretPath?.message}</FieldError>
+ </Field>
+ )}
+ />
+ <Controller
+ name="isReplication"
+ control={control}
+ defaultValue={false}
+ render={({ field: { value, onChange } }) => (
+ <Field>
+ <FieldContent>
+ <Select
+ value={value ? "true" : "false"}
+ onValueChange={(val) => onChange(val === "true")}
>
- <Select
- value={value ? "true" : "false"}
- onValueChange={(val) => onChange(val === "true")}
- className="w-full border border-mineshaft-500"
- >
+ <SelectTrigger className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
<SelectItem value="false">Ignore secret approval policies</SelectItem>
<SelectItem value="true">Respect secret approval policies</SelectItem>
- </Select>
- </FormControl>
- )}
- />
- <div className="mt-7 flex items-center">
- <Button
- isDisabled={isSubmitting}
- isLoading={isSubmitting}
- key="layout-create-project-submit"
- className="mr-4"
- type="submit"
- >
- Create Link
- </Button>
- <Button
- key="layout-cancel-create-project"
- onClick={onClose}
- variant="plain"
- colorSchema="secondary"
- >
- Cancel
- </Button>
+ </SelectContent>
+ </Select>
+ </FieldContent>
+ <FieldDescription>
+ {value
+ ? "Secrets from the source will be automatically sent to the destination. If approval policies exist at the destination, the secrets will be sent as approval requests instead of being applied immediately."
+ : "Secrets from the source location will be imported to the selected destination immediately, ignoring any approval policies at the destination."}
+ </FieldDescription>
+ </Field>
+ )}
+ />
+ <DialogFooter>
+ <Button type="button" variant="ghost" onClick={showSourceStep ? handleBack : handleClose}>
+ {showSourceStep ? "Back" : "Cancel"}
+ </Button>
+ <Button type="submit" variant="project" isPending={isSubmitting} isDisabled={isSubmitting}>
+ Create Import
+ </Button>
+ </DialogFooter>
+ </form>
+ );
+
+ const renderAnotherProjectForm = () => {
+ const sourceProjectOptions = uniqueSourceProjects.map((g) => ({
+ label: g.sourceProjectName,
+ value: g.sourceProjectId
+ }));
+
+ const environmentOptions = uniqueEnvironmentsForProject.map((g) => ({
+ label: g.environmentName,
+ value: g.environmentSlug
+ }));
+
+ const folderOptions = grantsForSelectedEnv.map((g) => ({
+ label: g.folderName === "root" ? "/" : `/${g.folderName}`,
+ value: g.folderName
+ }));
+
+ return (
+ <div className="space-y-4">
+ <DialogDescription>
+ Other projects have made these secret sets available to{" "}
+ {currentProject?.name ?? "this project"}. Select one to import.
+ </DialogDescription>
+
+ <Field>
+ <FieldLabel>Project</FieldLabel>
+ <FieldContent>
+ <FilterableSelect
+ options={sourceProjectOptions}
+ getOptionLabel={(o) => o.label}
+ getOptionValue={(o) => o.value}
+ placeholder="Select project..."
+ value={
+ selectedSourceProjectId
+ ? (sourceProjectOptions.find((o) => o.value === selectedSourceProjectId) ?? null)
+ : null
+ }
+ onChange={(newValue) => {
+ const single = Array.isArray(newValue) ? newValue[0] : newValue;
+ setSelectedSourceProjectId(single && "value" in single ? single.value : null);
+ setSelectedEnvironmentSlug(null);
+ setSelectedFolderName(null);
+ }}
+ />
+ </FieldContent>
+ </Field>
+
+ <Field>
+ <FieldLabel>Environment</FieldLabel>
+ <FieldContent>
+ <FilterableSelect
+ options={environmentOptions}
+ getOptionLabel={(o) => o.label}
+ getOptionValue={(o) => o.value}
+ placeholder="Select environment..."
+ isDisabled={!selectedSourceProjectId}
+ value={
+ selectedEnvironmentSlug
+ ? (environmentOptions.find((o) => o.value === selectedEnvironmentSlug) ?? null)
+ : null
+ }
+ onChange={(newValue) => {
+ const single = Array.isArray(newValue) ? newValue[0] : newValue;
+ setSelectedEnvironmentSlug(single && "value" in single ? single.value : null);
+ setSelectedFolderName(null);
+ }}
+ />
+ </FieldContent>
+ </Field>
+
+ <Field>
+ <FieldLabel>Folder path</FieldLabel>
+ <FieldContent>
+ <FilterableSelect
+ options={folderOptions}
+ getOptionLabel={(o) => o.label}
+ getOptionValue={(o) => o.value}
+ placeholder="Select folder..."
+ isDisabled={!selectedEnvironmentSlug}
+ value={
+ selectedFolderName
+ ? (folderOptions.find((o) => o.value === selectedFolderName) ?? null)
+ : null
+ }
+ onChange={(newValue) => {
+ const single = Array.isArray(newValue) ? newValue[0] : newValue;
+ setSelectedFolderName(single && "value" in single ? single.value : null);
+ }}
+ />
+ </FieldContent>
+ </Field>
+
+ {selectedGrant && (
+ <div className="flex items-center gap-3 rounded-lg border border-border bg-popover p-4">
+ <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md bg-mineshaft-700">
+ <Key className="size-4 text-yellow-400" />
+ </div>
+ <div>
+ <p className="text-sm font-medium text-foreground">
+ <span className="text-yellow-400">{selectedGrant.secretCount} secrets</span> will be
+ imported
+ </p>
+ <p className="mt-0.5 text-xs text-accent">
+ {selectedGrant.sourceProjectName} &middot; {selectedGrant.environmentName} &middot;{" "}
+ {selectedGrant.folderName === "root" ? "/" : `/${selectedGrant.folderName}`}
+ </p>
+ </div>
</div>
- </form>
- </ModalContent>
- </Modal>
+ )}
+
+ <DialogFooter>
+ <Button type="button" variant="ghost" onClick={handleBack}>
+ Back
+ </Button>
+ <Button
+ type="button"
+ variant="project"
+ isDisabled={!selectedGrant}
+ isLoading={isCreatingImport}
+ onClick={async () => {
+ if (!selectedGrant) return;
+ try {
+ await createSecretImport({
+ environment,
+ projectId,
+ path: secretPath,
+ import: {
+ sourceProjectId: selectedGrant.sourceProjectId,
+ environment: selectedGrant.environmentSlug,
+ path:
+ selectedGrant.folderName === "root" ? "/" : `/${selectedGrant.folderName}`
+ }
+ });
+ handleClose();
+ createNotification({ type: "success", text: "Successfully linked secrets." });
+ } catch (err) {
+ console.error(err);
+ const axiosError = err as AxiosError;
+ if (axiosError?.response?.status === 401) {
+ createNotification({
+ text: "You do not have access to the selected environment/path",
+ type: "error"
+ });
+ }
+ }
+ }}
+ >
+ Create Import
+ </Button>
+ </DialogFooter>
+ </div>
+ );
+ };
+
+ return (
+ <Dialog open={isOpen} onOpenChange={handleToggle}>
+ <DialogContent className="max-w-lg overflow-visible">
+ <DialogHeader>
+ <DialogTitle>Add Secret Import</DialogTitle>
+ </DialogHeader>
+ {effectiveStep === 1 && renderStep1()}
+ {effectiveStep === 2 && effectiveImportSource === "this-project" && renderThisProjectForm()}
+ {effectiveStep === 2 &&
+ effectiveImportSource === "another-project" &&
+ renderAnotherProjectForm()}
+ </DialogContent>
+ </Dialog>
);
};