Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(auth): hash passwords with PBKDF2 in FIPS mode (#18444)

Steffen Reuthereed7667074da
diff --git a/web/src/__tests__/server/credentials-login-fips.servertest.ts b/web/src/__tests__/server/credentials-login-fips.servertest.ts
new file mode 100644
index 0000000000..f4e4e1ed03
--- /dev/null
+++ b/web/src/__tests__/server/credentials-login-fips.servertest.ts
@@ -0,0 +1,86 @@
+import { randomUUID } from "crypto";
+import { hash } from "bcryptjs";
+import type { CredentialsConfig } from "next-auth/providers/credentials";
+import type * as SharedEnvModule from "@langfuse/shared/src/env";
+import { PASSWORD_RESET_REQUIRED_MESSAGE } from "@/src/features/auth/constants";
+import { hashPassword } from "@/src/features/auth-credentials/lib/passwordHash";
+import { getAuthOptions } from "@/src/server/auth";
+import { prisma } from "@langfuse/shared/src/db";
+
+const { fips } = vi.hoisted(() => ({
+ fips: { required: "false" as "true" | "false" },
+}));
+
+vi.mock("@langfuse/shared/src/env", async (importOriginal) => {
+ const actual = await importOriginal<typeof SharedEnvModule>();
+ return {
+ ...actual,
+ env: {
+ ...actual.env,
+ get LANGFUSE_REQUIRE_FIPS() {
+ return fips.required;
+ },
+ },
+ };
+});
+
+const PASSWORD = "Loginpass1!";
+
+describe("credentials login in FIPS mode", () => {
+ beforeEach(() => {
+ fips.required = "false";
+ });
+
+ it("asks a user with a bcrypt password to reset it", async () => {
+ const email = await createUser(await hash(PASSWORD, 4));
+ fips.required = "true";
+
+ await expect(signIn(email, PASSWORD)).rejects.toThrow(
+ PASSWORD_RESET_REQUIRED_MESSAGE,
+ );
+ });
+
+ it("signs in a user whose password was set in FIPS mode", async () => {
+ fips.required = "true";
+ const email = await createUser(await hashPassword(PASSWORD));
+
+ await expect(signIn(email, PASSWORD)).resolves.toMatchObject({ email });
+ await expect(signIn(email, "Wrongpass1!")).rejects.toThrow(
+ "Invalid credentials",
+ );
+ });
+
+ it("keeps signing in bcrypt users outside FIPS mode", async () => {
+ const email = await createUser(await hash(PASSWORD, 4));
+
+ await expect(signIn(email, PASSWORD)).resolves.toMatchObject({ email });
+ });
+});
+
+async function createUser(passwordHash: string) {
+ const id = randomUUID();
+ const email = `fips-login-${id}@example.com`;
+ await prisma.user.create({
+ data: {
+ id: `user-${id}`,
+ email,
+ name: "FIPS Login Test User",
+ password: passwordHash,
+ },
+ });
+ return email;
+}
+
+async function signIn(email: string, password: string) {
+ const provider = (await getAuthOptions()).providers.find(
+ (p) => p.id === "credentials",
+ );
+ const { authorize } = provider?.options as Pick<
+ CredentialsConfig,
+ "authorize"
+ >;
+ return authorize(
+ { email, password },
+ { body: {}, query: {}, headers: {}, method: "POST" },
+ );
+}
diff --git a/web/src/__tests__/server/credentials-reset-password.servertest.ts b/web/src/__tests__/server/credentials-reset-password.servertest.ts
index eaa0a5996f..0a29138e74 100644
--- a/web/src/__tests__/server/credentials-reset-password.servertest.ts
+++ b/web/src/__tests__/server/credentials-reset-password.servertest.ts
@@ -6,7 +6,7 @@ import { env } from "@/src/env.mjs";
import {
hashPassword,
verifyPassword,
-} from "@/src/features/auth-credentials/lib/credentialsServerUtils";
+} from "@/src/features/auth-credentials/lib/passwordHash";
import { appRouter } from "@/src/server/api/root";
import { createInnerTRPCContext } from "@/src/server/api/trpc";
import { prisma } from "@langfuse/shared/src/db";
diff --git a/web/src/__tests__/server/nextauth-email-callback.servertest.ts b/web/src/__tests__/server/nextauth-email-callback.servertest.ts
index 61acede86a..cffdd42253 100644
--- a/web/src/__tests__/server/nextauth-email-callback.servertest.ts
+++ b/web/src/__tests__/server/nextauth-email-callback.servertest.ts
@@ -16,7 +16,7 @@ import { env } from "@/src/env.mjs";
import {
hashPassword,
verifyPassword,
-} from "@/src/features/auth-credentials/lib/credentialsServerUtils";
+} from "@/src/features/auth-credentials/lib/passwordHash";
import auth from "@/src/pages/api/auth/[...nextauth]";
import { appRouter } from "@/src/server/api/root";
import { createInnerTRPCContext } from "@/src/server/api/trpc";
diff --git a/web/src/__tests__/server/unit/passwordHash.servertest.ts b/web/src/__tests__/server/unit/passwordHash.servertest.ts
new file mode 100644
index 0000000000..5d1d343a62
--- /dev/null
+++ b/web/src/__tests__/server/unit/passwordHash.servertest.ts
@@ -0,0 +1,112 @@
+import type * as BcryptModule from "bcryptjs";
+import type * as SharedEnvModule from "@langfuse/shared/src/env";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { hash } from "bcryptjs";
+import {
+ hashPassword,
+ passwordRequiresReset,
+ verifyPassword,
+} from "@/src/features/auth-credentials/lib/passwordHash";
+
+const { fips, compare } = vi.hoisted(() => ({
+ fips: { required: "false" as "true" | "false" },
+ compare: vi.fn(),
+}));
+
+vi.mock("@langfuse/shared/src/env", async (importOriginal) => {
+ const actual = await importOriginal<typeof SharedEnvModule>();
+ return {
+ ...actual,
+ env: {
+ ...actual.env,
+ get LANGFUSE_REQUIRE_FIPS() {
+ return fips.required;
+ },
+ },
+ };
+});
+
+// bcryptjs is CommonJS, so its functions sit on the default export.
+vi.mock("bcryptjs", async (importOriginal) => {
+ const { default: actual } = await importOriginal<{
+ default: typeof BcryptModule;
+ }>();
+ compare.mockImplementation(actual.compare);
+ return { ...actual, compare, default: { ...actual, compare } };
+});
+
+const PASSWORD = "correct horse battery staple";
+
+describe("passwordHash", () => {
+ beforeEach(() => {
+ fips.required = "false";
+ compare.mockClear();
+ });
+
+ it("writes and verifies bcrypt hashes outside FIPS mode", async () => {
+ const hashed = await hashPassword(PASSWORD);
+
+ expect(hashed).toMatch(/^\$2[aby]\$12\$/);
+ expect(await verifyPassword(PASSWORD, hashed)).toBe(true);
+ expect(passwordRequiresReset(hashed)).toBe(false);
+ });
+
+ it("writes and verifies PBKDF2-SHA256 hashes in FIPS mode", async () => {
+ fips.required = "true";
+
+ const hashed = await hashPassword(PASSWORD);
+
+ expect(hashed).toMatch(
+ /^\$pbkdf2-sha256\$i=600000\$[A-Za-z0-9+/]{22}\$[A-Za-z0-9+/]{43}$/,
+ );
+ expect(await verifyPassword(PASSWORD, hashed)).toBe(true);
+ expect(await verifyPassword(`${PASSWORD}!`, hashed)).toBe(false);
+ // Login forwards whatever was submitted; short input must not throw.
+ expect(await verifyPassword("", hashed)).toBe(false);
+ expect(passwordRequiresReset(hashed)).toBe(false);
+ });
+
+ it("keeps PBKDF2 hashes valid after FIPS mode is turned off", async () => {
+ fips.required = "true";
+ const hashed = await hashPassword(PASSWORD);
+ fips.required = "false";
+
+ expect(await verifyPassword(PASSWORD, hashed)).toBe(true);
+ });
+
+ it("rejects bcrypt hashes in FIPS mode without running bcrypt", async () => {
+ const bcryptHash = await hash(PASSWORD, 4);
+ fips.required = "true";
+
+ expect(await verifyPassword(PASSWORD, bcryptHash)).toBe(false);
+ expect(passwordRequiresReset(bcryptHash)).toBe(true);
+ expect(compare).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["an empty value", ""],
+ ["a plain string", PASSWORD],
+ ["a missing key", "$pbkdf2-sha256$i=600000$AAAAAAAAAAAAAAAAAAAAAA"],
+ [
+ "a non-numeric iteration count",
+ "$pbkdf2-sha256$i=many$AAAAAAAAAAAAAAAAAAAAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
+ ],
+ [
+ "an iteration count below the SP 800-132 minimum",
+ "$pbkdf2-sha256$i=999$AAAAAAAAAAAAAAAAAAAAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
+ ],
+ [
+ "an iteration count Node cannot run",
+ "$pbkdf2-sha256$i=9007199254740991$AAAAAAAAAAAAAAAAAAAAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
+ ],
+ [
+ "a salt below the SP 800-132 minimum",
+ "$pbkdf2-sha256$i=600000$AAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
+ ],
+ ])("rejects %s without throwing", async (_label, stored) => {
+ for (const required of ["false", "true"] as const) {
+ fips.required = required;
+ expect(await verifyPassword(PASSWORD, stored)).toBe(false);
+ }
+ });
+});
diff --git a/web/src/features/auth-credentials/lib/credentialsServerUtils.ts b/web/src/features/auth-credentials/lib/credentialsServerUtils.ts
index 7ca39c709e..49a2c3b9cd 100644
--- a/web/src/features/auth-credentials/lib/credentialsServerUtils.ts
+++ b/web/src/features/auth-credentials/lib/credentialsServerUtils.ts
@@ -3,9 +3,9 @@ import { createProjectMembershipsOnSignup } from "@/src/features/auth/lib/create
import { advanceSessionsExpiredAtForEmail } from "@/src/features/auth/lib/sessionExpiration";
import type { AdClickIds } from "@/src/features/auth";
import { env } from "@/src/env.mjs";
+import { hashPassword } from "@/src/features/auth-credentials/lib/passwordHash";
import { prisma } from "@langfuse/shared/src/db";
import { TRPCError } from "@trpc/server";
-import { compare, hash } from "bcryptjs";
function hashEmailOtpToken(token: string) {
if (!env.NEXTAUTH_SECRET) {
@@ -104,7 +104,7 @@ export async function consumeEmailOtpAndUpdatePassword({
await tx.verificationToken.deleteMany({ where: { identifier } });
// Keep password hashing behind successful OTP validation so unauthenticated
- // invalid attempts cannot trigger expensive bcrypt work.
+ // invalid attempts cannot trigger expensive hashing work.
const hashedPassword = await hashPassword(password);
const updated = await tx.user.updateMany({
where: { email: identifier },
@@ -129,16 +129,6 @@ export async function consumeEmailOtpAndUpdatePassword({
}
}
-export async function hashPassword(password: string) {
- const hashedPassword = await hash(password, 12);
- return hashedPassword;
-}
-
-export async function verifyPassword(password: string, hashedPassword: string) {
- const isValid = await compare(password, hashedPassword);
- return isValid;
-}
-
function isValidPassword(password: string) {
return password.length >= 8;
}
diff --git a/web/src/features/auth-credentials/lib/passwordHash.ts b/web/src/features/auth-credentials/lib/passwordHash.ts
new file mode 100644
index 0000000000..7d8b64a74f
--- /dev/null
+++ b/web/src/features/auth-credentials/lib/passwordHash.ts
@@ -0,0 +1,107 @@
+import { pbkdf2, randomBytes, timingSafeEqual } from "crypto";
+import { promisify } from "util";
+import { compare, hash } from "bcryptjs";
+import { env } from "@langfuse/shared/src/env";
+
+const pbkdf2Async = promisify(pbkdf2);
+
+const BCRYPT_COST = 12;
+const BCRYPT_HASH_PATTERN = /^\$2[aby]\$/;
+
+// PHC string format: $pbkdf2-sha256$i=<iterations>$<salt>$<key>, with
+// unpadded base64 salt and key.
+const PBKDF2_PREFIX = "$pbkdf2-sha256$";
+const PBKDF2_ITERATIONS = 600_000;
+const PBKDF2_SALT_BYTES = 16;
+const PBKDF2_KEY_BYTES = 32;
+// NIST SP 800-132 minimums for an approved PBKDF2 use; a stored hash below
+// them is treated as malformed.
+const PBKDF2_MIN_SALT_BYTES = 16;
+const PBKDF2_MIN_KEY_BYTES = 14;
+const PBKDF2_MIN_ITERATIONS = 1_000;
+// Keeps a corrupted stored hash from stalling a login.
+const PBKDF2_MAX_ITERATIONS = 10_000_000;
+
+/**
+ * isFipsModeRequired is true with LANGFUSE_REQUIRE_FIPS=true. bcrypt is not
+ * FIPS-approved, so those hosts hash and verify passwords only with
+ * PBKDF2-HMAC-SHA256. Other hosts write bcrypt and verify both formats.
+ */
+function isFipsModeRequired(): boolean {
+ return env.LANGFUSE_REQUIRE_FIPS === "true";
+}
+
+/** hashPassword hashes a password in the format this host writes. */
+export async function hashPassword(password: string): Promise<string> {
+ if (!isFipsModeRequired()) {
+ return hash(password, BCRYPT_COST);
+ }
+
+ const salt = randomBytes(PBKDF2_SALT_BYTES);
+ const key = await pbkdf2Async(
+ password,
+ salt,
+ PBKDF2_ITERATIONS,
+ PBKDF2_KEY_BYTES,
+ "sha256",
+ );
+ return `${PBKDF2_PREFIX}i=${PBKDF2_ITERATIONS}$${toBase64(salt)}$${toBase64(key)}`;
+}
+
+/**
+ * verifyPassword checks a password against a bcrypt or PBKDF2 hash. In FIPS
+ * mode a bcrypt hash never matches (see passwordRequiresReset), and any other
+ * stored value never matches anywhere.
+ */
+export async function verifyPassword(
+ password: string,
+ hashedPassword: string,
+): Promise<boolean> {
+ if (BCRYPT_HASH_PATTERN.test(hashedPassword)) {
+ if (isFipsModeRequired()) return false;
+ return compare(password, hashedPassword);
+ }
+
+ const parsed = parsePbkdf2Hash(hashedPassword);
+ if (!parsed) return false;
+
+ const key = await pbkdf2Async(
+ password,
+ parsed.salt,
+ parsed.iterations,
+ parsed.key.length,
+ "sha256",
+ );
+ return timingSafeEqual(key, parsed.key);
+}
+
+/** passwordRequiresReset is true for a bcrypt hash in FIPS mode, which only a password reset can replace. */
+export function passwordRequiresReset(hashedPassword: string): boolean {
+ return isFipsModeRequired() && BCRYPT_HASH_PATTERN.test(hashedPassword);
+}
+
+function parsePbkdf2Hash(
+ hashedPassword: string,
+): { iterations: number; salt: Buffer; key: Buffer } | null {
+ if (!hashedPassword.startsWith(PBKDF2_PREFIX)) return null;
+
+ const parts = hashedPassword.slice(PBKDF2_PREFIX.length).split("$");
+ if (parts.length !== 3) return null;
+ const [params, salt, key] = parts;
+
+ const iterations = Number(/^i=(\d+)$/.exec(params ?? "")?.[1]);
+ if (!Number.isSafeInteger(iterations)) return null;
+ if (iterations < PBKDF2_MIN_ITERATIONS) return null;
+ if (iterations > PBKDF2_MAX_ITERATIONS) return null;
+
+ const saltBytes = Buffer.from(salt ?? "", "base64");
+ const keyBytes = Buffer.from(key ?? "", "base64");
+ if (saltBytes.length < PBKDF2_MIN_SALT_BYTES) return null;
+ if (keyBytes.length < PBKDF2_MIN_KEY_BYTES) return null;
+
+ return { iterations, salt: saltBytes, key: keyBytes };
+}
+
+function toBase64(bytes: Buffer): string {
+ return bytes.toString("base64").replace(/=+$/, "");
+}
diff --git a/web/src/features/auth/constants.ts b/web/src/features/auth/constants.ts
index f1eae78827..1f247c04d3 100644
--- a/web/src/features/auth/constants.ts
+++ b/web/src/features/auth/constants.ts
@@ -7,3 +7,8 @@ export const ENTERPRISE_SSO_REQUIRED_MESSAGE =
// where it is matched to classify the render as an expected outcome.
export const MULTI_TENANT_SSO_DOMAIN_MISMATCH_MESSAGE =
"This domain is not associated with this SSO provider.";
+
+// Thrown by the credentials provider when LANGFUSE_REQUIRE_FIPS=true and the
+// stored password is a bcrypt hash, which FIPS mode does not verify.
+export const PASSWORD_RESET_REQUIRED_MESSAGE =
+ 'This instance runs in FIPS mode and your password must be reset. Use "forgot password?" to set a new one, or contact your administrator.';
diff --git a/web/src/server/auth.ts b/web/src/server/auth.ts
index 46a61bc089..e866007e25 100644
--- a/web/src/server/auth.ts
+++ b/web/src/server/auth.ts
@@ -10,8 +10,9 @@ import { prisma } from "@langfuse/shared/src/db";
import { isInAppAgentInstanceEnabled } from "@langfuse/shared/in-app-agent/server/modelProvider";
import {
hashPassword,
+ passwordRequiresReset,
verifyPassword,
-} from "@/src/features/auth-credentials/lib/credentialsServerUtils";
+} from "@/src/features/auth-credentials/lib/passwordHash";
import {
parseFlags,
parseFlagsWithOrganizationDefaults,
@@ -58,6 +59,7 @@ import {
import {
ENTERPRISE_SSO_REQUIRED_MESSAGE,
MULTI_TENANT_SSO_DOMAIN_MISMATCH_MESSAGE,
+ PASSWORD_RESET_REQUIRED_MESSAGE,
} from "@/src/features/auth/constants";
import { z } from "zod";
import { CloudConfigSchema, projectRoleAccessRights } from "@langfuse/shared";
@@ -124,7 +126,7 @@ const staticProviders: Provider[] = [
});
if (!dbUser) {
- // Keep bcrypt work comparable across failed login paths to reduce timing-based user enumeration.
+ // Keep hashing work comparable across failed login paths to reduce timing-based user enumeration.
await hashPassword(credentials.password);
throw new Error("Invalid credentials");
}
@@ -135,6 +137,10 @@ const staticProviders: Provider[] = [
);
}
+ if (passwordRequiresReset(dbUser.password)) {
+ throw new Error(PASSWORD_RESET_REQUIRED_MESSAGE);
+ }
+
const isValidPassword = await verifyPassword(
credentials.password,
dbUser.password,