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
chore: add sso.md and update makefile for full oidc/ldap/saml/scim local dev + seeding / bootstrap scripts to quickly launch a fully configured org with verified email domain and sso config
Scott Wilson07d497e4e547
diff --git a/.env.example b/.env.exampleindex fd4fdc50c8..b66bc323ba 100644--- a/.env.example+++ b/.env.example@@ -21,7 +21,7 @@ REDIS_URL=redis://redis:6379# Website URL# Required-SITE_URL=http://localhost:80+SITE_URL=http://localhost:8080# Mail/SMTPSMTP_HOST=diff --git a/Makefile b/Makefileindex 63a6ba9b21..806f6efd4e 100644--- a/Makefile+++ b/Makefile@@ -7,9 +7,6 @@ push:up-dev:docker compose -f docker-compose.dev.yml up --build-up-dev-ldap:- docker compose -f docker-compose.dev.yml --profile ldap up --build-up-dev-metrics:docker compose -f docker-compose.dev.yml --profile metrics up --build@@ -31,8 +28,14 @@ reviewable-api:reviewable: reviewable-ui reviewable-api-up-dev-sso:- docker compose -f docker-compose.dev.yml --profile sso up --build+up-dev-oidc:+ docker compose -f docker-compose.dev.yml --profile oidc up --build++up-dev-ldap:+ docker compose -f docker-compose.dev.yml --profile ldap up --build++up-dev-saml:+ docker compose -f docker-compose.dev.yml --profile saml up --buildup-dev-pingfed:docker compose -f docker-compose.dev.yml --profile pingfed up --build@@ -46,14 +49,39 @@ seed-dev-ad:samba-tool user delete jdoe 2>/dev/null || true; \samba-tool user delete asmith 2>/dev/null || true; \samba-tool group delete infisical-users 2>/dev/null || true; \- samba-tool user create jdoe "Passw0rd!" --given-name=John --surname=Doe [email protected]; \- samba-tool user create asmith "Passw0rd!" --given-name=Alice --surname=Smith [email protected]; \+ samba-tool user create jdoe "password123!" --given-name=John --surname=Doe [email protected]; \+ samba-tool user create asmith "password123!" --given-name=Alice --surname=Smith [email protected]; \samba-tool user rename jdoe [email protected]; \samba-tool user rename asmith [email protected]; \samba-tool group add infisical-users; \samba-tool group addmembers infisical-users jdoe,asmith \'+seed-dev-ldap:+ # Seeds OpenLDAP entries (idempotent) and the Infisical side for LDAP SSO testing: an+ # [email protected] admin, a verified domain, and an active LDAP config. With ORG_ID=<uuid>+ # it configures that org; otherwise it bootstraps a dedicated `ldap` org. Needs the stack up+ # (`make up-dev-ldap`).+ @docker compose -f docker-compose.dev.yml exec -T openldap \+ ldapadd -c -x -D "cn=admin,dc=ldap,dc=com" -w admin < docker/openldap/bootstrap.ldif; \+ status=$$?; \+ if [ $$status -ne 0 ] && [ $$status -ne 68 ]; then exit $$status; fi; \+ if [ $$status -eq 68 ]; then echo "LDAP entries already exist, continuing."; fi+ docker compose -f docker-compose.dev.yml exec -T backend npx tsx ./src/db/seed-ldap.ts $(ORG_ID)++seed-dev-oidc:+ # Sets up the Infisical side for OIDC SSO testing: an [email protected] admin, a verified+ # domain, and an active OIDC config. With ORG_ID=<uuid> it configures that existing org;+ # otherwise it bootstraps a dedicated `oidc` org. Needs the stack up (`make up-dev-oidc`).+ docker compose -f docker-compose.dev.yml exec -T backend npx tsx ./src/db/seed-oidc.ts $(ORG_ID)++seed-dev-saml:+ # Sets up SAML SSO + real SCIM provisioning against the local Authentik IdP. Bootstraps a+ # dedicated `saml` org ([email protected], verified saml.com domain, active SAML config, SCIM token),+ # configures Authentik (SAML + SCIM providers, app, john/[email protected]), and provisions those+ # users into Infisical via SCIM. Needs the stack up (`make up-dev-saml`).+ docker compose -f docker-compose.dev.yml exec -T backend npx tsx ./src/db/seed-saml.ts+# Golang commandsgo-generate:diff --git a/backend/package.json b/backend/package.jsonindex e488afa629..7ebe0ac511 100644--- a/backend/package.json+++ b/backend/package.json@@ -52,6 +52,9 @@"seed:new": "tsx ./scripts/create-seed-file.ts","seed": "knex --knexfile ./dist/db/knexfile.ts --client pg seed:run","seed-dev": "knex --knexfile ./src/db/knexfile.ts --client pg seed:run",+ "seed-oidc": "tsx ./src/db/seed-oidc.ts",+ "seed-ldap": "tsx ./src/db/seed-ldap.ts",+ "seed-saml": "tsx ./src/db/seed-saml.ts","db:reset": "npm run migration:rollback -- --all && npm run migration:latest","email:dev": "email dev --dir src/services/smtp/emails","validate-upgrade-path": "tsx ./scripts/validate-upgrade-path-file.ts"diff --git a/backend/src/db/seed-ldap.ts b/backend/src/db/seed-ldap.tsnew file mode 100644index 0000000000..14fdb4cdf0--- /dev/null+++ b/backend/src/db/seed-ldap.ts@@ -0,0 +1,263 @@+/* eslint-disable no-console */+// Standalone dev helper: stands up everything needed to test LDAP SSO against the local OpenLDAP+// dev container, without touching the shared `seed-dev` data. It is idempotent and writes:+// 1. a login-capable `[email protected]` admin (password `password123!`),+// 2. a `status=verified` `ldap.com` email-domain row (satisfies verifyEmailDomainOwnership+// for LDAP logins), and+// 3. an active `ldap_configs` row pointing at OpenLDAP, bind DN/password encrypted with the org+// KMS data key (the same key the login path decrypts with).+//+// Org selection:+// * `make seed-dev-ldap ORG_ID=<uuid>` / `npm run seed-ldap -- <uuid>` -> configure that org.+// * no org id -> bootstrap a dedicated `ldap` org (slug `ldap`) if missing.+//+// The directory entries themselves live in docker/openldap/bootstrap.ldif (`make seed-dev-ldap`+// applies both). The seeded users john, alice, and admin all sign in with `password123!`, by uid+// (john) or email ([email protected]). See sso.md.+import argon2, { argon2id } from "argon2";+import jsrp from "jsrp";++import { EmailDomainStatus } from "@app/ee/services/email-domain/email-domain-types";+import { inMemoryKeyStore } from "@app/keystore/memory";+import { crypto, SymmetricKeySize } from "@app/lib/crypto/cryptography";+import { initLogger, logger } from "@app/lib/logger";+import { AuthMethod } from "@app/services/auth/auth-type";+import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";+import { KmsDataKey } from "@app/services/kms/kms-types";+import { orgDALFactory } from "@app/services/org/org-dal";+import { superAdminDALFactory } from "@app/services/super-admin/super-admin-dal";++import { initDbConnection } from "./instance";+import { getMigrationEnvConfig, getMigrationHsmConfig } from "./migrations/utils/env-config";+import { getMigrationEncryptionServices, getMigrationHsmService } from "./migrations/utils/services";+import { AccessScope, OrgMembershipRole, OrgMembershipStatus, TableName } from "./schemas";++const ONE_YEAR_MS = 365 * 24 * 60 * 60 * 1000;+const SUPER_ADMIN_CONFIG_ID = "00000000-0000-0000-0000-000000000000";++// Parameterized variant of seed-data#generateUserSrpKeys; the SRP verifier is bound to the+// username (the email here), so it can't be shared with the hardcoded seed user.+const generateUserSrpKeys = async (email: string, password: string) => {+ const { publicKey, privateKey } = await crypto.encryption().asymmetric().generateKeyPair();++ // eslint-disable-next-line+ const client = new jsrp.client();+ await new Promise((resolve) => {+ client.init({ username: email, password }, () => resolve(null));+ });+ const { salt, verifier } = await new Promise<{ salt: string; verifier: string }>((resolve, reject) => {+ client.createVerifier((err, res) => (err ? reject(err) : resolve(res)));+ });++ const derivedKey = await argon2.hash(password, {+ salt: Buffer.from(salt),+ memoryCost: 65536,+ timeCost: 3,+ parallelism: 1,+ hashLength: 32,+ type: argon2id,+ raw: true+ });+ if (!derivedKey) throw new Error("Failed to derive key from password");++ const key = crypto.randomBytes(32);+ const {+ ciphertext: encryptedPrivateKey,+ iv: encryptedPrivateKeyIV,+ tag: encryptedPrivateKeyTag+ } = crypto.encryption().symmetric().encrypt({ plaintext: privateKey, key, keySize: SymmetricKeySize.Bits128 });+ const {+ ciphertext: protectedKey,+ iv: protectedKeyIV,+ tag: protectedKeyTag+ } = crypto+ .encryption()+ .symmetric()+ .encrypt({ plaintext: key.toString("hex"), key: derivedKey, keySize: SymmetricKeySize.Bits128 });++ return {+ protectedKey,+ protectedKeyIV,+ protectedKeyTag,+ publicKey,+ encryptedPrivateKey,+ encryptedPrivateKeyIV,+ encryptedPrivateKeyTag,+ salt,+ verifier+ };+};++const main = async () => {+ initLogger();++ const orgIdArg = process.argv[2] || process.env.SEED_ORG_ID || "";+ const useProvidedOrg = Boolean(orgIdArg);++ const email = process.env.SEED_SSO_USER_EMAIL || "[email protected]";+ const password = process.env.SEED_SSO_USER_PASSWORD || "password123!";+ const domain = (process.env.SEED_SSO_DOMAIN || email.split("@")[1] || "ldap.com").toLowerCase().trim();++ // The backend binds to OpenLDAP over the internal compose network (openldap:389). LDAP has no+ // browser redirect, so there is no hostname/issuer problem. Override for a host-run backend+ // (e.g. ldap://localhost:389).+ const url = process.env.SEED_LDAP_URL || "ldap://openldap:389";+ const bindDN = process.env.SEED_LDAP_BIND_DN || "cn=admin,dc=ldap,dc=com";+ const bindPass = process.env.SEED_LDAP_BIND_PASS || "admin";+ const searchBase = process.env.SEED_LDAP_SEARCH_BASE || "ou=people,dc=ldap,dc=com";+ const groupSearchBase = process.env.SEED_LDAP_GROUP_SEARCH_BASE || "ou=groups,dc=ldap,dc=com";+ // Match on uid OR mail so you can sign in with `john` or `[email protected]`.+ const searchFilter = process.env.SEED_LDAP_SEARCH_FILTER || "(|(uid={{username}})(mail={{username}}))";++ const dbConnectionUri = process.env.DB_CONNECTION_URI;+ if (!dbConnectionUri) throw new Error("DB_CONNECTION_URI is not set");++ const db = initDbConnection({ dbConnectionUri });++ try {+ // Bootstrap the KMS stack outside the service container, exactly as the *-to-kms migrations do.+ const { hsmService } = await getMigrationHsmService({ envConfig: getMigrationHsmConfig() });+ const superAdminDAL = superAdminDALFactory(db);+ const kmsRootConfigDAL = kmsRootConfigDALFactory(db);+ const envConfig = await getMigrationEnvConfig(superAdminDAL, hsmService, kmsRootConfigDAL);+ const keyStore = inMemoryKeyStore();+ const { kmsService } = await getMigrationEncryptionServices({ envConfig, keyStore, db });+ const orgDAL = orgDALFactory(db);++ // Resolve the org: use the one the caller passed, otherwise bootstrap a dedicated `ldap` org.+ let org;+ if (useProvidedOrg) {+ org = await orgDAL.findById(orgIdArg);+ if (!org) {+ logger.error(+ `LDAP seed: org not found [orgId=${orgIdArg}]. Pass an existing org id, or omit it to bootstrap one.`+ );+ process.exitCode = 1;+ return;+ }+ } else {+ org = await db(TableName.Organization).where({ slug: "ldap" }).first();+ if (!org) {+ // Make sure a fresh DB is marked initialized so the instance is usable.+ await db(TableName.SuperAdmin)+ .insert({+ // @ts-expect-error id is the fixed singleton id for the instance super-admin config row+ id: SUPER_ADMIN_CONFIG_ID,+ initialized: true,+ allowSignUp: true,+ fipsEnabled: process.env.FIPS_ENABLED === "true"+ })+ .onConflict("id")+ .ignore();+ [org] = await db(TableName.Organization)+ .insert({ name: "LDAP Org", slug: "ldap", customerId: null })+ .returning("*");+ logger.info(`LDAP seed: bootstrapped org 'ldap' [orgId=${org.id}]`);+ }+ }++ // Ensure a login-capable admin user with this email, then ensure org membership (admin role).+ let user = await db(TableName.Users).where({ email }).first();+ if (!user) {+ [user] = await db(TableName.Users)+ .insert({+ username: email,+ email,+ // Full instance admin only when standing up our own dev org; when configuring a+ // caller-provided org, just add a normal org admin.+ superAdmin: !useProvidedOrg,+ firstName: "LDAP",+ lastName: "Admin",+ authMethods: [AuthMethod.EMAIL],+ isAccepted: true,+ isEmailVerified: true,+ isMfaEnabled: false,+ mfaMethods: null,+ devices: null+ })+ .returning("*");++ const hashedPassword = await crypto.hashing().createHash(password, 10);+ await db(TableName.Users).where({ id: user.id }).update({ hashedPassword });++ const k = await generateUserSrpKeys(email, password);+ await db(TableName.UserEncryptionKey).insert({+ encryptionVersion: 2,+ protectedKey: k.protectedKey,+ protectedKeyIV: k.protectedKeyIV,+ protectedKeyTag: k.protectedKeyTag,+ publicKey: k.publicKey,+ encryptedPrivateKey: k.encryptedPrivateKey,+ iv: k.encryptedPrivateKeyIV,+ tag: k.encryptedPrivateKeyTag,+ salt: k.salt,+ verifier: k.verifier,+ userId: user.id+ });+ }++ const existingMembership = await db(TableName.Membership)+ .where({ scope: AccessScope.Organization, scopeOrgId: org.id, actorUserId: user.id })+ .first();+ if (!existingMembership) {+ const [membership] = await db(TableName.Membership)+ .insert({+ scope: AccessScope.Organization,+ scopeOrgId: org.id,+ actorUserId: user.id,+ isActive: true,+ status: OrgMembershipStatus.Accepted+ })+ .returning("*");+ await db(TableName.MembershipRole).insert({ membershipId: membership.id, role: OrgMembershipRole.Admin });+ }++ // Pre-verified email domain (plain insert; email_domains has no encrypted columns).+ await db(TableName.EmailDomains).where({ orgId: org.id, domain }).del();+ await db(TableName.EmailDomains).insert({+ orgId: org.id,+ domain,+ verificationMethod: "seed",+ verificationCode: crypto.randomBytes(16).toString("hex"),+ verificationRecordName: `_infisical-verification.${domain}`,+ status: EmailDomainStatus.Verified,+ verifiedAt: new Date(),+ codeExpiresAt: new Date(Date.now() + ONE_YEAR_MS)+ });++ // Active LDAP config. The bind DN/password are encrypted with the org KMS data key, the same+ // key the LDAP login path decrypts with, so placeholders would break the bind.+ const { encryptor } = await kmsService.createCipherPairWithDataKey(+ { type: KmsDataKey.Organization, orgId: org.id },+ db+ );++ await db(TableName.LdapConfig).where({ orgId: org.id }).del();+ await db(TableName.LdapConfig).insert({+ orgId: org.id,+ isActive: true,+ url,+ uniqueUserAttribute: "uid",+ searchBase,+ searchFilter,+ groupSearchBase,+ groupSearchFilter: "",+ encryptedLdapBindDN: encryptor({ plainText: Buffer.from(bindDN) }).cipherTextBlob,+ encryptedLdapBindPass: encryptor({ plainText: Buffer.from(bindPass) }).cipherTextBlob,+ encryptedLdapCaCertificate: null,+ encryptedLdapClientCertificate: null,+ encryptedLdapClientKeyCertificate: null+ });++ logger.info(+ `LDAP seeded [orgId=${org.id}] [org=${org.slug}]: admin '${email}', verified domain '${domain}', active LDAP config -> ${url}`+ );+ } finally {+ await db.destroy();+ }+};++main().catch((err) => {+ console.error(err);+ process.exit(1);+});diff --git a/backend/src/db/seed-oidc.ts b/backend/src/db/seed-oidc.tsnew file mode 100644index 0000000000..f7302802c6--- /dev/null+++ b/backend/src/db/seed-oidc.ts@@ -0,0 +1,256 @@+/* eslint-disable no-console */+// Standalone dev helper: stands up everything needed to test OIDC SSO against the local Keycloak+// dev container, without touching the shared `seed-dev` data. It is idempotent and writes:+// 1. a login-capable `[email protected]` admin (password `password123!`),+// 2. a `status=verified` `oidc.com` email-domain row (satisfies verifyEmailDomainOwnership+// for OIDC logins), and+// 3. an active `oidc_configs` row pointing at Keycloak, client id/secret encrypted with the org+// KMS data key (the same key the login path decrypts with).+//+// Org selection:+// * `make seed-dev-oidc ORG_ID=<uuid>` / `npm run seed-oidc -- <uuid>` -> configure that org.+// * no org id -> bootstrap a dedicated `oidc` org (slug `oidc`) if missing.+//+// It is deliberately NOT a Knex seed in `src/db/seeds/` (those all run on every `seed-dev`), so a+// normal dev never ends up with a dangling active SSO config. See sso.md.+import argon2, { argon2id } from "argon2";+import jsrp from "jsrp";++import { EmailDomainStatus } from "@app/ee/services/email-domain/email-domain-types";+import { inMemoryKeyStore } from "@app/keystore/memory";+import { crypto, SymmetricKeySize } from "@app/lib/crypto/cryptography";+import { initLogger, logger } from "@app/lib/logger";+import { AuthMethod } from "@app/services/auth/auth-type";+import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";+import { KmsDataKey } from "@app/services/kms/kms-types";+import { orgDALFactory } from "@app/services/org/org-dal";+import { superAdminDALFactory } from "@app/services/super-admin/super-admin-dal";++import { initDbConnection } from "./instance";+import { getMigrationEnvConfig, getMigrationHsmConfig } from "./migrations/utils/env-config";+import { getMigrationEncryptionServices, getMigrationHsmService } from "./migrations/utils/services";+import { AccessScope, OrgMembershipRole, OrgMembershipStatus, TableName } from "./schemas";++const ONE_YEAR_MS = 365 * 24 * 60 * 60 * 1000;+const SUPER_ADMIN_CONFIG_ID = "00000000-0000-0000-0000-000000000000";++// Parameterized variant of seed-data#generateUserSrpKeys; the SRP verifier is bound to the+// username (the email here), so it can't be shared with the hardcoded seed user.+const generateUserSrpKeys = async (email: string, password: string) => {+ const { publicKey, privateKey } = await crypto.encryption().asymmetric().generateKeyPair();++ // eslint-disable-next-line+ const client = new jsrp.client();+ await new Promise((resolve) => {+ client.init({ username: email, password }, () => resolve(null));+ });+ const { salt, verifier } = await new Promise<{ salt: string; verifier: string }>((resolve, reject) => {+ client.createVerifier((err, res) => (err ? reject(err) : resolve(res)));+ });++ const derivedKey = await argon2.hash(password, {+ salt: Buffer.from(salt),+ memoryCost: 65536,+ timeCost: 3,+ parallelism: 1,+ hashLength: 32,+ type: argon2id,+ raw: true+ });+ if (!derivedKey) throw new Error("Failed to derive key from password");++ const key = crypto.randomBytes(32);+ const {+ ciphertext: encryptedPrivateKey,+ iv: encryptedPrivateKeyIV,+ tag: encryptedPrivateKeyTag+ } = crypto.encryption().symmetric().encrypt({ plaintext: privateKey, key, keySize: SymmetricKeySize.Bits128 });+ const {+ ciphertext: protectedKey,+ iv: protectedKeyIV,+ tag: protectedKeyTag+ } = crypto+ .encryption()+ .symmetric()+ .encrypt({ plaintext: key.toString("hex"), key: derivedKey, keySize: SymmetricKeySize.Bits128 });++ return {+ protectedKey,+ protectedKeyIV,+ protectedKeyTag,+ publicKey,+ encryptedPrivateKey,+ encryptedPrivateKeyIV,+ encryptedPrivateKeyTag,+ salt,+ verifier+ };+};++const main = async () => {+ initLogger();++ const orgIdArg = process.argv[2] || process.env.SEED_ORG_ID || "";+ const useProvidedOrg = Boolean(orgIdArg);++ const email = process.env.SEED_SSO_USER_EMAIL || "[email protected]";+ const password = process.env.SEED_SSO_USER_PASSWORD || "password123!";+ const domain = (process.env.SEED_SSO_DOMAIN || email.split("@")[1] || "oidc.com").toLowerCase().trim();+ const clientId = process.env.SEED_OIDC_CLIENT_ID || "infisical-dev";+ const clientSecret = process.env.SEED_OIDC_CLIENT_SECRET || "infisical-dev-client-secret";+ // The backend fetches discovery over the internal compose network (keycloak:8080). Keycloak's+ // KC_HOSTNAME pins the issuer and browser-facing endpoints to http://localhost:8088, so the+ // browser stays on localhost and no keycloak.local /etc/hosts entry is needed. Override for a+ // host-run backend (e.g. http://localhost:8088/...).+ const discoveryURL =+ process.env.SEED_OIDC_DISCOVERY_URL || "http://keycloak:8080/realms/infisical/.well-known/openid-configuration";+ const jwtSignatureAlgorithm = process.env.SEED_OIDC_JWT_ALG || "RS256";++ const dbConnectionUri = process.env.DB_CONNECTION_URI;+ if (!dbConnectionUri) throw new Error("DB_CONNECTION_URI is not set");++ const db = initDbConnection({ dbConnectionUri });++ try {+ // Bootstrap the KMS stack outside the service container, exactly as the *-to-kms migrations do.+ const { hsmService } = await getMigrationHsmService({ envConfig: getMigrationHsmConfig() });+ const superAdminDAL = superAdminDALFactory(db);+ const kmsRootConfigDAL = kmsRootConfigDALFactory(db);+ const envConfig = await getMigrationEnvConfig(superAdminDAL, hsmService, kmsRootConfigDAL);+ const keyStore = inMemoryKeyStore();+ const { kmsService } = await getMigrationEncryptionServices({ envConfig, keyStore, db });+ const orgDAL = orgDALFactory(db);++ // Resolve the org: use the one the caller passed, otherwise bootstrap a dedicated `oidc` org.+ let org;+ if (useProvidedOrg) {+ org = await orgDAL.findById(orgIdArg);+ if (!org) {+ logger.error(+ `SSO seed: org not found [orgId=${orgIdArg}]. Pass an existing org id, or omit it to bootstrap one.`+ );+ process.exitCode = 1;+ return;+ }+ } else {+ org = await db(TableName.Organization).where({ slug: "oidc" }).first();+ if (!org) {+ // Make sure a fresh DB is marked initialized so the instance is usable.+ await db(TableName.SuperAdmin)+ .insert({+ // @ts-expect-error id is the fixed singleton id for the instance super-admin config row+ id: SUPER_ADMIN_CONFIG_ID,+ initialized: true,+ allowSignUp: true,+ fipsEnabled: process.env.FIPS_ENABLED === "true"+ })+ .onConflict("id")+ .ignore();+ [org] = await db(TableName.Organization)+ .insert({ name: "OIDC Org", slug: "oidc", customerId: null })+ .returning("*");+ logger.info(`SSO seed: bootstrapped org 'oidc' [orgId=${org.id}]`);+ }+ }++ // Ensure a login-capable admin user with this email, then ensure org membership (admin role).+ let user = await db(TableName.Users).where({ email }).first();+ if (!user) {+ [user] = await db(TableName.Users)+ .insert({+ username: email,+ email,+ // Full instance admin only when standing up our own dev org; when configuring a+ // caller-provided org, just add a normal org admin.+ superAdmin: !useProvidedOrg,+ firstName: "Test",+ lastName: "",+ authMethods: [AuthMethod.EMAIL],+ isAccepted: true,+ isEmailVerified: true,+ isMfaEnabled: false,+ mfaMethods: null,+ devices: null+ })+ .returning("*");++ const hashedPassword = await crypto.hashing().createHash(password, 10);+ await db(TableName.Users).where({ id: user.id }).update({ hashedPassword });++ const k = await generateUserSrpKeys(email, password);+ await db(TableName.UserEncryptionKey).insert({+ encryptionVersion: 2,+ protectedKey: k.protectedKey,+ protectedKeyIV: k.protectedKeyIV,+ protectedKeyTag: k.protectedKeyTag,+ publicKey: k.publicKey,+ encryptedPrivateKey: k.encryptedPrivateKey,+ iv: k.encryptedPrivateKeyIV,+ tag: k.encryptedPrivateKeyTag,+ salt: k.salt,+ verifier: k.verifier,+ userId: user.id+ });+ }++ const existingMembership = await db(TableName.Membership)+ .where({ scope: AccessScope.Organization, scopeOrgId: org.id, actorUserId: user.id })+ .first();+ if (!existingMembership) {+ const [membership] = await db(TableName.Membership)+ .insert({+ scope: AccessScope.Organization,+ scopeOrgId: org.id,+ actorUserId: user.id,+ isActive: true,+ status: OrgMembershipStatus.Accepted+ })+ .returning("*");+ await db(TableName.MembershipRole).insert({ membershipId: membership.id, role: OrgMembershipRole.Admin });+ }++ // Pre-verified email domain (plain insert; email_domains has no encrypted columns).+ await db(TableName.EmailDomains).where({ orgId: org.id, domain }).del();+ await db(TableName.EmailDomains).insert({+ orgId: org.id,+ domain,+ verificationMethod: "seed",+ verificationCode: crypto.randomBytes(16).toString("hex"),+ verificationRecordName: `_infisical-verification.${domain}`,+ status: EmailDomainStatus.Verified,+ verifiedAt: new Date(),+ codeExpiresAt: new Date(Date.now() + ONE_YEAR_MS)+ });++ // Active OIDC config. client id/secret are encrypted with the org KMS data key, the same+ // key the OIDC login path decrypts with, so placeholders would break login.+ const { encryptor } = await kmsService.createCipherPairWithDataKey(+ { type: KmsDataKey.Organization, orgId: org.id },+ db+ );++ await db(TableName.OidcConfig).where({ orgId: org.id }).del();+ await db(TableName.OidcConfig).insert({+ orgId: org.id,+ configurationType: "discoveryURL",+ discoveryURL,+ isActive: true,+ jwtSignatureAlgorithm,+ manageGroupMemberships: false,+ allowedEmailDomains: null,+ encryptedOidcClientId: encryptor({ plainText: Buffer.from(clientId) }).cipherTextBlob,+ encryptedOidcClientSecret: encryptor({ plainText: Buffer.from(clientSecret) }).cipherTextBlob+ });++ logger.info(+ `SSO seeded [orgId=${org.id}] [org=${org.slug}]: admin '${email}', verified domain '${domain}', active OIDC config -> ${discoveryURL}`+ );+ } finally {+ await db.destroy();+ }+};++main().catch((err) => {+ console.error(err);+ process.exit(1);+});diff --git a/backend/src/db/seed-saml.ts b/backend/src/db/seed-saml.tsnew file mode 100644index 0000000000..66b117bf52--- /dev/null+++ b/backend/src/db/seed-saml.ts@@ -0,0 +1,386 @@+/* eslint-disable no-console */+// Standalone dev helper: stands up SAML SSO + real SCIM provisioning against the local Authentik+// IdP (`make up-dev-saml`), without touching the shared `seed-dev` data. One `saml` org is used for+// both, since SCIM provisions the user and SAML logs them in (the SAML NameID must equal the SCIM+// userName, and Infisical only allows SCIM once an SSO config exists). It orchestrates BOTH sides:+// * Infisical (DB): a `saml` org (scimEnabled), a login-capable `[email protected]` admin, a verified+// `saml.com` domain, a SCIM token, and an active SAML config (Authentik's entryPoint + signing cert).+// * Authentik (API, via the bootstrap token): the test users john/[email protected] in a group, a SAML+// provider (ACS -> Infisical, NameID = email, audience spn:SITE_URL for SP-initiated), a SCIM+// provider pointed at Infisical's SCIM endpoint with that token, and an application binding both.+// * A SCIM sync is triggered at the end (provider save), provisioning the group into Infisical.+//+// Run: `make seed-dev-saml` / `npm run seed-saml`. See sso.md.+import { EmailDomainStatus } from "@app/ee/services/email-domain/email-domain-types";+import { SamlProviders } from "@app/ee/services/saml-config/saml-config-types";+import { inMemoryKeyStore } from "@app/keystore/memory";+import { crypto } from "@app/lib/crypto/cryptography";+import { initLogger, logger } from "@app/lib/logger";+import { AuthTokenType } from "@app/services/auth/auth-type";+import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";+import { KmsDataKey } from "@app/services/kms/kms-types";+import { superAdminDALFactory } from "@app/services/super-admin/super-admin-dal";++import { initDbConnection } from "./instance";+import { getMigrationEnvConfig, getMigrationHsmConfig } from "./migrations/utils/env-config";+import { getMigrationEncryptionServices, getMigrationHsmService } from "./migrations/utils/services";+import { TableName } from "./schemas";+import { seedAdminUser } from "./seed-sso-shared";++const ONE_YEAR_MS = 365 * 24 * 60 * 60 * 1000;+const SUPER_ADMIN_CONFIG_ID = "00000000-0000-0000-0000-000000000000";+// Fixed so the Infisical SAML config id (= the Authentik ACS path) is stable across re-runs.+const SAML_CONFIG_ID = "11111111-1111-1111-1111-111111111111";++const ORG_SLUG = "saml";+const ORG_NAME = "SAML Org";+const DOMAIN = "saml.com";+const ADMIN_EMAIL = "[email protected]";+const PASSWORD = process.env.SEED_SSO_USER_PASSWORD || "password123!";+const GROUP_NAME = "infisical-saml";+const APP_SLUG = "infisical";+const TEST_USERS = [+ { username: "[email protected]", email: "[email protected]", name: "John Doe" },+ { username: "[email protected]", email: "[email protected]", name: "Alice Smith" }+];++// Where the browser is sent (must be host-reachable) vs. where the backend/seed call the API and+// where Authentik's SCIM sync calls Infisical back (compose-internal).+const SITE_URL = process.env.SITE_URL || "http://localhost:8080";+const AK_PUBLIC = process.env.SEED_AUTHENTIK_PUBLIC_URL || "http://localhost:9100";+const AK = `${process.env.SEED_AUTHENTIK_URL || "http://authentik-server:9000"}/api/v3`;+const AK_TOKEN = process.env.SEED_AUTHENTIK_TOKEN || "authentik-dev-bootstrap-token";+const INFISICAL_SCIM_URL = process.env.SEED_SCIM_URL || "http://backend:4000/api/v1/scim";+const SAML_ENTRY_POINT = `${AK_PUBLIC}/application/saml/${APP_SLUG}/sso/binding/redirect/`;++const akHeaders = { Authorization: `Bearer ${AK_TOKEN}`, "Content-Type": "application/json" };++type TAkResult = { pk: string | number; [k: string]: unknown };++const akGet = async (path: string) => {+ const res = await fetch(`${AK}${path}`, { headers: akHeaders });+ if (!res.ok) throw new Error(`GET ${path} -> ${res.status} ${await res.text()}`);+ return res.json() as Promise<{ results?: TAkResult[]; [k: string]: unknown }>;+};+const akSend = async (method: string, path: string, body: Record<string, unknown>) => {+ const res = await fetch(`${AK}${path}`, { method, headers: akHeaders, body: JSON.stringify(body) });+ if (!res.ok) throw new Error(`${method} ${path} -> ${res.status} ${await res.text()}`);+ // Some endpoints (e.g. set_password) return 204 No Content.+ const text = await res.text();+ return (text ? JSON.parse(text) : {}) as TAkResult;+};+// Returns the pk of the first result, or null.+const akFindPk = async (path: string) => {+ const d = await akGet(path);+ return d.results && d.results.length ? d.results[0].pk : null;+};+// Ensures a custom SAML property mapping (matched by exact name), creating it if missing.+const ensureSamlMapping = async (name: string, samlName: string, expression: string) => {+ const d = await akGet(`/propertymappings/provider/saml/?search=${encodeURIComponent(name)}`);+ const found = (d.results || []).find((r) => (r as { name?: string }).name === name);+ if (found) return found.pk;+ return (await akSend("POST", `/propertymappings/provider/saml/`, { name, saml_name: samlName, expression })).pk;+};++const main = async () => {+ initLogger();++ const dbConnectionUri = process.env.DB_CONNECTION_URI;+ if (!dbConnectionUri) throw new Error("DB_CONNECTION_URI is not set");+ const authSecret = process.env.AUTH_SECRET || process.env.JWT_AUTH_SECRET;+ if (!authSecret) throw new Error("AUTH_SECRET (or JWT_AUTH_SECRET) is not set; cannot sign the SCIM token");+ const db = initDbConnection({ dbConnectionUri });++ try {+ // ---- Infisical: KMS bootstrap ----+ const { hsmService } = await getMigrationHsmService({ envConfig: getMigrationHsmConfig() });+ const superAdminDAL = superAdminDALFactory(db);+ const kmsRootConfigDAL = kmsRootConfigDALFactory(db);+ const envConfig = await getMigrationEnvConfig(superAdminDAL, hsmService, kmsRootConfigDAL);+ const keyStore = inMemoryKeyStore();+ const { kmsService } = await getMigrationEncryptionServices({ envConfig, keyStore, db });++ // ---- Infisical: org (SCIM enabled) ----+ let org = await db(TableName.Organization).where({ slug: ORG_SLUG }).first();+ if (!org) {+ await db(TableName.SuperAdmin)+ .insert({+ // @ts-expect-error id is the fixed singleton id for the instance super-admin config row+ id: SUPER_ADMIN_CONFIG_ID,+ initialized: true,+ allowSignUp: true,+ fipsEnabled: process.env.FIPS_ENABLED === "true"+ })+ .onConflict("id")+ .ignore();+ [org] = await db(TableName.Organization)+ .insert({ name: ORG_NAME, slug: ORG_SLUG, customerId: null, scimEnabled: true })+ .returning("*");+ logger.info(`SAML seed: bootstrapped org 'saml' [orgId=${org.id}]`);+ } else if (!org.scimEnabled) {+ await db(TableName.Organization).where({ id: org.id }).update({ scimEnabled: true });+ }++ // ---- Infisical: login-capable admin (password login + org owner) ----+ await seedAdminUser(db, {+ email: ADMIN_EMAIL,+ password: PASSWORD,+ firstName: "SAML",+ lastName: "Admin",+ superAdmin: true,+ orgId: org.id+ });++ // ---- Infisical: verified email domain (required for SCIM POST + SAML login) ----+ await db(TableName.EmailDomains).where({ orgId: org.id, domain: DOMAIN }).del();+ await db(TableName.EmailDomains).insert({+ orgId: org.id,+ domain: DOMAIN,+ verificationMethod: "seed",+ verificationCode: crypto.randomBytes(16).toString("hex"),+ verificationRecordName: `_infisical-verification.${DOMAIN}`,+ status: EmailDomainStatus.Verified,+ verifiedAt: new Date(),+ codeExpiresAt: new Date(Date.now() + ONE_YEAR_MS)+ });++ // ---- Infisical: SCIM token (scim_tokens row + JWT signed with AUTH_SECRET, mirrors scim-service) ----+ // Regenerated each run; the Authentik SCIM provider is re-PATCHed with it below so the two never+ // drift (e.g. after an Infisical DB reset that leaves Authentik holding a now-dangling token).+ await db(TableName.ScimToken).where({ orgId: org.id }).del();+ const [scimTokenRow] = await db(TableName.ScimToken)+ .insert({ orgId: org.id, description: "authentik dev SCIM", ttlDays: 365 })+ .returning("*");+ const scimToken = crypto+ .jwt()+ .sign({ scimTokenId: scimTokenRow.id, authTokenType: AuthTokenType.SCIM_TOKEN }, authSecret);++ // ---- Authentik: reachability ----+ const reachable = await fetch(`${AK}/core/users/?username=akadmin`, { headers: akHeaders }).catch(() => null);+ if (!reachable || !reachable.ok) {+ logger.error(`Authentik not reachable/authorized at ${AK} (is \`make up-dev-saml\` running?).`);+ process.exitCode = 1;+ return;+ }++ // ---- Authentik: prerequisite ids (looked up by name/slug, not hardcoded) ----+ const authFlow = await akFindPk(`/flows/instances/?slug=default-provider-authorization-implicit-consent`);+ const invalidationFlow = await akFindPk(`/flows/instances/?slug=default-provider-invalidation-flow`);+ const keypairPk = await akFindPk(`/crypto/certificatekeypairs/?search=${encodeURIComponent("Self-signed")}`);++ // Custom SAML attribute mappings emitting the exact attribute names Infisical reads (`email`,+ // `firstName`, `lastName`); Authentik's defaults use different names (emailaddress, name, ...) and+ // have no first/last-name mapping (it stores only a full `name`, which we split).+ const emailMapping = await ensureSamlMapping("Infisical: email", "email", "return request.user.email");+ const firstNameMapping = await ensureSamlMapping(+ "Infisical: firstName",+ "firstName",+ 'return (request.user.name or request.user.username).split(" ")[0]'+ );+ const lastNameMapping = await ensureSamlMapping(+ "Infisical: lastName",+ "lastName",+ 'return " ".join((request.user.name or "").split(" ")[1:])'+ );++ // ---- Authentik: test users + group (SCIM provider syncs only this group) ----+ const userPks: (string | number)[] = [];+ for (const u of TEST_USERS) {+ // eslint-disable-next-line no-await-in-loop+ let pk = await akFindPk(`/core/users/?username=${encodeURIComponent(u.username)}`);+ if (!pk) {+ // eslint-disable-next-line no-await-in-loop+ const created = await akSend("POST", `/core/users/`, {+ username: u.username,+ name: u.name,+ email: u.email,+ is_active: true,+ path: "users"+ });+ pk = created.pk;+ }+ // eslint-disable-next-line no-await-in-loop+ await akSend("POST", `/core/users/${pk}/set_password/`, { password: PASSWORD });+ userPks.push(pk);+ }++ let groupPk = await akFindPk(`/core/groups/?name=${encodeURIComponent(GROUP_NAME)}`);+ if (!groupPk) {+ const g = await akSend("POST", `/core/groups/`, { name: GROUP_NAME, users: userPks });+ groupPk = g.pk;+ } else {+ await akSend("PATCH", `/core/groups/${groupPk}/`, { users: userPks });+ }++ // ---- Authentik: SAML provider (ACS -> Infisical, NameID = email) ----+ const samlBody = {+ name: "infisical-saml",+ authorization_flow: authFlow,+ invalidation_flow: invalidationFlow,+ acs_url: `${SITE_URL}/api/v1/sso/saml2/${SAML_CONFIG_ID}`,+ // node-saml validates the assertion audience against SITE_URL (the SP entityID / Infisical+ // `issuer`). Infisical only expects the `spn:${issuer}` variant when its spInitiated RelayState+ // reaches the ACS; Authentik doesn't carry it through, so the default SITE_URL audience applies.+ audience: SITE_URL,+ issuer: SAML_ENTRY_POINT,+ sp_binding: "post",+ signing_kp: keypairPk,+ sign_assertion: true,+ sign_response: true,+ name_id_mapping: emailMapping,+ property_mappings: [emailMapping, firstNameMapping, lastNameMapping]+ };+ let samlProviderPk = await akFindPk(`/providers/saml/?name=infisical-saml`);+ if (samlProviderPk) {+ await akSend("PATCH", `/providers/saml/${samlProviderPk}/`, samlBody);+ } else {+ samlProviderPk = (await akSend("POST", `/providers/saml/`, samlBody)).pk;+ }++ // ---- Authentik: read the SAML signing cert (for the Infisical SAML config) ----+ const certRes = await fetch(`${AK}/crypto/certificatekeypairs/${keypairPk}/view_certificate/`, {+ headers: akHeaders+ });+ if (!certRes.ok) throw new Error(`read cert -> ${certRes.status} ${await certRes.text()}`);+ const idpCert = ((await certRes.json()) as { data: string }).data;++ // ---- Infisical: active SAML config (entryPoint/issuer/cert KMS-encrypted; unblocks SCIM) ----+ const { encryptor } = await kmsService.createCipherPairWithDataKey(+ { type: KmsDataKey.Organization, orgId: org.id },+ db+ );+ await db(TableName.SamlConfig).where({ orgId: org.id }).del();+ await db(TableName.SamlConfig).insert({+ // @ts-expect-error id is normally auto-generated; we pin it so it matches the Authentik ACS path+ id: SAML_CONFIG_ID,+ orgId: org.id,+ authProvider: SamlProviders.KEYCLOAK_SAML,+ isActive: true,+ encryptedSamlEntryPoint: encryptor({ plainText: Buffer.from(SAML_ENTRY_POINT) }).cipherTextBlob,+ encryptedSamlIssuer: encryptor({ plainText: Buffer.from(SITE_URL) }).cipherTextBlob,+ encryptedSamlCertificate: encryptor({ plainText: Buffer.from(idpCert) }).cipherTextBlob+ });++ // ---- Authentik: SCIM provider -> Infisical (users + groups; service accounts excluded) ----+ const scimUserMapping = await akFindPk(+ `/propertymappings/provider/scim/?search=${encodeURIComponent("default SCIM Mapping: User")}`+ );+ const scimGroupMapping = await akFindPk(+ `/propertymappings/provider/scim/?search=${encodeURIComponent("default SCIM Mapping: Group")}`+ );+ const scimBody = {+ name: "infisical-scim",+ url: INFISICAL_SCIM_URL,+ token: scimToken,+ exclude_users_service_account: true,+ property_mappings: scimUserMapping ? [scimUserMapping] : [],+ property_mappings_group: scimGroupMapping ? [scimGroupMapping] : []+ };+ // Recreate the provider each run. Authentik stores per-object "connections" (the remote SCIM id of+ // each provisioned user/group); after an Infisical DB reset those point at rows that no longer+ // exist, so it would PUT to dead ids and provision nothing. Deleting + recreating clears them. The+ // create tolerates "provider with this name already exists" (a concurrent run or residual provider)+ // by deleting again and retrying once.+ const deleteScimProvider = async () => {+ const pk = await akFindPk(`/providers/scim/?name=infisical-scim`);+ if (pk) await fetch(`${AK}/providers/scim/${pk}/`, { method: "DELETE", headers: akHeaders });+ };+ await deleteScimProvider();+ const createScimProvider = async (): Promise<string | number> => {+ try {+ return (await akSend("POST", `/providers/scim/`, scimBody)).pk;+ } catch {+ await deleteScimProvider();+ return (await akSend("POST", `/providers/scim/`, scimBody)).pk;+ }+ };+ const scimProviderPk = await createScimProvider();++ // ---- Authentik: application binding SAML (primary) + SCIM (backchannel) ----+ const appBody = {+ name: "Infisical",+ slug: APP_SLUG,+ provider: samlProviderPk,+ backchannel_providers: [scimProviderPk]+ };+ if (await akFindPk(`/core/applications/?slug=${APP_SLUG}`)) {+ await akSend("PATCH", `/core/applications/${APP_SLUG}/`, appBody);+ } else {+ await akSend("POST", `/core/applications/`, appBody);+ }++ // Wait for the Infisical backend HTTP server to be reachable (it may still be booting after+ // `make up-dev-saml`, or mid hot-reload in dev) so Authentik's SCIM sync doesn't hit a refused+ // connection and silently provision nothing.+ const healthUrl = `${INFISICAL_SCIM_URL.replace(/\/api\/v1\/scim$/, "")}/api/status`;+ let backendUp = false;+ for (let i = 0; i < 30 && !backendUp; i += 1) {+ // eslint-disable-next-line no-await-in-loop+ backendUp = await fetch(healthUrl)+ .then((r) => r.ok)+ .catch(() => false);+ if (!backendUp) {+ // eslint-disable-next-line no-await-in-loop+ await new Promise((resolve) => {+ setTimeout(resolve, 1000);+ });+ }+ }+ if (!backendUp) logger.warn(`Infisical backend not reachable at ${healthUrl}; SCIM sync may not provision.`);++ // ---- Provision + verify, with retries. Touch each test user to fire Authentik's per-object SCIM+ // sync (the user + their groups, i.e. infisical-saml). The sync is async, so poll Infisical and+ // re-touch for a few rounds: a transient miss (backend mid-restart, etc.) self-heals instead of+ // silently provisioning nothing. Per-object sync also keeps it scoped (no full-sync built-in-group+ // noise); the SCIM provider stays linked to the app as its backchannel provider. ----+ const expectedEmails = TEST_USERS.map((u) => u.email);+ let usersOk = 0;+ let groupMembers = 0;+ for (+ let round = 0;+ round < 8 && !(usersOk >= expectedEmails.length && groupMembers >= TEST_USERS.length);+ round += 1+ ) {+ // A changing attribute guarantees a save (hence a direct sync) each round. Touch the users so+ // they provision, and the group so it provisions with its members (the group re-syncs across+ // rounds until the users it references exist in Infisical).+ // eslint-disable-next-line no-await-in-loop+ await Promise.all([+ ...userPks.map((pk) => akSend("PATCH", `/core/users/${pk}/`, { attributes: { infisicalResync: round } })),+ akSend("PATCH", `/core/groups/${groupPk}/`, { attributes: { infisicalResync: round } })+ ]);+ // eslint-disable-next-line no-await-in-loop+ await new Promise((resolve) => {+ setTimeout(resolve, 3000);+ });+ // eslint-disable-next-line no-await-in-loop+ usersOk = (await db(TableName.Users).whereIn("email", expectedEmails).select("id")).length;+ // eslint-disable-next-line no-await-in-loop+ const grp = await db(TableName.Groups).where({ orgId: org.id, name: GROUP_NAME }).first();+ groupMembers = grp+ ? // eslint-disable-next-line no-await-in-loop+ Number((await db(TableName.UserGroupMembership).where({ groupId: grp.id }).count())[0].count)+ : 0;+ }+ if (usersOk >= expectedEmails.length && groupMembers >= TEST_USERS.length) {+ logger.info(`SCIM provisioning confirmed (${usersOk} users + ${GROUP_NAME} with ${groupMembers} members)`);+ } else {+ logger.warn(+ `SCIM provisioning incomplete (users ${usersOk}/${expectedEmails.length}, ${GROUP_NAME} members ${groupMembers}); re-run`+ );+ }++ logger.info(+ `SAML/SCIM seeded [org=${org.slug}]: admin '${ADMIN_EMAIL}', verified '${DOMAIN}', SAML entryPoint ${SAML_ENTRY_POINT}, SCIM -> ${INFISICAL_SCIM_URL}; provisioning ${TEST_USERS.map(+ (u) => u.email+ ).join(", ")}`+ );+ } finally {+ await db.destroy();+ }+};++main().catch((err) => {+ console.error(err);+ process.exit(1);+});diff --git a/backend/src/db/seed-sso-shared.ts b/backend/src/db/seed-sso-shared.tsnew file mode 100644index 0000000000..b319c4791b--- /dev/null+++ b/backend/src/db/seed-sso-shared.ts@@ -0,0 +1,135 @@+// Shared helpers for the standalone SSO dev seeds: SRP key generation and login-capable+// admin-user + org-membership creation. Used by seed-saml.ts (seed-oidc/seed-ldap still inline+// their own copies; converge them here when convenient). See sso.md.+import argon2, { argon2id } from "argon2";+import jsrp from "jsrp";+import { Knex } from "knex";++import { crypto, SymmetricKeySize } from "@app/lib/crypto/cryptography";+import { AuthMethod } from "@app/services/auth/auth-type";++import { AccessScope, OrgMembershipRole, OrgMembershipStatus, TableName } from "./schemas";++// Parameterized variant of seed-data#generateUserSrpKeys; the SRP verifier is bound to the+// username (the email here), so it can't be shared with the hardcoded seed user.+export const generateUserSrpKeys = async (email: string, password: string) => {+ const { publicKey, privateKey } = await crypto.encryption().asymmetric().generateKeyPair();++ // eslint-disable-next-line+ const client = new jsrp.client();+ await new Promise((resolve) => {+ client.init({ username: email, password }, () => resolve(null));+ });+ const { salt, verifier } = await new Promise<{ salt: string; verifier: string }>((resolve, reject) => {+ client.createVerifier((err, res) => (err ? reject(err) : resolve(res)));+ });++ const derivedKey = await argon2.hash(password, {+ salt: Buffer.from(salt),+ memoryCost: 65536,+ timeCost: 3,+ parallelism: 1,+ hashLength: 32,+ type: argon2id,+ raw: true+ });+ if (!derivedKey) throw new Error("Failed to derive key from password");++ const key = crypto.randomBytes(32);+ const {+ ciphertext: encryptedPrivateKey,+ iv: encryptedPrivateKeyIV,+ tag: encryptedPrivateKeyTag+ } = crypto.encryption().symmetric().encrypt({ plaintext: privateKey, key, keySize: SymmetricKeySize.Bits128 });+ const {+ ciphertext: protectedKey,+ iv: protectedKeyIV,+ tag: protectedKeyTag+ } = crypto+ .encryption()+ .symmetric()+ .encrypt({ plaintext: key.toString("hex"), key: derivedKey, keySize: SymmetricKeySize.Bits128 });++ return {+ protectedKey,+ protectedKeyIV,+ protectedKeyTag,+ publicKey,+ encryptedPrivateKey,+ encryptedPrivateKeyIV,+ encryptedPrivateKeyTag,+ salt,+ verifier+ };+};++type TSeedAdminUserDTO = {+ email: string;+ password: string;+ firstName: string;+ lastName: string;+ superAdmin: boolean;+ orgId: string;+};++// Creates a login-capable user (if missing) and ensures an org Admin membership.+export const seedAdminUser = async (+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ db: Knex<any, unknown[]>,+ { email, password, firstName, lastName, superAdmin, orgId }: TSeedAdminUserDTO+) => {+ let user = await db(TableName.Users).where({ email }).first();+ if (!user) {+ [user] = await db(TableName.Users)+ .insert({+ username: email,+ email,+ superAdmin,+ firstName,+ lastName,+ authMethods: [AuthMethod.EMAIL],+ isAccepted: true,+ isEmailVerified: true,+ isMfaEnabled: false,+ mfaMethods: null,+ devices: null+ })+ .returning("*");++ const hashedPassword = await crypto.hashing().createHash(password, 10);+ await db(TableName.Users).where({ id: user.id }).update({ hashedPassword });++ const k = await generateUserSrpKeys(email, password);+ await db(TableName.UserEncryptionKey).insert({+ encryptionVersion: 2,+ protectedKey: k.protectedKey,+ protectedKeyIV: k.protectedKeyIV,+ protectedKeyTag: k.protectedKeyTag,+ publicKey: k.publicKey,+ encryptedPrivateKey: k.encryptedPrivateKey,+ iv: k.encryptedPrivateKeyIV,+ tag: k.encryptedPrivateKeyTag,+ salt: k.salt,+ verifier: k.verifier,+ userId: user.id+ });+ }++ const existing = await db(TableName.Membership)+ .where({ scope: AccessScope.Organization, scopeOrgId: orgId, actorUserId: user.id })+ .first();+ if (!existing) {+ const [membership] = await db(TableName.Membership)+ .insert({+ scope: AccessScope.Organization,+ scopeOrgId: orgId,+ actorUserId: user.id,+ isActive: true,+ status: OrgMembershipStatus.Accepted+ })+ .returning("*");+ await db(TableName.MembershipRole).insert({ membershipId: membership.id, role: OrgMembershipRole.Admin });+ }++ return user;+};diff --git a/backend/src/ee/routes/v1/scim-router.ts b/backend/src/ee/routes/v1/scim-router.tsindex b1d3d19f16..32e67833bf 100644--- a/backend/src/ee/routes/v1/scim-router.ts+++ b/backend/src/ee/routes/v1/scim-router.ts@@ -367,7 +367,8 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {orgMembershipId: z.string().trim()}),body: z.object({- schemas: z.array(z.string()),+ // Optional: unused here (only Operations is read), and some IdPs (e.g. Authentik) omit it.+ schemas: z.array(z.string()).optional(),Operations: z.array(z.union([z.object({@@ -414,7 +415,8 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {.array(z.object({value: z.string(),- display: z.string()+ // Optional per SCIM (RFC 7643 §4.2) and unused here; some IdPs (e.g. Authentik) omit it.+ display: z.string().optional()})).optional()@@ -511,7 +513,8 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {members: z.array(z.object({value: z.string(),- display: z.string()+ // Optional per SCIM (RFC 7643 §4.2) and unused here; some IdPs (e.g. Authentik) omit it.+ display: z.string().optional()}))}),@@ -539,7 +542,8 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {groupId: z.string().trim()}),body: z.object({- schemas: z.array(z.string()),+ // Optional: unused here (only Operations is read), and some IdPs (e.g. Authentik) omit it.+ schemas: z.array(z.string()).optional(),Operations: z.array(z.union([z.object({diff --git a/backend/src/ee/services/scim/scim-types.ts b/backend/src/ee/services/scim/scim-types.tsindex 48e7f3fbbc..c8dec0b6d1 100644--- a/backend/src/ee/services/scim/scim-types.ts+++ b/backend/src/ee/services/scim/scim-types.ts@@ -105,9 +105,9 @@ export type TCreateScimGroupDTO = {displayName: string;orgId: string;members?: {- // TODO: account for members with value and display (is this optional?)value: string;- display: string;+ // Optional per SCIM (RFC 7643 §4.2); some IdPs (e.g. Authentik) omit it.+ display?: string;}[];};@@ -123,7 +123,8 @@ export type TUpdateScimGroupNamePutDTO = {displayName: string;members: {value: string;- display: string;+ // Optional per SCIM (RFC 7643 §4.2); some IdPs (e.g. Authentik) omit it.+ display?: string;}[];};diff --git a/docker-compose.dev.yml b/docker-compose.dev.ymlindex 72d76b4dc0..f7360adda4 100644--- a/docker-compose.dev.yml+++ b/docker-compose.dev.yml@@ -227,11 +227,13 @@ services:openldap:# note: more advanced configuration is available+ # Starts empty (base dc=ldap,dc=com + admin only). Seed test users/groups with+ # `make seed-dev-ldap` once it is up. See sso.md.image: osixia/openldap:1.5.0restart: alwaysenvironment:- LDAP_ORGANISATION: Acme- LDAP_DOMAIN: acme.com+ LDAP_ORGANISATION: LDAP+ LDAP_DOMAIN: ldap.comLDAP_ADMIN_PASSWORD: adminports:- 389:389@@ -242,7 +244,7 @@ services:profiles: [ldap]phpldapadmin:- # username: cn=admin,dc=acme,dc=com, pass is admin+ # username: cn=admin,dc=ldap,dc=com, pass is adminimage: osixia/phpldapadmin:latestrestart: alwaysenvironment:@@ -255,15 +257,50 @@ services:profiles: [ldap]keycloak:+ # Admin console: http://localhost:8088 (admin / admin).+ # On boot it imports the pre-seeded `infisical` realm (client `infisical-dev`,+ # users jdoe/asmith) from the mounted realm file. The container has no volume,+ # so the realm is re-imported fresh on every start. See sso.md.image: quay.io/keycloak/keycloak:26.1.0restart: alwaysenvironment:- KC_BOOTSTRAP_ADMIN_PASSWORD=admin- KC_BOOTSTRAP_ADMIN_USERNAME=admin- command: start-dev+ # Pin the browser-facing (frontend) URL so the OIDC issuer and authorization endpoint are+ # always http://localhost:8088, while backchannel calls (discovery/token/jwks) use whatever+ # URL the caller connected with. The backend therefore reaches Keycloak over the internal+ # compose network (keycloak:8080) yet the browser is sent to localhost:8088, so no+ # keycloak.local /etc/hosts entry is needed. See sso.md.+ - KC_HOSTNAME=http://localhost:8088+ - KC_HOSTNAME_BACKCHANNEL_DYNAMIC=true+ command: start-dev --import-realmports:- 8088:8080- profiles: [sso]+ volumes:+ - ./docker/keycloak/realm-infisical.json:/opt/keycloak/data/import/realm-infisical.json:ro+ profiles: [oidc]++ keycloak-config:+ # Dev-only one-shot: Keycloak's built-in `master` realm (the admin console) defaults to+ # sslRequired=external, which blocks http://localhost:8088 on Docker Desktop because the+ # container sees published-port traffic as a non-local client IP ("HTTPS required" page).+ # The realm import can't fix this (master already exists, so the bootstrap import skips it),+ # so we flip it with kcadm once Keycloak is up. The imported `infisical` realm is already+ # sslRequired=none, so the OIDC login flow itself is unaffected. See sso.md.+ image: quay.io/keycloak/keycloak:26.1.0+ depends_on:+ - keycloak+ restart: "no"+ entrypoint: ["bash", "-c"]+ command:+ - |+ until /opt/keycloak/bin/kcadm.sh config credentials \+ --server http://keycloak:8080 --realm master --user admin --password admin >/dev/null 2>&1; do+ echo "waiting for keycloak..."; sleep 3;+ done+ /opt/keycloak/bin/kcadm.sh update realms/master -s sslRequired=NONE \+ && echo "master realm sslRequired=NONE (dev only)"+ profiles: [oidc]pingfederate:# Requires free Ping Identity DevOps credentials — register at@@ -321,6 +358,66 @@ services:- samba_etc:/etc/samba/externalprofiles: [ad]+ # Authentik: open-source IdP for SAML + real (non-mock) SCIM provisioning. Admin UI at+ # http://localhost:9100 (akadmin / password123!), API token `authentik-dev-bootstrap-token`.+ # Has its own Postgres and reuses the dev Redis (DB 1). Configure via blueprints or its API.+ # See sso.md.+ authentik-postgres:+ image: postgres:16-alpine+ container_name: infisical-dev-authentik-postgres+ restart: unless-stopped+ environment:+ POSTGRES_DB: authentik+ POSTGRES_USER: authentik+ POSTGRES_PASSWORD: authentik+ volumes:+ - authentik_postgres:/var/lib/postgresql/data+ profiles: [saml]++ authentik-server:+ image: ghcr.io/goauthentik/server:2026.2.2+ container_name: infisical-dev-authentik-server+ restart: unless-stopped+ command: server+ environment:+ AUTHENTIK_SECRET_KEY: insecure-dev-only-key-do-not-use-in-prod-0000000000+ AUTHENTIK_POSTGRESQL__HOST: authentik-postgres+ AUTHENTIK_POSTGRESQL__NAME: authentik+ AUTHENTIK_POSTGRESQL__USER: authentik+ AUTHENTIK_POSTGRESQL__PASSWORD: authentik+ AUTHENTIK_REDIS__HOST: redis+ AUTHENTIK_REDIS__DB: "1"+ AUTHENTIK_BOOTSTRAP_PASSWORD: password123!+ AUTHENTIK_BOOTSTRAP_TOKEN: authentik-dev-bootstrap-token+ AUTHENTIK_BOOTSTRAP_EMAIL: [email protected]+ ports:+ - 9100:9000+ depends_on:+ - authentik-postgres+ - redis+ profiles: [saml]++ authentik-worker:+ image: ghcr.io/goauthentik/server:2026.2.2+ container_name: infisical-dev-authentik-worker+ restart: unless-stopped+ command: worker+ environment:+ AUTHENTIK_SECRET_KEY: insecure-dev-only-key-do-not-use-in-prod-0000000000+ AUTHENTIK_POSTGRESQL__HOST: authentik-postgres+ AUTHENTIK_POSTGRESQL__NAME: authentik+ AUTHENTIK_POSTGRESQL__USER: authentik+ AUTHENTIK_POSTGRESQL__PASSWORD: authentik+ AUTHENTIK_REDIS__HOST: redis+ AUTHENTIK_REDIS__DB: "1"+ AUTHENTIK_BOOTSTRAP_PASSWORD: password123!+ AUTHENTIK_BOOTSTRAP_TOKEN: authentik-dev-bootstrap-token+ AUTHENTIK_BOOTSTRAP_EMAIL: [email protected]+ depends_on:+ - authentik-postgres+ - redis+ profiles: [saml]+volumes:postgres-data:driver: local@@ -338,3 +435,5 @@ volumes:grafana_storage:softhsm_tokens:driver: local+ authentik_postgres:+ driver: localdiff --git a/docker/keycloak/realm-infisical.json b/docker/keycloak/realm-infisical.jsonnew file mode 100644index 0000000000..221570f0e1--- /dev/null+++ b/docker/keycloak/realm-infisical.json@@ -0,0 +1,74 @@+{+ "realm": "infisical",+ "enabled": true,+ "sslRequired": "none",+ "registrationAllowed": false,+ "loginWithEmailAllowed": true,+ "duplicateEmailsAllowed": false,+ "clients": [+ {+ "clientId": "infisical-dev",+ "name": "Infisical (dev)",+ "description": "Pre-seeded OIDC client for local Infisical SSO testing. See sso.md.",+ "enabled": true,+ "protocol": "openid-connect",+ "publicClient": false,+ "clientAuthenticatorType": "client-secret",+ "secret": "infisical-dev-client-secret",+ "standardFlowEnabled": true,+ "directAccessGrantsEnabled": true,+ "redirectUris": [+ "http://localhost:8080/api/v1/sso/oidc/callback",+ "http://localhost:8080/*"+ ],+ "webOrigins": ["http://localhost:8080"]+ }+ ],+ "users": [+ {+ "username": "john",+ "email": "[email protected]",+ "firstName": "John",+ "lastName": "Doe",+ "enabled": true,+ "emailVerified": true,+ "credentials": [+ {+ "type": "password",+ "value": "password123!",+ "temporary": false+ }+ ]+ },+ {+ "username": "alice",+ "email": "[email protected]",+ "firstName": "Alice",+ "lastName": "Smith",+ "enabled": true,+ "emailVerified": true,+ "credentials": [+ {+ "type": "password",+ "value": "password123!",+ "temporary": false+ }+ ]+ },+ {+ "username": "admin",+ "email": "[email protected]",+ "firstName": "OIDC",+ "lastName": "Admin",+ "enabled": true,+ "emailVerified": true,+ "credentials": [+ {+ "type": "password",+ "value": "password123!",+ "temporary": false+ }+ ]+ }+ ]+}diff --git a/docker/openldap/bootstrap.ldif b/docker/openldap/bootstrap.ldifnew file mode 100644index 0000000000..5b66a8d74a--- /dev/null+++ b/docker/openldap/bootstrap.ldif@@ -0,0 +1,67 @@+# Seed data for the local OpenLDAP dev container (osixia/openldap).+# Base DN dc=ldap,dc=com and cn=admin,dc=ldap,dc=com are created automatically+# by the image from LDAP_DOMAIN/LDAP_ADMIN_PASSWORD. Do not redefine them here.+#+# Apply with `make seed-dev-ldap` after the container is up (it pipes this file to+# ldapadd -c, so it is safe to re-run). See sso.md.+#+# Test users (uid / password): john / password123!, alice / password123!, admin / password123!+# Emails are @ldap.com so they don't collide with the OIDC users (@oidc.com). Sign in by uid+# (e.g. `john`) or by email (e.g. `[email protected]`).++dn: ou=people,dc=ldap,dc=com+objectClass: organizationalUnit+ou: people++dn: ou=groups,dc=ldap,dc=com+objectClass: organizationalUnit+ou: groups++dn: uid=john,ou=people,dc=ldap,dc=com+objectClass: inetOrgPerson+objectClass: posixAccount+objectClass: shadowAccount+uid: john+cn: John Doe+sn: Doe+givenName: John+mail: [email protected]+uidNumber: 10000+gidNumber: 10000+homeDirectory: /home/john+userPassword: password123!++dn: uid=alice,ou=people,dc=ldap,dc=com+objectClass: inetOrgPerson+objectClass: posixAccount+objectClass: shadowAccount+uid: alice+cn: Alice Smith+sn: Smith+givenName: Alice+mail: [email protected]+uidNumber: 10001+gidNumber: 10001+homeDirectory: /home/alice+userPassword: password123!++dn: uid=admin,ou=people,dc=ldap,dc=com+objectClass: inetOrgPerson+objectClass: posixAccount+objectClass: shadowAccount+uid: admin+cn: LDAP Admin+sn: Admin+givenName: LDAP+mail: [email protected]+uidNumber: 10002+gidNumber: 10002+homeDirectory: /home/admin+userPassword: password123!++dn: cn=infisical-users,ou=groups,dc=ldap,dc=com+objectClass: groupOfNames+cn: infisical-users+member: uid=john,ou=people,dc=ldap,dc=com+member: uid=alice,ou=people,dc=ldap,dc=com+member: uid=admin,ou=people,dc=ldap,dc=comdiff --git a/sso.md b/sso.mdnew file mode 100644index 0000000000..3d570f9660--- /dev/null+++ b/sso.md@@ -0,0 +1,384 @@+# Local SSO Development (OIDC, SAML, SCIM, LDAP)++This guide is for **contributors** who want to test Infisical's SSO flows against an+identity provider running locally in Docker. It covers the dev containers that ship+with `docker-compose.dev.yml`, their default credentials, what to enter in Infisical,+and how everything is pre-seeded so you can log in within a couple of minutes.++For the **end-user / production** setup of each provider, see the product docs instead:+[`docs/documentation/platform/sso`](docs/documentation/platform/sso) and+[`docs/documentation/platform/ldap`](docs/documentation/platform/ldap).++## Quick reference++| Provider | Bring up | Seed | Provider URL | Seeded users (password `password123!`) |+| --- | --- | --- | --- | --- |+| Keycloak (OIDC) | `make up-dev-oidc` | realm auto-imports on boot; configure Infisical with `make seed-dev-oidc` | http://localhost:8088 (admin / admin) | [email protected], [email protected], [email protected] |+| OpenLDAP (LDAP) | `make up-dev-ldap` | `make seed-dev-ldap` | http://localhost:6433 (phpLDAPadmin) | [email protected], [email protected], [email protected] |+| Authentik (SAML + SCIM) | `make up-dev-saml` | `make seed-dev-saml` | http://localhost:9100 (akadmin / password123!) | [email protected] (SCIM), [email protected] (SCIM), [email protected] |++All compose profiles also start the default stack (Postgres, Redis, backend, frontend,+nginx), so Infisical is available at **http://localhost:8080**.++## Prerequisites (do this once)++1. **Base stack works.** You can already run `make up-dev` and reach Infisical at+ http://localhost:8080. Create a instance admin account.++2. **`AUTH_SECRET` and `SITE_URL` are set.** `.env.example` already ships a sample+ `AUTH_SECRET`. For SSO you must also make sure `SITE_URL` matches the URL you open+ Infisical at, because the OIDC callback is built as `{SITE_URL}/api/v1/sso/oidc/callback`.+ For the standard dev stack set:++ ```bash+ SITE_URL=http://localhost:8080+ ```+++3. **Unlock the EE features** (next section). Without this every SSO config request returns+ `Upgrade plan to ...`.++## Unlocking SSO (EE feature gating)++OIDC, SAML, LDAP, SCIM, and groups are paid features. On a plain local instance there is no+license, so `getDefaultOnPremFeatures()` in+[`backend/src/ee/services/license/license-fns.ts`](backend/src/ee/services/license/license-fns.ts)+returns `oidcSSO: false` and `ldap: false`, and the config endpoints reject everything.+Pick one of:++- **Internal devs (recommended):** set a real or offline `LICENSE_KEY` in `backend/.env`+ (ask the team for a dev license). This mirrors a real enterprise instance.+- **OSS / no license:** temporarily flip the flags in `getDefaultOnPremFeatures()` to `true`+ for the features you are testing:++ ```ts+ oidcSSO: true,+ samlSSO: true,+ ldap: true,+ scim: true,+ groups: true,+ ```++ This is a **local-only change, do not commit it.**++Restart the backend after either change so the license service re-reads the plan.++> In case you lock yourself out after enforcing SSO, an org admin can always recover via the+> admin login portal at http://localhost:8080/login/admin.++---++## OIDC via Keycloak++```bash+make up-dev-oidc+```++Keycloak boots with the pre-seeded **`infisical`** realm imported from+[`docker/keycloak/realm-infisical.json`](docker/keycloak/realm-infisical.json): one OIDC+client and two users. The container has no volume, so the realm is re-imported fresh on+every start. To reload edits to the realm file, recreate it with `docker compose -f docker-compose.dev.yml --profile oidc up -d --force-recreate keycloak keycloak-config`.++A one-shot `keycloak-config` sidecar runs alongside it and sets the built-in `master` realm to+`sslRequired=none`, so the admin console works over plain HTTP. Without this, Keycloak returns+**"HTTPS required"** on Docker Desktop (the container sees a non-local client IP for the+`master` realm, whose default is `external`). The `infisical` realm already ships with+`sslRequired: none` in its realm file, so the login flow is unaffected either way.++### Default values++| Setting | Value |+| --- | --- |+| Admin console | http://localhost:8088 |+| Admin user / password | `admin` / `admin` |+| Realm | `infisical` |+| Client ID | `infisical-dev` |+| Client secret | `infisical-dev-client-secret` |+| JWT signature algorithm | `RS256` |+| Redirect URI (registered) | `http://localhost:8080/api/v1/sso/oidc/callback` |+| Seeded users | `[email protected]`, `[email protected]`, `[email protected]` (password `password123!`) |++### Discovery URL (how the networking works)++Keycloak is configured so the **issuer** and the **browser-facing** endpoints (authorization,+logout) are always `http://localhost:8088`, while the **backchannel** calls the backend makes+(discovery, token, JWKS) use whatever URL it connected with. That split, set via+`KC_HOSTNAME=http://localhost:8088` + `KC_HOSTNAME_BACKCHANNEL_DYNAMIC=true` in+`docker-compose.dev.yml`, lets the backend and the browser share one issuer with **no `/etc/hosts`+edit**:++- **Backend in Docker (the default for `make up-dev-oidc`):** the backend fetches discovery over+ the internal compose network, and the browser is redirected to `localhost:8088`. Discovery URL:++ ```+ http://keycloak:8080/realms/infisical/.well-known/openid-configuration+ ```++### Configure in Infisical++The fast path is to let the seed script do it. With the stack up, run:++```bash+make seed-dev-oidc+```++This bootstraps everything the Infisical side needs: an `[email protected]` admin (password+`password123!`), a **verified** `oidc.com` email domain (required for every SSO login), and+an **active** OIDC config pointing at the discovery URL above (client `infisical-dev`). With no+arguments it bootstraps a dedicated `oidc` org (slug `oidc`), creating it if missing; pass+`ORG_ID=<uuid>` to configure an existing org instead. SSO is still EE-gated, so make sure you have+unlocked the EE features first.++Then test the login two ways:++- **SSO:** open a fresh browser session at http://localhost:8080, choose **Continue with SSO**, and+ authenticate as any seeded Keycloak user (`[email protected]`, `[email protected]`, or+ `[email protected]`), all `password123!`. Signing in as `[email protected]` links to the seeded+ Infisical admin. You can also start the flow directly at+ `http://localhost:8080/api/v1/sso/oidc/login?orgSlug=oidc`.+- **Password:** sign in as the seeded admin `[email protected]` / `password123!` to manage the+ `oidc` org directly.++<details>+<summary>Or configure it by hand in the UI</summary>++1. Log in to http://localhost:8080 as the seeded admin and open the organization's+ **Single Sign-On (SSO)** settings.+2. Connect **OIDC**, choose configuration type **Discovery URL**, and fill in:+ - **Discovery Document URL:** the URL from the section above.+ - **JWT Signature Algorithm:** `RS256`.+ - **Client ID:** `infisical-dev`.+ - **Client Secret:** `infisical-dev-client-secret`.+ - Leave **Allowed Email Domains** empty to accept any seeded user while testing.+3. Verify the org's `oidc.com` domain under the org domain settings, otherwise the login is+ rejected. `make seed-dev-oidc` does this for you.+4. Save, then enable OIDC.+</details>++---++## LDAP via OpenLDAP++```bash+make up-dev-ldap+make seed-dev-ldap # adds OUs, users, and a group+```++`make seed-dev-ldap` does two things: it applies+[`docker/openldap/bootstrap.ldif`](docker/openldap/bootstrap.ldif) (OUs, users, group) to OpenLDAP+with `ldapadd -c`, and it configures the Infisical side, bootstrapping a dedicated `ldap` org with+an `[email protected]` admin (password `password123!`), a verified `ldap.com` domain, and an+**active** LDAP config pointing at OpenLDAP. With no arguments it targets/creates the `ldap` org;+pass `ORG_ID=<uuid>` to configure an existing org instead. SSO is EE-gated, so unlock the EE+features first.++> `ldapadd` only adds entries, it does not update existing ones. If you change a seeded user's+> password in `bootstrap.ldif` after the directory was already seeded, recreate the OpenLDAP volume+> to pick it up: `docker compose -f docker-compose.dev.yml rm -fsv openldap`, then re-run+> `make seed-dev-ldap`.++Browse the directory at http://localhost:6433 (phpLDAPadmin) with login+`cn=admin,dc=ldap,dc=com` / `admin`.++### Sign in++Sign in via LDAP into the `ldap` org as any seeded directory user, all `password123!`, by uid or+email:++- `[email protected]` (uid `admin`), which is also the seeded Infisical admin, so it links to that account+- `john` or `[email protected]` (John Doe)+- `alice` or `[email protected]` (Alice Smith)++The seed's search filter matches uid or mail, so either form works.++### Default values++| Field | Value (backend in Docker) | Value (backend on host) |+| --- | --- | --- |+| LDAP URL | `ldap://openldap:389` | `ldap://localhost:389` |+| Bind DN | `cn=admin,dc=ldap,dc=com` | same |+| Bind password | `admin` | same |+| User search base | `ou=people,dc=ldap,dc=com` | same |+| User search filter | `(\|(uid={{username}})(mail={{username}}))` | same |+| Unique user attribute | `uid` | same |+| Group search base | `ou=groups,dc=ldap,dc=com` | same |+| CA certificate | leave empty (`ldap://` has no TLS) | same |+| Seeded users | `john`, `alice`, `admin` (password `password123!`) | same |+| Seeded group | `infisical-users` | same |++Unlike OIDC, LDAP has no browser redirect, so there is no issuer/hostname problem: the backend+binds to the server directly. Just point `LDAP URL` at wherever the backend can reach OpenLDAP.++<details>+<summary>Or configure it by hand in the UI</summary>++1. In the org **Single Sign-On (SSO)** settings, connect **LDAP** and enter the values above.+2. Use **Test Connection** to confirm the bind works before saving.+3. Verify the org's `ldap.com` domain, otherwise the login is rejected (`make seed-dev-ldap`+ does this for you).+4. Enable LDAP, then log in as `john` / `password123!`.+5. (Optional) Map `cn=infisical-users` to an Infisical group under the LDAP config's group+ mappings to test group sync.+</details>++---++## SAML + SCIM via Authentik++[Authentik](https://goauthentik.io) is a full identity provider with **real** SAML SSO and+**outbound SCIM provisioning**, so unlike a mock IdP you can exercise the whole flow end to end:+SCIM provisions users into Infisical, and SAML logs them in. Both share one `saml` org, because the+two are coupled. The SAML `NameID` must equal the SCIM `userName` (both the user's email), and+Infisical only accepts SCIM provisioning once an SSO config exists for the org.++```bash+make up-dev-saml # default stack + Authentik (server, worker, its own Postgres; ~40s to ready)+make seed-dev-saml # wires both sides and provisions the test users+```++`make seed-dev-saml` does the whole bridge in one shot:++- **Infisical side:** bootstraps a dedicated `saml` org (slug `saml`) with SCIM enabled, an+ `[email protected]` admin (password `password123!`), a **verified** `saml.com` domain, an **active**+ SAML config, and a SCIM token.+- **Authentik side (via its API):** creates the `[email protected]` / `[email protected]` test users in an+ `infisical-saml` group, a **SAML provider** (ACS pointed at Infisical, `NameID` = email), and a+ **SCIM provider** pointed at Infisical's SCIM endpoint, bound together by one `Infisical`+ application.+- **The two secrets that have to cross over** are handled for you: the seed reads Authentik's SAML+ signing certificate into the Infisical SAML config, and writes the Infisical SCIM token into+ Authentik's SCIM provider. It then provisions john/alice via SCIM, each getting a SAML alias keyed+ on their email, so SAML login matches the SCIM-provisioned account.++SSO is EE-gated, so unlock the EE features first. The Authentik admin console is at+**http://localhost:9100** (`akadmin` / `password123!`).++### Sign in (SAML)++Open a fresh browser session at http://localhost:8080, choose **Continue with SSO**, enter the org+slug `saml`, and authenticate at Authentik as a seeded user, all `password123!`:++- `[email protected]` (John Doe)+- `[email protected]` (Alice Smith)++You can also start the flow directly at+`http://localhost:8080/api/v1/sso/redirect/saml2/organizations/saml`. Sign in as the password admin+`[email protected]` / `password123!` to manage the `saml` org directly.++### SCIM provisioning++`make seed-dev-saml` provisions john/alice (as users) and the `infisical-saml` group with those+members into the `saml` org. It touches each test user and the group in Authentik to fire a+per-object SCIM sync, then **polls Infisical and retries** (up to 8 rounds) until they all land, so+an async miss self-heals instead of being fire-and-forget; it logs `SCIM provisioning confirmed` on+success. To add more users, create them in Authentik and add them to `infisical-saml`.+Scoping to these objects also keeps Authentik's built-in groups out of Infisical.++The seed also **recreates** the Authentik SCIM provider on every run. Authentik stores a per-object+"connection" (the remote SCIM id of each provisioned user/group); after an Infisical DB reset those+point at rows that no longer exist, so Authentik would PUT to dead ids and silently provision+nothing. Recreating clears them so objects POST fresh into the current org.++### Default values++| Setting | Value |+| --- | --- |+| Authentik admin | http://localhost:9100 (`akadmin` / `password123!`) |+| Authentik API token (used by the seed) | `authentik-dev-bootstrap-token` |+| Org | `saml` |+| SAML entry point (browser) | `http://localhost:9100/application/saml/infisical/sso/binding/redirect/` |+| SAML ACS (Infisical) | `http://localhost:8080/api/v1/sso/saml2/<configId>` |+| NameID / SCIM userName / alias | the user's email |+| Assertion audience | `http://localhost:8080` (= `SITE_URL`, the Infisical SP `issuer`) |+| SCIM endpoint (Authentik → Infisical) | `http://backend:4000/api/v1/scim` |+| Seeded users | `[email protected]`, `[email protected]` (SCIM), `[email protected]` (password admin) |+| Seeded group | `infisical-saml` (provisioned with members john/alice) |++### How the networking works++Like OIDC, SAML has a browser redirect, so URLs split by audience: the browser is sent to Authentik+at **`localhost:9100`** (the SAML entry point and ACS use host-reachable URLs), while the seed and+Authentik's SCIM sync talk over the compose network (`authentik-server:9000`, `backend:4000`). The+seed uses internal addresses for its own API calls and host addresses for anything the browser+touches. Authentik runs on port `9100` because `9000` is taken by ClickHouse in the dev stack.++---++## Testing without the UI (curl)++Grab a JWT by logging in to http://localhost:8080 and copying the `Authorization: Bearer ...`+header from any API request in your browser's network tab. Then:++```bash+JWT="<paste token>"+ORG_ID="180870b7-f464-4740-8ffe-9d11c9245ea7"+```++**Create the OIDC config:**++```bash+curl -X POST http://localhost:8080/api/v1/sso/oidc/config \+ -H "Authorization: Bearer $JWT" -H "Content-Type: application/json" \+ -d '{+ "organizationId": "'"$ORG_ID"'",+ "configurationType": "discoveryURL",+ "discoveryURL": "http://keycloak:8080/realms/infisical/.well-known/openid-configuration",+ "clientId": "infisical-dev",+ "clientSecret": "infisical-dev-client-secret",+ "jwtSignatureAlgorithm": "RS256",+ "isActive": true+ }'+```++**Create the LDAP config:**++```bash+curl -X POST http://localhost:8080/api/v1/sso/ldap/config \+ -H "Authorization: Bearer $JWT" -H "Content-Type: application/json" \+ -d '{+ "organizationId": "'"$ORG_ID"'",+ "isActive": true,+ "url": "ldap://openldap:389",+ "bindDN": "cn=admin,dc=ldap,dc=com",+ "bindPass": "admin",+ "searchBase": "ou=people,dc=ldap,dc=com",+ "searchFilter": "(uid={{username}})",+ "uniqueUserAttribute": "uid",+ "groupSearchBase": "ou=groups,dc=ldap,dc=com"+ }'+```++**Test an LDAP bind** (the `ldapauth` strategy reads `username`/`password` from the body):++```bash+curl -X POST http://localhost:8080/api/v1/ldap/login \+ -H "Content-Type: application/json" \+ -d '{ "organizationSlug": "ldap", "username": "john", "password": "password123!" }'+```++A `200` with a `nextUrl` means the bind succeeded.++**Start an SP-initiated SAML login** (expect a `302` to Authentik carrying a `SAMLRequest`):++```bash+curl -sI "http://localhost:8080/api/v1/sso/redirect/saml2/organizations/saml" | grep -i location+```++---++## Troubleshooting++| Symptom | Likely cause / fix |+| --- | --- |+| `Upgrade plan to create ... configuration` | EE features not unlocked. See [Unlocking SSO](#unlocking-sso-ee-feature-gating), then restart the backend. |+| OIDC fails with an issuer / `iss` mismatch | The issuer is pinned to `http://localhost:8088` via Keycloak's `KC_HOSTNAME`, so the seeded config shouldn't hit this. If you overrode the discovery URL, keep the backend reaching Keycloak over the compose network (`keycloak:8080`) and leave `KC_HOSTNAME` pointing at the host the browser uses (`localhost:8088`). |+| Redirected to a broken page after Keycloak login | `SITE_URL` does not match the app URL. Set `SITE_URL=http://localhost:8080`. |+| Backend cannot reach the discovery URL | Inside Docker `localhost:8088` is the backend itself. Use the internal compose address `http://keycloak:8080/...` for OIDC discovery (or `ldap://openldap:389` for LDAP). |+| Keycloak admin console (`localhost:8088`) shows "HTTPS required" | The built-in `master` realm defaults to `sslRequired=external`, which Docker Desktop's non-local client IP trips over plain HTTP. The one-shot `keycloak-config` sidecar flips it to `NONE` on every `up`; refresh once it logs `master realm sslRequired=NONE`. (The `infisical` realm is already `none`, so the login flow is unaffected.) |+| Keycloak realm/users missing after a restart | The container is ephemeral; recreate it with `docker compose -f docker-compose.dev.yml --profile oidc up -d --force-recreate keycloak keycloak-config`, or `make down` then `make up-dev-oidc`. |+| LDAP users missing | Run `make seed-dev-ldap` after the container is up (OpenLDAP starts empty). |+| Login rejected: email domain not in the org's accepted domains | The org has no verified domain matching the user's email. `make seed-dev-oidc` verifies `oidc.com` (the `oidc` org), `make seed-dev-ldap` verifies `ldap.com` (the `ldap` org), and `make seed-dev-saml` verifies `saml.com` (the `saml` org); pass `ORG_ID=<org>` to verify a domain for another org. See [Email Domain Verification](docs/documentation/platform/email-domain). |+| SCIM users not appearing in the `saml` org | Re-run `make seed-dev-saml`; it recreates the Authentik SCIM provider so stale per-user connections (e.g. after an Infisical DB reset) don't dead-end on PUTs to ids that no longer exist. Provisioning also needs an active SSO config + verified domain + SCIM enabled, all set by the seed (`Neither SAML or OIDC SSO is configured` means the SAML config is missing). Provisioned users land with `invited` status; the seed polls and retries until it logs `SCIM provisioning confirmed` (if it logs `incomplete`, re-run). |+| SAML login fails with `assertion audience mismatch` | Authentik's SAML provider audience must equal `SITE_URL` (`http://localhost:8080`); the seed sets this. If you changed `SITE_URL`, re-run `make seed-dev-saml` so Authentik's audience and the SAML config agree. |+| Authentik unreachable or `Token invalid/expired` during the seed | Authentik takes ~40s after `make up-dev-saml` to finish bootstrapping (the worker applies blueprints and creates the API token). Wait for http://localhost:9100 to load, then re-run `make seed-dev-saml`. |+| Locked out after enforcing SSO | Recover via http://localhost:8080/login/admin. |