Skip to content

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

improvement(platfor-286): add e2e tests for saml

Tre Dubravacc8ee4beb35e
diff --git a/CLAUDE.md b/CLAUDE.md
index eb93e38674..3934650ace 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -22,6 +22,7 @@ infisical/
├── backend-go/ # Go API server — partial rewrite (see backend-go/CLAUDE.md)
├── frontend/ # React 18 SPA (see frontend/CLAUDE.md)
├── wasm/ # Rust crates compiled to WASM for the frontend (see wasm/<crate>/CLAUDE.md)
+├── e2e/ # External Playwright suite — gates prod deploys against gamma (see e2e/CLAUDE.md)
├── docs/ # Documentation site (Mintlify-based)
├── docker-compose.dev.yml # Local dev (PostgreSQL, Redis, backend, frontend, Nginx)
├── docker-compose.prod.yml # Production deployment stack
@@ -38,6 +39,7 @@ infisical/
- **`frontend/`** — React 18 SPA, Vite 6, TanStack Router + React Query, Tailwind CSS v4. See [`frontend/CLAUDE.md`](frontend/CLAUDE.md) for architecture, patterns, and commands.
- **`wasm/`** — Rust crates that compile to WASM for the frontend. Generated bindings are committed under `frontend/src/lib/<crate>/` so the frontend builds without a Rust toolchain. Each crate has its own `CLAUDE.md` with the rebuild command (e.g. [`wasm/ironrdp-decoder/CLAUDE.md`](wasm/ironrdp-decoder/CLAUDE.md)) — run it after any change to that crate's `src/` or `Cargo.toml` so source and bindings stay in sync.
- **`docs/`** — Product documentation site. Has its own Dockerfile for building. Reference docs for up-to-date feature descriptions and API usage.
+- **`e2e/`** — Playwright suite that runs against a deployed environment (gamma) between deploy and prod promotion. Distinct from `backend/e2e-test/` (in-process Vitest). Failure blocks every prod-deploy job. Covers SCIM + SAML flows (SP-initiated, IdP-initiated, deactivation, response rejection) against a mock IdP we control — see [`e2e/CLAUDE.md`](e2e/CLAUDE.md) for the harness and the one-time gamma bootstrap.
Enterprise features live in `backend/src/ee/` (services and routes), registered before community routes so they can override/extend them.
diff --git a/backend/scripts/seed-gamma-fixtures.ts b/backend/scripts/seed-gamma-fixtures.ts
new file mode 100644
index 0000000000..e82ee50c13
--- /dev/null
+++ b/backend/scripts/seed-gamma-fixtures.ts
@@ -0,0 +1,299 @@
+/* eslint-disable no-console */
+// Idempotent gamma e2e fixtures bootstrap.
+//
+// Creates the e2e org, a long-lived SCIM token row, and the SAML config row
+// pointing at the mock IdP hosted in `preview-environments`. Re-runs are
+// no-ops on row creation; the SCIM JWT is re-derived and printed each run so
+// operators can recapture it without touching the DB.
+//
+// SAML config fields (cert / issuer / entryPoint) are KMS-encrypted using the
+// same org-level data key the runtime SAML service uses, so gamma's
+// `getSaml()` decrypt path sees identical values to anything the admin API
+// would write.
+//
+// SAFETY: refuses to run against anything that looks like prod. Operator must
+// also type the database name interactively to confirm. Do not pipe `yes` into
+// this — that defeats the purpose.
+//
+// Usage (from backend/):
+// DB_CONNECTION_URI=<gamma uri> \
+// ENCRYPTION_KEY=<gamma encryption key> \
+// AUTH_SECRET=<gamma auth secret> \
+// E2E_ORG_NAME="e2e-scim-test" E2E_ORG_SLUG="e2e-scim-test" \
+// npx tsx scripts/seed-gamma-fixtures.ts
+
+import "dotenv/config";
+
+import fs from "node:fs";
+import path from "node:path";
+
+import knexLib from "knex";
+import promptSync from "prompt-sync";
+
+import { initializeHsmModule } from "@app/ee/services/hsm/hsm-fns";
+import { hsmServiceFactory } from "@app/ee/services/hsm/hsm-service";
+import { SamlProviders } from "@app/ee/services/saml-config/saml-config-types";
+import { getConfig, getHsmConfig, initEnvConfig } from "@app/lib/config/env";
+import { crypto } from "@app/lib/crypto/cryptography";
+import { initLogger, logger } from "@app/lib/logger";
+import { internalKmsDALFactory } from "@app/services/kms/internal-kms-dal";
+import { kmskeyDALFactory } from "@app/services/kms/kms-key-dal";
+import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";
+import { kmsServiceFactory } from "@app/services/kms/kms-service";
+import { KmsDataKey } from "@app/services/kms/kms-types";
+import { orgDALFactory } from "@app/services/org/org-dal";
+import { projectDALFactory } from "@app/services/project/project-dal";
+import { superAdminDALFactory } from "@app/services/super-admin/super-admin-dal";
+
+import { TableName } from "../src/db/schemas";
+import { AuthTokenType } from "../src/services/auth/auth-type";
+
+// Mock IdP hosted in preview-environments. The entryPoint is where gamma
+// redirects the browser to start SAML SSO; the issuer matches the IdP's
+// entityID; the cert is committed at e2e/fixtures/idp-cert.pem and the
+// matching private key lives only in CF Secrets (SAML_IDP_PRIVATE_KEY).
+const IDP_ENTRY_POINT = "https://preview-orchestrator.infisical.workers.dev/saml-idp/sso";
+const IDP_ISSUER = "https://preview-orchestrator.infisical.workers.dev/saml-idp";
+const IDP_CERT_PATH = path.resolve(__dirname, "../../e2e/fixtures/idp-cert.pem");
+
+// Email domain the SCIM-provisioned test users live under. SCIM POST rejects
+// any email whose domain isn't a `verified` row in `email_domains` for the
+// org (backend/src/ee/services/email-domain/email-domain-fns.ts:29). Using a
+// `.test` TLD (RFC 2606) avoids any collision with a real verified domain
+// that might already exist for Infisical's primary org.
+const E2E_EMAIL_DOMAIN = "infisical-e2e.test";
+
+const required = (key: string): string => {
+ const value = process.env[key];
+ if (!value) {
+ throw new Error(`${key} must be set`);
+ }
+ return value;
+};
+
+const PROD_PATTERN = /(^|[-_.])(prod|production)([-_.]|$)/i;
+
+const parseDbTarget = (uri: string): { host: string; dbName: string } => {
+ const match = uri.match(/^postgres(?:ql)?:\/\/(?:[^@]+@)?([^:/]+)(?::\d+)?\/([^?]+)/i);
+ if (!match) {
+ throw new Error("DB_CONNECTION_URI is not a parseable postgres:// URI");
+ }
+ return { host: match[1], dbName: match[2] };
+};
+
+const guardAgainstProd = (host: string, dbName: string) => {
+ if ((process.env.INFISICAL_ENV ?? "").toLowerCase() === "prod") {
+ throw new Error("Refusing to run: INFISICAL_ENV=prod");
+ }
+ if (PROD_PATTERN.test(host)) {
+ throw new Error(`Refusing to run: DB host "${host}" looks like prod.`);
+ }
+ if (PROD_PATTERN.test(dbName)) {
+ throw new Error(`Refusing to run: database name "${dbName}" looks like prod.`);
+ }
+
+ const prompt = promptSync({ sigint: true });
+ console.log("");
+ console.log("About to seed e2e fixtures against:");
+ console.log(` host: ${host}`);
+ console.log(` database: ${dbName}`);
+ console.log("");
+ const confirmation = prompt(`Re-type the database name to confirm: `);
+ if (confirmation !== dbName) {
+ throw new Error("Database name confirmation did not match — aborting.");
+ }
+};
+
+const main = async () => {
+ const dbUri = required("DB_CONNECTION_URI");
+ const orgName = process.env.E2E_ORG_NAME ?? "e2e-scim-test";
+ const orgSlug = process.env.E2E_ORG_SLUG ?? "e2e-scim-test";
+ const scimTokenDescription = "e2e-fixture";
+
+ const { host, dbName } = parseDbTarget(dbUri);
+ guardAgainstProd(host, dbName);
+
+ const knex = knexLib({
+ client: "pg",
+ connection: dbUri,
+ pool: { min: 1, max: 2 }
+ });
+
+ // Match the main app: no replicas are configured here, so route everything
+ // through the same connection. KMS service (kms-service.ts) reads via these.
+ knex.primaryNode = () => knex;
+ knex.replicaNode = () => knex;
+
+ initLogger();
+
+ const superAdminDAL = superAdminDALFactory(knex);
+ const kmsRootConfigDAL = kmsRootConfigDALFactory(knex);
+ const hsmConfig = getHsmConfig(logger);
+
+ const hsmModule = initializeHsmModule(hsmConfig);
+ hsmModule.initialize();
+
+ const hsmService = hsmServiceFactory({
+ hsmModule: hsmModule.getModule(),
+ envConfig: hsmConfig
+ });
+ await hsmService.startService();
+ const envConfig = await initEnvConfig(hsmService, kmsRootConfigDAL, superAdminDAL, logger);
+
+ // Wire just enough of the DAL graph for kmsService.createCipherPairWithDataKey
+ // against an organization. projectDAL is required by the factory contract
+ // even though it's only used on the project-scoped path.
+ const kmsDAL = kmskeyDALFactory(knex);
+ const internalKmsDAL = internalKmsDALFactory(knex);
+ const orgDAL = orgDALFactory(knex);
+ const projectDAL = projectDALFactory(knex);
+ const kmsService = kmsServiceFactory({
+ kmsRootConfigDAL,
+ kmsDAL,
+ internalKmsDAL,
+ orgDAL,
+ projectDAL,
+ hsmService,
+ envConfig
+ });
+ // Loads the decrypted root key into the service's in-memory buffer; the
+ // generateKmsKey path called by createCipherPairWithDataKey requires it.
+ // Gamma doesn't use HSM, so we pass an empty status — `null` strategy +
+ // `isHsmConfigured: false` matches the runtime status the main app reports.
+ await kmsService.startService({ rootKmsConfigEncryptionStrategy: null, isHsmConfigured: false });
+
+ let org = await knex(TableName.Organization).where({ slug: orgSlug }).first();
+ if (!org) {
+ [org] = await knex(TableName.Organization)
+ .insert({ name: orgName, slug: orgSlug, customerId: null, scimEnabled: true })
+ .returning("*");
+ console.log(`[seed] created org id=${org.id} slug=${orgSlug}`);
+ } else {
+ if (!org.scimEnabled) {
+ await knex(TableName.Organization).where({ id: org.id }).update({ scimEnabled: true });
+ console.log(`[seed] enabled SCIM on existing org id=${org.id}`);
+ }
+ console.log(`[seed] org exists id=${org.id} slug=${orgSlug}`);
+ }
+
+ let scimToken = await knex(TableName.ScimToken)
+ .where({ orgId: org.id, description: scimTokenDescription })
+ .first();
+ if (!scimToken) {
+ [scimToken] = await knex(TableName.ScimToken)
+ .insert({
+ orgId: org.id,
+ description: scimTokenDescription,
+ ttlDays: 0
+ })
+ .returning("*");
+ console.log(`[seed] created scim token row id=${scimToken.id}`);
+ } else {
+ console.log(`[seed] scim token row exists id=${scimToken.id}`);
+ }
+
+ // SAML config pointing at the mock IdP. The encryptor uses the org's KMS
+ // data key (created lazily on first access), so gamma's runtime SAML
+ // service decrypts these via the same code path.
+ const idpCert = fs.readFileSync(IDP_CERT_PATH, "utf8");
+ const { encryptor } = await kmsService.createCipherPairWithDataKey({
+ type: KmsDataKey.Organization,
+ orgId: org.id
+ });
+ const encryptedEntryPoint = encryptor({ plainText: Buffer.from(IDP_ENTRY_POINT) }).cipherTextBlob;
+ const encryptedIssuer = encryptor({ plainText: Buffer.from(IDP_ISSUER) }).cipherTextBlob;
+ const encryptedCert = encryptor({ plainText: Buffer.from(idpCert) }).cipherTextBlob;
+
+ const existingSamlConfig = await knex(TableName.SamlConfig).where({ orgId: org.id }).first();
+ let samlConfigId: string;
+ if (!existingSamlConfig) {
+ const [samlConfig] = await knex(TableName.SamlConfig)
+ .insert({
+ orgId: org.id,
+ authProvider: SamlProviders.KEYCLOAK_SAML,
+ isActive: true,
+ encryptedSamlEntryPoint: encryptedEntryPoint,
+ encryptedSamlIssuer: encryptedIssuer,
+ encryptedSamlCertificate: encryptedCert,
+ enableGroupSync: false
+ })
+ .returning("*");
+ samlConfigId = samlConfig.id;
+ console.log(`[seed] created saml config row id=${samlConfig.id} (mock idp ${IDP_ISSUER})`);
+ } else {
+ await knex(TableName.SamlConfig).where({ id: existingSamlConfig.id }).update({
+ authProvider: SamlProviders.KEYCLOAK_SAML,
+ isActive: true,
+ encryptedSamlEntryPoint: encryptedEntryPoint,
+ encryptedSamlIssuer: encryptedIssuer,
+ encryptedSamlCertificate: encryptedCert
+ });
+ samlConfigId = existingSamlConfig.id;
+ console.log(`[seed] saml config row exists id=${existingSamlConfig.id} — refreshed cert/entryPoint/issuer`);
+ }
+
+ // Verified email domain for SCIM-provisioned test users. Bypasses the DNS-TXT
+ // verification flow by inserting status=verified directly. Idempotent on
+ // (orgId, domain). Future-dated codeExpiresAt is a placeholder — once
+ // status is verified, the runtime code path doesn't read expiry.
+ const existingDomain = await knex(TableName.EmailDomains)
+ .where({ orgId: org.id, domain: E2E_EMAIL_DOMAIN })
+ .first();
+ if (!existingDomain) {
+ const [domainRow] = await knex(TableName.EmailDomains)
+ .insert({
+ orgId: org.id,
+ domain: E2E_EMAIL_DOMAIN,
+ verificationMethod: "dns-txt",
+ verificationCode: "e2e-bootstrap-no-verification-required",
+ verificationRecordName: `_infisical-verify.${E2E_EMAIL_DOMAIN}`,
+ status: "verified",
+ verifiedAt: new Date(),
+ codeExpiresAt: new Date(Date.now() + 365 * 24 * 60 * 60 * 1000)
+ })
+ .returning("*");
+ console.log(`[seed] created verified email domain id=${domainRow.id} (${E2E_EMAIL_DOMAIN})`);
+ } else if (existingDomain.status !== "verified") {
+ await knex(TableName.EmailDomains)
+ .where({ id: existingDomain.id })
+ .update({ status: "verified", verifiedAt: new Date() });
+ console.log(`[seed] email domain row exists id=${existingDomain.id} — flipped to verified`);
+ } else {
+ console.log(`[seed] email domain row exists id=${existingDomain.id} (already verified)`);
+ }
+
+ // saml-config-service.updateSamlCfg() flips scimEnabled to false; we bypass
+ // that path with a direct INSERT/UPDATE here, but re-assert true defensively
+ // in case anything else in the bootstrap leaves it disabled.
+ await knex(TableName.Organization).where({ id: org.id }).update({ scimEnabled: true });
+
+ const appCfg = getConfig();
+ const jwt = crypto.jwt().sign(
+ {
+ scimTokenId: scimToken.id,
+ authTokenType: AuthTokenType.SCIM_TOKEN
+ },
+ appCfg.AUTH_SECRET
+ );
+
+ console.log("");
+ console.log("=== e2e fixtures ===");
+ console.log(` organizationId = ${org.id}`);
+ console.log(` E2E_ORG_SLUG = ${orgSlug}`);
+ console.log(` E2E_SCIM_TOKEN = ${jwt}`);
+ console.log(` E2E_SAML_CONFIG_ID = ${samlConfigId}`);
+ console.log("");
+ console.log("Next steps (see e2e/CLAUDE.md):");
+ console.log(" 1. Confirm plan.scim and plan.samlSSO are enabled for this org.");
+ console.log(" 2. Deploy the mock IdP Worker with the SAML_IDP_PRIVATE_KEY and SAML_IDP_ADMIN_TOKEN");
+ console.log(" secrets set via `wrangler secret put`, and an IDP_SESSIONS KV namespace created.");
+ console.log(" 3. Stash E2E_SCIM_TOKEN and E2E_IDP_ADMIN_TOKEN in the infrastructure repo GH");
+ console.log(" Actions secrets.");
+
+ await knex.destroy();
+};
+
+main().catch((err) => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/e2e/.env.example b/e2e/.env.example
new file mode 100644
index 0000000000..3703e04c3c
--- /dev/null
+++ b/e2e/.env.example
@@ -0,0 +1,11 @@
+# SCIM token for the gamma e2e org. Created by backend/scripts/seed-gamma-fixtures.ts
+# and stored in the infrastructure repo's GH Actions secrets.
+E2E_SCIM_TOKEN=
+
+# Shared secret the test sends as `Authorization: Bearer` to POST /saml-idp/identity.
+# Same value as the SAML_IDP_ADMIN_TOKEN secret set on preview-environments.
+E2E_IDP_ADMIN_TOKEN=
+
+# Other config (gamma URL, org slug, IdP URL, SAML config id) is hardcoded
+# in e2e/helpers/constants.ts — none of those are secrets and keeping them in
+# code means CI only needs the two tokens above.
diff --git a/e2e/.gitignore b/e2e/.gitignore
new file mode 100644
index 0000000000..5f880b28f5
--- /dev/null
+++ b/e2e/.gitignore
@@ -0,0 +1,11 @@
+node_modules
+package-lock.json
+playwright-report
+test-results
+.env
+.env.local
+*.log
+
+# Local-only artifacts (e.g. private-key material staged for `wrangler secret put`).
+# Public cert is committed at fixtures/idp-cert.pem; matching key never enters git.
+fixtures/.local-*
diff --git a/e2e/CLAUDE.md b/e2e/CLAUDE.md
new file mode 100644
index 0000000000..0ebd43e824
--- /dev/null
+++ b/e2e/CLAUDE.md
@@ -0,0 +1,106 @@
+# CLAUDE.md
+
+Guidance for Claude Code sessions working in this directory. Covers both the operator-facing view (env vars, bootstrap, how to run) and the agent-facing context (architecture, gotchas, file layout).
+
+## What this directory is
+
+External Playwright suite targeting a deployed Infisical environment (gamma). Runs in CI between `gamma-deployment` and any prod-deploy job — defined as `gamma-playwright-e2e` in the `infrastructure` repo's `.github/workflows/infisical-deployment.yml`. A red run blocks all 11 prod/dedicated deploy jobs via `needs:`.
+
+**Not** the same as `backend/e2e-test/`, which is in-process Vitest with a bootstrapped server. That one tests the backend in isolation; this one tests the deployed product as a black box.
+
+## Scope discipline
+
+This suite exists for **smoke-level** verification — "does the surface still work end-to-end against real infrastructure." If a test is best expressed as "given these inputs to a function, assert these outputs," it belongs in a unit or integration test, not here. The CI cost per test (minutes, not seconds) makes narrow coverage expensive.
+
+Concrete rule: a test here should be *useful even if every integration test passed*. It's catching things integration tests can't — config drift, deploy regressions, end-to-end auth flows that depend on real IdPs.
+
+## Architecture
+
+- **Playwright** — TypeScript, Chromium project only. Single worker, `fullyParallel: false`. The single-worker constraint is load-bearing — see "Serial execution" below.
+- **Two-token CI surface.** Only the two real secrets (`E2E_SCIM_TOKEN`, `E2E_IDP_ADMIN_TOKEN`) come from env vars — validated fail-fast in [`helpers/env.ts`](helpers/env.ts). Deploy-level identifiers (gamma URL, org slug, IdP URL, SAML config row id) are constants in [`helpers/constants.ts`](helpers/constants.ts). The deliberate tradeoff: re-seeding gamma's e2e org rotates the `saml_configs.id`, which then has to be updated in code instead of in a GH Actions secret.
+- **Twingate-gated.** Gamma sits behind Twingate; the CI workflow installs the Twingate connector before tests run. Locally, you need to be on Twingate too. The Playwright Chromium inherits routes from the host network connector.
+- **Mock IdP we control.** SAML SSO points at `preview-orchestrator.infisical.workers.dev/saml-idp/*` — Hono routes on the existing `preview-environments` Worker, using `samlify` for signing under `nodejs_compat`. No SaaS account, no vendor DOM. The test calls `POST /saml-idp/identity` with a per-run NameID, sets the returned session id as a cookie on the Worker domain, then navigates to gamma's SAML start URL; the browser carries the cookie through gamma's 302 to the IdP, which mints a signed assertion for that identity. Cert is committed at [`fixtures/idp-cert.pem`](fixtures/idp-cert.pem); private key is in CF Secrets only (`SAML_IDP_PRIVATE_KEY`). Worker code lives in the `preview-environments` repo, not here — that side of the system is owned separately.
+- **Two SAML entry shapes, one spec file.** `tests/scim-saml-auth.spec.ts` covers both variants under one `describe`. SP-initiated navigates to gamma's `/api/v1/sso/redirect/saml2/organizations/:orgSlug` first; gamma 302s the browser to the Worker's `/saml-idp/sso` with an `AuthnRequest`. IdP-initiated starts at the Worker's `/saml-idp/initiate`, which mints an *unsolicited* signed `SAMLResponse` (no `InResponseTo` per SAML 2.0 §3.4.1.5) and auto-POSTs it directly to gamma's ACS at `/api/v1/sso/saml2/:samlConfigId`. The IdP-initiated test passes the gamma ACS URL through `POST /identity` (validated against the gamma SP origin allowlist), reachable via `gammaSamlAcsUrl()` in [`helpers/idp-client.ts`](helpers/idp-client.ts).
+
+## Load-bearing identity coupling
+
+This is the one detail that, if you get it wrong, makes the test silently fail in confusing ways:
+
+```
+SCIM userName == SAML NameID emitted by the IdP == UserAlias.externalId
+```
+
+The chain works because:
+- SCIM provisioning creates `UserAlias.externalId = req.body.userName` (backend `scim-router.ts:266` → `scim-service.ts:499`).
+- Org auth method is SAML, so the alias type is SAML (`scim-service.ts:428`).
+- SAML login looks up by `userAliasDAL.findOne({ externalId: profile.nameID, orgId, aliasType: SAML })` (`saml-config-service.ts:535`).
+
+With the in-house mock IdP, the test now **owns this value end-to-end**: it generates a per-run `EXTERNAL_ID` (`e2e-${runId}@infisical-e2e.test`) and passes the same string as the SCIM `userName`, the IdP `email` (which samlify uses as the SAML `NameID`), and implicitly as `UserAlias.externalId`. There's no SaaS-side configuration to drift. If `tests/scim-saml-auth.spec.ts` and `helpers/idp-client.ts` agree on the value, the chain holds.
+
+The current test still ends at `/signup/sso?token=…` rather than `/login/select-organization` — gamma routes any `userAlias.isEmailVerified = false` user through `SIGNUP_REQUIRED` (`auth-login-service.ts:322`), and SCIM hardcodes that field to `false` (`scim-service.ts:506`). The signup token JWT contains the verified identity fields. Patching the SCIM service to mark aliases verified at provisioning time would flip the redirect back to the original `/login/select-organization`; that's a separate backend change.
+
+## Serial execution is intentional
+
+Tests run with a single worker. The old reason (single static IdP identity) is gone — the mock IdP can mint an assertion for any NameID the test asks for, so per-run unique externalIds already work.
+
+What still binds us to single-worker is the **shared gamma org**: there's one `saml_configs` row, one set of `email_domains` rows, one `orgAuthMethod`. Concurrent tests writing to the same org's `user_aliases`/`memberships` rows risk subtle interleavings (e.g. the same email landing on a fallback `userDAL.findOne({ username })` from two flows at once). Unblocking parallelism would mean either per-test gamma orgs (heavier seed script) or accepting that risk for tests that don't touch shared org state.
+
+If you do enable parallel workers, also ensure the IdP `/saml-idp/identity` flow's cookie scoping survives — the Worker sets `path=/saml-idp`, so multiple concurrent tests can each set their own session cookie value on the Worker origin without collision (Playwright contexts are already isolated per test).
+
+## File layout
+
+| Path | Purpose | Touch when... |
+|---|---|---|
+| `playwright.config.ts` | Runner config — baseURL, retries, reporter | Adding a project (e.g. Firefox), changing retry policy |
+| `helpers/env.ts` | Fail-fast env loader for the two bearer-token secrets | Adding a new *secret* (also update `.env.example` and the CI workflow) — non-secret config goes in `constants.ts` instead |
+| `helpers/constants.ts` | Hardcoded deploy-level identifiers (gamma URL, org slug, IdP URL, SAML config id) | Gamma's e2e org is re-bootstrapped and `saml_configs.id` rotates — update `SAML_CONFIG_ID`; the seed script logs the new value on the `[seed] E2E_SAML_CONFIG_ID = <uuid>` line |
+| `helpers/scim.ts` | SCIM CRUD wrappers, reusable across tests | Any new SCIM operation a test needs (e.g. Groups) |
+| `helpers/idp-client.ts` | Talks to the mock IdP — stashes a NameID (+ optional ACS URL for IdP-initiated), sets the Worker-domain session cookie, and starts either SP- or IdP-initiated flows | Adding a new SAML-flavored flow, or if the Worker IdP's API/cookie scheme changes |
+| `tests/*.spec.ts` | One test per flow | Adding a new flow (see below) |
+| `fixtures/idp-cert.pem` | Committed public cert for the mock IdP; gamma's SAML config row holds this same cert (KMS-encrypted) | Rotating the IdP keypair (see [`fixtures/README.md`](fixtures/README.md)) |
+| `tsconfig.json` | TS config — no `baseUrl`/`paths` on purpose, relative imports only | Avoid unless you have a real reason |
+
+## Adding a new test
+
+1. **One *flow* per file**, not one test per file. A flow is a distinct end-to-end path being verified (e.g. "SCIM-provisioned user logs in via SAML", "SAML response rejection", "SCIM deactivation revokes SAML login"). Variants of the *same* flow that differ only in entry shape or input (SP-initiated vs IdP-initiated SAML; each strictness gate within a rejection suite) belong in the same file under one `test.describe`, as multiple `test()` blocks. Distinct flows get their own file.
+2. Name the file after the flow (`scim-saml-auth.spec.ts`, `saml-rejection.spec.ts`, `scim-deactivation.spec.ts`). Per-variant naming goes inside the file as test titles.
+3. Import from `../helpers/constants`, `../helpers/env`, `../helpers/scim`, `../helpers/idp-client`. Add a new helper module only if a fundamentally new flow needs shared setup (e.g. an OIDC helper if/when that's covered).
+4. **Per-variant state goes in `beforeEach` / `afterEach`**, not `beforeAll` / `afterAll`. Each variant test should own its own SCIM user (fresh `externalId`) so a mid-test crash on one variant doesn't poison the next. See `saml-rejection.spec.ts` for the pattern. Use `beforeAll`/`afterAll` only when there's genuinely shared, idempotent state across the whole file.
+5. **Always clean up.** `beforeEach` defensively deletes any state the test creates; `afterEach` deletes what the test produced. Tests crash mid-flow sometimes; the e2e org accumulates rows otherwise. Note: the SAML signup branch also creates a fresh user row on each run — currently leaks; revisit when SCIM's `isEmailVerified` default is patched.
+6. **One assertion-block per test should be enough** to claim the variant works. Factor a shared `expect…()` helper inside the file when multiple tests assert the same outcome shape (e.g. `expectSignupSsoRedirectFor(page, email)` in `scim-saml-auth.spec.ts`) — that's preferable to copying ~10 lines of expect calls across tests. Don't expand a smoke test into a unit-test-style assertion sprawl — push fine-grained detail into integration tests.
+7. **Don't share helpers across spec files.** Helpers live in `helpers/*` or as file-local consts/functions at the top of the spec. Cross-spec imports create CI debugging cliffs — avoid.
+8. Run locally first (`npm test`) with `.env` populated. CI will replicate via GH Actions secrets.
+
+## What you can break by accident
+
+These external dependencies have to stay in sync — if you change the backend or the Worker, the test breaks silently. Worth grepping for after any change in these areas:
+
+- **SCIM endpoint URL** (`backend/src/ee/routes/v1/scim-router.ts`, mounted at `/api/v1/scim`). `helpers/scim.ts` hardcodes `/api/v1/scim/Users` and `/api/v1/scim/Users/:id`. If the router prefix moves, update here.
+- **SAML start/ACS URLs** (`backend/src/ee/routes/v1/saml-router.ts`). `helpers/idp-client.ts` hardcodes `/api/v1/sso/redirect/saml2/organizations/:orgSlug` (SP-initiated) and `/api/v1/sso/saml2/:samlConfigId` (IdP-initiated ACS, built from `SAML_CONFIG_ID` in `helpers/constants.ts`). If either path moves, both consumer sites need to follow.
+- **Post-login redirect** (`saml-config-service.ts` → `auth-login-service.ts:322`). `tests/scim-saml-auth.spec.ts` asserts `/signup/sso?token=…`; if SCIM gets patched to mark aliases verified, the redirect flips to `/login/select-organization` and the assertion needs to follow.
+- **NameID-to-externalId mapping** (`saml-config-service.ts:535`). Currently `profile.nameID`. If the matching attribute changes, the identity-coupling section above becomes stale.
+- **`scimEnabled` / `orgAuthMethod` semantics** (`scim-service.ts:413, 419`). If new gating gets added (e.g. additional flags), the seed script in `backend/scripts/seed-gamma-fixtures.ts` needs to set them.
+- **Verified email domain check** (`email-domain-fns.ts:11`). SCIM POST and SAML login both require the email domain to be on the org's `email_domains` allowlist with `status='verified'`. The seed script writes one for `infisical-e2e.test`; if the test ever uses a different domain, add a row.
+- **Mock IdP cert ↔ gamma SAML config cert** must match. Seed script reads the committed cert from `e2e/fixtures/idp-cert.pem` and KMS-encrypts it into the `saml_configs` row; the Worker signs with the matching private key from `SAML_IDP_PRIVATE_KEY` (CF Secret). Rotating one requires rotating the other — see `fixtures/README.md`.
+- **passport-saml strictness** (`saml-router.ts:51-117`). Under `authProvider = keycloak-saml` (what the seed script writes), no overrides apply — passport-saml requires both Response and Assertion signed, attribute `email`/`firstName`/`lastName` present, and audience matching `appCfg.SITE_URL`. `validateInResponseTo` defaults to `"never"` in `@node-saml/node-saml` 5.x, which is why the IdP-initiated path works at all; flipping it to `"ifPresent"` or `"always"` would break IdP-initiated first. The Worker's unsolicited template omits `InResponseTo` entirely (per SAML 2.0 §3.4.1.5) so the test stays valid if that default is ever tightened. Changing the seed's `authProvider` value would change the strictness profile.
+
+## Common pitfalls
+
+- **Diagnostics about `@playwright/test`** before `npm install` runs — expected. Resolve by `cd e2e && npm install`.
+- **The seed script's bootstrap is one-pass now.** Direct DB writes don't trigger `updateSamlCfg`'s `scimEnabled=false` side effect, so a single run leaves a usable state. (The old SSOJet-era two-pass requirement is gone.) Re-run is still safe; it's idempotent.
+- **CF Access bypass for `/saml-idp/*`** must be in place on the `preview-orchestrator` Worker, otherwise every request to the mock IdP 302s to the CF Access login page. The bypass is safe because the IdP routes have their own auth (`Authorization: Bearer SAML_IDP_ADMIN_TOKEN` on `/identity`, cookie + KV lookup on `/sso` and `/initiate`, intentionally public on `/metadata.xml`).
+- **Worker changes ship via `wrangler deploy`**, not the gamma deploy. After editing Worker code (`/saml-idp/*` routes, IdP templates), deploy from the `preview-environments` repo before running the test or it'll hit the previous version. `tsc` passing here doesn't prove the Worker is up to date.
+- **SCIM POST + SAML signup leak a user row per test run** because the SAML signup branch creates a fresh `users` row even though SCIM already created one. SCIM `DELETE /Users/:id` removes the membership but not the orphan user. Tractable but accumulates; revisit if it becomes noisy.
+- **Don't add a `.npmrc` here for the 7-day minimum-release-age rule** — `e2e/` is a test harness, not a runtime artifact. The supply-chain concern that motivates the rule in `backend/`/`frontend/` doesn't apply.
+- **CI uses `npm install`, not `npm ci`** — we don't commit a lockfile yet. If you commit `package-lock.json`, switch the workflow to `npm ci` for determinism. Both are fine; just keep them consistent.
+- **Don't widen what the seed script creates** unless you've thought through the safety. It already refuses prod (host/dbname regex + `INFISICAL_ENV=prod` + interactive confirmation). Adding more powerful operations means re-evaluating the guard surface.
+
+## Where context lives
+
+- CI workflow: `infrastructure` repo, `.github/workflows/infisical-deployment.yml` (the `gamma-playwright-e2e` job)
+- Seed script: [`../backend/scripts/seed-gamma-fixtures.ts`](../backend/scripts/seed-gamma-fixtures.ts)
+- Backend SCIM service: `../backend/src/ee/services/scim/`
+- Backend SAML service: `../backend/src/ee/services/saml-config/`
+- Mock IdP Worker code: `preview-environments` repo, `src/saml-idp/` (separate repo — owned independently)
+- IdP keypair provenance + rotation: [`fixtures/README.md`](fixtures/README.md)
+- Root architectural notes: [`../CLAUDE.md`](../CLAUDE.md), [`../backend/CLAUDE.md`](../backend/CLAUDE.md)
diff --git a/e2e/fixtures/README.md b/e2e/fixtures/README.md
new file mode 100644
index 0000000000..71bf0e88e8
--- /dev/null
+++ b/e2e/fixtures/README.md
@@ -0,0 +1,38 @@
+# e2e/fixtures
+
+Long-lived test artifacts consumed by the e2e suite and the gamma bootstrap.
+
+## `idp-cert.pem`
+
+X.509 certificate of the SAML mock IdP hosted in `preview-environments` at
+`https://preview-orchestrator.infisical.workers.dev/saml-idp/*`. The matching
+private key lives only in Cloudflare Worker Secrets (`SAML_IDP_PRIVATE_KEY`)
+and is **never** committed.
+
+`backend/scripts/seed-gamma-fixtures.ts` reads this file and writes the cert
+into gamma's `saml_configs` row for the e2e org so gamma can verify the
+signed responses the Worker emits.
+
+### Provenance
+
+Generated once with:
+
+```sh
+openssl req -new -newkey rsa:2048 -nodes -keyout idp-key.pem -x509 -sha256 -days 3650 \
+ -subj "/CN=infisical-e2e-mock-idp/O=Infisical e2e/OU=Test Only" \
+ -out idp-cert.pem
+```
+
+10-year validity is deliberate — this cert is test-only and used only between
+the mock IdP and gamma's e2e org. There is no rotation tooling; if the cert
+ever does need to rotate, generate a new pair, push the new private key as
+`SAML_IDP_PRIVATE_KEY`, replace this file, and re-run the seed script (it's
+idempotent on the SAML config row's `cert` column).
+
+### Threat model
+
+The matching private key would let an attacker mint SAML assertions for the
+e2e org only. That org is feature-gated to SCIM-provisioned users (no
+self-signup against it) and exists exclusively for `tests/scim-saml-auth.spec.ts`.
+Worst case is impersonation of the test user inside an org with no real data.
+Keep the private key in CF Secrets and out of git regardless.
diff --git a/e2e/fixtures/idp-cert.pem b/e2e/fixtures/idp-cert.pem
new file mode 100644
index 0000000000..13171d6224
--- /dev/null
+++ b/e2e/fixtures/idp-cert.pem
@@ -0,0 +1,18 @@
+-----BEGIN CERTIFICATE-----
+MIIC1jCCAb4CCQD1FjEkwKeWMDANBgkqhkiG9w0BAQsFADAtMSswKQYDVQQDDCJw
+cmV2aWV3LW9yY2hlc3RyYXRvci1zYW1sLWlkcC1tb2NrMB4XDTI2MDUyMDIzMzEx
+OFoXDTM2MDUxNzIzMzExOFowLTErMCkGA1UEAwwicHJldmlldy1vcmNoZXN0cmF0
+b3Itc2FtbC1pZHAtbW9jazCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
+AJURuoBYGPD1zlbfxYZinW6DjD4FaXIvkU4g+LcGArzupqOu1OLkvmhZmIK+W5ij
+SDBYDcS7QfiucMIJDUf5qbCHBOyL5Dno//heNIk8W0DYy7hPWrbjK79SXIYjXqvq
+o3BxtWHpBkbJbUc9b+cKQ+8NLV8JCJbCbJXV5nUyIvX80OxlWW1n8PIPgHA/k4W4
+GjCk66BRSQgDK3eCdD2n1pNqkvdx8ghyt2tdvLx4wUz+U6bv+nQNBHVWHOGsBHYG
+xmRQrg1n3FSw9/OP+bhwboyzdo+M1J8yguDCnpsfxFfQq6HttlG/FlCC44usIJZw
+cZblLaTqAa8CjRlpH99ewnUCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAKbaaXMa7
+khJwHIQH+m+M5DIowQEy7fvgChxDJwkiYB3cGQfTZS9ihiEms0WIuFTHvl2IZTBr
+aiYO1CG+x+r2bmdEq+NU/1EWr/ddfzcde3GFB1HWk0qwaZck2NdfckWT7c/Z4sVt
+9GrhT55ypGR3tml2bjZI/6k3pLwxWS3KzUN2g8lcoaLL9h3J+3eqPsh1GhW0N5de
+uoK4eXV1T72/DC8VCDAETp/4oOhqngqIaZ+Rqgr+vh+GimYdCvTtHM7GJzCllfMz
+9f4UJ21tQvMQwm42mIo78LPVYeB3V4wN19o2UwLSRac/KiA5nfxjHMbd7/Wms5dk
+4jAqRC+9FEzKZA==
+-----END CERTIFICATE-----
diff --git a/e2e/helpers/constants.ts b/e2e/helpers/constants.ts
new file mode 100644
index 0000000000..6c652afb92
--- /dev/null
+++ b/e2e/helpers/constants.ts
@@ -0,0 +1,19 @@
+// Hardcoded deploy-level identifiers. None of these are secrets — pinning
+// them here instead of in env vars keeps the CI surface minimal (only the
+// SCIM and IdP-admin bearer tokens stay in GH Actions secrets).
+//
+// If gamma's e2e org or saml_configs row is ever re-bootstrapped from
+// scratch, the seed script (backend/scripts/seed-gamma-fixtures.ts) logs the
+// new row id on `[seed] E2E_SAML_CONFIG_ID = <uuid>`. Update SAML_CONFIG_ID
+// below to match — symptoms otherwise: gamma 404s on the ACS POST and the
+// IdP-initiated test fails on the redirect assertion.
+
+export const GAMMA_BASE_URL = "https://gamma.infisical.com";
+
+export const E2E_ORG_SLUG = "e2e-scim-test";
+
+export const IDP_BASE_URL = "https://preview-orchestrator.infisical.workers.dev";
+
+// `saml_configs.id` for the gamma e2e org. Created once by the seed script;
+// the row is long-lived, so a constant is acceptable here.
+export const SAML_CONFIG_ID = "03b67793-60a4-4d83-84cf-79c9b334d7c3";
diff --git a/e2e/helpers/env.ts b/e2e/helpers/env.ts
new file mode 100644
index 0000000000..093b20a3b2
--- /dev/null
+++ b/e2e/helpers/env.ts
@@ -0,0 +1,15 @@
+const required = (key: string): string => {
+ const value = process.env[key];
+ if (!value) {
+ throw new Error(`${key} must be set`);
+ }
+ return value;
+};
+
+// Only true secrets remain in env. Deploy-level identifiers (URLs, org slug,
+// SAML config id) live in `./constants.ts` so CI doesn't need to plumb them
+// through GH Actions secrets.
+export const env = {
+ scimToken: required("E2E_SCIM_TOKEN"),
+ idpAdminToken: required("E2E_IDP_ADMIN_TOKEN")
+};
diff --git a/e2e/helpers/idp-client.ts b/e2e/helpers/idp-client.ts
new file mode 100644
index 0000000000..df10425432
--- /dev/null
+++ b/e2e/helpers/idp-client.ts
@@ -0,0 +1,91 @@
+import type { BrowserContext, Page } from "@playwright/test";
+
+import { E2E_ORG_SLUG, GAMMA_BASE_URL, IDP_BASE_URL, SAML_CONFIG_ID } from "./constants";
+import { env } from "./env";
+
+// samlify reads `email` for both the assertion's NameID and the templated
+// `email` attribute — match the Worker-side IdpIdentity type so the test
+// owns NameID by setting email to the same value as SCIM externalId.
+type AssertionOverrides = {
+ audience?: string;
+ notOnOrAfterOffsetSeconds?: number;
+ inResponseTo?: string;
+};
+type IdpIdentity = {
+ email: string;
+ firstName?: string;
+ lastName?: string;
+ // Required for the IdP-initiated flow (consumed by GET /saml-idp/initiate);
+ // ignored by the SP-initiated /sso path. Worker validates against an
+ // allowlist of gamma SAML ACS URLs before storing.
+ acsUrl?: string;
+ // SAML-rejection tests use these to emit deliberately-broken assertions
+ // (wrong audience, expired NotOnOrAfter, mismatched InResponseTo) and assert
+ // gamma rejects. Worker contract: `src/saml-idp/router.ts:identityBody`.
+ assertionOverrides?: AssertionOverrides;
+};
+
+type IdentityResponse = {
+ sessionId: string;
+ cookieName: string;
+ ttlSeconds: number;
+};
+
+// Stash an identity with the mock IdP and set the corresponding session cookie
+// on the test browser context. After this returns, navigating the same `page`
+// to gamma's SAML start URL will cause the IdP to emit an assertion for this
+// identity (cookie travels along on the redirect from gamma -> IdP).
+export const primeSamlIdentity = async (page: Page, identity: IdpIdentity): Promise<void> => {
+ const response = await fetch(`${IDP_BASE_URL}/saml-idp/identity`, {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ authorization: `Bearer ${env.idpAdminToken}`
+ },
+ body: JSON.stringify(identity)
+ });
+ if (!response.ok) {
+ const detail = await response.text();
+ throw new Error(`Failed to prime SAML identity (${response.status}): ${detail}`);
+ }
+ const body = (await response.json()) as IdentityResponse;
+ await setIdpSessionCookie(page.context(), body);
+};
+
+const setIdpSessionCookie = async (ctx: BrowserContext, body: IdentityResponse): Promise<void> => {
+ const url = new URL(IDP_BASE_URL);
+ await ctx.addCookies([
+ {
+ name: body.cookieName,
+ value: body.sessionId,
+ domain: url.hostname,
+ path: "/saml-idp",
+ expires: Math.floor(Date.now() / 1000) + body.ttlSeconds,
+ // sameSite=None + secure is required for the cookie to travel on the
+ // cross-origin redirect from gamma to the Worker.
+ sameSite: "None",
+ secure: true,
+ httpOnly: false
+ }
+ ]);
+};
+
+export const startSamlLogin = async (page: Page): Promise<void> => {
+ await page.goto(`/api/v1/sso/redirect/saml2/organizations/${encodeURIComponent(E2E_ORG_SLUG)}`);
+};
+
+// ACS URL gamma exposes for the configured SAML provider. The IdP-initiated
+// flow needs this baked into the SAMLResponse since there's no AuthnRequest
+// to read it from. Mirrors `${appCfg.SITE_URL}/api/v1/sso/saml2/${configId}`
+// in backend/src/ee/routes/v1/saml-router.ts:85.
+export const gammaSamlAcsUrl = (): string =>
+ `${GAMMA_BASE_URL}/api/v1/sso/saml2/${SAML_CONFIG_ID}`;
+
+// Triggers the IdP-initiated flow. The page navigates to the Worker's
+// /initiate endpoint, which serves an auto-submitting form POSTing a signed
+// unsolicited SAMLResponse directly to gamma's ACS URL. `primeSamlIdentity`
+// must be called first with `acsUrl: gammaSamlAcsUrl()` so the Worker knows
+// where to deliver the response.
+export const startIdpInitiatedLogin = async (page: Page): Promise<void> => {
+ await page.goto(`${IDP_BASE_URL}/saml-idp/initiate`);
+};
diff --git a/e2e/helpers/scim.ts b/e2e/helpers/scim.ts
new file mode 100644
index 0000000000..ce78d7af3a
--- /dev/null
+++ b/e2e/helpers/scim.ts
@@ -0,0 +1,107 @@
+import type { APIRequestContext } from "@playwright/test";
+
+import { env } from "./env";
+
+export type ScimUser = {
+ id: string;
+ userName: string;
+ emails: { primary: boolean; value: string }[];
+ active: boolean;
+};
+
+const scimHeaders = () => ({
+ Authorization: `Bearer ${env.scimToken}`,
+ "Content-Type": "application/scim+json",
+ Accept: "application/scim+json"
+});
+
+export const createScimUser = async (
+ request: APIRequestContext,
+ input: { externalId: string; email: string; firstName?: string; lastName?: string }
+): Promise<ScimUser> => {
+ const response = await request.post("/api/v1/scim/Users", {
+ headers: scimHeaders(),
+ data: {
+ schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],
+ userName: input.externalId,
+ emails: [{ primary: true, value: input.email }],
+ name: {
+ givenName: input.firstName ?? "E2E",
+ familyName: input.lastName ?? "Test"
+ },
+ active: true
+ }
+ });
+
+ if (!response.ok()) {
+ const body = await response.text();
+ throw new Error(`SCIM create user failed (${response.status()}): ${body}`);
+ }
+
+ return response.json() as Promise<ScimUser>;
+};
+
+export const findScimUserByExternalId = async (
+ request: APIRequestContext,
+ externalId: string
+): Promise<ScimUser | null> => {
+ const response = await request.get("/api/v1/scim/Users", {
+ headers: scimHeaders(),
+ params: {
+ filter: `userName eq "${externalId}"`,
+ count: "1"
+ }
+ });
+
+ if (!response.ok()) {
+ const body = await response.text();
+ throw new Error(`SCIM list users failed (${response.status()}): ${body}`);
+ }
+
+ const payload = (await response.json()) as { Resources: ScimUser[] };
+ return payload.Resources[0] ?? null;
+};
+
+export const deleteScimUser = async (request: APIRequestContext, orgMembershipId: string): Promise<void> => {
+ const response = await request.delete(`/api/v1/scim/Users/${orgMembershipId}`, {
+ headers: scimHeaders()
+ });
+
+ if (!response.ok() && response.status() !== 404) {
+ const body = await response.text();
+ throw new Error(`SCIM delete user failed (${response.status()}): ${body}`);
+ }
+};
+
+export const ensureScimUserAbsent = async (request: APIRequestContext, externalId: string): Promise<void> => {
+ const existing = await findScimUserByExternalId(request, externalId);
+ if (!existing) {
+ return;
+ }
+ await deleteScimUser(request, existing.id);
+};
+
+// SCIM PATCH for {active: false} flips `memberships.isActive` on the gamma row
+// (see scim-service.ts:681). Per RFC 7644 §3.5.2 a replace op without `path`
+// accepts a value object — gamma's parser handles both shapes; the path form
+// is more explicit and what most IdPs send.
+export const setScimUserActive = async (
+ request: APIRequestContext,
+ orgMembershipId: string,
+ active: boolean
+): Promise<ScimUser> => {
+ const response = await request.patch(`/api/v1/scim/Users/${orgMembershipId}`, {
+ headers: scimHeaders(),
+ data: {
+ schemas: ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+ Operations: [{ op: "replace", path: "active", value: active }]
+ }
+ });
+
+ if (!response.ok()) {
+ const body = await response.text();
+ throw new Error(`SCIM patch active=${active} failed (${response.status()}): ${body}`);
+ }
+
+ return response.json() as Promise<ScimUser>;
+};
diff --git a/e2e/package.json b/e2e/package.json
new file mode 100644
index 0000000000..0674c58542
--- /dev/null
+++ b/e2e/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "@infisical/e2e",
+ "version": "0.1.0",
+ "private": true,
+ "description": "Playwright e2e suite that runs against a deployed Infisical environment (gamma) between deploy and prod promotion.",
+ "scripts": {
+ "test": "playwright test",
+ "test:headed": "playwright test --headed",
+ "test:ui": "playwright test --ui",
+ "report": "playwright show-report",
+ "install:browsers": "playwright install --with-deps chromium",
+ "type:check": "tsc --noEmit"
+ },
+ "devDependencies": {
+ "@playwright/test": "^1.55.1",
+ "@types/node": "20.17.10",
+ "dotenv": "16.4.7",
+ "typescript": "5.6.3"
+ }
+}
diff --git a/e2e/playwright.config.ts b/e2e/playwright.config.ts
new file mode 100644
index 0000000000..9e8ce5eab2
--- /dev/null
+++ b/e2e/playwright.config.ts
@@ -0,0 +1,41 @@
+import { defineConfig, devices } from "@playwright/test";
+import dotenv from "dotenv";
+
+import { GAMMA_BASE_URL } from "./helpers/constants";
+
+dotenv.config();
+
+const isCI = Boolean(process.env.CI);
+
+export default defineConfig({
+ testDir: "./tests",
+ fullyParallel: false,
+ forbidOnly: isCI,
+ retries: isCI ? 2 : 0,
+ workers: 1,
+ reporter: isCI
+ ? [
+ ["github"],
+ ["html", { outputFolder: "playwright-report", open: "never" }],
+ ["list"]
+ ]
+ : [["html", { open: "on-failure" }], ["list"]],
+ timeout: 60_000,
+ expect: {
+ timeout: 10_000
+ },
+ use: {
+ baseURL: GAMMA_BASE_URL,
+ trace: "retain-on-failure",
+ screenshot: "only-on-failure",
+ video: "retain-on-failure",
+ actionTimeout: 15_000,
+ navigationTimeout: 30_000
+ },
+ projects: [
+ {
+ name: "chromium",
+ use: { ...devices["Desktop Chrome"] }
+ }
+ ]
+});
diff --git a/e2e/tests/saml-rejection.spec.ts b/e2e/tests/saml-rejection.spec.ts
new file mode 100644
index 0000000000..0bfc2d05c4
--- /dev/null
+++ b/e2e/tests/saml-rejection.spec.ts
@@ -0,0 +1,125 @@
+import { expect, Page, request, test, type Response } from "@playwright/test";
+
+import { GAMMA_BASE_URL } from "../helpers/constants";
+import { primeSamlIdentity, startSamlLogin } from "../helpers/idp-client";
+import { createScimUser, deleteScimUser, ensureScimUserAbsent } from "../helpers/scim";
+
+// Each sub-test verifies one passport-saml strictness gate by having the mock
+// IdP emit a deliberately-broken assertion and asserting gamma's ACS POST
+// returns 4xx. The happy-path test (`scim-saml-auth.spec.ts`) covers the
+// reverse direction — that the same assertion shape, sans break, succeeds.
+//
+// Gamma's saml-router translates passport-saml validation errors into
+// `BadRequestError({ message: "Saml authentication failed. <reason>" })`
+// (saml-router.ts:325) → fastify returns 400 JSON. A regression that
+// silently disabled signature/audience/InResponseTo/Conditions checks would
+// flip these to 302 redirects to /signup/sso or /login/select-organization.
+
+const TEST_FIRST_NAME = "E2E";
+const TEST_LAST_NAME = "RejectionTest";
+
+const makeExternalId = (): string => {
+ const runId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+ return `e2e-rej-${runId}@infisical-e2e.test`;
+};
+
+const waitForAcsPostResponse = (page: Page): Promise<Response> =>
+ page.waitForResponse(
+ (response) => response.url().includes("/api/v1/sso/saml2/") && response.request().method() === "POST",
+ { timeout: 20_000 }
+ );
+
+test.describe("SAML response rejection", () => {
+ let orgMembershipId: string | null = null;
+ let externalId: string | null = null;
+
+ test.beforeEach(async () => {
+ externalId = makeExternalId();
+ const apiContext = await request.newContext({ baseURL: GAMMA_BASE_URL });
+ await ensureScimUserAbsent(apiContext, externalId);
+ await apiContext.dispose();
+ orgMembershipId = null;
+ });
+
+ test.afterEach(async () => {
+ if (!orgMembershipId) {
+ return;
+ }
+ const apiContext = await request.newContext({ baseURL: GAMMA_BASE_URL });
+ await deleteScimUser(apiContext, orgMembershipId);
+ await apiContext.dispose();
+ });
+
+ test("audience mismatch is rejected", async ({ page, request: apiRequest }) => {
+ const created = await createScimUser(apiRequest, {
+ externalId: externalId as string,
+ email: externalId as string,
+ firstName: TEST_FIRST_NAME,
+ lastName: TEST_LAST_NAME
+ });
+ orgMembershipId = created.id;
+
+ await primeSamlIdentity(page, {
+ email: externalId as string,
+ firstName: TEST_FIRST_NAME,
+ lastName: TEST_LAST_NAME,
+ assertionOverrides: {
+ audience: "https://wrong-audience.example.com"
+ }
+ });
+
+ const acsResponse = waitForAcsPostResponse(page);
+ await startSamlLogin(page);
+ const response = await acsResponse;
+ expect(response.status(), "gamma must reject when assertion audience != SITE_URL").toBe(400);
+ });
+
+ test("expired NotOnOrAfter is rejected", async ({ page, request: apiRequest }) => {
+ const created = await createScimUser(apiRequest, {
+ externalId: externalId as string,
+ email: externalId as string,
+ firstName: TEST_FIRST_NAME,
+ lastName: TEST_LAST_NAME
+ });
+ orgMembershipId = created.id;
+
+ await primeSamlIdentity(page, {
+ email: externalId as string,
+ firstName: TEST_FIRST_NAME,
+ lastName: TEST_LAST_NAME,
+ assertionOverrides: {
+ // 10 minutes in the past — well outside passport-saml's clock-skew tolerance.
+ notOnOrAfterOffsetSeconds: -600
+ }
+ });
+
+ const acsResponse = waitForAcsPostResponse(page);
+ await startSamlLogin(page);
+ const response = await acsResponse;
+ expect(response.status(), "gamma must reject when Conditions/@NotOnOrAfter is in the past").toBe(400);
+ });
+
+ test("InResponseTo mismatch is rejected", async ({ page, request: apiRequest }) => {
+ const created = await createScimUser(apiRequest, {
+ externalId: externalId as string,
+ email: externalId as string,
+ firstName: TEST_FIRST_NAME,
+ lastName: TEST_LAST_NAME
+ });
+ orgMembershipId = created.id;
+
+ await primeSamlIdentity(page, {
+ email: externalId as string,
+ firstName: TEST_FIRST_NAME,
+ lastName: TEST_LAST_NAME,
+ assertionOverrides: {
+ inResponseTo: "_does-not-match-the-real-authn-request-id"
+ }
+ });
+
+ const acsResponse = waitForAcsPostResponse(page);
+ await startSamlLogin(page);
+ const response = await acsResponse;
+ expect(response.status(), "gamma must reject when InResponseTo doesn't echo the AuthnRequest ID").toBe(400);
+ });
+});
diff --git a/e2e/tests/scim-deactivation.spec.ts b/e2e/tests/scim-deactivation.spec.ts
new file mode 100644
index 0000000000..8f5907fcc3
--- /dev/null
+++ b/e2e/tests/scim-deactivation.spec.ts
@@ -0,0 +1,80 @@
+import { expect, request, test, type Page, type Response } from "@playwright/test";
+
+import { GAMMA_BASE_URL } from "../helpers/constants";
+import { primeSamlIdentity, startSamlLogin } from "../helpers/idp-client";
+import {
+ createScimUser,
+ deleteScimUser,
+ ensureScimUserAbsent,
+ setScimUserActive
+} from "../helpers/scim";
+
+const TEST_FIRST_NAME = "E2E";
+const TEST_LAST_NAME = "DeactivationTest";
+
+const makeExternalId = (): string => {
+ const runId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+ return `e2e-deact-${runId}@infisical-e2e.test`;
+};
+
+const waitForAcsPostResponse = (page: Page): Promise<Response> =>
+ page.waitForResponse(
+ (response) => response.url().includes("/api/v1/sso/saml2/") && response.request().method() === "POST",
+ { timeout: 20_000 }
+ );
+
+test.describe("SCIM deactivation revokes SAML login", () => {
+ let orgMembershipId: string | null = null;
+ let externalId: string | null = null;
+
+ test.beforeEach(async () => {
+ externalId = makeExternalId();
+ const apiContext = await request.newContext({ baseURL: GAMMA_BASE_URL });
+ await ensureScimUserAbsent(apiContext, externalId);
+ await apiContext.dispose();
+ orgMembershipId = null;
+ });
+
+ test.afterEach(async () => {
+ if (!orgMembershipId) {
+ return;
+ }
+ const apiContext = await request.newContext({ baseURL: GAMMA_BASE_URL });
+ await deleteScimUser(apiContext, orgMembershipId);
+ await apiContext.dispose();
+ });
+
+ test("SAML login is rejected after SCIM deactivation", async ({ page, request: apiRequest }) => {
+ const created = await createScimUser(apiRequest, {
+ externalId: externalId as string,
+ email: externalId as string,
+ firstName: TEST_FIRST_NAME,
+ lastName: TEST_LAST_NAME
+ });
+ orgMembershipId = created.id;
+ expect(created.active).toBe(true);
+
+ const deactivated = await setScimUserActive(apiRequest, orgMembershipId, false);
+ expect(deactivated.active, "SCIM PATCH must persist active=false").toBe(false);
+
+ await primeSamlIdentity(page, {
+ email: externalId as string,
+ firstName: TEST_FIRST_NAME,
+ lastName: TEST_LAST_NAME
+ });
+
+ const acsResponse = waitForAcsPostResponse(page);
+ await startSamlLogin(page);
+ const response = await acsResponse;
+ // saml-router.ts:325 wraps any SAML strategy error in BadRequestError (400);
+ // a deactivation-aware throw inside samlLogin would surface as 401/403
+ // depending on where the check lands. Accept any 4xx so this test stays
+ // valid regardless of which layer enforces the gate. The thing we're
+ // guarding against is the 302-to-signup-or-login that means "accepted".
+ expect(
+ response.status(),
+ "gamma must reject SAML login for users whose membership.isActive is false"
+ ).toBeGreaterThanOrEqual(400);
+ expect(response.status()).toBeLessThan(500);
+ });
+});
diff --git a/e2e/tests/scim-saml-auth.spec.ts b/e2e/tests/scim-saml-auth.spec.ts
new file mode 100644
index 0000000000..cef9fac646
--- /dev/null
+++ b/e2e/tests/scim-saml-auth.spec.ts
@@ -0,0 +1,136 @@
+import { expect, Page, request, test } from "@playwright/test";
+
+import { GAMMA_BASE_URL } from "../helpers/constants";
+import {
+ gammaSamlAcsUrl,
+ primeSamlIdentity,
+ startIdpInitiatedLogin,
+ startSamlLogin
+} from "../helpers/idp-client";
+import { createScimUser, deleteScimUser, ensureScimUserAbsent } from "../helpers/scim";
+
+// SCIM userName (== externalId), SAML NameID, and UserAlias.externalId are
+// all this same string by construction — the test owns it end-to-end.
+// samlify uses `email` for the NameID and the SCIM provisioner sets
+// externalId from userName, so the chain holds as long as we pass the
+// same value as `email` to the IdP and `externalId`/`userName` to SCIM.
+// Email domain must match the verified row the seed script created in
+// email_domains for the e2e org. `.test` (RFC 2606) avoids any collision
+// with real Infisical domain rows that might be claimed by other orgs.
+const TEST_FIRST_NAME = "E2E";
+const TEST_LAST_NAME = "ScimUser";
+const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
+
+const makeExternalId = (): string => {
+ const runId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+ return `e2e-${runId}@infisical-e2e.test`;
+};
+
+// Decodes a JWT payload without verifying the signature. The signature is
+// gamma's; we trust it because we just received it from gamma over TLS.
+const decodeJwtPayload = (token: string): Record<string, unknown> => {
+ const payload = token.split(".")[1];
+ if (!payload) {
+ throw new Error("token does not look like a JWT");
+ }
+ return JSON.parse(Buffer.from(payload, "base64url").toString("utf8")) as Record<string, unknown>;
+};
+
+// SCIM-provisioned users currently land at /signup/sso (not /login/select-organization)
+// because gamma's SCIM service hardcodes user_aliases.isEmailVerified = false
+// (scim-service.ts:506) and processProviderCallback (auth-login-service.ts:322)
+// routes any !isEmailVerified through SIGNUP_REQUIRED. The signup token JWT is
+// the strongest verifiable signal that the full SAML flow worked for the
+// intended identity end-to-end — gamma trusted the IdP's signature, validated
+// audience (and InResponseTo on the SP-initiated branch), extracted the
+// attributes from the assertion, and reached the same user_alias SCIM created.
+const expectSignupSsoRedirectFor = async (page: Page, email: string): Promise<void> => {
+ await expect(page).toHaveURL(/\/signup\/sso\?token=/);
+
+ const token = new URL(page.url()).searchParams.get("token");
+ expect(token, "signup token must be present in the /signup/sso URL").toBeTruthy();
+
+ const claims = decodeJwtPayload(token as string);
+ expect(claims.authTokenType, "must be a provider-issued signup token").toBe("signupToken");
+ expect(claims.authMethod, "auth method should reflect the configured SAML provider").toBe("keycloak-saml");
+ expect(claims.email, "email in the token must match the IdP-emitted NameID").toBe(email);
+ expect(claims.firstName).toBe(TEST_FIRST_NAME);
+ expect(claims.lastName).toBe(TEST_LAST_NAME);
+ expect(claims.userId, "gamma should reference a user row").toMatch(UUID_PATTERN);
+ expect(claims.aliasId, "gamma should reference a user_alias row").toMatch(UUID_PATTERN);
+ expect(claims.organizationId, "auth should be scoped to the e2e org").toMatch(UUID_PATTERN);
+};
+
+test.describe("SCIM provisioning + SAML login", () => {
+ let orgMembershipId: string | null = null;
+ let externalId: string | null = null;
+
+ test.beforeEach(async () => {
+ externalId = makeExternalId();
+ orgMembershipId = null;
+ const apiContext = await request.newContext({ baseURL: GAMMA_BASE_URL });
+ await ensureScimUserAbsent(apiContext, externalId);
+ await apiContext.dispose();
+ });
+
+ test.afterEach(async () => {
+ if (!orgMembershipId) {
+ return;
+ }
+ const apiContext = await request.newContext({ baseURL: GAMMA_BASE_URL });
+ await deleteScimUser(apiContext, orgMembershipId);
+ await apiContext.dispose();
+ });
+
+ // SP-initiated: browser starts at gamma, gamma 302s to the IdP with an
+ // AuthnRequest. The IdP's /sso route signs an assertion bound to that
+ // request and auto-POSTs SAMLResponse back to gamma's ACS.
+ test("SP-initiated SAML login succeeds for a SCIM-provisioned user", async ({ page, request: apiRequest }) => {
+ const created = await createScimUser(apiRequest, {
+ externalId: externalId as string,
+ email: externalId as string,
+ firstName: TEST_FIRST_NAME,
+ lastName: TEST_LAST_NAME
+ });
+ orgMembershipId = created.id;
+
+ expect(created.userName).toBe(externalId);
+ expect(created.active).toBe(true);
+
+ await primeSamlIdentity(page, {
+ email: externalId as string,
+ firstName: TEST_FIRST_NAME,
+ lastName: TEST_LAST_NAME
+ });
+
+ await startSamlLogin(page);
+ await expectSignupSsoRedirectFor(page, externalId as string);
+ });
+
+ // IdP-initiated: browser starts at the Worker's /saml-idp/initiate, which
+ // mints an *unsolicited* signed SAMLResponse (no InResponseTo per SAML 2.0
+ // §3.4.1.5) and auto-POSTs it directly to gamma's ACS. Exercises gamma's
+ // unsolicited-response branch that the SP-initiated path doesn't touch.
+ test("IdP-initiated SAML login succeeds for a SCIM-provisioned user", async ({ page, request: apiRequest }) => {
+ const created = await createScimUser(apiRequest, {
+ externalId: externalId as string,
+ email: externalId as string,
+ firstName: TEST_FIRST_NAME,
+ lastName: TEST_LAST_NAME
+ });
+ orgMembershipId = created.id;
+
+ expect(created.userName).toBe(externalId);
+ expect(created.active).toBe(true);
+
+ await primeSamlIdentity(page, {
+ email: externalId as string,
+ firstName: TEST_FIRST_NAME,
+ lastName: TEST_LAST_NAME,
+ acsUrl: gammaSamlAcsUrl()
+ });
+
+ await startIdpInitiatedLogin(page);
+ await expectSignupSsoRedirectFor(page, externalId as string);
+ });
+});
diff --git a/e2e/tsconfig.json b/e2e/tsconfig.json
new file mode 100644
index 0000000000..920e35a828
--- /dev/null
+++ b/e2e/tsconfig.json
@@ -0,0 +1,17 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "Bundler",
+ "lib": ["ES2022", "DOM"],
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "noEmit": true,
+ "forceConsistentCasingInFileNames": true
+ },
+ "include": ["**/*.ts"],
+ "exclude": ["node_modules", "playwright-report", "test-results"]
+}