Skip to content

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

feat: add endpoint to support project warning

adilson4f2114e796a7
diff --git a/backend/e2e-test/product-insights-project-warnings.spec.ts b/backend/e2e-test/product-insights-project-warnings.spec.ts
new file mode 100644
index 0000000000..9f63403ef9
--- /dev/null
+++ b/backend/e2e-test/product-insights-project-warnings.spec.ts
@@ -0,0 +1,409 @@
+import { randomUUID } from "node:crypto";
+
+import { createMongoAbility, ForbiddenError, MongoAbility } from "@casl/ability";
+import { Knex } from "knex";
+import { afterAll, beforeAll, describe, expect, test } from "vitest";
+
+import {
+ ProjectType,
+ ProjectVersion,
+ TableName,
+ TAppConnectionsInsert,
+ TDynamicSecretLeasesInsert,
+ TDynamicSecretsInsert,
+ TOrganizationsInsert,
+ TProjectEnvironmentsInsert,
+ TProjectsInsert,
+ TSecretFoldersInsert,
+ TSecretRotationsV2Insert,
+ TSecretsV2Insert,
+ TSecretSyncsInsert,
+ TUsersInsert
+} from "@app/db/schemas";
+import { DynamicSecretLeaseStatus } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-types";
+import { TFeatureSet } from "@app/ee/services/license/license-types";
+import {
+ OrgPermissionSecretsManagementInsightsActions,
+ OrgPermissionSet,
+ OrgPermissionSubjects
+} from "@app/ee/services/permission/org-permission";
+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import { productInsightsDALFactory } from "@app/ee/services/product-insights/product-insights-dal";
+import { productInsightsServiceFactory } from "@app/ee/services/product-insights/product-insights-service";
+import { TGetSecretsProjectWarningsDTO } from "@app/ee/services/product-insights/product-insights-types";
+import { SecretRotationStatus } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-enums";
+import { ActorType, AuthMethod } from "@app/services/auth/auth-type";
+import { SecretSyncStatus } from "@app/services/secret-sync/secret-sync-types";
+
+declare const testDb: Knex;
+
+const ORG_ID = randomUUID();
+const OTHER_ORG_ID = randomUUID();
+const suffix = randomUUID().slice(0, 8);
+
+const USER_ID = randomUUID();
+const CONNECTION_ID = randomUUID();
+
+// Project names are chosen so the severity tiebreak (name asc) yields a
+// deterministic order: warn ranks first by score, then clean/noBlindIndex/
+// deletedEnv alphabetically.
+const projects = {
+ // Every issue type at once
+ warn: { projectId: randomUUID(), envId: randomUUID(), folderId: randomUUID(), name: `zz-warn-${suffix}` },
+ // No issues at all
+ clean: { projectId: randomUUID(), envId: randomUUID(), folderId: randomUUID(), name: `aa-clean-${suffix}` },
+ // Blind indexing disabled: duplicated metric must be null even with matching indexes
+ noBlindIndex: {
+ projectId: randomUUID(),
+ envId: randomUUID(),
+ folderId: randomUUID(),
+ name: `bb-noblind-${suffix}`
+ },
+ // Live project whose only environment is soft-deleted: all counts must be zero
+ deletedEnv: { projectId: randomUUID(), envId: randomUUID(), folderId: randomUUID(), name: `cc-delenv-${suffix}` },
+ // Filtered out of the listing entirely
+ otherProductType: { projectId: randomUUID(), envId: randomUUID(), folderId: randomUUID(), name: `pam-${suffix}` },
+ deletedProject: { projectId: randomUUID(), envId: randomUUID(), folderId: randomUUID(), name: `del-${suffix}` },
+ oldVersion: { projectId: randomUUID(), envId: randomUUID(), folderId: randomUUID(), name: `v1-${suffix}` },
+ otherOrg: { projectId: randomUUID(), envId: randomUUID(), folderId: randomUUID(), name: `other-${suffix}` }
+};
+
+const projectList = Object.values(projects);
+
+const DYNAMIC_SECRET_ID = randomUUID();
+
+const buildPermission = (canRead: boolean): MongoAbility<OrgPermissionSet> =>
+ createMongoAbility<OrgPermissionSet>(
+ canRead
+ ? [
+ {
+ action: OrgPermissionSecretsManagementInsightsActions.Read,
+ subject: OrgPermissionSubjects.SecretsManagementInsights
+ }
+ ]
+ : []
+ );
+
+let canReadInsights = true;
+let planHasInsights = true;
+
+const permissionService: Pick<TPermissionServiceFactory, "getOrgPermission"> = {
+ getOrgPermission: async () => ({
+ permission: buildPermission(canReadInsights),
+ memberships: [],
+ hasRole: () => false
+ })
+};
+
+const licenseService = {
+ getPlan: async () => ({ secretAccessInsights: planHasInsights }) as unknown as TFeatureSet
+};
+
+const productInsightsService = productInsightsServiceFactory({
+ permissionService,
+ licenseService,
+ orgDAL: { countAllOrgMembers: async () => 0 },
+ identityOrgMembershipDAL: { countAllOrgIdentities: async () => 0 },
+ dynamicSecretLeaseDAL: { countLeasesForOrg: async () => 0 },
+ productInsightsDAL: productInsightsDALFactory(testDb),
+ // Pass-through stub: every read misses so each call hits the database directly.
+ keyStore: { getItem: async () => null, setItemWithExpiry: async () => "OK" }
+});
+
+const actor = (orgId: string, page?: { offset: number; limit: number }): TGetSecretsProjectWarningsDTO => ({
+ actor: ActorType.USER,
+ actorId: USER_ID,
+ actorAuthMethod: AuthMethod.EMAIL,
+ actorOrgId: orgId,
+ orgId,
+ offset: page?.offset ?? 0,
+ limit: page?.limit ?? 20
+});
+
+const secret = (folderId: string, overrides: Partial<TSecretsV2Insert> = {}): TSecretsV2Insert & { id: string } => ({
+ id: randomUUID(),
+ key: `SECRET_${randomUUID().slice(0, 8)}`,
+ folderId,
+ ...overrides
+});
+
+describe("product-insights secrets project warnings", () => {
+ beforeAll(async () => {
+ const orgRows: (TOrganizationsInsert & { id: string })[] = [
+ { id: ORG_ID, name: `warnings-${suffix}`, slug: `warnings-${suffix}` },
+ { id: OTHER_ORG_ID, name: `warnings-other-${suffix}`, slug: `warnings-other-${suffix}` }
+ ];
+ await testDb(TableName.Organization).insert(orgRows);
+
+ // Owner of the personal-override secret that must be excluded from counts
+ const userRows: (TUsersInsert & { id: string })[] = [
+ { id: USER_ID, username: `warnings-user-${suffix}`, isAccepted: true, isGhost: false }
+ ];
+ await testDb(TableName.Users).insert(userRows);
+
+ const projectRows: (TProjectsInsert & { id: string })[] = projectList.map((p) => ({
+ id: p.projectId,
+ name: p.name,
+ slug: p.name,
+ orgId: p === projects.otherOrg ? OTHER_ORG_ID : ORG_ID,
+ type: p === projects.otherProductType ? ProjectType.PAM : ProjectType.SecretManager,
+ // The listing only covers v3 projects (the column defaults to v1)
+ version: p === projects.oldVersion ? ProjectVersion.V1 : ProjectVersion.V3,
+ ...(p === projects.deletedProject ? { deleteAfter: new Date() } : {}),
+ ...(p === projects.noBlindIndex ? { secretBlindIndexEnabled: false } : { secretBlindIndexEnabled: true })
+ }));
+ await testDb(TableName.Project).insert(projectRows);
+
+ const environmentRows: (TProjectEnvironmentsInsert & { id: string })[] = projectList.map((p, index) => ({
+ id: p.envId,
+ name: "Development",
+ slug: "dev",
+ position: index + 1,
+ projectId: p.projectId,
+ ...(p === projects.deletedEnv ? { deleteAfter: new Date() } : {})
+ }));
+ await testDb(TableName.Environment).insert(environmentRows);
+
+ const folderRows: (TSecretFoldersInsert & { id: string })[] = projectList.map((p) => ({
+ id: p.folderId,
+ name: "root",
+ envId: p.envId,
+ parentId: null
+ }));
+ await testDb(TableName.SecretFolder).insert(folderRows);
+
+ const staleDate = new Date();
+ staleDate.setDate(staleDate.getDate() - 100);
+
+ // The stale fixtures set updatedAt at INSERT time: secrets_v2 has an
+ // on-update trigger that resets updatedAt to now() on every UPDATE, so
+ // backdating after the fact is impossible. The typed insert omits the
+ // immutable updatedAt column, hence the cast.
+ const backdated = { updatedAt: staleDate } as Partial<TSecretsV2Insert>;
+ const secretRows: (TSecretsV2Insert & { id: string })[] = [
+ // warn: 2 duplicates + 1 stale + 1 fresh = 4 shared secrets
+ secret(projects.warn.folderId, { secretValueBlindIndex: `dup-${suffix}` }),
+ secret(projects.warn.folderId, { secretValueBlindIndex: `dup-${suffix}` }),
+ secret(projects.warn.folderId, { secretValueBlindIndex: `stale-${suffix}`, ...backdated }),
+ secret(projects.warn.folderId),
+ // personal override: excluded from every count
+ secret(projects.warn.folderId, { userId: USER_ID, type: "personal" }),
+ // clean: a single fresh secret
+ secret(projects.clean.folderId),
+ // noBlindIndex: matching indexes, but the project has blind indexing disabled
+ secret(projects.noBlindIndex.folderId, { secretValueBlindIndex: `dup-nbi-${suffix}` }),
+ secret(projects.noBlindIndex.folderId, { secretValueBlindIndex: `dup-nbi-${suffix}` }),
+ // deletedEnv: a stale secret behind a soft-deleted environment must not count
+ secret(projects.deletedEnv.folderId, { secretValueBlindIndex: `stale-denv-${suffix}`, ...backdated })
+ ];
+ await testDb(TableName.SecretV2).insert(secretRows);
+
+ const connectionRows: (TAppConnectionsInsert & { id: string })[] = [
+ {
+ id: CONNECTION_ID,
+ name: `conn-${suffix}`,
+ app: "postgres",
+ method: "username-and-password",
+ encryptedCredentials: Buffer.from("{}"),
+ orgId: ORG_ID
+ }
+ ];
+ await testDb(TableName.AppConnection).insert(connectionRows);
+
+ const rotation = (folderId: string, rotationStatus: string): TSecretRotationsV2Insert & { id: string } => ({
+ id: randomUUID(),
+ name: `rot-${randomUUID().slice(0, 8)}`,
+ type: "postgres-credentials",
+ parameters: {},
+ secretsMapping: {},
+ encryptedGeneratedCredentials: Buffer.from("{}"),
+ folderId,
+ connectionId: CONNECTION_ID,
+ rotationInterval: 30,
+ rotateAtUtc: { hours: 0, minutes: 0 },
+ rotationStatus,
+ lastRotationAttemptedAt: new Date(),
+ lastRotatedAt: new Date()
+ });
+ await testDb(TableName.SecretRotationV2).insert([
+ rotation(projects.warn.folderId, SecretRotationStatus.Failed),
+ // successful rotations must not count
+ rotation(projects.warn.folderId, SecretRotationStatus.Success),
+ // failed rotation behind a soft-deleted environment must not count
+ rotation(projects.deletedEnv.folderId, SecretRotationStatus.Failed)
+ ]);
+
+ const sync = (projectId: string, syncStatus: string): TSecretSyncsInsert & { id: string } => ({
+ id: randomUUID(),
+ name: `sync-${randomUUID().slice(0, 8)}`,
+ destination: "aws-parameter-store",
+ destinationConfig: {},
+ syncOptions: {},
+ projectId,
+ connectionId: CONNECTION_ID,
+ syncStatus
+ });
+ await testDb(TableName.SecretSync).insert([
+ sync(projects.warn.projectId, SecretSyncStatus.Failed),
+ // succeeded syncs must not count
+ sync(projects.warn.projectId, SecretSyncStatus.Succeeded),
+ // failed sync in a soft-deleted project must not count
+ sync(projects.deletedProject.projectId, SecretSyncStatus.Failed)
+ ]);
+
+ const dynamicSecretRows: (TDynamicSecretsInsert & { id: string })[] = [
+ {
+ id: DYNAMIC_SECRET_ID,
+ name: `dyn-${suffix}`,
+ version: 1,
+ type: "sql-database",
+ defaultTTL: "1h",
+ folderId: projects.warn.folderId,
+ encryptedInput: Buffer.from("{}")
+ }
+ ];
+ await testDb(TableName.DynamicSecret).insert(dynamicSecretRows);
+
+ const lease = (status?: string): TDynamicSecretLeasesInsert & { id: string } => ({
+ id: randomUUID(),
+ version: 1,
+ externalEntityId: `ext-${randomUUID().slice(0, 8)}`,
+ expireAt: new Date(Date.now() + 60 * 60 * 1000),
+ dynamicSecretId: DYNAMIC_SECRET_ID,
+ ...(status ? { status } : {})
+ });
+ await testDb(TableName.DynamicSecretLease).insert([
+ lease(DynamicSecretLeaseStatus.FailedDeletion),
+ // healthy active leases must not count as orphaned
+ lease()
+ ]);
+ });
+
+ afterAll(async () => {
+ const orgIds = [ORG_ID, OTHER_ORG_ID];
+ await testDb(TableName.DynamicSecretLease).where("dynamicSecretId", DYNAMIC_SECRET_ID).delete();
+ await testDb(TableName.DynamicSecret).where("id", DYNAMIC_SECRET_ID).delete();
+ await testDb(TableName.SecretRotationV2).where("connectionId", CONNECTION_ID).delete();
+ await testDb(TableName.SecretSync).where("connectionId", CONNECTION_ID).delete();
+ await testDb(TableName.AppConnection).where("id", CONNECTION_ID).delete();
+ await testDb(TableName.SecretV2)
+ .whereIn(
+ "folderId",
+ projectList.map((p) => p.folderId)
+ )
+ .delete();
+ await testDb(TableName.SecretFolder)
+ .whereIn(
+ "id",
+ projectList.map((p) => p.folderId)
+ )
+ .delete();
+ await testDb(TableName.Environment)
+ .whereIn(
+ "id",
+ projectList.map((p) => p.envId)
+ )
+ .delete();
+ await testDb(TableName.Project).whereIn("orgId", orgIds).delete();
+ await testDb(TableName.Users).where("id", USER_ID).delete();
+ await testDb(TableName.Organization).whereIn("id", orgIds).delete();
+ });
+
+ test("returns all secret-manager projects ordered by severity with correct counts", async () => {
+ const result = await productInsightsService.getSecretsProjectWarnings(actor(ORG_ID));
+
+ // warn, clean, noBlindIndex, deletedEnv. The PAM project, the soft-deleted
+ // project, the v1 project and the other org's project are excluded from the listing.
+ expect(result.totalProjects).toBe(4);
+ expect(result.projectsWithIssues).toBe(1);
+ expect(result.projects).toHaveLength(4);
+
+ // warn ranks first by score; the rest tie at zero and sort by name.
+ expect(result.projects.map((p) => p.projectName)).toEqual([
+ projects.warn.name,
+ projects.clean.name,
+ projects.noBlindIndex.name,
+ projects.deletedEnv.name
+ ]);
+
+ const warn = result.projects[0];
+ expect(warn).toMatchObject({
+ projectId: projects.warn.projectId,
+ // The personal override secret is excluded
+ totalSecrets: 4,
+ warnings: {
+ duplicatedSecrets: 2,
+ staleSecrets: 1,
+ failedRotations: 1,
+ failedSyncs: 1,
+ orphanedLeases: 1
+ }
+ });
+ expect(warn.severityScore).toBeGreaterThan(0);
+
+ const clean = result.projects.find((p) => p.projectId === projects.clean.projectId);
+ expect(clean).toMatchObject({
+ totalSecrets: 1,
+ severityScore: 0,
+ warnings: {
+ duplicatedSecrets: 0,
+ staleSecrets: 0,
+ failedRotations: 0,
+ failedSyncs: 0,
+ orphanedLeases: 0
+ }
+ });
+
+ // Blind indexing disabled: the duplicated metric is unknowable, not zero
+ const noBlindIndex = result.projects.find((p) => p.projectId === projects.noBlindIndex.projectId);
+ expect(noBlindIndex?.warnings.duplicatedSecrets).toBeNull();
+ expect(noBlindIndex?.severityScore).toBe(0);
+
+ // Soft-deleted environment: its stale secret and failed rotation contribute nothing
+ const deletedEnv = result.projects.find((p) => p.projectId === projects.deletedEnv.projectId);
+ expect(deletedEnv).toMatchObject({
+ totalSecrets: 0,
+ severityScore: 0,
+ warnings: { staleSecrets: 0, failedRotations: 0 }
+ });
+ });
+
+ test("pagination slices rows while window totals stay constant", async () => {
+ const page = await productInsightsService.getSecretsProjectWarnings(actor(ORG_ID, { offset: 1, limit: 2 }));
+
+ expect(page.totalProjects).toBe(4);
+ expect(page.projectsWithIssues).toBe(1);
+ expect(page.offset).toBe(1);
+ expect(page.limit).toBe(2);
+ expect(page.projects.map((p) => p.projectName)).toEqual([projects.clean.name, projects.noBlindIndex.name]);
+ });
+
+ test("an organization with no projects reports empty results", async () => {
+ const result = await productInsightsService.getSecretsProjectWarnings(actor(randomUUID()));
+ expect(result.projects).toEqual([]);
+ expect(result.totalProjects).toBe(0);
+ expect(result.projectsWithIssues).toBe(0);
+ });
+
+ test("throws when the actor cannot read secrets management insights", async () => {
+ canReadInsights = false;
+ try {
+ await expect(productInsightsService.getSecretsProjectWarnings(actor(ORG_ID))).rejects.toBeInstanceOf(
+ ForbiddenError
+ );
+ } finally {
+ canReadInsights = true;
+ }
+ });
+
+ test("throws when the plan does not include secret access insights", async () => {
+ planHasInsights = false;
+ try {
+ await expect(productInsightsService.getSecretsProjectWarnings(actor(ORG_ID))).rejects.toThrow(
+ /Upgrade your plan/
+ );
+ } finally {
+ planHasInsights = true;
+ }
+ });
+});
diff --git a/backend/e2e-test/product-insights-service.spec.ts b/backend/e2e-test/product-insights-service.spec.ts
index 1d1250a5d2..016393715d 100644
--- a/backend/e2e-test/product-insights-service.spec.ts
+++ b/backend/e2e-test/product-insights-service.spec.ts
@@ -27,6 +27,7 @@ import {
OrgPermissionSubjects
} from "@app/ee/services/permission/org-permission";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import { productInsightsDALFactory } from "@app/ee/services/product-insights/product-insights-dal";
import { productInsightsServiceFactory } from "@app/ee/services/product-insights/product-insights-service";
import { TProductInsightsDTO } from "@app/ee/services/product-insights/product-insights-types";
import { ActorType, AuthMethod } from "@app/services/auth/auth-type";
@@ -110,7 +111,10 @@ const productInsightsService = productInsightsServiceFactory({
licenseService,
orgDAL: orgDALFactory(testDb),
identityOrgMembershipDAL: identityOrgDALFactory(testDb),
- dynamicSecretLeaseDAL: dynamicSecretLeaseDALFactory(testDb)
+ dynamicSecretLeaseDAL: dynamicSecretLeaseDALFactory(testDb),
+ productInsightsDAL: productInsightsDALFactory(testDb),
+ // Pass-through stub: every read misses so each call hits the database directly.
+ keyStore: { getItem: async () => null, setItemWithExpiry: async () => "OK" }
});
const actor = (orgId: string): TProductInsightsDTO => ({
diff --git a/backend/e2e-test/routes/v1/product-insights.spec.ts b/backend/e2e-test/routes/v1/product-insights.spec.ts
index 7162473b01..d604e7707f 100644
--- a/backend/e2e-test/routes/v1/product-insights.spec.ts
+++ b/backend/e2e-test/routes/v1/product-insights.spec.ts
@@ -6,11 +6,6 @@ const URL = "/api/v1/product-insights/secrets/usage-insights";
// This file only asserts the route wiring, because the e2e instance runs unlicensed and the plan gate
// therefore rejects every request before any count is taken.
describe("Product Insights V1 Router", async () => {
- test("GET usage insights requires authentication", async () => {
- const res = await testServer.inject({ method: "GET", url: URL });
- expect(res.statusCode).toBe(401);
- });
-
test("GET usage insights is registered and refuses on plan restriction", async () => {
const res = await testServer.inject({
method: "GET",
@@ -23,4 +18,28 @@ describe("Product Insights V1 Router", async () => {
expect(res.statusCode).toBe(400);
expect(res.json().message).toContain("Upgrade your plan");
});
+
+ const WARNINGS_URL = "/api/v1/product-insights/secrets/project-warnings";
+
+ test("GET project warnings is registered and refuses on plan restriction", async () => {
+ const res = await testServer.inject({
+ method: "GET",
+ url: WARNINGS_URL,
+ headers: { authorization: `Bearer ${jwtAuthToken}` }
+ });
+
+ expect(res.statusCode).toBe(400);
+ expect(res.json().message).toContain("Upgrade your plan");
+ });
+
+ test("GET project warnings rejects an out-of-bounds limit", async () => {
+ const res = await testServer.inject({
+ method: "GET",
+ url: `${WARNINGS_URL}?limit=500`,
+ headers: { authorization: `Bearer ${jwtAuthToken}` }
+ });
+
+ // Schema validation failures map to 422 (ValidationError in error-handler.ts)
+ expect(res.statusCode).toBe(422);
+ });
});
diff --git a/backend/src/ee/routes/v1/product-insights-router.ts b/backend/src/ee/routes/v1/product-insights-router.ts
index c383d901f6..fe3e61bf81 100644
--- a/backend/src/ee/routes/v1/product-insights-router.ts
+++ b/backend/src/ee/routes/v1/product-insights-router.ts
@@ -1,7 +1,11 @@
import { z } from "zod";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
-import { SecretsUsageInsightsSchema } from "@app/ee/services/product-insights/product-insights-schemas";
+import {
+ SecretsProjectWarningsSchema,
+ SecretsUsageInsightsSchema
+} from "@app/ee/services/product-insights/product-insights-schemas";
+import { PRODUCT_INSIGHTS } from "@app/lib/api-docs";
import { readLimit } from "@app/server/config/rateLimiter";
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
import { AuthMode } from "@app/services/auth/auth-type";
@@ -44,4 +48,66 @@ export const registerProductInsightsRouter = async (server: FastifyZodProvider)
return { usageInsights };
}
});
+
+ server.route({
+ method: "GET",
+ url: "/secrets/project-warnings",
+ config: {
+ rateLimit: readLimit
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ schema: {
+ operationId: "getSecretsProjectWarnings",
+ description:
+ "List the organization's secret management projects with outstanding issue counts, ordered by severity.",
+ querystring: z.object({
+ offset: z.coerce
+ .number()
+ .int()
+ .min(0)
+ .max(10000)
+ .default(0)
+ .describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.offset),
+ limit: z.coerce
+ .number()
+ .int()
+ .min(1)
+ .max(100)
+ .default(20)
+ .describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.limit)
+ }),
+ response: {
+ 200: z.object({
+ projectWarnings: SecretsProjectWarningsSchema
+ })
+ }
+ },
+ handler: async (req) => {
+ const projectWarnings = await server.services.productInsights.getSecretsProjectWarnings({
+ actor: req.permission.type,
+ actorId: req.permission.id,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId,
+ orgId: req.permission.orgId,
+ offset: req.query.offset,
+ limit: req.query.limit
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ event: {
+ type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_PROJECT_WARNINGS,
+ metadata: {
+ totalProjects: projectWarnings.totalProjects,
+ projectsWithIssues: projectWarnings.projectsWithIssues,
+ offset: req.query.offset,
+ limit: req.query.limit
+ }
+ }
+ });
+
+ return { projectWarnings };
+ }
+ });
};
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 1adae48a14..cf5472214c 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -682,6 +682,7 @@ export enum EventType {
VIEW_INSIGHTS_SECRETS_DUPLICATION = "view-insights-secrets-duplication",
VIEW_INSIGHTS_SECRETS_MANAGEMENT_COUNTS = "view-insights-secrets-management-counts",
VIEW_INSIGHTS_SECRETS_MANAGEMENT_USAGE = "view-insights-secrets-management-usage",
+ VIEW_INSIGHTS_SECRETS_MANAGEMENT_PROJECT_WARNINGS = "view-insights-secrets-management-project-warnings",
CREATE_AUDIT_REPORT = "create-audit-report",
GET_AUDIT_REPORTS = "get-audit-reports",
@@ -5530,6 +5531,16 @@ interface ViewSecretManagementInsightsUsageEvent {
};
}
+interface ViewSecretManagementInsightsProjectWarningsEvent {
+ type: EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_PROJECT_WARNINGS;
+ metadata: {
+ totalProjects: number;
+ projectsWithIssues: number;
+ offset: number;
+ limit: number;
+ };
+}
+
interface CreateAuditReportEvent {
type: EventType.CREATE_AUDIT_REPORT;
metadata: {
@@ -7481,6 +7492,7 @@ export type Event =
| ViewInsightsSecretsDuplicationEvent
| ViewSecretManagementInsightsCountsEvent
| ViewSecretManagementInsightsUsageEvent
+ | ViewSecretManagementInsightsProjectWarningsEvent
| CreateAuditReportEvent
| GetAuditReportsEvent
| GetAuditReportEvent
diff --git a/backend/src/ee/services/product-insights/product-insights-dal.ts b/backend/src/ee/services/product-insights/product-insights-dal.ts
new file mode 100644
index 0000000000..112de82cc2
--- /dev/null
+++ b/backend/src/ee/services/product-insights/product-insights-dal.ts
@@ -0,0 +1,238 @@
+import { Knex } from "knex";
+
+import { TDbClient } from "@app/db";
+import { ProjectType, ProjectVersion, TableName } from "@app/db/schemas";
+import { DynamicSecretLeaseStatus } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-types";
+import { SecretRotationStatus } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-enums";
+import { DatabaseError } from "@app/lib/errors";
+import { SecretSyncStatus } from "@app/services/secret-sync/secret-sync-types";
+
+import { TSecretsProjectWarning } from "./product-insights-types";
+
+// Relative severity weights for ranking projects by outstanding issues. Failed
+// rotations are the most urgent signal (a credential that should have changed
+// did not); duplicated secrets are the weakest (see the approximation note on
+// the duplicate_groups CTE below).
+export const PROJECT_WARNING_SEVERITY_WEIGHTS = {
+ failedRotation: 100,
+ failedSync: 50,
+ orphanedLease: 25,
+ staleSecret: 5,
+ duplicatedSecret: 1
+} as const;
+
+type TProjectWarningRow = {
+ projectId: string;
+ projectName: string;
+ projectSlug: string;
+ totalSecrets: string | number;
+ staleSecrets: string | number;
+ duplicatedSecrets: string | number | null;
+ failedRotations: string | number;
+ failedSyncs: string | number;
+ orphanedLeases: string | number;
+ severityScore: string | number;
+ totalProjects: string | number;
+ projectsWithIssues: string | number;
+};
+
+export type TProductInsightsDALFactory = ReturnType<typeof productInsightsDALFactory>;
+
+export const productInsightsDALFactory = (db: TDbClient) => {
+ const findProjectWarningsForOrg = async (
+ orgId: string,
+ { offset, limit, staleBefore }: { offset: number; limit: number; staleBefore: Date },
+ tx?: Knex
+ ): Promise<{ projects: TSecretsProjectWarning[]; totalProjects: number; projectsWithIssues: number }> => {
+ try {
+ const conn = tx || db.replicaNode();
+ const weights = PROJECT_WARNING_SEVERITY_WEIGHTS;
+
+ const rows = await conn
+ // Every secret-manager project of the org, returned even with zero issues
+ .with("org_projects", (qb) =>
+ qb
+ .from(TableName.Project)
+ .where(`${TableName.Project}.orgId`, orgId)
+ .whereNull(`${TableName.Project}.deleteAfter`)
+ .where(`${TableName.Project}.type`, ProjectType.SecretManager)
+ .where(`${TableName.Project}.version`, ProjectVersion.V3) // only secret-manager v3 projects are supported
+ .select(
+ `${TableName.Project}.id`,
+ `${TableName.Project}.name`,
+ `${TableName.Project}.slug`,
+ `${TableName.Project}.secretBlindIndexEnabled`
+ )
+ )
+ // totalSecrets + staleSecrets share one scan via FILTER. Mirrors
+ // countByProject / countStaleByProject in secret-v2-bridge-dal.ts:
+ // exclude personal/override secrets, skip soft-deleted environments.
+ .with("secret_counts", (qb) =>
+ qb
+ .from(TableName.SecretV2)
+ .join(TableName.SecretFolder, `${TableName.SecretV2}.folderId`, `${TableName.SecretFolder}.id`)
+ .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)
+ .join("org_projects", `${TableName.Environment}.projectId`, "org_projects.id")
+ .whereNull(`${TableName.Environment}.deleteAfter`)
+ .whereNull(`${TableName.SecretV2}.userId`)
+ .groupBy(`${TableName.Environment}.projectId`)
+ .select(`${TableName.Environment}.projectId`)
+ .select(db.raw(`count(*) as "totalSecrets"`))
+ .select(
+ db.raw(`count(*) filter (where ??.?? < ?) as "staleSecrets"`, [
+ TableName.SecretV2,
+ "updatedAt",
+ staleBefore
+ ])
+ )
+ )
+ // Duplicated secrets: secrets sharing a value blind index within a project.
+ //
+ // APPROXIMATION: unlike the per-project insights endpoint
+ // (insights-service.ts getSecretsDuplication), this is SQL-only and does
+ // NOT decrypt values to exclude secret references (`${...}` interpolation),
+ // because decrypting every secret of every project in the org is
+ // prohibitively expensive for a paginated org-level listing. Secrets that
+ // merely reference the same secret are therefore counted as duplicates
+ // here, so this count can be slightly higher than the duplication insight.
+ // TODO: perform a load testing to check how bad this can be for large orgs.
+ .with("duplicate_groups", (qb) =>
+ qb
+ .from(TableName.SecretV2)
+ .join(TableName.SecretFolder, `${TableName.SecretV2}.folderId`, `${TableName.SecretFolder}.id`)
+ .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)
+ .join("org_projects", `${TableName.Environment}.projectId`, "org_projects.id")
+ .whereNull(`${TableName.Environment}.deleteAfter`)
+ .whereNull(`${TableName.SecretV2}.userId`)
+ .whereNotNull(`${TableName.SecretV2}.secretValueBlindIndex`)
+ .groupBy([`${TableName.Environment}.projectId`, `${TableName.SecretV2}.secretValueBlindIndex`])
+ .having(db.raw("count(*) > 1"))
+ .select(`${TableName.Environment}.projectId`)
+ .select(db.raw(`count(*) as "dupCount"`))
+ )
+ .with("duplicated_counts", (qb) =>
+ qb.from("duplicate_groups").groupBy("projectId").select("projectId").sum("dupCount as duplicatedSecrets")
+ )
+ .with("failed_rotations", (qb) =>
+ qb
+ .from(TableName.SecretRotationV2)
+ .join(TableName.SecretFolder, `${TableName.SecretRotationV2}.folderId`, `${TableName.SecretFolder}.id`)
+ .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)
+ .join("org_projects", `${TableName.Environment}.projectId`, "org_projects.id")
+ .whereNull(`${TableName.Environment}.deleteAfter`)
+ .where(`${TableName.SecretRotationV2}.rotationStatus`, SecretRotationStatus.Failed)
+ .groupBy(`${TableName.Environment}.projectId`)
+ .select(`${TableName.Environment}.projectId`)
+ .select(db.raw(`count(*) as "failedRotations"`))
+ )
+ .with("failed_syncs", (qb) =>
+ qb
+ .from(TableName.SecretSync)
+ .join("org_projects", `${TableName.SecretSync}.projectId`, "org_projects.id")
+ .where(`${TableName.SecretSync}.syncStatus`, SecretSyncStatus.Failed)
+ .groupBy(`${TableName.SecretSync}.projectId`)
+ .select(`${TableName.SecretSync}.projectId`)
+ .select(db.raw(`count(*) as "failedSyncs"`))
+ )
+ // Leases are hard-deleted on successful revocation/expiry (see the
+ // countLeasesForOrg comment in dynamic-secret-lease-dal.ts), so any
+ // surviving row with FailedDeletion status is an orphaned credential
+ // that needs manual cleanup.
+ .with("orphaned_leases", (qb) =>
+ qb
+ .from(TableName.DynamicSecretLease)
+ .join(
+ TableName.DynamicSecret,
+ `${TableName.DynamicSecretLease}.dynamicSecretId`,
+ `${TableName.DynamicSecret}.id`
+ )
+ .join(TableName.SecretFolder, `${TableName.DynamicSecret}.folderId`, `${TableName.SecretFolder}.id`)
+ .join(TableName.Environment, `${TableName.SecretFolder}.envId`, `${TableName.Environment}.id`)
+ .join("org_projects", `${TableName.Environment}.projectId`, "org_projects.id")
+ .whereNull(`${TableName.Environment}.deleteAfter`)
+ .where(`${TableName.DynamicSecretLease}.status`, DynamicSecretLeaseStatus.FailedDeletion)
+ .groupBy(`${TableName.Environment}.projectId`)
+ .select(`${TableName.Environment}.projectId`)
+ .select(db.raw(`count(*) as "orphanedLeases"`))
+ )
+ // Wrapping the scored rows in a CTE lets the outer query reference
+ // "severityScore" in ORDER BY and in the FILTER window without
+ // repeating the weighted-sum expression.
+ .with("scored", (qb) =>
+ qb
+ .from("org_projects as p")
+ .leftJoin("secret_counts as sc", "sc.projectId", "p.id")
+ .leftJoin("duplicated_counts as dc", "dc.projectId", "p.id")
+ .leftJoin("failed_rotations as fr", "fr.projectId", "p.id")
+ .leftJoin("failed_syncs as fs", "fs.projectId", "p.id")
+ .leftJoin("orphaned_leases as ol", "ol.projectId", "p.id")
+ .select(
+ "p.id as projectId",
+ "p.name as projectName",
+ "p.slug as projectSlug",
+ db.raw(`coalesce(sc."totalSecrets", 0) as "totalSecrets"`),
+ db.raw(`coalesce(sc."staleSecrets", 0) as "staleSecrets"`),
+ // null (not 0) when blind indexing is off: the metric is unknowable, not zero
+ db.raw(
+ `case when p."secretBlindIndexEnabled" then coalesce(dc."duplicatedSecrets", 0) else null end as "duplicatedSecrets"`
+ ),
+ db.raw(`coalesce(fr."failedRotations", 0) as "failedRotations"`),
+ db.raw(`coalesce(fs."failedSyncs", 0) as "failedSyncs"`),
+ db.raw(`coalesce(ol."orphanedLeases", 0) as "orphanedLeases"`),
+ db.raw(
+ `(? * coalesce(fr."failedRotations", 0)
+ + ? * coalesce(fs."failedSyncs", 0)
+ + ? * coalesce(ol."orphanedLeases", 0)
+ + ? * coalesce(sc."staleSecrets", 0)
+ + ? * (case when p."secretBlindIndexEnabled" then coalesce(dc."duplicatedSecrets", 0) else 0 end)
+ ) as "severityScore"`,
+ [
+ weights.failedRotation,
+ weights.failedSync,
+ weights.orphanedLease,
+ weights.staleSecret,
+ weights.duplicatedSecret
+ ]
+ )
+ )
+ )
+ .from<TProjectWarningRow>("scored")
+ .select("scored.*")
+ .select(db.raw(`count(*) over() as "totalProjects"`))
+ .select(db.raw(`count(*) filter (where "severityScore" > 0) over() as "projectsWithIssues"`))
+ .orderByRaw(`"severityScore" desc, "projectName" asc, "projectId" asc`)
+ .offset(offset)
+ .limit(limit);
+
+ const typedRows = rows as unknown as TProjectWarningRow[];
+
+ const projects = typedRows.map((row) => ({
+ projectId: row.projectId,
+ projectName: row.projectName,
+ projectSlug: row.projectSlug,
+ totalSecrets: Number(row.totalSecrets),
+ severityScore: Number(row.severityScore),
+ warnings: {
+ duplicatedSecrets: row.duplicatedSecrets === null ? null : Number(row.duplicatedSecrets),
+ staleSecrets: Number(row.staleSecrets),
+ failedRotations: Number(row.failedRotations),
+ failedSyncs: Number(row.failedSyncs),
+ orphanedLeases: Number(row.orphanedLeases)
+ }
+ }));
+
+ // Window totals are only recoverable from a returned row; an empty page
+ // (no projects, or the client paged past the end) reports zeros, matching
+ // the searchProjects precedent in project-dal.ts.
+ return {
+ projects,
+ totalProjects: Number(typedRows[0]?.totalProjects ?? 0),
+ projectsWithIssues: Number(typedRows[0]?.projectsWithIssues ?? 0)
+ };
+ } catch (error) {
+ throw new DatabaseError({ error, name: "FindProjectWarningsForOrg" });
+ }
+ };
+
+ return { findProjectWarningsForOrg };
+};
diff --git a/backend/src/ee/services/product-insights/product-insights-schemas.ts b/backend/src/ee/services/product-insights/product-insights-schemas.ts
index 2d015d417d..7836fcb0e5 100644
--- a/backend/src/ee/services/product-insights/product-insights-schemas.ts
+++ b/backend/src/ee/services/product-insights/product-insights-schemas.ts
@@ -7,3 +7,32 @@ export const SecretsUsageInsightsSchema = z.object({
users: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_USAGE_INSIGHTS.users),
identities: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_USAGE_INSIGHTS.identities)
});
+
+export const SecretsProjectWarningSchema = z.object({
+ projectId: z.string().uuid().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.projectId),
+ projectName: z.string().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.projectName),
+ projectSlug: z.string().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.projectSlug),
+ totalSecrets: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.totalSecrets),
+ severityScore: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.severityScore),
+ warnings: z
+ .object({
+ duplicatedSecrets: z
+ .number()
+ .int()
+ .nullable()
+ .describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.duplicatedSecrets),
+ staleSecrets: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.staleSecrets),
+ failedRotations: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.failedRotations),
+ failedSyncs: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.failedSyncs),
+ orphanedLeases: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.orphanedLeases)
+ })
+ .describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.warnings)
+});
+
+export const SecretsProjectWarningsSchema = z.object({
+ projects: SecretsProjectWarningSchema.array(),
+ totalProjects: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.totalProjects),
+ projectsWithIssues: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.projectsWithIssues),
+ offset: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.offset),
+ limit: z.number().int().describe(PRODUCT_INSIGHTS.GET_SECRETS_PROJECT_WARNINGS.limit)
+});
diff --git a/backend/src/ee/services/product-insights/product-insights-service.ts b/backend/src/ee/services/product-insights/product-insights-service.ts
index 7b4b586215..ed96fe0728 100644
--- a/backend/src/ee/services/product-insights/product-insights-service.ts
+++ b/backend/src/ee/services/product-insights/product-insights-service.ts
@@ -2,13 +2,21 @@ import { TableName } from "@app/db/schemas";
import { TDynamicSecretLeaseDALFactory } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-dal";
import { OrgPermissionSecretsManagementInsightsActions } from "@app/ee/services/permission/org-permission";
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
+import { KeyStorePrefixes, KeyStoreTtls, TKeyStoreFactory } from "@app/keystore/keystore";
+import { withCache } from "@app/lib/cache/with-cache";
import { BadRequestError } from "@app/lib/errors";
import { TIdentityOrgDALFactory } from "@app/services/identity/identity-org-dal";
import { TOrgDALFactory } from "@app/services/org/org-dal";
import { TLicenseServiceFactory } from "../license/license-service";
+import { TProductInsightsDALFactory } from "./product-insights-dal";
import { checkSecretsManagementInsightsPermission } from "./product-insights-fns";
-import { TGetSecretsUsageInsightsDTO, TSecretsUsageInsights } from "./product-insights-types";
+import {
+ TGetSecretsProjectWarningsDTO,
+ TGetSecretsUsageInsightsDTO,
+ TSecretsProjectWarnings,
+ TSecretsUsageInsights
+} from "./product-insights-types";
type TProductInsightsServiceFactoryDep = {
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
@@ -16,8 +24,13 @@ type TProductInsightsServiceFactoryDep = {
orgDAL: Pick<TOrgDALFactory, "countAllOrgMembers">;
identityOrgMembershipDAL: Pick<TIdentityOrgDALFactory, "countAllOrgIdentities">;
dynamicSecretLeaseDAL: Pick<TDynamicSecretLeaseDALFactory, "countLeasesForOrg">;
+ productInsightsDAL: Pick<TProductInsightsDALFactory, "findProjectWarningsForOrg">;
+ keyStore: Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;
};
+// Same threshold the per-project insights summary uses (insights-service.ts)
+const STALE_SECRET_THRESHOLD_DAYS = 90;
+
export type TProductInsightsServiceFactory = ReturnType<typeof productInsightsServiceFactory>;
export const productInsightsServiceFactory = ({
@@ -25,7 +38,9 @@ export const productInsightsServiceFactory = ({
licenseService,
orgDAL,
identityOrgMembershipDAL,
- dynamicSecretLeaseDAL
+ dynamicSecretLeaseDAL,
+ productInsightsDAL,
+ keyStore
}: TProductInsightsServiceFactoryDep) => {
const getSecretsUsageInsights = async (dto: TGetSecretsUsageInsightsDTO): Promise<TSecretsUsageInsights> => {
await checkSecretsManagementInsightsPermission(
@@ -52,5 +67,40 @@ export const productInsightsServiceFactory = ({
return { activeLeases, users, identities };
};
- return { getSecretsUsageInsights };
+ const getSecretsProjectWarnings = async (dto: TGetSecretsProjectWarningsDTO): Promise<TSecretsProjectWarnings> => {
+ // Permission and plan checks run before the cache lookup so cached data is
+ // never served to an unauthorized actor.
+ await checkSecretsManagementInsightsPermission(
+ permissionService,
+ OrgPermissionSecretsManagementInsightsActions.Read,
+ dto
+ );
+
+ const plan = await licenseService.getPlan(dto.orgId);
+ if (!plan.secretAccessInsights) {
+ throw new BadRequestError({
+ message: "Secrets management insights are not available on your plan. Upgrade your plan to access insights."
+ });
+ }
+
+ const cacheKey = KeyStorePrefixes.ProductInsightsCache(dto.orgId, `project-warnings:${dto.offset}:${dto.limit}`);
+ return withCache({
+ keyStore,
+ key: cacheKey,
+ ttlSeconds: KeyStoreTtls.InsightsCacheInSeconds,
+ fetcher: async () => {
+ const staleBefore = new Date();
+ staleBefore.setDate(staleBefore.getDate() - STALE_SECRET_THRESHOLD_DAYS);
+
+ const { projects, totalProjects, projectsWithIssues } = await productInsightsDAL.findProjectWarningsForOrg(
+ dto.orgId,
+ { offset: dto.offset, limit: dto.limit, staleBefore }
+ );
+
+ return { projects, totalProjects, projectsWithIssues, offset: dto.offset, limit: dto.limit };
+ }
+ });
+ };
+
+ return { getSecretsUsageInsights, getSecretsProjectWarnings };
};
diff --git a/backend/src/ee/services/product-insights/product-insights-types.ts b/backend/src/ee/services/product-insights/product-insights-types.ts
index ed9bab2371..59043eb148 100644
--- a/backend/src/ee/services/product-insights/product-insights-types.ts
+++ b/backend/src/ee/services/product-insights/product-insights-types.ts
@@ -9,3 +9,34 @@ export type TSecretsUsageInsights = {
users: number;
identities: number;
};
+
+export type TGetSecretsProjectWarningsDTO = TProductInsightsDTO & {
+ offset: number;
+ limit: number;
+};
+
+export type TProjectWarningCounts = {
+ // null when the project does not have secret blind indexing enabled (the metric is unknowable, not zero)
+ duplicatedSecrets: number | null;
+ staleSecrets: number;
+ failedRotations: number;
+ failedSyncs: number;
+ orphanedLeases: number;
+};
+
+export type TSecretsProjectWarning = {
+ projectId: string;
+ projectName: string;
+ projectSlug: string;
+ totalSecrets: number;
+ severityScore: number;
+ warnings: TProjectWarningCounts;
+};
+
+export type TSecretsProjectWarnings = {
+ projects: TSecretsProjectWarning[];
+ totalProjects: number;
+ projectsWithIssues: number;
+ offset: number;
+ limit: number;
+};
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index cfa3e97e9a..2c3be5afff 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -143,6 +143,7 @@ export const KeyStorePrefixes = {
EmailSignupOtpLock: (hash: string) => `email-signup-otp:${hash}:lock` as const,
EmailSignupResendCooldown: (hash: string) => `email-signup-otp:${hash}:cd` as const,
InsightsCache: (projectId: string, endpoint: string) => `insights-cache:${projectId}:${endpoint}` as const,
+ ProductInsightsCache: (orgId: string, endpoint: string) => `product-insights-cache:${orgId}:${endpoint}` as const,
AdminConfig: "infisical-admin-cfg",
UpdateCheckLatestVersion: "update-check-latest-version",
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 75d3108d95..271b839d9c 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -898,6 +898,26 @@ export const PRODUCT_INSIGHTS = {
"The number of dynamic secret leases currently active across the organization's secret management projects. Revoked and expired leases are not counted.",
users: "The number of users who have accepted an active membership in the organization.",
identities: "The number of machine identities that belong to the organization."
+ },
+ GET_SECRETS_PROJECT_WARNINGS: {
+ offset: "The number of projects to skip before returning results.",
+ limit: "The maximum number of projects to return per page.",
+ projectId: "The ID of the project.",
+ projectName: "The name of the project.",
+ projectSlug: "The slug of the project.",
+ duplicatedSecrets:
+ "The number of secrets in the project whose value is shared with at least one other secret in the same project. Secrets whose value is a reference to another secret are counted as duplicates. Null when the project does not have secret blind indexing enabled.",
+ staleSecrets: "The number of secrets in the project that have not been updated in the last 90 days.",
+ failedRotations: "The number of secret rotations in the project whose last rotation attempt failed.",
+ failedSyncs: "The number of secret syncs in the project whose last sync attempt failed.",
+ orphanedLeases:
+ "The number of dynamic secret leases in the project that failed to be revoked and require manual cleanup.",
+ totalSecrets: "The total number of shared secrets in the project.",
+ warnings: "The counts of outstanding issues detected in the project.",
+ severityScore:
+ "A relative score used to rank projects by the severity of their outstanding issues. The scoring heuristic may change over time.",
+ totalProjects: "The total number of secret management projects in the organization.",
+ projectsWithIssues: "The number of secret management projects in the organization with at least one issue."
}
} as const;
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index 3ac3258a55..d3fbcfe0d3 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -139,6 +139,7 @@ import { pkiInstallationServiceFactory } from "@app/ee/services/pki-discovery/pk
import { scepDynamicChallengeDALFactory } from "@app/ee/services/pki-scep/pki-scep-dynamic-challenge-dal";
import { pkiScepServiceFactory } from "@app/ee/services/pki-scep/pki-scep-service";
import { scepTransactionDALFactory } from "@app/ee/services/pki-scep/pki-scep-transaction-dal";
+import { productInsightsDALFactory } from "@app/ee/services/product-insights/product-insights-dal";
import { productInsightsServiceFactory } from "@app/ee/services/product-insights/product-insights-service";
import { projectEventsServiceFactory } from "@app/ee/services/project-events/project-events-service";
import { projectEventsSSEServiceFactory } from "@app/ee/services/project-events/project-events-sse-service";
@@ -618,6 +619,7 @@ export const registerRoutes = async (
const integrationDAL = integrationDALFactory(db);
const offlineUsageReportDAL = offlineUsageReportDALFactory(db);
const orgProductStatsDAL = orgProductStatsDALFactory(db);
+ const productInsightsDAL = productInsightsDALFactory(db);
const integrationAuthDAL = integrationAuthDALFactory(db);
const webhookDAL = webhookDALFactory(db);
const serviceTokenDAL = serviceTokenDALFactory(db);
@@ -2753,7 +2755,9 @@ export const registerRoutes = async (
licenseService,
orgDAL,
identityOrgMembershipDAL,
- dynamicSecretLeaseDAL
+ dynamicSecretLeaseDAL,
+ productInsightsDAL,
+ keyStore
});
// DAILY
diff --git a/backend/src/services/secret-folder/secret-folder-service.ts b/backend/src/services/secret-folder/secret-folder-service.ts
index f5582320c7..4117f56502 100644
--- a/backend/src/services/secret-folder/secret-folder-service.ts
+++ b/backend/src/services/secret-folder/secret-folder-service.ts
@@ -16,6 +16,7 @@ import { TSecretApprovalRequestSecretDALFactory } from "@app/ee/services/secret-
import { TSecretRotationV2DALFactory } from "@app/ee/services/secret-rotation-v2/secret-rotation-v2-dal";
import { PgSqlLock } from "@app/keystore/keystore";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { logger } from "@app/lib/logger";
import { OrderByDirection, OrgServiceActor } from "@app/lib/types";
import { ActorType } from "@app/services/auth/auth-type";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
@@ -1639,6 +1640,7 @@ export const secretFolderServiceFactory = ({
canActorReadBlock(permission, destinationEnvironment, "secret_approval_policy", destinationBlock.blockingAbsPath)
? destinationBlock
: undefined;
+ logger.info({ readableDestinationBlock }, "readableDestinationBlock");
return {
canMove: !sourceBlock,
diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsx
index d2168736f8..117df1f9aa 100644
--- a/frontend/src/hooks/api/auditLogs/constants.tsx
+++ b/frontend/src/hooks/api/auditLogs/constants.tsx
@@ -292,6 +292,8 @@ export const eventToNameMap: { [K in EventType]: string } = {
[EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_COUNTS]:
"View Secrets Management Resource Counts Insights",
[EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_USAGE]: "View Secrets Management Usage Insights",
+ [EventType.VIEW_INSIGHTS_SECRETS_MANAGEMENT_PROJECT_WARNINGS]:
+ "View Secrets Management Project Warnings Insights",
[EventType.CREATE_PROJECT_ROLE]: "Create Project Role",
[EventType.UPDATE_PROJECT_ROLE]: "Update Project Role",
diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsx
index 56b4140635..7912c807a1 100644
--- a/frontend/src/hooks/api/auditLogs/enums.tsx
+++ b/frontend/src/hooks/api/auditLogs/enums.tsx
@@ -283,6 +283,7 @@ export enum EventType {
VIEW_INSIGHTS_SECRETS_DUPLICATION = "view-insights-secrets-duplication",
VIEW_INSIGHTS_SECRETS_MANAGEMENT_COUNTS = "view-insights-secrets-management-counts",
VIEW_INSIGHTS_SECRETS_MANAGEMENT_USAGE = "view-insights-secrets-management-usage",
+ VIEW_INSIGHTS_SECRETS_MANAGEMENT_PROJECT_WARNINGS = "view-insights-secrets-management-project-warnings",
CREATE_PROJECT_ROLE = "create-project-role",
UPDATE_PROJECT_ROLE = "update-project-role",