Skip to content

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

MVP preliminary idea for initial sync behavior

Tuan Dang43d40d747505
diff --cc backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts
index ef10db8048,9a91b745d9..c53136f137
--- a/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts
+++ b/backend/src/ee/services/secret-approval-request/secret-approval-request-service.ts
@@@ -17,6 -18,6 +18,8 @@@ import { TSecretVersionDALFactory } fro
import { TSecretBlindIndexDALFactory } from "@app/services/secret-blind-index/secret-blind-index-dal";
import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";
import { TSecretTagDALFactory } from "@app/services/secret-tag/secret-tag-dal";
++import { TSecretDALFactory } from "@app/services/secret/secret-dal";
++import { TSecretVersionTagDALFactory } from "@app/services/secret/secret-version-tag-dal";
import { TPermissionServiceFactory } from "../permission/permission-service";
import { ProjectPermissionActions, ProjectPermissionSub } from "../permission/project-permission";
@@@ -43,10 -44,11 +46,13 @@@ type TSecretApprovalRequestServiceFacto
secretApprovalRequestSecretDAL: TSecretApprovalRequestSecretDALFactory;
secretApprovalRequestReviewerDAL: TSecretApprovalRequestReviewerDALFactory;
folderDAL: Pick<TSecretFolderDALFactory, "findBySecretPath" | "findById" | "findSecretPathByFolderIds">;
-- secretTagDAL: Pick<TSecretTagDALFactory, "findManyTagsById">;
++ secretDAL: TSecretDALFactory;
++ secretTagDAL: Pick<TSecretTagDALFactory, "findManyTagsById" | "saveTagsToSecret">;
secretBlindIndexDAL: Pick<TSecretBlindIndexDALFactory, "findOne">;
snapshotService: Pick<TSecretSnapshotServiceFactory, "performSnapshot">;
-- secretVersionDAL: Pick<TSecretVersionDALFactory, "findLatestVersionMany">;
++ secretVersionDAL: Pick<TSecretVersionDALFactory, "findLatestVersionMany" | "insertMany">;
++ secretVersionTagDAL: Pick<TSecretVersionTagDALFactory, "insertMany">;
+ projectDAL: Pick<TProjectDALFactory, "checkProjectUpgradeStatus">;
secretService: Pick<
TSecretServiceFactory,
| "fnSecretBulkInsert"
@@@ -62,8 -64,8 +68,10 @@@ export type TSecretApprovalRequestServi
export const secretApprovalRequestServiceFactory = ({
secretApprovalRequestDAL,
++ secretDAL,
folderDAL,
secretTagDAL,
++ secretVersionTagDAL,
secretApprovalRequestReviewerDAL,
secretApprovalRequestSecretDAL,
secretBlindIndexDAL,
@@@ -332,7 -335,7 +341,11 @@@
tags: el?.tags.map(({ id }) => id),
version: 1,
type: SecretType.Shared
-- }))
++ })),
++ secretDAL,
++ secretVersionDAL,
++ secretTagDAL,
++ secretVersionTagDAL
})
: [];
const updatedSecrets = secretUpdationCommits.length
@@@ -450,7 -455,7 +465,8 @@@
inputSecrets: createdSecrets,
folderId,
isNew: true,
-- blindIndexCfg
++ blindIndexCfg,
++ secretDAL
});
commits.push(
@@@ -477,7 -482,7 +493,8 @@@
inputSecrets: updatedSecrets,
folderId,
isNew: false,
-- blindIndexCfg
++ blindIndexCfg,
++ secretDAL
});
// now find any secret that needs to update its name
@@@ -487,7 -492,7 +504,8 @@@
inputSecrets: nameUpdatedSecrets,
folderId,
isNew: true,
-- blindIndexCfg
++ blindIndexCfg,
++ secretDAL
});
const secsGroupedByBlindIndex = groupBy(secretsToBeUpdated, (el) => el.secretBlindIndex as string);
@@@ -526,7 -531,7 +544,8 @@@
inputSecrets: deletedSecrets,
folderId,
isNew: false,
-- blindIndexCfg
++ blindIndexCfg,
++ secretDAL
});
const secretsGroupedByBlindIndex = groupBy(secrets, (i) => {
if (!i.secretBlindIndex) throw new BadRequestError({ message: "Missing secret blind index" });
diff --cc backend/src/server/routes/index.ts
index 28f65ea998,7880f79e3b..caecf852c6
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@@ -355,7 -421,7 +421,11 @@@ export const registerRoutes = async
orgDAL,
projectMembershipDAL,
smtpService,
-- projectDAL
++ projectDAL,
++ secretVersionDAL,
++ secretBlindIndexDAL,
++ secretTagDAL,
++ secretVersionTagDAL,
});
const secretBlindIndexService = secretBlindIndexServiceFactory({
permissionService,
@@@ -378,6 -445,6 +449,7 @@@
const sarService = secretApprovalRequestServiceFactory({
permissionService,
folderDAL,
++ secretDAL,
secretTagDAL,
secretApprovalRequestSecretDAL: sarSecretDAL,
secretApprovalRequestReviewerDAL: sarReviewerDAL,
@@@ -386,6 -454,6 +459,7 @@@
secretApprovalRequestDAL,
secretService,
snapshotService,
++ secretVersionTagDAL,
secretQueueService
});
const secretRotationQueue = secretRotationQueueFactory({
diff --cc backend/src/server/routes/v1/integration-router.ts
index ab0ba36eb9,ec712a543a..b5d3b28d5b
--- a/backend/src/server/routes/v1/integration-router.ts
+++ b/backend/src/server/routes/v1/integration-router.ts
@@@ -30,6 -32,6 +32,7 @@@ export const registerIntegrationRouter
.object({
secretPrefix: z.string().optional(),
secretSuffix: z.string().optional(),
++ syncBehavior: z.string().optional(),
secretGCPLabel: z
.object({
labelName: z.string(),
diff --cc backend/src/services/integration-auth/integration-auth-service.ts
index 60f3d561c9,0b3f9b4c3f..aa23547475
--- a/backend/src/services/integration-auth/integration-auth-service.ts
+++ b/backend/src/services/integration-auth/integration-auth-service.ts
@@@ -43,6 -41,6 +43,7 @@@ import
import { getIntegrationOptions, Integrations, IntegrationUrls } from "./integration-list";
import { getTeams } from "./integration-team";
import { exchangeCode, exchangeRefresh } from "./integration-token";
++import { access } from "node:fs";
type TIntegrationAuthServiceFactoryDep = {
integrationAuthDAL: TIntegrationAuthDALFactory;
@@@ -578,37 -576,6 +579,38 @@@ export const integrationAuthServiceFact
return [];
};
+ const getHerokuPipelines = async ({ id, actor, actorId, actorOrgId }: TIntegrationAuthHerokuPipelinesDTO) => {
+ const integrationAuth = await integrationAuthDAL.findById(id);
+ if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" });
+
+ const { permission } = await permissionService.getProjectPermission(
+ actor,
+ actorId,
+ integrationAuth.projectId,
+ actorOrgId
+ );
+ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Integrations);
+ const botKey = await projectBotService.getBotKey(integrationAuth.projectId);
+ const { accessToken } = await getIntegrationAccessToken(integrationAuth, botKey);
++
+ const { data } = await request.get<THerokuPipelineCoupling[]>(
+ `${IntegrationUrls.HEROKU_API_URL}/pipeline-couplings`,
+ {
+ headers: {
+ Accept: "application/vnd.heroku+json; version=3",
+ Authorization: `Bearer ${accessToken}`,
+ "Accept-Encoding": "application/json"
+ }
+ }
+ );
-
++
+ return data.map(({ app: { id: appId }, stage, pipeline: { id: pipelineId, name } }) => ({
+ app: { appId },
+ stage,
+ pipeline: { pipelineId, name }
+ }));
+ };
+
const getRailwayEnvironments = async ({ id, actor, actorId, actorOrgId, appId }: TIntegrationAuthRailwayEnvDTO) => {
const integrationAuth = await integrationAuthDAL.findById(id);
if (!integrationAuth) throw new BadRequestError({ message: "Failed to find integration" });
diff --cc backend/src/services/integration-auth/integration-list.ts
index d3cabbcb56,d3cabbcb56..816d6f4093
--- a/backend/src/services/integration-auth/integration-list.ts
+++ b/backend/src/services/integration-auth/integration-list.ts
@@@ -37,6 -37,6 +37,12 @@@ export enum IntegrationType
OAUTH2 = "oauth2"
}
++export enum IntegrationSyncBehavior {
++ OVERWRITE_TARGET = "overwrite-target",
++ PREFER_TARGET = "prefer-target",
++ PREFER_SOURCE = "prefer-source"
++}
++
export enum IntegrationUrls {
// integration oauth endpoints
GCP_TOKEN_URL = "https://oauth2.googleapis.com/token",
diff --cc backend/src/services/integration-auth/integration-sync-secret.ts
index abb6a7b1ea,62a4dcfa71..7e613ceabf
--- a/backend/src/services/integration-auth/integration-sync-secret.ts
+++ b/backend/src/services/integration-auth/integration-sync-secret.ts
@@@ -20,11 -20,11 +20,20 @@@ import sodium from "libsodium-wrappers"
import isEqual from "lodash.isequal";
import { z } from "zod";
--import { TIntegrationAuths, TIntegrations } from "@app/db/schemas";
++import { TIntegrationAuths, TIntegrations, SecretType } from "@app/db/schemas";
import { request } from "@app/lib/config/request";
import { BadRequestError } from "@app/lib/errors";
--import { Integrations, IntegrationUrls } from "./integration-list";
++import { Integrations, IntegrationUrls, IntegrationSyncBehavior } from "./integration-list";
++import { TProjectDALFactory } from "@app/services/project/project-dal";
++import { TSecretDALFactory } from "@app/services/secret/secret-dal";
++import { TSecretBlindIndexDALFactory } from "@app/services/secret-blind-index/secret-blind-index-dal";
++import { TSecretTagDALFactory } from "@app/services/secret-tag/secret-tag-dal";
++import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";
++import { TSecretVersionDALFactory } from "@app/services/secret/secret-version-dal";
++import { TSecretVersionTagDALFactory } from "@app/services/secret/secret-version-tag-dal";
++
++import { createManySecretsRawHelper } from "../secret/secret-fns";
const getSecretKeyValuePair = (secrets: Record<string, { value: string | null; comment?: string } | null>) =>
Object.keys(secrets).reduce<Record<string, string | null | undefined>>((prev, key) => {
@@@ -600,16 -580,16 +589,40 @@@ const syncSecretsAWSSecretManager = asy
/**
* Sync/push [secrets] to Heroku app named [integration.app]
++ * server.services...
*/
const syncSecretsHeroku = async ({
++ projectDAL,
++ secretDAL,
++ secretVersionDAL,
++ secretBlindIndexDAL,
++ secretTagDAL,
++ secretVersionTagDAL,
++ folderDAL,
++ botKey, // TODO: consider getting botKey inside this fn
++ projectId,
++ environment,
++ secretPath,
integration,
secrets,
accessToken
}: {
++ projectDAL: TProjectDALFactory;
++ secretDAL: TSecretDALFactory;
++ secretVersionDAL: TSecretVersionDALFactory;
++ secretBlindIndexDAL: TSecretBlindIndexDALFactory;
++ secretTagDAL: TSecretTagDALFactory;
++ secretVersionTagDAL: TSecretVersionTagDALFactory;
++ folderDAL: TSecretFolderDALFactory;
++ botKey: string;
++ projectId: string;
++ environment: string;
++ secretPath: string;
integration: TIntegrations;
secrets: Record<string, { value: string; comment?: string } | null>;
accessToken: string;
}) => {
++
const herokuSecrets = (
await request.get(`${IntegrationUrls.HEROKU_API_URL}/apps/${integration.app}/config-vars`, {
headers: {
@@@ -619,13 -599,13 +632,63 @@@
}
})
).data;
++
++ let secretsToAdd: { [key: string]: string } = {};
++ let secretsToUpdate: { [key: string]: string } = {};
++
++ const metadata = z.record(z.any()).parse(integration.metadata);
Object.keys(herokuSecrets).forEach((key) => {
-- if (!(key in secrets)) {
-- secrets[key] = null;
++ switch (metadata.syncBehavior) {
++ case IntegrationSyncBehavior.OVERWRITE_TARGET: {
++ if (!(key in secrets)) secrets[key] = null;
++ break;
++ };
++ case IntegrationSyncBehavior.PREFER_TARGET: {
++ secrets[key] = herokuSecrets[key];
++ if (!(key in secrets)) {
++ secretsToAdd[key] = herokuSecrets[key];
++ } else {
++ if (secrets[key] !== herokuSecrets[key]) {
++ secretsToUpdate[key] = secrets[key]?.value as string;
++ }
++ }
++ break;
++ };
++ case IntegrationSyncBehavior.PREFER_SOURCE: {
++ if(!(key in secrets)) {
++ secrets[key] = herokuSecrets[key];
++ secretsToAdd[key] = herokuSecrets[key];
++ }
++ break;
++ };
++ default: {
++ if (!(key in secrets)) secrets[key] = null;
++ break;
++ };
}
});
++ await createManySecretsRawHelper({
++ botKey,
++ projectDAL,
++ secretDAL,
++ secretVersionDAL,
++ secretBlindIndexDAL,
++ secretTagDAL,
++ secretVersionTagDAL,
++ folderDAL,
++ projectId,
++ environment,
++ path: secretPath,
++ secrets: Object.keys(secretsToAdd).map((key) => ({
++ secretName: key,
++ secretValue: secretsToAdd[key],
++ type: SecretType.Shared,
++ secretComment: ""
++ }))
++ });
++
await request.patch(
`${IntegrationUrls.HEROKU_API_URL}/apps/${integration.app}/config-vars`,
getSecretKeyValuePair(secrets),
@@@ -2950,8 -2930,8 +3013,22 @@@ const syncSecretsHasuraCloud = async (
/**
* Sync/push [secrets] to [app] in integration named [integration]
++ *
++ * Do this in terms of DAL
++ *
*/
export const syncIntegrationSecrets = async ({
++ projectDAL,
++ secretDAL,
++ secretVersionDAL,
++ secretBlindIndexDAL,
++ secretTagDAL,
++ secretVersionTagDAL,
++ folderDAL,
++ botKey,
++ projectId,
++ environment,
++ secretPath,
integration,
integrationAuth,
secrets,
@@@ -2959,6 -2939,6 +3036,17 @@@
accessToken,
appendices
}: {
++ projectDAL: TProjectDALFactory;
++ secretDAL: TSecretDALFactory;
++ secretVersionDAL: TSecretVersionDALFactory;
++ secretBlindIndexDAL: TSecretBlindIndexDALFactory;
++ secretTagDAL: TSecretTagDALFactory;
++ secretVersionTagDAL: TSecretVersionTagDALFactory;
++ folderDAL: TSecretFolderDALFactory;
++ botKey: string;
++ projectId: string;
++ environment: string;
++ secretPath: string;
integration: TIntegrations;
integrationAuth: TIntegrationAuths;
secrets: Record<string, { value: string; comment?: string }>;
@@@ -2999,9 -2979,9 +3087,20 @@@
break;
case Integrations.HEROKU:
await syncSecretsHeroku({
++ projectDAL,
++ secretDAL,
++ secretVersionDAL,
++ secretBlindIndexDAL,
++ secretTagDAL,
++ secretVersionTagDAL,
++ folderDAL,
++ botKey,
++ projectId,
++ environment,
++ secretPath,
integration,
secrets,
-- accessToken
++ accessToken,
});
break;
case Integrations.VERCEL:
diff --cc backend/src/services/secret/secret-fns.ts
index 0f6caa2489,0f6caa2489..382e873109
--- a/backend/src/services/secret/secret-fns.ts
+++ b/backend/src/services/secret/secret-fns.ts
@@@ -1,12 -1,12 +1,31 @@@
/* eslint-disable no-await-in-loop */
import path from "path";
--import { SecretKeyEncoding, TSecretBlindIndexes, TSecrets } from "@app/db/schemas";
++import {
++ SecretKeyEncoding,
++ TSecretBlindIndexes,
++ TSecrets,
++ SecretEncryptionAlgo,
++ SecretType,
++ TableName
++} from "@app/db/schemas";
import { getConfig } from "@app/lib/config/env";
--import { buildSecretBlindIndexFromName, decryptSymmetric128BitHexKeyUTF8 } from "@app/lib/crypto";
++import {
++ buildSecretBlindIndexFromName,
++ encryptSymmetric128BitHexKeyUTF8,
++ decryptSymmetric128BitHexKeyUTF8
++} from "@app/lib/crypto";
import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";
import { TSecretDALFactory } from "./secret-dal";
++import {
++ TCreateManySecretsRawHelper,
++ TFnSecretBulkInsert,
++ TFnSecretBlindIndexCheck
++} from "./secret-types";
++
++import { groupBy, unique } from "@app/lib/fn";
++import { BadRequestError } from "@app/lib/errors";
export const generateSecretBlindIndexBySalt = async (secretName: string, secretBlindIndexDoc: TSecretBlindIndexes) => {
const appCfg = getConfig();
@@@ -228,3 -228,3 +247,201 @@@ export const decryptSecretRaw = (secret
user: secret.userId
};
};
++
++/**
++ * Checks and handles secrets using a blind index method.
++ * The function generates mappings between secret names and their blind indexes, validates user IDs for personal secrets, and retrieves secrets from the database based on their blind indexes.
++ * For new secrets (isNew = true), it ensures they don't already exist in the database.
++ * For existing secrets, it verifies their presence in the database.
++ * If discrepancies are found, errors are thrown. The function returns mappings and the fetched secrets.
++ */
++export const fnSecretBlindIndexCheck = async ({
++ inputSecrets,
++ folderId,
++ isNew,
++ userId,
++ blindIndexCfg,
++ secretDAL
++}: TFnSecretBlindIndexCheck) => {
++ const blindIndex2KeyName: Record<string, string> = {}; // used at audit log point
++ const keyName2BlindIndex = await Promise.all(
++ inputSecrets.map(({ secretName }) => generateSecretBlindIndexBySalt(secretName, blindIndexCfg))
++ ).then((blindIndexes) =>
++ blindIndexes.reduce<Record<string, string>>((prev, curr, i) => {
++ // eslint-disable-next-line
++ prev[inputSecrets[i].secretName] = curr;
++ blindIndex2KeyName[curr] = inputSecrets[i].secretName;
++ return prev;
++ }, {})
++ );
++
++ if (inputSecrets.some(({ type }) => type === SecretType.Personal) && !userId) {
++ throw new BadRequestError({ message: "Missing user id for personal secret" });
++ }
++
++ const secrets = await secretDAL.findByBlindIndexes(
++ folderId,
++ inputSecrets.map(({ secretName, type }) => ({
++ blindIndex: keyName2BlindIndex[secretName],
++ type: type || SecretType.Shared
++ })),
++ userId
++ );
++
++ if (isNew) {
++ if (secrets.length) throw new BadRequestError({ message: "Secret already exist" });
++ } else {
++ const secretKeysInDB = unique(secrets, (el) => el.secretBlindIndex as string).map(
++ (el) => blindIndex2KeyName[el.secretBlindIndex as string]
++ );
++ const hasUnknownSecretsProvided = secretKeysInDB.length !== inputSecrets.length;
++ if (hasUnknownSecretsProvided) {
++ const keysMissingInDB = Object.keys(keyName2BlindIndex).filter((key) => !secretKeysInDB.includes(key));
++ throw new BadRequestError({
++ message: `Secret not found: blind index ${keysMissingInDB.join(",")}`
++ });
++ }
++ }
++
++ return { blindIndex2KeyName, keyName2BlindIndex, secrets };
++};
++
++// these functions are special functions shared by a couple of resources
++// used by secret approval, rotation or anywhere in which secret needs to modified
++export const fnSecretBulkInsert = async ({ // TODO: Pick types here
++ folderId,
++ inputSecrets,
++ secretDAL,
++ secretVersionDAL,
++ secretTagDAL,
++ secretVersionTagDAL,
++ tx
++}: TFnSecretBulkInsert) => {
++ const newSecrets = await secretDAL.insertMany(
++ inputSecrets.map(({ tags, ...el }) => ({ ...el, folderId })),
++ tx
++ );
++ const newSecretGroupByBlindIndex = groupBy(newSecrets, (item) => item.secretBlindIndex as string);
++ const newSecretTags = inputSecrets.flatMap(({ tags: secretTags = [], secretBlindIndex }) =>
++ secretTags.map((tag) => ({
++ [`${TableName.SecretTag}Id` as const]: tag,
++ [`${TableName.Secret}Id` as const]: newSecretGroupByBlindIndex[secretBlindIndex as string][0].id
++ }))
++ );
++ const secretVersions = await secretVersionDAL.insertMany(
++ inputSecrets.map(({ tags, ...el }) => ({
++ ...el,
++ folderId,
++ secretId: newSecretGroupByBlindIndex[el.secretBlindIndex as string][0].id
++ })),
++ tx
++ );
++ if (newSecretTags.length) {
++ const secTags = await secretTagDAL.saveTagsToSecret(newSecretTags, tx);
++ const secVersionsGroupBySecId = groupBy(secretVersions, (i) => i.secretId);
++ const newSecretVersionTags = secTags.flatMap(({ secretsId, secret_tagsId }) => ({
++ [`${TableName.SecretVersion}Id` as const]: secVersionsGroupBySecId[secretsId][0].id,
++ [`${TableName.SecretTag}Id` as const]: secret_tagsId
++ }));
++ await secretVersionTagDAL.insertMany(newSecretVersionTags, tx);
++ }
++
++ return newSecrets.map((secret) => ({ ...secret, _id: secret.id }));
++};
++
++export const createManySecretsRawHelper = async ({ // TODO: place on top
++ projectId,
++ environment,
++ path,
++ secrets,
++ userId,
++ botKey, // TODO: consider getting botKey inside this fn
++ projectDAL,
++ secretDAL,
++ secretVersionDAL,
++ secretBlindIndexDAL,
++ secretTagDAL,
++ secretVersionTagDAL,
++ folderDAL
++}: TCreateManySecretsRawHelper) => {
++await projectDAL.checkProjectUpgradeStatus(projectId);
++
++const folder = await folderDAL.findBySecretPath(projectId, environment, path);
++if (!folder) throw new BadRequestError({ message: "Folder not found", name: "Create secret" });
++const folderId = folder.id;
++
++const blindIndexCfg = await secretBlindIndexDAL.findOne({ projectId });
++if (!blindIndexCfg) throw new BadRequestError({ message: "Blind index not found", name: "Update secret" });
++
++const inputSecrets = await Promise.all(
++ secrets.map(async (secret) => {
++ const secretKeyEncrypted = encryptSymmetric128BitHexKeyUTF8(secret.secretName, botKey);
++ const secretValueEncrypted = encryptSymmetric128BitHexKeyUTF8(secret.secretValue || "", botKey);
++ const secretCommentEncrypted = encryptSymmetric128BitHexKeyUTF8(secret.secretComment || "", botKey);
++
++ if (secret.type === SecretType.Personal) {
++ const sharedExist = await secretDAL.findOne({
++ secretBlindIndex: keyName2BlindIndex[secret.secretName],
++ folderId,
++ type: SecretType.Shared
++ });
++
++ if (!sharedExist)
++ throw new BadRequestError({
++ message: "Failed to create personal secret override for no corresponding shared secret"
++ });
++
++ if (!userId) throw new BadRequestError({ message: "Missing user id for personal secret" });
++ }
++
++ const tags = secret.tags ? await secretTagDAL.findManyTagsById(projectId, secret.tags) : [];
++ if ((secret.tags || []).length !== tags.length) throw new BadRequestError({ message: "Tag not found" });
++
++ return ({
++ type: secret.type,
++ userId: secret.type === SecretType.Personal ? userId : null,
++ secretName: secret.secretName,
++ secretKeyCiphertext: secretKeyEncrypted.ciphertext,
++ secretKeyIV: secretKeyEncrypted.iv,
++ secretKeyTag: secretKeyEncrypted.tag,
++ secretValueCiphertext: secretValueEncrypted.ciphertext,
++ secretValueIV: secretValueEncrypted.iv,
++ secretValueTag: secretValueEncrypted.tag,
++ secretCommentCiphertext: secretCommentEncrypted.ciphertext,
++ secretCommentIV: secretCommentEncrypted.iv,
++ secretCommentTag: secretCommentEncrypted.tag,
++ skipMultilineEncoding: secret.skipMultilineEncoding,
++ tags: secret.tags
++ });
++ })
++);
++
++ // insert operation
++ const { keyName2BlindIndex } = await fnSecretBlindIndexCheck({
++ inputSecrets,
++ folderId,
++ isNew: true,
++ blindIndexCfg,
++ secretDAL
++ });
++
++ const newSecrets = await secretDAL.transaction(async (tx) =>
++ fnSecretBulkInsert({
++ inputSecrets: inputSecrets.map(({ secretName, ...el }) => ({
++ ...el,
++ version: 0,
++ secretBlindIndex: keyName2BlindIndex[secretName],
++ algorithm: SecretEncryptionAlgo.AES_256_GCM,
++ keyEncoding: SecretKeyEncoding.UTF8
++ })),
++ folderId,
++ secretDAL,
++ secretVersionDAL,
++ secretTagDAL,
++ secretVersionTagDAL,
++ tx
++ })
++ );
++
++ return newSecrets;
++}
diff --cc backend/src/services/secret/secret-queue.ts
index b797b7caf6,b797b7caf6..2b5a692984
--- a/backend/src/services/secret/secret-queue.ts
+++ b/backend/src/services/secret/secret-queue.ts
@@@ -25,6 -25,6 +25,11 @@@ import { TSecretDALFactory } from "./se
import { interpolateSecrets } from "./secret-fns";
import { TCreateSecretReminderDTO, THandleReminderDTO, TRemoveSecretReminderDTO } from "./secret-types";
++import { TSecretBlindIndexDALFactory } from "@app/services/secret-blind-index/secret-blind-index-dal";
++import { TSecretTagDALFactory } from "@app/services/secret-tag/secret-tag-dal";
++import { TSecretVersionDALFactory } from "@app/services/secret/secret-version-dal";
++import { TSecretVersionTagDALFactory } from "@app/services/secret/secret-version-tag-dal";
++
export type TSecretQueueFactory = ReturnType<typeof secretQueueFactory>;
type TSecretQueueFactoryDep = {
@@@ -32,15 -32,15 +37,19 @@@
integrationDAL: Pick<TIntegrationDALFactory, "findByProjectIdV2">;
projectBotService: Pick<TProjectBotServiceFactory, "getBotKey">;
integrationAuthService: Pick<TIntegrationAuthServiceFactory, "getIntegrationAccessToken">;
-- folderDAL: Pick<TSecretFolderDALFactory, "findBySecretPath" | "findByManySecretPath">;
-- secretDAL: Pick<TSecretDALFactory, "findByFolderId" | "find">;
++ folderDAL: TSecretFolderDALFactory;
++ secretDAL: TSecretDALFactory;
secretImportDAL: Pick<TSecretImportDALFactory, "find">;
webhookDAL: Pick<TWebhookDALFactory, "findAllWebhooks" | "transaction" | "update" | "bulkUpdate">;
projectEnvDAL: Pick<TProjectEnvDALFactory, "findOne">;
-- projectDAL: Pick<TProjectDALFactory, "findById">;
++ projectDAL: TProjectDALFactory;
projectMembershipDAL: Pick<TProjectMembershipDALFactory, "findAllProjectMembers">;
smtpService: TSmtpService;
orgDAL: Pick<TOrgDALFactory, "findOrgByProjectId">;
++ secretVersionDAL: TSecretVersionDALFactory;
++ secretBlindIndexDAL: TSecretBlindIndexDALFactory;
++ secretTagDAL: TSecretTagDALFactory;
++ secretVersionTagDAL: TSecretVersionTagDALFactory;
};
export type TGetSecrets = {
@@@ -62,7 -62,7 +71,11 @@@ export const secretQueueFactory = (
orgDAL,
smtpService,
projectDAL,
-- projectMembershipDAL
++ projectMembershipDAL,
++ secretVersionDAL,
++ secretBlindIndexDAL,
++ secretTagDAL,
++ secretVersionTagDAL,
}: TSecretQueueFactoryDep) => {
const syncIntegrations = async (dto: TGetSecrets) => {
await queueService.queue(QueueName.IntegrationSync, QueueJobs.IntegrationSync, dto, {
@@@ -307,6 -307,6 +320,17 @@@
}
await syncIntegrationSecrets({
++ projectDAL,
++ secretDAL,
++ secretVersionDAL,
++ secretBlindIndexDAL,
++ secretTagDAL,
++ secretVersionTagDAL,
++ folderDAL,
++ botKey,
++ projectId,
++ environment,
++ secretPath,
integration,
integrationAuth,
secrets: Object.keys(suffixedSecrets).length !== 0 ? suffixedSecrets : secrets,
diff --cc backend/src/services/secret/secret-service.ts
index ff9dce9a8d,ecd13dae18..6b4aaf2d5a
--- a/backend/src/services/secret/secret-service.ts
+++ b/backend/src/services/secret/secret-service.ts
@@@ -18,19 -19,19 +19,22 @@@ import { TSecretImportDALFactory } fro
import { fnSecretsFromImports } from "../secret-import/secret-import-fns";
import { TSecretTagDALFactory } from "../secret-tag/secret-tag-dal";
import { TSecretDALFactory } from "./secret-dal";
--import { decryptSecretRaw, generateSecretBlindIndexBySalt } from "./secret-fns";
++import {
++ decryptSecretRaw,
++ fnSecretBlindIndexCheck,
++ fnSecretBulkInsert
++} from "./secret-fns";
import { TSecretQueueFactory } from "./secret-queue";
import {
++ TCreateManySecretsRawHelper,
TCreateBulkSecretDTO,
TCreateSecretDTO,
TCreateSecretRawDTO,
TDeleteBulkSecretDTO,
TDeleteSecretDTO,
TDeleteSecretRawDTO,
-- TFnSecretBlindIndexCheck,
TFnSecretBlindIndexCheckV2,
TFnSecretBulkDelete,
-- TFnSecretBulkInsert,
TFnSecretBulkUpdate,
TGetASecretDTO,
TGetASecretRawDTO,
@@@ -92,41 -95,41 +98,6 @@@ export const secretServiceFactory = (
return secretBlindIndex;
};
-- // these functions are special functions shared by a couple of resources
-- // used by secret approval, rotation or anywhere in which secret needs to modified
-- const fnSecretBulkInsert = async ({ folderId, inputSecrets, tx }: TFnSecretBulkInsert) => {
-- const newSecrets = await secretDAL.insertMany(
-- inputSecrets.map(({ tags, ...el }) => ({ ...el, folderId })),
-- tx
-- );
-- const newSecretGroupByBlindIndex = groupBy(newSecrets, (item) => item.secretBlindIndex as string);
-- const newSecretTags = inputSecrets.flatMap(({ tags: secretTags = [], secretBlindIndex }) =>
-- secretTags.map((tag) => ({
-- [`${TableName.SecretTag}Id` as const]: tag,
-- [`${TableName.Secret}Id` as const]: newSecretGroupByBlindIndex[secretBlindIndex as string][0].id
-- }))
-- );
-- const secretVersions = await secretVersionDAL.insertMany(
-- inputSecrets.map(({ tags, ...el }) => ({
-- ...el,
-- folderId,
-- secretId: newSecretGroupByBlindIndex[el.secretBlindIndex as string][0].id
-- })),
-- tx
-- );
-- if (newSecretTags.length) {
-- const secTags = await secretTagDAL.saveTagsToSecret(newSecretTags, tx);
-- const secVersionsGroupBySecId = groupBy(secretVersions, (i) => i.secretId);
-- const newSecretVersionTags = secTags.flatMap(({ secretsId, secret_tagsId }) => ({
-- [`${TableName.SecretVersion}Id` as const]: secVersionsGroupBySecId[secretsId][0].id,
-- [`${TableName.SecretTag}Id` as const]: secret_tagsId
-- }));
-- await secretVersionTagDAL.insertMany(newSecretVersionTags, tx);
-- }
--
-- return newSecrets.map((secret) => ({ ...secret, _id: secret.id }));
-- };
--
const fnSecretBulkUpdate = async ({ tx, inputSecrets, folderId, projectId }: TFnSecretBulkUpdate) => {
const newSecrets = await secretDAL.bulkUpdate(
inputSecrets.map(({ filter, data: { tags, ...data } }) => ({
@@@ -199,54 -202,63 +170,6 @@@
return deletedSecrets;
};
- // this is a utility function for secret modification
- // this will check given secret name blind index exist or not
- // if its a created secret set isNew to true
- // thus if these blindindex exist it will throw an error
- // vice versa when u need to check for updated secret
- // this will also return the blind index grouped by secretName
- /**
- * Checks and handles secrets using a blind index method.
- * The function generates mappings between secret names and their blind indexes, validates user IDs for personal secrets, and retrieves secrets from the database based on their blind indexes.
- * For new secrets (isNew = true), it ensures they don't already exist in the database.
- * For existing secrets, it verifies their presence in the database.
- * If discrepancies are found, errors are thrown. The function returns mappings and the fetched secrets.
- */
-- const fnSecretBlindIndexCheck = async ({
-- inputSecrets,
-- folderId,
-- isNew,
-- userId,
-- blindIndexCfg
-- }: TFnSecretBlindIndexCheck) => {
-- const blindIndex2KeyName: Record<string, string> = {}; // used at audit log point
-- const keyName2BlindIndex = await Promise.all(
-- inputSecrets.map(({ secretName }) => generateSecretBlindIndexBySalt(secretName, blindIndexCfg))
-- ).then((blindIndexes) =>
-- blindIndexes.reduce<Record<string, string>>((prev, curr, i) => {
-- // eslint-disable-next-line
-- prev[inputSecrets[i].secretName] = curr;
-- blindIndex2KeyName[curr] = inputSecrets[i].secretName;
-- return prev;
-- }, {})
-- );
--
-- if (inputSecrets.some(({ type }) => type === SecretType.Personal) && !userId) {
-- throw new BadRequestError({ message: "Missing user id for personal secret" });
-- }
--
-- const secrets = await secretDAL.findByBlindIndexes(
-- folderId,
-- inputSecrets.map(({ secretName, type }) => ({
-- blindIndex: keyName2BlindIndex[secretName],
-- type: type || SecretType.Shared
-- })),
-- userId
-- );
--
-- if (isNew) {
-- if (secrets.length) throw new BadRequestError({ message: "Secret already exist" });
- } else if (secrets.length !== inputSecrets.length)
- throw new BadRequestError({
- message: `Secret not found: blind index ${JSON.stringify(keyName2BlindIndex)}`
- });
- } else {
- const secretKeysInDB = unique(secrets, (el) => el.secretBlindIndex as string).map(
- (el) => blindIndex2KeyName[el.secretBlindIndex as string]
- );
- const hasUnknownSecretsProvided = secretKeysInDB.length !== inputSecrets.length;
- if (hasUnknownSecretsProvided) {
- const keysMissingInDB = Object.keys(keyName2BlindIndex).filter((key) => !secretKeysInDB.includes(key));
- throw new BadRequestError({
- message: `Secret not found: blind index ${keysMissingInDB.join(",")}`
- });
- }
- }
--
-- return { blindIndex2KeyName, keyName2BlindIndex, secrets };
-- };
--
// this is used when secret blind index already exist
// mainly for secret approval
const fnSecretBlindIndexCheckV2 = async ({ inputSecrets, folderId, userId }: TFnSecretBlindIndexCheckV2) => {
@@@ -297,7 -311,7 +222,8 @@@
folderId,
isNew: true,
userId: actorId,
-- blindIndexCfg
++ blindIndexCfg,
++ secretDAL
});
// if user creating personal check its shared also exist
@@@ -334,6 -348,6 +260,10 @@@
tags: inputSecret.tags
}
],
++ secretDAL,
++ secretVersionDAL,
++ secretTagDAL,
++ secretVersionTagDAL,
tx
})
);
@@@ -375,7 -395,7 +311,8 @@@
folderId,
isNew: false,
blindIndexCfg,
-- userId: actorId
++ userId: actorId,
++ secretDAL
});
if (inputSecret.newSecretName && inputSecret.type === SecretType.Personal) {
throw new BadRequestError({ message: "Personal secret cannot change the key name" });
@@@ -387,7 -407,7 +324,8 @@@
inputSecrets: [{ secretName: inputSecret.newSecretName }],
folderId,
isNew: true,
-- blindIndexCfg
++ blindIndexCfg,
++ secretDAL
});
newSecretNameBlindIndex = kN2NewBlindIndex[inputSecret.newSecretName];
}
@@@ -474,7 -496,7 +414,8 @@@
inputSecrets: [{ secretName: inputSecret.secretName }],
folderId,
isNew: false,
-- blindIndexCfg
++ blindIndexCfg,
++ secretDAL
});
const deletedSecret = await secretDAL.transaction(async (tx) =>
@@@ -661,7 -685,7 +604,8 @@@
inputSecrets,
folderId,
isNew: true,
-- blindIndexCfg
++ blindIndexCfg,
++ secretDAL
});
// get all tags
@@@ -680,6 -704,6 +624,10 @@@
keyEncoding: SecretKeyEncoding.UTF8
})),
folderId,
++ secretDAL,
++ secretVersionDAL,
++ secretTagDAL,
++ secretVersionTagDAL,
tx
})
);
@@@ -716,7 -742,7 +666,8 @@@
inputSecrets,
folderId,
isNew: false,
-- blindIndexCfg
++ blindIndexCfg,
++ secretDAL
});
// now find any secret that needs to update its name
@@@ -726,7 -752,7 +677,8 @@@
inputSecrets: nameUpdatedSecrets,
folderId,
isNew: true,
-- blindIndexCfg
++ blindIndexCfg,
++ secretDAL
});
// get all tags
@@@ -787,7 -815,7 +741,8 @@@
inputSecrets,
folderId,
isNew: false,
-- blindIndexCfg
++ blindIndexCfg,
++ secretDAL
});
const secretsDeleted = await secretDAL.transaction(async (tx) =>
@@@ -871,6 -899,6 +826,98 @@@
});
return decryptSecretRaw(secret, botKey);
};
++
++ const createManySecretsRawHelper = async ({ // TODO: place on top
++ projectId,
++ environment,
++ path,
++ secrets,
++ userId
++ }: TCreateManySecretsRawHelper) => {
++ const botKey = await projectBotService.getBotKey(projectId);
++ if (!botKey) throw new BadRequestError({ message: "Project bot not found", name: "bot_not_found_error" });
++
++ await projectDAL.checkProjectUpgradeStatus(projectId);
++
++ const folder = await folderDAL.findBySecretPath(projectId, environment, path);
++ if (!folder) throw new BadRequestError({ message: "Folder not found", name: "Create secret" });
++ const folderId = folder.id;
++
++ const blindIndexCfg = await secretBlindIndexDAL.findOne({ projectId });
++ if (!blindIndexCfg) throw new BadRequestError({ message: "Blind index not found", name: "Update secret" });
++
++ const inputSecrets = await Promise.all(
++ secrets.map(async (secret) => {
++ const secretKeyEncrypted = encryptSymmetric128BitHexKeyUTF8(secret.secretName, botKey);
++ const secretValueEncrypted = encryptSymmetric128BitHexKeyUTF8(secret.secretValue || "", botKey);
++ const secretCommentEncrypted = encryptSymmetric128BitHexKeyUTF8(secret.secretComment || "", botKey);
++
++ if (secret.type === SecretType.Personal) {
++ const sharedExist = await secretDAL.findOne({
++ secretBlindIndex: keyName2BlindIndex[secret.secretName],
++ folderId,
++ type: SecretType.Shared
++ });
++
++ if (!sharedExist)
++ throw new BadRequestError({
++ message: "Failed to create personal secret override for no corresponding shared secret"
++ });
++
++ if (!userId) throw new BadRequestError({ message: "Missing user id for personal secret" });
++ }
++
++ const tags = secret.tags ? await secretTagDAL.findManyTagsById(projectId, secret.tags) : [];
++ if ((secret.tags || []).length !== tags.length) throw new BadRequestError({ message: "Tag not found" });
++
++ return ({
++ type: secret.type,
++ userId: secret.type === SecretType.Personal ? userId : null,
++ secretName: secret.secretName,
++ secretKeyCiphertext: secretKeyEncrypted.ciphertext,
++ secretKeyIV: secretKeyEncrypted.iv,
++ secretKeyTag: secretKeyEncrypted.tag,
++ secretValueCiphertext: secretValueEncrypted.ciphertext,
++ secretValueIV: secretValueEncrypted.iv,
++ secretValueTag: secretValueEncrypted.tag,
++ secretCommentCiphertext: secretCommentEncrypted.ciphertext,
++ secretCommentIV: secretCommentEncrypted.iv,
++ secretCommentTag: secretCommentEncrypted.tag,
++ skipMultilineEncoding: secret.skipMultilineEncoding,
++ tags: secret.tags
++ });
++ })
++ );
++
++ // insert operation
++ const { keyName2BlindIndex } = await fnSecretBlindIndexCheck({
++ inputSecrets,
++ folderId,
++ isNew: true,
++ blindIndexCfg,
++ secretDAL
++ });
++
++ const newSecrets = await secretDAL.transaction(async (tx) =>
++ fnSecretBulkInsert({
++ inputSecrets: inputSecrets.map(({ secretName, ...el }) => ({
++ ...el,
++ version: 0,
++ secretBlindIndex: keyName2BlindIndex[secretName],
++ algorithm: SecretEncryptionAlgo.AES_256_GCM,
++ keyEncoding: SecretKeyEncoding.UTF8
++ })),
++ folderId,
++ secretDAL,
++ secretVersionDAL,
++ secretTagDAL,
++ secretVersionTagDAL,
++ tx
++ })
++ );
++
++ return newSecrets;
++ }
const createSecretRaw = async ({
secretName,
diff --cc backend/src/services/secret/secret-types.ts
index 50f678172c,50f678172c..6b0b205ed8
--- a/backend/src/services/secret/secret-types.ts
+++ b/backend/src/services/secret/secret-types.ts
@@@ -2,6 -2,6 +2,13 @@@ import { Knex } from "knex"
import { SecretType, TSecretBlindIndexes, TSecrets, TSecretsInsert, TSecretsUpdate } from "@app/db/schemas";
import { TProjectPermission } from "@app/lib/types";
++import { TProjectDALFactory } from "@app/services/project/project-dal";
++import { TSecretDALFactory } from "@app/services/secret/secret-dal";
++import { TSecretBlindIndexDALFactory } from "@app/services/secret-blind-index/secret-blind-index-dal";
++import { TSecretTagDALFactory } from "@app/services/secret-tag/secret-tag-dal";
++import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";
++import { TSecretVersionDALFactory } from "@app/services/secret/secret-version-dal";
++import { TSecretVersionTagDALFactory } from "@app/services/secret/secret-version-tag-dal";
type TPartialSecret = Pick<TSecrets, "id" | "secretReminderRepeatDays" | "secretReminderNote">;
@@@ -181,6 -181,6 +188,10 @@@ export type TFnSecretBulkInsert =
folderId: string;
tx?: Knex;
inputSecrets: Array<Omit<TSecretsInsert, "folderId"> & { tags?: string[] }>;
++ secretDAL: Pick<TSecretDALFactory, "insertMany">;
++ secretVersionDAL: Pick<TSecretVersionDALFactory, "insertMany">;
++ secretTagDAL: Pick<TSecretTagDALFactory, "saveTagsToSecret">;
++ secretVersionTagDAL: Pick<TSecretVersionTagDALFactory, "insertMany">;
};
export type TFnSecretBulkUpdate = {
@@@ -204,6 -204,6 +215,7 @@@ export type TFnSecretBlindIndexCheck =
blindIndexCfg: TSecretBlindIndexes;
inputSecrets: Array<{ secretName: string; type?: SecretType }>;
isNew: boolean;
++ secretDAL: Pick<TSecretDALFactory, "findByBlindIndexes">;
};
// when blind index is already present
@@@ -229,3 -229,3 +241,31 @@@ export type TRemoveSecretReminderDTO =
secretId: string;
repeatDays: number;
};
++
++// ---
++
++export type TCreateManySecretsRawHelper = {
++ projectId: string;
++ environment: string;
++ path: string;
++ secrets: {
++ secretName: string;
++ secretValue: string;
++ type: SecretType;
++ secretComment?: string;
++ skipMultilineEncoding?: boolean;
++ tags?: string[];
++ metadata?: {
++ source?: string;
++ }
++ }[];
++ userId?: string; // only relevant for personal secret(s)
++ botKey: string;
++ projectDAL: TProjectDALFactory;
++ secretDAL: TSecretDALFactory;
++ secretVersionDAL: TSecretVersionDALFactory;
++ secretBlindIndexDAL: TSecretBlindIndexDALFactory;
++ secretTagDAL: TSecretTagDALFactory;
++ secretVersionTagDAL: TSecretVersionTagDALFactory;
++ folderDAL: TSecretFolderDALFactory;
++}
diff --cc frontend/src/hooks/api/integrations/queries.tsx
index 70bee92c36,70bee92c36..5eb8d0d57b
--- a/frontend/src/hooks/api/integrations/queries.tsx
+++ b/frontend/src/hooks/api/integrations/queries.tsx
@@@ -61,6 -61,6 +61,7 @@@ export const useCreateIntegration = ()
metadata?: {
secretPrefix?: string;
secretSuffix?: string;
++ syncBehavior?: string;
}
}) => {
const { data: { integration } } = await apiRequest.post("/api/v1/integration", {
diff --cc frontend/src/hooks/api/integrations/types.ts
index f63257f849,f63257f849..0470a2c581
--- a/frontend/src/hooks/api/integrations/types.ts
+++ b/frontend/src/hooks/api/integrations/types.ts
@@@ -33,9 -33,9 +33,22 @@@ export type TIntegration =
__v: number;
metadata?: {
secretSuffix?: string;
++ syncBehavior?: IntegrationSyncBehavior;
scope: string;
org: string;
project: string;
environment: string;
};
};
++
++export enum IntegrationSyncBehavior {
++ OVERWRITE_TARGET = "overwrite-target",
++ PREFER_TARGET = "prefer-target",
++ PREFER_SOURCE = "prefer-source"
++}
++
++export const syncBehaviors = [
++ { label: "Overwrite target", value: IntegrationSyncBehavior.OVERWRITE_TARGET },
++ { label: "Prefer target", value: IntegrationSyncBehavior.PREFER_TARGET },
++ { label: "Prefer source", value: IntegrationSyncBehavior.PREFER_SOURCE }
++];
diff --cc frontend/src/pages/integrations/heroku/create.tsx
index e312f11f3c,a63cc1d074..bb0a144ae6
--- a/frontend/src/pages/integrations/heroku/create.tsx
+++ b/frontend/src/pages/integrations/heroku/create.tsx
@@@ -1,16 -1,8 +1,18 @@@
import { useEffect, useState } from "react";
++import { Controller, useForm } from "react-hook-form";
+import Head from "next/head";
+import Image from "next/image";
+import Link from "next/link";
import { useRouter } from "next/router";
+import { faArrowUpRightFromSquare, faBookOpen, faBugs, faCircleInfo } from "@fortawesome/free-solid-svg-icons";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import queryString from "query-string";
--
+import { RadioGroup } from "@app/components/v2/RadioGroup";
import { useCreateIntegration } from "@app/hooks/api";
+import { useGetIntegrationAuthHerokuPipelines } from "@app/hooks/api/integrationAuth/queries";
+import { App, Pipeline } from "@app/hooks/api/integrationAuth/types";
++import * as yup from "yup";
++import { yupResolver } from "@hookform/resolvers/yup";
import {
Button,
@@@ -25,12 -17,11 +27,37 @@@ import
useGetIntegrationAuthApps,
useGetIntegrationAuthById
} from "../../../hooks/api/integrationAuth";
-import { useGetWorkspaceById } from "../../../hooks/api/workspace";
+import { useCreateWsEnvironment, useGetWorkspaceById } from "../../../hooks/api/workspace";
++import { IntegrationSyncBehavior, syncBehaviors } from "@app/hooks/api/integrations/types";
++
++const schema = yup.object({
++ selectedSourceEnvironment: yup.string().required("Source environment is required"),
++ secretPath: yup.string().required("Secret path is required"),
++ targetApp: yup.string().required("Heroku app is required"),
++ syncBehavior: yup
++ .string()
++ .oneOf(syncBehaviors.map((b) => b.value), "Invalid sync behavior")
++ .required("Initial sync behavior is required")
++});
++
++type FormData = yup.InferType<typeof schema>;
export default function HerokuCreateIntegrationPage() {
const router = useRouter();
++
++ const { control, handleSubmit, setValue, watch } = useForm<FormData>({
++ resolver: yupResolver(schema),
++ defaultValues: {
++ secretPath: "/",
++ syncBehavior: IntegrationSyncBehavior.PREFER_SOURCE
++ }
++ });
++
++ const selectedSourceEnvironment = watch("selectedSourceEnvironment");
++
++
const { mutateAsync } = useCreateIntegration();
+ const { mutateAsync: mutateAsyncEnv } = useCreateWsEnvironment();
const { integrationAuthId } = queryString.parse(router.asPath.split("?")[1]);
@@@ -40,276 -31,116 +67,329 @@@
integrationAuthId: (integrationAuthId as string) ?? ""
});
- const [selectedSourceEnvironment, setSelectedSourceEnvironment] = useState("");
- const [targetApp, setTargetApp] = useState("");
- const [secretPath, setSecretPath] = useState("/");
-
+ const { data: integrationAuthPipelineCouplings } = useGetIntegrationAuthHerokuPipelines({
+ integrationAuthId: (integrationAuthId as string) ?? ""
+ });
-
- const [selectedSourceEnvironment, setSelectedSourceEnvironment] = useState("");
++
+ const [uniquePipelines, setUniquePipelines] = useState<Pipeline[]>();
+ const [selectedPipeline, setSelectedPipeline] = useState("");
+ const [selectedPipelineApps, setSelectedPipelineApps] = useState<App[]>();
- const [targetApp, setTargetApp] = useState("");
- const [secretPath, setSecretPath] = useState("/");
+ const [integrationType, setIntegrationType] = useState("App");
-
++
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
if (workspace) {
-- setSelectedSourceEnvironment(workspace.environments[0].slug);
++ setValue("selectedSourceEnvironment", workspace.environments[0].slug);
}
}, [workspace]);
+ useEffect(() => {
+ if (integrationAuthPipelineCouplings) {
+ const uniquePipelinesConst = Array.from(
+ new Set(
+ integrationAuthPipelineCouplings
+ .map(({ pipeline: { pipelineId, name } }) => ({
+ name,
+ pipelineId
+ }))
+ .map((obj) => JSON.stringify(obj))
+ )).map((str) => JSON.parse(str)) as { pipelineId: string; name: string }[]
++
++ [... (new Set())]
+ setUniquePipelines(uniquePipelinesConst);
+ if (uniquePipelinesConst) {
+ if (uniquePipelinesConst!.length > 0) {
+ setSelectedPipeline(uniquePipelinesConst![0].name);
+ } else {
+ setSelectedPipeline("none");
+ }
+ }
+ }
+ }, [integrationAuthPipelineCouplings]);
+
+ useEffect(() => {
+ if (integrationAuthPipelineCouplings) {
+ setSelectedPipelineApps(integrationAuthApps?.filter(app => integrationAuthPipelineCouplings
+ .filter((pipelineCoupling) => pipelineCoupling.pipeline.name === selectedPipeline)
+ .map(coupling => coupling.app.appId).includes(String(app.appId))))
+ }
+ }, [selectedPipeline]);
+
useEffect(() => {
if (integrationAuthApps) {
if (integrationAuthApps.length > 0) {
-- setTargetApp(integrationAuthApps[0].name);
++ setValue("targetApp", integrationAuthApps[0].name);
} else {
-- setTargetApp("none");
++ setValue("targetApp", "none");
}
}
}, [integrationAuthApps]);
-- const handleButtonClick = async () => {
-- try {
-- setIsLoading(true);
++ // const handleButtonClick = async () => {
++ // try {
++ // setIsLoading(true);
++
++ // if (!integrationAuth?.id) return;
++
++ // if (integrationType === "App") {
++ // await mutateAsync({
++ // integrationAuthId: integrationAuth?.id,
++ // isActive: true,
++ // app: targetApp,
++ // sourceEnvironment: selectedSourceEnvironment,
++ // secretPath
++ // });
++ // } else if (integrationType === "Pipeline") {
++ // selectedPipelineApps?.map(async (app, index) => {
++ // setTimeout(async () => {
++ // await mutateAsyncEnv({
++ // workspaceId: String(localStorage.getItem("projectData.id")),
++ // name: app.name,
++ // slug: app.name.toLowerCase().replaceAll(" ", "-")
++ // });
++ // await mutateAsync({
++ // integrationAuthId: integrationAuth?.id,
++ // isActive: true,
++ // app: app.name,
++ // sourceEnvironment: app.name.toLowerCase().replaceAll(" ", "-"),
++ // secretPath
++ // })
++ // }, 1000*index)
++ // })
++ // }
+
++ // setIsLoading(false);
++ // router.push(`/integrations/${localStorage.getItem("projectData.id")}`);
++ // } catch (err) {
++ // console.error(err);
++ // }
++ // };
+
++ const onFormSubmit = async ({
++ selectedSourceEnvironment: sce,
++ secretPath,
++ targetApp,
++ syncBehavior,
++ }: FormData) => {
++ try {
if (!integrationAuth?.id) return;
- if (integrationType === "App") {
- await mutateAsync({
- integrationAuthId: integrationAuth?.id,
- isActive: true,
- app: targetApp,
- sourceEnvironment: selectedSourceEnvironment,
- secretPath
- });
- } else if (integrationType === "Pipeline") {
- selectedPipelineApps?.map(async (app, index) => {
- setTimeout(async () => {
- await mutateAsyncEnv({
- workspaceId: String(localStorage.getItem("projectData.id")),
- name: app.name,
- slug: app.name.toLowerCase().replaceAll(" ", "-")
- });
- await mutateAsync({
- integrationAuthId: integrationAuth?.id,
- isActive: true,
- app: app.name,
- sourceEnvironment: app.name.toLowerCase().replaceAll(" ", "-"),
- secretPath
- })
- }, 1000*index)
- })
- }
++ setIsLoading(true);
++
+ await mutateAsync({
+ integrationAuthId: integrationAuth?.id,
+ isActive: true,
+ app: targetApp,
+ sourceEnvironment: selectedSourceEnvironment,
- secretPath
++ secretPath,
++ metadata: {
++ syncBehavior
++ }
+ });
setIsLoading(false);
router.push(`/integrations/${localStorage.getItem("projectData.id")}`);
} catch (err) {
console.error(err);
}
-- };
++ }
return integrationAuth &&
workspace &&
selectedSourceEnvironment &&
-- integrationAuthApps &&
-- targetApp ? (
- <div className="flex h-full w-full items-center justify-center">
- <Card className="max-w-md rounded-md p-8">
- <CardTitle className="text-center">Heroku Integration</CardTitle>
- <FormControl label="Project Environment" className="mt-4">
- <Select
- value={selectedSourceEnvironment}
- onValueChange={(val) => setSelectedSourceEnvironment(val)}
- className="w-full border border-mineshaft-500"
- >
- {workspace?.environments.map((sourceEnvironment) => (
- <SelectItem
- value={sourceEnvironment.slug}
- key={`source-environment-${sourceEnvironment.slug}`}
++ integrationAuthApps ? (
+ <div className="flex flex-col h-full w-full items-center justify-center">
+ <Head>
+ <title>Set Up Heroku Integration</title>
+ <link rel="icon" href="/infisical.ico" />
+ </Head>
+ <Card className="max-w-lg rounded-md border border-mineshaft-600 p-0">
+ <CardTitle
+ className="px-6 text-left text-xl"
+ subTitle="Select which environment or folder in Infisical you want to sync to Heroku's environment variables."
+ >
+ <div className="flex flex-row items-center">
+ <div className="flex items-center">
+ <Image
+ src="/images/integrations/Heroku.png"
+ height={30}
+ width={30}
+ alt="Heroku logo"
+ />
+ </div>
+ <span className="ml-2">Heroku Integration </span>
+ <Link href="https://infisical.com/docs/integrations/cloud/heroku" passHref>
+ <a target="_blank" rel="noopener noreferrer">
+ <div className="ml-2 mb-1 inline-block cursor-default rounded-md bg-yellow/20 px-1.5 pb-[0.03rem] pt-[0.04rem] text-sm text-yellow opacity-80 hover:opacity-100">
+ <FontAwesomeIcon icon={faBookOpen} className="mr-1.5" />
+ Docs
+ <FontAwesomeIcon
+ icon={faArrowUpRightFromSquare}
+ className="ml-1.5 mb-[0.07rem] text-xxs"
+ />
+ </div>
+ </a>
+ </Link>
+ </div>
+ </CardTitle>
- <RadioGroup
- value={integrationType}
- onValueChange={(val) => setIntegrationType(val)}
- />
- {integrationType === "Pipeline" && <>
- <FormControl label="Heroku Pipeline" className="px-6">
- <Select
- value={selectedPipeline}
- onValueChange={(val) => setSelectedPipeline(val)}
- className="w-full border border-mineshaft-500"
- >
- {uniquePipelines?.map((pipeline) => (
- <SelectItem
- value={pipeline.name}
- key={`source-environment-${pipeline.name}`}
++ <form onSubmit={handleSubmit(onFormSubmit)} className="px-6">
++ <Controller
++ control={control}
++ name="selectedSourceEnvironment"
++ render={({ field: { onChange, ...field }, fieldState: { error } }) => (
++ <FormControl
++ label="Project Environment"
++ errorText={error?.message}
++ isError={Boolean(error)}
>
- {pipeline.name}
- {sourceEnvironment.name}
-- </SelectItem>
-- ))}
-- </Select>
-- </FormControl>
- <div className="px-6 text-sm mb-4 inline-block text-bunker-300">
- After creating the integration, the following Heroku apps will be automatically synced to Infisical:
- <div className="flex flex-col">
- {selectedPipelineApps?.map(app => <p key={app.name} className="text-bunker-200 pl-0.5 inline-flex"><span className="text-primary pr-1">-&gt;</span> {app.name}</p>)}
- </div>
- From then on, every new app in the selected pipeline will be synced to Infisical, too.
- </div>
- </>}
- {integrationType === "App" && <>
- <FormControl label="Project Environment" className="px-6">
- <Select
- value={selectedSourceEnvironment}
- onValueChange={(val) => setSelectedSourceEnvironment(val)}
- className="w-full border border-mineshaft-500"
- >
- {workspace?.environments.map((sourceEnvironment) => (
- <SelectItem
- value={sourceEnvironment.slug}
- key={`source-environment-${sourceEnvironment.slug}`}
- <FormControl label="Secrets Path">
- <Input
- value={secretPath}
- onChange={(evt) => setSecretPath(evt.target.value)}
- placeholder="Provide a path, default is /"
++ <Select
++ defaultValue={field.value}
++ {...field}
++ onValueChange={(e) => onChange(e)}
++ className="w-full"
++ >
++ {workspace?.environments.map((sourceEnvironment) => (
++ <SelectItem
++ value={sourceEnvironment.slug}
++ key={`source-environment-${sourceEnvironment.slug}`}
++ >
++ {sourceEnvironment.name}
++ </SelectItem>
++ ))}
++ </Select>
++ </FormControl>
++ )}
+ />
- </FormControl>
- <FormControl label="Heroku App" className="mt-4">
- <Select
- value={targetApp}
- onValueChange={(val) => setTargetApp(val)}
- className="w-full border border-mineshaft-500"
- isDisabled={integrationAuthApps.length === 0}
- >
- {integrationAuthApps.length > 0 ? (
- integrationAuthApps.map((integrationAuthApp) => (
- <SelectItem
- value={integrationAuthApp.name}
- key={`target-app-${integrationAuthApp.name}`}
++ <Controller
++ control={control}
++ defaultValue=""
++ name="secretPath"
++ render={({ field, fieldState: { error } }) => (
++ <FormControl
++ label="Secrets Path"
++ isError={Boolean(error)}
++ errorText={error?.message}
+ >
- {sourceEnvironment.name}
- </SelectItem>
- ))}
- </Select>
- </FormControl>
- <FormControl label="Secrets Path" className="px-6">
- <Input
- value={secretPath}
- onChange={(evt) => setSecretPath(evt.target.value)}
- placeholder="Provide a path, default is /"
++ <Input {...field} placeholder="/" />
++ </FormControl>
++ )}
+ />
- </FormControl>
- <FormControl label="Heroku App" className="px-6">
- <Select
- value={targetApp}
- onValueChange={(val) => setTargetApp(val)}
- className="w-full border border-mineshaft-500"
- isDisabled={integrationAuthApps.length === 0}
- >
- {integrationAuthApps.length > 0 ? (
- integrationAuthApps.map((integrationAuthApp) => (
- <SelectItem
- value={integrationAuthApp.name}
- key={`target-app-${integrationAuthApp.name}`}
++ <Controller
++ control={control}
++ name="targetApp"
++ render={({ field: { onChange, ...field }, fieldState: { error } }) => {
++ return (
++ <FormControl
++ label="Heroku App"
++ errorText={error?.message}
++ isError={Boolean(error)}
>
-- {integrationAuthApp.name}
-- </SelectItem>
-- ))
-- ) : (
-- <SelectItem value="none" key="target-app-none">
-- No apps found
-- </SelectItem>
++ <Select
++ {...field}
++ onValueChange={(e) => {
++ if (e === "") return;
++ onChange(e);
++ }}
++ className="w-full"
++ >
++ {integrationAuthApps.length > 0 ? (
++ integrationAuthApps.map((integrationAuthApp) => (
++ <SelectItem
++ value={String(integrationAuthApp.name as string)}
++ key={`target-app-${String(integrationAuthApp.appId)}`}
++ >
++ {integrationAuthApp.name}
++ </SelectItem>
++ ))
++ ) : (
++ <SelectItem value="none" key="target-app-none">
++ No apps found
++ </SelectItem>
++ )}
++ </Select>
++ </FormControl>
++ );
++ }}
++ />
++ <Controller
++ control={control}
++ name="syncBehavior"
++ render={({ field: { onChange, ...field }, fieldState: { error } }) => (
++ <FormControl
++ label="Initial Sync Behavior"
++ errorText={error?.message}
++ isError={Boolean(error)}
++ >
++ <Select {...field} onValueChange={(e) => onChange(e)} className="w-full">
++ {syncBehaviors.map((b) => {
++ return (
++ <SelectItem value={b.value} key={`sync-behavior-${b.value}`}>
++ {b.label}
++ </SelectItem>
++ );
++ })}
++ </Select>
++ </FormControl>
)}
-- </Select>
- </FormControl></>}
- </FormControl>
-- <Button
-- onClick={handleButtonClick}
-- color="mineshaft"
- variant="outline_bg"
- className="mt-2 mb-6 ml-auto mr-6"
- className="mt-4"
-- isLoading={isLoading}
-- isDisabled={integrationAuthApps.length === 0}
-- >
-- Create Integration
-- </Button>
++ />
++ <Button
++ colorSchema="primary"
++ variant="outline_bg"
++ className="mb-6 mt-2 ml-auto"
++ size="sm"
++ type="submit"
++ isLoading={isLoading}
++ isDisabled={integrationAuthApps.length === 0}
++ >
++ Create Integration
++ </Button>
++ </form>
</Card>
- {integrationType === "App" && <>
++ {/* {integrationType === "App" && <>
+ <div className="mt-6 w-full max-w-md border-t border-mineshaft-800" />
+ <div className="mt-6 flex w-full max-w-lg flex-col rounded-md border border-mineshaft-600 bg-mineshaft-800 p-4">
+ <div className="flex flex-row items-center">
+ <FontAwesomeIcon icon={faCircleInfo} className="text-xl text-mineshaft-200" />{" "}
+ <span className="text-md ml-3 text-mineshaft-100">Pro Tips</span>
+ </div>
+ <span className="mt-4 text-sm text-mineshaft-300">
+ After creating an integration, your secrets will start syncing immediately. This might
+ cause an unexpected override of current secrets in Heroku with secrets from Infisical.
+ </span>
- </div></>}
++ </div></>} */}
</div>
) : (
- <div />
+ <div className="flex h-full w-full items-center justify-center">
+ <Head>
+ <title>Set Up Vercel Integration</title>
+ <link rel="icon" href="/infisical.ico" />
+ </Head>
+ {isIntegrationAuthAppsLoading ? (
+ <img
+ src="/images/loading/loading.gif"
+ height={70}
+ width={120}
+ alt="infisical loading indicator"
+ />
+ ) : (
+ <div className="flex h-max max-w-md flex-col rounded-md border border-mineshaft-600 bg-mineshaft-800 p-6 text-center text-mineshaft-200">
+ <FontAwesomeIcon icon={faBugs} className="inlineli my-2 text-6xl" />
+ <p>
+ Something went wrong. Please contact{" "}
+ <a
+ className="inline cursor-pointer text-mineshaft-100 underline decoration-primary-500 underline-offset-4 opacity-80 duration-200 hover:opacity-100"
+ target="_blank"
+ rel="noopener noreferrer"
+ href="mailto:[email protected]"
+ >
+ </a>{" "}
+ if the issue persists.
+ </p>
+ </div>
+ )}
+ </div>
);
}
diff --cc frontend/src/views/SecretOverviewPage/SecretOverviewPage.tsx
index c95e09acbe,09208ea4e5..1fba46266c
--- a/frontend/src/views/SecretOverviewPage/SecretOverviewPage.tsx
+++ b/frontend/src/views/SecretOverviewPage/SecretOverviewPage.tsx
@@@ -2,13 -2,15 +2,17 @@@ import { useEffect, useRef, useState }
import { useTranslation } from "react-i18next";
import Link from "next/link";
import { useRouter } from "next/router";
+import { faCheckCircle } from "@fortawesome/free-regular-svg-icons";
+ import { subject } from "@casl/ability";
import {
+ faAngleDown,
faArrowDown,
faArrowUp,
faFolderBlank,
+ faList,
- faMagnifyingGlass
+ faFolderPlus,
+ faMagnifyingGlass,
+ faPlus
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
@@@ -284,249 -320,286 +333,332 @@@ export const SecretOverviewPage = () =
filteredFolderNames?.length === 0;
return (
- <div className="container mx-auto px-6 text-mineshaft-50 dark:[color-scheme:dark]">
- <ProjectIndexSecretsSection decryptFileKey={latestFileKey!} />
- <div className="relative right-5 ml-4">
- <NavHeader pageName={t("dashboard.title")} isProjectRelated />
- </div>
- <div className="mt-6">
- <p className="text-3xl font-semibold text-bunker-100">Secrets Overview</p>
- <p className="text-md text-bunker-300">
- Inject your secrets using
- <a
- className="ml-1 text-mineshaft-300 underline decoration-primary-800 underline-offset-4 duration-200 hover:text-mineshaft-100 hover:decoration-primary-600"
- href="https://infisical.com/docs/cli/overview"
- target="_blank"
- rel="noopener noreferrer"
- >
- Infisical CLI
- </a>
- ,
- <a
- className="ml-1 text-mineshaft-300 underline decoration-primary-800 underline-offset-4 duration-200 hover:text-mineshaft-100 hover:decoration-primary-600"
- href="https://infisical.com/docs/documentation/getting-started/api"
- target="_blank"
- rel="noopener noreferrer"
- >
- Infisical API
- </a>
- ,
- <a
- className="ml-1 text-mineshaft-300 underline decoration-primary-800 underline-offset-4 duration-200 hover:text-mineshaft-100 hover:decoration-primary-600"
- href="https://infisical.com/docs/sdks/overview"
- target="_blank"
- rel="noopener noreferrer"
- >
- Infisical SDKs
- </a>
- , and
- <a
- className="ml-1 text-mineshaft-300 underline decoration-primary-800 underline-offset-4 duration-200 hover:text-mineshaft-100 hover:decoration-primary-600"
- href="https://infisical.com/docs/documentation/getting-started/introduction"
- target="_blank"
- rel="noopener noreferrer"
- >
- more
- </a>
- .
- </p>
- </div>
- <div className="mt-8 flex items-center justify-between">
- <FolderBreadCrumbs secretPath={secretPath} onResetSearch={handleResetSearch} />
- <div className="w-96 flex flex-row">
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <IconButton
- ariaLabel="Environments"
- variant="plain"
- size="sm"
- className="flex justify-center items-center overflow-hidden p-0 w-11 bg-mineshaft-800 hover:bg-primary/10 hover:border-primary/60 border border-mineshaft-600 mr-2"
+ <>
+ <div className="container mx-auto px-6 text-mineshaft-50 dark:[color-scheme:dark]">
+ <ProjectIndexSecretsSection decryptFileKey={latestFileKey!} />
+ <div className="relative right-5 ml-4">
+ <NavHeader pageName={t("dashboard.title")} isProjectRelated />
+ </div>
+ <div className="space-y-8">
+ <div className="mt-6">
+ <p className="text-3xl font-semibold text-bunker-100">Secrets Overview</p>
+ <p className="text-md text-bunker-300">
+ Inject your secrets using
+ <a
+ className="ml-1 text-mineshaft-300 underline decoration-primary-800 underline-offset-4 duration-200 hover:text-mineshaft-100 hover:decoration-primary-600"
+ href="https://infisical.com/docs/cli/overview"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ Infisical CLI
+ </a>
+ ,
+ <a
+ className="ml-1 text-mineshaft-300 underline decoration-primary-800 underline-offset-4 duration-200 hover:text-mineshaft-100 hover:decoration-primary-600"
+ href="https://infisical.com/docs/documentation/getting-started/api"
+ target="_blank"
+ rel="noopener noreferrer"
>
- <Tooltip content="Choose visible environments" className="mb-2">
- <FontAwesomeIcon icon={faList} />
- </Tooltip>
- </IconButton>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuLabel>Choose visible environments</DropdownMenuLabel>
- {userAvailableEnvs.map((avaiableEnv) => {
- const { id: envId, name } = avaiableEnv;
+ Infisical API
+ </a>
+ ,
+ <a
+ className="ml-1 text-mineshaft-300 underline decoration-primary-800 underline-offset-4 duration-200 hover:text-mineshaft-100 hover:decoration-primary-600"
+ href="https://infisical.com/docs/sdks/overview"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ Infisical SDKs
+ </a>
+ , and
+ <a
+ className="ml-1 text-mineshaft-300 underline decoration-primary-800 underline-offset-4 duration-200 hover:text-mineshaft-100 hover:decoration-primary-600"
+ href="https://infisical.com/docs/documentation/getting-started/introduction"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ more
+ </a>
+ .
+ </p>
+ </div>
- const isEnvSelected = visibleEnvs.map(env => env.id).includes(envId);
- return (
- <DropdownMenuItem
- onClick={() => handleEnvSelect(envId)}
- key={envId}
- icon={isEnvSelected && <FontAwesomeIcon className="text-primary" icon={faCheckCircle} />}
- iconPos="left"
+ {currentWorkspace?.version === ProjectVersion.V1 && (
+ <UpgradeProjectAlert project={currentWorkspace} />
+ )}
+
+ <div className="flex items-center justify-between">
+ <FolderBreadCrumbs secretPath={secretPath} onResetSearch={handleResetSearch} />
+ <div className="flex flex-row items-center justify-center space-x-2">
++ <DropdownMenu>
++ <DropdownMenuTrigger asChild>
++ <IconButton
++ ariaLabel="Environments"
++ variant="plain"
++ size="sm"
++ className="flex justify-center items-center overflow-hidden p-0 w-11 bg-mineshaft-800 hover:bg-primary/10 hover:border-primary/60 border border-mineshaft-600 mr-2"
+ >
- <div className="flex items-center">
- {name}
- </div>
- </DropdownMenuItem>
- );
- })}
- {/* <DropdownMenuItem className="px-1.5" asChild>
- <Button
- size="xs"
- className="w-full"
- colorSchema="primary"
- variant="outline_bg"
- leftIcon={<FontAwesomeIcon icon={faHockeyPuck} />}
- // onClick={onCreateTag}
++ <Tooltip content="Choose visible environments" className="mb-2">
++ <FontAwesomeIcon icon={faList} />
++ </Tooltip>
++ </IconButton>
++ </DropdownMenuTrigger>
++ <DropdownMenuContent align="end">
++ <DropdownMenuLabel>Choose visible environments</DropdownMenuLabel>
++ {userAvailableEnvs.map((avaiableEnv) => {
++ const { id: envId, name } = avaiableEnv;
++
++ const isEnvSelected = visibleEnvs.map(env => env.id).includes(envId);
++ return (
++ <DropdownMenuItem
++ onClick={() => handleEnvSelect(envId)}
++ key={envId}
++ icon={isEnvSelected && <FontAwesomeIcon className="text-primary" icon={faCheckCircle} />}
++ iconPos="left"
++ >
++ <div className="flex items-center">
++ {name}
++ </div>
++ </DropdownMenuItem>
++ );
++ })}
++ {/* <DropdownMenuItem className="px-1.5" asChild>
++ <Button
++ size="xs"
++ className="w-full"
++ colorSchema="primary"
++ variant="outline_bg"
++ leftIcon={<FontAwesomeIcon icon={faHockeyPuck} />}
++ // onClick={onCreateTag}
++ >
++ Create an environment
++ </Button>
++ </DropdownMenuItem> */}
++ </DropdownMenuContent>
++ </DropdownMenu>
+ <div className="w-80">
+ <Input
+ className="h-[2.3rem] bg-mineshaft-800 placeholder-mineshaft-50 duration-200 focus:bg-mineshaft-700/80"
+ placeholder="Search by secret/folder name..."
+ value={searchFilter}
+ onChange={(e) => setSearchFilter(e.target.value)}
+ leftIcon={<FontAwesomeIcon icon={faMagnifyingGlass} />}
+ />
+ </div>
+ <div>
+ <ProjectPermissionCan
+ I={ProjectPermissionActions.Create}
+ a={subject(ProjectPermissionSub.Secrets, { secretPath })}
>
- Create an environment
- </Button>
- </DropdownMenuItem> */}
- </DropdownMenuContent>
- </DropdownMenu>
- <Input
- className="h-[2.3rem] bg-mineshaft-800 placeholder-mineshaft-50 duration-200 focus:bg-mineshaft-700/80"
- placeholder="Search by secret/folder name..."
- value={searchFilter}
- onChange={(e) => setSearchFilter(e.target.value)}
- leftIcon={<FontAwesomeIcon icon={faMagnifyingGlass} />}
- />
- </div>
- </div>
- <div className="thin-scrollbar mt-4" ref={parentTableRef}>
- <TableContainer className="max-h-[calc(100vh-250px)] overflow-y-auto">
- <Table>
- <THead>
- <Tr className="sticky top-0 z-20 border-0">
- <Th className="sticky left-0 z-20 min-w-[20rem] border-b-0 p-0">
- <div className="flex items-center border-b border-r border-mineshaft-600 px-5 pt-3.5 pb-3">
- Name
+ {(isAllowed) => (
+ <Button
+ variant="outline_bg"
+ leftIcon={<FontAwesomeIcon icon={faPlus} />}
+ onClick={() => handlePopUpOpen("addSecretsInAllEnvs")}
+ className="h-10 rounded-r-none"
+ isDisabled={!isAllowed}
+ >
+ Add Secret
+ </Button>
+ )}
+ </ProjectPermissionCan>
+ <DropdownMenu
+ open={popUp.misc.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("misc", isOpen)}
+ >
+ <DropdownMenuTrigger asChild>
<IconButton
- variant="plain"
- className="ml-2"
- ariaLabel="sort"
- onClick={() => setSortDir((prev) => (prev === "asc" ? "desc" : "asc"))}
+ ariaLabel="add-folder-or-import"
+ variant="outline_bg"
+ className="rounded-l-none bg-mineshaft-600 p-3"
>
- <FontAwesomeIcon icon={sortDir === "asc" ? faArrowDown : faArrowUp} />
+ <FontAwesomeIcon icon={faAngleDown} />
</IconButton>
- </div>
- </Th>
- {visibleEnvs?.map(({ name, slug }, index) => {
- const envSecKeyCount = getEnvSecretKeyCount(slug);
- const missingKeyCount = secKeys.length - envSecKeyCount;
- return (
- <Th
- className="min-table-row min-w-[11rem] border-b-0 p-0 text-center"
- key={`secret-overview-${name}-${index + 1}`}
- >
- <div className="flex items-center justify-center border-b border-mineshaft-600 px-5 pt-3.5 pb-[0.83rem]">
- <button
- type="button"
- className="text-sm font-medium duration-100 hover:text-mineshaft-100"
- onClick={() => handleExploreEnvClick(slug)}
- >
- {name}
- </button>
- {missingKeyCount > 0 && (
- <Tooltip
- className="max-w-none lowercase"
- content={`${missingKeyCount} secrets missing\n compared to other environments`}
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <div className="flex flex-col space-y-1 p-1.5">
+ <ProjectPermissionCan
+ I={ProjectPermissionActions.Create}
+ a={subject(ProjectPermissionSub.Secrets, { secretPath })}
+ >
+ {(isAllowed) => (
+ <Button
+ leftIcon={<FontAwesomeIcon icon={faFolderPlus} />}
+ onClick={() => {
+ handlePopUpOpen("addFolder");
+ handlePopUpClose("misc");
+ }}
+ isDisabled={!isAllowed}
+ variant="outline_bg"
+ className="h-10"
+ isFullWidth
>
- <div className="ml-2 flex h-[1.1rem] cursor-default items-center justify-center rounded-sm border border-red-400 bg-red-600 p-1 text-xs font-medium text-bunker-100">
- <span className="text-bunker-100">{missingKeyCount}</span>
- </div>
- </Tooltip>
+ Add Folder
+ </Button>
)}
- </div>
- </Th>
- );
- })}
- </Tr>
- </THead>
- <TBody>
- {canViewOverviewPage && isTableLoading && (
- <TableSkeleton
- columns={userAvailableEnvs.length + 1}
- innerKey="secret-overview-loading"
- rows={5}
- className="bg-mineshaft-700"
- />
- )}
- {isTableEmpty && !isTableLoading && (
- <Tr>
- <Td colSpan={visibleEnvs.length + 1}>
- <EmptyState title="Let's add some secrets" icon={faFolderBlank} iconSize="3x">
- <Link
- href={{
- pathname: "/project/[id]/secrets/[env]",
- query: { id: workspaceId, env: visibleEnvs?.[0]?.slug }
- }}
+ </ProjectPermissionCan>
+ </div>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </div>
+ </div>
+ </div>
+ <div className="thin-scrollbar mt-4" ref={parentTableRef}>
+ <TableContainer className="max-h-[calc(100vh-250px)] overflow-y-auto">
+ <Table>
+ <THead>
+ <Tr className="sticky top-0 z-20 border-0">
+ <Th className="sticky left-0 z-20 min-w-[20rem] border-b-0 p-0">
+ <div className="flex items-center border-b border-r border-mineshaft-600 px-5 pt-3.5 pb-3">
+ Name
+ <IconButton
+ variant="plain"
+ className="ml-2"
+ ariaLabel="sort"
+ onClick={() => setSortDir((prev) => (prev === "asc" ? "desc" : "asc"))}
>
- <Button
- className="mt-4"
- variant="outline_bg"
- colorSchema="primary"
- size="md"
- >
- Go to {visibleEnvs?.[0]?.name}
- </Button>
- </Link>
- </EmptyState>
- </Td>
+ <FontAwesomeIcon icon={sortDir === "asc" ? faArrowDown : faArrowUp} />
+ </IconButton>
+ </div>
+ </Th>
- {userAvailableEnvs?.map(({ name, slug }, index) => {
++ {visibleEnvs?.map(({ name, slug }, index) => {
+ const envSecKeyCount = getEnvSecretKeyCount(slug);
+ const missingKeyCount = secKeys.length - envSecKeyCount;
+ return (
+ <Th
+ className="min-table-row min-w-[11rem] border-b-0 p-0 text-center"
+ key={`secret-overview-${name}-${index + 1}`}
+ >
+ <div className="flex items-center justify-center border-b border-mineshaft-600 px-5 pt-3.5 pb-[0.83rem]">
+ <button
+ type="button"
+ className="text-sm font-medium duration-100 hover:text-mineshaft-100"
+ onClick={() => handleExploreEnvClick(slug)}
+ >
+ {name}
+ </button>
+ {missingKeyCount > 0 && (
+ <Tooltip
+ className="max-w-none lowercase"
+ content={`${missingKeyCount} secrets missing\n compared to other environments`}
+ >
+ <div className="ml-2 flex h-[1.1rem] cursor-default items-center justify-center rounded-sm border border-red-400 bg-red-600 p-1 text-xs font-medium text-bunker-100">
+ <span className="text-bunker-100">{missingKeyCount}</span>
+ </div>
+ </Tooltip>
+ )}
+ </div>
+ </Th>
+ );
+ })}
</Tr>
- )}
- {!isTableLoading &&
- filteredFolderNames.map((folderName, index) => (
- <SecretOverviewFolderRow
- folderName={folderName}
- isFolderPresentInEnv={isFolderPresentInEnv}
- environments={visibleEnvs}
- key={`overview-${folderName}-${index + 1}`}
- onClick={handleFolderClick}
+ </THead>
+ <TBody>
+ {canViewOverviewPage && isTableLoading && (
+ <TableSkeleton
- columns={userAvailableEnvs.length + 1}
++ columns={visibleEnvs.length + 1}
+ innerKey="secret-overview-loading"
+ rows={5}
+ className="bg-mineshaft-700"
/>
- ))}
- {!isTableLoading &&
- (visibleEnvs?.length > 0 ? (
- filteredSecretNames.map((key, index) => (
- <SecretOverviewTableRow
- secretPath={secretPath}
- onSecretCreate={handleSecretCreate}
- onSecretDelete={handleSecretDelete}
- onSecretUpdate={handleSecretUpdate}
- key={`overview-${key}-${index + 1}`}
+ )}
+ {isTableEmpty && !isTableLoading && (
+ <Tr>
- <Td colSpan={userAvailableEnvs.length + 1}>
++ <Td colSpan={visibleEnvs.length + 1}>
+ <EmptyState title="Let's add some secrets" icon={faFolderBlank} iconSize="3x">
+ <Link
+ href={{
+ pathname: "/project/[id]/secrets/[env]",
- query: { id: workspaceId, env: userAvailableEnvs?.[0]?.slug }
++ query: { id: workspaceId, env: visibleEnvs?.[0]?.slug }
+ }}
+ >
+ <Button
+ className="mt-4"
+ variant="outline_bg"
+ colorSchema="primary"
+ size="md"
+ >
- Go to {userAvailableEnvs?.[0]?.name}
++ Go to {visibleEnvs?.[0]?.name}
+ </Button>
+ </Link>
+ </EmptyState>
+ </Td>
+ </Tr>
+ )}
+ {!isTableLoading &&
+ filteredFolderNames.map((folderName, index) => (
+ <SecretOverviewFolderRow
+ folderName={folderName}
+ isFolderPresentInEnv={isFolderPresentInEnv}
- environments={userAvailableEnvs}
+ environments={visibleEnvs}
- secretKey={key}
- getSecretByKey={getSecretByKey}
- expandableColWidth={expandableTableWidth}
+ key={`overview-${folderName}-${index + 1}`}
+ onClick={handleFolderClick}
+ />
+ ))}
+ {!isTableLoading &&
- (userAvailableEnvs?.length > 0 ? (
++ (visibleEnvs?.length > 0 ? (
+ filteredSecretNames.map((key, index) => (
+ <SecretOverviewTableRow
+ secretPath={secretPath}
+ onSecretCreate={handleSecretCreate}
+ onSecretDelete={handleSecretDelete}
+ onSecretUpdate={handleSecretUpdate}
+ key={`overview-${key}-${index + 1}`}
- environments={userAvailableEnvs}
++ environments={visibleEnvs}
+ secretKey={key}
+ getSecretByKey={getSecretByKey}
+ expandableColWidth={expandableTableWidth}
+ />
+ ))
+ ) : (
+ <PermissionDeniedBanner />
+ ))}
+ </TBody>
+ <TFoot>
+ <Tr className="sticky bottom-0 z-10 border-0 bg-mineshaft-800">
+ <Td className="sticky left-0 z-10 border-0 bg-mineshaft-800 p-0">
+ <div
+ className="w-full border-t border-r border-mineshaft-600"
+ style={{ height: "45px" }}
/>
- ))
- ) : (
- <PermissionDeniedBanner />
- ))}
- </TBody>
- <TFoot>
- <Tr className="sticky bottom-0 z-10 border-0 bg-mineshaft-800">
- <Td className="sticky left-0 z-10 border-0 bg-mineshaft-800 p-0">
- <div
- className="w-full border-t border-r border-mineshaft-600"
- style={{ height: "45px" }}
- />
- </Td>
- {visibleEnvs.map(({ name, slug }) => (
- <Td key={`explore-${name}-btn`} className="border-0 border-mineshaft-600 p-0">
- <div className="flex w-full items-center justify-center border-r border-t border-mineshaft-600 px-5 py-2">
- <Button
- size="xs"
- variant="outline_bg"
- isFullWidth
- onClick={() => handleExploreEnvClick(slug)}
- >
- Explore
- </Button>
- </div>
</Td>
- ))}
- </Tr>
- </TFoot>
- </Table>
- </TableContainer>
- {userAvailableEnvs.map(({ name, slug }) => (
++ {visibleEnvs?.map(({ name, slug }) => (
+ <Td key={`explore-${name}-btn`} className="border-0 border-mineshaft-600 p-0">
+ <div className="flex w-full items-center justify-center border-r border-t border-mineshaft-600 px-5 py-2">
+ <Button
+ size="xs"
+ variant="outline_bg"
+ isFullWidth
+ onClick={() => handleExploreEnvClick(slug)}
+ >
+ Explore
+ </Button>
+ </div>
+ </Td>
+ ))}
+ </Tr>
+ </TFoot>
+ </Table>
+ </TableContainer>
+ </div>
</div>
- </div>
+ <CreateSecretForm
+ secretPath={secretPath}
+ isOpen={popUp.addSecretsInAllEnvs.isOpen}
+ getSecretByKey={getSecretByKey}
+ onTogglePopUp={(isOpen) => handlePopUpToggle("addSecretsInAllEnvs", isOpen)}
+ onClose={() => handlePopUpClose("addSecretsInAllEnvs")}
+ decryptFileKey={latestFileKey!}
+ />
+ <Modal
+ isOpen={popUp.addFolder.isOpen}
+ onOpenChange={(isOpen) => handlePopUpToggle("addFolder", isOpen)}
+ >
+ <ModalContent title="Create Folder">
+ <FolderForm onCreateFolder={handleFolderCreate} />
+ </ModalContent>
+ </Modal>
+ </>
);
};