Skip to content

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

avoid SAML replay issue

Thiago Araujo da Silva248ce15b172b
diff --git a/backend/src/ee/routes/v1/saml-router.ts b/backend/src/ee/routes/v1/saml-router.ts
index 2bf244c2a7..263096bda3 100644
--- a/backend/src/ee/routes/v1/saml-router.ts
+++ b/backend/src/ee/routes/v1/saml-router.ts
@@ -193,9 +193,12 @@ export const registerSamlRouter = async (server: FastifyZodProvider) => {
}
const { ssoConfig } = req as unknown as FastifyRequest;
+ const parsedAssertion = profile.getAssertion?.();
+ await server.services.saml.consumeSamlAssertion({ samlConfigId: ssoConfig.id, parsedAssertion });
+
const idpMfa = matchIdpMfaSignal({
kind: "saml",
- authnContextClassRefs: extractSamlAuthnContextClassRefs(profile.getAssertion?.()),
+ authnContextClassRefs: extractSamlAuthnContextClassRefs(parsedAssertion),
attributes: profile.attributes as Record<string, unknown> | undefined,
config: ssoConfig
});
diff --git a/backend/src/ee/services/saml-config/saml-assertion-fns.test.ts b/backend/src/ee/services/saml-config/saml-assertion-fns.test.ts
new file mode 100644
index 0000000000..6841b9b14a
--- /dev/null
+++ b/backend/src/ee/services/saml-config/saml-assertion-fns.test.ts
@@ -0,0 +1,119 @@
+import {
+ getSamlAssertionReplayDetails,
+ getSamlAssertionReplayWindow,
+ SAML_ASSERTION_FALLBACK_WINDOW_MS
+} from "./saml-assertion-fns";
+
+const assertion = ({
+ id = "_a1b2c3",
+ conditionsNotOnOrAfter = "2026-10-31T10:05:00Z",
+ subjectNotOnOrAfter = "2026-10-31T10:03:00Z"
+}: {
+ id?: string;
+ conditionsNotOnOrAfter?: string;
+ subjectNotOnOrAfter?: string;
+} = {}) => ({
+ $: { ID: id, IssueInstant: "2026-10-31T10:00:00Z" },
+ Conditions: [{ $: { NotBefore: "2026-10-31T09:59:00Z", NotOnOrAfter: conditionsNotOnOrAfter } }],
+ Subject: [
+ {
+ SubjectConfirmation: [
+ {
+ $: { Method: "urn:oasis:names:tc:SAML:2.0:cm:bearer" },
+ SubjectConfirmationData: [{ $: { NotOnOrAfter: subjectNotOnOrAfter } }]
+ }
+ ]
+ }
+ ]
+});
+
+describe("getSamlAssertionReplayDetails", () => {
+ test("reads the ID, IssueInstant and the latest NotOnOrAfter from an Assertion root", () => {
+ expect(getSamlAssertionReplayDetails({ Assertion: assertion() })).toEqual({
+ assertionId: "_a1b2c3",
+ issuedAt: new Date("2026-10-31T10:00:00Z"),
+ expiresAt: new Date("2026-10-31T10:05:00Z")
+ });
+ });
+
+ test("uses the subject confirmation expiry when it is the later one", () => {
+ const details = getSamlAssertionReplayDetails({
+ Assertion: assertion({
+ conditionsNotOnOrAfter: "2026-10-31T10:01:00Z",
+ subjectNotOnOrAfter: "2026-10-31T10:09:00Z"
+ })
+ });
+ expect(details.expiresAt).toEqual(new Date("2026-10-31T10:09:00Z"));
+ });
+
+ test("finds the assertion inside a Response wrapper", () => {
+ expect(getSamlAssertionReplayDetails({ Response: [{ Assertion: [assertion()] }] }).assertionId).toBe("_a1b2c3");
+ });
+
+ test.each([
+ ["no ID", { Assertion: { ...assertion(), $: { IssueInstant: "2026-10-31T10:00:00Z" } } }],
+ ["a blank ID", { Assertion: assertion({ id: " " }) }],
+ ["nothing parsed", undefined]
+ ])("returns no assertion ID for %s", (_, parsed) => {
+ expect(getSamlAssertionReplayDetails(parsed).assertionId).toBeUndefined();
+ });
+
+ test("returns no timestamps when none is present or parseable", () => {
+ const parsed = {
+ Assertion: {
+ $: { ID: "_x", IssueInstant: "yesterday" },
+ Conditions: [{ $: { NotOnOrAfter: "not a date" } }],
+ Subject: [{}]
+ }
+ };
+ expect(getSamlAssertionReplayDetails(parsed)).toEqual({
+ assertionId: "_x",
+ issuedAt: undefined,
+ expiresAt: undefined
+ });
+ });
+});
+
+describe("getSamlAssertionReplayWindow", () => {
+ const now = Date.parse("2026-10-31T10:00:00Z");
+
+ test("remembers the ID until NotOnOrAfter plus the margin", () => {
+ expect(getSamlAssertionReplayWindow({ expiresAt: new Date("2026-10-31T10:05:00Z") }, now)).toEqual({
+ accepted: true,
+ ttlSeconds: 360
+ });
+ });
+
+ test("prefers NotOnOrAfter over the IssueInstant fallback", () => {
+ const window = getSamlAssertionReplayWindow(
+ { expiresAt: new Date("2026-10-31T10:05:00Z"), issuedAt: new Date("2026-10-31T09:59:00Z") },
+ now
+ );
+ expect(window).toEqual({ accepted: true, ttlSeconds: 360 });
+ });
+
+ test("falls back to a fixed window after IssueInstant when NotOnOrAfter is missing", () => {
+ const issuedAt = new Date(now - 10 * 60 * 1000);
+ expect(getSamlAssertionReplayWindow({ issuedAt }, now)).toEqual({
+ accepted: true,
+ ttlSeconds: (SAML_ASSERTION_FALLBACK_WINDOW_MS - 10 * 60 * 1000) / 1000 + 60
+ });
+ });
+
+ test("covers an IssueInstant in the future until the whole window has passed", () => {
+ const issuedAt = new Date(now + 5 * 60 * 1000);
+ expect(getSamlAssertionReplayWindow({ issuedAt }, now)).toEqual({
+ accepted: true,
+ ttlSeconds: (SAML_ASSERTION_FALLBACK_WINDOW_MS + 5 * 60 * 1000) / 1000 + 60
+ });
+ });
+
+ test("refuses an assertion without NotOnOrAfter issued before the fallback window", () => {
+ const issuedAt = new Date(now - SAML_ASSERTION_FALLBACK_WINDOW_MS - 2 * 60 * 1000);
+ expect(getSamlAssertionReplayWindow({ issuedAt }, now)).toEqual({ accepted: false, reason: "expired" });
+ });
+
+ test("refuses an assertion with neither NotOnOrAfter nor IssueInstant", () => {
+ expect(getSamlAssertionReplayWindow({}, now)).toEqual({ accepted: false, reason: "missing-timestamps" });
+ });
+});
diff --git a/backend/src/ee/services/saml-config/saml-assertion-fns.ts b/backend/src/ee/services/saml-config/saml-assertion-fns.ts
new file mode 100644
index 0000000000..171df2023e
--- /dev/null
+++ b/backend/src/ee/services/saml-config/saml-assertion-fns.ts
@@ -0,0 +1,77 @@
+// node-saml parses with xml2js explicitArray and explicitCharkey: every child is an array, a text node is
+// { _: "value" }, XML attributes sit under "$", and the root is either the Assertion or a Response wrapping one.
+export const samlXmlChildren = (node: unknown, name: string): unknown[] => {
+ if (!node || typeof node !== "object") return [];
+ const value = (node as Record<string, unknown>)[name];
+ if (value === undefined || value === null) return [];
+ return Array.isArray(value) ? value : [value];
+};
+
+const xmlAttribute = (node: unknown, name: string): string | undefined => {
+ if (!node || typeof node !== "object") return undefined;
+ const value = (node as { $?: Record<string, unknown> }).$?.[name];
+ return typeof value === "string" ? value : undefined;
+};
+
+export const getSamlAssertionNode = (parsedAssertion: unknown): unknown =>
+ samlXmlChildren(parsedAssertion, "Assertion")[0] ??
+ samlXmlChildren(samlXmlChildren(parsedAssertion, "Response")[0], "Assertion")[0] ??
+ parsedAssertion;
+
+const parseTimestamp = (value: string | undefined) => {
+ const timestamp = Date.parse(value ?? "");
+ return Number.isFinite(timestamp) ? new Date(timestamp) : undefined;
+};
+
+// The latest NotOnOrAfter in the assertion bounds how long node-saml would still accept it, so it is how long
+// the assertion ID has to be remembered to refuse a replay.
+export const getSamlAssertionReplayDetails = (parsedAssertion: unknown) => {
+ const assertion = getSamlAssertionNode(parsedAssertion);
+ const assertionId = xmlAttribute(assertion, "ID")?.trim() || undefined;
+ const issuedAt = parseTimestamp(xmlAttribute(assertion, "IssueInstant"));
+
+ const expiries = [
+ ...samlXmlChildren(assertion, "Conditions"),
+ ...samlXmlChildren(assertion, "Subject")
+ .flatMap((subject) => samlXmlChildren(subject, "SubjectConfirmation"))
+ .flatMap((confirmation) => samlXmlChildren(confirmation, "SubjectConfirmationData"))
+ ]
+ .map((node) => parseTimestamp(xmlAttribute(node, "NotOnOrAfter"))?.getTime())
+ .filter((timestamp): timestamp is number => timestamp !== undefined);
+
+ return {
+ assertionId,
+ issuedAt,
+ expiresAt: expiries.length ? new Date(Math.max(...expiries)) : undefined
+ };
+};
+
+// node-saml accepts no clock skew, so the margin only covers the gap between its check and the claim.
+const SAML_ASSERTION_REPLAY_MARGIN_MS = 60 * 1000;
+// node-saml accepts an assertion with no NotOnOrAfter indefinitely, which no replay record could cover. The SAML
+// profile requires one, but some IdPs omit it, so instead of refusing those logins we accept such an assertion
+// for this long after its IssueInstant and remember its ID for that same window.
+export const SAML_ASSERTION_FALLBACK_WINDOW_MS = 60 * 60 * 1000;
+
+export type TSamlAssertionReplayWindow =
+ | { accepted: true; ttlSeconds: number }
+ | { accepted: false; reason: "missing-timestamps" | "expired" };
+
+export const getSamlAssertionReplayWindow = (
+ { expiresAt, issuedAt }: { expiresAt?: Date; issuedAt?: Date },
+ now = Date.now()
+): TSamlAssertionReplayWindow => {
+ let acceptedUntil: number;
+ if (expiresAt) {
+ acceptedUntil = expiresAt.getTime();
+ } else if (issuedAt) {
+ acceptedUntil = issuedAt.getTime() + SAML_ASSERTION_FALLBACK_WINDOW_MS;
+ } else {
+ return { accepted: false, reason: "missing-timestamps" };
+ }
+
+ const rememberUntil = acceptedUntil + SAML_ASSERTION_REPLAY_MARGIN_MS;
+ if (rememberUntil <= now) return { accepted: false, reason: "expired" };
+
+ return { accepted: true, ttlSeconds: Math.ceil((rememberUntil - now) / 1000) };
+};
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 c0d73ef519..4c62f0f1d2 100644
--- a/backend/src/ee/services/saml-config/saml-config-service.ts
+++ b/backend/src/ee/services/saml-config/saml-config-service.ts
@@ -16,7 +16,10 @@ import {
} from "@app/db/schemas";
import { TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";
import { getEnforcedIdentityLimit, throwOnPlanSeatLimitReached } from "@app/ee/services/license/license-fns";
+import { KeyStorePrefixes, TKeyStoreFactory } from "@app/keystore/keystore";
+import { crypto } from "@app/lib/crypto";
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
+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 { recordSsoConfigChangeMetric, SsoConfigAction, SsoProvider } from "@app/lib/telemetry/metrics";
@@ -57,6 +60,7 @@ import { TUserGroupMembershipDALFactory } from "../group/user-group-membership-d
import { TLicenseServiceFactory } from "../license/license-service";
import { OrgPermissionSsoActions, OrgPermissionSubjects } from "../permission/org-permission";
import { TPermissionServiceFactory } from "../permission/permission-service-types";
+import { getSamlAssertionReplayDetails, getSamlAssertionReplayWindow } from "./saml-assertion-fns";
import { TSamlConfigDALFactory } from "./saml-config-dal";
import { SamlProviders, TSamlConfigServiceFactory } from "./saml-config-types";
@@ -111,6 +115,7 @@ type TSamlConfigServiceFactoryDep = {
emailDomainDAL: Pick<TEmailDomainDALFactory, "findOne">;
telemetryService: Pick<TTelemetryServiceFactory, "sendPostHogEvents">;
usageMeteringService: Pick<TUsageMeteringServiceFactory, "emit">;
+ keyStore: Pick<TKeyStoreFactory, "setItemWithExpiryNX">;
};
export const samlConfigServiceFactory = ({
@@ -138,7 +143,8 @@ export const samlConfigServiceFactory = ({
loginService,
emailDomainDAL,
telemetryService,
- usageMeteringService
+ usageMeteringService,
+ keyStore
}: TSamlConfigServiceFactoryDep): TSamlConfigServiceFactory => {
const parseSamlGroups = (groupsValue: string): string[] => {
let samlGroups: string[] = [];
@@ -559,6 +565,47 @@ export const samlConfigServiceFactory = ({
};
};
+ // Called with the assertion node-saml has already verified, before any login logic. The ID is claimed in
+ // Redis, which every instance shares, until the assertion expires, so a captured response cannot start a
+ // second session; that matters most when the org trusts the MFA it carries. This covers IdP-initiated logins
+ // too, which InResponseTo validation would not.
+ const consumeSamlAssertion: TSamlConfigServiceFactory["consumeSamlAssertion"] = async ({
+ samlConfigId,
+ parsedAssertion
+ }) => {
+ const { assertionId, issuedAt, expiresAt } = getSamlAssertionReplayDetails(parsedAssertion);
+ if (!assertionId) {
+ throw new BadRequestError({
+ message:
+ "The SAML response from your identity provider has no assertion ID, so Infisical cannot make sure it is used only once. Check the SAML app settings in your identity provider."
+ });
+ }
+
+ const replayWindow = getSamlAssertionReplayWindow({ expiresAt, issuedAt });
+ if (!replayWindow.accepted) {
+ throw new BadRequestError({
+ message:
+ replayWindow.reason === "expired"
+ ? "This SAML response has expired. Sign in again through your identity provider."
+ : "The SAML response from your identity provider has no expiry (NotOnOrAfter) or issue time (IssueInstant), so Infisical cannot make sure it is used only once. Check the SAML app settings in your identity provider."
+ });
+ }
+
+ const assertionIdHash = crypto.nativeCrypto.createHash("sha256").update(assertionId).digest("hex");
+ const claimed = await keyStore.setItemWithExpiryNX(
+ KeyStorePrefixes.SamlAssertionReplay(samlConfigId, assertionIdHash),
+ replayWindow.ttlSeconds,
+ "1"
+ );
+
+ if (!claimed) {
+ logger.warn({ samlConfigId, assertionIdHash }, "Rejected a SAML assertion that was already used");
+ throw new BadRequestError({
+ message: "This SAML response was already used. Sign in again through your identity provider."
+ });
+ }
+ };
+
const samlLogin: TSamlConfigServiceFactory["samlLogin"] = async ({
externalId,
email,
@@ -875,6 +922,7 @@ export const samlConfigServiceFactory = ({
createSamlCfg,
updateSamlCfg,
getSaml,
- samlLogin
+ samlLogin,
+ consumeSamlAssertion
};
};
diff --git a/backend/src/ee/services/saml-config/saml-config-types.ts b/backend/src/ee/services/saml-config/saml-config-types.ts
index 235607582e..027afaeb28 100644
--- a/backend/src/ee/services/saml-config/saml-config-types.ts
+++ b/backend/src/ee/services/saml-config/saml-config-types.ts
@@ -91,4 +91,5 @@ export type TSamlConfigServiceFactory = {
mfaAuthnContexts?: string[] | null;
}>;
samlLogin: (arg: TSamlLoginDTO) => Promise<TProviderAuthResult & { userId: string; orgId: string; orgName: string }>;
+ consumeSamlAssertion: (arg: { samlConfigId: string; parsedAssertion: unknown }) => Promise<void>;
};
diff --git a/backend/src/keystore/keystore.ts b/backend/src/keystore/keystore.ts
index f1ca593af2..62f7b65c10 100644
--- a/backend/src/keystore/keystore.ts
+++ b/backend/src/keystore/keystore.ts
@@ -261,7 +261,10 @@ export const KeyStorePrefixes = {
`native-integration-deprecation-notice:${orgId}:${period}` as const,
LegacyPkiDeprecationNotice: (orgId: string, period: string) =>
- `legacy-pki-deprecation-notice:${orgId}:${period}` as const
+ `legacy-pki-deprecation-notice:${orgId}:${period}` as const,
+
+ SamlAssertionReplay: (samlConfigId: string, assertionIdHash: string) =>
+ `saml-assertion-replay:${samlConfigId}:${assertionIdHash}` as const
};
export const KeyStoreTtls = {
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index c5f582dfcb..29204d22c4 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -1662,7 +1662,8 @@ export const registerRoutes = async (
telemetryService,
usageMeteringService,
alertChannelRecipientDAL,
- eventEmitter: eventOutboxService
+ eventEmitter: eventOutboxService,
+ keyStore
});
const ldapService = ldapConfigServiceFactory({
diff --git a/backend/src/services/auth/idp-mfa-signal.ts b/backend/src/services/auth/idp-mfa-signal.ts
index f3ac92d3d8..2f29598b04 100644
--- a/backend/src/services/auth/idp-mfa-signal.ts
+++ b/backend/src/services/auth/idp-mfa-signal.ts
@@ -1,3 +1,5 @@
+import { getSamlAssertionNode, samlXmlChildren } from "@app/ee/services/saml-config/saml-assertion-fns";
+
// "amr" is the OIDC Core claim name. SAML has no standard attribute name, so the Okta convention is the default.
const DEFAULT_MFA_CLAIM_NAME = "amr";
@@ -113,8 +115,6 @@ export const matchIdpMfaSignal = (input: TIdpMfaSignalInput): TIdpMfaSignal => {
return { verified: evidence.length > 0, evidence, received };
};
-// node-saml parses with xml2js explicitArray and explicitCharkey: every child is an array, a text node is
-// { _: "value" }, and the root is either the Assertion or a Response wrapping one.
const textOf = (node: unknown): string | undefined => {
if (typeof node === "string") return node;
if (node && typeof node === "object" && "_" in node && typeof (node as { _: unknown })._ === "string") {
@@ -123,21 +123,10 @@ const textOf = (node: unknown): string | undefined => {
return undefined;
};
-const children = (node: unknown, name: string): unknown[] => {
- if (!node || typeof node !== "object") return [];
- const value = (node as Record<string, unknown>)[name];
- if (value === undefined || value === null) return [];
- return Array.isArray(value) ? value : [value];
-};
-
export const extractSamlAuthnContextClassRefs = (parsedAssertion: unknown): string[] => {
- const root =
- children(parsedAssertion, "Assertion")[0] ??
- children(children(parsedAssertion, "Response")[0], "Assertion")[0] ??
- parsedAssertion;
- return children(root, "AuthnStatement")
- .flatMap((statement) => children(statement, "AuthnContext"))
- .flatMap((context) => children(context, "AuthnContextClassRef"))
+ return samlXmlChildren(getSamlAssertionNode(parsedAssertion), "AuthnStatement")
+ .flatMap((statement) => samlXmlChildren(statement, "AuthnContext"))
+ .flatMap((context) => samlXmlChildren(context, "AuthnContextClassRef"))
.map(textOf)
.filter((value): value is string => Boolean(value));
};