Skip to content

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

record metrics in application layer

Matheus Nogueirae80d35d33f58
diff --git a/backend/src/db/migrations/20260709200205_dynamic_secret_leases_expire_at_index.ts b/backend/src/db/migrations/20260709200205_dynamic_secret_leases_expire_at_index.ts
deleted file mode 100644
index 8d08821ec6..0000000000
--- a/backend/src/db/migrations/20260709200205_dynamic_secret_leases_expire_at_index.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { Knex } from "knex";
-
-import { TableName } from "../schemas";
-
-export async function up(knex: Knex): Promise<void> {
- const hasIndex = await knex.schema.hasTable(TableName.DynamicSecretLease).then(async (exists) => {
- if (!exists) return false;
- const indexes = await knex.raw(
- `SELECT indexname FROM pg_indexes WHERE tablename = '${TableName.DynamicSecretLease}'`
- );
- return indexes.rows.some((row: { indexname: string }) => row.indexname === "dynamic_secret_leases_expire_at_index");
- });
-
- if (!hasIndex) {
- await knex.schema.alterTable(TableName.DynamicSecretLease, (t) => {
- t.index("expireAt", "dynamic_secret_leases_expire_at_index");
- });
- }
-}
-
-export async function down(knex: Knex): Promise<void> {
- await knex.schema.alterTable(TableName.DynamicSecretLease, (t) => {
- t.dropIndex("expireAt", "dynamic_secret_leases_expire_at_index");
- });
-}
diff --git a/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-queue.ts b/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-queue.ts
index 52f6b03232..05568db225 100644
--- a/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-queue.ts
+++ b/backend/src/ee/services/dynamic-secret-lease/dynamic-secret-lease-queue.ts
@@ -1,5 +1,6 @@
import { ProjectMembershipRole } from "@app/db/schemas";
import { getConfig } from "@app/lib/config/env";
+import { recordDynamicSecretOrphanedLeaseMetric } from "@app/lib/telemetry/metrics";
import { applyJitter } from "@app/lib/delay";
import { DisableRotationErrors, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
@@ -141,6 +142,7 @@ export const dynamicSecretLeaseQueueServiceFactory = ({
data: { leaseId: string; dynamicSecretId: string; isRetry?: boolean } | { dynamicSecretCfgId: string },
retryCount?: number
): Promise<void> => {
+ let providerType: string | undefined;
try {
if (jobName === QueueJobs.DynamicSecretRevocation) {
const { leaseId } = data as { leaseId: string };
@@ -163,6 +165,7 @@ export const dynamicSecretLeaseQueueServiceFactory = ({
});
const dynamicSecretCfg = dynamicSecretLease.dynamicSecret;
+ providerType = dynamicSecretCfg.type;
const selectedProvider = dynamicSecretProviders[dynamicSecretCfg.type as DynamicSecretProviders];
const decryptedStoredInput = JSON.parse(
secretManagerDecryptor({ cipherTextBlob: dynamicSecretCfg.encryptedInput }).toString()
@@ -183,6 +186,7 @@ export const dynamicSecretLeaseQueueServiceFactory = ({
logger.info(`Failed to find dynamic secret with ${dynamicSecretCfgId}`);
return;
}
+ providerType = dynamicSecretCfg.type;
if ((dynamicSecretCfg.status as DynamicSecretStatus) !== DynamicSecretStatus.Deleting) {
logger.info(`Dynamic secret ${dynamicSecretCfgId} is not in deleting status`);
return;
@@ -233,6 +237,9 @@ export const dynamicSecretLeaseQueueServiceFactory = ({
status: DynamicSecretStatus.FailedDeletion,
statusDetails: (error as Error)?.message?.slice(0, 255)
});
+ if (providerType) {
+ recordDynamicSecretOrphanedLeaseMetric({ provider: providerType });
+ }
}
if (jobName === QueueJobs.DynamicSecretRevocation) {
@@ -245,6 +252,9 @@ export const dynamicSecretLeaseQueueServiceFactory = ({
status: DynamicSecretStatus.FailedDeletion,
statusDetails: `${(error as Error)?.message?.slice(0, 255)} - Retrying automatically`
});
+ if (providerType) {
+ recordDynamicSecretOrphanedLeaseMetric({ provider: providerType });
+ }
// only add to retry queue if this is not a retry, and if the error is not a DisableRotationErrors error
if (!isRetry && !(error instanceof DisableRotationErrors)) {
diff --git a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts
index 2c3dd4b511..a1f3de2957 100644
--- a/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts
+++ b/backend/src/ee/services/secret-rotation-v2/secret-rotation-v2-service.ts
@@ -66,6 +66,7 @@ import { KeyStorePrefixes, PgSqlLock, TKeyStoreFactory } from "@app/keystore/key
import { getConfig } from "@app/lib/config/env";
import { DatabaseErrorCode } from "@app/lib/error-codes";
import { BadRequestError, DatabaseError, InternalServerError, NotFoundError } from "@app/lib/errors";
+import { recordSecretRotationOutcomeMetric } from "@app/lib/telemetry/metrics";
import { OrderByDirection, OrgServiceActor } from "@app/lib/types";
import { QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { TAppConnectionDALFactory } from "@app/services/app-connection/app-connection-dal";
@@ -1461,10 +1462,14 @@ export const secretRotationV2ServiceFactory = ({
excludeReplication: true
});
+ recordSecretRotationOutcomeMetric({ type, outcome: "success" });
+
return updatedRotation;
} catch (error) {
const errorMessage = parseRotationErrorMessage(error);
+ recordSecretRotationOutcomeMetric({ type, outcome: "failure" });
+
if (isManualRotation) {
await triggerFailedWebhook(projectId, environment, error, folder, secretRotation, isManualRotation);
}
diff --git a/backend/src/lib/telemetry/metrics.ts b/backend/src/lib/telemetry/metrics.ts
index fe36ab4be7..668e3563b8 100644
--- a/backend/src/lib/telemetry/metrics.ts
+++ b/backend/src/lib/telemetry/metrics.ts
@@ -556,6 +556,41 @@ export const recordSecretSyncOutcomeMetric = (params: {
});
};
+// -- Secret rotation outcome (InfisicalCore meter) --------------------------------------------------
+export const secretRotationOutcomeCounter = infisicalCoreMeter.createCounter(
+ "infisical.secret_rotation.outcome.count",
+ {
+ description:
+ "Secret rotation attempts by type and outcome. Alert on failure ratio > 50% per type with >= 5 total rotations.",
+ unit: "{attempt}"
+ }
+);
+
+export const recordSecretRotationOutcomeMetric = (params: { type: string; outcome: "success" | "failure" }) => {
+ if (!isTelemetryEnabled()) return;
+ secretRotationOutcomeCounter.add(1, {
+ type: params.type,
+ outcome: params.outcome
+ });
+};
+
+// -- Dynamic secret orphaned lease (InfisicalCore meter) ---------------------------------------------
+export const dynamicSecretOrphanedLeaseCounter = infisicalCoreMeter.createCounter(
+ "infisical.dynamic_secret.orphaned_lease.count",
+ {
+ description:
+ "Dynamic secret lease revocation failures by provider. Alert on any value > 0 sustained 60m.",
+ unit: "{failure}"
+ }
+);
+
+export const recordDynamicSecretOrphanedLeaseMetric = (params: { provider: string }) => {
+ if (!isTelemetryEnabled()) return;
+ dynamicSecretOrphanedLeaseCounter.add(1, {
+ provider: params.provider
+ });
+};
+
// -- Boot-time observable gauges (InfisicalCore meter) ----------------------------------------------
// Registered once at boot from main.ts with the primary Knex instance. Runs AFTER setupTelemetry() has
// installed the real MeterProvider, so we resolve the real meter directly here (observable gauges can't
@@ -600,58 +635,4 @@ export const registerInfrastructureMetrics = (db: Knex) => {
result.observe(pool.numFree?.() ?? 0, { "db.pool.state": "free" });
result.observe(pool.numPendingAcquires?.() ?? 0, { "db.pool.state": "pending" });
});
-
- // Secret rotation status: GROUP BY type, rotationStatus. Backs "A rotation type is broken" alert.
- const rotationStatusGauge = meter.createObservableGauge("infisical.secret_rotation.status", {
- description:
- "Current secret rotation counts by type and status. Alert on failure ratio > 50% per type with >= 5 total rotations.",
- unit: "{rotation}"
- });
-
- rotationStatusGauge.addCallback(async (result) => {
- if (!isTelemetryEnabled()) return;
- try {
- const rows: { type: string; rotationStatus: string; count: string }[] = await db("secret_rotations_v2")
- .select("type", "rotationStatus")
- .count("* as count")
- .groupBy("type", "rotationStatus");
-
- for (const row of rows) {
- result.observe(Number(row.count), {
- type: row.type,
- outcome: row.rotationStatus
- });
- }
- } catch {
- // DB unavailable during startup or shutdown; skip this export tick.
- }
- });
-
- // Orphaned dynamic secret credentials: leases past expiry still marked "Failed to delete".
- const orphanedGauge = meter.createObservableGauge("infisical.dynamic_secret.orphaned", {
- description:
- "Dynamic secret leases past expiry with status 'Failed to delete', grouped by provider. Alert on any value > 0 sustained 60m.",
- unit: "{credential}"
- });
-
- orphanedGauge.addCallback(async (result) => {
- if (!isTelemetryEnabled()) return;
- try {
- const rows: { type: string; count: string }[] = await db("dynamic_secret_leases")
- .join("dynamic_secrets", "dynamic_secret_leases.dynamicSecretId", "dynamic_secrets.id")
- .where("dynamic_secret_leases.status", "Failed to delete")
- .where("dynamic_secret_leases.expireAt", "<", db.fn.now())
- .select("dynamic_secrets.type")
- .count("* as count")
- .groupBy("dynamic_secrets.type");
-
- for (const row of rows) {
- result.observe(Number(row.count), {
- provider: row.type
- });
- }
- } catch {
- // DB unavailable during startup or shutdown; skip this export tick.
- }
- });
};