Skip to content

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

feat: add OTEL_DROP_LEGACY_METERS configuration and integrate new OpenTelemetry instrumentation

Victor Hugo dos Santosb6e96f1ec926
diff --git a/.env.dev.example b/.env.dev.example
index 9d6dd74aa3..da60b195e7 100644
--- a/.env.dev.example
+++ b/.env.dev.example
@@ -84,6 +84,7 @@ OTEL_OTLP_PUSH_INTERVAL=
OTEL_COLLECTOR_BASIC_AUTH_USERNAME=
OTEL_COLLECTOR_BASIC_AUTH_PASSWORD=
+OTEL_DROP_LEGACY_METERS=false
PLAIN_API_KEY=
PLAIN_WISH_LABEL_IDS=
diff --git a/.env.example b/.env.example
index 785e80cce6..e856c595f5 100644
--- a/.env.example
+++ b/.env.example
@@ -71,6 +71,7 @@ OTEL_OTLP_PUSH_INTERVAL=
OTEL_COLLECTOR_BASIC_AUTH_USERNAME=
OTEL_COLLECTOR_BASIC_AUTH_PASSWORD=
+OTEL_DROP_LEGACY_METERS=false
PLAIN_API_KEY=
PLAIN_WISH_LABEL_IDS=
diff --git a/backend/package-lock.json b/backend/package-lock.json
index 5f6911e192..04e10e3c77 100644
--- a/backend/package-lock.json
+++ b/backend/package-lock.json
@@ -61,6 +61,7 @@
"@opentelemetry/exporter-prometheus": "^0.55.0",
"@opentelemetry/instrumentation": "^0.55.0",
"@opentelemetry/instrumentation-http": "^0.57.2",
+ "@opentelemetry/instrumentation-runtime-node": "^0.31.0",
"@opentelemetry/resources": "^1.28.0",
"@opentelemetry/sdk-metrics": "^1.28.0",
"@opentelemetry/semantic-conventions": "^1.27.0",
@@ -8845,6 +8846,127 @@
"node": ">=14"
}
},
+ "node_modules/@opentelemetry/instrumentation-runtime-node": {
+ "version": "0.31.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-runtime-node/-/instrumentation-runtime-node-0.31.0.tgz",
+ "integrity": "sha512-HkLsuEfUDahFiL/xFtEqJDMp7sp8ynOtA045bJi9nAH8CrPvljPW5SgJQb2mQqEYJQopbWYZ2lPqQEfj7bYgJg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/api-logs": "^0.218.0",
+ "@opentelemetry/core": "^2.0.0",
+ "@opentelemetry/instrumentation": "^0.218.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": "^1.3.0"
+ }
+ },
+ "node_modules/@opentelemetry/instrumentation-runtime-node/node_modules/@opentelemetry/api-logs": {
+ "version": "0.218.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.218.0.tgz",
+ "integrity": "sha512-fmEWp5kXlGEc3i/lR698Hz41DfGyN4Tbe4g7L1AxSc7fF8Xeh/FQ9Quqpa9dVA413Q1Ad43QOLzU4JoXgbFPWw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/api": "^1.3.0"
+ },
+ "engines": {
+ "node": ">=8.0.0"
+ }
+ },
+ "node_modules/@opentelemetry/instrumentation-runtime-node/node_modules/@opentelemetry/core": {
+ "version": "2.7.1",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.7.1.tgz",
+ "integrity": "sha512-QAqIj32AtK6+pEVNG7EOVxHdE06RP+FM5qpiEJ4RtDcFIqKUZHYhl7/7UY5efhwmwNAg7j8QbJVBLxMerc0+gw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/semantic-conventions": "^1.29.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": ">=1.0.0 <1.10.0"
+ }
+ },
+ "node_modules/@opentelemetry/instrumentation-runtime-node/node_modules/@opentelemetry/instrumentation": {
+ "version": "0.218.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation/-/instrumentation-0.218.0.tgz",
+ "integrity": "sha512-mIZil8Es+sYDK5m+DQiwAwF57F14TF2YlEqvIjZ/RQWcxDBwRGsKfdK2Tv65OU9meQKCMzSIFS9mxAcnAb6Bkg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@opentelemetry/api-logs": "0.218.0",
+ "import-in-the-middle": "^3.0.0",
+ "require-in-the-middle": "^8.0.0"
+ },
+ "engines": {
+ "node": "^18.19.0 || >=20.6.0"
+ },
+ "peerDependencies": {
+ "@opentelemetry/api": "^1.3.0"
+ }
+ },
+ "node_modules/@opentelemetry/instrumentation-runtime-node/node_modules/@opentelemetry/semantic-conventions": {
+ "version": "1.41.1",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.41.1.tgz",
+ "integrity": "sha512-/UhIkaZgPutTFmQ7RnIJGgDXZmtEJ7Dvi86xNTFWcnRxVRNk/aotsqDJYeEvDP+FSMB2SdW+pQzNMcWP0rwuNA==",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@opentelemetry/instrumentation-runtime-node/node_modules/cjs-module-lexer": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-2.2.0.tgz",
+ "integrity": "sha512-4bHTS2YuzUvtoLjdy+98ykbNB5jS0+07EvFNXerqZQJ89F7DI6ET7OQo/HJuW6K0aVsKA9hj9/RVb2kQVOrPDQ==",
+ "license": "MIT"
+ },
+ "node_modules/@opentelemetry/instrumentation-runtime-node/node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@opentelemetry/instrumentation-runtime-node/node_modules/import-in-the-middle": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/import-in-the-middle/-/import-in-the-middle-3.0.1.tgz",
+ "integrity": "sha512-pYkiyXVL2Mf3pozdlDGV6NAObxQx13Ae8knZk1UJRJ6uRW/ZRmTGHlQYtrsSl7ubuE5F8CD1z+s1n4RHNuTtuA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "acorn": "^8.15.0",
+ "acorn-import-attributes": "^1.9.5",
+ "cjs-module-lexer": "^2.2.0",
+ "module-details-from-path": "^1.0.4"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@opentelemetry/instrumentation-runtime-node/node_modules/require-in-the-middle": {
+ "version": "8.0.1",
+ "resolved": "https://registry.npmjs.org/require-in-the-middle/-/require-in-the-middle-8.0.1.tgz",
+ "integrity": "sha512-QT7FVMXfWOYFbeRBF6nu+I6tr2Tf3u0q8RIEjNob/heKY/nh7drD/k7eeMFmSQgnTtCzLDcCu/XEnpW2wk4xCQ==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.3.5",
+ "module-details-from-path": "^1.0.3"
+ },
+ "engines": {
+ "node": ">=9.3.0 || >=8.10.0 <9.0.0"
+ }
+ },
"node_modules/@opentelemetry/otlp-exporter-base": {
"version": "0.55.0",
"resolved": "https://registry.npmjs.org/@opentelemetry/otlp-exporter-base/-/otlp-exporter-base-0.55.0.tgz",
@@ -20659,9 +20781,10 @@
}
},
"node_modules/module-details-from-path": {
- "version": "1.0.3",
- "resolved": "https://registry.npmjs.org/module-details-from-path/-/module-details-from-path-1.0.3.tgz",
- "integrity": "sha512-ySViT69/76t8VhE1xXHK6Ch4NcDd26gx0MzKXLO+F7NOtnqH68d9zF94nT8ZWSxXh8ELOERsnJO/sWt1xZYw5A=="
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/module-details-from-path/-/module-details-from-path-1.0.4.tgz",
+ "integrity": "sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w==",
+ "license": "MIT"
},
"node_modules/moment": {
"version": "2.30.1",
diff --git a/backend/package.json b/backend/package.json
index 6f24b39c57..ff64bf98fa 100644
--- a/backend/package.json
+++ b/backend/package.json
@@ -188,6 +188,7 @@
"@opentelemetry/exporter-prometheus": "^0.55.0",
"@opentelemetry/instrumentation": "^0.55.0",
"@opentelemetry/instrumentation-http": "^0.57.2",
+ "@opentelemetry/instrumentation-runtime-node": "^0.31.0",
"@opentelemetry/resources": "^1.28.0",
"@opentelemetry/sdk-metrics": "^1.28.0",
"@opentelemetry/semantic-conventions": "^1.27.0",
diff --git a/backend/src/ee/routes/v1/saml-router.ts b/backend/src/ee/routes/v1/saml-router.ts
index 592390f159..4832c1533e 100644
--- a/backend/src/ee/routes/v1/saml-router.ts
+++ b/backend/src/ee/routes/v1/saml-router.ts
@@ -20,7 +20,12 @@ import { getConfig } from "@app/lib/config/env";
import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
-import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";
+import {
+ AuthAttemptAuthMethod,
+ AuthAttemptAuthResult,
+ authAttemptCounter,
+ recordAuthAttemptMetric
+} from "@app/lib/telemetry/metrics";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
import { addAuthOriginDomainCookie } from "@app/server/lib/cookie";
import { getTelemetryDistinctId } from "@app/server/lib/telemetry";
@@ -118,6 +123,7 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
},
// eslint-disable-next-line
async (req, profile, cb) => {
+ const authMetricStartTime = performance.now();
if (!profile) throw new BadRequestError({ message: "Missing profile" });
const email =
@@ -197,6 +203,13 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.SAML,
+ result: AuthAttemptAuthResult.SUCCESS,
+ orgId: loginResult.orgId
+ });
+
cb(null, loginResult);
} catch (error) {
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
@@ -209,6 +222,13 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.SAML,
+ result: AuthAttemptAuthResult.FAILURE,
+ error
+ });
+
logger.error(error);
cb(error as Error);
}
diff --git a/backend/src/ee/services/audit-log-stream/audit-log-stream-service.ts b/backend/src/ee/services/audit-log-stream/audit-log-stream-service.ts
index 0727edab8c..410c7b7177 100644
--- a/backend/src/ee/services/audit-log-stream/audit-log-stream-service.ts
+++ b/backend/src/ee/services/audit-log-stream/audit-log-stream-service.ts
@@ -11,7 +11,13 @@ import {
import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
+import { classifyError } from "@app/lib/errors/classify";
import { logger } from "@app/lib/logger";
+import {
+ auditLogStreamAlertFiredCounter,
+ auditLogStreamDeliveryCounter,
+ auditLogStreamDeliveryDurationHistogram
+} from "@app/lib/telemetry/metrics";
import { OrgServiceActor } from "@app/lib/types";
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { TNotificationServiceFactory } from "@app/services/notification/notification-service";
@@ -374,6 +380,11 @@ export const auditLogStreamServiceFactory = ({
);
if (!acquired) return;
+ auditLogStreamAlertFiredCounter.add(1, {
+ "audit_log_stream.provider": provider,
+ "infisical.organization.id": orgId
+ });
+
await notifyStreamFailure(orgId, streamId, provider, failureCount, lastError).catch(async (notifyErr) => {
logger.error(
notifyErr,
@@ -403,9 +414,26 @@ export const auditLogStreamServiceFactory = ({
const factory = LOG_STREAM_FACTORY_MAP[provider as LogProvider]();
+ const deliveryStart = Date.now();
+ const metricBaseAttrs = {
+ "audit_log_stream.provider": provider,
+ "infisical.organization.id": orgId
+ };
+
try {
await factory.streamLog({ credentials, auditLog });
+ const durationS = (Date.now() - deliveryStart) / 1000;
+ auditLogStreamDeliveryCounter.add(1, { ...metricBaseAttrs, outcome: "success" });
+ auditLogStreamDeliveryDurationHistogram.record(durationS, { ...metricBaseAttrs, outcome: "success" });
} catch (error) {
+ const durationS = (Date.now() - deliveryStart) / 1000;
+ const errorType = classifyError(error);
+ auditLogStreamDeliveryCounter.add(1, { ...metricBaseAttrs, outcome: "failure", "error.type": errorType });
+ auditLogStreamDeliveryDurationHistogram.record(durationS, {
+ ...metricBaseAttrs,
+ outcome: "failure",
+ "error.type": errorType
+ });
let errorMessage: string;
if (isAxiosError(error)) {
errorMessage = `${error?.message ?? "Request failed"} — ${JSON.stringify(error?.response?.data) ?? ""}`;
diff --git a/backend/src/ee/services/audit-log/audit-log-queue.ts b/backend/src/ee/services/audit-log/audit-log-queue.ts
index 0e37b89cd7..6aab576329 100644
--- a/backend/src/ee/services/audit-log/audit-log-queue.ts
+++ b/backend/src/ee/services/audit-log/audit-log-queue.ts
@@ -7,6 +7,11 @@ import { TAuditLogStreamServiceFactory } from "@app/ee/services/audit-log-stream
import { TKeyStoreFactory } from "@app/keystore/keystore";
import { getConfig } from "@app/lib/config/env";
import { logger } from "@app/lib/logger";
+import {
+ auditLogDroppedCounter,
+ auditLogEnqueuedCounter,
+ auditLogPersistDurationHistogram
+} from "@app/lib/telemetry/metrics";
import { JOB_SCHEDULER_PREFIX, QueueJobs, QueueName, TQueueServiceFactory } from "@app/queue";
import { TProjectDALFactory } from "@app/services/project/project-dal";
@@ -69,6 +74,11 @@ export const auditLogQueueServiceFactory = async ({
const isClickHouseBatchEnabled = Boolean(clickhouseClient && CLICKHOUSE_AUDIT_LOG_ENABLED);
const pushToLog = async (data: TCreateAuditLogDTO) => {
+ auditLogEnqueuedCounter.add(1, {
+ "audit_log.event_type": data.event?.type ?? "unknown",
+ "audit_log.actor_type": data.actor?.type ?? "unknown",
+ ...(data.orgId ? { "infisical.organization.id": data.orgId } : {})
+ });
await queueService.queue<QueueName.AuditLog>(QueueName.AuditLog, QueueJobs.AuditLog, data, {
removeOnFail: {
count: 3
@@ -147,6 +157,8 @@ export const auditLogQueueServiceFactory = async ({
};
// Push to Redis stream for ClickHouse batch processing
+ const persistStart = Date.now();
+ const backend = isClickHouseBatchEnabled ? "clickhouse" : "postgres";
if (isClickHouseBatchEnabled) {
try {
await keyStore.streamAdd(AUDIT_LOG_CLICKHOUSE_STREAM_KEY, "*", {
@@ -161,6 +173,11 @@ export const auditLogQueueServiceFactory = async ({
} else {
await auditLogDAL.create(auditLog);
}
+ auditLogPersistDurationHistogram.record((Date.now() - persistStart) / 1000, {
+ "audit_log.backend": backend,
+ "audit_log.event_type": event.type,
+ "infisical.organization.id": orgId
+ });
if (getConfig().AUDIT_LOG_STREAMS_ENABLED) {
await auditLogStreamService.streamLog(orgId, auditLog);
@@ -175,6 +192,18 @@ export const auditLogQueueServiceFactory = async ({
}
});
+ // Track audit log events that were ultimately dropped after exhausting BullMQ's retry budget.
+ queueService.listen(QueueName.AuditLog, "failed", (job) => {
+ if (!job) return;
+ const attemptsRemaining = (job.opts.attempts ?? 1) - (job.attemptsMade ?? 0);
+ if (attemptsRemaining > 0) return;
+ auditLogDroppedCounter.add(1, {
+ "audit_log.event_type": job.data?.event?.type ?? "unknown",
+ "audit_log.drop_reason": "max_retries",
+ ...(job.data?.orgId ? { "infisical.organization.id": job.data.orgId } : {})
+ });
+ });
+
// Batch consumer: reads from Redis stream and inserts into ClickHouse every 5 seconds
if (isClickHouseBatchEnabled) {
queueService.start(QueueName.AuditLogClickHouseBatch, async () => {
diff --git a/backend/src/ee/services/ldap-config/ldap-config-service.ts b/backend/src/ee/services/ldap-config/ldap-config-service.ts
index 9e0d839e14..7628f7a08a 100644
--- a/backend/src/ee/services/ldap-config/ldap-config-service.ts
+++ b/backend/src/ee/services/ldap-config/ldap-config-service.ts
@@ -13,9 +13,19 @@ import { TGroupDALFactory } from "@app/ee/services/group/group-dal";
import { addUsersToGroupByUserIds, removeUsersFromGroupByUserIds } from "@app/ee/services/group/group-fns";
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
import { throwOnPlanSeatLimitReached } from "@app/ee/services/license/license-fns";
+import { getConfig } from "@app/lib/config/env";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
+import {
+ AuthAttemptAuthMethod,
+ AuthAttemptAuthResult,
+ authAttemptCounter,
+ recordAuthAttemptMetric,
+ recordSsoConfigChangeMetric,
+ SsoConfigAction,
+ SsoProvider
+} from "@app/lib/telemetry/metrics";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { sanitizeEmail, validateEmail } from "@app/lib/validator/validate-email";
import { TAuthLoginFactory } from "@app/services/auth/auth-login-service";
@@ -218,6 +228,8 @@ export const ldapConfigServiceFactory = ({
: null
});
+ recordSsoConfigChangeMetric({ provider: SsoProvider.Ldap, action: SsoConfigAction.Create, orgId });
+
return ldapConfig;
};
@@ -393,6 +405,8 @@ export const ldapConfigServiceFactory = ({
return updatedLdapCfg;
});
+ recordSsoConfigChangeMetric({ provider: SsoProvider.Ldap, action: SsoConfigAction.Update, orgId });
+
return config;
};
@@ -447,7 +461,7 @@ export const ldapConfigServiceFactory = ({
return { opts, ldapConfig };
};
- const ldapLogin = async ({
+ const ldapLoginInner = async ({
ldapConfigId,
externalId,
firstName,
@@ -721,6 +735,55 @@ export const ldapConfigServiceFactory = ({
return callbackResult;
};
+ const ldapLogin = async (dto: TLdapLoginDTO) => {
+ const authMetricStartTime = performance.now();
+ const appCfg = getConfig();
+ try {
+ const callbackResult = await ldapLoginInner(dto);
+
+ if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
+ authAttemptCounter.add(1, {
+ "infisical.user.email": dto.email,
+ "infisical.organization.id": dto.orgId,
+ "infisical.auth.method": AuthAttemptAuthMethod.LDAP,
+ "infisical.auth.result": AuthAttemptAuthResult.SUCCESS,
+ "client.address": dto.ip,
+ "user_agent.original": dto.userAgent
+ });
+ }
+
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.LDAP,
+ result: AuthAttemptAuthResult.SUCCESS,
+ orgId: dto.orgId
+ });
+
+ return callbackResult;
+ } catch (error) {
+ if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
+ authAttemptCounter.add(1, {
+ "infisical.user.email": dto.email,
+ "infisical.organization.id": dto.orgId,
+ "infisical.auth.method": AuthAttemptAuthMethod.LDAP,
+ "infisical.auth.result": AuthAttemptAuthResult.FAILURE,
+ "client.address": dto.ip,
+ "user_agent.original": dto.userAgent
+ });
+ }
+
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.LDAP,
+ result: AuthAttemptAuthResult.FAILURE,
+ orgId: dto.orgId,
+ error
+ });
+
+ throw error;
+ }
+ };
+
const getLdapGroupMaps = async ({
ldapConfigId,
actor,
diff --git a/backend/src/ee/services/oidc/oidc-config-service.ts b/backend/src/ee/services/oidc/oidc-config-service.ts
index 2fbe358b80..24b4d08c1d 100644
--- a/backend/src/ee/services/oidc/oidc-config-service.ts
+++ b/backend/src/ee/services/oidc/oidc-config-service.ts
@@ -18,7 +18,15 @@ import { BadRequestError, ForbiddenRequestError, NotFoundError, OidcAuthError }
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
-import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";
+import {
+ AuthAttemptAuthMethod,
+ AuthAttemptAuthResult,
+ authAttemptCounter,
+ recordAuthAttemptMetric,
+ recordSsoConfigChangeMetric,
+ SsoConfigAction,
+ SsoProvider
+} from "@app/lib/telemetry/metrics";
import { OrgServiceActor } from "@app/lib/types";
import {
blockLocalAndPrivateIpAddresses,
@@ -574,6 +582,7 @@ export const oidcConfigServiceFactory = ({
const [ssoConfig] = await oidcConfigDAL.update({ orgId: org.id }, updateQuery);
await orgDAL.updateById(org.id, { authEnforced: false, scimEnabled: false });
+ recordSsoConfigChangeMetric({ provider: SsoProvider.Oidc, action: SsoConfigAction.Update, orgId: org.id });
return ssoConfig;
};
@@ -663,6 +672,8 @@ export const oidcConfigServiceFactory = ({
encryptedOidcClientSecret: encryptor({ plainText: Buffer.from(clientSecret) }).cipherTextBlob
});
+ recordSsoConfigChangeMetric({ provider: SsoProvider.Oidc, action: SsoConfigAction.Create, orgId: org.id });
+
return oidcCfg;
};
@@ -754,6 +765,7 @@ export const oidcConfigServiceFactory = ({
},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(_req: any, tokenSet: TokenSet, cb: any) => {
+ const authMetricStartTime = performance.now();
const claims = tokenSet.claims();
if (!claims.email) {
throw new BadRequestError({
@@ -802,9 +814,16 @@ export const oidcConfigServiceFactory = ({
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.OIDC,
+ result: AuthAttemptAuthResult.SUCCESS,
+ orgId: org.id
+ });
+
cb(null, loginResult);
})
- .catch((error) => {
+ .catch((error: unknown) => {
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
authAttemptCounter.add(1, {
"infisical.user.email": claims?.email?.toLowerCase(),
@@ -817,6 +836,14 @@ export const oidcConfigServiceFactory = ({
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.OIDC,
+ result: AuthAttemptAuthResult.FAILURE,
+ orgId: org.id,
+ error
+ });
+
cb(error);
});
}
diff --git a/backend/src/ee/services/saml-config/saml-config-service.ts b/backend/src/ee/services/saml-config/saml-config-service.ts
index a60c8c63d9..94bd3e160a 100644
--- a/backend/src/ee/services/saml-config/saml-config-service.ts
+++ b/backend/src/ee/services/saml-config/saml-config-service.ts
@@ -18,6 +18,7 @@ import { throwOnPlanSeatLimitReached } from "@app/ee/services/license/license-fn
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
+import { recordSsoConfigChangeMetric, SsoConfigAction, SsoProvider } from "@app/lib/telemetry/metrics";
import { sanitizeEmail, validateEmail } from "@app/lib/validator/validate-email";
import { TAuthLoginFactory } from "@app/services/auth/auth-login-service";
import { AuthMethod } from "@app/services/auth/auth-type";
@@ -334,6 +335,8 @@ export const samlConfigServiceFactory = ({
enableGroupSync: enableGroupSync || false
});
+ recordSsoConfigChangeMetric({ provider: SsoProvider.Saml, action: SsoConfigAction.Create, orgId });
+
return samlConfig;
};
@@ -420,6 +423,8 @@ export const samlConfigServiceFactory = ({
const [ssoConfig] = await samlConfigDAL.update({ orgId }, updateQuery);
await orgDAL.updateById(orgId, { authEnforced: false, scimEnabled: false });
+ recordSsoConfigChangeMetric({ provider: SsoProvider.Saml, action: SsoConfigAction.Update, orgId });
+
return ssoConfig;
};
diff --git a/backend/src/ee/services/scim/scim-service.ts b/backend/src/ee/services/scim/scim-service.ts
index 82b6e6a81a..dba9883678 100644
--- a/backend/src/ee/services/scim/scim-service.ts
+++ b/backend/src/ee/services/scim/scim-service.ts
@@ -26,6 +26,7 @@ import { ms } from "@app/lib/ms";
import { alphaNumericNanoId } from "@app/lib/nanoid";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
+import { recordScimOperationMetric, ScimOperation } from "@app/lib/telemetry/metrics";
import { sanitizeEmail, validateEmail } from "@app/lib/validator/validate-email";
import { TAdditionalPrivilegeDALFactory } from "@app/services/additional-privilege/additional-privilege-dal";
import { AuthTokenType } from "@app/services/auth/auth-type";
@@ -1617,6 +1618,24 @@ export const scimServiceFactory = ({
return processedCount;
};
+ const withScimMetric =
+ <TArgs extends [{ orgId?: string }, ...unknown[]], TReturn>(
+ operation: ScimOperation,
+ fn: (...args: TArgs) => Promise<TReturn>
+ ) =>
+ async (...args: TArgs): Promise<TReturn> => {
+ const startTime = performance.now();
+ const orgId = args[0]?.orgId;
+ try {
+ const result = await fn(...args);
+ recordScimOperationMetric({ startTime, operation, outcome: "success", orgId });
+ return result;
+ } catch (error) {
+ recordScimOperationMetric({ startTime, operation, outcome: "failure", orgId, error });
+ throw error;
+ }
+ };
+
return {
createScimToken,
listScimTokens,
@@ -1624,16 +1643,16 @@ export const scimServiceFactory = ({
listScimEvents,
listScimUsers,
getScimUser,
- createScimUser,
- updateScimUser,
- replaceScimUser,
- deleteScimUser,
+ createScimUser: withScimMetric(ScimOperation.CreateUser, createScimUser),
+ updateScimUser: withScimMetric(ScimOperation.UpdateUser, updateScimUser),
+ replaceScimUser: withScimMetric(ScimOperation.ReplaceUser, replaceScimUser),
+ deleteScimUser: withScimMetric(ScimOperation.DeleteUser, deleteScimUser),
listScimGroups,
- createScimGroup,
+ createScimGroup: withScimMetric(ScimOperation.CreateGroup, createScimGroup),
getScimGroup,
- deleteScimGroup,
- replaceScimGroup,
- updateScimGroup,
+ deleteScimGroup: withScimMetric(ScimOperation.DeleteGroup, deleteScimGroup),
+ replaceScimGroup: withScimMetric(ScimOperation.ReplaceGroup, replaceScimGroup),
+ updateScimGroup: withScimMetric(ScimOperation.UpdateGroup, updateScimGroup),
fnValidateScimToken,
notifyExpiringTokens
};
diff --git a/backend/src/lib/cache/with-cache.ts b/backend/src/lib/cache/with-cache.ts
index 8b1747f524..b34726f20a 100644
--- a/backend/src/lib/cache/with-cache.ts
+++ b/backend/src/lib/cache/with-cache.ts
@@ -1,5 +1,6 @@
import { TKeyStoreFactory } from "@app/keystore/keystore";
import { logger } from "@app/lib/logger";
+import { permissionCacheFingerprintDurationHistogram, permissionCacheLookupCounter } from "@app/lib/telemetry/metrics";
type TCacheKeyStore = Pick<TKeyStoreFactory, "getItem" | "setItemWithExpiry">;
@@ -124,6 +125,7 @@ export const withCacheFingerprint = async <T>({
if (markerValue !== null && cachedDataStr !== null) {
try {
const { payload } = JSON.parse(cachedDataStr) as TCachedData<T>;
+ permissionCacheLookupCounter.add(1, { "cache.result": "marker_hit" });
return applyReviver(payload, reviver);
} catch (err) {
logger.warn(
@@ -135,9 +137,13 @@ export const withCacheFingerprint = async <T>({
// Marker expired or cache miss — compute fingerprint (1 lightweight DB read)
let currentFingerprint: string;
+ const fingerprintStart = Date.now();
try {
currentFingerprint = await fingerprintFetcher();
+ permissionCacheFingerprintDurationHistogram.record((Date.now() - fingerprintStart) / 1000);
} catch (err) {
+ permissionCacheFingerprintDurationHistogram.record((Date.now() - fingerprintStart) / 1000);
+ permissionCacheLookupCounter.add(1, { "cache.result": "fingerprint_error" });
logger.error({ err }, `withCacheFingerprint: fingerprint fetch failed, bypassing cache`);
return dataFetcher();
}
@@ -148,6 +154,7 @@ export const withCacheFingerprint = async <T>({
const cachedData = JSON.parse(cachedDataStr) as TCachedData<T>;
if (cachedData.fingerprint === currentFingerprint) {
await cacheSet(keyStore, markerKey, markerTtlSeconds, "1", "withCacheFingerprint: marker reset failed");
+ permissionCacheLookupCounter.add(1, { "cache.result": "fingerprint_match" });
return applyReviver(cachedData.payload, reviver);
}
} catch (err) {
@@ -159,6 +166,7 @@ export const withCacheFingerprint = async <T>({
}
// Fingerprint mismatch or no cached data — full re-fetch
+ permissionCacheLookupCounter.add(1, { "cache.result": "full_refetch" });
const result = await dataFetcher();
await cacheSet(
diff --git a/backend/src/lib/config/env.ts b/backend/src/lib/config/env.ts
index 431e7368ee..a359ed5be5 100644
--- a/backend/src/lib/config/env.ts
+++ b/backend/src/lib/config/env.ts
@@ -339,6 +339,7 @@ const envSchema = z
OTEL_COLLECTOR_BASIC_AUTH_USERNAME: zpStr(z.string().optional()),
OTEL_COLLECTOR_BASIC_AUTH_PASSWORD: zpStr(z.string().optional()),
OTEL_EXPORT_TYPE: z.enum(["prometheus", "otlp"]).optional(),
+ OTEL_DROP_LEGACY_METERS: zodStrBool.default("false"),
PYLON_API_KEY: zpStr(z.string().optional()),
DISABLE_AUDIT_LOG_GENERATION: zodStrBool.default("false"),
@@ -642,6 +643,7 @@ export const getTelemetryConfig = () => {
return {
useOtel: parsedEnv.data.OTEL_TELEMETRY_COLLECTION_ENABLED,
useDataDogTracer: parsedEnv.data.SHOULD_USE_DATADOG_TRACER,
+ dropLegacyMeters: parsedEnv.data.OTEL_DROP_LEGACY_METERS,
OTEL: {
otlpURL: parsedEnv.data.OTEL_EXPORT_OTLP_ENDPOINT,
otlpUser: parsedEnv.data.OTEL_COLLECTOR_BASIC_AUTH_USERNAME,
diff --git a/backend/src/lib/errors/classify.ts b/backend/src/lib/errors/classify.ts
new file mode 100644
index 0000000000..0a3fc9d2ed
--- /dev/null
+++ b/backend/src/lib/errors/classify.ts
@@ -0,0 +1,88 @@
+import jwt from "jsonwebtoken";
+
+import {
+ BadRequestError,
+ CryptographyError,
+ DatabaseError,
+ ForbiddenRequestError,
+ GatewayTimeoutError,
+ InternalServerError,
+ NotFoundError,
+ OidcAuthError,
+ PermissionBoundaryError,
+ PolicyViolationError,
+ RateLimitError,
+ ScimRequestError,
+ UnauthorizedError
+} from "./index";
+
+// Closed enum of error categories used as the `error.type` metric label across the API error counter,
+// queue job failure counter, audit log stream delivery counter, and any other metric that needs to
+// classify a thrown error. Keep cardinality bounded, never echo error messages back as labels.
+export const ERROR_TYPES = [
+ "validation",
+ "auth",
+ "permission",
+ "not_found",
+ "rate_limit",
+ "db",
+ "timeout",
+ "network",
+ "cryptography",
+ "policy",
+ "scim",
+ "oidc",
+ "internal",
+ "unknown"
+] as const;
+
+export type ErrorType = (typeof ERROR_TYPES)[number];
+
+// Duck-typed Axios error detection, avoids pulling axios as a hard dep here.
+const isAxiosLikeError = (err: unknown): err is { code?: string; response?: { status?: number } } =>
+ typeof err === "object" &&
+ err !== null &&
+ // axios sets isAxiosError = true on the error instance
+ (("isAxiosError" in err && (err as { isAxiosError?: boolean }).isAxiosError === true) ||
+ "response" in err ||
+ ("code" in err && typeof (err as { code?: string }).code === "string"));
+
+/**
+ * Classify a thrown error into one of the bounded ERROR_TYPES values. Used for the `error.type` label
+ * on metrics. Falls back to "unknown" when nothing matches, never throws.
+ */
+export const classifyError = (err: unknown): ErrorType => {
+ if (err instanceof jwt.JsonWebTokenError) return "auth";
+ if (err instanceof UnauthorizedError) return "auth";
+ if (err instanceof ForbiddenRequestError || err instanceof PermissionBoundaryError) return "permission";
+ if (err instanceof RateLimitError) return "rate_limit";
+ if (err instanceof NotFoundError) return "not_found";
+ if (err instanceof BadRequestError) return "validation";
+ if (err instanceof DatabaseError) return "db";
+ if (err instanceof GatewayTimeoutError) return "timeout";
+ if (err instanceof CryptographyError) return "cryptography";
+ if (err instanceof PolicyViolationError) return "policy";
+ if (err instanceof ScimRequestError) return "scim";
+ if (err instanceof OidcAuthError) return "oidc";
+ if (err instanceof InternalServerError) return "internal";
+
+ if (isAxiosLikeError(err)) {
+ const { code } = err as { code?: string };
+ if (code === "ECONNABORTED" || code === "ETIMEDOUT") return "timeout";
+ if (code === "ECONNRESET" || code === "ENOTFOUND" || code === "ECONNREFUSED") return "network";
+ const status = err.response?.status;
+ if (status === 429) return "rate_limit";
+ if (status === 401 || status === 403) return "auth";
+ if (status === 404) return "not_found";
+ if (status && status >= 400 && status < 500) return "validation";
+ return "network";
+ }
+
+ if (err instanceof Error) {
+ const msg = err.message?.toLowerCase() ?? "";
+ if (msg.includes("timeout") || msg.includes("timed out")) return "timeout";
+ if (msg.includes("connect") || msg.includes("network")) return "network";
+ }
+
+ return "unknown";
+};
diff --git a/backend/src/lib/telemetry/instrumentation.ts b/backend/src/lib/telemetry/instrumentation.ts
index 4fe8a8ef79..24c69c7ad2 100644
--- a/backend/src/lib/telemetry/instrumentation.ts
+++ b/backend/src/lib/telemetry/instrumentation.ts
@@ -3,8 +3,15 @@ import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-proto";
import { PrometheusExporter } from "@opentelemetry/exporter-prometheus";
import { registerInstrumentations } from "@opentelemetry/instrumentation";
import { HttpInstrumentation } from "@opentelemetry/instrumentation-http";
+import { RuntimeNodeInstrumentation } from "@opentelemetry/instrumentation-runtime-node";
import { Resource } from "@opentelemetry/resources";
-import { AggregationTemporality, MeterProvider, PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";
+import {
+ Aggregation,
+ AggregationTemporality,
+ MeterProvider,
+ PeriodicExportingMetricReader,
+ View
+} from "@opentelemetry/sdk-metrics";
import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from "@opentelemetry/semantic-conventions";
import tracer from "dd-trace";
import dotenv from "dotenv";
@@ -13,25 +20,75 @@ import { getTelemetryConfig } from "../config/env";
dotenv.config();
+// Strict allowlist of attribute keys that may appear on metrics emitted by the "InfisicalCore" meter.
+// Any attribute passed at a call site that's not in this list is silently dropped by the SDK View.
+// Cardinality control is centralized here. Call sites stay simple and a contributor adding an
+// unbounded label by mistake is caught automatically.
+//
+// If you need per-actor breakdowns, query the audit log table. It carries actorId, actorType, ip, userAgent and full event detail.
+// Legacy meters ("Infisical", "API") have no View — their existing labels flow through unchanged for
+// self-hosted backwards compatibility.
+const INFISICAL_CORE_METER_ATTRIBUTES = [
+ // HTTP semantics
+ "http.request.method",
+ "http.route",
+ "http.response.status_code",
+ // Tenant scope — bounded by org/project count
+ "infisical.organization.id",
+ "infisical.project.id",
+ "infisical.environment",
+ // Bounded enums
+ "infisical.auth.method",
+ "infisical.auth.result",
+ "queue.name",
+ "queue.state",
+ "job.name",
+ "error.type",
+ "outcome",
+ "attempts.exhausted",
+ "audit_log.event_type",
+ "audit_log.actor_type",
+ "audit_log.backend",
+ "audit_log.drop_reason",
+ "audit_log_stream.provider",
+ "kms.operation",
+ "kms.key_type",
+ "scim.operation",
+ "sso.provider",
+ "sso.action",
+ "db.pool.state",
+ "cache.result",
+ "rate_limit.bucket",
+ // Build info gauge labels — single-value per deploy, no cardinality concern
+ "service.version",
+ "git.commit.sha",
+ "node.version"
+];
+
const initTelemetryInstrumentation = ({
exportType,
otlpURL,
otlpUser,
otlpPassword,
- otlpPushInterval
+ otlpPushInterval,
+ dropLegacyMeters
}: {
exportType?: string;
otlpURL?: string;
otlpUser?: string;
otlpPassword?: string;
otlpPushInterval?: number;
+ dropLegacyMeters?: boolean;
}) => {
diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.DEBUG);
+ const serviceVersion = process.env.INFISICAL_PLATFORM_VERSION || "unknown";
+
const resource = Resource.default().merge(
new Resource({
[ATTR_SERVICE_NAME]: "infisical-core",
- [ATTR_SERVICE_VERSION]: "0.1.0"
+ [ATTR_SERVICE_VERSION]: serviceVersion,
+ "git.commit.sha": process.env.DD_GIT_COMMIT_SHA || "unknown"
})
);
@@ -62,15 +119,30 @@ const initTelemetryInstrumentation = ({
throw new Error("Invalid OTEL export type");
}
+ const views: View[] = [
+ new View({
+ meterName: "InfisicalCore",
+ attributeKeys: INFISICAL_CORE_METER_ATTRIBUTES
+ })
+ ];
+
+ if (dropLegacyMeters) {
+ views.push(
+ new View({ meterName: "Infisical", aggregation: Aggregation.Drop() }),
+ new View({ meterName: "API", aggregation: Aggregation.Drop() })
+ );
+ }
+
const meterProvider = new MeterProvider({
resource,
- readers: metricReaders
+ readers: metricReaders,
+ views
});
opentelemetry.metrics.setGlobalMeterProvider(meterProvider);
registerInstrumentations({
- instrumentations: [new HttpInstrumentation()]
+ instrumentations: [new HttpInstrumentation(), new RuntimeNodeInstrumentation()]
});
};
@@ -80,7 +152,10 @@ const setupTelemetry = () => {
if (appCfg.useOtel) {
// eslint-disable-next-line no-console
console.log("Initializing telemetry instrumentation");
- initTelemetryInstrumentation({ ...appCfg.OTEL });
+ initTelemetryInstrumentation({
+ ...appCfg.OTEL,
+ dropLegacyMeters: Boolean(appCfg.dropLegacyMeters)
+ });
}
if (appCfg.useDataDogTracer) {
diff --git a/backend/src/lib/telemetry/metrics.ts b/backend/src/lib/telemetry/metrics.ts
index 8489564666..a8c649d927 100644
--- a/backend/src/lib/telemetry/metrics.ts
+++ b/backend/src/lib/telemetry/metrics.ts
@@ -1,12 +1,20 @@
import { requestContext } from "@fastify/request-context";
import opentelemetry from "@opentelemetry/api";
+import type { Knex } from "knex";
+import { classifyError } from "@app/lib/errors/classify";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
import { getConfig } from "../config/env";
+// Legacy meter — kept for backwards compatibility. The pre-existing metrics below already ship with
+// high-cardinality labels documented in the docs.
const infisicalMeter = opentelemetry.metrics.getMeter("Infisical");
+// The MeterProvider applies a strict attribute allowlist (View in
+// instrumentation.ts) to anything emitted here, dropping high-cardinality labels at the SDK level.
+const infisicalCoreMeter = opentelemetry.metrics.getMeter("InfisicalCore");
+
export enum AuthAttemptAuthMethod {
EMAIL = "email",
SAML = "saml",
@@ -14,6 +22,7 @@ export enum AuthAttemptAuthMethod {
GOOGLE = "google",
GITHUB = "github",
GITLAB = "gitlab",
+ LDAP = "ldap",
TOKEN_AUTH = "token-auth",
UNIVERSAL_AUTH = "universal-auth",
KUBERNETES_AUTH = "kubernetes-auth",
@@ -34,6 +43,8 @@ export enum AuthAttemptAuthResult {
FAILURE = "failure"
}
+// -- Legacy instruments (documented public contract; do not change labels) --------------------------
+
export const authAttemptCounter = infisicalMeter.createCounter("infisical.auth.attempt.count", {
description: "Authentication attempts (both successful and failed)",
unit: "{attempt}"
@@ -165,3 +176,326 @@ export const recordKmipOperationMetric = (params: {
kmipOperationCounter.add(1, attributes);
}
};
+
+// -- New low-cardinality instruments (InfisicalCore meter) ------------------------------------------
+
+const isTelemetryEnabled = () => getConfig().OTEL_TELEMETRY_COLLECTION_ENABLED;
+
+/**
+ * Pull only the keys that survive the InfisicalCore View allowlist (see instrumentation.ts):
+ * organization.id, project.id. Returns an empty object when no request context is available
+ * (e.g. queue workers / cron handlers) — those call sites pass their own tenant labels.
+ */
+export const buildBaseAttributes = (): Record<string, string> => {
+ const attributes: Record<string, string> = {};
+
+ const orgId = requestContext.get(RequestContextKey.OrgId);
+ if (orgId) attributes["infisical.organization.id"] = orgId;
+
+ const projectDetails = requestContext.get(RequestContextKey.ProjectDetails);
+ if (projectDetails?.id) attributes["infisical.project.id"] = projectDetails.id;
+
+ return attributes;
+};
+
+// Queue worker lifecycle metrics. Wired in queue-service.ts via worker.on('completed' | 'failed' | 'stalled').
+export const queueJobCounter = infisicalCoreMeter.createCounter("infisical.queue.job.count", {
+ description: "Queue jobs processed by outcome (completed or failed)",
+ unit: "{job}"
+});
+
+export const queueJobDurationHistogram = infisicalCoreMeter.createHistogram("infisical.queue.job.duration", {
+ description:
+ "Queue job processing duration (worker pickup to completion). Skipped on framework-level failures where processedOn is undefined.",
+ unit: "s"
+});
+
+export const queueJobWaitHistogram = infisicalCoreMeter.createHistogram("infisical.queue.job.wait", {
+ description:
+ "Queue job wait time (queue contention only). Subtracts job.opts.delay so intentional scheduling doesn't inflate percentiles.",
+ unit: "s"
+});
+
+export const queueJobFailureCounter = infisicalCoreMeter.createCounter("infisical.queue.job.failure.count", {
+ description:
+ "Queue job failures classified by error type. attempts.exhausted=true means all retries are spent (real failure).",
+ unit: "{failure}"
+});
+
+export const queueStalledCounter = infisicalCoreMeter.createCounter("infisical.queue.stalled.count", {
+ description:
+ "Stalled queue jobs (lock expired without completing). Strongest signal of a stuck worker / OOM / network partition.",
+ unit: "{job}"
+});
+
+// Audit log lifecycle metrics. Wired in audit-log-queue.ts at pushToLog / worker handler / failed listener.
+export const auditLogEnqueuedCounter = infisicalCoreMeter.createCounter("infisical.audit_log.enqueued.count", {
+ description: "Audit log events enqueued for persistence, by event type and actor type.",
+ unit: "{event}"
+});
+
+export const auditLogPersistDurationHistogram = infisicalCoreMeter.createHistogram(
+ "infisical.audit_log.persist.duration",
+ {
+ description: "Latency from worker pickup to durable storage (postgres or clickhouse).",
+ unit: "s"
+ }
+);
+
+export const auditLogDroppedCounter = infisicalCoreMeter.createCounter("infisical.audit_log.dropped.count", {
+ description:
+ "Audit log events that failed to persist (max retries / validation / disabled). Operators should alert on this.",
+ unit: "{event}"
+});
+
+// Audit log stream metrics. Wired in audit-log-stream-service.ts streamLog().
+export const auditLogStreamDeliveryCounter = infisicalCoreMeter.createCounter(
+ "infisical.audit_log_stream.delivery.count",
+ {
+ description: "Per-provider audit log stream delivery attempts (success or failure).",
+ unit: "{delivery}"
+ }
+);
+
+export const auditLogStreamDeliveryDurationHistogram = infisicalCoreMeter.createHistogram(
+ "infisical.audit_log_stream.delivery.duration",
+ {
+ description: "Per-provider audit log stream delivery latency.",
+ unit: "s"
+ }
+);
+
+export const auditLogStreamAlertFiredCounter = infisicalCoreMeter.createCounter(
+ "infisical.audit_log_stream.alert.fired.count",
+ {
+ description: "Times the audit log stream sliding-window failure threshold tripped an admin alert.",
+ unit: "{alert}"
+ }
+);
+
+// KMS crypto metrics. Wired in kms-service.ts by wrapping the encryptor/decryptor returned by
+// encryptWithKmsKey / decryptWithKmsKey. Captures per-operation latency including external KMS network calls.
+export enum KmsCryptoOperation {
+ ENCRYPT = "encrypt",
+ DECRYPT = "decrypt"
+}
+
+export enum KmsKeyType {
+ INTERNAL = "internal",
+ AWS = "aws",
+ GCP = "gcp",
+ HSM = "hsm"
+}
+
+export const kmsCryptoCounter = infisicalCoreMeter.createCounter("infisical.kms.crypto.count", {
+ description: "KMS encrypt/decrypt operations by key type and outcome.",
+ unit: "{operation}"
+});
+
+export const kmsCryptoDurationHistogram = infisicalCoreMeter.createHistogram("infisical.kms.crypto.duration", {
+ description: "KMS encrypt/decrypt operation latency. External KMS (AWS/GCP) includes network round trip.",
+ unit: "s"
+});
+
+export const recordKmsCryptoMetric = (params: {
+ operation: KmsCryptoOperation;
+ keyType: KmsKeyType;
+ outcome: "success" | "failure";
+ durationSeconds: number;
+ errorType?: string;
+}) => {
+ if (!isTelemetryEnabled()) return;
+ const attributes = {
+ ...buildBaseAttributes(),
+ "kms.operation": params.operation,
+ "kms.key_type": params.keyType,
+ outcome: params.outcome,
+ ...(params.errorType ? { "error.type": params.errorType } : {})
+ };
+ kmsCryptoCounter.add(1, attributes);
+ kmsCryptoDurationHistogram.record(params.durationSeconds, attributes);
+};
+
+// Permission cache metrics. Wired in lib/cache/with-cache.ts withCacheFingerprint().
+export const permissionCacheLookupCounter = infisicalCoreMeter.createCounter(
+ "infisical.permission_cache.lookup.count",
+ {
+ description: "Permission cache lookups by branch: short-marker hit, fingerprint match, full refetch.",
+ unit: "{lookup}"
+ }
+);
+
+export const permissionCacheFingerprintDurationHistogram = infisicalCoreMeter.createHistogram(
+ "infisical.permission_cache.fingerprint.duration",
+ {
+ description: "Time spent computing the permission fingerprint (lightweight DB read on marker expiry).",
+ unit: "s"
+ }
+);
+
+export const coreHttpErrorCounter = infisicalCoreMeter.createCounter("infisical.core.http.error.count", {
+ description: "API errors with bounded error classification. Labels limited to InfisicalCore View allowlist.",
+ unit: "{error}"
+});
+
+// Rate limit metric. Wired in error-handler.ts on RateLimitError.
+export const rateLimitExceededCounter = infisicalCoreMeter.createCounter("infisical.rate_limit.exceeded.count", {
+ description: "HTTP 429 responses (rate limit exceeded).",
+ unit: "{request}"
+});
+
+// Build info. Constant-value observable gauge that emits 1 with build identification labels every export.
+const buildInfoGauge = infisicalCoreMeter.createObservableGauge("infisical.build.info", {
+ description: "Always 1. Labels carry build identification (version, git sha, node version)."
+});
+
+buildInfoGauge.addCallback((result) => {
+ if (!isTelemetryEnabled()) return;
+ result.observe(1, {
+ "service.version": process.env.INFISICAL_PLATFORM_VERSION || "unknown",
+ "git.commit.sha": process.env.DD_GIT_COMMIT_SHA || "unknown",
+ "node.version": process.version
+ });
+});
+
+// -- Authentication latency (InfisicalCore meter) ---------------------------------------------------
+export const authAttemptDurationHistogram = infisicalCoreMeter.createHistogram("infisical.auth.attempt.duration", {
+ description:
+ "Authentication attempt latency by method and result. External verifications (SAML/OIDC/Kubernetes/cloud) include the IdP/provider network round trip.",
+ unit: "s"
+});
+
+export const recordAuthAttemptMetric = (params: {
+ startTime: number;
+ method: AuthAttemptAuthMethod;
+ result: AuthAttemptAuthResult;
+ error?: unknown;
+ orgId?: string;
+}) => {
+ if (!isTelemetryEnabled()) return;
+ const attributes: Record<string, string> = {
+ "infisical.auth.method": params.method,
+ "infisical.auth.result": params.result
+ };
+ if (params.error !== undefined) attributes["error.type"] = classifyError(params.error);
+ if (params.orgId) attributes["infisical.organization.id"] = params.orgId;
+ authAttemptDurationHistogram.record((performance.now() - params.startTime) / 1000, attributes);
+};
+
+// Machine identity access token renewals. Distinct from the auth.attempt series (initial login).
+export const tokenRenewalCounter = infisicalCoreMeter.createCounter("infisical.auth.token.renewal.count", {
+ description: "Machine identity access token renewal attempts by outcome.",
+ unit: "{renewal}"
+});
+
+export const recordTokenRenewalMetric = (params: {
+ outcome: "success" | "failure";
+ authMethod?: string;
+ error?: unknown;
+}) => {
+ if (!isTelemetryEnabled()) return;
+ const attributes: Record<string, string> = { outcome: params.outcome };
+ if (params.authMethod) attributes["infisical.auth.method"] = params.authMethod;
+ if (params.error !== undefined) attributes["error.type"] = classifyError(params.error);
+ tokenRenewalCounter.add(1, attributes);
+};
+
+// -- SCIM provisioning (InfisicalCore meter) --------------------------------------------------------
+export enum ScimOperation {
+ CreateUser = "create_user",
+ UpdateUser = "update_user",
+ ReplaceUser = "replace_user",
+ DeleteUser = "delete_user",
+ CreateGroup = "create_group",
+ UpdateGroup = "update_group",
+ ReplaceGroup = "replace_group",
+ DeleteGroup = "delete_group"
+}
+
+export const scimOperationCounter = infisicalCoreMeter.createCounter("infisical.scim.operation.count", {
+ description: "SCIM provisioning operations (user/group create, update, replace, delete) by outcome.",
+ unit: "{operation}"
+});
+
+export const scimOperationDurationHistogram = infisicalCoreMeter.createHistogram("infisical.scim.operation.duration", {
+ description: "SCIM provisioning operation latency by operation type and outcome.",
+ unit: "s"
+});
+
+export const recordScimOperationMetric = (params: {
+ startTime: number;
+ operation: ScimOperation;
+ outcome: "success" | "failure";
+ orgId?: string;
+ error?: unknown;
+}) => {
+ if (!isTelemetryEnabled()) return;
+ const attributes: Record<string, string> = {
+ "scim.operation": params.operation,
+ outcome: params.outcome
+ };
+ if (params.orgId) attributes["infisical.organization.id"] = params.orgId;
+ if (params.error !== undefined) attributes["error.type"] = classifyError(params.error);
+ scimOperationCounter.add(1, attributes);
+ scimOperationDurationHistogram.record((performance.now() - params.startTime) / 1000, attributes);
+};
+
+// -- SSO config lifecycle (InfisicalCore meter) -----------------------------------------------------
+export enum SsoProvider {
+ Saml = "saml",
+ Oidc = "oidc",
+ Ldap = "ldap"
+}
+
+export enum SsoConfigAction {
+ Create = "create",
+ Update = "update"
+}
+
+export const ssoConfigChangeCounter = infisicalCoreMeter.createCounter("infisical.sso.config.change.count", {
+ description: "SSO configuration changes (create/update) by provider. Detects unexpected SSO reconfiguration.",
+ unit: "{change}"
+});
+
+export const recordSsoConfigChangeMetric = (params: {
+ provider: SsoProvider;
+ action: SsoConfigAction;
+ orgId?: string;
+}) => {
+ if (!isTelemetryEnabled()) return;
+ const attributes: Record<string, string> = {
+ "sso.provider": params.provider,
+ "sso.action": params.action
+ };
+ if (params.orgId) attributes["infisical.organization.id"] = params.orgId;
+ ssoConfigChangeCounter.add(1, attributes);
+};
+
+// -- Database connection-pool observable gauge (InfisicalCore meter) --------------------------------
+// Registered once at boot from main.ts with the primary Knex instance. Reads in-memory tarn pool
+// counters, so it's cheap to observe on every export.
+export const registerInfrastructureMetrics = (db: Knex) => {
+ const dbPoolGauge = infisicalCoreMeter.createObservableGauge("infisical.db.pool.connections", {
+ description: "Knex/tarn connection pool counts by state (used, free, pending).",
+ unit: "{connection}"
+ });
+
+ dbPoolGauge.addCallback((result) => {
+ if (!isTelemetryEnabled()) return;
+ const pool = (
+ db.client as
+ | {
+ pool?: {
+ numUsed?: () => number;
+ numFree?: () => number;
+ numPendingAcquires?: () => number;
+ };
+ }
+ | undefined
+ )?.pool;
+ if (!pool) return;
+ result.observe(pool.numUsed?.() ?? 0, { "db.pool.state": "used" });
+ result.observe(pool.numFree?.() ?? 0, { "db.pool.state": "free" });
+ result.observe(pool.numPendingAcquires?.() ?? 0, { "db.pool.state": "pending" });
+ });
+};
diff --git a/backend/src/main.ts b/backend/src/main.ts
index cef7a188a2..7c3f1b06e7 100644
--- a/backend/src/main.ts
+++ b/backend/src/main.ts
@@ -19,6 +19,7 @@ import { axiosResponseInterceptor } from "./lib/config/request";
import { removeTemporaryBaseDirectory } from "./lib/files";
import { initLogger } from "./lib/logger";
import { CustomLogger } from "./lib/logger/logger";
+import { registerInfrastructureMetrics } from "./lib/telemetry/metrics";
import { queueServiceFactory } from "./queue";
import { main } from "./server/app";
import { bootstrapCheck } from "./server/boot-strap-check";
@@ -57,6 +58,9 @@ const run = async () => {
readReplicas: databaseCredentials.readReplicas
});
+ // Register connection-pool and entity-count observable gauges. No-ops when telemetry is disabled.
+ registerInfrastructureMetrics(db);
+
const superAdminDAL = superAdminDALFactory(db);
const kmsRootConfigDAL = kmsRootConfigDALFactory(db);
const envConfig = await initEnvConfig(hsmService, kmsRootConfigDAL, superAdminDAL, logger);
diff --git a/backend/src/queue/queue-service.ts b/backend/src/queue/queue-service.ts
index 1c631bb901..bb6849ea18 100644
--- a/backend/src/queue/queue-service.ts
+++ b/backend/src/queue/queue-service.ts
@@ -1,6 +1,8 @@
+import opentelemetry from "@opentelemetry/api";
import {
Job,
JobSchedulerJson,
+ MetricsTime,
Queue,
QueueOptions,
RepeatOptions,
@@ -28,7 +30,15 @@ import {
import { getConfig } from "@app/lib/config/env";
import { buildRedisFromConfig, TRedisConfigKeys } from "@app/lib/config/redis";
import { crypto } from "@app/lib/crypto";
+import { classifyError } from "@app/lib/errors/classify";
import { logger } from "@app/lib/logger";
+import {
+ queueJobCounter,
+ queueJobDurationHistogram,
+ queueJobFailureCounter,
+ queueJobWaitHistogram,
+ queueStalledCounter
+} from "@app/lib/telemetry/metrics";
import { QueueWorkerProfile } from "@app/lib/types";
import {
TAppConnectionCredentialRotationRotateJobPayload,
@@ -586,6 +596,34 @@ export const queueServiceFactory = (redisCfg: TRedisConfigKeys): TQueueServiceFa
Record<QueueName, Worker<TQueueJobTypes[QueueName]["payload"], void, TQueueJobTypes[QueueName]["name"]>>
> = {};
+ // Observable gauge for queue depth. The SDK invokes the callback on each export (every 30s for OTLP
+ // push, on each scrape for Prometheus). Iterates only initialized queues in queueContainer; one
+ // snapshot covers all ~30 named queues. Failures are swallowed because metrics must never crash the app.
+ const queueDepthGauge = opentelemetry.metrics
+ .getMeter("InfisicalCore")
+ .createObservableGauge("infisical.queue.depth", {
+ description: "Number of jobs in each queue state (waiting, active, delayed, failed, completed)",
+ unit: "{job}"
+ });
+
+ queueDepthGauge.addCallback(async (observableResult) => {
+ if (!getConfig().OTEL_TELEMETRY_COLLECTION_ENABLED) return;
+ await Promise.allSettled(
+ Object.entries(queueContainer).map(async ([name, q]) => {
+ if (!q) return;
+ try {
+ const counts = await q.getJobCounts();
+ Object.entries(counts).forEach(([state, count]) => {
+ if (typeof count !== "number") return;
+ observableResult.observe(count, { "queue.name": name, "queue.state": state });
+ });
+ } catch (err) {
+ logger.warn({ err, queue: name }, `queue.depth gauge: getJobCounts failed [queue=${name}]`);
+ }
+ })
+ );
+ });
+
// Remove orphaned job schedulers left in Redis by deleted queues.
// Queues migrated to the cronJob system (cron-job.ts) are listed here so their
// BullMQ schedulers and pending jobs are cleaned up on first boot of the new image.
@@ -688,12 +726,62 @@ export const queueServiceFactory = (redisCfg: TRedisConfigKeys): TQueueServiceFa
return;
}
- workerContainer[name] = new Worker(name, jobFn, {
+ const worker = new Worker(name, jobFn, {
prefix: isClusterMode ? `{${name}}` : undefined,
...fipsSettings,
...queueSettings,
+ // Enable BullMQ's built-in per-minute completion/failure tracking in Redis. Survives pod restarts
+ // (OTel cumulative counters reset), useful as a fallback when Prometheus retention is short.
+ metrics: { maxDataPoints: MetricsTime.ONE_WEEK * 2 },
connection
});
+
+ // Cross-cutting metric emission for every queue. Single registration covers all ~30 named queues
+ // since BullMQ Worker is an EventEmitter and we attach the listeners here.
+ worker.on("completed", (job) => {
+ const baseAttrs = { "queue.name": name, "job.name": job.name } as Record<string, string>;
+ queueJobCounter.add(1, { ...baseAttrs, outcome: "completed" });
+
+ if (typeof job.processedOn === "number" && typeof job.timestamp === "number") {
+ const durationMs = Date.now() - job.processedOn;
+ queueJobDurationHistogram.record(durationMs / 1000, { ...baseAttrs, outcome: "completed" });
+
+ // Wait = (worker pickup) - (enqueue time + intentional delay). Subtracting opts.delay is what
+ // makes this measure queue contention, not scheduling
+ const intentionalDelayMs = job.opts.delay ?? 0;
+ const waitMs = Math.max(0, job.processedOn - job.timestamp - intentionalDelayMs);
+ queueJobWaitHistogram.record(waitMs / 1000, baseAttrs);
+ }
+ });
+
+ worker.on("failed", (job, err) => {
+ const baseAttrs = {
+ "queue.name": name,
+ "job.name": job?.name ?? "unknown"
+ } as Record<string, string>;
+ queueJobCounter.add(1, { ...baseAttrs, outcome: "failed" });
+
+ // Skip duration on framework-level failures (job hydration failed before start). Emitting 0
+ // would pollute the histogram with phantom zero-duration points.
+ if (job && typeof job.processedOn === "number") {
+ const durationMs = Date.now() - job.processedOn;
+ queueJobDurationHistogram.record(durationMs / 1000, { ...baseAttrs, outcome: "failed" });
+ }
+
+ const errorType = classifyError(err);
+ const attemptsExhausted = !!(job?.opts.attempts && job.attemptsMade && job.attemptsMade >= job.opts.attempts);
+ queueJobFailureCounter.add(1, {
+ ...baseAttrs,
+ "error.type": errorType,
+ "attempts.exhausted": attemptsExhausted ? "true" : "false"
+ });
+ });
+
+ worker.on("stalled", () => {
+ queueStalledCounter.add(1, { "queue.name": name });
+ });
+
+ workerContainer[name] = worker;
};
const listen: TQueueServiceFactory["listen"] = (name, event, listener) => {
diff --git a/backend/src/server/plugins/error-handler.ts b/backend/src/server/plugins/error-handler.ts
index 7893ff9a58..443962f68b 100644
--- a/backend/src/server/plugins/error-handler.ts
+++ b/backend/src/server/plugins/error-handler.ts
@@ -22,7 +22,9 @@ import {
ScimRequestError,
UnauthorizedError
} from "@app/lib/errors";
+import { classifyError } from "@app/lib/errors/classify";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
+import { coreHttpErrorCounter, rateLimitExceededCounter } from "@app/lib/telemetry/metrics";
enum JWTErrors {
JwtExpired = "jwt expired",
@@ -132,6 +134,15 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider
}
errorCounter.add(1, attributes);
+
+ const coreAttrs: Record<string, string | number> = {
+ "http.request.method": method,
+ "http.route": route,
+ "error.type": classifyError(error)
+ };
+ if (orgId) coreAttrs["infisical.organization.id"] = orgId;
+ if (projectDetails?.id) coreAttrs["infisical.project.id"] = projectDetails.id;
+ coreHttpErrorCounter.add(1, coreAttrs);
}
if (error instanceof BadRequestError) {
@@ -203,6 +214,10 @@ export const fastifyErrHandler = fastifyPlugin(async (server: FastifyZodProvider
details: error?.details
});
} else if (error instanceof RateLimitError) {
+ rateLimitExceededCounter.add(1, {
+ "http.route": req.routerPath ?? "unknown",
+ "http.request.method": req.method
+ });
void res.status(HttpStatusCodes.TooManyRequests).send({
reqId: req.id,
statusCode: HttpStatusCodes.TooManyRequests,
diff --git a/backend/src/server/routes/v1/sso-router.ts b/backend/src/server/routes/v1/sso-router.ts
index d594acb4b4..faceccc9ee 100644
--- a/backend/src/server/routes/v1/sso-router.ts
+++ b/backend/src/server/routes/v1/sso-router.ts
@@ -23,7 +23,12 @@ import { logger } from "@app/lib/logger";
import { ms } from "@app/lib/ms";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
import { fetchGithubEmails, fetchGithubUser } from "@app/lib/requests/github";
-import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";
+import {
+ AuthAttemptAuthMethod,
+ AuthAttemptAuthResult,
+ authAttemptCounter,
+ recordAuthAttemptMetric
+} from "@app/lib/telemetry/metrics";
import { authRateLimit } from "@app/server/config/rateLimiter";
import { addAuthOriginDomainCookie } from "@app/server/lib/cookie";
import { AuthMethod, ProviderAuthResult } from "@app/services/auth/auth-type";
@@ -54,6 +59,7 @@ export const registerOauthMiddlewares = (server: FastifyZodProvider) => {
},
// eslint-disable-next-line
async (req, _accessToken, _refreshToken, profile, cb) => {
+ const authMetricStartTime = performance.now();
// @ts-expect-error this is because this is express type and not fastify
const callbackPort = req.session.get("callbackPort");
// @ts-expect-error this is because this is express type and not fastify
@@ -107,6 +113,13 @@ export const registerOauthMiddlewares = (server: FastifyZodProvider) => {
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.GOOGLE,
+ result: AuthAttemptAuthResult.SUCCESS,
+ orgId: loginResult.orgId
+ });
+
cb(null, loginResult);
} catch (error) {
logger.error(error);
@@ -119,6 +132,12 @@ export const registerOauthMiddlewares = (server: FastifyZodProvider) => {
"user_agent.original": requestContext.get(RequestContextKey.UserAgent)
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.GOOGLE,
+ result: AuthAttemptAuthResult.FAILURE,
+ error
+ });
cb(error as Error, false);
}
}
@@ -145,6 +164,7 @@ export const registerOauthMiddlewares = (server: FastifyZodProvider) => {
},
// eslint-disable-next-line
async (req: any, accessToken: string, _refreshToken: string, _profile: any, done: Function) => {
+ const authMetricStartTime = performance.now();
const ghEmails = await fetchGithubEmails(accessToken);
const { email } = ghEmails.filter((gitHubEmail) => gitHubEmail.primary && gitHubEmail.verified)[0];
@@ -195,6 +215,13 @@ export const registerOauthMiddlewares = (server: FastifyZodProvider) => {
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.GITHUB,
+ result: AuthAttemptAuthResult.SUCCESS,
+ orgId: loginResult.orgId
+ });
+
done(null, { ...loginResult, externalProviderAccessToken: accessToken });
} catch (err) {
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
@@ -206,6 +233,12 @@ export const registerOauthMiddlewares = (server: FastifyZodProvider) => {
"user_agent.original": requestContext.get(RequestContextKey.UserAgent)
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.GITHUB,
+ result: AuthAttemptAuthResult.FAILURE,
+ error: err
+ });
logger.error(err);
done(err as Error, false);
}
@@ -231,6 +264,7 @@ export const registerOauthMiddlewares = (server: FastifyZodProvider) => {
pkce: true
},
async (req: any, _accessToken: string, _refreshToken: string, profile: any, cb: any) => {
+ const authMetricStartTime = performance.now();
const email = profile.emails[0].value;
try {
@@ -275,6 +309,13 @@ export const registerOauthMiddlewares = (server: FastifyZodProvider) => {
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.GITLAB,
+ result: AuthAttemptAuthResult.SUCCESS,
+ orgId: loginResult.orgId
+ });
+
return cb(null, loginResult);
} catch (error) {
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
@@ -287,6 +328,13 @@ export const registerOauthMiddlewares = (server: FastifyZodProvider) => {
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.GITLAB,
+ result: AuthAttemptAuthResult.FAILURE,
+ error
+ });
+
logger.error(error);
cb(error as Error, false);
}
diff --git a/backend/src/services/auth/auth-login-service.ts b/backend/src/services/auth/auth-login-service.ts
index 8a0a54779b..2c409df4fe 100644
--- a/backend/src/services/auth/auth-login-service.ts
+++ b/backend/src/services/auth/auth-login-service.ts
@@ -27,7 +27,12 @@ import { getMinExpiresIn, removeTrailingSlash } from "@app/lib/fn";
import { logger } from "@app/lib/logger";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
-import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";
+import {
+ AuthAttemptAuthMethod,
+ AuthAttemptAuthResult,
+ authAttemptCounter,
+ recordAuthAttemptMetric
+} from "@app/lib/telemetry/metrics";
import { sanitizeEmail, validateEmail } from "@app/lib/validator";
import { getUserAgentType } from "@app/server/plugins/audit-log";
import { getServerCfg } from "@app/services/super-admin/super-admin-service";
@@ -528,6 +533,7 @@ export const authLoginServiceFactory = ({
userAgent: string;
captchaToken?: string;
}) => {
+ const authMetricStartTime = performance.now();
const appCfg = getConfig();
const email = sanitizeEmail(unsanitizedEmail);
@@ -587,6 +593,12 @@ export const authLoginServiceFactory = ({
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.EMAIL,
+ result: AuthAttemptAuthResult.SUCCESS
+ });
+
return {
tokens: {
accessToken: token.access,
@@ -605,6 +617,13 @@ export const authLoginServiceFactory = ({
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.EMAIL,
+ result: AuthAttemptAuthResult.FAILURE,
+ error
+ });
+
throw error;
}
};
diff --git a/backend/src/services/identity-access-token/identity-access-token-service.ts b/backend/src/services/identity-access-token/identity-access-token-service.ts
index 0fbfe02f3b..864b9a108b 100644
--- a/backend/src/services/identity-access-token/identity-access-token-service.ts
+++ b/backend/src/services/identity-access-token/identity-access-token-service.ts
@@ -6,6 +6,7 @@ import { getConfig } from "@app/lib/config/env";
import { crypto } from "@app/lib/crypto";
import { UnauthorizedError } from "@app/lib/errors";
import { checkIPAgainstBlocklist, TIp } from "@app/lib/ip";
+import { recordTokenRenewalMetric } from "@app/lib/telemetry/metrics";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -370,7 +371,7 @@ export const identityAccessTokenServiceFactory = ({
};
};
- const renewAccessToken = async ({ accessToken }: TRenewAccessTokenDTO) => {
+ const renewAccessTokenInner = async ({ accessToken }: TRenewAccessTokenDTO) => {
const appCfg = getConfig();
const decodedToken = assertMinimalRenewClaims(verifyAccessTokenJwt(accessToken));
@@ -474,6 +475,17 @@ export const identityAccessTokenServiceFactory = ({
};
};
+ const renewAccessToken = async (dto: TRenewAccessTokenDTO) => {
+ try {
+ const result = await renewAccessTokenInner(dto);
+ recordTokenRenewalMetric({ outcome: "success" });
+ return result;
+ } catch (error) {
+ recordTokenRenewalMetric({ outcome: "failure", error });
+ throw error;
+ }
+ };
+
const revokeAccessToken = async (accessToken: string) => {
const appCfg = getConfig();
diff --git a/backend/src/services/identity-alicloud-auth/identity-alicloud-auth-service.ts b/backend/src/services/identity-alicloud-auth/identity-alicloud-auth-service.ts
index bb0c91e244..862e73c13e 100644
--- a/backend/src/services/identity-alicloud-auth/identity-alicloud-auth-service.ts
+++ b/backend/src/services/identity-alicloud-auth/identity-alicloud-auth-service.ts
@@ -26,7 +26,12 @@ import { logger } from "@app/lib/logger";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
-import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";
+import {
+ AuthAttemptAuthMethod,
+ AuthAttemptAuthResult,
+ authAttemptCounter,
+ recordAuthAttemptMetric
+} from "@app/lib/telemetry/metrics";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -75,6 +80,7 @@ export const identityAliCloudAuthServiceFactory = ({
identityAccessTokenService
}: TIdentityAliCloudAuthServiceFactoryDep) => {
const login = async ({ identityId, organizationSlug, ...params }: TLoginAliCloudAuthDTO) => {
+ const authMetricStartTime = performance.now();
const appCfg = getConfig();
const identityAliCloudAuth = await identityAliCloudAuthDAL.findOne({ identityId });
if (!identityAliCloudAuth) {
@@ -215,6 +221,13 @@ export const identityAliCloudAuthServiceFactory = ({
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.ALICLOUD_AUTH,
+ result: AuthAttemptAuthResult.SUCCESS,
+ orgId: org.id
+ });
+
return {
identityAliCloudAuth,
accessToken,
@@ -234,6 +247,14 @@ export const identityAliCloudAuthServiceFactory = ({
"user_agent.original": requestContext.get(RequestContextKey.UserAgent)
});
}
+
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.ALICLOUD_AUTH,
+ result: AuthAttemptAuthResult.FAILURE,
+ orgId: org.id,
+ error
+ });
throw error;
}
};
diff --git a/backend/src/services/identity-aws-auth/identity-aws-auth-service.ts b/backend/src/services/identity-aws-auth/identity-aws-auth-service.ts
index 87dc278c9f..1537dfe79b 100644
--- a/backend/src/services/identity-aws-auth/identity-aws-auth-service.ts
+++ b/backend/src/services/identity-aws-auth/identity-aws-auth-service.ts
@@ -27,7 +27,12 @@ import { logger } from "@app/lib/logger";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
-import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";
+import {
+ AuthAttemptAuthMethod,
+ AuthAttemptAuthResult,
+ authAttemptCounter,
+ recordAuthAttemptMetric
+} from "@app/lib/telemetry/metrics";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -115,6 +120,7 @@ export const identityAwsAuthServiceFactory = ({
iamRequestHeaders,
organizationSlug
}: TLoginAwsAuthDTO) => {
+ const authMetricStartTime = performance.now();
const appCfg = getConfig();
const identityAwsAuth = await identityAwsAuthDAL.findOne({ identityId });
if (!identityAwsAuth) {
@@ -316,6 +322,13 @@ export const identityAwsAuthServiceFactory = ({
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.AWS_AUTH,
+ result: AuthAttemptAuthResult.SUCCESS,
+ orgId: org.id
+ });
+
return { accessToken, identityAwsAuth, identityAccessToken, identity };
} catch (error) {
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
@@ -330,6 +343,14 @@ export const identityAwsAuthServiceFactory = ({
"user_agent.original": requestContext.get(RequestContextKey.UserAgent)
});
}
+
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.AWS_AUTH,
+ result: AuthAttemptAuthResult.FAILURE,
+ orgId: org.id,
+ error
+ });
throw error;
}
};
diff --git a/backend/src/services/identity-azure-auth/identity-azure-auth-service.ts b/backend/src/services/identity-azure-auth/identity-azure-auth-service.ts
index 684ba7e325..fff2af57c3 100644
--- a/backend/src/services/identity-azure-auth/identity-azure-auth-service.ts
+++ b/backend/src/services/identity-azure-auth/identity-azure-auth-service.ts
@@ -22,7 +22,12 @@ import { extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
-import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";
+import {
+ AuthAttemptAuthMethod,
+ AuthAttemptAuthResult,
+ authAttemptCounter,
+ recordAuthAttemptMetric
+} from "@app/lib/telemetry/metrics";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -71,6 +76,7 @@ export const identityAzureAuthServiceFactory = ({
identityAccessTokenService
}: TIdentityAzureAuthServiceFactoryDep) => {
const login = async ({ identityId, jwt: azureJwt, organizationSlug }: TLoginAzureAuthDTO) => {
+ const authMetricStartTime = performance.now();
const appCfg = getConfig();
const identityAzureAuth = await identityAzureAuthDAL.findOne({ identityId });
if (!identityAzureAuth) {
@@ -218,6 +224,13 @@ export const identityAzureAuthServiceFactory = ({
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.AZURE_AUTH,
+ result: AuthAttemptAuthResult.SUCCESS,
+ orgId: org.id
+ });
+
return { accessToken, identityAzureAuth, identityAccessToken, identity };
} catch (error) {
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
@@ -232,6 +245,14 @@ export const identityAzureAuthServiceFactory = ({
"user_agent.original": requestContext.get(RequestContextKey.UserAgent)
});
}
+
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.AZURE_AUTH,
+ result: AuthAttemptAuthResult.FAILURE,
+ orgId: org.id,
+ error
+ });
throw error;
}
};
diff --git a/backend/src/services/identity-gcp-auth/identity-gcp-auth-service.ts b/backend/src/services/identity-gcp-auth/identity-gcp-auth-service.ts
index 67c550a1f7..3a1af9daf5 100644
--- a/backend/src/services/identity-gcp-auth/identity-gcp-auth-service.ts
+++ b/backend/src/services/identity-gcp-auth/identity-gcp-auth-service.ts
@@ -22,7 +22,12 @@ import { extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
-import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";
+import {
+ AuthAttemptAuthMethod,
+ AuthAttemptAuthResult,
+ authAttemptCounter,
+ recordAuthAttemptMetric
+} from "@app/lib/telemetry/metrics";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -69,6 +74,7 @@ export const identityGcpAuthServiceFactory = ({
identityAccessTokenService
}: TIdentityGcpAuthServiceFactoryDep) => {
const login = async ({ identityId, jwt: gcpJwt, organizationSlug }: TLoginGcpAuthDTO) => {
+ const authMetricStartTime = performance.now();
const appCfg = getConfig();
const identityGcpAuth = await identityGcpAuthDAL.findOne({ identityId });
if (!identityGcpAuth) {
@@ -261,6 +267,13 @@ export const identityGcpAuthServiceFactory = ({
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.GCP_AUTH,
+ result: AuthAttemptAuthResult.SUCCESS,
+ orgId: org.id
+ });
+
return { accessToken, identityGcpAuth, identityAccessToken, identity };
} catch (error) {
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
@@ -275,6 +288,14 @@ export const identityGcpAuthServiceFactory = ({
"user_agent.original": requestContext.get(RequestContextKey.UserAgent)
});
}
+
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.GCP_AUTH,
+ result: AuthAttemptAuthResult.FAILURE,
+ orgId: org.id,
+ error
+ });
throw error;
}
};
diff --git a/backend/src/services/identity-jwt-auth/identity-jwt-auth-service.ts b/backend/src/services/identity-jwt-auth/identity-jwt-auth-service.ts
index e71325f9e3..ff217d8ed3 100644
--- a/backend/src/services/identity-jwt-auth/identity-jwt-auth-service.ts
+++ b/backend/src/services/identity-jwt-auth/identity-jwt-auth-service.ts
@@ -32,7 +32,12 @@ import { extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
-import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";
+import {
+ AuthAttemptAuthMethod,
+ AuthAttemptAuthResult,
+ authAttemptCounter,
+ recordAuthAttemptMetric
+} from "@app/lib/telemetry/metrics";
import { getValueByDot } from "@app/lib/template/dot-access";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
@@ -85,6 +90,7 @@ export const identityJwtAuthServiceFactory = ({
identityAccessTokenService
}: TIdentityJwtAuthServiceFactoryDep) => {
const login = async ({ identityId, jwt: jwtValue, organizationSlug }: TLoginJwtAuthDTO) => {
+ const authMetricStartTime = performance.now();
const appCfg = getConfig();
const identityJwtAuth = await identityJwtAuthDAL.findOne({ identityId });
if (!identityJwtAuth) {
@@ -377,6 +383,13 @@ export const identityJwtAuthServiceFactory = ({
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.JWT_AUTH,
+ result: AuthAttemptAuthResult.SUCCESS,
+ orgId: org.id
+ });
+
return { accessToken, identityJwtAuth, identityAccessToken, identity };
} catch (error) {
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
@@ -391,6 +404,14 @@ export const identityJwtAuthServiceFactory = ({
"user_agent.original": requestContext.get(RequestContextKey.UserAgent)
});
}
+
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.JWT_AUTH,
+ result: AuthAttemptAuthResult.FAILURE,
+ orgId: org.id,
+ error
+ });
throw error;
}
};
diff --git a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts
index 2275bcca0e..8722fb17ec 100644
--- a/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts
+++ b/backend/src/services/identity-kubernetes-auth/identity-kubernetes-auth-service.ts
@@ -47,7 +47,12 @@ import { logger } from "@app/lib/logger";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
-import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";
+import {
+ AuthAttemptAuthMethod,
+ AuthAttemptAuthResult,
+ authAttemptCounter,
+ recordAuthAttemptMetric
+} from "@app/lib/telemetry/metrics";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -285,6 +290,7 @@ export const identityKubernetesAuthServiceFactory = ({
};
const login = async ({ identityId, jwt: serviceAccountJwt, organizationSlug }: TLoginKubernetesAuthDTO) => {
+ const authMetricStartTime = performance.now();
const appCfg = getConfig();
const identityKubernetesAuth = await identityKubernetesAuthDAL.findOne({ identityId });
if (!identityKubernetesAuth) {
@@ -731,6 +737,13 @@ export const identityKubernetesAuthServiceFactory = ({
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.KUBERNETES_AUTH,
+ result: AuthAttemptAuthResult.SUCCESS,
+ orgId: org.id
+ });
+
return { accessToken, identityKubernetesAuth, identityAccessToken, identity };
} catch (error) {
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
@@ -746,6 +759,14 @@ export const identityKubernetesAuthServiceFactory = ({
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.KUBERNETES_AUTH,
+ result: AuthAttemptAuthResult.FAILURE,
+ orgId: org.id,
+ error
+ });
+
if (isKnownError(error)) {
throw error;
}
diff --git a/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts b/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts
index 5816699821..7440666921 100644
--- a/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts
+++ b/backend/src/services/identity-ldap-auth/identity-ldap-auth-service.ts
@@ -33,7 +33,12 @@ import { logger } from "@app/lib/logger";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
-import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";
+import {
+ AuthAttemptAuthMethod,
+ AuthAttemptAuthResult,
+ authAttemptCounter,
+ recordAuthAttemptMetric
+} from "@app/lib/telemetry/metrics";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { ActorType } from "../auth/auth-type";
@@ -162,6 +167,7 @@ export const identityLdapAuthServiceFactory = ({
};
const login = async ({ identityId, organizationSlug }: TLoginLdapAuthDTO) => {
+ const authMetricStartTime = performance.now();
const appCfg = getConfig();
const identityLdapAuth = await identityLdapAuthDAL.findOne({ identityId });
@@ -281,6 +287,13 @@ export const identityLdapAuthServiceFactory = ({
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.LDAP_AUTH,
+ result: AuthAttemptAuthResult.SUCCESS,
+ orgId: org.id
+ });
+
return { accessToken, identityLdapAuth, identityAccessToken, identity };
} catch (error) {
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
@@ -295,6 +308,14 @@ export const identityLdapAuthServiceFactory = ({
"user_agent.original": requestContext.get(RequestContextKey.UserAgent)
});
}
+
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.LDAP_AUTH,
+ result: AuthAttemptAuthResult.FAILURE,
+ orgId: org.id,
+ error
+ });
throw error;
}
};
diff --git a/backend/src/services/identity-oci-auth/identity-oci-auth-service.ts b/backend/src/services/identity-oci-auth/identity-oci-auth-service.ts
index 62f3665d87..0c3146753b 100644
--- a/backend/src/services/identity-oci-auth/identity-oci-auth-service.ts
+++ b/backend/src/services/identity-oci-auth/identity-oci-auth-service.ts
@@ -27,7 +27,12 @@ import { logger } from "@app/lib/logger";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
-import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";
+import {
+ AuthAttemptAuthMethod,
+ AuthAttemptAuthResult,
+ authAttemptCounter,
+ recordAuthAttemptMetric
+} from "@app/lib/telemetry/metrics";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -73,6 +78,7 @@ export const identityOciAuthServiceFactory = ({
identityAccessTokenService
}: TIdentityOciAuthServiceFactoryDep) => {
const login = async ({ identityId, headers, userOcid, organizationSlug }: TLoginOciAuthDTO) => {
+ const authMetricStartTime = performance.now();
const appCfg = getConfig();
const identityOciAuth = await identityOciAuthDAL.findOne({ identityId });
if (!identityOciAuth) {
@@ -226,6 +232,13 @@ export const identityOciAuthServiceFactory = ({
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.OCI_AUTH,
+ result: AuthAttemptAuthResult.SUCCESS,
+ orgId: org.id
+ });
+
return {
identityOciAuth,
accessToken,
@@ -245,6 +258,14 @@ export const identityOciAuthServiceFactory = ({
"user_agent.original": requestContext.get(RequestContextKey.UserAgent)
});
}
+
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.OCI_AUTH,
+ result: AuthAttemptAuthResult.FAILURE,
+ orgId: org.id,
+ error
+ });
throw error;
}
};
diff --git a/backend/src/services/identity-oidc-auth/identity-oidc-auth-service.ts b/backend/src/services/identity-oidc-auth/identity-oidc-auth-service.ts
index ebb2d19dff..96cebf9a79 100644
--- a/backend/src/services/identity-oidc-auth/identity-oidc-auth-service.ts
+++ b/backend/src/services/identity-oidc-auth/identity-oidc-auth-service.ts
@@ -34,7 +34,12 @@ import { logger } from "@app/lib/logger";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
-import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";
+import {
+ AuthAttemptAuthMethod,
+ AuthAttemptAuthResult,
+ authAttemptCounter,
+ recordAuthAttemptMetric
+} from "@app/lib/telemetry/metrics";
import { getValueByDot } from "@app/lib/template/dot-access";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
@@ -86,6 +91,7 @@ export const identityOidcAuthServiceFactory = ({
identityAccessTokenService
}: TIdentityOidcAuthServiceFactoryDep) => {
const login = async ({ identityId, jwt: oidcJwt, organizationSlug }: TLoginOidcAuthDTO) => {
+ const authMetricStartTime = performance.now();
const appCfg = getConfig();
const identityOidcAuth = await identityOidcAuthDAL.findOne({ identityId });
if (!identityOidcAuth) {
@@ -551,6 +557,13 @@ export const identityOidcAuthServiceFactory = ({
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.OIDC_AUTH,
+ result: AuthAttemptAuthResult.SUCCESS,
+ orgId: org.id
+ });
+
return { accessToken, identityOidcAuth, identityAccessToken, identity, oidcTokenData: verifiedTokenData };
} catch (error) {
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
@@ -565,6 +578,14 @@ export const identityOidcAuthServiceFactory = ({
"user_agent.original": requestContext.get(RequestContextKey.UserAgent)
});
}
+
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.OIDC_AUTH,
+ result: AuthAttemptAuthResult.FAILURE,
+ orgId: org.id,
+ error
+ });
throw error;
}
};
diff --git a/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-service.ts b/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-service.ts
index 5418a813ea..6b994a4773 100644
--- a/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-service.ts
+++ b/backend/src/services/identity-spiffe-auth/identity-spiffe-auth-service.ts
@@ -31,7 +31,12 @@ import { logger } from "@app/lib/logger";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
-import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";
+import {
+ AuthAttemptAuthMethod,
+ AuthAttemptAuthResult,
+ authAttemptCounter,
+ recordAuthAttemptMetric
+} from "@app/lib/telemetry/metrics";
import { blockLocalAndPrivateIpAddresses } from "@app/lib/validator";
import { ActorType } from "../auth/auth-type";
@@ -289,6 +294,7 @@ export const identitySpiffeAuthServiceFactory = ({
};
const login = async ({ identityId, jwt: jwtValue, organizationSlug }: TLoginSpiffeAuthDTO) => {
+ const authMetricStartTime = performance.now();
const appCfg = getConfig();
const identitySpiffeAuth = await identitySpiffeAuthDAL.findOne({ identityId });
if (!identitySpiffeAuth) {
@@ -455,6 +461,13 @@ export const identitySpiffeAuthServiceFactory = ({
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.SPIFFE_AUTH,
+ result: AuthAttemptAuthResult.SUCCESS,
+ orgId: org.id
+ });
+
return { accessToken, identitySpiffeAuth, identityAccessToken, identity };
} catch (error) {
if (appCfg.OTEL_TELEMETRY_COLLECTION_ENABLED) {
@@ -469,6 +482,14 @@ export const identitySpiffeAuthServiceFactory = ({
"user_agent.original": requestContext.get(RequestContextKey.UserAgent)
});
}
+
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.SPIFFE_AUTH,
+ result: AuthAttemptAuthResult.FAILURE,
+ orgId: org.id,
+ error
+ });
throw error;
}
};
diff --git a/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-service.ts b/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-service.ts
index 35358d22bf..9b2ccc5c27 100644
--- a/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-service.ts
+++ b/backend/src/services/identity-tls-cert-auth/identity-tls-cert-auth-service.ts
@@ -24,7 +24,12 @@ import { extractIPDetails, isValidIpOrCidr, TIp } from "@app/lib/ip";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
-import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";
+import {
+ AuthAttemptAuthMethod,
+ AuthAttemptAuthResult,
+ authAttemptCounter,
+ recordAuthAttemptMetric
+} from "@app/lib/telemetry/metrics";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -83,6 +88,7 @@ export const identityTlsCertAuthServiceFactory = ({
clientCertificate,
organizationSlug
}) => {
+ const authMetricStartTime = performance.now();
const appCfg = getConfig();
const identityTlsCertAuth = await identityTlsCertAuthDAL.findOne({ identityId });
if (!identityTlsCertAuth) {
@@ -265,6 +271,13 @@ export const identityTlsCertAuthServiceFactory = ({
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.TLS_CERT_AUTH,
+ result: AuthAttemptAuthResult.SUCCESS,
+ orgId: org.id
+ });
+
return {
identityTlsCertAuth,
accessToken,
@@ -284,6 +297,14 @@ export const identityTlsCertAuthServiceFactory = ({
"user_agent.original": requestContext.get(RequestContextKey.UserAgent)
});
}
+
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.TLS_CERT_AUTH,
+ result: AuthAttemptAuthResult.FAILURE,
+ orgId: org.id,
+ error
+ });
throw error;
}
};
diff --git a/backend/src/services/identity-ua/identity-ua-service.ts b/backend/src/services/identity-ua/identity-ua-service.ts
index babc162ac2..1bdd222f7e 100644
--- a/backend/src/services/identity-ua/identity-ua-service.ts
+++ b/backend/src/services/identity-ua/identity-ua-service.ts
@@ -26,7 +26,12 @@ import { logger } from "@app/lib/logger";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
-import { AuthAttemptAuthMethod, AuthAttemptAuthResult, authAttemptCounter } from "@app/lib/telemetry/metrics";
+import {
+ AuthAttemptAuthMethod,
+ AuthAttemptAuthResult,
+ authAttemptCounter,
+ recordAuthAttemptMetric
+} from "@app/lib/telemetry/metrics";
import { ActorType } from "../auth/auth-type";
import { TIdentityDALFactory } from "../identity/identity-dal";
@@ -86,6 +91,7 @@ export const identityUaServiceFactory = ({
identityAccessTokenService
}: TIdentityUaServiceFactoryDep) => {
const login = async ({ clientId, clientSecret, ip, organizationSlug }: TLoginUaDTO) => {
+ const authMetricStartTime = performance.now();
const appCfg = getConfig();
const identityUa = await identityUaDAL.findOne({ clientId });
if (!identityUa) {
@@ -356,6 +362,13 @@ export const identityUaServiceFactory = ({
});
}
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.UNIVERSAL_AUTH,
+ result: AuthAttemptAuthResult.SUCCESS,
+ orgId: org.id
+ });
+
return {
accessToken,
identityUa,
@@ -378,6 +391,14 @@ export const identityUaServiceFactory = ({
"user_agent.original": requestContext.get(RequestContextKey.UserAgent)
});
}
+
+ recordAuthAttemptMetric({
+ startTime: authMetricStartTime,
+ method: AuthAttemptAuthMethod.UNIVERSAL_AUTH,
+ result: AuthAttemptAuthResult.FAILURE,
+ orgId: org.id,
+ error
+ });
throw error;
}
};
diff --git a/backend/src/services/kms/kms-service.ts b/backend/src/services/kms/kms-service.ts
index 7d640fbdf3..80a9f80fbf 100644
--- a/backend/src/services/kms/kms-service.ts
+++ b/backend/src/services/kms/kms-service.ts
@@ -20,10 +20,12 @@ import { crypto } from "@app/lib/crypto/cryptography";
import { detectPqcVariantFromDer } from "@app/lib/crypto/pqc/pqc-crypto";
import { AsymmetricKeyAlgorithm, isPqcKeyAlgorithm, KMS_TO_OPENSSL_NAME, signingService } from "@app/lib/crypto/sign";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
+import { classifyError } from "@app/lib/errors/classify";
import { logger } from "@app/lib/logger";
import { alphaNumericNanoId } from "@app/lib/nanoid";
import { requestMemoKeys } from "@app/lib/request-context/memo-keys";
import { requestMemoize } from "@app/lib/request-context/request-memoizer";
+import { KmsCryptoOperation, KmsKeyType, recordKmsCryptoMetric } from "@app/lib/telemetry/metrics";
import {
getByteLengthForSymmetricEncryptionAlgorithm,
KMS_ROOT_CONFIG_UUID,
@@ -335,10 +337,27 @@ export const kmsServiceFactory = ({
throw new BadRequestError({ message: "Invalid KMS provider." });
}
+ const externalKeyType = kmsDoc.externalKms.provider === KmsProviders.Aws ? KmsKeyType.AWS : KmsKeyType.GCP;
return async ({ cipherTextBlob }: Pick<TDecryptWithKmsDTO, "cipherTextBlob">) => {
+ const cryptoStart = Date.now();
try {
const { data } = await externalKms.decrypt(cipherTextBlob);
+ recordKmsCryptoMetric({
+ operation: KmsCryptoOperation.DECRYPT,
+ keyType: externalKeyType,
+ outcome: "success",
+ durationSeconds: (Date.now() - cryptoStart) / 1000
+ });
return data;
+ } catch (err) {
+ recordKmsCryptoMetric({
+ operation: KmsCryptoOperation.DECRYPT,
+ keyType: externalKeyType,
+ outcome: "failure",
+ durationSeconds: (Date.now() - cryptoStart) / 1000,
+ errorType: classifyError(err)
+ });
+ throw err;
} finally {
await externalKms.cleanup();
}
@@ -356,9 +375,27 @@ export const kmsServiceFactory = ({
const kmsKey = keyCipher.decrypt(kmsDoc.internalKms?.encryptedKey as Buffer, ROOT_ENCRYPTION_KEY);
return ({ cipherTextBlob: versionedCipherTextBlob }: Pick<TDecryptWithKmsDTO, "cipherTextBlob">) => {
- const cipherTextBlob = versionedCipherTextBlob.subarray(0, -KMS_VERSION_BLOB_LENGTH);
- const decryptedBlob = dataCipher.decrypt(cipherTextBlob, kmsKey);
- return Promise.resolve(decryptedBlob);
+ const cryptoStart = Date.now();
+ try {
+ const cipherTextBlob = versionedCipherTextBlob.subarray(0, -KMS_VERSION_BLOB_LENGTH);
+ const decryptedBlob = dataCipher.decrypt(cipherTextBlob, kmsKey);
+ recordKmsCryptoMetric({
+ operation: KmsCryptoOperation.DECRYPT,
+ keyType: KmsKeyType.INTERNAL,
+ outcome: "success",
+ durationSeconds: (Date.now() - cryptoStart) / 1000
+ });
+ return Promise.resolve(decryptedBlob);
+ } catch (err) {
+ recordKmsCryptoMetric({
+ operation: KmsCryptoOperation.DECRYPT,
+ keyType: KmsKeyType.INTERNAL,
+ outcome: "failure",
+ durationSeconds: (Date.now() - cryptoStart) / 1000,
+ errorType: classifyError(err)
+ });
+ throw err;
+ }
};
};
@@ -617,10 +654,27 @@ export const kmsServiceFactory = ({
throw new BadRequestError({ message: "Invalid KMS provider." });
}
+ const externalKeyType = kmsDoc.externalKms.provider === KmsProviders.Aws ? KmsKeyType.AWS : KmsKeyType.GCP;
return async ({ plainText }: Pick<TEncryptWithKmsDTO, "plainText">) => {
+ const cryptoStart = Date.now();
try {
const { encryptedBlob } = await externalKms.encrypt(plainText);
+ recordKmsCryptoMetric({
+ operation: KmsCryptoOperation.ENCRYPT,
+ keyType: externalKeyType,
+ outcome: "success",
+ durationSeconds: (Date.now() - cryptoStart) / 1000
+ });
return { cipherTextBlob: encryptedBlob };
+ } catch (err) {
+ recordKmsCryptoMetric({
+ operation: KmsCryptoOperation.ENCRYPT,
+ keyType: externalKeyType,
+ outcome: "failure",
+ durationSeconds: (Date.now() - cryptoStart) / 1000,
+ errorType: classifyError(err)
+ });
+ throw err;
} finally {
await externalKms.cleanup();
}
@@ -636,14 +690,32 @@ export const kmsServiceFactory = ({
const keyCipher = symmetricCipherService(SymmetricKeyAlgorithm.AES_GCM_256);
const dataCipher = symmetricCipherService(encryptionAlgorithm);
return ({ plainText }: Pick<TEncryptWithKmsDTO, "plainText">) => {
- const kmsKey = keyCipher.decrypt(kmsDoc.internalKms?.encryptedKey as Buffer, ROOT_ENCRYPTION_KEY);
- const encryptedPlainTextBlob = dataCipher.encrypt(plainText, kmsKey);
+ const cryptoStart = Date.now();
+ try {
+ const kmsKey = keyCipher.decrypt(kmsDoc.internalKms?.encryptedKey as Buffer, ROOT_ENCRYPTION_KEY);
+ const encryptedPlainTextBlob = dataCipher.encrypt(plainText, kmsKey);
- // Buffer#1 encrypted text + Buffer#2 version number
- const versionBlob = Buffer.from(KMS_VERSION, "utf8"); // length is 3
- const cipherTextBlob = Buffer.concat([encryptedPlainTextBlob, versionBlob]);
+ // Buffer#1 encrypted text + Buffer#2 version number
+ const versionBlob = Buffer.from(KMS_VERSION, "utf8"); // length is 3
+ const cipherTextBlob = Buffer.concat([encryptedPlainTextBlob, versionBlob]);
- return Promise.resolve({ cipherTextBlob });
+ recordKmsCryptoMetric({
+ operation: KmsCryptoOperation.ENCRYPT,
+ keyType: KmsKeyType.INTERNAL,
+ outcome: "success",
+ durationSeconds: (Date.now() - cryptoStart) / 1000
+ });
+ return Promise.resolve({ cipherTextBlob });
+ } catch (err) {
+ recordKmsCryptoMetric({
+ operation: KmsCryptoOperation.ENCRYPT,
+ keyType: KmsKeyType.INTERNAL,
+ outcome: "failure",
+ durationSeconds: (Date.now() - cryptoStart) / 1000,
+ errorType: classifyError(err)
+ });
+ throw err;
+ }
};
};
diff --git a/docs/self-hosting/configuration/envars.mdx b/docs/self-hosting/configuration/envars.mdx
index f42850169b..857c3a27ce 100644
--- a/docs/self-hosting/configuration/envars.mdx
+++ b/docs/self-hosting/configuration/envars.mdx
@@ -870,6 +870,10 @@ If the export type is set to `otlp`, you will have to configure a value for `OTE
The password for authenticating with the telemetry collector.
</ParamField>
+<ParamField query="OTEL_DROP_LEGACY_METERS" type="string" default="false" optional>
+ When set to `true`, the SDK discards all data points from the high-cardinality `Infisical` and `API` meters before aggregation. The instruments still exist in code (no errors), but nothing is stored or exported. Only bounded-cardinality `InfisicalCore` metrics are emitted. Useful for large or multi-tenant deployments where per-actor label cardinality is too expensive. See [Monitoring & Telemetry](/self-hosting/guides/monitoring-telemetry#two-meter-tiers) for details.
+</ParamField>
+
## Identity Auth Method
<ParamField
diff --git a/docs/self-hosting/guides/monitoring-telemetry.mdx b/docs/self-hosting/guides/monitoring-telemetry.mdx
index a78c8fe6d8..c424306a07 100644
--- a/docs/self-hosting/guides/monitoring-telemetry.mdx
+++ b/docs/self-hosting/guides/monitoring-telemetry.mdx
@@ -340,7 +340,25 @@ Replace `otel-collector:8889` with the actual hostname and port where your OpenT
## Available Metrics
-Infisical exposes the following key metrics in OpenTelemetry format:
+Infisical emits metrics on two OpenTelemetry meters simultaneously. Choose which to scrape based on your deployment scale.
+
+- **`Infisical` meter (high-cardinality):** the original metrics (`infisical.http.server.request.*`, `infisical.http.server.error.count`, `infisical.secret.read.count`, `infisical.auth.attempt.count`, `infisical.kmip.operation.count`) include per-actor labels such as `user.email`, `identity.name`, `client.address`, `user_agent.original`, `organization.name`, `project.name`, `secret.path`, and `secret.name`. Useful for small self-hosted deployments where you want per-user visibility directly in Grafana. May become expensive at large scale due to label cardinality.
+- **`InfisicalCore` meter (bounded-cardinality):** all newer metrics (queue, audit log, KMS, permission cache, rate limit, build info, `infisical.core.http.error.count`, authentication latency, token renewal, SSO config changes, SCIM provisioning, and database connection pool) use only IDs and bounded enums as labels. No names, emails, IPs, or user agents. Designed for large or multi-tenant deployments. Per-actor detail is available in audit logs instead.
+
+Both meters emit at the same time. If you are a small self-hosted instance and find the per-actor labels useful, keep using the `Infisical`-meter metrics. For larger deployments, scrape only the `InfisicalCore` metrics to keep cardinality under control.
+
+To eliminate the in-memory cost of the legacy meters entirely, set `OTEL_DROP_LEGACY_METERS=true`. When enabled, the SDK discards all data points from the `Infisical` and `API` meters before aggregation. The instruments still exist in code (no errors), but nothing is stored or exported. Only `InfisicalCore` metrics are emitted. Defaults to `false`.
+
+For per-user / per-identity / per-IP breakdowns, query the audit log table. It carries `actorId`, `actorType`, `ip`, `userAgent` and full event detail. Metrics give you the *rate* and *latency*; audit logs give you the *who*.
+
+### Resource attributes (every metric)
+
+Every emitted metric carries these resource-level attributes (no per-metric cardinality cost):
+
+- `service.name` — the fixed identifier for the Infisical backend service
+- `service.version` — the release version or git SHA of the running Infisical instance
+- `git.commit.sha` — the exact commit the build was produced from, when available
+- `deployment.environment` — the environment the instance is running in (e.g. `production`, `staging`, `development`)
### Core API Metrics
@@ -483,6 +501,115 @@ These metrics track authentication attempts and outcomes, enabling you to monito
- `user_agent.original` (string, optional): User agent/client information
- `infisical.auth.attempt.username` (string, optional): Attempted username/email (if available)
</Accordion>
+ <Accordion title="Authentication Latency (InfisicalCore)">
+ **Metric Name**: `infisical.auth.attempt.duration`
+
+ **Type**: Histogram
+
+ **Unit**: `s` (seconds)
+
+ **Description**: Authentication attempt latency by method and result. External verifications (SAML, OIDC, Kubernetes, AWS, GCP, Azure, OCI, AliCloud, ...) include the IdP/provider network round trip, so this is what tells you "SAML logins suddenly got slow" or "Kubernetes auth verification is timing out". Covers every user and machine identity login flow, including LDAP user login.
+
+ **Attributes** (bounded):
+ - `infisical.auth.method` (string): Authentication method (`email`, `saml`, `oidc`, `google`, `github`, `gitlab`, `ldap`, `universal-auth`, `kubernetes-auth`, `aws-auth`, `gcp-auth`, `azure-auth`, `oci-auth`, `alicloud-auth`, `tls-cert-auth`, `oidc-auth`, `jwt-auth`, `ldap-auth`, `spiffe-auth`)
+ - `infisical.auth.result` (string): `success` or `failure`
+ - `error.type` (string, optional): Bounded failure classification (present on failures)
+ - `infisical.organization.id` (string, optional): Organization ID when known
+ </Accordion>
+ <Accordion title="Token Renewal (InfisicalCore)">
+ **Metric Name**: `infisical.auth.token.renewal.count`
+
+ **Type**: Counter
+
+ **Unit**: `{renewal}`
+
+ **Description**: Machine identity access token renewal attempts by outcome. Distinct from `infisical.auth.attempt.*`, which tracks initial logins.
+
+ **Attributes** (bounded):
+ - `outcome` (string): `success` or `failure`
+ - `infisical.auth.method` (string, optional): Identity auth method when known
+ - `error.type` (string, optional): Bounded failure classification (present on failures)
+ </Accordion>
+</AccordionGroup>
+
+<Note>
+ The `infisical.auth.attempt.count` counter lives on the high-cardinality `Infisical` meter, while
+ `infisical.auth.attempt.duration` and `infisical.auth.token.renewal.count` live on the bounded
+ `InfisicalCore` meter. There is no per-identity "active identity" gauge: there is no reliable
+ last-authenticated timestamp in the schema, so monthly/weekly active identity counts are best derived
+ from the `infisical.auth.attempt.*` series in your metrics backend (e.g. `count by (...)` over a time
+ window) rather than a snapshot gauge.
+</Note>
+
+### SSO Configuration Metrics (InfisicalCore)
+
+These metrics track changes to SSO configuration, helping you detect unexpected reconfiguration of identity providers.
+
+<AccordionGroup>
+ <Accordion title="SSO Config Changes">
+ **Metric Name**: `infisical.sso.config.change.count`
+
+ **Type**: Counter
+
+ **Unit**: `{change}`
+
+ **Description**: SSO configuration create/update events by provider.
+
+ **Attributes** (bounded):
+ - `sso.provider` (string): `saml`, `oidc`, or `ldap`
+ - `sso.action` (string): `create` or `update`
+ - `infisical.organization.id` (string, optional): Organization ID
+ </Accordion>
+</AccordionGroup>
+
+### SCIM Provisioning Metrics (InfisicalCore)
+
+These metrics track SCIM provisioning operations (user and group lifecycle), enabling you to monitor directory-sync throughput and failures.
+
+<AccordionGroup>
+ <Accordion title="SCIM Operations">
+ **Metric Name**: `infisical.scim.operation.count`
+
+ **Type**: Counter
+
+ **Unit**: `{operation}`
+
+ **Description**: SCIM provisioning operations by type and outcome.
+
+ **Attributes** (bounded):
+ - `scim.operation` (string): `create_user`, `update_user`, `replace_user`, `delete_user`, `create_group`, `update_group`, `replace_group`, `delete_group`
+ - `outcome` (string): `success` or `failure`
+ - `infisical.organization.id` (string, optional): Organization ID
+ - `error.type` (string, optional): Bounded failure classification (present on failures)
+ </Accordion>
+ <Accordion title="SCIM Operation Latency">
+ **Metric Name**: `infisical.scim.operation.duration`
+
+ **Type**: Histogram
+
+ **Unit**: `s` (seconds)
+
+ **Description**: Latency of SCIM provisioning operations. Same attributes as `infisical.scim.operation.count`.
+ </Accordion>
+</AccordionGroup>
+
+### Database Metrics (InfisicalCore)
+
+This metric provides visibility into connection pool health. Query latency is intentionally not emitted, as managed databases (for example, Amazon RDS Performance Insights) already report per-statement latency at the server.
+
+<AccordionGroup>
+ <Accordion title="Connection Pool">
+ **Metric Name**: `infisical.db.pool.connections`
+
+ **Type**: Observable Gauge
+
+ **Unit**: `{connection}`
+
+ **Description**: Knex/tarn connection pool counts, observed on each export. Watch `pending` rising with `used` saturated for pool exhaustion.
+
+ **Attributes** (bounded):
+ - `db.pool.state` (string): `used`, `free`, or `pending`
+ </Accordion>
</AccordionGroup>
### Key Management Interoperability Protocol Metrics
@@ -547,6 +674,291 @@ These metrics monitor secret synchronization operations between Infisical and ex
</Accordion>
</AccordionGroup>
+### Job Queue Metrics (InfisicalCore)
+
+These metrics give per-queue visibility into BullMQ worker health: throughput, latency, contention, failures, and stalls. Use these to detect stuck workers, queue backlog, and which queues are failing.
+
+<AccordionGroup>
+ <Accordion title="Queue Job Count">
+ **Metric Name**: `infisical.queue.job.count`
+
+ **Type**: Counter
+
+ **Unit**: `{job}`
+
+ **Description**: Jobs processed by outcome.
+
+ **Attributes**:
+ - `queue.name` (string): e.g. `audit-log`, `secret-sync`, `secret-rotation-v2`
+ - `job.name` (string): BullMQ job name
+ - `outcome` (string): `completed` or `failed`
+ </Accordion>
+
+ <Accordion title="Queue Job Duration">
+ **Metric Name**: `infisical.queue.job.duration`
+
+ **Type**: Histogram
+
+ **Unit**: `s`
+
+ **Description**: Job processing duration (worker pickup to completion). Skipped on framework-level failures where `processedOn` is undefined, so the histogram is not polluted with phantom zero-duration points.
+
+ **Attributes**: `queue.name`, `job.name`, `outcome`
+ </Accordion>
+
+ <Accordion title="Queue Job Wait">
+ **Metric Name**: `infisical.queue.job.wait`
+
+ **Type**: Histogram
+
+ **Unit**: `s`
+
+ **Description**: Time the job spent waiting for a worker (queue contention). Subtracts the configured `job.opts.delay` so intentional scheduling doesn't inflate percentiles. Only recorded on `completed` jobs.
+
+ **Attributes**: `queue.name`, `job.name`
+ </Accordion>
+
+ <Accordion title="Queue Job Failure (classified)">
+ **Metric Name**: `infisical.queue.job.failure.count`
+
+ **Type**: Counter
+
+ **Unit**: `{failure}`
+
+ **Description**: Failures classified by error type. Alert when `attempts.exhausted="true"` — those are real failures (all retries spent), not transient errors.
+
+ **Attributes**:
+ - `queue.name`, `job.name`
+ - `error.type` (string): one of `validation`, `auth`, `permission`, `not_found`, `rate_limit`, `db`, `timeout`, `network`, `cryptography`, `policy`, `scim`, `oidc`, `internal`, `unknown`
+ - `attempts.exhausted` (string): `"true"` or `"false"`
+ </Accordion>
+
+ <Accordion title="Queue Stalled">
+ **Metric Name**: `infisical.queue.stalled.count`
+
+ **Type**: Counter
+
+ **Unit**: `{job}`
+
+ **Description**: Stalled jobs (the worker's lock on a job expired without completing it). Strongest signal of a stuck worker, OOM, or network partition. Previously invisible.
+
+ **Attributes**: `queue.name`
+ </Accordion>
+
+ <Accordion title="Queue Depth">
+ **Metric Name**: `infisical.queue.depth`
+
+ **Type**: Observable Gauge
+
+ **Unit**: `{job}`
+
+ **Description**: Current number of jobs in each queue state. The SDK invokes the callback on each scrape / push interval.
+
+ **Attributes**:
+ - `queue.name` (string)
+ - `queue.state` (string): `waiting`, `active`, `delayed`, `failed`, `completed`, etc.
+ </Accordion>
+</AccordionGroup>
+
+### Audit Log Metrics (InfisicalCore)
+
+End-to-end audit-log pipeline observability: how many events get enqueued per event type / actor, how long persistence takes, and how many are ultimately dropped.
+
+<AccordionGroup>
+ <Accordion title="Audit Log Enqueued">
+ **Metric Name**: `infisical.audit_log.enqueued.count`
+
+ **Type**: Counter
+
+ **Unit**: `{event}`
+
+ **Description**: Audit log events enqueued to BullMQ for persistence.
+
+ **Attributes**:
+ - `audit_log.event_type` (string): e.g. `LOGIN_USER`, `CREATE_SECRET`, ...
+ - `audit_log.actor_type` (string): `user`, `identity`, `service`
+ - `infisical.organization.id` (string, optional)
+ </Accordion>
+
+ <Accordion title="Audit Log Persist Duration">
+ **Metric Name**: `infisical.audit_log.persist.duration`
+
+ **Type**: Histogram
+
+ **Unit**: `s`
+
+ **Description**: Latency from worker pickup to durable storage.
+
+ **Attributes**:
+ - `audit_log.backend` (string): `postgres` or `clickhouse`
+ - `audit_log.event_type` (string)
+ - `infisical.organization.id` (string)
+ </Accordion>
+
+ <Accordion title="Audit Log Dropped">
+ **Metric Name**: `infisical.audit_log.dropped.count`
+
+ **Type**: Counter
+
+ **Unit**: `{event}`
+
+ **Description**: Audit log events that exhausted BullMQ retries and were not persisted. **Operators should alert when this is non-zero** — a dropped audit event is a compliance signal.
+
+ **Attributes**:
+ - `audit_log.event_type` (string)
+ - `audit_log.drop_reason` (string): `max_retries`
+ - `infisical.organization.id` (string, optional)
+ </Accordion>
+</AccordionGroup>
+
+### Audit Log Stream Metrics (InfisicalCore)
+
+Per-provider observability for the audit-log stream feature (Datadog, Splunk, Custom HTTP, Azure, Cribl).
+
+<AccordionGroup>
+ <Accordion title="Audit Log Stream Delivery">
+ **Metric Name**: `infisical.audit_log_stream.delivery.count`
+
+ **Type**: Counter
+
+ **Unit**: `{delivery}`
+
+ **Description**: Per-provider stream delivery attempts.
+
+ **Attributes**:
+ - `audit_log_stream.provider` (string): `datadog`, `splunk`, `custom`, `azure`, `cribl`
+ - `infisical.organization.id` (string)
+ - `outcome` (string): `success` or `failure`
+ - `error.type` (string, only on failure): one of the closed enum values
+ </Accordion>
+
+ <Accordion title="Audit Log Stream Delivery Duration">
+ **Metric Name**: `infisical.audit_log_stream.delivery.duration`
+
+ **Type**: Histogram
+
+ **Unit**: `s`
+
+ **Description**: Per-provider stream delivery latency (HTTP round trip to the SIEM).
+
+ **Attributes**: `audit_log_stream.provider`, `infisical.organization.id`, `outcome`, `error.type` (on failure)
+ </Accordion>
+
+ <Accordion title="Audit Log Stream Alert Fired">
+ **Metric Name**: `infisical.audit_log_stream.alert.fired.count`
+
+ **Type**: Counter
+
+ **Unit**: `{alert}`
+
+ **Description**: Times the sliding-window failure threshold (default 20 failures in 5 minutes) tripped an admin email alert. Useful for catching repeated SIEM degradations even if individual deliveries succeed in between.
+
+ **Attributes**: `audit_log_stream.provider`, `infisical.organization.id`
+ </Accordion>
+</AccordionGroup>
+
+### KMS Crypto Metrics (InfisicalCore)
+
+KMS encrypt/decrypt is the hottest path in the system (every secret read and write touches it). These metrics capture per-operation latency, including the network round trip for external KMS providers (AWS / GCP).
+
+<AccordionGroup>
+ <Accordion title="KMS Crypto Count">
+ **Metric Name**: `infisical.kms.crypto.count`
+
+ **Type**: Counter
+
+ **Unit**: `{operation}`
+
+ **Description**: KMS encrypt/decrypt operations by key type and outcome.
+
+ **Attributes**:
+ - `kms.operation` (string): `encrypt` or `decrypt`
+ - `kms.key_type` (string): `internal`, `aws`, `gcp`, `hsm`
+ - `outcome` (string): `success` or `failure`
+ - `error.type` (string, only on failure)
+ </Accordion>
+
+ <Accordion title="KMS Crypto Duration">
+ **Metric Name**: `infisical.kms.crypto.duration`
+
+ **Type**: Histogram
+
+ **Unit**: `s`
+
+ **Description**: Per-operation latency. Internal KMS is local AES-GCM (sub-millisecond). External KMS includes a network round trip (typically 50-200ms).
+
+ **Attributes**: `kms.operation`, `kms.key_type`, `outcome`, `error.type` (on failure)
+ </Accordion>
+</AccordionGroup>
+
+### Permission Cache Metrics (InfisicalCore)
+
+The CASL permission cache uses a fingerprint-based two-tier scheme. These metrics tell you whether the cache is doing its job.
+
+<AccordionGroup>
+ <Accordion title="Permission Cache Lookup">
+ **Metric Name**: `infisical.permission_cache.lookup.count`
+
+ **Type**: Counter
+
+ **Unit**: `{lookup}`
+
+ **Description**: Per-lookup branch: `marker_hit` (fast path, 0 DB reads), `fingerprint_match` (1 DB read, cached data returned), `full_refetch` (full DB re-fetch), or `fingerprint_error` (fingerprint fetch failed, bypassing cache).
+
+ **Attributes**:
+ - `cache.result` (string): `marker_hit`, `fingerprint_match`, `full_refetch`, `fingerprint_error`
+ </Accordion>
+
+ <Accordion title="Permission Cache Fingerprint Duration">
+ **Metric Name**: `infisical.permission_cache.fingerprint.duration`
+
+ **Type**: Histogram
+
+ **Unit**: `s`
+
+ **Description**: Time to compute the lightweight permission fingerprint (1 DB read on marker expiry).
+ </Accordion>
+</AccordionGroup>
+
+### Rate Limit Metrics (InfisicalCore)
+
+<AccordionGroup>
+ <Accordion title="Rate Limit Exceeded">
+ **Metric Name**: `infisical.rate_limit.exceeded.count`
+
+ **Type**: Counter
+
+ **Unit**: `{request}`
+
+ **Description**: HTTP 429 responses (rate limit exceeded). Labels are intentionally bounded to `http.route` only — for per-actor breakdowns, query the audit log.
+
+ **Attributes**:
+ - `http.route` (string)
+ - `http.request.method` (string)
+ </Accordion>
+</AccordionGroup>
+
+### Build Info (InfisicalCore)
+
+<AccordionGroup>
+ <Accordion title="Build Info">
+ **Metric Name**: `infisical.build.info`
+
+ **Type**: Observable Gauge
+
+ **Description**: Always emits `1`. The labels carry the deployed version, git SHA, and Node version. Use this to filter Grafana dashboards by deployed version without paying per-metric cardinality.
+
+ **Attributes**:
+ - `service.version` (string)
+ - `git.commit.sha` (string)
+ - `node.version` (string)
+ </Accordion>
+</AccordionGroup>
+
+### Node Runtime Metrics (auto)
+
+Heap usage, GC pause, event loop lag, and other Node runtime metrics are auto-emitted via `@opentelemetry/instrumentation-runtime-node`. Metric names follow the OTel runtime semantic conventions (`nodejs.eventloop.delay.*`, `v8js.heap.size.*`, etc.).
+
### System Metrics
These low-level HTTP metrics are automatically collected by OpenTelemetry's instrumentation layer, providing baseline performance data for all HTTP traffic.