AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
feat(auth): find a domain's owner platform and its sign-in methods (ENG-491) (#16973)
lina-alomari27b1ea2128ea
diff --git a/brain/knowledge/connections-auth/ee-authentication-sso-rbac.md b/brain/knowledge/connections-auth/ee-authentication-sso-rbac.mdindex 985dc63d3a4..138fb5bcfc6 100644--- a/brain/knowledge/connections-auth/ee-authentication-sso-rbac.md+++ b/brain/knowledge/connections-auth/ee-authentication-sso-rbac.md@@ -38,6 +38,7 @@ Enterprise auth layer extending CE with SAML 2.0 SSO, Google/GitHub federated OA- **Removing the SSO domain also deletes SAML, in one update.** `updateSsoDomain` with `null` clears `ssoDomain`, `ssoDomainVerification` and `federatedAuthProviders.saml` in the same `platformService.update`; the page's Remove domain is that one request. Without a domain the sign-in page could not start SSO anyway (`/discover` needs a verified domain), and new SAML connections already require one. History: #13071 shipped a Remove button that never worked (see the next bullet); #13072 dropped the button without a stated reason; ENG-977 fixed the server and brought it back. **Changing** to a different domain still keeps SAML while the new one is pending. The sign-in page's SSO path is closed then (no verified domain for `/discover`), but IdP-initiated sign-in or a direct `/login?platformId=` link still works, and `assertEmailMatchesSsoDomain` skips unverified domains on purpose so platforms that had SAML before domain verification keep working; so the platform's own IdP can sign in any email until the new domain verifies (ENG-994). `verifySsoDomain` on an already-verified domain returns without re-checking DNS, so the page only offers "Verify DNS" while pending. Removal deletes SAML rather than keeping it saved because SAML has no on/off state: a kept config would stay live with no domain check. When ENG-982 adds on/off, removal should switch to turning SAML off (and the remove dialog and docs that say "deletes" change with it).- **Every domain claim gets a fresh TXT value, so a record left at the DNS provider never re-verifies anything.** `computeNextVerification` issues `activepieces-verify=<new apId>` for any new or re-added domain, and `txtRecordMatches` needs that exact value at `_activepieces-verify.<domain>` (any of the TXT strings there may match, so admins can add the new value beside the old one). Removing and re-adding a domain therefore always lands on PENDING, and a stale record cannot verify the domain for this platform or another one.- **`platformService.update` writes most fields with `spreadIfDefined`, which drops `null` as well as `undefined`, so those fields cannot be cleared through it.** That silently made "remove the SSO domain" a no-op while the endpoint still answered `{ ssoDomain: null }`. `ssoDomain` and `ssoDomainVerification` now use `spreadIfNotUndefined`, like `themeColors`; any other field that needs clearing must switch the same way, and a test that reads the row back is the only thing that catches it.+- **On EE, a verified domain is owned by nobody.** `verifiedDomainHooks` is only set in the Cloud arm of `app.ts`, so CE and EE always get `null` and `discoverSignInMethods` returns `{ domainOwned: false }`. On EE the single platform's settings apply to everyone, through `/v1/flags`. Turning domain ownership on for EE changes behaviour for existing installs (SAML-only setups without a verified domain would let passwords back in), so it needs its own decision.- Managed auth gated separately by `embeddingEnabled` (signing keys). See the Managed Auth page.- The authn rate limiter (`core/security/rate-limit.ts`) is registered with `global: false` — it protects NOTHING by default. Every public endpoint that sends email or does auth work must opt in per-route via `config.rateLimit` (see `authentication.controller.ts` / `otp-controller.ts` for the `API_RATE_LIMIT_AUTHN_*` pattern).diff --git a/brain/knowledge/connections-auth/index.md b/brain/knowledge/connections-auth/index.mdindex d15e5a46f29..a3b7e5de38d 100644--- a/brain/knowledge/connections-auth/index.md+++ b/brain/knowledge/connections-auth/index.md@@ -27,6 +27,9 @@ Platform owners register their own OAuth client_id/secret per piece so connectioUser identity, sign-in, JWT sessions. `UserIdentity` = canonical email+password+provider (one per email, shared across platforms); `User` = platform-scoped membership. First sign-up auto-creates a Platform + personal Project + ADMIN user. JWT is 7-day, signed with a shared secret; rotating `tokenVersion` on UserIdentity invalidates all sessions. `accessTokenManager` also mints long-lived engine/worker tokens. Endpoints: `/v1/authentication/sign-up|sign-in|switch-platform`. PrincipalTypes: USER/ENGINE/WORKER/SERVICE/UNKNOWN/ONBOARDING (the last is the pre-platform session that can only call `POST /v1/platforms`).+**Owned domain** — an email domain a platform has verified, on a plan with SSO. Cloud only for now; looked up by `verifiedDomainHooks.findPlatformIdByDomain`. _Avoid_: "managed domain" ("managed" means embedding users), "claimed domain".+**Domain owner platform** — the platform that owns a domain; `authenticationService.discoverSignInMethods` returns its sign-in methods. Its settings will apply to people on that domain (ENG-492). _Avoid_: "home platform", "domain owner" (a platform owner is a user).+### EE AuthenticationExtends CE with SSO + RBAC. SAML 2.0 (`/v1/authn/saml/login` → IdP → ACS `/acs`) and Google/GitHub federated OAuth both funnel into `authenticationService.federatedAuthn()`; gated by `ssoEnabled`. Per-project RBAC via `assertPrincipalAccessToProject()` and `assertUserHasPermissionToFlow()`. Config stored on `platform.federatedAuthProviders`. Authz hooks: `platformMustHaveFeatureEnabled` (402), `projectMustBeTeamType`, `platformMustBeOwnedByCurrentUser`. OTP (email verify, password reset, and the `EMAIL_LOGIN` sign-in code) lives here. Its entity is registered for every edition and `otpModule` now covers COMMUNITY too, but `sendOtp` returns early off Cloud/EE for the two link types and the `EMAIL_LOGIN` sign-in flow is served only on Cloud behind a configured captcha, so CE can send nothing today.diff --git a/packages/server/api/src/app/app.ts b/packages/server/api/src/app/app.tsindex bbe1ef4919b..a34ce93b4a7 100644--- a/packages/server/api/src/app/app.ts+++ b/packages/server/api/src/app/app.ts@@ -24,6 +24,7 @@ import { platformAppConnectionModule } from './app-connection/platform-app-conneimport { authenticationModule } from './authentication/authentication.module'import { otpModule } from './authentication/otp/otp-module'import { passwordlessAuthModule } from './authentication/passwordless-auth.module'+import { verifiedDomainHooks } from './authentication/verified-domain-hooks'import { canaryRoutingMiddleware } from './core/canary/canary-routing.middleware'import { collaborativeModule } from './core/collaborative/collaborative.module'import { oidcModule } from './core/security/oidc/oidc.module'@@ -46,6 +47,7 @@ import { enterpriseLocalAuthnModule } from './ee/authentication/enterprise-localimport { federatedAuthModule } from './ee/authentication/federated-authn/federated-authn-module'import { rbacMiddleware } from './ee/authentication/project-role/rbac-middleware'import { authnSsoSamlModule } from './ee/authentication/saml-authn/authn-sso-saml-module'+import { authnSsoSamlService } from './ee/authentication/saml-authn/authn-sso-saml-service'import { embedSubdomainModule } from './ee/embed-subdomain/embed-subdomain.module'import { enterpriseFlagsHooks } from './ee/flags/enterprise-flags.hooks'import { flowApprovalModule } from './ee/flows/flow-approval/flow-approval.module'@@ -389,6 +391,7 @@ export const setupApp = async (app: FastifyInstance): Promise<FastifyInstance> =publishHooksFactory.set(eeFlowPublishHook)billingProvider.set(autumnBillingProvider)resumePageHooks.set((log) => ({ getTheme: (params) => appearanceHelper.getTheme({ ...params, log }) }))+ verifiedDomainHooks.set(authnSsoSamlService)flowPublishHooks.set((log) => ({ assertReferencesResolve: assertAgentsResolveInProject, findMissingRequiredActions: (params) => pieceSetRequiredActions(log).findMissing(params) }))aiUsageHooks.set(agentConversationCreditsHooks)eventDestinationHooks.set(eventDestinationEntitlementHooks)diff --git a/packages/server/api/src/app/authentication/authentication-utils.ts b/packages/server/api/src/app/authentication/authentication-utils.tsindex 965796e1e5f..1c37c71dabd 100644--- a/packages/server/api/src/app/authentication/authentication-utils.ts+++ b/packages/server/api/src/app/authentication/authentication-utils.ts@@ -1,5 +1,5 @@import { ActivepiecesError, assertNotNullOrUndefined, ErrorCode, isNil } from '@activepieces/core-utils'-import { ApEdition, ApEnvironment, AuthenticationResponse, EndpointScope, pickTelemetryPii, PlatformRole, PrincipalType, Project, ProjectType, SsoDomainVerificationStatus, TelemetryEventName, User, UserIdentity, UserIdentityProvider, UserStatus } from '@activepieces/shared'+import { ApEdition, ApEnvironment, AuthenticationResponse, EndpointScope, pickTelemetryPii, PlatformRole, PlatformWithoutSensitiveData, PrincipalType, Project, ProjectType, SsoDomainVerificationStatus, TelemetryEventName, User, UserIdentity, UserIdentityProvider, UserStatus } from '@activepieces/shared'import { FastifyBaseLogger, FastifyRequest } from 'fastify'import { system } from '../helper/system/system'import { AppSystemProp } from '../helper/system/system-props'@@ -267,12 +267,26 @@ export const authenticationUtils = (log: FastifyBaseLogger) => ({const project = await projectService(log).getOneOrThrow(projectId)return project.ownerId},+ getSignInMethods({ platform }: GetSignInMethodsParams): SignInMethods {+ if (system.getEdition() === ApEdition.COMMUNITY) {+ return { email: true, google: false, sso: false }+ }+ return {+ email: platform.emailAuthEnabled,+ google: isGoogleConfigured() && platform.googleAuthEnabled,+ sso: !isNil(platform.federatedAuthProviders?.saml),+ }+ },})function findPersonalProject(projects: Project[], userId: string): Project | undefined {return projects.find((project) => project.ownerId === userId && project.type === ProjectType.PERSONAL)}+function isGoogleConfigured(): boolean {+ return !isNil(system.get(AppSystemProp.GOOGLE_CLIENT_ID)) && !isNil(system.get(AppSystemProp.GOOGLE_CLIENT_SECRET))+}+type SendTelemetryParams = {identity: UserIdentityuser: User@@ -308,6 +322,16 @@ export type AuthenticationResult = {signedUp: boolean}+export type SignInMethods = {+ email: boolean+ google: boolean+ sso: boolean+}++type GetSignInMethodsParams = {+ platform: Pick<PlatformWithoutSensitiveData, 'emailAuthEnabled' | 'googleAuthEnabled' | 'federatedAuthProviders'>+}+type GetOnboardingResponseParams = {identityId: string}diff --git a/packages/server/api/src/app/authentication/authentication.service.ts b/packages/server/api/src/app/authentication/authentication.service.tsindex 3f017418ac4..f56dfdae9b2 100644--- a/packages/server/api/src/app/authentication/authentication.service.ts+++ b/packages/server/api/src/app/authentication/authentication.service.ts@@ -9,10 +9,11 @@ import { AppSystemProp } from '../helper/system/system-props'import { platformService } from '../platform/platform.service'import { userService } from '../user/user-service'import { userInvitationsService } from '../user-invitations/user-invitation.service'-import { AuthenticationResult, authenticationUtils } from './authentication-utils'+import { AuthenticationResult, authenticationUtils, SignInMethods } from './authentication-utils'import { zerobounce } from './lib/zerobounce'import { otpService } from './otp/otp-service'import { userIdentityService } from './user-identity/user-identity-service'+import { verifiedDomainHooks } from './verified-domain-hooks'const PLATFORM_CONTROLLED_PROVIDERS = new Set([UserIdentityProvider.JWT, UserIdentityProvider.SAML])@@ -207,6 +208,14 @@ export const authenticationService = (log: FastifyBaseLogger) => ({projectId: null,})},+ async discoverSignInMethods({ domain }: DiscoverSignInMethodsParams): Promise<SignInDiscovery> {+ const domainOwnerPlatformId = await verifiedDomainHooks.get(log).findPlatformIdByDomain({ domain })+ if (isNil(domainOwnerPlatformId)) {+ return { domainOwned: false }+ }+ const domainOwnerPlatform = await platformService(log).getOneWithPlanOrThrow(domainOwnerPlatformId)+ return { domainOwned: true, methods: authenticationUtils(log).getSignInMethods({ platform: domainOwnerPlatform }) }+ },})async function assertUserCanSwitchToPlatform(platform: PlatformWithoutSensitiveData | undefined): Promise<void> {@@ -330,3 +339,11 @@ type SwitchPlatformParams = {identityId: stringplatformId: string}++type DiscoverSignInMethodsParams = {+ domain: string+}++export type SignInDiscovery =+ | { domainOwned: true, methods: SignInMethods }+ | { domainOwned: false }diff --git a/packages/server/api/src/app/authentication/verified-domain-hooks.ts b/packages/server/api/src/app/authentication/verified-domain-hooks.tsnew file mode 100644index 00000000000..eb85d5e3b65--- /dev/null+++ b/packages/server/api/src/app/authentication/verified-domain-hooks.ts@@ -0,0 +1,12 @@+import { PlatformId } from '@activepieces/core-utils'+import { hooksFactory } from '../helper/hooks-factory'++export const verifiedDomainHooks = hooksFactory.create<VerifiedDomainHooks>(() => ({+ async findPlatformIdByDomain(): Promise<PlatformId | null> {+ return null+ },+}))++export type VerifiedDomainHooks = {+ findPlatformIdByDomain(params: { domain: string }): Promise<PlatformId | null>+}diff --git a/packages/server/api/src/app/ee/authentication/saml-authn/authn-sso-saml-service.ts b/packages/server/api/src/app/ee/authentication/saml-authn/authn-sso-saml-service.tsindex 491f8aa29ac..dd7ba10b7db 100644--- a/packages/server/api/src/app/ee/authentication/saml-authn/authn-sso-saml-service.ts+++ b/packages/server/api/src/app/ee/authentication/saml-authn/authn-sso-saml-service.ts@@ -58,26 +58,24 @@ export const authnSsoSamlService = (log: FastifyBaseLogger) => {return response},async discoverByDomain(domain: string): Promise<DiscoverResult> {+ const platformId = await this.findPlatformIdByDomain({ domain })+ if (isNil(platformId)) {+ return { platformId: null }+ }+ const samlConfigured = await platformService(log).hasSamlConfigured(platformId)+ return { platformId: samlConfigured ? platformId : null }+ },+ async findPlatformIdByDomain({ domain }: FindPlatformIdByDomainParams): Promise<PlatformId | null> {const ssoDomain = domain.trim().toLowerCase()if (ssoDomain.length === 0) {- return { platformId: null }+ return null}const platform = await platformRepo().findOneBy({ ssoDomain })- if (isNil(platform)) {- return { platformId: null }- }- if (platform.ssoDomainVerification?.status !== SsoDomainVerificationStatus.VERIFIED) {- return { platformId: null }+ if (isNil(platform) || platform.ssoDomainVerification?.status !== SsoDomainVerificationStatus.VERIFIED) {+ return null}const plan = await platformPlanService(log).getOrCreateForPlatform(platform.id)- if (!plan.ssoEnabled) {- return { platformId: null }- }- const samlConfigured = await platformService(log).hasSamlConfigured(platform.id)- if (!samlConfigured) {- return { platformId: null }- }- return { platformId: platform.id }+ return plan.ssoEnabled ? platform.id : null},async updateSsoDomain({ platformId, ssoDomain, userId, ip }: UpdateSsoDomainParams): Promise<SsoDomainState> {const normalized = ssoDomain?.trim().toLowerCase() ?? null@@ -221,6 +219,10 @@ type DiscoverResult = {platformId: string | null}+type FindPlatformIdByDomainParams = {+ domain: string+}+type UpdateSsoDomainParams = {platformId: PlatformIdssoDomain: string | nulldiff --git a/packages/server/api/test/integration/ce/authentication/sign-in-discovery.test.ts b/packages/server/api/test/integration/ce/authentication/sign-in-discovery.test.tsnew file mode 100644index 00000000000..fd31664de66--- /dev/null+++ b/packages/server/api/test/integration/ce/authentication/sign-in-discovery.test.ts@@ -0,0 +1,35 @@+import { FastifyBaseLogger } from 'fastify'+import { authenticationUtils } from '../../../../src/app/authentication/authentication-utils'+import { authenticationService } from '../../../../src/app/authentication/authentication.service'+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'++let mockLog: FastifyBaseLogger++beforeAll(async () => {+ const app = await setupTestEnvironment()+ mockLog = app.log+})++afterEach(() => {+ delete process.env.AP_GOOGLE_CLIENT_ID+ delete process.env.AP_GOOGLE_CLIENT_SECRET+})++afterAll(async () => {+ await teardownTestEnvironment()+})++describe('Sign-in discovery', () => {+ it('returns domainOwned: false', async () => {+ await expect(authenticationService(mockLog).discoverSignInMethods({ domain: 'community.example.com' })).resolves.toEqual({ domainOwned: false })+ })++ it('reports password only on CE', () => {+ process.env.AP_GOOGLE_CLIENT_ID = 'test-google-client-id'+ process.env.AP_GOOGLE_CLIENT_SECRET = 'test-google-client-secret'+ const methods = authenticationUtils(mockLog).getSignInMethods({+ platform: { emailAuthEnabled: false, googleAuthEnabled: true, federatedAuthProviders: { saml: {} } },+ })+ expect(methods).toEqual({ email: true, google: false, sso: false })+ })+})diff --git a/packages/server/api/test/integration/cloud/authn/sign-in-discovery.test.ts b/packages/server/api/test/integration/cloud/authn/sign-in-discovery.test.tsnew file mode 100644index 00000000000..8487928b674--- /dev/null+++ b/packages/server/api/test/integration/cloud/authn/sign-in-discovery.test.ts@@ -0,0 +1,107 @@+import { SsoDomainVerificationRecordType, SsoDomainVerificationStatus } from '@activepieces/shared'+import { FastifyBaseLogger } from 'fastify'+import { authenticationService } from '../../../../src/app/authentication/authentication.service'+import { mockAndSaveBasicSetup } from '../../../helpers/mocks'+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'++let mockLog: FastifyBaseLogger++beforeAll(async () => {+ const app = await setupTestEnvironment()+ mockLog = app.log+})++afterEach(() => {+ delete process.env.AP_GOOGLE_CLIENT_ID+ delete process.env.AP_GOOGLE_CLIENT_SECRET+})++afterAll(async () => {+ await teardownTestEnvironment()+})++describe('Sign-in discovery', () => {+ it('returns the methods of the platform that owns the domain, ignoring case', async () => {+ await saveDomainOwnerPlatform({ domain: 'acme.example.com', status: SsoDomainVerificationStatus.VERIFIED, ssoEnabled: true, emailAuthEnabled: false, samlConfigured: true })+ await expect(authenticationService(mockLog).discoverSignInMethods({ domain: ' ACME.example.com ' })).resolves.toEqual({+ domainOwned: true,+ methods: { email: false, google: false, sso: true },+ })+ })++ it('returns the methods of a platform that owns the domain without setting up SSO', async () => {+ await saveDomainOwnerPlatform({ domain: 'no-saml.example.com', status: SsoDomainVerificationStatus.VERIFIED, ssoEnabled: true, emailAuthEnabled: true, samlConfigured: false })+ await expect(authenticationService(mockLog).discoverSignInMethods({ domain: 'no-saml.example.com' })).resolves.toEqual({+ domainOwned: true,+ methods: { email: true, google: false, sso: false },+ })+ })++ it('reports Google only when the server has it set up', async () => {+ await saveDomainOwnerPlatform({ domain: 'google.example.com', status: SsoDomainVerificationStatus.VERIFIED, ssoEnabled: true, emailAuthEnabled: true, samlConfigured: false })+ process.env.AP_GOOGLE_CLIENT_ID = 'test-google-client-id'+ process.env.AP_GOOGLE_CLIENT_SECRET = 'test-google-client-secret'+ await expect(authenticationService(mockLog).discoverSignInMethods({ domain: 'google.example.com' })).resolves.toEqual({+ domainOwned: true,+ methods: { email: true, google: true, sso: false },+ })+ })++ it('does not report Google when the platform turned it off', async () => {+ await saveDomainOwnerPlatform({ domain: 'google-off.example.com', status: SsoDomainVerificationStatus.VERIFIED, ssoEnabled: true, emailAuthEnabled: true, samlConfigured: false, googleAuthEnabled: false })+ process.env.AP_GOOGLE_CLIENT_ID = 'test-google-client-id'+ process.env.AP_GOOGLE_CLIENT_SECRET = 'test-google-client-secret'+ await expect(authenticationService(mockLog).discoverSignInMethods({ domain: 'google-off.example.com' })).resolves.toEqual({+ domainOwned: true,+ methods: { email: true, google: false, sso: false },+ })+ })++ it('does not report Google when only the client id is set', async () => {+ await saveDomainOwnerPlatform({ domain: 'google-no-secret.example.com', status: SsoDomainVerificationStatus.VERIFIED, ssoEnabled: true, emailAuthEnabled: true, samlConfigured: false })+ process.env.AP_GOOGLE_CLIENT_ID = 'test-google-client-id'+ await expect(authenticationService(mockLog).discoverSignInMethods({ domain: 'google-no-secret.example.com' })).resolves.toEqual({+ domainOwned: true,+ methods: { email: true, google: false, sso: false },+ })+ })++ it.each([+ { reason: 'the domain is blank', domain: 'blank.example.com', lookup: ' ', status: SsoDomainVerificationStatus.VERIFIED, ssoEnabled: true },+ { reason: 'the domain is pending', domain: 'pending.example.com', lookup: 'pending.example.com', status: SsoDomainVerificationStatus.PENDING_VERIFICATION, ssoEnabled: true },+ { reason: 'the plan has no SSO', domain: 'no-sso.example.com', lookup: 'no-sso.example.com', status: SsoDomainVerificationStatus.VERIFIED, ssoEnabled: false },+ { reason: 'the domain is a subdomain', domain: 'parent.example.com', lookup: 'eu.parent.example.com', status: SsoDomainVerificationStatus.VERIFIED, ssoEnabled: true },+ { reason: 'no platform owns the domain', domain: 'claimed.example.com', lookup: 'unclaimed.example.com', status: SsoDomainVerificationStatus.VERIFIED, ssoEnabled: true },+ ])('returns only domainOwned: false when $reason', async ({ domain, lookup, status, ssoEnabled }) => {+ await saveDomainOwnerPlatform({ domain, status, ssoEnabled, emailAuthEnabled: true, samlConfigured: true })+ await expect(authenticationService(mockLog).discoverSignInMethods({ domain: lookup })).resolves.toEqual({ domainOwned: false })+ })+})++async function saveDomainOwnerPlatform({ domain, status, ssoEnabled, emailAuthEnabled, samlConfigured, googleAuthEnabled = true }: SaveDomainOwnerPlatformParams): Promise<void> {+ await mockAndSaveBasicSetup({+ platform: {+ ssoDomain: domain,+ ssoDomainVerification: {+ status,+ record: { type: SsoDomainVerificationRecordType.TXT, name: `_activepieces-verify.${domain}`, value: 'activepieces-verify=test' },+ createdAt: new Date().toISOString(),+ },+ emailAuthEnabled,+ googleAuthEnabled,+ federatedAuthProviders: {+ saml: samlConfigured ? { idpMetadata: '<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"></md:EntityDescriptor>', idpCertificate: 'test-cert' } : null,+ },+ },+ plan: { ssoEnabled },+ })+}++type SaveDomainOwnerPlatformParams = {+ domain: string+ status: SsoDomainVerificationStatus+ ssoEnabled: boolean+ emailAuthEnabled: boolean+ samlConfigured: boolean+ googleAuthEnabled?: boolean+}diff --git a/packages/server/api/test/integration/ee/authn/sign-in-discovery.test.ts b/packages/server/api/test/integration/ee/authn/sign-in-discovery.test.tsnew file mode 100644index 00000000000..1215d7e5c5c--- /dev/null+++ b/packages/server/api/test/integration/ee/authn/sign-in-discovery.test.ts@@ -0,0 +1,33 @@+import { SsoDomainVerificationRecordType, SsoDomainVerificationStatus } from '@activepieces/shared'+import { FastifyBaseLogger } from 'fastify'+import { authenticationService } from '../../../../src/app/authentication/authentication.service'+import { mockAndSaveBasicSetup } from '../../../helpers/mocks'+import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'++let mockLog: FastifyBaseLogger++beforeAll(async () => {+ const app = await setupTestEnvironment()+ mockLog = app.log+})++afterAll(async () => {+ await teardownTestEnvironment()+})++describe('Sign-in discovery', () => {+ it('returns domainOwned: false on self-hosted even for a verified domain', async () => {+ await mockAndSaveBasicSetup({+ platform: {+ ssoDomain: 'self-hosted.example.com',+ ssoDomainVerification: {+ status: SsoDomainVerificationStatus.VERIFIED,+ record: { type: SsoDomainVerificationRecordType.TXT, name: '_activepieces-verify.self-hosted.example.com', value: 'activepieces-verify=test' },+ createdAt: new Date().toISOString(),+ },+ },+ plan: { ssoEnabled: true },+ })+ await expect(authenticationService(mockLog).discoverSignInMethods({ domain: 'self-hosted.example.com' })).resolves.toEqual({ domainOwned: false })+ })+})diff --git a/packages/server/api/test/integration/ee/saml-discover/saml-discover.test.ts b/packages/server/api/test/integration/ee/saml-discover/saml-discover.test.tsindex b3f18c4cdb2..d95c0b9be1e 100644--- a/packages/server/api/test/integration/ee/saml-discover/saml-discover.test.ts+++ b/packages/server/api/test/integration/ee/saml-discover/saml-discover.test.ts@@ -1,7 +1,8 @@+import { SsoDomainVerificationRecordType, SsoDomainVerificationStatus } from '@activepieces/shared'import { FastifyInstance } from 'fastify'import { StatusCodes } from 'http-status-codes'import { databaseConnection } from '../../../../src/app/database/database-connection'-import { createMockPlatform, createMockPlatformPlan, createMockUser, createMockUserIdentity } from '../../../helpers/mocks'+import { createMockPlatform, createMockPlatformPlan, createMockUser, createMockUserIdentity, mockAndSaveBasicSetup } from '../../../helpers/mocks'import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'let app: FastifyInstance | null = null@@ -121,5 +122,35 @@ describe('SAML Discover API', () => {expect(response?.statusCode).toBe(StatusCodes.OK)expect(response?.json().platformId).toBeNull()})++ it.each([+ { reason: 'the domain is pending', domain: 'pending-saml.example.com', lookup: 'pending-saml.example.com', status: SsoDomainVerificationStatus.PENDING_VERIFICATION, ssoEnabled: true },+ { reason: 'the plan has no SSO', domain: 'no-sso-saml.example.com', lookup: 'no-sso-saml.example.com', status: SsoDomainVerificationStatus.VERIFIED, ssoEnabled: false },+ { reason: 'the domain is blank', domain: 'blank-saml.example.com', lookup: ' ', status: SsoDomainVerificationStatus.VERIFIED, ssoEnabled: true },+ ])('should return null platformId when $reason, even with SAML configured', async ({ domain, lookup, status, ssoEnabled }) => {+ await mockAndSaveBasicSetup({+ platform: {+ ssoDomain: domain,+ ssoDomainVerification: {+ status,+ record: { type: SsoDomainVerificationRecordType.TXT, name: `_activepieces-verify.${domain}`, value: 'activepieces-verify=test-token' },+ createdAt: new Date().toISOString(),+ },+ federatedAuthProviders: {+ saml: { idpMetadata: '<md:EntityDescriptor xmlns:md="urn:oasis:names:tc:SAML:2.0:metadata"></md:EntityDescriptor>', idpCertificate: 'test-cert' },+ },+ },+ plan: { ssoEnabled },+ })++ const response = await app?.inject({+ method: 'POST',+ url: '/api/v1/authn/saml/discover',+ body: { domain: lookup },+ })++ expect(response?.statusCode).toBe(StatusCodes.OK)+ expect(response?.json().platformId).toBeNull()+ })})})