Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
refactor(pam): classify cloud probe failures by HTTP status
bernie-gdb01c808c9b1
diff --git a/backend/src/ee/services/pam-account-heartbeat/pam-heartbeat-fns.test.ts b/backend/src/ee/services/pam-account-heartbeat/pam-heartbeat-fns.test.tsnew file mode 100644index 0000000000..72e6f7bfc5--- /dev/null+++ b/backend/src/ee/services/pam-account-heartbeat/pam-heartbeat-fns.test.ts@@ -0,0 +1,44 @@+import { describe, expect, test } from "vitest";++import { PamHeartbeatStatus } from "../pam/pam-enums";+import { classifyCloudProbeError } from "./pam-heartbeat-fns";++// Shapes the three federation helpers actually throw: axios (Azure, GCP) and the AWS SDK.+const axiosError = (status: number) => ({ isAxiosError: true, response: { status } });+const awsError = (status: number) => ({ name: "AccessDenied", $metadata: { httpStatusCode: status } });+const wrapped = (cause: unknown) => Object.assign(new Error("Azure rejected the credentials"), { error: cause });++describe("classifyCloudProbeError", () => {+ test.each([+ ["revoked access (403)", axiosError(403)],+ ["rejected client secret (401)", axiosError(401)],+ ["invalid_client (400)", axiosError(400)],+ ["AWS AccessDenied (403)", awsError(403)]+ ])("%s stops the schedule", (_label, err) => {+ expect(classifyCloudProbeError(err)).toBe(PamHeartbeatStatus.InvalidCredentials);+ });++ test.each([+ ["provider outage (500)", axiosError(500)],+ ["bad gateway (502)", axiosError(502)],+ ["throttled (429)", axiosError(429)],+ ["request timeout (408)", axiosError(408)],+ ["AWS internal failure (500)", awsError(500)],+ ["connection refused", { code: "ECONNREFUSED" }],+ ["DNS failure", { code: "ENOTFOUND" }],+ ["TLS failure with no response", new Error("unable to verify the first certificate")]+ ])("%s keeps checking", (_label, err) => {+ expect(classifyCloudProbeError(err)).toBe(PamHeartbeatStatus.CannotCheck);+ });++ // Azure and GCP rethrow their own error type, so the status only survives on the cause.+ test("reads the status through a wrapping error", () => {+ expect(classifyCloudProbeError(wrapped(axiosError(401)))).toBe(PamHeartbeatStatus.InvalidCredentials);+ expect(classifyCloudProbeError(wrapped(axiosError(503)))).toBe(PamHeartbeatStatus.CannotCheck);+ });++ // A transport code above a status must not be read as a verdict on the credential.+ test("a connection error wrapping nothing stays unchecked", () => {+ expect(classifyCloudProbeError(wrapped({ code: "ETIMEDOUT" }))).toBe(PamHeartbeatStatus.CannotCheck);+ });+});diff --git a/backend/src/ee/services/pam-account-heartbeat/pam-heartbeat-fns.ts b/backend/src/ee/services/pam-account-heartbeat/pam-heartbeat-fns.tsindex b8599c1d9a..878e6b9efb 100644--- a/backend/src/ee/services/pam-account-heartbeat/pam-heartbeat-fns.ts+++ b/backend/src/ee/services/pam-account-heartbeat/pam-heartbeat-fns.ts@@ -36,63 +36,50 @@ export const isHeartbeatScheduled = (heartbeat: TPamHeartbeatConfig | undefined)// Retrying a rejected credential is how a monitoring feature locks out a privileged account.export const stopsSchedule = (status: PamHeartbeatStatus) => status === PamHeartbeatStatus.InvalidCredentials;-const TRANSPORT_ERROR_PATTERNS = [- "etimedout",- "econnrefused",- "econnreset",- "ehostunreach",- "enetunreach",- "enotfound",- "eai_again",- "socket hang up",- "x509",- "tls",- "certificate",- "service unavailable",- "internalfailure",- "internal server error",- "bad gateway",- "throttl",- "slowdown",- "rate exceeded",- "too many requests",- "timeout",- "timed out",- "gateway",- "tunnel"-];-// Unclassified resolves to rejected on purpose: an ambiguous result costs a false alarm, not a lockout.export const statusForFailureKind = (kind: GatewayFailureKind | null): PamHeartbeatStatus => {if (kind === "transport") return PamHeartbeatStatus.CannotCheck;return PamHeartbeatStatus.InvalidCredentials;};-// Cloud accounts have no lockout, so the bias inverts: only a recognised rejection stops the schedule.-const CLOUD_REJECTION_PATTERNS = [- "accessdenied",- "access denied",- "unauthorized",- "unauthorised",- "invalid_client",- "invalid_grant",- "invalidclienttokenid",- "signaturedoesnotmatch",- "expiredtoken",- "invalid credentials",- "permission denied",- "forbidden",- "not authorized to perform",- "invalid jwt",- "is disabled",- "has been deleted"-];+// Cloud accounts are brokered over HTTP, so the provider's status says what its prose only hints at. A status+// at all means the request was answered and the credential judged; 5xx, 408, and 429 are the provider having a+// bad day rather than a verdict on the credential.+const RETRYABLE_STATUSES = new Set([408, 429]);++const CONNECTION_ERROR_CODES = new Set([+ "ECONNREFUSED",+ "ECONNRESET",+ "ECONNABORTED",+ "ETIMEDOUT",+ "ENOTFOUND",+ "EAI_AGAIN",+ "EPIPE"+]);++// Walks the cause chain the errors thrown by the federation helpers carry on their `error` field.+const httpStatusOf = (err: unknown): number | undefined => {+ let current = err;+ for (let depth = 0; current && typeof current === "object" && depth < 5; depth += 1) {+ const candidate = current as {+ response?: { status?: number };+ $metadata?: { httpStatusCode?: number };+ code?: unknown;+ error?: unknown;+ cause?: unknown;+ };+ const status = candidate.response?.status ?? candidate.$metadata?.httpStatusCode;+ if (typeof status === "number") return status;+ if (typeof candidate.code === "string" && CONNECTION_ERROR_CODES.has(candidate.code)) return undefined;+ current = candidate.error ?? candidate.cause;+ }+ return undefined;+};export const classifyCloudProbeError = (err: unknown): PamHeartbeatStatus => {- const message = (err instanceof Error ? err.message : String(err)).toLowerCase();- if (TRANSPORT_ERROR_PATTERNS.some((pattern) => message.includes(pattern))) return PamHeartbeatStatus.CannotCheck;- if (CLOUD_REJECTION_PATTERNS.some((pattern) => message.includes(pattern))) {- return PamHeartbeatStatus.InvalidCredentials;+ const status = httpStatusOf(err);+ if (status === undefined || status >= 500 || RETRYABLE_STATUSES.has(status)) {+ return PamHeartbeatStatus.CannotCheck;}- return PamHeartbeatStatus.CannotCheck;+ return status >= 400 ? PamHeartbeatStatus.InvalidCredentials : PamHeartbeatStatus.CannotCheck;};diff --git a/backend/src/ee/services/pam-session/azure/azure-federation.ts b/backend/src/ee/services/pam-session/azure/azure-federation.tsindex d6eeb896c6..20fc714d20 100644--- a/backend/src/ee/services/pam-session/azure/azure-federation.ts+++ b/backend/src/ee/services/pam-session/azure/azure-federation.ts@@ -37,8 +37,10 @@ export const getAzureAccessToken = async ({} catch (err) {if (axios.isAxiosError(err) && err.response) {const data = err.response.data as TAzureTokenErrorResponse;+ // The cause carries the response status, which callers use to tell a refused credential from an outage.throw new BadRequestError({- message: `Azure rejected the service principal credentials: ${data.error_description || data.error || "unknown error"}`+ message: `Azure rejected the service principal credentials: ${data.error_description || data.error || "unknown error"}`,+ error: err});}throw new InternalServerError({ message: "Failed to reach the Azure token endpoint" });diff --git a/backend/src/ee/services/pam-session/gcp/gcp-federation.ts b/backend/src/ee/services/pam-session/gcp/gcp-federation.tsindex cb3ae43a50..f2dfdff51b 100644--- a/backend/src/ee/services/pam-session/gcp/gcp-federation.ts+++ b/backend/src/ee/services/pam-session/gcp/gcp-federation.ts@@ -13,7 +13,9 @@ const tokenError = (serviceAccountEmail: string, err: unknown) =>new BadRequestError({message: `Failed to obtain GCP access token for [serviceAccountEmail=${serviceAccountEmail}]: ${err instanceof Error ? err.message : String(err)- }`+ }`,+ // The cause carries the response status, which callers use to tell a refused credential from an outage.+ error: err});// mints a short-lived access token for the target service account