Skip to content

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

refactor(security): replace COOKIE_SECRET_SIGN_KEY with derived cookie signing key

Victor Hugo dos Santos677fb679ec40
diff --git a/backend/src/ee/routes/v1/ldap-router.ts b/backend/src/ee/routes/v1/ldap-router.ts
index d290807a83..84437dd401 100644
--- a/backend/src/ee/routes/v1/ldap-router.ts
+++ b/backend/src/ee/routes/v1/ldap-router.ts
@@ -18,6 +18,7 @@ import { TLDAPConfig } from "@app/ee/services/ldap-config/ldap-config-types";
import { isValidLdapFilter, searchGroups } from "@app/ee/services/ldap-config/ldap-fns";
import { ApiDocsTags, LdapSso } from "@app/lib/api-docs";
import { getConfig } from "@app/lib/config/env";
+import { getCookieSigningKey } from "@app/lib/crypto/cookie-signing-key";
import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
@@ -30,7 +31,7 @@ import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
export const registerLdapRouter = async (server: FastifyZodProvider) => {
const appCfg = getConfig();
const passport = new Authenticator({ key: "ldap", userProperty: "passportUser" });
- await server.register(fastifySession, { secret: appCfg.COOKIE_SECRET_SIGN_KEY });
+ await server.register(fastifySession, { secret: getCookieSigningKey() });
await server.register(passport.initialize());
await server.register(passport.secureSession());
diff --git a/backend/src/ee/routes/v1/oidc-router.ts b/backend/src/ee/routes/v1/oidc-router.ts
index ddecbfef8a..0269643075 100644
--- a/backend/src/ee/routes/v1/oidc-router.ts
+++ b/backend/src/ee/routes/v1/oidc-router.ts
@@ -15,6 +15,7 @@ import { OidcConfigsSchema } from "@app/db/schemas";
import { OIDCConfigurationType, OIDCJWTSignatureAlgorithm } from "@app/ee/services/oidc/oidc-config-types";
import { ApiDocsTags, OidcSSo } from "@app/lib/api-docs";
import { getConfig } from "@app/lib/config/env";
+import { getCookieSigningKey } from "@app/lib/crypto/cookie-signing-key";
import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { authRateLimit, readLimit, writeLimit } from "@app/server/config/rateLimiter";
@@ -56,7 +57,7 @@ export const registerOidcRouter = async (server: FastifyZodProvider) => {
});
await server.register(fastifySession, {
- secret: appCfg.COOKIE_SECRET_SIGN_KEY,
+ secret: getCookieSigningKey(),
store: redisStore,
cookie: {
secure: appCfg.HTTPS_ENABLED,
diff --git a/backend/src/ee/routes/v1/saml-router.ts b/backend/src/ee/routes/v1/saml-router.ts
index ad171569a3..e3454d3753 100644
--- a/backend/src/ee/routes/v1/saml-router.ts
+++ b/backend/src/ee/routes/v1/saml-router.ts
@@ -17,6 +17,7 @@ import { z } from "zod";
import { SamlProviders, TGetSamlCfgDTO } from "@app/ee/services/saml-config/saml-config-types";
import { ApiDocsTags, SamlSso } from "@app/lib/api-docs";
import { getConfig } from "@app/lib/config/env";
+import { getCookieSigningKey } from "@app/lib/crypto/cookie-signing-key";
import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
@@ -48,7 +49,7 @@ type TSAMLConfig = {
export const registerSamlRouter = async (server: FastifyZodProvider) => {
const appCfg = getConfig();
const passport = new Authenticator({ key: "saml", userProperty: "passportUser" });
- await server.register(fastifySession, { secret: appCfg.COOKIE_SECRET_SIGN_KEY });
+ await server.register(fastifySession, { secret: getCookieSigningKey() });
await server.register(passport.initialize());
await server.register(passport.secureSession());
server.decorateRequest("ssoConfig");
diff --git a/backend/src/lib/config/env.ts b/backend/src/lib/config/env.ts
index 3d9b6ceffb..eebf49ea97 100644
--- a/backend/src/lib/config/env.ts
+++ b/backend/src/lib/config/env.ts
@@ -253,10 +253,7 @@ const envSchema = z
SMTP_CUSTOM_CA_CERT: zpStr(
z.string().optional().describe("Base64 encoded custom CA certificate PEM(s) for the SMTP server")
),
- COOKIE_SECRET_SIGN_KEY: z
- .string()
- .min(32)
- .default("#5VihU%rbXHcHwWwCot5L3vyPsx$7dWYw^iGk!EJg2bC*f$PD$%KCqx^R@#^LSEf"),
+ COOKIE_SECRET_SIGN_KEY: zpStr(z.string().min(32).optional()),
// Ensure that the SITE_URL never ends with a trailing slash
SITE_URL: zpStr(z.string().transform((val) => (val ? removeTrailingSlash(val) : val))).optional(),
diff --git a/backend/src/lib/crypto/cookie-signing-key.ts b/backend/src/lib/crypto/cookie-signing-key.ts
new file mode 100644
index 0000000000..2b73ae8720
--- /dev/null
+++ b/backend/src/lib/crypto/cookie-signing-key.ts
@@ -0,0 +1,29 @@
+import crypto from "node:crypto";
+
+import { InternalServerError } from "@app/lib/errors";
+
+const COOKIE_SIGNING_KEY_CONTEXT = "infisical-cookie-signing-key-v1";
+
+let cookieSigningKey: string | undefined;
+
+/**
+ * Derives the cookie signing key from the KMS root key, which is already generated and persisted
+ * per instance at first boot. That keeps the key unique to the deployment without a second secret
+ * at rest, and stable across restarts, replicas, and KEK rotations.
+ */
+export const deriveCookieSigningKey = (rootKey: Buffer) =>
+ Buffer.from(crypto.hkdfSync("sha256", rootKey, Buffer.alloc(0), COOKIE_SIGNING_KEY_CONTEXT, 32)).toString("base64");
+
+export const setCookieSigningKey = (key: string) => {
+ cookieSigningKey = key;
+};
+
+export const getCookieSigningKey = () => {
+ if (!cookieSigningKey) {
+ throw new InternalServerError({
+ message: "Cookie signing key was requested before the KMS root key was loaded"
+ });
+ }
+
+ return cookieSigningKey;
+};
diff --git a/backend/src/server/app.ts b/backend/src/server/app.ts
index 3cc47e4c55..82811a23c7 100644
--- a/backend/src/server/app.ts
+++ b/backend/src/server/app.ts
@@ -3,7 +3,7 @@ import path from "node:path";
import type { ClickHouseClient } from "@clickhouse/client";
import type { FastifyCookieOptions } from "@fastify/cookie";
-import cookie from "@fastify/cookie";
+import cookie, { signerFactory } from "@fastify/cookie";
import type { FastifyCorsOptions } from "@fastify/cors";
import cors from "@fastify/cors";
import fastifyEtag from "@fastify/etag";
@@ -20,6 +20,7 @@ import { Knex } from "knex";
import { THsmServiceFactory } from "@app/ee/services/hsm/hsm-service";
import { TKeyStoreFactory } from "@app/keystore/keystore";
import { getConfig, IS_PACKAGED, TEnvConfig } from "@app/lib/config/env";
+import { getCookieSigningKey } from "@app/lib/crypto/cookie-signing-key";
import { CustomLogger } from "@app/lib/logger/logger";
import { alphaNumericNanoId } from "@app/lib/nanoid";
import { RequestContextKey } from "@app/lib/request-context/request-context-keys";
@@ -113,8 +114,17 @@ export const main = async ({
});
try {
+ let cookieSigner: ReturnType<typeof signerFactory> | undefined;
+ const getCookieSigner = () => {
+ if (!cookieSigner) cookieSigner = signerFactory(getCookieSigningKey());
+ return cookieSigner;
+ };
+
await server.register<FastifyCookieOptions>(cookie, {
- secret: appCfg.COOKIE_SECRET_SIGN_KEY
+ secret: {
+ sign: (value) => getCookieSigner().sign(value),
+ unsign: (value) => getCookieSigner().unsign(value)
+ }
});
await server.register(fastifyEtag);
diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.ts
index d882a84651..38ac0482bf 100644
--- a/backend/src/server/routes/index.ts
+++ b/backend/src/server/routes/index.ts
@@ -199,6 +199,7 @@ import { keyValueStoreDALFactory } from "@app/keystore/key-value-store-dal";
import { TKeyStoreFactory } from "@app/keystore/keystore";
import { getConfig, TEnvConfig } from "@app/lib/config/env";
import { cronJobFactory } from "@app/lib/cron/cron-job";
+import { setCookieSigningKey } from "@app/lib/crypto/cookie-signing-key";
import { crypto } from "@app/lib/crypto/cryptography";
import { BadRequestError } from "@app/lib/errors";
import { initGatewayLoadTracker } from "@app/lib/gateway-v2/gateway-load-tracker";
@@ -3994,6 +3995,8 @@ export const registerRoutes = async (
}
await kmsService.startService(hsmStatus);
+ setCookieSigningKey(appCfg.COOKIE_SECRET_SIGN_KEY || kmsService.getCookieSigningKey());
+
// Register all cron jobs (synchronous registrations) before starting the scheduler
encryptionKeyRotationService.init();
telemetryQueue.startTelemetryCheck();
diff --git a/backend/src/server/routes/v1/identity-ldap-auth-router.ts b/backend/src/server/routes/v1/identity-ldap-auth-router.ts
index a194246040..c998b9a39f 100644
--- a/backend/src/server/routes/v1/identity-ldap-auth-router.ts
+++ b/backend/src/server/routes/v1/identity-ldap-auth-router.ts
@@ -18,7 +18,7 @@ import { IdentityLdapAuthsSchema } from "@app/db/schemas/identity-ldap-auths";
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
import { isValidLdapFilter } from "@app/ee/services/ldap-config/ldap-fns";
import { ApiDocsTags, LDAP_AUTH } from "@app/lib/api-docs";
-import { getConfig } from "@app/lib/config/env";
+import { getCookieSigningKey } from "@app/lib/crypto/cookie-signing-key";
import { UnauthorizedError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
@@ -32,9 +32,8 @@ import { isSuperAdmin } from "@app/services/super-admin/super-admin-fns";
import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
export const registerIdentityLdapAuthRouter = async (server: FastifyZodProvider) => {
- const appCfg = getConfig();
const passport = new Authenticator({ key: "ldap-identity-auth", userProperty: "passportMachineIdentity" });
- await server.register(fastifySession, { secret: appCfg.COOKIE_SECRET_SIGN_KEY });
+ await server.register(fastifySession, { secret: getCookieSigningKey() });
await server.register(passport.initialize());
await server.register(passport.secureSession());
diff --git a/backend/src/server/routes/v1/sso-router.ts b/backend/src/server/routes/v1/sso-router.ts
index e9270ba995..ea4ba8715f 100644
--- a/backend/src/server/routes/v1/sso-router.ts
+++ b/backend/src/server/routes/v1/sso-router.ts
@@ -18,6 +18,7 @@ import { z } from "zod";
import { INFISICAL_PROVIDER_GITHUB_ACCESS_TOKEN } from "@app/lib/config/const";
import { getConfig } from "@app/lib/config/env";
+import { getCookieSigningKey } from "@app/lib/crypto/cookie-signing-key";
import { BadRequestError, NotFoundError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { ms } from "@app/lib/ms";
@@ -425,7 +426,7 @@ export const registerSsoRouter = async (server: FastifyZodProvider) => {
});
await server.register(fastifySession, {
- secret: appCfg.COOKIE_SECRET_SIGN_KEY,
+ secret: getCookieSigningKey(),
store: redisStore,
cookie: {
secure: appCfg.HTTPS_ENABLED,
diff --git a/backend/src/services/kms/kms-service.ts b/backend/src/services/kms/kms-service.ts
index 45254a4c6c..5bfce2733a 100644
--- a/backend/src/services/kms/kms-service.ts
+++ b/backend/src/services/kms/kms-service.ts
@@ -18,6 +18,7 @@ import { withCache } from "@app/lib/cache/with-cache";
import { getOriginalConfig, TEnvConfig } from "@app/lib/config/env";
import { generateSecretValueBlindIndexFromKmsKey } from "@app/lib/crypto/blind-index";
import { symmetricCipherService, SymmetricKeyAlgorithm } from "@app/lib/crypto/cipher";
+import { deriveCookieSigningKey } from "@app/lib/crypto/cookie-signing-key";
import { crypto } from "@app/lib/crypto/cryptography";
import { HmacAlgorithm, hmacService } from "@app/lib/crypto/hmac";
import { setLegacyKeyMaterial, TLegacyKeyMaterial, TLegacyKeySnapshot } from "@app/lib/crypto/legacy-key";
@@ -1796,6 +1797,13 @@ export const kmsServiceFactory = ({
await $ensureKekHistory();
};
+ const getCookieSigningKey = () => {
+ if (!ROOT_ENCRYPTION_KEY.length) {
+ throw new InternalServerError({ message: "KMS root key is not loaded" });
+ }
+ return deriveCookieSigningKey(ROOT_ENCRYPTION_KEY);
+ };
+
/** How a rotation stages a key the instance is not running with yet. */
const encryptRootKeyForKek = (kekBuffer: Buffer) => {
if (!ROOT_ENCRYPTION_KEY.length) {
@@ -1892,6 +1900,7 @@ export const kmsServiceFactory = ({
return {
startService,
+ getCookieSigningKey,
encryptRootKeyForKek,
getCurrentKekLabel,
generateKmsKey,
diff --git a/docs/self-hosting/configuration/envars.mdx b/docs/self-hosting/configuration/envars.mdx
index 3d43ec6f3a..ad2f3798ee 100644
--- a/docs/self-hosting/configuration/envars.mdx
+++ b/docs/self-hosting/configuration/envars.mdx
@@ -25,6 +25,13 @@ Used to configure platform-specific security and operational settings.
-base64 32`.
</ParamField>
+<ParamField query="COOKIE_SECRET_SIGN_KEY" type="string" default="generated per instance">
+ Signs the session cookies used by the SAML, OIDC, and LDAP login flows. Left unset, each
+ instance derives its own key at startup, so no two deployments share one. Set it to a random
+ 32-byte base64 string, generated with `openssl rand -base64 32`, to manage the key yourself.
+ Changing the value ends every login already in progress.
+</ParamField>
+
<ParamField query="SITE_URL" type="string" default="none" required>
Must be an absolute URL including the protocol (e.g.
https://app.infisical.com).