Skip to content

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

job and frontend UX

Matheus Nogueira3b51d3fca948
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index 759204b429..ba35a1688d 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -111,7 +111,8 @@ export enum QueueName {
PamDiscoveryScan = "pam-discovery-scan",
CaAutoRenewal = "ca-auto-renewal",
ProjectHardDelete = "project-hard-delete",
- SignerAutoRenewal = "signer-auto-renewal"
+ SignerAutoRenewal = "signer-auto-renewal",
+ SecretBlindIndexMigration = "secret-blind-index-migration"
}
export enum QueueJobs {
@@ -185,13 +186,14 @@ export enum QueueJobs {
DailySecretSyncRetry = "daily-secret-sync-retry-job",
DigiCertOrderPolling = "digicert-order-polling-job",
ProjectHardDelete = "project-hard-delete-job",
- SignerDailyAutoRenewal = "signer-daily-auto-renewal"
+ SignerDailyAutoRenewal = "signer-daily-auto-renewal",
+ SecretBlindIndexMigration = "secret-blind-index-migration"
}
export type TQueueOptions = {
jobId: string;
- removeOnComplete?: boolean | { count: number };
- removeOnFail?: boolean | { count: number };
+ removeOnComplete?: boolean | { count: number } | { age: number };
+ removeOnFail?: boolean | { count: number } | { age : number};
attempts?: number;
delay?: number;
backoff?: {
@@ -507,6 +509,10 @@ export type TQueueJobTypes = {
name: QueueJobs.SignerDailyAutoRenewal;
payload: undefined;
};
+ [QueueName.SecretBlindIndexMigration]: {
+ name: QueueJobs.SecretBlindIndexMigration;
+ payload: { projectId: string };
+ };
};
const SECRET_SCANNING_QUEUES = [
@@ -597,6 +603,7 @@ export type TQueueServiceFactory = {
) => Promise<void>;
removeJobScheduler: <T extends QueueName>(name: T, schedulerId: string) => Promise<void>;
getJobSchedulers: (name: QueueName, start?: number, end?: number) => Promise<JobSchedulerJson[]>;
+ getJob: <T extends QueueName>(name: T, jobId: string) => Promise<Job<TQueueJobTypes[T]["payload"], void, TQueueJobTypes[T]["name"]> | undefined>;
};
export const queueServiceFactory = (redisCfg: TRedisConfigKeys): TQueueServiceFactory => {
@@ -979,6 +986,13 @@ export const queueServiceFactory = (redisCfg: TRedisConfigKeys): TQueueServiceFa
return q.getJobSchedulers(startOffset, endOffset);
};
+ const getJob: TQueueServiceFactory["getJob"] = async (name, jobId) => {
+ const q = queueContainer[name];
+ if (!q) return undefined;
+ const job = await q.getJob(jobId);
+ return job ?? undefined;
+ };
+
return {
start,
listen,
@@ -994,6 +1008,7 @@ export const queueServiceFactory = (redisCfg: TRedisConfigKeys): TQueueServiceFa
getDelayedJobs,
upsertJobScheduler,
removeJobScheduler,
- getJobSchedulers
+ getJobSchedulers,
+ getJob
};
};
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 5432b65cab..c5301b0bd5 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1302,6 +1302,8 @@ export const registerRoutes = async (
const projectQueueService = projectQueueFactory({
queueService,
secretDAL,
+ secretV2BridgeDAL,
+ kmsService,
folderDAL,
projectDAL,
orgDAL,
diff --git a/backend/src/server/routes/v1/project-router.ts b/backend/src/server/routes/v1/project-router.ts
index 8354a57cb3..2211342be4 100644
--- a/backend/src/server/routes/v1/project-router.ts
+++ b/backend/src/server/routes/v1/project-router.ts
@@ -569,6 +569,83 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
}
});
+ server.route({
+ method: "POST",
+ url: "/:projectId/secret-blind-index",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ hide: false,
+ operationId: "enableProjectSecretBlindIndex",
+ tags: [ApiDocsTags.Projects],
+ description: "Enable secret blind indexing for duplicate detection",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ projectId: z.string().trim()
+ }),
+ response: {
+ 200: z.object({
+ message: z.string()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ await server.services.project.enableSecretBlindIndex({
+ projectId: req.params.projectId,
+ actorAuthMethod: req.permission.authMethod,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId
+ });
+
+ return { message: "Successfully enabled secret blind indexing" };
+ }
+ });
+
+ server.route({
+ method: "GET",
+ url: "/:projectId/secret-blind-index/status",
+ config: {
+ rateLimit: readLimit
+ },
+ schema: {
+ hide: false,
+ operationId: "getProjectSecretBlindIndexStatus",
+ tags: [ApiDocsTags.Projects],
+ description: "Get secret blind index migration status",
+ security: [
+ {
+ bearerAuth: []
+ }
+ ],
+ params: z.object({
+ projectId: z.string().trim()
+ }),
+ response: {
+ 200: z.object({
+ status: z.enum(["not-found", "pending", "completed", "failed"]),
+ message: z.string().optional()
+ })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
+ handler: async (req) => {
+ return server.services.project.getSecretBlindIndexMigrationStatus({
+ projectId: req.params.projectId,
+ actorAuthMethod: req.permission.authMethod,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorOrgId: req.permission.orgId
+ });
+ }
+ });
+
server.route({
method: "PUT",
url: "/:projectId/audit-logs-retention",
diff --git a/backend/src/services/project/project-queue.ts b/backend/src/services/project/project-queue.ts
index ae5b1009ed..1ddbdae5c6 100644
--- a/backend/src/services/project/project-queue.ts
+++ b/backend/src/services/project/project-queue.ts
@@ -32,6 +32,8 @@ import { logger } from "@app/lib/logger";
import { QueueJobs, QueueName, TQueueJobTypes, TQueueServiceFactory } from "@app/queue";
import { TIntegrationAuthDALFactory } from "../integration-auth/integration-auth-dal";
+import { KmsDataKey } from "../kms/kms-types";
+import { TKmsServiceFactory } from "../kms/kms-service";
import { TMembershipRoleDALFactory } from "../membership/membership-role-dal";
import { TMembershipUserDALFactory } from "../membership-user/membership-user-dal";
import { TOrgDALFactory } from "../org/org-dal";
@@ -42,6 +44,7 @@ import { TProjectKeyDALFactory } from "../project-key/project-key-dal";
import { TSecretDALFactory } from "../secret/secret-dal";
import { TSecretVersionDALFactory } from "../secret/secret-version-dal";
import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";
+import { TSecretV2BridgeDALFactory } from "../secret-v2-bridge/secret-v2-bridge-dal";
import { TUserDALFactory } from "../user/user-dal";
import { TProjectDALFactory } from "./project-dal";
import { assignWorkspaceKeysToMembers, createProjectKey } from "./project-fns";
@@ -53,6 +56,8 @@ type TProjectQueueFactoryDep = {
secretVersionDAL: Pick<TSecretVersionDALFactory, "find" | "bulkUpdateNoVersionIncrement" | "delete">;
folderDAL: Pick<TSecretFolderDALFactory, "find">;
secretDAL: Pick<TSecretDALFactory, "find" | "bulkUpdateNoVersionIncrement">;
+ secretV2BridgeDAL: Pick<TSecretV2BridgeDALFactory, "findProjectSecretsWithNullBlindIndex" | "batchSetBlindIndexes">;
+ kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;
projectKeyDAL: Pick<TProjectKeyDALFactory, "findLatestProjectKey" | "find" | "create" | "delete" | "insertMany">;
secretApprovalRequestDAL: Pick<TSecretApprovalRequestDALFactory, "find">;
secretApprovalSecretDAL: Pick<TSecretApprovalRequestSecretDALFactory, "find" | "bulkUpdateNoVersionIncrement">;
@@ -70,6 +75,8 @@ type TProjectQueueFactoryDep = {
export const projectQueueFactory = ({
queueService,
secretDAL,
+ secretV2BridgeDAL,
+ kmsService,
folderDAL,
userDAL,
secretVersionDAL,
@@ -639,7 +646,105 @@ export const projectQueueFactory = ({
logger.error(err, "Upgrade project failed", job?.data);
});
+ const startSecretBlindIndexMigration = async (projectId: string) => {
+ const jobId = `enable-blind-index-project-${projectId}`;
+
+ const existingJob = await queueService.getJob(QueueName.SecretBlindIndexMigration, jobId);
+ if (existingJob) {
+ const state = await existingJob.getState();
+ if (state === "completed" || state === "failed") {
+ await existingJob.remove();
+ } else {
+ logger.info(`Job for project ${projectId} already exists, skipping`)
+ return;
+ }
+ }
+
+ await queueService.queue(
+ QueueName.SecretBlindIndexMigration,
+ QueueJobs.SecretBlindIndexMigration,
+ { projectId },
+ {
+ removeOnComplete: { age: 360 },
+ removeOnFail: { age: 24 * 3600 },
+ jobId
+ }
+ );
+ };
+
+ queueService.start(QueueName.SecretBlindIndexMigration, async (job) => {
+ const { projectId } = job.data;
+ const BATCH_SIZE = 500;
+
+ logger.info(`SecretBlindIndexMigration: starting migration [projectId=${projectId}]`);
+
+ const { decryptor, generateSecretBlindIndex } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.SecretManager,
+ projectId
+ });
+
+ let totalProcessed = 0;
+
+ // eslint-disable-next-line no-constant-condition, @typescript-eslint/no-unnecessary-condition
+ while (true) {
+ const secrets = await secretV2BridgeDAL.findProjectSecretsWithNullBlindIndex(projectId, BATCH_SIZE);
+
+ if (secrets.length === 0) break;
+
+ const updates: { id: string; secretValueBlindIndex: string }[] = [];
+ for (const secret of secrets) {
+ const decryptedValue = decryptor({ cipherTextBlob: secret.encryptedValue! });
+ const blindIndex = await generateSecretBlindIndex(decryptedValue);
+ updates.push({ id: secret.id, secretValueBlindIndex: blindIndex });
+ }
+
+ if (updates.length > 0) {
+ await secretV2BridgeDAL.batchSetBlindIndexes(updates);
+ }
+
+ totalProcessed += updates.length;
+ logger.info(
+ `SecretBlindIndexMigration: processed batch [projectId=${projectId}] [batchSize=${updates.length}] [totalProcessed=${totalProcessed}]`
+ );
+
+ if (secrets.length < BATCH_SIZE) break;
+ }
+
+ await projectDAL.updateById(projectId, { secretBlindIndexEnabled: true });
+
+ logger.info(
+ `SecretBlindIndexMigration: migration complete [projectId=${projectId}] [totalProcessed=${totalProcessed}]`
+ );
+ });
+
+ queueService.listen(QueueName.SecretBlindIndexMigration, "failed", (job, err) => {
+ logger.error(err, `SecretBlindIndexMigration: failed [projectId=${job?.data.projectId}]`);
+ });
+
+ const getSecretBlindIndexMigrationStatus = async (projectId: string) => {
+ const jobId = `enable-blind-index-project-${projectId}`;
+ const job = await queueService.getJob(QueueName.SecretBlindIndexMigration, jobId);
+
+ if (!job) {
+ return { status: "not-found" as const };
+ }
+
+ const state = await job.getState();
+
+ if (state === "failed") {
+ return { status: "failed" as const, message: job.failedReason ?? "Unknown error" };
+ }
+
+ if (state === "completed") {
+ return { status: "completed" as const };
+ }
+
+ return { status: "pending" as const };
+ };
+
return {
- upgradeProject
+ upgradeProject,
+ startSecretBlindIndexMigration,
+ getSecretBlindIndexMigrationStatus
};
};
diff --git a/backend/src/services/project/project-service.ts b/backend/src/services/project/project-service.ts
index 90b36444ce..df0d11dd0a 100644
--- a/backend/src/services/project/project-service.ts
+++ b/backend/src/services/project/project-service.ts
@@ -104,6 +104,7 @@ import {
TCreateProjectDTO,
TDeleteProjectDTO,
TDeleteProjectWorkflowIntegration,
+ TEnableSecretBlindIndexDTO,
TGetActivityTrendDTO,
TGetDashboardStatsDTO,
TGetProjectDTO,
@@ -2573,6 +2574,53 @@ export const projectServiceFactory = ({
return { requests };
};
+ const enableSecretBlindIndex = async ({
+ actor,
+ actorId,
+ actorOrgId,
+ actorAuthMethod,
+ projectId
+ }: TEnableSecretBlindIndexDTO) => {
+ const project = await projectDAL.findById(projectId);
+ if (!project) throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });
+
+ // TODO: what permissions should we ask for this???
+ const { permission } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId: project.id,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.SecretManager
+ });
+ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Settings);
+
+ await projectQueue.startSecretBlindIndexMigration(project.id);
+ };
+
+ const getSecretBlindIndexMigrationStatus = async ({
+ actor,
+ actorId,
+ actorOrgId,
+ actorAuthMethod,
+ projectId
+ }: TEnableSecretBlindIndexDTO) => {
+ const project = await projectDAL.findById(projectId);
+ if (!project) throw new NotFoundError({ message: `Project with ID '${projectId}' not found` });
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId: project.id,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.SecretManager
+ });
+ ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Edit, ProjectPermissionSub.Settings);
+
+ return projectQueue.getSecretBlindIndexMigrationStatus(project.id);
+ };
+
return {
createProject,
deleteProject,
@@ -2612,6 +2660,8 @@ export const projectServiceFactory = ({
requestProjectAccess,
getMyPendingProjectAccessRequests,
searchProjects,
- extractProjectIdFromSlug
+ extractProjectIdFromSlug,
+ enableSecretBlindIndex,
+ getSecretBlindIndexMigrationStatus
};
};
diff --git a/backend/src/services/project/project-types.ts b/backend/src/services/project/project-types.ts
index dbc7138a0a..14662bf188 100644
--- a/backend/src/services/project/project-types.ts
+++ b/backend/src/services/project/project-types.ts
@@ -73,6 +73,8 @@ export type TToggleProjectDeleteProtectionDTO = {
hasDeleteProtection: boolean;
} & TProjectPermission;
+export type TEnableSecretBlindIndexDTO = TProjectPermission;
+
export type TUpdateProjectVersionLimitDTO = {
pitVersionLimit: number;
workspaceSlug: string;
diff --git a/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts b/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts
index b5213c3f10..865e5a32a8 100644
--- a/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts
+++ b/backend/src/services/secret-v2-bridge/secret-v2-bridge-dal.ts
@@ -1023,6 +1023,47 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
}
};
+ const findProjectSecretsWithNullBlindIndex = async (projectId: string, limit: number, tx?: Knex) => {
+ try {
+ const docs = await (tx || db.replicaNode())(TableName.SecretV2)
+ .join(TableName.SecretFolder, `${TableName.SecretV2}.folderId`, `${TableName.SecretFolder}.id`)
+ .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)
+ .where("projectId", projectId)
+ .whereNull(`${TableName.Environment}.deleteAfter`)
+ .whereNull(`${TableName.SecretV2}.secretValueBlindIndex`)
+ .whereNotNull(`${TableName.SecretV2}.encryptedValue`)
+ .select(`${TableName.SecretV2}.id` as "id", `${TableName.SecretV2}.encryptedValue` as "encryptedValue")
+ .limit(limit);
+ return docs as Pick<TSecretsV2, "id" | "encryptedValue">[];
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindProjectSecretsWithNullBlindIndex" });
+ }
+ };
+
+ const batchSetBlindIndexes = async (updates: { id: string; secretValueBlindIndex: string }[], tx?: Knex) => {
+ if (updates.length === 0) return;
+
+ try {
+ const bindings: string[] = [];
+ const valuePlaceholders = updates.map(({ id, secretValueBlindIndex }) => {
+ bindings.push(id, secretValueBlindIndex);
+ return "(CAST(? AS uuid), ?)";
+ });
+
+ const query = `
+ UPDATE ${TableName.SecretV2}
+ SET "secretValueBlindIndex" = v.blind_index
+ FROM (VALUES ${valuePlaceholders.join(", ")}) AS v(id, blind_index)
+ WHERE ${TableName.SecretV2}.id = v.id
+ AND ${TableName.SecretV2}."secretValueBlindIndex" IS NULL
+ `;
+
+ await (tx || db).raw(query, bindings);
+ } catch (error) {
+ throw new DatabaseError({ error, name: "BatchSetBlindIndexes" });
+ }
+ };
+
const findOneWithTags = async (filter: Partial<TSecretsV2>, tx?: Knex) => {
try {
const rawDocs = await (tx || db.replicaNode())(TableName.SecretV2)
@@ -1238,7 +1279,12 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
let currentIndex: string | null = null;
let currentGroup: { key: string; environment: string; folderId: string }[] = [];
- for (const row of rows as { key: string; folderId: string; secretValueBlindIndex: string; environment: string }[]) {
+ for (const row of rows as {
+ key: string;
+ folderId: string;
+ secretValueBlindIndex: string;
+ environment: string;
+ }[]) {
if (row.secretValueBlindIndex !== currentIndex) {
if (currentGroup.length > 0) {
groups.push({ secrets: currentGroup });
@@ -1291,6 +1337,8 @@ export const secretV2BridgeDALFactory = ({ db, keyStore }: TSecretV2DalArg) => {
upsertSecretReferences,
findReferencedSecretReferences,
findAllProjectSecretValues,
+ findProjectSecretsWithNullBlindIndex,
+ batchSetBlindIndexes,
countByFolderIds,
findStaleByProject,
countStaleByProject,
diff --git a/frontend/src/hooks/api/projects/index.tsx b/frontend/src/hooks/api/projects/index.tsx
index da28d34a27..2daf7bb94e 100644
--- a/frontend/src/hooks/api/projects/index.tsx
+++ b/frontend/src/hooks/api/projects/index.tsx
@@ -1,6 +1,7 @@
export {
useAddGroupToWorkspace,
useDeleteGroupFromWorkspace,
+ useEnableSecretBlindIndex,
useLeaveProject,
useMigrateProjectToV3,
useRequestProjectAccess,
diff --git a/frontend/src/hooks/api/projects/mutations.tsx b/frontend/src/hooks/api/projects/mutations.tsx
index d44596f162..2f02e51339 100644
--- a/frontend/src/hooks/api/projects/mutations.tsx
+++ b/frontend/src/hooks/api/projects/mutations.tsx
@@ -7,6 +7,7 @@ import { groupKeys } from "../groups/queries";
import { TGroupMembership } from "../groups/types";
import { pkiApplicationKeys } from "../pkiApplications/queries";
import { userKeys } from "../users/query-keys";
+import { secretInsightsKeys } from "../secretInsights/queries";
import { projectKeys } from "./query-keys";
import {
TProjectSshConfig,
@@ -167,6 +168,23 @@ export const useRequestProjectAccess = () => {
});
};
+export const useEnableSecretBlindIndex = () => {
+ const queryClient = useQueryClient();
+ return useMutation<{ message: string }, object, { projectId: string }>({
+ mutationFn: async ({ projectId }) => {
+ const { data } = await apiRequest.post<{ message: string }>(
+ `/api/v1/projects/${projectId}/secret-blind-index`
+ );
+ return data;
+ },
+ onSuccess: (_, { projectId }) => {
+ queryClient.invalidateQueries({
+ queryKey: secretInsightsKeys.secretsDuplication({ projectId })
+ });
+ }
+ });
+};
+
export const useUpdateProjectSshConfig = () => {
const queryClient = useQueryClient();
return useMutation<TProjectSshConfig, object, TUpdateProjectSshConfigDTO>({
diff --git a/frontend/src/hooks/api/secretInsights/index.ts b/frontend/src/hooks/api/secretInsights/index.ts
index 2091982cd0..f1f04afb8b 100644
--- a/frontend/src/hooks/api/secretInsights/index.ts
+++ b/frontend/src/hooks/api/secretInsights/index.ts
@@ -1,9 +1,11 @@
export {
+ secretInsightsKeys,
useGetAuthMethodDistribution,
useGetCalendarInsights,
useGetInsightsSummary,
// useGetSecretAccessLocations,
useGetSecretAccessVolume,
+ useGetSecretBlindIndexStatus,
useGetSecretsDuplication
} from "./queries";
export type {
diff --git a/frontend/src/hooks/api/secretInsights/queries.tsx b/frontend/src/hooks/api/secretInsights/queries.tsx
index 3a5b0172d5..3d397eac94 100644
--- a/frontend/src/hooks/api/secretInsights/queries.tsx
+++ b/frontend/src/hooks/api/secretInsights/queries.tsx
@@ -13,6 +13,8 @@ import {
// TGetSecretAccessLocationsResponse,
TGetSecretAccessVolumeDTO,
TGetSecretAccessVolumeResponse,
+ TGetSecretBlindIndexStatusDTO,
+ TGetSecretBlindIndexStatusResponse,
TGetSecretsDuplicationDTO,
TGetSecretsDuplicationResponse
} from "./types";
@@ -30,7 +32,9 @@ export const secretInsightsKeys = {
summary: (params: TGetInsightsSummaryDTO) =>
[...secretInsightsKeys.all(), "summary", params] as const,
secretsDuplication: (params: TGetSecretsDuplicationDTO) =>
- [...secretInsightsKeys.all(), "secrets-duplication", params] as const
+ [...secretInsightsKeys.all(), "secrets-duplication", params] as const,
+ blindIndexStatus: (params: TGetSecretBlindIndexStatusDTO) =>
+ [...secretInsightsKeys.all(), "blind-index-status", params] as const
};
const INSIGHTS_STALE_TIME = 5 * 60 * 1000; // 5 minutes
@@ -190,3 +194,28 @@ export const useGetSecretsDuplication = (
...options
});
};
+
+export const useGetSecretBlindIndexStatus = (
+ params: TGetSecretBlindIndexStatusDTO,
+ options?: Omit<
+ UseQueryOptions<
+ TGetSecretBlindIndexStatusResponse,
+ unknown,
+ TGetSecretBlindIndexStatusResponse,
+ ReturnType<typeof secretInsightsKeys.blindIndexStatus>
+ >,
+ "queryKey" | "queryFn"
+ >
+) => {
+ return useQuery({
+ queryKey: secretInsightsKeys.blindIndexStatus(params),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<TGetSecretBlindIndexStatusResponse>(
+ `/api/v1/projects/${params.projectId}/secret-blind-index/status`
+ );
+ return data;
+ },
+ staleTime: 0,
+ ...options
+ });
+};
diff --git a/frontend/src/hooks/api/secretInsights/types.ts b/frontend/src/hooks/api/secretInsights/types.ts
index 60cc65a9ba..bab6742218 100644
--- a/frontend/src/hooks/api/secretInsights/types.ts
+++ b/frontend/src/hooks/api/secretInsights/types.ts
@@ -141,3 +141,12 @@ export type TGetSecretsDuplicationResponse = {
secretBlindIndexEnabled: boolean;
groups: TDuplicatedSecretGroup[];
};
+
+export type TGetSecretBlindIndexStatusDTO = {
+ projectId: string;
+};
+
+export type TGetSecretBlindIndexStatusResponse = {
+ status: "not-found" | "pending" | "completed" | "failed";
+ message?: string;
+};
diff --git a/frontend/src/pages/secret-manager/InsightsPage/components/DuplicatedSecretsCard.tsx b/frontend/src/pages/secret-manager/InsightsPage/components/DuplicatedSecretsCard.tsx
index 24246c8ddd..0cec8bb10b 100644
--- a/frontend/src/pages/secret-manager/InsightsPage/components/DuplicatedSecretsCard.tsx
+++ b/frontend/src/pages/secret-manager/InsightsPage/components/DuplicatedSecretsCard.tsx
@@ -1,4 +1,14 @@
-import { ArrowRightIcon, CopyIcon, FolderIcon, LinkIcon, LockIcon } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import {
+ AlertTriangleIcon,
+ ArrowRightIcon,
+ CopyIcon,
+ FolderIcon,
+ LinkIcon,
+ Loader2Icon,
+ LockIcon
+} from "lucide-react";
import {
Accordion,
@@ -19,7 +29,12 @@ import {
TooltipTrigger
} from "@app/components/v3";
import { useProject } from "@app/context";
-import { useGetSecretsDuplication } from "@app/hooks/api/secretInsights";
+import { useEnableSecretBlindIndex } from "@app/hooks/api/projects";
+import {
+ secretInsightsKeys,
+ useGetSecretBlindIndexStatus,
+ useGetSecretsDuplication
+} from "@app/hooks/api/secretInsights";
const ENVIRONMENT_COLOR_MAP: Record<string, string> = {
production: "bg-green-500",
@@ -34,6 +49,10 @@ const getEnvironmentDotColor = (slug: string) => {
export const DuplicatedSecretsCard = () => {
const { projectId } = useProject();
+ const queryClient = useQueryClient();
+ const [migrationTriggered, setMigrationTriggered] = useState(false);
+
+ const enableBlindIndex = useEnableSecretBlindIndex();
const { data, isPending } = useGetSecretsDuplication(
{ projectId },
@@ -43,6 +62,73 @@ export const DuplicatedSecretsCard = () => {
const groups = data?.groups ?? [];
const secretBlindIndexEnabled = data?.secretBlindIndexEnabled ?? true;
+ const shouldPollStatus =
+ !!projectId && !isPending && !secretBlindIndexEnabled;
+
+ const { data: statusData } = useGetSecretBlindIndexStatus(
+ { projectId },
+ {
+ enabled: shouldPollStatus,
+ refetchInterval: (query) => {
+ const status = query.state.data?.status;
+ if (status === "completed" || status === "failed" || status === "not-found") return false;
+ return 2000;
+ }
+ }
+ );
+
+ const migrationStatus = statusData?.status;
+
+ useEffect(() => {
+ if (migrationStatus === "pending") {
+ setMigrationTriggered(true);
+ }
+ }, [migrationStatus]);
+
+ useEffect(() => {
+ if (statusData?.status === "completed" && migrationTriggered) {
+ queryClient.invalidateQueries({
+ queryKey: secretInsightsKeys.secretsDuplication({ projectId })
+ });
+ setMigrationTriggered(false);
+ }
+ }, [statusData?.status, migrationTriggered, projectId, queryClient]);
+
+ const handleEnableClick = () => {
+ setMigrationTriggered(true);
+ enableBlindIndex.mutate(
+ { projectId },
+ {
+ onSuccess: () => {
+ queryClient.invalidateQueries({
+ // queryKey: secretInsightsKeys.blindIndexStatus({ projectId })
+ });
+ }
+ }
+ );
+ };
+
+ const handleRetryClick = () => {
+ setMigrationTriggered(true);
+ enableBlindIndex.reset();
+ enableBlindIndex.mutate(
+ { projectId },
+ {
+ onSuccess: () => {
+ queryClient.invalidateQueries({
+ queryKey: secretInsightsKeys.blindIndexStatus({ projectId })
+ });
+ }
+ }
+ );
+ };
+
+ const isMigrationRunning =
+ migrationTriggered && migrationStatus !== "completed" && migrationStatus !== "failed";
+ const isMigrationFailed = migrationStatus === "failed" && !enableBlindIndex.isPending;
+ const showEnableButton =
+ !secretBlindIndexEnabled && !isMigrationRunning && !isMigrationFailed;
+
return (
<Card>
<CardHeader>
@@ -54,9 +140,30 @@ export const DuplicatedSecretsCard = () => {
</CardHeader>
<CardContent>
{isPending && <Skeleton className="h-[280px] w-full" />}
- {!isPending && !secretBlindIndexEnabled && (
- <div className="flex h-[200px] items-center justify-center">
- <Button variant="outline">Enable Secret Duplication Detection</Button>
+ {!isPending && showEnableButton && (
+ <div className="flex h-[200px] flex-col items-center justify-center gap-3">
+ <Button variant="outline" onClick={handleEnableClick}>
+ Enable Secret Duplication Detection
+ </Button>
+ </div>
+ )}
+ {!isPending && isMigrationRunning && (
+ <div className="flex h-[200px] flex-col items-center justify-center gap-3">
+ <Loader2Icon className="size-6 animate-spin text-primary" />
+ <p className="text-sm text-muted">
+ Indexing secrets for duplicate detection. This may take a moment...
+ </p>
+ </div>
+ )}
+ {!isPending && isMigrationFailed && (
+ <div className="flex h-[200px] flex-col items-center justify-center gap-3">
+ <AlertTriangleIcon className="size-6 text-red-500" />
+ <p className="text-sm text-red-400">
+ Failed to index secrets: {statusData?.message ?? "Unknown error"}
+ </p>
+ <Button variant="outline" onClick={handleRetryClick}>
+ Retry
+ </Button>
</div>
)}
{!isPending && secretBlindIndexEnabled && groups.length === 0 && (